diff options
Diffstat (limited to 'src/org/traccar/api/AsyncSocket.java')
-rw-r--r-- | src/org/traccar/api/AsyncSocket.java | 58 |
1 files changed, 51 insertions, 7 deletions
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<Long> 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); } } |