aboutsummaryrefslogtreecommitdiff
path: root/src/org/traccar
diff options
context:
space:
mode:
Diffstat (limited to 'src/org/traccar')
-rw-r--r--src/org/traccar/DataManager.java40
-rw-r--r--src/org/traccar/Device.java49
-rw-r--r--src/org/traccar/Position.java142
-rw-r--r--src/org/traccar/Server.java529
-rw-r--r--src/org/traccar/TrackerEventHandler.java76
-rw-r--r--src/org/traccar/TrackerServer.java88
-rw-r--r--src/org/traccar/helper/NamedParameterStatement.java158
-rw-r--r--src/org/traccar/protocol/gl200/Gl200ProtocolDecoder.java159
-rw-r--r--src/org/traccar/protocol/gps103/Gps103ProtocolDecoder.java180
-rw-r--r--src/org/traccar/protocol/t55/T55ProtocolDecoder.java200
-rw-r--r--src/org/traccar/protocol/tk103/Tk103ProtocolDecoder.java175
-rw-r--r--src/org/traccar/protocol/xexun/XexunFrameDecoder.java92
-rw-r--r--src/org/traccar/protocol/xexun/XexunProtocolDecoder.java175
13 files changed, 2063 insertions, 0 deletions
diff --git a/src/org/traccar/DataManager.java b/src/org/traccar/DataManager.java
new file mode 100644
index 000000000..c2ba588cd
--- /dev/null
+++ b/src/org/traccar/DataManager.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar;
+
+import java.util.List;
+
+/**
+ * Data manager
+ */
+public interface DataManager {
+
+ /**
+ * Read device list
+ */
+ public List getDevices() throws Exception;
+
+ /**
+ * Get device by imei
+ */
+ public Device getDeviceByImei(String imei) throws Exception;
+
+ /**
+ * Write position
+ */
+ public void setPosition(Position position) throws Exception;
+
+}
diff --git a/src/org/traccar/Device.java b/src/org/traccar/Device.java
new file mode 100644
index 000000000..ad952bac8
--- /dev/null
+++ b/src/org/traccar/Device.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar;
+
+/**
+ * Device
+ */
+public class Device {
+
+ /**
+ * Id
+ */
+ private Long id;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long newId) {
+ id = newId;
+ }
+
+ /**
+ * International mobile equipment identity (IMEI)
+ */
+ private String imei;
+
+ public String getImei() {
+ return imei;
+ }
+
+ public void setImei(String newImei) {
+ imei = newImei;
+ }
+
+}
diff --git a/src/org/traccar/Position.java b/src/org/traccar/Position.java
new file mode 100644
index 000000000..29451482d
--- /dev/null
+++ b/src/org/traccar/Position.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar;
+
+import java.util.Date;
+
+/**
+ * Position information
+ */
+public class Position {
+
+ /**
+ * Id
+ */
+ private Long id;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long newId) {
+ id = newId;
+ }
+
+ /**
+ * Device
+ */
+ private Long deviceId;
+
+ public Long getDeviceId() {
+ return deviceId;
+ }
+
+ public void setDeviceId(Long newDeviceId) {
+ deviceId = newDeviceId;
+ }
+
+ /**
+ * Time (UTC)
+ */
+ private Date time;
+
+ public Date getTime() {
+ return time;
+ }
+
+ public void setTime(Date newTime) {
+ time = newTime;
+ }
+
+ /**
+ * Validity flag
+ */
+ private Boolean valid;
+
+ public Boolean getValid() {
+ return valid;
+ }
+
+ public void setValid(Boolean newValid) {
+ valid = newValid;
+ }
+
+ /**
+ * Latitude
+ */
+ private Double latitude;
+
+ public Double getLatitude() {
+ return latitude;
+ }
+
+ public void setLatitude(Double newLatitude) {
+ latitude = newLatitude;
+ }
+
+ /**
+ * Longitude
+ */
+ private Double longitude;
+
+ public Double getLongitude() {
+ return longitude;
+ }
+
+ public void setLongitude(Double newLongitude) {
+ longitude = newLongitude;
+ }
+
+ /**
+ * Altitude
+ */
+ private Double altitude;
+
+ public Double getAltitude() {
+ return altitude;
+ }
+
+ public void setAltitude(Double newAltitude) {
+ altitude = newAltitude;
+ }
+
+ /**
+ * Speed (knots)
+ */
+ private Double speed;
+
+ public Double getSpeed() {
+ return speed;
+ }
+
+ public void setSpeed(Double newSpeed) {
+ speed = newSpeed;
+ }
+
+ /**
+ * Course
+ */
+ private Double course;
+
+ public Double getCourse() {
+ return course;
+ }
+
+ public void setCourse(Double newCourse) {
+ course = newCourse;
+ }
+
+}
diff --git a/src/org/traccar/Server.java b/src/org/traccar/Server.java
new file mode 100644
index 000000000..7dd2a5990
--- /dev/null
+++ b/src/org/traccar/Server.java
@@ -0,0 +1,529 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Properties;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.sql.DriverManager;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.logging.Logger;
+import java.util.logging.FileHandler;
+import java.util.logging.Formatter;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import org.traccar.helper.NamedParameterStatement;
+import org.jboss.netty.handler.codec.string.StringDecoder;
+import org.jboss.netty.handler.codec.string.StringEncoder;
+import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
+import org.jboss.netty.buffer.ChannelBuffers;
+import org.jboss.netty.handler.logging.LoggingHandler;
+import org.traccar.protocol.xexun.XexunFrameDecoder;
+import org.traccar.protocol.xexun.XexunProtocolDecoder;
+import org.traccar.protocol.gps103.Gps103ProtocolDecoder;
+import org.traccar.protocol.tk103.Tk103ProtocolDecoder;
+import org.traccar.protocol.gl200.Gl200ProtocolDecoder;
+import org.traccar.protocol.t55.T55ProtocolDecoder;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ChannelPipeline;
+import org.jboss.netty.channel.ChannelPipelineFactory;
+import org.jboss.netty.channel.ChannelStateEvent;
+import org.jboss.netty.channel.Channels;
+import org.jboss.netty.channel.SimpleChannelHandler;
+
+/**
+ * Server
+ */
+public class Server implements DataManager {
+
+ /**
+ * Server list
+ */
+ private List serverList;
+
+ private boolean loggerEnable;
+
+ public Server() {
+ serverList = new LinkedList();
+ loggerEnable = false;
+ }
+
+ public boolean isLoggerEnabled() {
+ return loggerEnable;
+ }
+
+ /**
+ * Init
+ */
+ public void init(String[] arguments)
+ throws IOException, ClassNotFoundException, SQLException {
+
+ // Load properties
+ Properties properties = new Properties();
+ if (arguments.length > 0) {
+ properties.loadFromXML(new FileInputStream(arguments[0]));
+ }
+
+ initDatabase(properties);
+ initLogger(properties);
+
+ initXexunServer(properties);
+ initGps103Server(properties);
+ initTk103Server(properties);
+ initGl200Server(properties);
+ initT55Server(properties);
+ }
+
+ /**
+ * Database connection
+ */
+ private Connection connection;
+
+ private NamedParameterStatement selectDevice;
+
+ private NamedParameterStatement insertPosition;
+
+ /**
+ * Init database
+ */
+ private void initDatabase(Properties properties)
+ throws ClassNotFoundException, SQLException {
+
+ // Load driver
+ String driver = properties.getProperty("database.driver");
+ if (driver != null) {
+ Class.forName(driver);
+ }
+
+ // Connect database
+ String url = properties.getProperty("database.url");
+ String user = properties.getProperty("database.user");
+ String password = properties.getProperty("database.password");
+
+ if (user != null && password != null) {
+ connection = DriverManager.getConnection(url, user, password);
+ } else {
+ connection = DriverManager.getConnection(url);
+ }
+
+ // Init statements
+ String selectDeviceQuery = properties.getProperty("database.selectDevice");
+ if (selectDeviceQuery != null) {
+ selectDevice = new NamedParameterStatement(connection, selectDeviceQuery);
+ }
+
+ String insertPositionQuery = properties.getProperty("database.insertPosition");
+ if (insertPositionQuery != null) {
+ insertPosition = new NamedParameterStatement(connection, insertPositionQuery);
+ }
+ }
+
+ /**
+ * Devices
+ */
+ private Map devices;
+
+ public synchronized List getDevices() throws SQLException {
+
+ List deviceList = new LinkedList();
+
+ ResultSet result = selectDevice.executeQuery();
+ while (result.next()) {
+ Device device = new Device();
+ device.setId(result.getLong("id"));
+ device.setImei(result.getString("imei"));
+ deviceList.add(device);
+ }
+
+ return deviceList;
+ }
+
+ public Device getDeviceByImei(String imei) throws SQLException {
+
+ // Init device list
+ if (devices == null) {
+ devices = new HashMap();
+
+ List deviceList = getDevices();
+
+ for (Object device: deviceList) {
+ devices.put(((Device) device).getImei(), device);
+ }
+ }
+
+ return (Device) devices.get(imei);
+ }
+
+ public synchronized void setPosition(Position position) throws SQLException {
+
+ insertPosition.setLong("device_id", position.getDeviceId());
+ insertPosition.setTimestamp("time", position.getTime());
+ insertPosition.setBoolean("valid", position.getValid());
+ insertPosition.setDouble("altitude", position.getAltitude());
+ insertPosition.setDouble("latitude", position.getLatitude());
+ insertPosition.setDouble("longitude", position.getLongitude());
+ insertPosition.setDouble("speed", position.getSpeed());
+ insertPosition.setDouble("course", position.getCourse());
+
+ insertPosition.executeUpdate();
+ }
+
+ /**
+ * Init logger
+ */
+ public void initLogger(Properties properties) throws IOException {
+
+ loggerEnable = Boolean.valueOf(properties.getProperty("logger.enable"));
+
+ if (loggerEnable) {
+
+ Logger logger = Logger.getLogger("logger");
+ String fileName = properties.getProperty("logger.file");
+ if (fileName != null) {
+
+ FileHandler file = new FileHandler(fileName, true);
+
+ file.setFormatter(new Formatter() {
+ private final String LINE_SEPARATOR =
+ System.getProperty("line.separator", "\n");
+
+ private final DateFormat dateFormat =
+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
+
+ public String format(LogRecord record) {
+ String line = dateFormat.format(new Date(record.getMillis()));
+ line += " - ";
+ line += formatMessage(record);
+ line += LINE_SEPARATOR;
+ return line;
+ }
+ });
+
+ logger.setLevel(Level.ALL);
+ logger.addHandler(file);
+ }
+ }
+ }
+
+ /**
+ * Open channel handler
+ */
+ protected class OpenChannelHandler extends SimpleChannelHandler {
+
+ private TrackerServer server;
+
+ public OpenChannelHandler(TrackerServer server) {
+ this.server = server;
+ }
+
+ @Override
+ public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
+ server.getChannelGroup().add(e.getChannel());
+ }
+ }
+
+ /**
+ * Xexun pipeline factory
+ */
+ protected class XexunPipelineFactory implements ChannelPipelineFactory {
+
+ private TrackerServer server;
+ private Server serverCreator;
+ private Integer resetDelay;
+
+ public XexunPipelineFactory(
+ TrackerServer server, Server serverCreator, Integer resetDelay) {
+ this.server = server;
+ this.serverCreator = serverCreator;
+ this.resetDelay = resetDelay;
+ }
+
+ public ChannelPipeline getPipeline() {
+ ChannelPipeline pipeline = Channels.pipeline();
+ pipeline.addLast("openHandler", new OpenChannelHandler(server));
+ if (serverCreator.isLoggerEnabled()) {
+ pipeline.addLast("logger", new LoggingHandler("logger"));
+ }
+ pipeline.addLast("frameDecoder", new XexunFrameDecoder());
+ pipeline.addLast("stringDecoder", new StringDecoder());
+ pipeline.addLast("objectDecoder", new XexunProtocolDecoder(serverCreator, resetDelay));
+ pipeline.addLast("handler", new TrackerEventHandler(serverCreator));
+ return pipeline;
+ }
+ }
+
+ /**
+ * Init Xexun server
+ */
+ public void initXexunServer(Properties properties) throws SQLException {
+
+ boolean enable = Boolean.valueOf(properties.getProperty("xexun.enable"));
+ if (enable) {
+
+ TrackerServer server = new TrackerServer(
+ Integer.valueOf(properties.getProperty("xexun.port")));
+
+ String resetDelay = properties.getProperty("xexun.resetDelay");
+ server.setPipelineFactory(new XexunPipelineFactory(
+ server, this, (resetDelay == null) ? 0 : Integer.valueOf(resetDelay)));
+
+ serverList.add(server);
+ }
+ }
+
+ /**
+ * Gps103 pipeline factory
+ */
+ protected class Gps103PipelineFactory implements ChannelPipelineFactory {
+
+ private TrackerServer server;
+ private Server serverCreator;
+ private Integer resetDelay;
+
+ public Gps103PipelineFactory(
+ TrackerServer server, Server serverCreator, Integer resetDelay) {
+ this.server = server;
+ this.serverCreator = serverCreator;
+ this.resetDelay = resetDelay;
+ }
+
+ public ChannelPipeline getPipeline() {
+ ChannelPipeline pipeline = Channels.pipeline();
+ pipeline.addLast("openHandler", new OpenChannelHandler(server));
+ if (serverCreator.isLoggerEnabled()) {
+ pipeline.addLast("logger", new LoggingHandler("logger"));
+ }
+ byte delimiter[] = { (byte) ';' };
+ pipeline.addLast("frameDecoder",
+ new DelimiterBasedFrameDecoder(1024, ChannelBuffers.wrappedBuffer(delimiter)));
+ pipeline.addLast("stringDecoder", new StringDecoder());
+ pipeline.addLast("stringEncoder", new StringEncoder());
+ pipeline.addLast("objectDecoder", new Gps103ProtocolDecoder(serverCreator, resetDelay));
+ pipeline.addLast("handler", new TrackerEventHandler(serverCreator));
+ return pipeline;
+ }
+ }
+
+ /**
+ * Init Gps103 server
+ */
+ public void initGps103Server(Properties properties) throws SQLException {
+
+ boolean enable = Boolean.valueOf(properties.getProperty("gps103.enable"));
+ if (enable) {
+
+ TrackerServer server = new TrackerServer(
+ Integer.valueOf(properties.getProperty("gps103.port")));
+
+ String resetDelay = properties.getProperty("gps103.resetDelay");
+ server.setPipelineFactory(new Gps103PipelineFactory(
+ server, this, (resetDelay == null) ? 0 : Integer.valueOf(resetDelay)));
+
+ serverList.add(server);
+ }
+ }
+
+ /**
+ * Tk103 pipeline factory
+ */
+ protected class Tk103PipelineFactory implements ChannelPipelineFactory {
+
+ private TrackerServer server;
+ private Server serverCreator;
+ private Integer resetDelay;
+
+ public Tk103PipelineFactory(
+ TrackerServer server, Server serverCreator, Integer resetDelay) {
+ this.server = server;
+ this.serverCreator = serverCreator;
+ this.resetDelay = resetDelay;
+ }
+
+ public ChannelPipeline getPipeline() {
+ ChannelPipeline pipeline = Channels.pipeline();
+ pipeline.addLast("openHandler", new OpenChannelHandler(server));
+ if (serverCreator.isLoggerEnabled()) {
+ pipeline.addLast("logger", new LoggingHandler("logger"));
+ }
+ byte delimiter[] = { (byte) ')' };
+ pipeline.addLast("frameDecoder",
+ new DelimiterBasedFrameDecoder(1024, ChannelBuffers.wrappedBuffer(delimiter)));
+ pipeline.addLast("stringDecoder", new StringDecoder());
+ pipeline.addLast("stringEncoder", new StringEncoder());
+ pipeline.addLast("objectDecoder", new Tk103ProtocolDecoder(serverCreator, resetDelay));
+ pipeline.addLast("handler", new TrackerEventHandler(serverCreator));
+ return pipeline;
+ }
+ }
+
+ /**
+ * Init Tk103 server
+ */
+ public void initTk103Server(Properties properties) throws SQLException {
+
+ boolean enable = Boolean.valueOf(properties.getProperty("tk103.enable"));
+ if (enable) {
+
+ TrackerServer server = new TrackerServer(
+ Integer.valueOf(properties.getProperty("tk103.port")));
+
+ String resetDelay = properties.getProperty("tk103.resetDelay");
+ server.setPipelineFactory(new Tk103PipelineFactory(
+ server, this, (resetDelay == null) ? 0 : Integer.valueOf(resetDelay)));
+
+ serverList.add(server);
+ }
+ }
+
+ /**
+ * Gl200 pipeline factory
+ */
+ protected class Gl200PipelineFactory implements ChannelPipelineFactory {
+
+ private TrackerServer server;
+ private Server serverCreator;
+ private Integer resetDelay;
+
+ public Gl200PipelineFactory(
+ TrackerServer server, Server serverCreator, Integer resetDelay) {
+ this.server = server;
+ this.serverCreator = serverCreator;
+ this.resetDelay = resetDelay;
+ }
+
+ public ChannelPipeline getPipeline() {
+ ChannelPipeline pipeline = Channels.pipeline();
+ pipeline.addLast("openHandler", new OpenChannelHandler(server));
+ if (serverCreator.isLoggerEnabled()) {
+ pipeline.addLast("logger", new LoggingHandler("logger"));
+ }
+ byte delimiter[] = { (byte) '$' };
+ pipeline.addLast("frameDecoder",
+ new DelimiterBasedFrameDecoder(1024, ChannelBuffers.wrappedBuffer(delimiter)));
+ pipeline.addLast("stringDecoder", new StringDecoder());
+ pipeline.addLast("stringEncoder", new StringEncoder());
+ pipeline.addLast("objectDecoder", new Gl200ProtocolDecoder(serverCreator, resetDelay));
+ pipeline.addLast("handler", new TrackerEventHandler(serverCreator));
+ return pipeline;
+ }
+ }
+
+ /**
+ * Init Gl200 server
+ */
+ public void initGl200Server(Properties properties) throws SQLException {
+
+ boolean enable = Boolean.valueOf(properties.getProperty("gl200.enable"));
+ if (enable) {
+
+ TrackerServer server = new TrackerServer(
+ Integer.valueOf(properties.getProperty("gl200.port")));
+
+ String resetDelay = properties.getProperty("gl200.resetDelay");
+ server.setPipelineFactory(new Gl200PipelineFactory(
+ server, this, (resetDelay == null) ? 0 : Integer.valueOf(resetDelay)));
+
+ serverList.add(server);
+ }
+ }
+
+ /**
+ * T55 pipeline factory
+ */
+ protected class T55PipelineFactory implements ChannelPipelineFactory {
+
+ private TrackerServer server;
+ private Server serverCreator;
+ private Integer resetDelay;
+
+ public T55PipelineFactory(
+ TrackerServer server, Server serverCreator, Integer resetDelay) {
+ this.server = server;
+ this.serverCreator = serverCreator;
+ this.resetDelay = resetDelay;
+ }
+
+ public ChannelPipeline getPipeline() {
+ ChannelPipeline pipeline = Channels.pipeline();
+ pipeline.addLast("openHandler", new OpenChannelHandler(server));
+ if (serverCreator.isLoggerEnabled()) {
+ pipeline.addLast("logger", new LoggingHandler("logger"));
+ }
+ byte delimiter[] = { (byte) '\r', (byte) '\n' };
+ pipeline.addLast("frameDecoder",
+ new DelimiterBasedFrameDecoder(1024, ChannelBuffers.wrappedBuffer(delimiter)));
+ pipeline.addLast("stringDecoder", new StringDecoder());
+ pipeline.addLast("stringEncoder", new StringEncoder());
+ pipeline.addLast("objectDecoder", new T55ProtocolDecoder(serverCreator, resetDelay));
+ pipeline.addLast("handler", new TrackerEventHandler(serverCreator));
+ return pipeline;
+ }
+ }
+
+ /**
+ * Init T55 server
+ */
+ public void initT55Server(Properties properties) throws SQLException {
+
+ boolean enable = Boolean.valueOf(properties.getProperty("t55.enable"));
+ if (enable) {
+
+ TrackerServer server = new TrackerServer(
+ Integer.valueOf(properties.getProperty("t55.port")));
+
+ String resetDelay = properties.getProperty("t55.resetDelay");
+ server.setPipelineFactory(new T55PipelineFactory(
+ server, this, (resetDelay == null) ? 0 : Integer.valueOf(resetDelay)));
+
+ serverList.add(server);
+ }
+ }
+
+ /**
+ * Start
+ */
+ public void start() {
+ for (Object server: serverList) {
+ ((TrackerServer) server).start();
+ }
+ }
+
+ /**
+ * Stop
+ */
+ public void stop() {
+ for (Object server: serverList) {
+ ((TrackerServer) server).stop();
+ }
+ }
+
+ /**
+ * Destroy
+ */
+ public void destroy() {
+ serverList.clear();
+ }
+
+}
diff --git a/src/org/traccar/TrackerEventHandler.java b/src/org/traccar/TrackerEventHandler.java
new file mode 100644
index 000000000..78be1b340
--- /dev/null
+++ b/src/org/traccar/TrackerEventHandler.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar;
+
+import org.jboss.netty.channel.SimpleChannelHandler;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ExceptionEvent;
+import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.channel.ChannelHandler;
+
+/**
+ * Tracker message handler
+ */
+@ChannelHandler.Sharable
+public class TrackerEventHandler extends SimpleChannelHandler {
+
+ /**
+ * Data manager
+ */
+ private DataManager dataManager;
+
+ TrackerEventHandler(DataManager newDataManager) {
+ super();
+ dataManager = newDataManager;
+ }
+
+ @Override
+ public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
+
+ if (e.getMessage() instanceof Position) {
+
+ Position position = (Position) e.getMessage();
+
+ if (position == null) {
+ System.out.println("null message");
+ } else {
+ System.out.println(
+ "id: " + position.getId() +
+ ", deviceId: " + position.getDeviceId() +
+ ", valid: " + position.getValid() +
+ ", time: " + position.getTime() +
+ ", latitude: " + position.getLatitude() +
+ ", longitude: " + position.getLongitude() +
+ ", altitude: " + position.getAltitude() +
+ ", speed: " + position.getSpeed() +
+ ", course: " + position.getCourse());
+ }
+
+ // Write position to database
+ try {
+ dataManager.setPosition(position);
+ } catch (Exception error) {
+ System.out.println(error.getMessage());
+ }
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
+ e.getChannel().close();
+ }
+
+}
diff --git a/src/org/traccar/TrackerServer.java b/src/org/traccar/TrackerServer.java
new file mode 100644
index 000000000..20beaec5e
--- /dev/null
+++ b/src/org/traccar/TrackerServer.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.traccar;
+
+import java.net.InetSocketAddress;
+import java.util.concurrent.Executors;
+import org.jboss.netty.bootstrap.ServerBootstrap;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
+import org.jboss.netty.channel.group.ChannelGroup;
+import org.jboss.netty.channel.group.DefaultChannelGroup;
+import org.jboss.netty.channel.group.ChannelGroupFuture;
+
+/**
+ * Tracker server
+ */
+public class TrackerServer extends ServerBootstrap {
+
+ /**
+ * Initialization
+ */
+ private void init(Integer port, Integer threadPoolSize) {
+
+ setPort(port);
+
+ // Create channel factory
+ setFactory(new NioServerSocketChannelFactory(
+ Executors.newCachedThreadPool(),
+ Executors.newCachedThreadPool()));
+ }
+
+ public TrackerServer(Integer port) {
+ init(port, 1);
+ }
+
+ /**
+ * Server port
+ */
+ private Integer port;
+
+ public Integer getPort() {
+ return port;
+ }
+
+ private void setPort(Integer newPort) {
+ port = newPort;
+ }
+
+ /**
+ * Opened channels
+ */
+ private ChannelGroup allChannels = new DefaultChannelGroup();
+
+ public ChannelGroup getChannelGroup() {
+ return allChannels;
+ }
+
+ /**
+ * Start server
+ */
+ public void start() {
+ Channel channel = bind(new InetSocketAddress(getPort()));
+ getChannelGroup().add(channel);
+ }
+
+ /**
+ * Stop server
+ */
+ public void stop() {
+ ChannelGroupFuture future = getChannelGroup().close();
+ future.awaitUninterruptibly();
+ getFactory().releaseExternalResources();
+ }
+
+}
diff --git a/src/org/traccar/helper/NamedParameterStatement.java b/src/org/traccar/helper/NamedParameterStatement.java
new file mode 100644
index 000000000..4e5ffc4fc
--- /dev/null
+++ b/src/org/traccar/helper/NamedParameterStatement.java
@@ -0,0 +1,158 @@
+package net.sourceforge.opentracking.helper;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Date;
+
+public class NamedParameterStatement {
+
+ /**
+ * Native statement
+ */
+ private final PreparedStatement statement;
+
+ /**
+ * Index mapping
+ */
+ private final Map indexMap;
+
+ /**
+ * Initialize statement
+ */
+ public NamedParameterStatement(Connection connection, String query)
+ throws SQLException {
+
+ indexMap = new HashMap();
+ String parsedQuery = parse(query, indexMap);
+ statement = connection.prepareStatement(parsedQuery);
+ }
+
+ /**
+ * Parse query
+ */
+ static final String parse(String query, Map paramMap) {
+
+ int length = query.length();
+ StringBuffer parsedQuery = new StringBuffer(length);
+ boolean inSingleQuote = false;
+ boolean inDoubleQuote = false;
+ int index = 1;
+
+ for(int i = 0; i < length; i++) {
+
+ char c = query.charAt(i);
+
+ // String end
+ if (inSingleQuote) {
+ if (c == '\'') inSingleQuote = false;
+ } else if (inDoubleQuote) {
+ if (c == '"') inDoubleQuote = false;
+ } else {
+
+ // String begin
+ if (c == '\'') {
+ inSingleQuote = true;
+ } else if (c == '"') {
+ inDoubleQuote = true;
+ } else if (c == ':' && i + 1 < length &&
+ Character.isJavaIdentifierStart(query.charAt(i + 1))) {
+
+ // Identifier name
+ int j = i + 2;
+ while (j < length && Character.isJavaIdentifierPart(query.charAt(j))) j++;
+
+ String name = query.substring(i + 1, j);
+ c = '?';
+ i += name.length();
+
+ // Add to list
+ List indexList = (List) paramMap.get(name);
+ if (indexList == null) {
+ indexList = new LinkedList();
+ paramMap.put(name, indexList);
+ }
+ indexList.add(new Integer(index));
+
+ index++;
+ }
+ }
+
+ parsedQuery.append(c);
+ }
+
+ return parsedQuery.toString();
+ }
+
+ /**
+ * Execute query with result
+ */
+ public ResultSet executeQuery() throws SQLException {
+ return statement.executeQuery();
+ }
+
+
+ /**
+ * Executes query without result
+ */
+ public int executeUpdate() throws SQLException {
+ return statement.executeUpdate();
+ }
+
+ /**
+ * Immediately closes the statement
+ */
+ public void close() throws SQLException {
+ statement.close();
+ }
+
+ public void setInt(String name, int value) throws SQLException {
+
+ List indexList = (List) indexMap.get(name);
+ if (indexList != null) for (Object index: indexList) {
+ statement.setInt((Integer) index, value);
+ }
+ }
+
+ public void setLong(String name, long value) throws SQLException {
+
+ List indexList = (List) indexMap.get(name);
+ if (indexList != null) for (Object index: indexList) {
+ statement.setLong((Integer) index, value);
+ }
+ }
+
+ public void setBoolean(String name, boolean value) throws SQLException {
+
+ List indexList = (List) indexMap.get(name);
+ if (indexList != null) for (Object index: indexList) {
+ statement.setBoolean((Integer) index, value);
+ }
+ }
+
+ public void setDouble(String name, double value) throws SQLException {
+
+ List indexList = (List) indexMap.get(name);
+ if (indexList != null) for (Object index: indexList) {
+ statement.setDouble((Integer) index, value);
+ }
+ }
+
+ public void setTimestamp(String name, Date value) throws SQLException {
+
+ List indexList = (List) indexMap.get(name);
+ if (indexList != null) for (Object index: indexList) {
+ statement.setTimestamp(
+ (Integer) index,
+ new Timestamp(value.getTime()));
+ }
+ }
+
+}
diff --git a/src/org/traccar/protocol/gl200/Gl200ProtocolDecoder.java b/src/org/traccar/protocol/gl200/Gl200ProtocolDecoder.java
new file mode 100644
index 000000000..6d0e0a8d9
--- /dev/null
+++ b/src/org/traccar/protocol/gl200/Gl200ProtocolDecoder.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sourceforge.opentracking.protocol.gl200;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
+import net.sourceforge.opentracking.Position;
+import net.sourceforge.opentracking.DataManager;
+import org.jboss.netty.channel.ChannelEvent;
+import org.jboss.netty.channel.ChannelState;
+import org.jboss.netty.channel.ChannelStateEvent;
+
+/**
+ * GL200 tracker protocol decoder
+ */
+public class Gl200ProtocolDecoder extends OneToOneDecoder {
+
+ /**
+ * Data manager
+ */
+ private DataManager dataManager;
+
+ /**
+ * Reset connection delay
+ */
+ private Integer resetDelay;
+
+ /**
+ * Init device table
+ */
+ public Gl200ProtocolDecoder(DataManager dataManager, Integer resetDelay) {
+ this.dataManager = dataManager;
+ this.resetDelay = resetDelay;
+ }
+
+ /**
+ * Regular expressions pattern
+ */
+ static private Pattern pattern = Pattern.compile(
+ "\\+RESP:GT...," +
+ "\\d{6}," + // Protocol version
+ "(\\d{15})," + // IMEI
+ "[^,]*," + // Device name
+ "\\d," + // Report ID
+ "\\d," + // Report type
+ "\\d*," + // Number
+ "(\\d*)," + // GPS accuracy
+ "(\\d+.\\d)," + // Speed
+ "(\\d+)," + // Course
+ "(-?\\d+.\\d)," + // Altitude
+ "(-?\\d+.\\d+)," + // Longitude
+ "(-?\\d+.\\d+)," + // Latitude
+ "(\\d{4})(\\d{2})(\\d{2})" + // Date (YYYYMMDD)
+ "(\\d{2})(\\d{2})(\\d{2})," + // Time (HHMMSS)
+ "[^$]*");
+
+ /**
+ * Decode message
+ */
+ protected Object decode(
+ ChannelHandlerContext ctx, Channel channel, Object msg)
+ throws Exception {
+
+ String sentence = (String) msg;
+
+ // Parse message
+ Matcher parser = pattern.matcher(sentence);
+ if (!parser.matches()) {
+ return null;
+ }
+
+ // Create new position
+ Position position = new Position();
+
+ Integer index = 1;
+
+ // Get device by IMEI
+ String imei = parser.group(index++);
+ position.setDeviceId(dataManager.getDeviceByImei(imei).getId());
+
+ // Validity
+ position.setValid(Integer.valueOf(parser.group(index++)) == 0 ? false : true);
+
+ // Position info
+ position.setSpeed(Double.valueOf(parser.group(index++)));
+ position.setCourse(Double.valueOf(parser.group(index++)));
+ position.setAltitude(Double.valueOf(parser.group(index++)));
+ position.setLongitude(Double.valueOf(parser.group(index++)));
+ position.setLatitude(Double.valueOf(parser.group(index++)));
+
+ // Date
+ Calendar time = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+ time.clear();
+ time.set(Calendar.YEAR, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
+ time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
+
+ // Time
+ time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
+ position.setTime(time.getTime());
+
+ return position;
+ }
+
+ /**
+ * Disconnect channel
+ */
+ class DisconnectTask extends TimerTask {
+ private Channel channel;
+
+ public DisconnectTask(Channel channel) {
+ this.channel = channel;
+ }
+
+ public void run() {
+ channel.disconnect();
+ }
+ }
+
+ /**
+ * Handle connect event
+ */
+ @Override
+ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
+ super.handleUpstream(ctx, evt);
+
+ if (evt instanceof ChannelStateEvent) {
+ ChannelStateEvent event = (ChannelStateEvent) evt;
+
+ if (event.getState() == ChannelState.CONNECTED && event.getValue() != null && resetDelay != 0) {
+ new Timer().schedule(new DisconnectTask(evt.getChannel()), resetDelay);
+ }
+ }
+ }
+
+}
diff --git a/src/org/traccar/protocol/gps103/Gps103ProtocolDecoder.java b/src/org/traccar/protocol/gps103/Gps103ProtocolDecoder.java
new file mode 100644
index 000000000..85e29cc0e
--- /dev/null
+++ b/src/org/traccar/protocol/gps103/Gps103ProtocolDecoder.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sourceforge.opentracking.protocol.gps103;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
+import net.sourceforge.opentracking.Position;
+import net.sourceforge.opentracking.DataManager;
+import org.jboss.netty.channel.ChannelEvent;
+import org.jboss.netty.channel.ChannelState;
+import org.jboss.netty.channel.ChannelStateEvent;
+
+/**
+ * Gps 103 tracker protocol decoder
+ */
+public class Gps103ProtocolDecoder extends OneToOneDecoder {
+
+ /**
+ * Data manager
+ */
+ private DataManager dataManager;
+
+ /**
+ * Reset connection delay
+ */
+ private Integer resetDelay;
+
+ /**
+ * Init device table
+ */
+ public Gps103ProtocolDecoder(DataManager dataManager, Integer resetDelay) {
+ this.dataManager = dataManager;
+ this.resetDelay = resetDelay;
+ }
+
+ /**
+ * Regular expressions pattern
+ */
+ static private Pattern pattern = Pattern.compile(
+ "imei:" +
+ "([\\d]+)," + // IMEI
+ "[^,]+," +
+ "(\\d{2})(\\d{2})(\\d{2})[\\d]+," + // Date
+ "[+]?[\\d]*," +
+ "[FL]," + // F - full / L - low
+ "([\\d]{2})([\\d]{2})([\\d]{2}).([\\d]{3})," + // Time (HHMMSS.SSS)
+ "([AV])," + // Validity
+ "([\\d]{2})([\\d]{2}.[\\d]{4})," + // Latitude (DDMM.MMMM)
+ "([NS])," +
+ "([\\d]{3})([\\d]{2}.[\\d]{4})," + // Longitude (DDDMM.MMMM)
+ "([EW])," +
+ "([\\d]+.[\\d]{2})," + // Speed
+ ".*");
+
+ /**
+ * Decode message
+ */
+ protected Object decode(
+ ChannelHandlerContext ctx, Channel channel, Object msg)
+ throws Exception {
+
+ String sentence = (String) msg;
+
+ // Send response #1
+ if (sentence.contains("##")) {
+ channel.write("LOAD");
+ }
+
+ // Send response #2
+ if (sentence.length() == 15 && Character.isDigit(sentence.charAt(0))) {
+ channel.write("ON");
+ }
+
+ // Parse message
+ Matcher parser = pattern.matcher(sentence);
+ if (!parser.matches()) {
+ return null;
+ }
+
+ // Create new position
+ Position position = new Position();
+
+ Integer index = 1;
+
+ // Get device by IMEI
+ String imei = parser.group(index++);
+ position.setDeviceId(dataManager.getDeviceByImei(imei).getId());
+
+ // Date
+ Calendar time = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+ time.clear();
+ time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
+ time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
+
+ // Time
+ time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MILLISECOND, Integer.valueOf(parser.group(index++)));
+ position.setTime(time.getTime());
+
+ // Validity
+ position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);
+
+ // Latitude
+ Double latitude = Double.valueOf(parser.group(index++));
+ latitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
+ position.setLatitude(latitude);
+
+ // Longitude
+ Double lonlitude = Double.valueOf(parser.group(index++));
+ lonlitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("W") == 0) lonlitude = -lonlitude;
+ position.setLongitude(lonlitude);
+
+ // Altitude
+ position.setAltitude(0.0);
+
+ // Speed
+ position.setSpeed(Double.valueOf(parser.group(index++)));
+ position.setCourse(0.0);
+
+ return position;
+ }
+
+ /**
+ * Disconnect channel
+ */
+ class DisconnectTask extends TimerTask {
+ private Channel channel;
+
+ public DisconnectTask(Channel channel) {
+ this.channel = channel;
+ }
+
+ public void run() {
+ channel.disconnect();
+ }
+ }
+
+ /**
+ * Handle connect event
+ */
+ @Override
+ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
+ super.handleUpstream(ctx, evt);
+
+ if (evt instanceof ChannelStateEvent) {
+ ChannelStateEvent event = (ChannelStateEvent) evt;
+
+ if (event.getState() == ChannelState.CONNECTED && event.getValue() != null && resetDelay != 0) {
+ new Timer().schedule(new DisconnectTask(evt.getChannel()), resetDelay);
+ }
+ }
+ }
+
+}
diff --git a/src/org/traccar/protocol/t55/T55ProtocolDecoder.java b/src/org/traccar/protocol/t55/T55ProtocolDecoder.java
new file mode 100644
index 000000000..01954b474
--- /dev/null
+++ b/src/org/traccar/protocol/t55/T55ProtocolDecoder.java
@@ -0,0 +1,200 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sourceforge.opentracking.protocol.t55;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
+import net.sourceforge.opentracking.Position;
+import net.sourceforge.opentracking.DataManager;
+import org.jboss.netty.channel.ChannelEvent;
+import org.jboss.netty.channel.ChannelState;
+import org.jboss.netty.channel.ChannelStateEvent;
+
+/**
+ * Gps 103 tracker protocol decoder
+ */
+public class T55ProtocolDecoder extends OneToOneDecoder {
+
+ /**
+ * Data manager
+ */
+ private DataManager dataManager;
+
+ /**
+ * Reset connection delay
+ */
+ private Integer resetDelay;
+
+ /**
+ * Device ID
+ */
+ private Long deviceId;
+
+ /**
+ * Init device table
+ */
+ public T55ProtocolDecoder(DataManager dataManager, Integer resetDelay) {
+ this.dataManager = dataManager;
+ this.resetDelay = resetDelay;
+ }
+
+ /**
+ * Regular expressions pattern
+ */
+ static private Pattern pattern = Pattern.compile(
+ "\\$GPRMC," +
+ "(\\d{2})(\\d{2})(\\d{2}).(\\d{3})," + // Time (HHMMSS.SSS)
+ "([AV])," + // Validity
+ "(\\d{2})(\\d{2}.\\d{4})," + // Latitude (DDMM.MMMM)
+ "([NS])," +
+ "(\\d{3})(\\d{2}.\\d{4})," + // Longitude (DDDMM.MMMM)
+ "([EW])," +
+ "(\\d+.\\d{2})?," + // Speed
+ "(\\d+.\\d{2})?," + // Course
+ "(\\d{2})(\\d{2})(\\d{2})" + // Date (DDMMYY)
+ ".+"); // Other (Checksumm)
+
+ /**
+ * Decode message
+ */
+ protected Object decode(
+ ChannelHandlerContext ctx, Channel channel, Object msg)
+ throws Exception {
+
+ String sentence = (String) msg;
+
+ //System.out.println(sentence);
+
+ // Detect device ID
+ if (sentence.contains("$PGID")) {
+ String imei = sentence.substring(6, 6 + 15);
+ deviceId = dataManager.getDeviceByImei(imei).getId();
+ }
+
+ // Parse message
+ else if (sentence.contains("$GPRMC") && deviceId != null) {
+
+ // Send response
+ if (channel != null) {
+ channel.write("OK1\r\n");
+ }
+
+ // Parse message
+ Matcher parser = pattern.matcher(sentence);
+ if (!parser.matches()) {
+ return null;
+ }
+
+ // Create new position
+ Position position = new Position();
+ position.setDeviceId(deviceId);
+
+ Integer index = 1;
+
+ // Time
+ Calendar time = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+ time.clear();
+ time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
+ index += 1; // Skip milliseconds
+ position.setTime(time.getTime());
+
+ // Validity
+ position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);
+
+ // Latitude
+ Double latitude = Double.valueOf(parser.group(index++));
+ latitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
+ position.setLatitude(latitude);
+
+ // Longitude
+ Double lonlitude = Double.valueOf(parser.group(index++));
+ lonlitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("W") == 0) lonlitude = -lonlitude;
+ position.setLongitude(lonlitude);
+
+ // Speed
+ String speed = parser.group(index++);
+ if (speed != null) {
+ position.setSpeed(Double.valueOf(speed));
+ } else {
+ position.setSpeed(0.0);
+ }
+
+ // Course
+ String course = parser.group(index++);
+ if (course != null) {
+ position.setCourse(Double.valueOf(course));
+ } else {
+ position.setCourse(0.0);
+ }
+
+ // Date
+ time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
+ time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
+
+ // Altitude
+ position.setAltitude(0.0);
+
+ return position;
+ }
+
+ return null;
+ }
+
+ /**
+ * Disconnect channel
+ */
+ class DisconnectTask extends TimerTask {
+ private Channel channel;
+
+ public DisconnectTask(Channel channel) {
+ this.channel = channel;
+ }
+
+ public void run() {
+ channel.disconnect();
+ }
+ }
+
+ /**
+ * Handle connect event
+ */
+ @Override
+ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
+ super.handleUpstream(ctx, evt);
+
+ if (evt instanceof ChannelStateEvent) {
+ ChannelStateEvent event = (ChannelStateEvent) evt;
+
+ if (event.getState() == ChannelState.CONNECTED && event.getValue() != null && resetDelay != 0) {
+ new Timer().schedule(new DisconnectTask(evt.getChannel()), resetDelay);
+ }
+ }
+ }
+
+}
diff --git a/src/org/traccar/protocol/tk103/Tk103ProtocolDecoder.java b/src/org/traccar/protocol/tk103/Tk103ProtocolDecoder.java
new file mode 100644
index 000000000..12108b121
--- /dev/null
+++ b/src/org/traccar/protocol/tk103/Tk103ProtocolDecoder.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sourceforge.opentracking.protocol.tk103;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
+import net.sourceforge.opentracking.Position;
+import net.sourceforge.opentracking.DataManager;
+import org.jboss.netty.channel.ChannelEvent;
+import org.jboss.netty.channel.ChannelState;
+import org.jboss.netty.channel.ChannelStateEvent;
+
+/**
+ * Gps 103 tracker protocol decoder
+ */
+public class Tk103ProtocolDecoder extends OneToOneDecoder {
+
+ /**
+ * Data manager
+ */
+ private DataManager dataManager;
+
+ /**
+ * Reset connection delay
+ */
+ private Integer resetDelay;
+
+ /**
+ * Init device table
+ */
+ public Tk103ProtocolDecoder(DataManager dataManager, Integer resetDelay) {
+ this.dataManager = dataManager;
+ this.resetDelay = resetDelay;
+ }
+
+ /**
+ * Regular expressions pattern
+ */
+ static private Pattern pattern = Pattern.compile(
+ "\\(" +
+ "(\\d+)" + // Device ID
+ "(.{4})" + // Command
+ "(\\d{15})" + // IMEI (?)
+ "(\\d{2})(\\d{2})(\\d{2})" + // Date (YYMMDD)
+ "([AV])" + // Validity
+ "(\\d{2})(\\d{2}.\\d{4})" + // Latitude (DDMM.MMMM)
+ "([NS])" +
+ "(\\d{3})(\\d{2}.\\d{4})" + // Longitude (DDDMM.MMMM)
+ "([EW])" +
+ "(\\d+.\\d)" + // Speed
+ "(\\d{2})(\\d{2})(\\d{2})" + // Time (HHMMSS)
+ "(\\d+.\\d{2})" + // Course
+ "(\\d+)" + // State
+ ".+"); // Mileage (?)
+
+ /**
+ * Decode message
+ */
+ protected Object decode(
+ ChannelHandlerContext ctx, Channel channel, Object msg)
+ throws Exception {
+
+ String sentence = (String) msg;
+
+ // TODO: Send response (?)
+
+ // Parse message
+ Matcher parser = pattern.matcher(sentence);
+ if (!parser.matches()) {
+ return null;
+ }
+
+ // Create new position
+ Position position = new Position();
+
+ Integer index = 1;
+ index += 2; // Skip Device ID and command
+
+ // Get device by IMEI
+ String imei = parser.group(index++);
+ position.setDeviceId(dataManager.getDeviceByImei(imei).getId());
+
+ // Date
+ Calendar time = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+ time.clear();
+ time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
+ time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
+
+ // Validity
+ position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);
+
+ // Latitude
+ Double latitude = Double.valueOf(parser.group(index++));
+ latitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
+ position.setLatitude(latitude);
+
+ // Longitude
+ Double lonlitude = Double.valueOf(parser.group(index++));
+ lonlitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("W") == 0) lonlitude = -lonlitude;
+ position.setLongitude(lonlitude);
+
+ // Altitude
+ position.setAltitude(0.0);
+
+ // Speed
+ position.setSpeed(Double.valueOf(parser.group(index++)));
+
+ // Time
+ time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
+ position.setTime(time.getTime());
+
+ // Course
+ position.setCourse(Double.valueOf(parser.group(index++)));
+
+ return position;
+ }
+
+ /**
+ * Disconnect channel
+ */
+ class DisconnectTask extends TimerTask {
+ private Channel channel;
+
+ public DisconnectTask(Channel channel) {
+ this.channel = channel;
+ }
+
+ public void run() {
+ channel.disconnect();
+ }
+ }
+
+ /**
+ * Handle connect event
+ */
+ @Override
+ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
+ super.handleUpstream(ctx, evt);
+
+ if (evt instanceof ChannelStateEvent) {
+ ChannelStateEvent event = (ChannelStateEvent) evt;
+
+ if (event.getState() == ChannelState.CONNECTED && event.getValue() != null && resetDelay != 0) {
+ new Timer().schedule(new DisconnectTask(evt.getChannel()), resetDelay);
+ }
+ }
+ }
+
+}
diff --git a/src/org/traccar/protocol/xexun/XexunFrameDecoder.java b/src/org/traccar/protocol/xexun/XexunFrameDecoder.java
new file mode 100644
index 000000000..839e5b3ec
--- /dev/null
+++ b/src/org/traccar/protocol/xexun/XexunFrameDecoder.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sourceforge.opentracking.protocol.xexun;
+
+import org.jboss.netty.handler.codec.frame.FrameDecoder;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.buffer.ChannelBuffer;
+
+public class XexunFrameDecoder extends FrameDecoder {
+
+ /**
+ * Find string in network buffer
+ */
+ private static Integer find(
+ ChannelBuffer buf,
+ Integer start,
+ Integer length,
+ String subString) {
+
+ int index = start;
+ boolean match;
+
+ for (; index < length; index++) {
+ match = true;
+
+ for (int i = 0; i < subString.length(); i++) {
+ char c = (char) buf.getByte(index + i);
+ if (c != subString.charAt(i)) {
+ match = false;
+ break;
+ }
+ }
+
+ if (match) {
+ return index;
+ }
+ }
+
+ return null;
+ }
+
+ protected Object decode(
+ ChannelHandlerContext ctx,
+ Channel channel,
+ ChannelBuffer buf) throws Exception {
+
+ // Check minimum length
+ int length = buf.readableBytes();
+ if (length < 100) {
+ return null;
+ }
+
+ // Find start
+ Integer beginIndex = find(buf, 0, length, "GPRMC");
+ if (beginIndex == null) {
+ return null;
+ }
+
+ // Find identifier
+ Integer idIndex = find(buf, beginIndex, length, "imei:");
+ if (idIndex == null) {
+ return null;
+ }
+
+ // Find end
+ Integer endIndex = find(buf, idIndex, length, ",");
+ if (endIndex == null) {
+ return null;
+ }
+
+ // Read buffer
+ buf.skipBytes(beginIndex);
+ ChannelBuffer frame = buf.readBytes(endIndex - beginIndex + 1);
+
+ return frame;
+ }
+
+}
diff --git a/src/org/traccar/protocol/xexun/XexunProtocolDecoder.java b/src/org/traccar/protocol/xexun/XexunProtocolDecoder.java
new file mode 100644
index 000000000..872569e1a
--- /dev/null
+++ b/src/org/traccar/protocol/xexun/XexunProtocolDecoder.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2010 Anton Tananaev (anton@tananaev.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package net.sourceforge.opentracking.protocol.xexun;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import java.text.ParseException;
+import java.util.TimeZone;
+import java.util.Timer;
+import java.util.TimerTask;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
+import net.sourceforge.opentracking.Position;
+import net.sourceforge.opentracking.DataManager;
+import org.jboss.netty.channel.ChannelEvent;
+import org.jboss.netty.channel.ChannelState;
+import org.jboss.netty.channel.ChannelStateEvent;
+
+/**
+ * Xexun tracker protocol decoder
+ */
+public class XexunProtocolDecoder extends OneToOneDecoder {
+
+ /**
+ * Data manager
+ */
+ private DataManager dataManager;
+
+ /**
+ * Reset connection delay
+ */
+ private Integer resetDelay;
+
+ /**
+ * Init device table
+ */
+ public XexunProtocolDecoder(DataManager dataManager, Integer resetDelay) {
+ this.dataManager = dataManager;
+ this.resetDelay = resetDelay;
+ }
+
+ /**
+ * Regular expressions pattern
+ */
+ static private Pattern pattern = Pattern.compile(
+ "GPRMC," +
+ "([\\d]{2})([\\d]{2})([\\d]{2}).([\\d]{3})," + // Time (HHMMSS.SSS)
+ "([AV])," + // Validity
+ "([\\d]{2})([\\d]{2}.[\\d]{4})," + // Latitude (DDMM.MMMM)
+ "([NS])," +
+ "([\\d]{3})([\\d]{2}.[\\d]{4})," + // Longitude (DDDMM.MMMM)
+ "([EW])," +
+ "([\\d]+.[\\d]+)," + // Speed
+ "([\\d]+.[\\d]+)?," + // Course
+ "([\\d]{2})([\\d]{2})([\\d]{2})," + // Date (DDMMYY)
+ ".*imei:" +
+ "([\\d]+),"); // IMEI
+
+ /**
+ * Decode message
+ */
+ protected Object decode(
+ ChannelHandlerContext ctx, Channel channel, Object msg)
+ throws Exception {
+
+ // Parse message
+ String sentence = (String) msg;
+ Matcher parser = pattern.matcher(sentence);
+ if (!parser.matches()) {
+ throw new ParseException(null, 0);
+ }
+
+ // Create new position
+ Position position = new Position();
+
+ Integer index = 1;
+
+ // Time
+ Calendar time = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
+ time.clear();
+ time.set(Calendar.HOUR, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MINUTE, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.SECOND, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MILLISECOND, Integer.valueOf(parser.group(index++)));
+
+ // Validity
+ position.setValid(parser.group(index++).compareTo("A") == 0 ? true : false);
+
+ // Latitude
+ Double latitude = Double.valueOf(parser.group(index++));
+ latitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("S") == 0) latitude = -latitude;
+ position.setLatitude(latitude);
+
+ // Longitude
+ Double lonlitude = Double.valueOf(parser.group(index++));
+ lonlitude += Double.valueOf(parser.group(index++)) / 60;
+ if (parser.group(index++).compareTo("W") == 0) lonlitude = -lonlitude;
+ position.setLongitude(lonlitude);
+
+ // Altitude
+ position.setAltitude(0.0);
+
+ // Speed
+ position.setSpeed(Double.valueOf(parser.group(index++)));
+
+ // Course
+ String course = parser.group(index++);
+ if (course != null) {
+ position.setCourse(Double.valueOf(course));
+ } else {
+ position.setCourse(0.0);
+ }
+
+ // Date
+ time.set(Calendar.DAY_OF_MONTH, Integer.valueOf(parser.group(index++)));
+ time.set(Calendar.MONTH, Integer.valueOf(parser.group(index++)) - 1);
+ time.set(Calendar.YEAR, 2000 + Integer.valueOf(parser.group(index++)));
+ position.setTime(time.getTime());
+
+ // Get device by IMEI
+ String imei = parser.group(index++);
+ position.setDeviceId(dataManager.getDeviceByImei(imei).getId());
+
+ return position;
+ }
+
+ /**
+ * Disconnect channel
+ */
+ class DisconnectTask extends TimerTask {
+ private Channel channel;
+
+ public DisconnectTask(Channel channel) {
+ this.channel = channel;
+ }
+
+ public void run() {
+ channel.disconnect();
+ }
+ }
+
+ /**
+ * Handle connect event
+ */
+ @Override
+ public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
+ super.handleUpstream(ctx, evt);
+
+ if (evt instanceof ChannelStateEvent) {
+ ChannelStateEvent event = (ChannelStateEvent) evt;
+
+ if (event.getState() == ChannelState.CONNECTED && event.getValue() != null && resetDelay != 0) {
+ new Timer().schedule(new DisconnectTask(evt.getChannel()), resetDelay);
+ }
+ }
+ }
+
+}