diff options
Diffstat (limited to 'src/org/traccar/database')
-rw-r--r-- | src/org/traccar/database/ConnectionManager.java | 35 |
1 files changed, 32 insertions, 3 deletions
diff --git a/src/org/traccar/database/ConnectionManager.java b/src/org/traccar/database/ConnectionManager.java index 345bb4577..ae931151d 100644 --- a/src/org/traccar/database/ConnectionManager.java +++ b/src/org/traccar/database/ConnectionManager.java @@ -25,8 +25,13 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.TimeUnit; + import org.jboss.netty.channel.Channel; +import org.jboss.netty.util.Timeout; +import org.jboss.netty.util.TimerTask; import org.traccar.Context; +import org.traccar.GlobalTimer; import org.traccar.Protocol; import org.traccar.helper.Log; import org.traccar.model.Device; @@ -34,11 +39,17 @@ import org.traccar.model.Position; public class ConnectionManager { + private static final long DEFAULT_TIMEOUT = 600; + + private final long deviceTimeout; + private final Map<Long, ActiveDevice> activeDevices = new HashMap<>(); private final Map<Long, Position> positions = new HashMap<>(); private final Map<Long, Set<UpdateListener>> listeners = new HashMap<>(); + private final Map<Long, Timeout> timeouts = new HashMap<>(); public ConnectionManager(DataManager dataManager) { + deviceTimeout = Context.getConfig().getLong("status.timeout", DEFAULT_TIMEOUT) * 1000; if (dataManager != null) { try { for (Position position : dataManager.getLatestPositions()) { @@ -57,7 +68,7 @@ public class ConnectionManager { public void removeActiveDevice(Channel channel) { for (ActiveDevice activeDevice : activeDevices.values()) { if (activeDevice.getChannel() == channel) { - updateDevice(activeDevice.getDeviceId(), Device.STATUS_OFFLINE, new Date()); + updateDevice(activeDevice.getDeviceId(), Device.STATUS_OFFLINE, null); activeDevices.remove(activeDevice.getDeviceId()); break; } @@ -68,10 +79,28 @@ public class ConnectionManager { return activeDevices.get(deviceId); } - public synchronized void updateDevice(long deviceId, String status, Date time) { + public synchronized void updateDevice(final long deviceId, String status, Date time) { Device device = Context.getIdentityManager().getDeviceById(deviceId); device.setStatus(status); - device.setLastUpdate(time); + if (time != null) { + device.setLastUpdate(time); + } + + Timeout timeout = timeouts.remove(deviceId); + if (timeout != null) { + timeout.cancel(); + } + + if (status.equals(Device.STATUS_ONLINE)) { + timeouts.put(deviceId, GlobalTimer.getTimer().newTimeout(new TimerTask() { + @Override + public void run(Timeout timeout) throws Exception { + if (!timeout.isCancelled()) { + updateDevice(deviceId, Device.STATUS_UNKNOWN, null); + } + } + }, deviceTimeout, TimeUnit.MILLISECONDS)); + } try { Context.getDataManager().updateDeviceStatus(device); |