From 44d38a8f121304fc6504ebaabbfb0a402779ca1d Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Tue, 15 Dec 2015 14:24:35 +1300 Subject: Finish server side web sockets --- src/org/traccar/api/AsyncSocket.java | 58 +++++++++++++++++++++++++++++++----- 1 file changed, 51 insertions(+), 7 deletions(-) (limited to 'src/org/traccar/api/AsyncSocket.java') diff --git a/src/org/traccar/api/AsyncSocket.java b/src/org/traccar/api/AsyncSocket.java index 8630b207d..fe20081d3 100644 --- a/src/org/traccar/api/AsyncSocket.java +++ b/src/org/traccar/api/AsyncSocket.java @@ -16,15 +16,59 @@ package org.traccar.api; import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; -import org.eclipse.jetty.websocket.api.annotations.WebSocket; +import org.eclipse.jetty.websocket.api.WebSocketAdapter; +import org.traccar.Context; +import org.traccar.database.ConnectionManager; +import org.traccar.model.Device; +import org.traccar.model.Position; +import org.traccar.web.JsonConverter; -@WebSocket -public class AsyncSocket { +import javax.json.Json; +import javax.json.JsonObjectBuilder; +import java.util.Arrays; +import java.util.Collection; - @OnWebSocketMessage - public void onWebSocketText(Session session, String message) { - session.getRemote().sendString(message, null); +public class AsyncSocket extends WebSocketAdapter implements ConnectionManager.UpdateListener { + + private static final String KEY_DEVICES = "devices"; + private static final String KEY_POSITIONS = "positions"; + + private Collection devices; + + public AsyncSocket(long userId) { + devices = Context.getPermissionsManager().allowedDevices(userId); + } + + @Override + public void onWebSocketConnect(Session session) { + super.onWebSocketConnect(session); + + sendData(KEY_POSITIONS, Context.getConnectionManager().getInitialState(devices)); + + Context.getConnectionManager().addListener(devices, this); + } + + @Override + public void onWebSocketClose(int statusCode, String reason) { + super.onWebSocketClose(statusCode, reason); + + Context.getConnectionManager().removeListener(devices, this); + } + + @Override + public void onUpdateDevice(Device device) { + sendData(KEY_DEVICES, Arrays.asList(device)); + } + + @Override + public void onUpdatePosition(Position position) { + sendData(KEY_POSITIONS, Arrays.asList(position)); + } + + private void sendData(String key, Collection data) { + JsonObjectBuilder json = Json.createObjectBuilder(); + json.add(key, JsonConverter.arrayToJson(data)); + getRemote().sendString(json.build().toString(), null); } } -- cgit v1.2.3