diff options
Diffstat (limited to 'src/main')
65 files changed, 2436 insertions, 205 deletions
diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java index 3acd19b6a..9adea61b0 100644 --- a/src/main/java/org/traccar/MainModule.java +++ b/src/main/java/org/traccar/MainModule.java @@ -191,7 +191,7 @@ public class MainModule extends AbstractModule { case "google": return new GoogleGeolocationProvider(key); case "opencellid": - return new OpenCellIdGeolocationProvider(key); + return new OpenCellIdGeolocationProvider(url, key); case "unwired": return new UnwiredGeolocationProvider(url, key); default: diff --git a/src/main/java/org/traccar/StringProtocolEncoder.java b/src/main/java/org/traccar/StringProtocolEncoder.java index d9acce7f0..e9fb65500 100644 --- a/src/main/java/org/traccar/StringProtocolEncoder.java +++ b/src/main/java/org/traccar/StringProtocolEncoder.java @@ -17,8 +17,6 @@ package org.traccar; import org.traccar.model.Command; -import java.util.Map; - public abstract class StringProtocolEncoder extends BaseProtocolEncoder { public StringProtocolEncoder(Protocol protocol) { @@ -31,21 +29,27 @@ public abstract class StringProtocolEncoder extends BaseProtocolEncoder { protected String formatCommand(Command command, String format, ValueFormatter valueFormatter, String... keys) { - String result = String.format(format, (Object[]) keys); - - result = result.replaceAll("\\{" + Command.KEY_UNIQUE_ID + "}", getUniqueId(command.getDeviceId())); - for (Map.Entry<String, Object> entry : command.getAttributes().entrySet()) { + Object[] values = new String[keys.length]; + for (int i = 0; i < keys.length; i++) { String value = null; - if (valueFormatter != null) { - value = valueFormatter.formatValue(entry.getKey(), entry.getValue()); - } - if (value == null) { - value = entry.getValue().toString(); + if (keys[i].equals(Command.KEY_UNIQUE_ID)) { + value = getUniqueId(command.getDeviceId()); + } else { + Object object = command.getAttributes().get(keys[i]); + if (valueFormatter != null) { + value = valueFormatter.formatValue(keys[i], object); + } + if (value == null && object != null) { + value = object.toString(); + } + if (value == null) { + value = ""; + } } - result = result.replaceAll("\\{" + entry.getKey() + "}", value); + values[i] = value; } - return result; + return String.format(format, values); } protected String formatCommand(Command command, String format, String... keys) { diff --git a/src/main/java/org/traccar/api/resource/SessionResource.java b/src/main/java/org/traccar/api/resource/SessionResource.java index fd331c766..e3c5d457f 100644 --- a/src/main/java/org/traccar/api/resource/SessionResource.java +++ b/src/main/java/org/traccar/api/resource/SessionResource.java @@ -18,6 +18,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.helper.DataConverter; +import org.traccar.helper.ServletHelper; import org.traccar.helper.LogAction; import org.traccar.model.User; @@ -106,6 +107,7 @@ public class SessionResource extends BaseResource { LogAction.login(user.getId()); return user; } else { + LogAction.failedLogin(ServletHelper.retrieveRemoteAddress(request)); throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build()); } } diff --git a/src/main/java/org/traccar/geolocation/OpenCellIdGeolocationProvider.java b/src/main/java/org/traccar/geolocation/OpenCellIdGeolocationProvider.java index 768aaf6a2..cb3094e16 100644 --- a/src/main/java/org/traccar/geolocation/OpenCellIdGeolocationProvider.java +++ b/src/main/java/org/traccar/geolocation/OpenCellIdGeolocationProvider.java @@ -26,11 +26,10 @@ public class OpenCellIdGeolocationProvider implements GeolocationProvider { private String url; - public OpenCellIdGeolocationProvider(String key) { - this("http://opencellid.org/cell/get", key); - } - public OpenCellIdGeolocationProvider(String url, String key) { + if (url == null) { + url = "http://opencellid.org/cell/get"; + } this.url = url + "?format=json&mcc=%d&mnc=%d&lac=%d&cellid=%d&key=" + key; } diff --git a/src/main/java/org/traccar/helper/LogAction.java b/src/main/java/org/traccar/helper/LogAction.java index db13337b8..16d55ec60 100644 --- a/src/main/java/org/traccar/helper/LogAction.java +++ b/src/main/java/org/traccar/helper/LogAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2017 - 2020 Anton Tananaev (anton@traccar.org) * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -44,6 +44,7 @@ public final class LogAction { private static final String PATTERN_OBJECT = "user: %d, action: %s, object: %s, id: %d"; private static final String PATTERN_LINK = "user: %d, action: %s, owner: %s, id: %d, property: %s, id: %d"; private static final String PATTERN_LOGIN = "user: %d, action: %s"; + private static final String PATTERN_LOGIN_FAILED = "login failed from: %s"; private static final String PATTERN_DEVICE_ACCUMULATORS = "user: %d, action: %s, deviceId: %d"; public static void create(long userId, BaseModel object) { @@ -74,6 +75,13 @@ public final class LogAction { logLoginAction(ACTION_LOGOUT, userId); } + public static void failedLogin(String remoteAddress) { + if (remoteAddress == null || remoteAddress.isEmpty()) { + remoteAddress = "unknown"; + } + LOGGER.info(String.format(PATTERN_LOGIN_FAILED, remoteAddress)); + } + public static void resetDeviceAccumulators(long userId, long deviceId) { LOGGER.info(String.format( PATTERN_DEVICE_ACCUMULATORS, userId, ACTION_DEVICE_ACCUMULATORS, deviceId)); @@ -85,7 +93,7 @@ public final class LogAction { } private static void logLinkAction(String action, long userId, - Class<?> owner, long ownerId, Class<?> property, long propertyId) { + Class<?> owner, long ownerId, Class<?> property, long propertyId) { LOGGER.info(String.format( PATTERN_LINK, userId, action, Introspector.decapitalize(owner.getSimpleName()), ownerId, diff --git a/src/main/java/org/traccar/helper/ServletHelper.java b/src/main/java/org/traccar/helper/ServletHelper.java new file mode 100644 index 000000000..e3481e249 --- /dev/null +++ b/src/main/java/org/traccar/helper/ServletHelper.java @@ -0,0 +1,27 @@ +package org.traccar.helper; + +import javax.servlet.http.HttpServletRequest; + + +public final class ServletHelper { + + private ServletHelper() { + } + + public static String retrieveRemoteAddress(HttpServletRequest request) { + + if (request != null) { + String remoteAddress = request.getHeader("X-FORWARDED-FOR"); + + if (remoteAddress != null && !remoteAddress.isEmpty()) { + return remoteAddress.substring(0, remoteAddress.indexOf(",")); // removes the additional data + } else { + remoteAddress = request.getRemoteAddr(); + return remoteAddress; + } + } else { + return null; + } + } + +} diff --git a/src/main/java/org/traccar/model/Command.java b/src/main/java/org/traccar/model/Command.java index 336fc61f4..abe538a10 100644 --- a/src/main/java/org/traccar/model/Command.java +++ b/src/main/java/org/traccar/model/Command.java @@ -68,6 +68,7 @@ public class Command extends Message implements Cloneable { public static final String KEY_UNIQUE_ID = "uniqueId"; public static final String KEY_FREQUENCY = "frequency"; + public static final String KEY_LANGUAGE = "language"; public static final String KEY_TIMEZONE = "timezone"; public static final String KEY_DEVICE_PASSWORD = "devicePassword"; public static final String KEY_RADIUS = "radius"; diff --git a/src/main/java/org/traccar/protocol/AdmProtocolEncoder.java b/src/main/java/org/traccar/protocol/AdmProtocolEncoder.java index 1c3dfc156..c02fa4112 100644 --- a/src/main/java/org/traccar/protocol/AdmProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/AdmProtocolEncoder.java @@ -34,7 +34,7 @@ public class AdmProtocolEncoder extends StringProtocolEncoder { return formatCommand(command, "STATUS\r\n"); case Command.TYPE_CUSTOM: - return formatCommand(command, "{%s}\r\n", Command.KEY_DATA); + return formatCommand(command, "%s\r\n", Command.KEY_DATA); default: return null; diff --git a/src/main/java/org/traccar/protocol/BlueProtocol.java b/src/main/java/org/traccar/protocol/BlueProtocol.java new file mode 100644 index 000000000..79f0714ec --- /dev/null +++ b/src/main/java/org/traccar/protocol/BlueProtocol.java @@ -0,0 +1,35 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.handler.codec.LengthFieldBasedFrameDecoder; +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class BlueProtocol extends BaseProtocol { + + public BlueProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 1, 2, 3, 0)); + pipeline.addLast(new BlueProtocolDecoder(BlueProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/BlueProtocolDecoder.java b/src/main/java/org/traccar/protocol/BlueProtocolDecoder.java new file mode 100644 index 000000000..98a8ae565 --- /dev/null +++ b/src/main/java/org/traccar/protocol/BlueProtocolDecoder.java @@ -0,0 +1,113 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.Protocol; +import org.traccar.helper.BitUtil; +import org.traccar.helper.DateBuilder; +import org.traccar.model.Position; + +import java.net.SocketAddress; + +public class BlueProtocolDecoder extends BaseProtocolDecoder { + + public BlueProtocolDecoder(Protocol protocol) { + super(protocol); + } + + private double readCoordinate(ByteBuf buf, boolean negative) { + + int value = buf.readUnsignedShort(); + int degrees = value / 100; + double minutes = value % 100 + buf.readUnsignedShort() * 0.0001; + double coordinate = degrees + minutes / 60; + return negative ? -coordinate : coordinate; + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ByteBuf buf = (ByteBuf) msg; + + buf.readUnsignedByte(); // header + buf.readUnsignedShort(); // length + buf.readUnsignedByte(); // version + buf.readUnsignedByte(); + + String id = String.valueOf(buf.readUnsignedInt()); + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); + if (deviceSession == null) { + return null; + } + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + while (buf.readableBytes() > 1) { + + int frameEnd = buf.readerIndex() + buf.readUnsignedByte(); + + int type = buf.readUnsignedByte(); + buf.readUnsignedByte(); // reference id + buf.readUnsignedByte(); + buf.readUnsignedByte(); // flags + + if (type == 0x01) { + + buf.readUnsignedByte(); // reserved + int flags = buf.readUnsignedByte(); + + position.setValid(BitUtil.check(flags, 7)); + position.setLatitude(readCoordinate(buf, BitUtil.check(flags, 6))); + position.setLongitude(readCoordinate(buf, BitUtil.check(flags, 5))); + position.setSpeed(buf.readUnsignedShort() + buf.readUnsignedShort() * 0.001); + position.setCourse(buf.readUnsignedShort() + buf.readUnsignedByte() * 0.01); + + DateBuilder dateBuilder = new DateBuilder() + .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) + .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); + position.setTime(dateBuilder.getDate()); + + buf.readUnsignedShort(); // lac + buf.readUnsignedShort(); // cid + + } else if (type == 0x12) { + + int status; + + status = buf.readUnsignedByte(); // status 1 + position.set(Position.KEY_ALARM, BitUtil.check(status, 1) ? Position.ALARM_VIBRATION : null); + + buf.readUnsignedByte(); // status 2 + buf.readUnsignedByte(); // status 3 + buf.readUnsignedByte(); // status 4 + buf.readUnsignedByte(); // status 5 + buf.readUnsignedByte(); // status 6 + + } + + buf.readerIndex(frameEnd); + } + + return position.getFixTime() != null ? position : null; + } + +} diff --git a/src/main/java/org/traccar/protocol/CarcellProtocolEncoder.java b/src/main/java/org/traccar/protocol/CarcellProtocolEncoder.java index 083fe9a9e..78dbe7e91 100644 --- a/src/main/java/org/traccar/protocol/CarcellProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/CarcellProtocolEncoder.java @@ -30,9 +30,9 @@ public class CarcellProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "$SRVCMD,{%s},BA#\r\n", Command.KEY_UNIQUE_ID); + return formatCommand(command, "$SRVCMD,%s,BA#\r\n", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "$SRVCMD,{%s},BD#\r\n", Command.KEY_UNIQUE_ID); + return formatCommand(command, "$SRVCMD,%s,BD#\r\n", Command.KEY_UNIQUE_ID); default: return null; } diff --git a/src/main/java/org/traccar/protocol/CastelProtocolDecoder.java b/src/main/java/org/traccar/protocol/CastelProtocolDecoder.java index 03e4b25fd..23401b5ee 100644 --- a/src/main/java/org/traccar/protocol/CastelProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/CastelProtocolDecoder.java @@ -23,6 +23,7 @@ import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; +import org.traccar.helper.BitUtil; import org.traccar.helper.Checksum; import org.traccar.helper.DateBuilder; import org.traccar.helper.ObdDecoder; @@ -185,7 +186,14 @@ public class CastelProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_ODOMETER_TRIP, buf.readUnsignedIntLE()); position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedIntLE()); buf.readUnsignedShortLE(); // current fuel consumption - position.set(Position.KEY_STATUS, buf.readUnsignedIntLE()); + + long state = buf.readUnsignedIntLE(); + position.set(Position.KEY_ALARM, BitUtil.check(state, 4) ? Position.ALARM_ACCELERATION : null); + position.set(Position.KEY_ALARM, BitUtil.check(state, 5) ? Position.ALARM_BRAKING : null); + position.set(Position.KEY_ALARM, BitUtil.check(state, 6) ? Position.ALARM_IDLE : null); + position.set(Position.KEY_IGNITION, BitUtil.check(state, 2 * 8 + 2)); + position.set(Position.KEY_STATUS, state); + buf.skipBytes(8); } diff --git a/src/main/java/org/traccar/protocol/EsealProtocolEncoder.java b/src/main/java/org/traccar/protocol/EsealProtocolEncoder.java index 6ee305ed8..74f9e22ab 100644 --- a/src/main/java/org/traccar/protocol/EsealProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/EsealProtocolEncoder.java @@ -31,13 +31,13 @@ public class EsealProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand( - command, "##S,eSeal,{%s},256,3.0.8,{%s},E##", Command.KEY_UNIQUE_ID, Command.KEY_DATA); + command, "##S,eSeal,%s,256,3.0.8,%s,E##", Command.KEY_UNIQUE_ID, Command.KEY_DATA); case Command.TYPE_ALARM_ARM: return formatCommand( - command, "##S,eSeal,{%s},256,3.0.8,RC-Power Control,Power OFF,E##", Command.KEY_UNIQUE_ID); + command, "##S,eSeal,%s,256,3.0.8,RC-Power Control,Power OFF,E##", Command.KEY_UNIQUE_ID); case Command.TYPE_ALARM_DISARM: return formatCommand( - command, "##S,eSeal,{%s},256,3.0.8,RC-Unlock,E##", Command.KEY_UNIQUE_ID); + command, "##S,eSeal,%s,256,3.0.8,RC-Unlock,E##", Command.KEY_UNIQUE_ID); default: return null; } diff --git a/src/main/java/org/traccar/protocol/Gl200ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Gl200ProtocolEncoder.java index 32307446b..dd0672c23 100644 --- a/src/main/java/org/traccar/protocol/Gl200ProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/Gl200ProtocolEncoder.java @@ -32,17 +32,17 @@ public class Gl200ProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { case Command.TYPE_POSITION_SINGLE: - return formatCommand(command, "AT+GTRTO={%s},1,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "AT+GTRTO=%s,1,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "AT+GTOUT={%s},1,,,0,0,0,0,0,0,0,,,,,,,FFFF$", + return formatCommand(command, "AT+GTOUT=%s,1,,,0,0,0,0,0,0,0,,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "AT+GTOUT={%s},0,,,0,0,0,0,0,0,0,,,,,,,FFFF$", + return formatCommand(command, "AT+GTOUT=%s,0,,,0,0,0,0,0,0,0,,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_IDENTIFICATION: - return formatCommand(command, "AT+GTRTO={%s},8,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "AT+GTRTO=%s,8,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: - return formatCommand(command, "AT+GTRTO={%s},3,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "AT+GTRTO=%s,3,,,,,,FFFF$", Command.KEY_DEVICE_PASSWORD); default: return null; } diff --git a/src/main/java/org/traccar/protocol/GlobalstarProtocolDecoder.java b/src/main/java/org/traccar/protocol/GlobalstarProtocolDecoder.java index 5739a1224..26af8d5af 100644 --- a/src/main/java/org/traccar/protocol/GlobalstarProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/GlobalstarProtocolDecoder.java @@ -17,28 +17,40 @@ package org.traccar.protocol; import com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream; import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufOutputStream; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; +import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpVersion; import org.traccar.BaseHttpProtocolDecoder; import org.traccar.DeviceSession; +import org.traccar.NetworkMessage; import org.traccar.Protocol; import org.traccar.helper.DataConverter; import org.traccar.model.Position; import org.w3c.dom.Document; +import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.net.SocketAddress; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; @@ -67,6 +79,38 @@ public class GlobalstarProtocolDecoder extends BaseHttpProtocolDecoder { } } + private void sendResponse(Channel channel, String messageId) throws TransformerException { + + Document document = documentBuilder.newDocument(); + Element rootElement = document.createElement("stuResponseMsg"); + rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); + rootElement.setAttribute( + "xsi:noNamespaceSchemaLocation", "http://cody.glpconnect.com/XSD/StuResponse_Rev1_0.xsd"); + rootElement.setAttribute("deliveryTimeStamp", new SimpleDateFormat("dd/MM/yyyy hh:mm:ss z").format(new Date())); + rootElement.setAttribute("messageID", "00000000000000000000000000000000"); + rootElement.setAttribute("correlationID", messageId); + document.appendChild(rootElement); + + Element state = document.createElement("state"); + state.appendChild(document.createTextNode("pass")); + rootElement.appendChild(state); + + Element stateMessage = document.createElement("stateMessage"); + stateMessage.appendChild(document.createTextNode("Messages received and stored successfully")); + rootElement.appendChild(stateMessage); + + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + ByteBuf content = Unpooled.buffer(); + transformer.transform(new DOMSource(document), new StreamResult(new ByteBufOutputStream(content))); + + FullHttpResponse response = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); + if (channel != null) { + channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress())); + } + } + + @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { @@ -112,7 +156,7 @@ public class GlobalstarProtocolDecoder extends BaseHttpProtocolDecoder { } } - sendResponse(channel, HttpResponseStatus.OK); + sendResponse(channel, document.getFirstChild().getAttributes().getNamedItem("messageID").getNodeValue()); return positions; } diff --git a/src/main/java/org/traccar/protocol/Gps103ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Gps103ProtocolEncoder.java index 7128823ed..e662e9b04 100644 --- a/src/main/java/org/traccar/protocol/Gps103ProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/Gps103ProtocolEncoder.java @@ -47,24 +47,24 @@ public class Gps103ProtocolEncoder extends StringProtocolEncoder implements Stri switch (command.getType()) { case Command.TYPE_CUSTOM: - return formatCommand(command, "**,imei:{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DATA); + return formatCommand(command, "**,imei:%s,%s", Command.KEY_UNIQUE_ID, Command.KEY_DATA); case Command.TYPE_POSITION_STOP: - return formatCommand(command, "**,imei:{%s},A", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,A", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_SINGLE: - return formatCommand(command, "**,imei:{%s},B", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,B", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_PERIODIC: return formatCommand( - command, "**,imei:{%s},C,{%s}", this, Command.KEY_UNIQUE_ID, Command.KEY_FREQUENCY); + command, "**,imei:%s,C,%s", this, Command.KEY_UNIQUE_ID, Command.KEY_FREQUENCY); case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "**,imei:{%s},J", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,J", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "**,imei:{%s},K", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,K", Command.KEY_UNIQUE_ID); case Command.TYPE_ALARM_ARM: - return formatCommand(command, "**,imei:{%s},L", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,L", Command.KEY_UNIQUE_ID); case Command.TYPE_ALARM_DISARM: - return formatCommand(command, "**,imei:{%s},M", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,M", Command.KEY_UNIQUE_ID); case Command.TYPE_REQUEST_PHOTO: - return formatCommand(command, "**,imei:{%s},160", Command.KEY_UNIQUE_ID); + return formatCommand(command, "**,imei:%s,160", Command.KEY_UNIQUE_ID); default: return null; } diff --git a/src/main/java/org/traccar/protocol/GranitProtocolSmsEncoder.java b/src/main/java/org/traccar/protocol/GranitProtocolSmsEncoder.java index 7dd4b2d77..be0ab5130 100644 --- a/src/main/java/org/traccar/protocol/GranitProtocolSmsEncoder.java +++ b/src/main/java/org/traccar/protocol/GranitProtocolSmsEncoder.java @@ -32,7 +32,7 @@ public class GranitProtocolSmsEncoder extends StringProtocolEncoder { case Command.TYPE_REBOOT_DEVICE: return "BB+RESET"; case Command.TYPE_POSITION_PERIODIC: - return formatCommand(command, "BB+BBMD={%s}", Command.KEY_FREQUENCY); + return formatCommand(command, "BB+BBMD=%s", Command.KEY_FREQUENCY); default: return null; } diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java index e1ff0b6b6..b51da00d7 100644 --- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java @@ -209,7 +209,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { sendResponse(channel, false, MSG_X1_PHOTO_DATA, 0, content); } - private boolean decodeGps(Position position, ByteBuf buf, boolean hasLength, TimeZone timezone) { + public static boolean decodeGps(Position position, ByteBuf buf, boolean hasLength, TimeZone timezone) { DateBuilder dateBuilder = new DateBuilder(timezone) .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) @@ -548,6 +548,15 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.01); position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01); + long portInfo = buf.readUnsignedInt(); + + position.set(Position.KEY_INPUT, buf.readUnsignedByte()); + position.set(Position.KEY_OUTPUT, buf.readUnsignedByte()); + + for (int i = 1; i <= BitUtil.between(portInfo, 20, 24); i++) { + position.set(Position.PREFIX_ADC + i, buf.readUnsignedShort() * 0.01); + } + return position; } else if (type == MSG_X1_PHOTO_INFO) { @@ -1011,7 +1020,28 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { while (buf.readableBytes() > 6) { int moduleType = buf.readUnsignedShort(); int moduleLength = buf.readUnsignedShort(); + switch (moduleType) { + case 0x03: + position.set(Position.KEY_ICCID, ByteBufUtil.hexDump(buf.readSlice(10))); + break; + case 0x09: + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + break; + case 0x0a: + position.set(Position.KEY_SATELLITES_VISIBLE, buf.readUnsignedByte()); + break; + case 0x11: + CellTower cellTower = CellTower.from( + buf.readUnsignedShort(), + buf.readUnsignedShort(), + buf.readUnsignedShort(), + buf.readUnsignedMedium(), + buf.readUnsignedByte()); + if (cellTower.getCellId() > 0) { + position.setNetwork(new Network(cellTower)); + } + break; case 0x18: position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.01); break; @@ -1072,6 +1102,11 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { position.setLatitude(latitude); position.setLongitude(longitude); break; + case 0x34: + position.set(Position.KEY_EVENT, buf.readUnsignedByte()); + buf.readUnsignedIntLE(); // time + buf.skipBytes(buf.readUnsignedByte()); // content + break; default: buf.skipBytes(moduleLength); break; diff --git a/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java b/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java index f221cd25c..320fe991d 100644 --- a/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/H02ProtocolDecoder.java @@ -19,6 +19,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; +import org.traccar.Context; import org.traccar.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; @@ -185,7 +186,7 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { .number("(d+)(dd.d+),") // longitude .groupEnd() .expression("([EW]),") - .number("(d+.?d*),") // speed + .number(" *(d+.?d*),") // speed .number("(d+.?d*)?,") // course .number("(?:d+,)?") // battery .number("(?:(dd)(dd)(dd))?") // date (ddmmyy) @@ -287,9 +288,15 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { private void sendResponse(Channel channel, SocketAddress remoteAddress, String id, String type) { if (channel != null && id != null) { - DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + String response; + DateFormat dateFormat = new SimpleDateFormat(type.equals("R12") ? "HHmmss" : "yyyyMMddHHmmss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - String response = String.format("*HQ,%s,V4,%s,%s#", id, type, dateFormat.format(new Date())); + String time = dateFormat.format(new Date()); + if (type.equals("R12")) { + response = String.format("*HQ,%s,%s,%s#", id, type, time); + } else { + response = String.format("*HQ,%s,V4,%s,%s#", id, type, time); + } channel.writeAndFlush(new NetworkMessage(response, remoteAddress)); } } @@ -316,6 +323,8 @@ public class H02ProtocolDecoder extends BaseProtocolDecoder { if (parser.hasNext() && parser.next().equals("V1")) { sendResponse(channel, remoteAddress, id, "V1"); + } else if (Context.getConfig().getBoolean(getProtocolName() + ".ack")) { + sendResponse(channel, remoteAddress, id, "R12"); } DateBuilder dateBuilder = new DateBuilder(); diff --git a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java index fceefa73a..f425ec86f 100644 --- a/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java @@ -98,6 +98,9 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { if (BitUtil.check(value, 20)) { return Position.ALARM_GEOFENCE; } + if (BitUtil.check(value, 28)) { + return Position.ALARM_MOVEMENT; + } if (BitUtil.check(value, 29)) { return Position.ALARM_ACCIDENT; } @@ -160,22 +163,23 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_ALARM, decodeAlarm(buf.readUnsignedInt())); - int flags = buf.readInt(); + int status = buf.readInt(); - position.set(Position.KEY_IGNITION, BitUtil.check(flags, 0)); + position.set(Position.KEY_IGNITION, BitUtil.check(status, 0)); + position.set(Position.KEY_BLOCKED, BitUtil.check(status, 10)); - position.setValid(BitUtil.check(flags, 1)); + position.setValid(BitUtil.check(status, 1)); double lat = buf.readUnsignedInt() * 0.000001; double lon = buf.readUnsignedInt() * 0.000001; - if (BitUtil.check(flags, 2)) { + if (BitUtil.check(status, 2)) { position.setLatitude(-lat); } else { position.setLatitude(lat); } - if (BitUtil.check(flags, 3)) { + if (BitUtil.check(status, 3)) { position.setLongitude(-lon); } else { position.setLongitude(lon); @@ -211,6 +215,13 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { case 0x31: position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); break; + case 0x33: + String sentence = buf.readCharSequence(length, StandardCharsets.US_ASCII).toString(); + if (sentence.startsWith("*M00")) { + String lockStatus = sentence.substring(8, 8 + 7); + position.set(Position.KEY_BATTERY, Integer.parseInt(lockStatus.substring(2, 5)) * 0.01); + } + break; case 0x91: position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.1); position.set(Position.KEY_RPM, buf.readUnsignedShort()); @@ -231,6 +242,15 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { Position.KEY_VIN, buf.readCharSequence(length, StandardCharsets.US_ASCII).toString()); } break; + case 0xD0: + long userStatus = buf.readUnsignedInt(); + if (BitUtil.check(userStatus, 3)) { + position.set(Position.KEY_ALARM, Position.ALARM_VIBRATION); + } + break; + case 0xD3: + position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1); + break; default: break; } @@ -257,4 +277,3 @@ public class HuabaoProtocolDecoder extends BaseProtocolDecoder { } } - diff --git a/src/main/java/org/traccar/protocol/ItsProtocolDecoder.java b/src/main/java/org/traccar/protocol/ItsProtocolDecoder.java index d76d9c92e..e8d77f1a8 100644 --- a/src/main/java/org/traccar/protocol/ItsProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/ItsProtocolDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 - 2019 Anton Tananaev (anton@traccar.org) + * Copyright 2018 - 2020 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ public class ItsProtocolDecoder extends BaseProtocolDecoder { .text("$") .expression(",?[^,]+,") // event .groupBegin() - .expression("[^,]+,") // vendor + .expression("[^,]*,") // vendor .expression("[^,]+,") // firmware version .expression("(..),") // status .number("(d+),").optional() // event @@ -81,8 +81,8 @@ public class ItsProtocolDecoder extends BaseProtocolDecoder { .number("([01]{2}),") // outputs .groupBegin() .number("d+,") // index - .number("(d+.d+),") // adc1 - .number("(d+.d+),") // adc2 + .number("(d+.?d*),") // adc1 + .number("(d+.?d*),") // adc2 .groupEnd("?") .groupEnd("?") .or() @@ -195,22 +195,25 @@ public class ItsProtocolDecoder extends BaseProtocolDecoder { position.set("emergency", parser.nextInt() > 0); - String[] cells = parser.next().split(","); - int mcc = Integer.parseInt(cells[1]); - int mnc = Integer.parseInt(cells[2]); - int lac = Integer.parseInt(cells[3], 16); - int cid = Integer.parseInt(cells[4], 16); - Network network = new Network(CellTower.from(mcc, mnc, lac, cid, Integer.parseInt(cells[0]))); - if (!cells[5].startsWith("(")) { - for (int i = 0; i < 4; i++) { - lac = Integer.parseInt(cells[5 + 3 * i + 1], 16); - cid = Integer.parseInt(cells[5 + 3 * i + 2], 16); - if (lac > 0 && cid > 0) { - network.addCellTower(CellTower.from(mcc, mnc, lac, cid)); + String cellsString = parser.next(); + if (!cellsString.contains("x")) { + String[] cells = cellsString.split(","); + int mcc = Integer.parseInt(cells[1]); + int mnc = Integer.parseInt(cells[2]); + int lac = Integer.parseInt(cells[3], 16); + int cid = Integer.parseInt(cells[4], 16); + Network network = new Network(CellTower.from(mcc, mnc, lac, cid, Integer.parseInt(cells[0]))); + if (!cells[5].startsWith("(")) { + for (int i = 0; i < 4; i++) { + lac = Integer.parseInt(cells[5 + 3 * i + 1], 16); + cid = Integer.parseInt(cells[5 + 3 * i + 2], 16); + if (lac > 0 && cid > 0) { + network.addCellTower(CellTower.from(mcc, mnc, lac, cid)); + } } } + position.setNetwork(network); } - position.setNetwork(network); String input = parser.next(); if (input.charAt(input.length() - 1) == '2') { diff --git a/src/main/java/org/traccar/protocol/LaipacProtocolEncoder.java b/src/main/java/org/traccar/protocol/LaipacProtocolEncoder.java index 343ac9431..0c9f8ebb8 100644 --- a/src/main/java/org/traccar/protocol/LaipacProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/LaipacProtocolEncoder.java @@ -40,13 +40,13 @@ public class LaipacProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { case Command.TYPE_CUSTOM: - return formatCommand(command, "{%s}", + return formatCommand(command, "%s", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: - return formatCommand(command, "AVREQ,{%s},1", + return formatCommand(command, "AVREQ,%s,1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: - return formatCommand(command, "AVRESET,{%s},{%s}", + return formatCommand(command, "AVRESET,%s,%s", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: return null; diff --git a/src/main/java/org/traccar/protocol/MiniFinderProtocolEncoder.java b/src/main/java/org/traccar/protocol/MiniFinderProtocolEncoder.java index 36fb9fc2f..059f688f7 100644 --- a/src/main/java/org/traccar/protocol/MiniFinderProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/MiniFinderProtocolEncoder.java @@ -57,28 +57,28 @@ public class MiniFinderProtocolEncoder extends StringProtocolEncoder implements switch (command.getType()) { case Command.TYPE_SET_TIMEZONE: - return formatCommand(command, "{%s}L{%s}", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_TIMEZONE); + return formatCommand(command, "%sL%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_TIMEZONE); case Command.TYPE_VOICE_MONITORING: - return formatCommand(command, "{%s}P{%s}", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); + return formatCommand(command, "%sP%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); case Command.TYPE_ALARM_SPEED: - return formatCommand(command, "{%s}J1{%s}", Command.KEY_DEVICE_PASSWORD, Command.KEY_DATA); + return formatCommand(command, "%sJ1%s", Command.KEY_DEVICE_PASSWORD, Command.KEY_DATA); case Command.TYPE_ALARM_GEOFENCE: - return formatCommand(command, "{%s}R1{%s}", Command.KEY_DEVICE_PASSWORD, Command.KEY_RADIUS); + return formatCommand(command, "%sR1%s", Command.KEY_DEVICE_PASSWORD, Command.KEY_RADIUS); case Command.TYPE_ALARM_VIBRATION: - return formatCommand(command, "{%s}W1,{%s}", Command.KEY_DEVICE_PASSWORD, Command.KEY_DATA); + return formatCommand(command, "%sW1,%s", Command.KEY_DEVICE_PASSWORD, Command.KEY_DATA); case Command.TYPE_SET_AGPS: - return formatCommand(command, "{%s}AGPS{%s}", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); + return formatCommand(command, "%sAGPS%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); case Command.TYPE_ALARM_FALL: - return formatCommand(command, "{%s}F{%s}", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); + return formatCommand(command, "%sF%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); case Command.TYPE_MODE_POWER_SAVING: - return formatCommand(command, "{%s}SP{%s}", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); + return formatCommand(command, "%sSP%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); case Command.TYPE_MODE_DEEP_SLEEP: - return formatCommand(command, "{%s}DS{%s}", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); + return formatCommand(command, "%sDS%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_ENABLE); case Command.TYPE_SOS_NUMBER: - return formatCommand(command, "{%s}{%s}1,{%s}", this, + return formatCommand(command, "%s%s1,%s", this, Command.KEY_DEVICE_PASSWORD, Command.KEY_INDEX, Command.KEY_PHONE); case Command.TYPE_SET_INDICATOR: - return formatCommand(command, "{%s}LED{%s}", Command.KEY_DEVICE_PASSWORD, Command.KEY_DATA); + return formatCommand(command, "%sLED%s", Command.KEY_DEVICE_PASSWORD, Command.KEY_DATA); default: return null; } diff --git a/src/main/java/org/traccar/protocol/MotorProtocol.java b/src/main/java/org/traccar/protocol/MotorProtocol.java new file mode 100644 index 000000000..680687e15 --- /dev/null +++ b/src/main/java/org/traccar/protocol/MotorProtocol.java @@ -0,0 +1,37 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.handler.codec.LineBasedFrameDecoder; +import io.netty.handler.codec.string.StringDecoder; +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class MotorProtocol extends BaseProtocol { + + public MotorProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new LineBasedFrameDecoder(1024)); + pipeline.addLast(new StringDecoder()); + pipeline.addLast(new MotorProtocolDecoder(MotorProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/MotorProtocolDecoder.java b/src/main/java/org/traccar/protocol/MotorProtocolDecoder.java new file mode 100644 index 000000000..8ce4fe8b1 --- /dev/null +++ b/src/main/java/org/traccar/protocol/MotorProtocolDecoder.java @@ -0,0 +1,85 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.Protocol; +import org.traccar.helper.BcdUtil; +import org.traccar.helper.BitUtil; +import org.traccar.helper.DataConverter; +import org.traccar.helper.DateBuilder; +import org.traccar.model.Position; + +import java.net.SocketAddress; + +public class MotorProtocolDecoder extends BaseProtocolDecoder { + + public MotorProtocolDecoder(Protocol protocol) { + super(protocol); + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + String sentence = (String) msg; + ByteBuf buf = Unpooled.wrappedBuffer(DataConverter.parseHex(sentence)); + + String id = String.format("%08x", buf.readUnsignedIntLE()); + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); + if (deviceSession == null) { + return null; + } + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + buf.skipBytes(2); // divider + + position.set(Position.KEY_STATUS, buf.readUnsignedShortLE()); + + buf.skipBytes(2); // divider + buf.readUnsignedMediumLE(); // command + + int flags = buf.readUnsignedByte(); + position.setValid(BitUtil.check(flags, 7)); + if (BitUtil.check(flags, 0)) { + position.set(Position.KEY_ALARM, Position.ALARM_GENERAL); + } + + position.setLatitude(BcdUtil.readInteger(buf, 2) + BcdUtil.readInteger(buf, 6) * 0.0001 / 60); + position.setLongitude(BcdUtil.readInteger(buf, 4) + BcdUtil.readInteger(buf, 6) * 0.0001 / 60); + position.setSpeed(BcdUtil.readInteger(buf, 4) * 0.1); + position.setCourse(BcdUtil.readInteger(buf, 4) * 0.1); + + position.setTime(new DateBuilder() + .setYear(BcdUtil.readInteger(buf, 2)) + .setMonth(BcdUtil.readInteger(buf, 2)) + .setDay(BcdUtil.readInteger(buf, 2)) + .setHour(BcdUtil.readInteger(buf, 2)) + .setMinute(BcdUtil.readInteger(buf, 2)) + .setSecond(BcdUtil.readInteger(buf, 2)).getDate()); + + position.set(Position.KEY_RSSI, BcdUtil.readInteger(buf, 2)); + + return position; + } + +} diff --git a/src/main/java/org/traccar/protocol/OmnicommFrameDecoder.java b/src/main/java/org/traccar/protocol/OmnicommFrameDecoder.java new file mode 100644 index 000000000..1caf6ceb9 --- /dev/null +++ b/src/main/java/org/traccar/protocol/OmnicommFrameDecoder.java @@ -0,0 +1,58 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import org.traccar.BaseFrameDecoder; + +public class OmnicommFrameDecoder extends BaseFrameDecoder { + + @Override + protected Object decode( + ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception { + + if (buf.readableBytes() < 10) { + return null; + } + + int endIndex = buf.getUnsignedShortLE(2) + buf.readerIndex() + 6; + if (buf.writerIndex() < endIndex) { + return null; + } + + ByteBuf result = Unpooled.buffer(); + result.writeByte(buf.readUnsignedByte()); + while (buf.readerIndex() < endIndex) { + int b = buf.readUnsignedByte(); + if (b == 0xDB) { + int ext = buf.readUnsignedByte(); + if (ext == 0xDC) { + result.writeByte(0xC0); + } else if (ext == 0xDD) { + result.writeByte(0xDB); + } + endIndex += 1; + } else { + result.writeByte(b); + } + } + return result; + } + +} diff --git a/src/main/java/org/traccar/protocol/OmnicommProtocol.java b/src/main/java/org/traccar/protocol/OmnicommProtocol.java new file mode 100644 index 000000000..96660cb59 --- /dev/null +++ b/src/main/java/org/traccar/protocol/OmnicommProtocol.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class OmnicommProtocol extends BaseProtocol { + + public OmnicommProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new OmnicommFrameDecoder()); + pipeline.addLast(new OmnicommProtocolDecoder(OmnicommProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/OmnicommProtocolDecoder.java b/src/main/java/org/traccar/protocol/OmnicommProtocolDecoder.java new file mode 100644 index 000000000..cd8b74c9a --- /dev/null +++ b/src/main/java/org/traccar/protocol/OmnicommProtocolDecoder.java @@ -0,0 +1,142 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import com.google.protobuf.InvalidProtocolBufferException; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.NetworkMessage; +import org.traccar.Protocol; +import org.traccar.helper.Checksum; +import org.traccar.helper.UnitsConverter; +import org.traccar.model.Position; +import org.traccar.protobuf.OmnicommMessageOuterClass; + +import java.net.SocketAddress; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +public class OmnicommProtocolDecoder extends BaseProtocolDecoder { + + public OmnicommProtocolDecoder(Protocol protocol) { + super(protocol); + } + + public static final int MSG_IDENTIFICATION = 0x80; + public static final int MSG_ARCHIVE_INQUIRY = 0x85; + public static final int MSG_ARCHIVE_DATA = 0x86; + public static final int MSG_REMOVE_ARCHIVE_INQUIRY = 0x87; + + private OmnicommMessageOuterClass.OmnicommMessage parseProto( + ByteBuf buf, int length) throws InvalidProtocolBufferException { + + final byte[] array; + final int offset; + if (buf.hasArray()) { + array = buf.array(); + offset = buf.arrayOffset() + buf.readerIndex(); + } else { + array = ByteBufUtil.getBytes(buf, buf.readerIndex(), length, false); + offset = 0; + } + buf.skipBytes(length); + + return OmnicommMessageOuterClass.OmnicommMessage + .getDefaultInstance().getParserForType().parseFrom(array, offset, length); + } + + private void sendResponse(Channel channel, int type, long index) { + if (channel != null) { + ByteBuf response = Unpooled.buffer(); + response.writeByte(0xC0); + response.writeByte(type); + response.writeShortLE(4); + response.writeIntLE((int) index); + response.writeShortLE(Checksum.crc16(Checksum.CRC16_CCITT_FALSE, + response.nioBuffer(1, response.writerIndex() - 1))); + channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress())); + } + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ByteBuf buf = (ByteBuf) msg; + + buf.readUnsignedByte(); // prefix + int type = buf.readUnsignedByte(); + buf.readUnsignedShortLE(); // length + + if (type == MSG_IDENTIFICATION) { + + getDeviceSession(channel, remoteAddress, String.valueOf(buf.readUnsignedIntLE())); + sendResponse(channel, MSG_ARCHIVE_INQUIRY, 0); + + } else if (type == MSG_ARCHIVE_DATA) { + + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); + if (deviceSession == null) { + return null; + } + + long index = buf.readUnsignedIntLE(); + buf.readUnsignedIntLE(); // time + buf.readUnsignedByte(); // priority + + List<Position> positions = new LinkedList<>(); + + while (buf.readableBytes() > 2) { + + OmnicommMessageOuterClass.OmnicommMessage message = parseProto(buf, buf.readUnsignedShortLE()); + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + if (message.hasNAV()) { + OmnicommMessageOuterClass.OmnicommMessage.NAV nav = message.getNAV(); + position.setValid(true); + position.setTime(new Date((nav.getGPSTime() + 1230768000) * 1000L)); // from 2009-01-01 12:00 + position.setLatitude(nav.getLAT() * 0.0000001); + position.setLongitude(nav.getLON() * 0.0000001); + position.setSpeed(UnitsConverter.knotsFromKph(nav.getGPSVel() * 0.1)); + position.setCourse(nav.getGPSDir()); + position.setAltitude(nav.getGPSAlt() * 0.1); + position.set(Position.KEY_SATELLITES, nav.getGPSNSat()); + } + + if (position.getFixTime() != null) { + positions.add(position); + } + } + + if (positions.isEmpty()) { + sendResponse(channel, MSG_REMOVE_ARCHIVE_INQUIRY, index + 1); + return null; + } else { + return positions; + } + } + + return null; + } + +} diff --git a/src/main/java/org/traccar/protocol/OutsafeProtocol.java b/src/main/java/org/traccar/protocol/OutsafeProtocol.java new file mode 100644 index 000000000..c728a404d --- /dev/null +++ b/src/main/java/org/traccar/protocol/OutsafeProtocol.java @@ -0,0 +1,39 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpRequestDecoder; +import io.netty.handler.codec.http.HttpResponseEncoder; +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class OutsafeProtocol extends BaseProtocol { + + public OutsafeProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new HttpResponseEncoder()); + pipeline.addLast(new HttpRequestDecoder()); + pipeline.addLast(new HttpObjectAggregator(65535)); + pipeline.addLast(new OutsafeProtocolDecoder(OutsafeProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java b/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java new file mode 100644 index 000000000..5e95270e8 --- /dev/null +++ b/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java @@ -0,0 +1,69 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.channel.Channel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpResponseStatus; +import org.traccar.BaseHttpProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.Protocol; +import org.traccar.model.Position; + +import javax.json.Json; +import javax.json.JsonObject; +import java.io.StringReader; +import java.net.SocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +public class OutsafeProtocolDecoder extends BaseHttpProtocolDecoder { + + public OutsafeProtocolDecoder(Protocol protocol) { + super(protocol); + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + FullHttpRequest request = (FullHttpRequest) msg; + String content = request.content().toString(StandardCharsets.UTF_8); + JsonObject json = Json.createReader(new StringReader(content)).readObject(); + + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, json.getString("device")); + if (deviceSession == null) { + sendResponse(channel, HttpResponseStatus.BAD_REQUEST); + return null; + } + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + position.setTime(new Date()); + position.setValid(true); + position.setLatitude(json.getJsonNumber("latitude").doubleValue()); + position.setLongitude(json.getJsonNumber("longitude").doubleValue()); + position.setAltitude(json.getJsonNumber("altitude").doubleValue()); + position.setCourse(json.getJsonNumber("heading").intValue()); + + position.set(Position.KEY_RSSI, json.getJsonNumber("rssi").intValue()); + + sendResponse(channel, HttpResponseStatus.OK); + return position; + } + +} diff --git a/src/main/java/org/traccar/protocol/PacificTrackProtocolDecoder.java b/src/main/java/org/traccar/protocol/PacificTrackProtocolDecoder.java index 199348c54..15e08d7b1 100644 --- a/src/main/java/org/traccar/protocol/PacificTrackProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/PacificTrackProtocolDecoder.java @@ -73,18 +73,18 @@ public class PacificTrackProtocolDecoder extends BaseProtocolDecoder { position.setValid(BitUtil.check(buf.readUnsignedByte(), 4)); int date = buf.readUnsignedByte(); DateBuilder dateBuilder = new DateBuilder() - .setDate(2000 + BitUtil.from(date, 4), BitUtil.to(date, 4), buf.readUnsignedByte()) + .setDate(2010 + BitUtil.from(date, 4), BitUtil.to(date, 4), buf.readUnsignedByte()) .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); position.setTime(dateBuilder.getDate()); position.setLatitude(buf.readUnsignedInt() / 1000000.0 - 90.0); position.setLongitude(buf.readUnsignedInt() / 1000000.0 - 180.0); int speedAndCourse = buf.readUnsignedMedium(); position.setCourse(BitUtil.from(speedAndCourse, 12)); - position.setSpeed(UnitsConverter.knotsFromKph(BitUtil.to(speedAndCourse, 12))); + position.setSpeed(UnitsConverter.knotsFromKph(BitUtil.to(speedAndCourse, 12) * 0.1)); position.set(Position.KEY_INDEX, buf.readUnsignedShort()); break; case 0x100: - String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1); + String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(0, 15); deviceSession = getDeviceSession(channel, remoteAddress, imei); break; default: diff --git a/src/main/java/org/traccar/protocol/PluginProtocolDecoder.java b/src/main/java/org/traccar/protocol/PluginProtocolDecoder.java index 106889ee0..949c994ee 100644 --- a/src/main/java/org/traccar/protocol/PluginProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/PluginProtocolDecoder.java @@ -19,6 +19,7 @@ import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.Protocol; +import org.traccar.helper.BitUtil; import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.helper.UnitsConverter; @@ -40,17 +41,30 @@ public class PluginProtocolDecoder extends BaseProtocolDecoder { .number("(dd)(dd)(dd),") // time (hhmmss) .number("(-?d+.d+),") // longitude .number("(-?d+.d+),") // latitude - .number("(d+),") // speed + .number("(d+.?d*),") // speed .number("(d+),") // course .number("(-?d+),") // altitude .number("(-?d+),") // satellites .number("d+,") // type - .number("(d+),") // odometer + .number("(d+.?d*),") // odometer .number("(d+),") // status - .expression("[^,]*,") + .number("(d+.?d*),") // fuel .expression("[^,]*,") .text("0") .groupBegin() + .number(",(-?d+.?d*)") // temperature 1 + .number(",(-?d+.?d*)") // temperature 2 + .number(",d+") // oil level + .number(",(d+)") // rpm + .number(",(d+)") // obd speed + .number(",d+") // people up + .number(",d+") // people down + .number(",d+") // obd status + .number(",d+") // fuel intake air temperature + .number(",(d+)") // throttle + .number(",(d+)") // battery + .groupEnd("?") + .groupBegin() .text(",+,") .number("(d+),") // event .groupEnd("?") @@ -74,18 +88,50 @@ public class PluginProtocolDecoder extends BaseProtocolDecoder { Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); - position.setValid(true); position.setTime(parser.nextDateTime()); position.setLongitude(parser.nextDouble()); position.setLatitude(parser.nextDouble()); - position.setSpeed(UnitsConverter.knotsFromKph(parser.nextInt())); + position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble())); position.setCourse(parser.nextInt()); position.setAltitude(parser.nextInt()); position.set(Position.KEY_SATELLITES, parser.nextInt()); - position.set(Position.KEY_ODOMETER, parser.nextInt()); - position.set(Position.KEY_STATUS, parser.nextInt()); - position.set(Position.KEY_EVENT, parser.nextInt()); + position.set(Position.KEY_ODOMETER, (long) (parser.nextDouble() * 1000)); + + int status = parser.nextInt(); + position.setValid(BitUtil.check(status, 0)); + position.set(Position.KEY_IGNITION, BitUtil.check(status, 1)); + for (int i = 0; i < 4; i++) { + position.set(Position.PREFIX_IN + (i + 1), BitUtil.check(status, 20 + i)); + } + position.set(Position.KEY_STATUS, status); + + position.set(Position.KEY_FUEL_LEVEL, parser.nextDouble()); + + if (parser.hasNext(6)) { + position.set(Position.PREFIX_TEMP + 1, parser.nextDouble()); + position.set(Position.PREFIX_TEMP + 2, parser.nextDouble()); + position.set(Position.KEY_RPM, parser.nextInt()); + position.set(Position.KEY_OBD_SPEED, parser.nextInt()); + position.set(Position.KEY_THROTTLE, parser.nextInt() * 0.1); + position.set(Position.KEY_POWER, parser.nextInt() * 0.1); + } + + if (parser.hasNext()) { + int event = parser.nextInt(); + switch (event) { + case 11317: + position.set(Position.KEY_ALARM, Position.ALARM_ACCELERATION); + break; + case 11319: + position.set(Position.KEY_ALARM, Position.ALARM_BRAKING); + break; + default: + break; + + } + position.set(Position.KEY_EVENT, event); + } return position; } diff --git a/src/main/java/org/traccar/protocol/Pt215FrameDecoder.java b/src/main/java/org/traccar/protocol/PstFrameDecoder.java index 0b3bae914..dbafd1476 100644 --- a/src/main/java/org/traccar/protocol/Pt215FrameDecoder.java +++ b/src/main/java/org/traccar/protocol/PstFrameDecoder.java @@ -16,40 +16,36 @@ package org.traccar.protocol; import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import org.traccar.BaseFrameDecoder; -public class Pt215FrameDecoder extends BaseFrameDecoder { - - private ByteBuf decodeFrame(ByteBuf buf, int length) { - if (buf.readableBytes() >= length) { - return buf.readRetainedSlice(length); - } - return null; - } +public class PstFrameDecoder extends BaseFrameDecoder { @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception { - if (buf.readableBytes() < 5) { - return null; + while (buf.isReadable() && buf.getByte(buf.readerIndex()) == 0x28) { + buf.skipBytes(1); } - int type = buf.getUnsignedByte(buf.readerIndex() + 2 + 1); - switch (type) { - case Pt215ProtocolDecoder.MSG_LOGIN: - return decodeFrame(buf, 15); - case Pt215ProtocolDecoder.MSG_GPS_REALTIME: - case Pt215ProtocolDecoder.MSG_GPS_OFFLINE: - return decodeFrame(buf, 27); - case Pt215ProtocolDecoder.MSG_STATUS: - return decodeFrame(buf, 11); - default: - return null; - + int endIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) 0x29); + if (endIndex > 0) { + ByteBuf result = Unpooled.buffer(endIndex - buf.readerIndex()); + while (buf.readerIndex() < endIndex) { + int b = buf.readUnsignedByte(); + if (b == 0x27) { + b = buf.readUnsignedByte() ^ 0x40; + } + result.writeByte(b); + } + buf.skipBytes(1); + return result; } + + return null; } } diff --git a/src/main/java/org/traccar/protocol/PstProtocol.java b/src/main/java/org/traccar/protocol/PstProtocol.java new file mode 100644 index 000000000..0ed9affd8 --- /dev/null +++ b/src/main/java/org/traccar/protocol/PstProtocol.java @@ -0,0 +1,40 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class PstProtocol extends BaseProtocol { + + public PstProtocol() { + addServer(new TrackerServer(true, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new PstProtocolDecoder(PstProtocol.this)); + } + }); + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new PstFrameDecoder()); + pipeline.addLast(new PstProtocolDecoder(PstProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/PstProtocolDecoder.java b/src/main/java/org/traccar/protocol/PstProtocolDecoder.java new file mode 100644 index 000000000..23e2afbbd --- /dev/null +++ b/src/main/java/org/traccar/protocol/PstProtocolDecoder.java @@ -0,0 +1,116 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.Protocol; +import org.traccar.helper.BitUtil; +import org.traccar.helper.DateBuilder; +import org.traccar.model.Position; + +import java.net.SocketAddress; +import java.util.Date; + +public class PstProtocolDecoder extends BaseProtocolDecoder { + + public PstProtocolDecoder(Protocol protocol) { + super(protocol); + } + + public static final int MSG_STATUS = 0x05; + + private Date readDate(ByteBuf buf) { + long value = buf.readUnsignedInt(); + return new DateBuilder() + .setYear((int) BitUtil.between(value, 26, 32)) + .setMonth((int) BitUtil.between(value, 22, 26)) + .setDay((int) BitUtil.between(value, 17, 22)) + .setHour((int) BitUtil.between(value, 12, 17)) + .setMinute((int) BitUtil.between(value, 6, 12)) + .setSecond((int) BitUtil.between(value, 0, 6)).getDate(); + } + + private double readCoordinate(ByteBuf buf) { + long value = buf.readUnsignedInt(); + int sign = BitUtil.check(value, 31) ? -1 : 1; + value = BitUtil.to(value, 31); + return sign * (BitUtil.from(value, 16) + BitUtil.to(value, 16) * 0.00001) / 60; + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ByteBuf buf = (ByteBuf) msg; + + String id = String.valueOf(buf.readUnsignedInt()); + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id); + if (deviceSession == null) { + return null; + } + + buf.readUnsignedByte(); // version + buf.readUnsignedInt(); // index + + int type = buf.readUnsignedByte(); + + if (type == MSG_STATUS) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + position.setDeviceTime(readDate(buf)); + + buf.readUnsignedByte(); + + int count = buf.readUnsignedByte(); + for (int i = 0; i < count; i++) { + + int tag = buf.readUnsignedByte(); + int length = buf.readUnsignedByte(); + + switch (tag) { + case 0x0D: + int battery = buf.readUnsignedByte(); + if (battery <= 20) { + position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte() * 5); + } + break; + case 0x10: + position.setFixTime(readDate(buf)); + position.setLatitude(readCoordinate(buf)); + position.setLongitude(readCoordinate(buf)); + position.setSpeed(buf.readUnsignedByte()); + position.setCourse(buf.readUnsignedByte() * 2); + position.setAltitude(buf.readShort()); + buf.readUnsignedInt(); // gps condition + break; + default: + buf.skipBytes(length); + break; + } + } + + return position.getFixTime() != null ? position : null; + } + + return null; + } + +} diff --git a/src/main/java/org/traccar/protocol/Pt215Protocol.java b/src/main/java/org/traccar/protocol/Pt215Protocol.java index 31ddc2c7a..09bd9b121 100644 --- a/src/main/java/org/traccar/protocol/Pt215Protocol.java +++ b/src/main/java/org/traccar/protocol/Pt215Protocol.java @@ -15,6 +15,7 @@ */ package org.traccar.protocol; +import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import org.traccar.BaseProtocol; import org.traccar.PipelineBuilder; import org.traccar.TrackerServer; @@ -25,7 +26,7 @@ public class Pt215Protocol extends BaseProtocol { addServer(new TrackerServer(false, getName()) { @Override protected void addProtocolHandlers(PipelineBuilder pipeline) { - pipeline.addLast(new Pt215FrameDecoder()); + pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 2, 1, -1, 0)); pipeline.addLast(new Pt215ProtocolDecoder(Pt215Protocol.this)); } }); diff --git a/src/main/java/org/traccar/protocol/Pt502ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Pt502ProtocolEncoder.java index ba08b16ae..364ecae86 100644 --- a/src/main/java/org/traccar/protocol/Pt502ProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/Pt502ProtocolEncoder.java @@ -46,13 +46,13 @@ public class Pt502ProtocolEncoder extends StringProtocolEncoder implements Strin switch (command.getType()) { case Command.TYPE_CUSTOM: - return formatCommand(command, "{%s}\r\n", Command.KEY_DATA); + return formatCommand(command, "%s\r\n", Command.KEY_DATA); case Command.TYPE_OUTPUT_CONTROL: - return formatCommand(command, "#OPC{%s},{%s}\r\n", Command.KEY_INDEX, Command.KEY_DATA); + return formatCommand(command, "#OPC%s,%s\r\n", Command.KEY_INDEX, Command.KEY_DATA); case Command.TYPE_SET_TIMEZONE: - return formatCommand(command, "#TMZ{%s}\r\n", Command.KEY_TIMEZONE); + return formatCommand(command, "#TMZ%s\r\n", Command.KEY_TIMEZONE); case Command.TYPE_ALARM_SPEED: - return formatCommand(command, "#SPD{%s}\r\n", Command.KEY_DATA); + return formatCommand(command, "#SPD%s\r\n", Command.KEY_DATA); case Command.TYPE_REQUEST_PHOTO: return formatCommand(command, "#PHO\r\n"); default: diff --git a/src/main/java/org/traccar/protocol/RstProtocolDecoder.java b/src/main/java/org/traccar/protocol/RstProtocolDecoder.java index 071200d6d..f9c8d9df8 100644 --- a/src/main/java/org/traccar/protocol/RstProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/RstProtocolDecoder.java @@ -20,6 +20,7 @@ import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; +import org.traccar.helper.BitUtil; import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.helper.UnitsConverter; @@ -84,10 +85,10 @@ public class RstProtocolDecoder extends BaseProtocolDecoder { String firmware = parser.next(); String serial = parser.next(); int index = parser.nextInt(); - int type = parser.nextInt(); + parser.nextInt(); // type if (channel != null && archive.equals("A")) { - String response = "RST;A;" + model + ";" + firmware + ";" + serial + ";" + index + ";" + type + ";FIM;"; + String response = "RST;A;" + model + ";" + firmware + ";" + serial + ";" + index + ";6;FIM;"; channel.writeAndFlush(new NetworkMessage(response, remoteAddress)); } @@ -120,7 +121,10 @@ public class RstProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_ODOMETER, parser.nextInt()); position.set(Position.KEY_RSSI, parser.nextInt()); position.set(Position.PREFIX_TEMP + 1, (int) parser.nextHexInt().byteValue()); - position.set(Position.KEY_STATUS, parser.nextHexInt() << 8 + parser.nextHexInt()); + + int status = parser.nextHexInt() << 8 + parser.nextHexInt(); + position.set(Position.KEY_IGNITION, BitUtil.check(status, 7)); + position.set(Position.KEY_STATUS, status); return position; } diff --git a/src/main/java/org/traccar/protocol/RuptelaProtocolDecoder.java b/src/main/java/org/traccar/protocol/RuptelaProtocolDecoder.java index 2d476427d..227a9ac91 100644 --- a/src/main/java/org/traccar/protocol/RuptelaProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/RuptelaProtocolDecoder.java @@ -19,6 +19,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; +import org.traccar.Context; import org.traccar.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; @@ -34,6 +35,8 @@ import java.util.List; public class RuptelaProtocolDecoder extends BaseProtocolDecoder { + private ByteBuf photo; + public RuptelaProtocolDecoder(Protocol protocol) { super(protocol); } @@ -247,6 +250,43 @@ public class RuptelaProtocolDecoder extends BaseProtocolDecoder { return positions; + } else if (type == MSG_FILES) { + + int subtype = buf.readUnsignedByte(); + int source = buf.readUnsignedByte(); + + if (subtype == 2) { + ByteBuf filename = buf.readSlice(8); + int total = buf.readUnsignedShort(); + int current = buf.readUnsignedShort(); + if (photo == null) { + photo = Unpooled.buffer(); + } + photo.writeBytes(buf.readSlice(buf.readableBytes() - 2)); + if (current < total - 1) { + ByteBuf content = Unpooled.buffer(); + content.writeByte(subtype); + content.writeByte(source); + content.writeBytes(filename); + content.writeShort(current + 1); + ByteBuf response = RuptelaProtocolEncoder.encodeContent(type, content); + content.release(); + if (channel != null) { + channel.writeAndFlush(new NetworkMessage(response, remoteAddress)); + } + } else { + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + getLastLocation(position, null); + position.set(Position.KEY_IMAGE, Context.getMediaManager().writeFile(imei, photo, "jpg")); + photo.release(); + photo = null; + return position; + } + } + + return null; + } else { return decodeCommandResponse(deviceSession, type, buf); diff --git a/src/main/java/org/traccar/protocol/RuptelaProtocolEncoder.java b/src/main/java/org/traccar/protocol/RuptelaProtocolEncoder.java index 51967403d..fb0dcf690 100644 --- a/src/main/java/org/traccar/protocol/RuptelaProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/RuptelaProtocolEncoder.java @@ -19,6 +19,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.traccar.BaseProtocolEncoder; import org.traccar.helper.Checksum; +import org.traccar.helper.DataConverter; import org.traccar.model.Command; import org.traccar.Protocol; @@ -30,7 +31,7 @@ public class RuptelaProtocolEncoder extends BaseProtocolEncoder { super(protocol); } - private ByteBuf encodeContent(int type, ByteBuf content) { + public static ByteBuf encodeContent(int type, ByteBuf content) { ByteBuf buf = Unpooled.buffer(); @@ -49,8 +50,14 @@ public class RuptelaProtocolEncoder extends BaseProtocolEncoder { switch (command.getType()) { case Command.TYPE_CUSTOM: - content.writeBytes(command.getString(Command.KEY_DATA).getBytes(StandardCharsets.US_ASCII)); - return encodeContent(RuptelaProtocolDecoder.MSG_SMS_VIA_GPRS, content); + String data = command.getString(Command.KEY_DATA); + if (data.matches("(\\p{XDigit}{2})+")) { + content.writeBytes(DataConverter.parseHex(data)); + return content; + } else { + content.writeBytes(data.getBytes(StandardCharsets.US_ASCII)); + return encodeContent(RuptelaProtocolDecoder.MSG_SMS_VIA_GPRS, content); + } case Command.TYPE_REQUEST_PHOTO: content.writeByte(1); // sub-command content.writeByte(0); // source diff --git a/src/main/java/org/traccar/protocol/S168Protocol.java b/src/main/java/org/traccar/protocol/S168Protocol.java new file mode 100644 index 000000000..e78664c40 --- /dev/null +++ b/src/main/java/org/traccar/protocol/S168Protocol.java @@ -0,0 +1,39 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.handler.codec.string.StringDecoder; +import io.netty.handler.codec.string.StringEncoder; +import org.traccar.BaseProtocol; +import org.traccar.CharacterDelimiterFrameDecoder; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class S168Protocol extends BaseProtocol { + + public S168Protocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new CharacterDelimiterFrameDecoder(1024, '$')); + pipeline.addLast(new StringEncoder()); + pipeline.addLast(new StringDecoder()); + pipeline.addLast(new S168ProtocolDecoder(S168Protocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java b/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java new file mode 100644 index 000000000..71aff1a65 --- /dev/null +++ b/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java @@ -0,0 +1,81 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.Protocol; +import org.traccar.helper.UnitsConverter; +import org.traccar.model.Position; + +import java.net.SocketAddress; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.TimeZone; + +public class S168ProtocolDecoder extends BaseProtocolDecoder { + + public S168ProtocolDecoder(Protocol protocol) { + super(protocol); + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + String sentence = (String) msg; + String[] values = sentence.split("#"); + + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, values[1]); + if (deviceSession == null) { + return null; + } + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + String content = values[4]; + String[] fragments = content.split(";"); + for (String fragment : fragments) { + + int dataIndex = fragment.indexOf(':'); + String type = fragment.substring(0, dataIndex); + values = fragment.substring(dataIndex + 1).split(","); + int index = 0; + + switch (type) { + case "GDATA": + position.setValid(values[index++].equals("A")); + position.set(Position.KEY_SATELLITES, Integer.parseInt(values[index++])); + DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + position.setTime(dateFormat.parse(values[index++])); + position.setLatitude(Double.parseDouble(values[index++])); + position.setLongitude(Double.parseDouble(values[index++])); + position.setSpeed(UnitsConverter.knotsFromKph(Double.parseDouble(values[index++]))); + position.setCourse(Integer.parseInt(values[index++])); + position.setAltitude(Integer.parseInt(values[index++])); + break; + default: + break; + } + } + + return position.getAttributes().containsKey(Position.KEY_SATELLITES) ? position : null; + } + +} diff --git a/src/main/java/org/traccar/protocol/SigfoxProtocolDecoder.java b/src/main/java/org/traccar/protocol/SigfoxProtocolDecoder.java index f9c79fb5b..304f61836 100644 --- a/src/main/java/org/traccar/protocol/SigfoxProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/SigfoxProtocolDecoder.java @@ -24,6 +24,7 @@ import io.netty.handler.codec.http.HttpResponseStatus; import org.traccar.BaseHttpProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.Protocol; +import org.traccar.helper.BitUtil; import org.traccar.helper.DataConverter; import org.traccar.helper.UnitsConverter; import org.traccar.model.Network; @@ -31,7 +32,10 @@ import org.traccar.model.Position; import org.traccar.model.WifiAccessPoint; import javax.json.Json; +import javax.json.JsonNumber; import javax.json.JsonObject; +import javax.json.JsonString; +import javax.json.JsonValue; import java.io.StringReader; import java.net.SocketAddress; import java.net.URLDecoder; @@ -44,6 +48,30 @@ public class SigfoxProtocolDecoder extends BaseHttpProtocolDecoder { super(protocol); } + private int getJsonInt(JsonObject json, String key) { + JsonValue value = json.get(key); + if (value != null) { + if (value.getValueType() == JsonValue.ValueType.NUMBER) { + return ((JsonNumber) value).intValue(); + } else if (value.getValueType() == JsonValue.ValueType.STRING) { + return Integer.parseInt(((JsonString) value).getString()); + } + } + return 0; + } + + private double getJsonDouble(JsonObject json, String key) { + JsonValue value = json.get(key); + if (value != null) { + if (value.getValueType() == JsonValue.ValueType.NUMBER) { + return ((JsonNumber) value).doubleValue(); + } else if (value.getValueType() == JsonValue.ValueType.STRING) { + return Double.parseDouble(((JsonString) value).getString()); + } + } + return 0; + } + @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { @@ -65,18 +93,24 @@ public class SigfoxProtocolDecoder extends BaseHttpProtocolDecoder { position.setDeviceId(deviceSession.getDeviceId()); if (json.containsKey("time")) { - position.setTime(new Date(json.getInt("time") * 1000L)); + position.setTime(new Date(getJsonInt(json, "time") * 1000L)); } else { position.setTime(new Date()); } - if (json.containsKey("location")) { + if (json.containsKey("location") + || json.containsKey("lat") && json.containsKey("lng") && !json.containsKey("data")) { - JsonObject location = json.getJsonObject("location"); + JsonObject location; + if (json.containsKey("location")) { + location = json.getJsonObject("location"); + } else { + location = json; + } position.setValid(true); - position.setLatitude(location.getJsonNumber("lat").doubleValue()); - position.setLongitude(location.getJsonNumber("lng").doubleValue()); + position.setLatitude(getJsonDouble(location, "lat")); + position.setLongitude(getJsonDouble(location, "lng")); } else { @@ -84,7 +118,25 @@ public class SigfoxProtocolDecoder extends BaseHttpProtocolDecoder { ByteBuf buf = Unpooled.wrappedBuffer(DataConverter.parseHex(data)); try { int event = buf.readUnsignedByte(); - if (event >> 4 == 0) { + if (event == 0x0f || event == 0x1f) { + + position.setValid(event >> 4 > 0); + + long value; + value = buf.readUnsignedInt(); + position.setLatitude(BitUtil.to(value, 31) * 0.000001); + if (BitUtil.check(value, 31)) { + position.setLatitude(-position.getLatitude()); + } + value = buf.readUnsignedInt(); + position.setLongitude(BitUtil.to(value, 31) * 0.000001); + if (BitUtil.check(value, 31)) { + position.setLongitude(-position.getLongitude()); + } + + position.set(Position.KEY_BATTERY, (int) buf.readUnsignedByte()); + + } else if (event >> 4 == 0) { position.setValid(true); position.setLatitude(buf.readIntLE() * 0.0000001); @@ -154,10 +206,10 @@ public class SigfoxProtocolDecoder extends BaseHttpProtocolDecoder { } if (json.containsKey("rssi")) { - position.set(Position.KEY_RSSI, json.getJsonNumber("rssi").doubleValue()); + position.set(Position.KEY_RSSI, getJsonDouble(json, "rssi")); } if (json.containsKey("seqNumber")) { - position.set(Position.KEY_INDEX, json.getInt("seqNumber")); + position.set(Position.KEY_INDEX, getJsonInt(json, "seqNumber")); } sendResponse(channel, HttpResponseStatus.OK); diff --git a/src/main/java/org/traccar/protocol/SolarPoweredProtocol.java b/src/main/java/org/traccar/protocol/SolarPoweredProtocol.java new file mode 100644 index 000000000..53a948cdc --- /dev/null +++ b/src/main/java/org/traccar/protocol/SolarPoweredProtocol.java @@ -0,0 +1,34 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class SolarPoweredProtocol extends BaseProtocol { + + public SolarPoweredProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new HuabaoFrameDecoder()); + pipeline.addLast(new SolarPoweredProtocolDecoder(SolarPoweredProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/SolarPoweredProtocolDecoder.java b/src/main/java/org/traccar/protocol/SolarPoweredProtocolDecoder.java new file mode 100644 index 000000000..eae37386a --- /dev/null +++ b/src/main/java/org/traccar/protocol/SolarPoweredProtocolDecoder.java @@ -0,0 +1,97 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.Protocol; +import org.traccar.helper.BitUtil; +import org.traccar.helper.DateBuilder; +import org.traccar.helper.UnitsConverter; +import org.traccar.model.Position; + +import java.net.SocketAddress; + +public class SolarPoweredProtocolDecoder extends BaseProtocolDecoder { + + public SolarPoweredProtocolDecoder(Protocol protocol) { + super(protocol); + } + + public static final int MSG_ACTIVE_REPORTING = 0x11; + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ByteBuf buf = (ByteBuf) msg; + + buf.readUnsignedByte(); // start marker + + String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(0, 15); + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei); + if (deviceSession == null) { + return null; + } + + int type = buf.readUnsignedByte(); + buf.readUnsignedShort(); // attributes + + if (type == MSG_ACTIVE_REPORTING) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + while (buf.readableBytes() > 2) { + int tag = buf.readUnsignedByte(); + int length = buf.readUnsignedByte(); + switch (tag) { + case 0x81: + int status = buf.readUnsignedByte(); + DateBuilder dateBuilder = new DateBuilder() + .setDate(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()) + .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); + position.setTime(dateBuilder.getDate()); + position.setLatitude(buf.readUnsignedInt() * 0.000001); + if (BitUtil.check(status, 3)) { + position.setLatitude(-position.getLatitude()); + } + position.setLongitude(buf.readUnsignedInt() * 0.000001); + if (BitUtil.check(status, 2)) { + position.setLongitude(-position.getLongitude()); + } + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte())); + position.set(Position.KEY_DEVICE_TEMP, (int) buf.readByte()); + position.set(Position.KEY_BATTERY, buf.readUnsignedByte() * 0.02); + position.setCourse(buf.readUnsignedByte()); + break; + default: + buf.skipBytes(length); + break; + } + } + + return position; + + } + + return null; + } + +} diff --git a/src/main/java/org/traccar/protocol/StarcomProtocolDecoder.java b/src/main/java/org/traccar/protocol/StarcomProtocolDecoder.java index 90151d061..5ffddb318 100644 --- a/src/main/java/org/traccar/protocol/StarcomProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/StarcomProtocolDecoder.java @@ -18,6 +18,7 @@ package org.traccar.protocol; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; +import org.traccar.helper.UnitsConverter; import org.traccar.model.Position; import java.net.SocketAddress; @@ -66,7 +67,7 @@ public class StarcomProtocolDecoder extends BaseProtocolDecoder { position.setAltitude(Double.parseDouble(value)); break; case "velocity": - position.setSpeed(Integer.parseInt(value)); + position.setSpeed(UnitsConverter.knotsFromKph(Integer.parseInt(value))); break; case "heading": position.setCourse(Integer.parseInt(value)); @@ -74,8 +75,8 @@ public class StarcomProtocolDecoder extends BaseProtocolDecoder { case "eventid": position.set(Position.KEY_EVENT, Integer.parseInt(value)); break; - case "odometer": - position.set(Position.KEY_ODOMETER, Long.parseLong(value)); + case "mileage": + position.set(Position.KEY_ODOMETER, (long) (Double.parseDouble(value) * 1000)); break; case "satellites": position.set(Position.KEY_SATELLITES, Integer.parseInt(value)); diff --git a/src/main/java/org/traccar/protocol/SuntechFrameDecoder.java b/src/main/java/org/traccar/protocol/SuntechFrameDecoder.java index 7b8337468..8748ecc61 100644 --- a/src/main/java/org/traccar/protocol/SuntechFrameDecoder.java +++ b/src/main/java/org/traccar/protocol/SuntechFrameDecoder.java @@ -32,7 +32,7 @@ public class SuntechFrameDecoder extends BaseFrameDecoder { protected Object decode( ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception { - if (buf.getByte(buf.readerIndex()) == (byte) 0x81) { + if (buf.getByte(buf.readerIndex() + 1) == 0) { int length = 1 + 2 + buf.getShort(buf.readerIndex() + 1); if (buf.readableBytes() >= length) { diff --git a/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java b/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java index 04113c51e..8d58803c9 100644 --- a/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/SuntechProtocolDecoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 - 2019 Anton Tananaev (anton@traccar.org) + * Copyright 2013 - 2020 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,6 +38,8 @@ import java.util.TimeZone; public class SuntechProtocolDecoder extends BaseProtocolDecoder { + private String prefix; + private int protocolType; private boolean hbm; private boolean includeAdc; @@ -48,6 +50,10 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { super(protocol); } + public String getPrefix() { + return prefix; + } + public void setProtocolType(int protocolType) { this.protocolType = protocolType; } @@ -236,6 +242,10 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_INDEX, Integer.parseInt(values[index++])); position.set(Position.KEY_STATUS, Integer.parseInt(values[index++])); + if (values[index].length() == 3) { + index += 1; // collaborative network + } + DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); position.setTime(dateFormat.parse(values[index++] + values[index++])); @@ -272,7 +282,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { position.setDeviceId(deviceSession.getDeviceId()); position.set(Position.KEY_TYPE, type); - if (protocol.equals("ST300") || protocol.equals("ST500") || protocol.equals("ST600")) { + if (protocol.startsWith("ST3") || protocol.equals("ST500") || protocol.equals("ST600")) { index += 1; // model } @@ -304,7 +314,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { position.set(Position.KEY_POWER, Double.parseDouble(values[index++])); String io = values[index++]; - if (io.length() == 6) { + if (io.length() >= 6) { position.set(Position.KEY_IGNITION, io.charAt(0) == '1'); position.set(Position.PREFIX_IN + 1, io.charAt(1) == '1'); position.set(Position.PREFIX_IN + 2, io.charAt(2) == '1'); @@ -508,7 +518,7 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { private Position decodeBinary( Channel channel, SocketAddress remoteAddress, ByteBuf buf) { - buf.readUnsignedByte(); // header + int type = buf.readUnsignedByte(); buf.readUnsignedShort(); // length DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ByteBufUtil.hexDump(buf.readSlice(5))); @@ -593,6 +603,23 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { position.setValid(buf.readUnsignedByte() > 0); } + if (BitUtil.check(mask, 17)) { + int input = buf.readUnsignedByte(); + position.set(Position.KEY_IGNITION, BitUtil.check(input, 0)); + position.set(Position.KEY_INPUT, input); + } + + if (BitUtil.check(mask, 18)) { + position.set(Position.KEY_OUTPUT, buf.readUnsignedByte()); + } + + if (BitUtil.check(mask, 19)) { + int value = buf.readUnsignedByte(); + if (type == 0x82) { + position.set(Position.KEY_ALARM, decodeAlert(value)); + } + } + return position; } @@ -602,22 +629,23 @@ public class SuntechProtocolDecoder extends BaseProtocolDecoder { ByteBuf buf = (ByteBuf) msg; - if (buf.getByte(buf.readerIndex()) == (byte) 0x81) { + if (buf.getByte(buf.readerIndex() + 1) == 0) { return decodeBinary(channel, remoteAddress, buf); } else { String[] values = buf.toString(StandardCharsets.US_ASCII).split(";"); + prefix = values[0]; - if (values[0].length() < 5) { + if (prefix.length() < 5) { return decodeUniversal(channel, remoteAddress, values); - } else if (values[0].startsWith("ST9")) { + } else if (prefix.startsWith("ST9")) { return decode9(channel, remoteAddress, values); - } else if (values[0].startsWith("ST4")) { + } else if (prefix.startsWith("ST4")) { return decode4(channel, remoteAddress, values); } else { - return decode2356(channel, remoteAddress, values[0].substring(0, 5), values); + return decode2356(channel, remoteAddress, prefix.substring(0, 5), values); } } } diff --git a/src/main/java/org/traccar/protocol/SuntechProtocolEncoder.java b/src/main/java/org/traccar/protocol/SuntechProtocolEncoder.java index 6dae42ad5..3b4995110 100644 --- a/src/main/java/org/traccar/protocol/SuntechProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/SuntechProtocolEncoder.java @@ -15,6 +15,8 @@ */ package org.traccar.protocol; +import io.netty.channel.Channel; +import org.traccar.BasePipelineFactory; import org.traccar.StringProtocolEncoder; import org.traccar.model.Command; import org.traccar.Protocol; @@ -25,32 +27,49 @@ public class SuntechProtocolEncoder extends StringProtocolEncoder { super(protocol); } + private String getPrefix(Channel channel) { + String prefix = "SA200CMD"; + if (channel != null) { + SuntechProtocolDecoder protocolDecoder = + BasePipelineFactory.getHandler(channel.pipeline(), SuntechProtocolDecoder.class); + if (protocolDecoder != null) { + String decoderPrefix = protocolDecoder.getPrefix(); + if (decoderPrefix != null && decoderPrefix.length() > 5) { + prefix = decoderPrefix.substring(0, decoderPrefix.length() - 3) + "CMD"; + } + } + } + return prefix; + } + @Override - protected Object encodeCommand(Command command) { + protected Object encodeCommand(Channel channel, Command command) { + + String prefix = getPrefix(channel); switch (command.getType()) { case Command.TYPE_REBOOT_DEVICE: - return formatCommand(command, "SA200CMD;{%s};02;Reboot\r", Command.KEY_UNIQUE_ID); + return formatCommand(command, prefix + ";%s;02;Reboot\r", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_SINGLE: - return formatCommand(command, "SA200GTR;{%s};02;\r", Command.KEY_UNIQUE_ID); + return formatCommand(command, prefix + ";%s;02;\r", Command.KEY_UNIQUE_ID); case Command.TYPE_OUTPUT_CONTROL: if (command.getAttributes().containsKey(Command.KEY_DATA)) { if (command.getAttributes().get(Command.KEY_DATA).equals("1")) { - return formatCommand(command, "SA200CMD;{%s};02;Enable{%s}\r", + return formatCommand(command, prefix + ";%s;02;Enable%s\r", Command.KEY_UNIQUE_ID, Command.KEY_INDEX); } else { - return formatCommand(command, "SA200CMD;{%s};02;Disable{%s}\r", + return formatCommand(command, prefix + ";%s;02;Disable%s\r", Command.KEY_UNIQUE_ID, Command.KEY_INDEX); } } case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "SA200CMD;{%s};02;Enable1\r", Command.KEY_UNIQUE_ID); + return formatCommand(command, prefix + ";%s;02;Enable1\r", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "SA200CMD;{%s};02;Disable1\r", Command.KEY_UNIQUE_ID); + return formatCommand(command, prefix + ";%s;02;Disable1\r", Command.KEY_UNIQUE_ID); case Command.TYPE_ALARM_ARM: - return formatCommand(command, "SA200CMD;{%s};02;Enable2\r", Command.KEY_UNIQUE_ID); + return formatCommand(command, prefix + ";%s;02;Enable2\r", Command.KEY_UNIQUE_ID); case Command.TYPE_ALARM_DISARM: - return formatCommand(command, "SA200CMD;{%s};02;Disable2\r", Command.KEY_UNIQUE_ID); + return formatCommand(command, prefix + ";%s;02;Disable2\r", Command.KEY_UNIQUE_ID); default: return null; } diff --git a/src/main/java/org/traccar/protocol/SviasProtocolEncoder.java b/src/main/java/org/traccar/protocol/SviasProtocolEncoder.java index 2607d7bd1..d218f63ce 100644 --- a/src/main/java/org/traccar/protocol/SviasProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/SviasProtocolEncoder.java @@ -30,11 +30,11 @@ public class SviasProtocolEncoder extends StringProtocolEncoder { protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_CUSTOM: - return formatCommand(command, "{%s}", Command.KEY_DATA); + return formatCommand(command, "%s", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AT+STR=1*"); case Command.TYPE_SET_ODOMETER: - return formatCommand(command, "AT+ODT={%s}*", Command.KEY_DATA); + return formatCommand(command, "AT+ODT=%s*", Command.KEY_DATA); case Command.TYPE_ENGINE_STOP: return formatCommand(command, "AT+OUT=1,1*"); case Command.TYPE_ENGINE_RESUME: diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java index c634d2438..cc2868a20 100644 --- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java @@ -200,6 +200,9 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { case 9: position.set(Position.PREFIX_ADC + 1, readValue(buf, length, false)); break; + case 10: + position.set(Position.PREFIX_ADC + 2, readValue(buf, length, false)); + break; case 17: position.set("axisX", readValue(buf, length, true)); break; diff --git a/src/main/java/org/traccar/protocol/Tk103ProtocolEncoder.java b/src/main/java/org/traccar/protocol/Tk103ProtocolEncoder.java index a8aa84105..5d7e63920 100644 --- a/src/main/java/org/traccar/protocol/Tk103ProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/Tk103ProtocolEncoder.java @@ -50,7 +50,7 @@ public class Tk103ProtocolEncoder extends StringProtocolEncoder { if (alternative) { switch (command.getType()) { case Command.TYPE_CUSTOM: - return formatAlt(command, "{%s}", Command.KEY_DATA); + return formatAlt(command, "%s", Command.KEY_DATA); case Command.TYPE_GET_VERSION: return formatAlt(command, "*about*"); case Command.TYPE_POWER_OFF: @@ -74,36 +74,36 @@ public class Tk103ProtocolEncoder extends StringProtocolEncoder { case Command.TYPE_ALARM_SOS: return formatAlt(command, command.getBoolean(Command.KEY_ENABLE) ? "*soson*" : "*sosoff*"); case Command.TYPE_SET_CONNECTION: - return formatAlt(command, "*setip*%s*{%s}*", - command.getString(Command.KEY_SERVER).replace(".", "*"), Command.KEY_PORT); + String server = command.getString(Command.KEY_SERVER).replace(".", "*"); + return formatAlt(command, "*setip*" + server + "*%s*", Command.KEY_PORT); case Command.TYPE_SOS_NUMBER: - return formatAlt(command, "*master*{%s}*{%s}*", Command.KEY_DEVICE_PASSWORD, Command.KEY_PHONE); + return formatAlt(command, "*master*%s*%s*", Command.KEY_DEVICE_PASSWORD, Command.KEY_PHONE); default: return null; } } else { switch (command.getType()) { case Command.TYPE_CUSTOM: - return formatCommand(command, "({%s}{%s})", Command.KEY_UNIQUE_ID, Command.KEY_DATA); + return formatCommand(command, "(%s%s)", Command.KEY_UNIQUE_ID, Command.KEY_DATA); case Command.TYPE_GET_VERSION: - return formatCommand(command, "({%s}AP07)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAP07)", Command.KEY_UNIQUE_ID); case Command.TYPE_REBOOT_DEVICE: - return formatCommand(command, "({%s}AT00)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAT00)", Command.KEY_UNIQUE_ID); case Command.TYPE_SET_ODOMETER: - return formatCommand(command, "({%s}AX01)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAX01)", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_SINGLE: - return formatCommand(command, "({%s}AP00)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAP00)", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_PERIODIC: - return formatCommand(command, "({%s}AR00%s0000)", Command.KEY_UNIQUE_ID, - String.format("%04X", command.getInteger(Command.KEY_FREQUENCY))); + String frequency = String.format("%04X", command.getInteger(Command.KEY_FREQUENCY)); + return formatCommand(command, "(%sAR00" + frequency + "0000)", Command.KEY_UNIQUE_ID); case Command.TYPE_POSITION_STOP: - return formatCommand(command, "({%s}AR0000000000)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAR0000000000)", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "({%s}AV010)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAV010)", Command.KEY_UNIQUE_ID); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "({%s}AV011)", Command.KEY_UNIQUE_ID); + return formatCommand(command, "(%sAV011)", Command.KEY_UNIQUE_ID); case Command.TYPE_OUTPUT_CONTROL: - return formatCommand(command, "({%s}AV00{%s})", Command.KEY_UNIQUE_ID, Command.KEY_DATA); + return formatCommand(command, "(%sAV00%s)", Command.KEY_UNIQUE_ID, Command.KEY_DATA); default: return null; } diff --git a/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java b/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java index 2a06d35e5..7ad99b37e 100644 --- a/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Tlt2hProtocolDecoder.java @@ -36,10 +36,18 @@ public class Tlt2hProtocolDecoder extends BaseProtocolDecoder { } private static final Pattern PATTERN_HEADER = new PatternBuilder() - .number("#(d+)#") // imei - .any() - .expression("#([^#]+)#") // status - .number("d+") // number of records + .number("#(d+)") // imei + .expression("#[^#]*") // user + .number("#d+") // password + .groupBegin() + .number("#([01])") // door + .number("#(d+)") // fuel voltage + .number("#(d+)") // power + .number("#(d+)") // battery + .number("#(d+)") // temperature + .groupEnd("?") + .expression("#([^#]+)") // status + .number("#d+") // number of records .compile(); private static final Pattern PATTERN_POSITION = new PatternBuilder() @@ -114,6 +122,19 @@ public class Tlt2hProtocolDecoder extends BaseProtocolDecoder { return null; } + Boolean door = null; + Double adc = null; + Double power = null; + Double battery = null; + Double temperature = null; + if (parser.hasNext(5)) { + door = parser.nextInt() == 1; + adc = parser.nextInt() * 0.1; + power = parser.nextInt() * 0.1; + battery = parser.nextInt() * 0.1; + temperature = parser.nextInt() * 0.1; + } + String status = parser.next(); String[] messages = sentence.substring(sentence.indexOf('\n') + 1).split("\r\n"); @@ -140,6 +161,11 @@ public class Tlt2hProtocolDecoder extends BaseProtocolDecoder { dateBuilder.setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0)); position.setTime(dateBuilder.getDate()); + position.set(Position.KEY_DOOR, door); + position.set(Position.PREFIX_ADC + 1, adc); + position.set(Position.KEY_POWER, power); + position.set(Position.KEY_BATTERY, battery); + position.set(Position.PREFIX_TEMP + 1, temperature); decodeStatus(position, status); positions.add(position); diff --git a/src/main/java/org/traccar/protocol/TopinProtocol.java b/src/main/java/org/traccar/protocol/TopinProtocol.java new file mode 100644 index 000000000..844dd7518 --- /dev/null +++ b/src/main/java/org/traccar/protocol/TopinProtocol.java @@ -0,0 +1,33 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +public class TopinProtocol extends BaseProtocol { + + public TopinProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new TopinProtocolDecoder(TopinProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/TopinProtocolDecoder.java b/src/main/java/org/traccar/protocol/TopinProtocolDecoder.java new file mode 100644 index 000000000..ea72b7cb8 --- /dev/null +++ b/src/main/java/org/traccar/protocol/TopinProtocolDecoder.java @@ -0,0 +1,172 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.buffer.Unpooled; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.NetworkMessage; +import org.traccar.Protocol; +import org.traccar.model.CellTower; +import org.traccar.model.Network; +import org.traccar.model.Position; +import org.traccar.model.WifiAccessPoint; + +import java.net.SocketAddress; +import java.util.TimeZone; + +public class TopinProtocolDecoder extends BaseProtocolDecoder { + + public TopinProtocolDecoder(Protocol protocol) { + super(protocol); + } + + public static final int MSG_LOGIN = 0x01; + public static final int MSG_GPS = 0x10; + public static final int MSG_GPS_OFFLINE = 0x11; + public static final int MSG_STATUS = 0x13; + public static final int MSG_WIFI_OFFLINE = 0x17; + public static final int MSG_WIFI = 0x69; + + private void sendResponse(Channel channel, int type, ByteBuf content) { + if (channel != null) { + ByteBuf response = Unpooled.buffer(); + response.writeShort(0x7878); + response.writeByte(1 + content.readableBytes()); + response.writeByte(type); + response.writeBytes(content); + response.writeByte('\r'); + response.writeByte('\n'); + content.release(); + channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress())); + } + } + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ByteBuf buf = (ByteBuf) msg; + + buf.skipBytes(2); // header + int length = buf.readUnsignedByte(); + + int type = buf.readUnsignedByte(); + + DeviceSession deviceSession; + if (type == MSG_LOGIN) { + String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1); + deviceSession = getDeviceSession(channel, remoteAddress, imei); + ByteBuf content = Unpooled.buffer(); + content.writeByte(deviceSession != null ? 0x01 : 0x44); + sendResponse(channel, type, content); + return null; + } else { + deviceSession = getDeviceSession(channel, remoteAddress); + if (deviceSession == null) { + return null; + } + } + + if (type == MSG_GPS || type == MSG_GPS_OFFLINE) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + ByteBuf time = buf.slice(buf.readerIndex(), 6); + + Gt06ProtocolDecoder.decodeGps(position, buf, false, TimeZone.getTimeZone("UTC")); + + ByteBuf content = Unpooled.buffer(); + content.writeBytes(time); + sendResponse(channel, type, content); + + return position; + + } else if (type == MSG_STATUS) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + getLastLocation(position, null); + + int battery = buf.readUnsignedByte(); + int firmware = buf.readUnsignedByte(); + int timezone = buf.readUnsignedByte(); + int interval = buf.readUnsignedByte(); + int signal = 0; + if (length >= 7) { + signal = buf.readUnsignedByte(); + position.set(Position.KEY_RSSI, signal); + } + + position.set(Position.KEY_BATTERY_LEVEL, battery); + position.set(Position.KEY_VERSION_FW, firmware); + + ByteBuf content = Unpooled.buffer(); + content.writeByte(battery); + content.writeByte(firmware); + content.writeByte(timezone); + content.writeByte(interval); + if (length >= 7) { + content.writeByte(signal); + } + sendResponse(channel, type, content); + + return position; + + } else if (type == MSG_WIFI || type == MSG_WIFI_OFFLINE) { + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + + getLastLocation(position, null); + + ByteBuf time = buf.readSlice(6); + + Network network = new Network(); + for (int i = 0; i < length; i++) { + String mac = String.format("%02x:%02x:%02x:%02x:%02x:%02x", + buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte(), + buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte()); + network.addWifiAccessPoint(WifiAccessPoint.from(mac, buf.readUnsignedByte())); + } + + int cellCount = buf.readUnsignedByte(); + int mcc = buf.readUnsignedShort(); + int mnc = buf.readUnsignedByte(); + for (int i = 0; i < cellCount; i++) { + network.addCellTower(CellTower.from( + mcc, mnc, buf.readUnsignedShort(), buf.readUnsignedShort(), buf.readUnsignedByte())); + } + + position.setNetwork(network); + + ByteBuf content = Unpooled.buffer(); + content.writeBytes(time); + sendResponse(channel, type, content); + + return position; + + } + + return null; + } + +} diff --git a/src/main/java/org/traccar/protocol/TotemProtocolEncoder.java b/src/main/java/org/traccar/protocol/TotemProtocolEncoder.java index 3bbb92031..a96dd1ee3 100644 --- a/src/main/java/org/traccar/protocol/TotemProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/TotemProtocolEncoder.java @@ -34,9 +34,9 @@ public class TotemProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { // Assuming PIN 8 (Output C) is the power wire, like manual says but it can be PIN 5,7,8 case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "*{%s},025,C,1#", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "*%s,025,C,1#", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "*{%s},025,C,0#", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "*%s,025,C,0#", Command.KEY_DEVICE_PASSWORD); default: return null; } diff --git a/src/main/java/org/traccar/protocol/UproProtocolDecoder.java b/src/main/java/org/traccar/protocol/UproProtocolDecoder.java index 873b22006..a17003fc8 100644 --- a/src/main/java/org/traccar/protocol/UproProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/UproProtocolDecoder.java @@ -171,12 +171,31 @@ public class UproProtocolDecoder extends BaseProtocolDecoder { position.setAltitude( Integer.parseInt(data.readSlice(6).toString(StandardCharsets.US_ASCII)) * 0.1); break; + case 'J': + if (data.readableBytes() == 6) { + char index = (char) data.readUnsignedByte(); + int status = data.readUnsignedByte(); + double value = Integer.parseInt(data.readSlice(4).toString(StandardCharsets.US_ASCII)) * 0.1; + if (BitUtil.check(status, 0)) { + value = -value; + } + position.set(Position.PREFIX_TEMP + index, value); + } + break; case 'K': position.set("statusExtended", data.toString(StandardCharsets.US_ASCII)); break; case 'M': - position.set(Position.KEY_BATTERY_LEVEL, - Integer.parseInt(data.readSlice(3).toString(StandardCharsets.US_ASCII)) * 0.1); + if (data.readableBytes() == 3) { + position.set(Position.KEY_BATTERY_LEVEL, + Integer.parseInt(data.readSlice(3).toString(StandardCharsets.US_ASCII)) * 0.1); + } else if (data.readableBytes() == 4) { + char index = (char) data.readUnsignedByte(); + data.readUnsignedByte(); // status + position.set( + "humidity" + index, + Integer.parseInt(data.readSlice(2).toString(StandardCharsets.US_ASCII))); + } break; case 'N': position.set(Position.KEY_RSSI, diff --git a/src/main/java/org/traccar/protocol/VnetProtocol.java b/src/main/java/org/traccar/protocol/VnetProtocol.java new file mode 100644 index 000000000..0fed30e13 --- /dev/null +++ b/src/main/java/org/traccar/protocol/VnetProtocol.java @@ -0,0 +1,37 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.handler.codec.LengthFieldBasedFrameDecoder; +import org.traccar.BaseProtocol; +import org.traccar.PipelineBuilder; +import org.traccar.TrackerServer; + +import java.nio.ByteOrder; + +public class VnetProtocol extends BaseProtocol { + + public VnetProtocol() { + addServer(new TrackerServer(false, getName()) { + @Override + protected void addProtocolHandlers(PipelineBuilder pipeline) { + pipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 1500, 4, 2, 12, 0, true)); + pipeline.addLast(new VnetProtocolDecoder(VnetProtocol.this)); + } + }); + } + +} diff --git a/src/main/java/org/traccar/protocol/VnetProtocolDecoder.java b/src/main/java/org/traccar/protocol/VnetProtocolDecoder.java new file mode 100644 index 000000000..1ee00bd3f --- /dev/null +++ b/src/main/java/org/traccar/protocol/VnetProtocolDecoder.java @@ -0,0 +1,105 @@ +/* + * Copyright 2019 Anton Tananaev (anton@traccar.org) + * + * 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.protocol; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.channel.Channel; +import org.traccar.BaseProtocolDecoder; +import org.traccar.DeviceSession; +import org.traccar.NetworkMessage; +import org.traccar.Protocol; +import org.traccar.helper.BcdUtil; +import org.traccar.helper.BitUtil; +import org.traccar.helper.DateBuilder; +import org.traccar.helper.UnitsConverter; +import org.traccar.model.Position; + +import java.net.SocketAddress; + +public class VnetProtocolDecoder extends BaseProtocolDecoder { + + public VnetProtocolDecoder(Protocol protocol) { + super(protocol); + } + + public static final int MSG_LOGIN = 0x0000; + public static final int MSG_LBS = 0x32; + public static final int MSG_GPS = 0x33; + + @Override + protected Object decode( + Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { + + ByteBuf buf = (ByteBuf) msg; + + buf.skipBytes(2); // header + int type = BitUtil.to(buf.readUnsignedShortLE(), 15); + buf.readUnsignedShortLE(); // length + + DateBuilder dateBuilder = new DateBuilder() + .setDateReverse(BcdUtil.readInteger(buf, 2), BcdUtil.readInteger(buf, 2), BcdUtil.readInteger(buf, 2)) + .setTime(BcdUtil.readInteger(buf, 2), BcdUtil.readInteger(buf, 2), BcdUtil.readInteger(buf, 2)); + + if (type == MSG_LOGIN) { + + String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(0, 15); + getDeviceSession(channel, remoteAddress, imei); + if (channel != null) { + channel.writeAndFlush(new NetworkMessage( + buf.retainedSlice(0, buf.writerIndex()), channel.remoteAddress())); + } + + } else if (type == MSG_GPS) { + + DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); + if (deviceSession == null) { + return null; + } + + Position position = new Position(getProtocolName()); + position.setDeviceId(deviceSession.getDeviceId()); + position.setTime(dateBuilder.getDate()); + + int value; + int degrees; + + value = BcdUtil.readInteger(buf, 8); + degrees = value / 1000000; + double lat = degrees + value % 1000000 * 0.0001 / 60; + + value = BcdUtil.readInteger(buf, 10); + degrees = value / 10000000; + double lon = degrees + value % 10000000 * 0.00001 / 60; + + int flags = buf.readUnsignedByte(); + position.setValid(BitUtil.check(flags, 0)); + position.setLatitude(BitUtil.check(flags, 1) ? lat : -lat); + position.setLongitude(BitUtil.check(flags, 2) ? lon : -lon); + + position.set(Position.KEY_SATELLITES, buf.readUnsignedByte()); + position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedByte())); + position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE()); + position.setCourse(buf.readUnsignedByte() * 2); + + return position; + + } + + return null; + } + +} diff --git a/src/main/java/org/traccar/protocol/WatchProtocolEncoder.java b/src/main/java/org/traccar/protocol/WatchProtocolEncoder.java index b433dfd2a..f285267ba 100644 --- a/src/main/java/org/traccar/protocol/WatchProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/WatchProtocolEncoder.java @@ -137,33 +137,33 @@ public class WatchProtocolEncoder extends StringProtocolEncoder implements Strin case Command.TYPE_POSITION_SINGLE: return formatTextCommand(channel, command, "RG"); case Command.TYPE_SOS_NUMBER: - return formatTextCommand(channel, command, "SOS{%s},{%s}", Command.KEY_INDEX, Command.KEY_PHONE); + return formatTextCommand(channel, command, "SOS%s,%s", Command.KEY_INDEX, Command.KEY_PHONE); case Command.TYPE_ALARM_SOS: - return formatTextCommand(channel, command, "SOSSMS,{%s}", Command.KEY_ENABLE); + return formatTextCommand(channel, command, "SOSSMS,%s", Command.KEY_ENABLE); case Command.TYPE_ALARM_BATTERY: - return formatTextCommand(channel, command, "LOWBAT,{%s}", Command.KEY_ENABLE); + return formatTextCommand(channel, command, "LOWBAT,%s", Command.KEY_ENABLE); case Command.TYPE_REBOOT_DEVICE: return formatTextCommand(channel, command, "RESET"); case Command.TYPE_POWER_OFF: return formatTextCommand(channel, command, "POWEROFF"); case Command.TYPE_ALARM_REMOVE: - return formatTextCommand(channel, command, "REMOVE,{%s}", Command.KEY_ENABLE); + return formatTextCommand(channel, command, "REMOVE,%s", Command.KEY_ENABLE); case Command.TYPE_SILENCE_TIME: - return formatTextCommand(channel, command, "SILENCETIME,{%s}", Command.KEY_DATA); + return formatTextCommand(channel, command, "SILENCETIME,%s", Command.KEY_DATA); case Command.TYPE_ALARM_CLOCK: - return formatTextCommand(channel, command, "REMIND,{%s}", Command.KEY_DATA); + return formatTextCommand(channel, command, "REMIND,%s", Command.KEY_DATA); case Command.TYPE_SET_PHONEBOOK: - return formatTextCommand(channel, command, "PHB,{%s}", Command.KEY_DATA); + return formatTextCommand(channel, command, "PHB,%s", Command.KEY_DATA); case Command.TYPE_MESSAGE: - return formatTextCommand(channel, command, "MESSAGE,{%s}", Command.KEY_MESSAGE); + return formatTextCommand(channel, command, "MESSAGE,%s", Command.KEY_MESSAGE); case Command.TYPE_VOICE_MESSAGE: return formatBinaryCommand(channel, command, "TK,", getBinaryData(command)); case Command.TYPE_POSITION_PERIODIC: - return formatTextCommand(channel, command, "UPLOAD,{%s}", Command.KEY_FREQUENCY); + return formatTextCommand(channel, command, "UPLOAD,%s", Command.KEY_FREQUENCY); case Command.TYPE_SET_TIMEZONE: - return formatTextCommand(channel, command, "LZ,,{%s}", Command.KEY_TIMEZONE); + return formatTextCommand(channel, command, "LZ,%s,%s", Command.KEY_LANGUAGE, Command.KEY_TIMEZONE); case Command.TYPE_SET_INDICATOR: - return formatTextCommand(channel, command, "FLOWER,{%s}", Command.KEY_DATA); + return formatTextCommand(channel, command, "FLOWER,%s", Command.KEY_DATA); default: return null; } diff --git a/src/main/java/org/traccar/protocol/WialonProtocolEncoder.java b/src/main/java/org/traccar/protocol/WialonProtocolEncoder.java index c45edf00d..93086bf8a 100644 --- a/src/main/java/org/traccar/protocol/WialonProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/WialonProtocolEncoder.java @@ -32,11 +32,11 @@ public class WialonProtocolEncoder extends StringProtocolEncoder { case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "reboot\r\n"); case Command.TYPE_SEND_USSD: - return formatCommand(command, "USSD:{%s}\r\n", Command.KEY_PHONE); + return formatCommand(command, "USSD:%s\r\n", Command.KEY_PHONE); case Command.TYPE_IDENTIFICATION: return formatCommand(command, "VER?\r\n"); case Command.TYPE_OUTPUT_CONTROL: - return formatCommand(command, "L{%s}={%s}\r\n", Command.KEY_INDEX, Command.KEY_DATA); + return formatCommand(command, "L%s=%s\r\n", Command.KEY_INDEX, Command.KEY_DATA); default: return null; } diff --git a/src/main/java/org/traccar/protocol/WondexProtocolEncoder.java b/src/main/java/org/traccar/protocol/WondexProtocolEncoder.java index e9bb23d15..21f1ee321 100644 --- a/src/main/java/org/traccar/protocol/WondexProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/WondexProtocolEncoder.java @@ -32,17 +32,17 @@ public class WondexProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { case Command.TYPE_REBOOT_DEVICE: - return formatCommand(command, "$WP+REBOOT={%s}", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "$WP+REBOOT=%s", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_GET_DEVICE_STATUS: - return formatCommand(command, "$WP+TEST={%s}", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "$WP+TEST=%s", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_GET_MODEM_STATUS: - return formatCommand(command, "$WP+GSMINFO={%s}", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "$WP+GSMINFO=%s", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_IDENTIFICATION: - return formatCommand(command, "$WP+IMEI={%s}", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "$WP+IMEI=%s", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_POSITION_SINGLE: - return formatCommand(command, "$WP+GETLOCATION={%s}", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "$WP+GETLOCATION=%s", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_GET_VERSION: - return formatCommand(command, "$WP+VER={%s}", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "$WP+VER=%s", Command.KEY_DEVICE_PASSWORD); default: return null; } diff --git a/src/main/java/org/traccar/protocol/XexunProtocolEncoder.java b/src/main/java/org/traccar/protocol/XexunProtocolEncoder.java index fc849fe15..4f2707c2a 100644 --- a/src/main/java/org/traccar/protocol/XexunProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/XexunProtocolEncoder.java @@ -32,9 +32,9 @@ public class XexunProtocolEncoder extends StringProtocolEncoder { switch (command.getType()) { case Command.TYPE_ENGINE_STOP: - return formatCommand(command, "powercar{%s} 11", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "powercar%s 11", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_ENGINE_RESUME: - return formatCommand(command, "powercar{%s} 00", Command.KEY_DEVICE_PASSWORD); + return formatCommand(command, "powercar%s 00", Command.KEY_DEVICE_PASSWORD); default: return null; } diff --git a/src/main/java/org/traccar/protocol/Xrb28ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xrb28ProtocolDecoder.java index 938394d6b..69e5b7372 100644 --- a/src/main/java/org/traccar/protocol/Xrb28ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Xrb28ProtocolDecoder.java @@ -47,7 +47,7 @@ public class Xrb28ProtocolDecoder extends BaseProtocolDecoder { .expression("..,") // vendor .number("d{15},") // imei .expression("..,") // type - .number("0,") // reserved + .number("[01],") // reserved .number("(dd)(dd)(dd).d+,") // time (hhmmss) .expression("([AV]),") // validity .number("(dd)(dd.d+),") // latitude diff --git a/src/main/proto/OmnicommMessage.proto b/src/main/proto/OmnicommMessage.proto new file mode 100644 index 000000000..a3b5b6138 --- /dev/null +++ b/src/main/proto/OmnicommMessage.proto @@ -0,0 +1,464 @@ +syntax = "proto2"; + +package org.traccar.protobuf; + +message OmnicommMessage { + + repeated uint32 mID = 1 [packed=true]; // идентификатор события (возможно несколько событий в одном сообщении.) + + optional group General = 2 { // Основные параметры + optional uint32 Time = 1;//[4] Время/дата события (в OmnicommTime) + optional uint32 IDFAS = 2;//[4] Идентификатор бортового оборудования + optional bytes IDDrv = 3;//[8] ID iButton (8 байт) + optional uint32 FLG = 4;//[1] Общие флаги состояния + /* Битовая маска: + 0 бит = Положение ключа зажигания + 0 – зажигание выключено, + 1 – зажигание включено. + 1 бит = Наличие связи GSM + 0 – Нет связи, + 1 – Есть связь. + 2 бит = Корректность данных GPS + 0 – Данные некорректны, + 1 – Данные корректны. + 3 бит = Нахождение в роуминге + 0 – В домашней сети, + 1 – В роуминге. + 4 бит = Состояние питания + 0 – Внешнее питание, + 1 – Резервное питание. + 5 бит = Тревожная кнопка (текущее состояние кнопки) + 0 – Кнопка отжата, + 1 – Кнопка нажата. + 6 бит = Вскрытие устройства + 0 – Устройство закрыто, + 1 – Устройство открыто. + 7 бит = Состояние дискретного выхода + 0 – Выключен, + 1 – Включен. + 8 бит = Кнопка голосового вызова + 0 - Кнопка отжата + 1 - Кнопка нажата + 9 бит = глушение GPS + 0 – Выключен, + 1 – Включен. + 10 бит = глушение GSM + 0 – Выключен, + 1 – Включен. + 11 бит = неисправность аккумулятора + 0 – Нет, + 1 – Да. + */ + optional uint32 Mileage = 5;//[4] Пробег (1LSB = 0.1 метр) + optional uint32 VImp = 6;//[2] Скорость по датчику (1LSB = 1км/ч) + optional uint32 TImp = 7;//[2] Обороты по датчику (1LSB = 1об./мин.) + optional uint32 Uboard = 8;//[4] Напряжение питания (1LSB = 0.1В) + optional uint32 BatLife =9;//[4] Уровень заряда аккумулятора (1LSB = 1%) + optional sint32 SumAcc = 10;//[4] Корень суммы квадратов ускорений осей x,y,z (1LSB = 0.01g) + optional bytes Phone = 11;//[6] Номер вызывающего или вызываемого абонента + optional sint32 AmtrX = 12;//[4] Ускорение по оси X + optional sint32 AmtrY = 13;//[4] Ускорение по оси Y + optional sint32 AmtrZ = 14;//[4] Ускорение по оси Z + optional bytes TachoCardID = 15;//[16] ID карты тахографа (16 байт) + optional uint32 AccelStatus = 16;//[1] Статус калибровки акселерометра: 0 - не используется, 1 - калибруется, 2 - откалиброван, 3 - Ошибка определения осей + optional uint32 HoursKoef = 17;// Моточасы с использование коэффициента + optional uint32 GsmSignalQuality = 18;// Уровень сигнала GSM, усл.ед.: 0 - нет сигнала, 1 - плохой, 2 - слабый, 3 - удовлетворительный, 4 - хороший, 5 - отличный + optional uint32 WifiSignalQuality = 19;// Уровень сигнала Wi-Fi, усл.ед? 0 - нет сигнала, 1 - плохой, 2 - слабый, 3 - удовлетворительный, 4 - хороший, 5 - отличный + } + + optional group Photo = 4 { // Описание блока передачи части изображения + optional uint32 POSBLK=1;//[4] Позиция текущего блока (в байтах от начала фотографии) + optional uint32 SZPHOTO=2; //[4] Размер всей фотографии (в байтах) + optional uint32 SIZEBLK=3;//[4] Размер текущего блока фотографии (в байтах) + optional bytes IMGDAT=4;//[2048] Буфер фотографии (данные фотографии) + optional uint32 IDPH=5;//[4] Идентификатор фотографии + optional uint32 IMGSTAT=6;//[1] Статус изображения, см. Таблицу "Коды состояния фотокамеры". + } + + optional group NAV = 5 { // Навигация + required sint32 LAT=1;//[4] Широта (1LSB = 0,0000001гр.) + required sint32 LON=2;//[4] Долгота (1LSB = 0,0000001гр.) + required uint32 GPSVel=3;//[2] Скорость по GPS (1LSB = 0.1км/ч) + required uint32 GPSDir=4;//[2] Направление (1LSB = 1гр.) + required uint32 GPSNSat=5;//[1] Количество спутников + required sint32 GPSAlt=6;//[2] Высота над уровнем моря (1LSB = 0.1м) + optional uint32 GPSTime = 7;//[4] Время/дата события по GPS (в OmnicommTime) + } + + optional group UniDt = 6 { // Универсальные входы + optional sint32 UniVal0 = 1;//[4] Данные универсального входа 1 + optional sint32 UniVal1 = 2;//[4] Данные универсального входа 2 + optional sint32 UniVal2 = 3;//[4] Данные универсального входа 3 + optional sint32 UniVal3 = 4;//[4] Данные универсального входа 4 + optional sint32 UniVal4 = 5;//[4] Данные универсального входа 5 + optional sint32 UniVal5 = 6;//[4] Данные универсального входа 6 + } + + optional group CanDt_J1939 = 7 { // Данные шины CAN (протокол J1939) + optional uint32 SPN70 = 70;//[1] Cостояние парковочного тормоза + /* Возможные значения + 00 - Parking brake not set + 01 - Parking brake set + 10 - Error + 11 - Not available + */ + optional uint32 SPN91 = 91;//[1] Пположение педали акселерометра (0.4%) + /* Ошибки: + 254 = Error + 255 = Not available + */ + optional uint32 SPN96 = 96; // Уровень топлива 1 бак.(0.4 %) Если есть SPN38, то первый бак, если нет, общий уровень + /* Ошибки: + 251=Error + 252= Not available + */ + + optional uint32 SPN100 = 100;//[1] Давление масла двигателя (1 LSB=4 kPa) + /* Ошибки: + 254 = Error + 255 = Not available + */ + optional uint32 SPN110 = 110;//[1] температура ОЖ двигателя. Cмещение -40 (диапазон данных от -40 до 210°C) + /* Ошибки: + 254 = Error + 255 = Not available + */ + optional uint32 SPN174 = 174;//[1] температура топлива. Cмещение -40 (диапазон данных от -40 до 210°C) + /* Ошибки: + 254=Error + 255= Not available + */ + optional uint32 SPN175 = 175;//[2] температура масла двигателя. Cмещение - 273 (диапазон данных от -273 до 1735 deg C) + optional uint32 SPN182 = 182;//[4] суточный расход топлива (0.5 L) + /* Ошибки: + 4 261 412 864 .. 4 278 190 079 =Error + 4 278 190 080 .. 4 294 967 294 = Not available + */ + optional uint32 SPN184 = 184;//[2] мгновенная экономичность (1/512 km/L) + /* Ошибки: + 65 024 .. 65 279 =Error + 65 280 .. 65 535 = Not available + */ + optional uint32 SPN190 = 190;//[2] обороты двигателя (0.125 rpm) + /* Ошибки: + 65 024 .. 65 279 =Error + 65 280 .. 65 535 = Not available + */ + optional uint32 SPN244 = 244;//[4] суточный пробег (0.125 km) + /* Ошибки: + 4 261 412 864 .. 4 278 190 079 =Error + 4 278 190 080 .. 4 294 967 294 = Not available + */ + optional uint32 SPN245 = 245;//[4] общий пробег (0.125 km) + /* Ошибки: + 4 261 412 864 .. 4 278 190 079 =Error + 4 278 190 080 .. 4 294 967 294 = Not available + */ + optional uint32 SPN247 = 247;//[4] общее время работы двигателя (0.05 hr) + /* Ошибки: + 4 261 412 864 .. 4 278 190 079 =Error + 4 278 190 080 .. 4 294 967 294 = Not available + */ + optional uint32 SPN250 = 250;//[4] общий расход топлива за все время (0.5 L) + /* Ошибки: + 4 261 412 864 .. 4 278 190 079 =Error + 4 278 190 080 .. 4 294 967 294 = Not available + */ + optional uint32 SPN521 = 521;//[1] положение педали рабочего тормоза (0.4 %) + /* Ошибки: + 254=Error + 255= Not available + */ + optional uint32 SPN522 = 522;//[1] положение педали сцепления (0.4 %) + /* Ошибки: + 254=Error + 255= Not available + */ + optional uint32 SPN527 = 527;//[1] состояние круиз-контроля + /* Возможные значения: + 0 = Off/Disabled + 1 = Hold + 2 = Accelerate + 3 = Decelerate + 4 = Resume + 5 = Set + 6 = Accelerator Override + 7 = Not available + */ + repeated uint32 SPN582 = 582 [packed=true]; /*PGN 65258 */ //[2*8] Нагрузка на ось + optional uint32 SPN597 = 597;//[1] состояние педали рабочего тормоза + /* Возможные значения: + 0 = Brake pedal released + 1 = Brake pedal depressed + 2 = Error + 3 = Not Available + */ + optional uint32 SPN598 = 598;//[1] состояние педали сцепления + /* Возможные значения: + 0 = Clutch pedal released + 1 = Clutch pedal depressed + 2 = Error + 3 = Not Available + */ + optional uint32 SPN914 = 914;//[2] пробег до следующего ТО. Cмещение -160635 km (5 km) + /* Ошибки: + 65 024 .. 65 279 =Error + 65 280 .. 65 535 = Not available + */ + optional uint32 SPN916 = 916;//[1] время работы двигателя до следующего ТО. Cмещение -32127 hr (1 hr) + /* Ошибки: + 65 024 .. 65 279 =Error + 65 280 .. 65 535 = Not available + */ + repeated uint32 SPN928 = 928 [packed=true]; /*PGN 65258 */ //[1*8] индекс оси + optional uint32 SPN1624 = 1624;//[2] мгновенная скорость (1/256 km/h) + // (по CAN это SPN 84, номер не менял чтобы конфликтов с предыдущими прошивками не возникло) + /* Ошибки: + 65 024 .. 65 279 =Error + 65 280 .. 65 535 = Not available + */ + optional uint32 SPN1821 = 1821;//[1] состояние дверей + /* Возможные значения: + 0 = At least 1 door is open + 1 = Closing last door + 2 = All doors closed + 3..13 = Not defined + 14 = Error + 15 = Not available + */ + optional uint32 SPN1856 = 1856;//[1] состояние ремней безопасности + /* Возможные значения: + 0 = NOT Buckled + 1 = OK - Seat Belt is buckled + 2 = Error - Switch state cannot be determined + 3 = Not Available + */ + } + + optional group LLSDt = 8 { // Топливные датчики LLS/LLS-AF + optional sint32 TLLS1 = 1; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS1 = 2; //[2] уровень + optional sint32 FLLS1 = 3; //[1] код состояния см. Таблицу "Коды состояния LLS". + + optional sint32 TLLS2 = 4; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS2 = 5; //[4] уровень + optional sint32 FLLS2 = 6; //[1] код состояния см. Таблицу "Коды состояния LLS". + + optional sint32 TLLS3 = 7; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS3 = 8; //[4] уровень + optional sint32 FLLS3 = 9; //[1] код состояния см. Таблицу "Коды состояния LLS". + + optional sint32 TLLS4 = 10; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS4 = 11; //[4] уровень + optional sint32 FLLS4 = 12; //[1] код состояния см. Таблицу "Коды состояния LLS". + + optional sint32 TLLS5 = 13; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS5 = 14; //[4] уровень + optional sint32 FLLS5 = 15; //[1] код состояния см. "Коды состояния LLS". + + optional sint32 TLLS6 = 16; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS6 = 17; //[4] уровень + optional sint32 FLLS6 = 18; //[1] код состояния см. "Коды состояния LLS". + + optional sint32 TLLS7 = 19; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS7 = 20; //[4] уровень + optional sint32 FLLS7 = 21; //[1] код состояния см. "Коды состояния LLS". + + optional sint32 TLLS8 = 22; //[1] температура (1LSB = 1гр.C) + optional uint32 CLLS8 = 23; //[4] уровень + optional sint32 FLLS8 = 24; //[1] код состояния см. "Коды состояния LLS". + + repeated uint32 LLSRefKoef= 25 [packed=true]; //[8] набор из восьми поправочных коэффициентов ДУТ (поз. 0 - ДУТ1, поз. 1 - ДУТ2, ...) + } + + optional group Other = 9 { // прочее оборудование + optional group OneWire = 1 { + // Температурные датчики 1-wire Присутствуют только температуры с настроенных датчиков + optional sint32 OneWire1 = 1; //[1] температура c датчика 1 + optional sint32 OneWire2 = 2; //[1] температура c датчика 2 + optional sint32 OneWire3 = 3; //[1] температура c датчика 3 + optional sint32 OneWire4 = 4; //[1] температура c датчика 4 + optional sint32 OneWire5 = 5; //[1] температура c датчика 5 + optional sint32 OneWire6 = 6; //[1] температура c датчика 6 + optional sint32 OneWire7 = 7; //[1] температура c датчика 7 + optional sint32 OneWire8 = 8; //[1] температура c датчика 8 + } + optional group Pherip = 2 { // Периферия кладется в архив только при данные с только подключенных и настроенных устройств + optional uint32 PassengerIn= 1; //[1] Количество вошедших пассажиров + optional uint32 PassengerOut= 2; //[1] Количество вышедших пассажиров + optional uint32 DoorMask= 3; //[1] маска дверей датчика пасажиропотока + optional uint32 DriverStatus= 4; //[1] Статус водителя + optional bytes TPMS = 5; //[92] Система контроля давления воздуха в шинах, всего возможно 46 датчика. Массив из 46 структур по 2 байта. + optional bytes iQFreeze = 6; //[512] Система контроля рефрижераторами iQFreeze.json - http://wiki.omnicomm.ru/pages/viewpage.action?pageId=11567726 + } + optional group ExCAN = 3 { // Расширенные парметры CAN + repeated uint32 SPNid = 1; //[24] Коды SPN + repeated uint32 SPNval = 2; //[24] Зачения SPN + optional uint64 Adr64TEREX = 10; + optional uint64 Adr65TEREX = 11; + optional uint64 Adr66TEREX = 12; + optional uint64 Adr67TEREX = 13; + repeated uint64 Adr11TEREX = 14; //[10] Коды ошибок + optional uint64 Adr69TEREX = 15; + } + optional group Taho_DDD = 4 { // Описание блока передачи части DDD-файла + optional uint32 BLKPOS=1;// Позиция текущего блока (в байтах от начала файла) + optional bytes FILEDATA=2;//[1024] Данные блока + optional bytes CARDID=3;//[16] Идентификатор карты водителя + optional uint32 STATUS_DATA=4; // параметр равен 1 если данный блок последний в файле, 2 - если ошибка чтения данных, 0 – если обычный блок данных + } + optional group APC = 5 { // Данные от ДПП IRMA. + optional uint32 APCStatus1 = 1; //[1] Статус ДПП IRMA #1: 0 – ок, 1 – «саботаж», 2 – «дефект», 3 – «датчик не отвечает» + optional uint32 APCStatus2 = 2; //[1] Статус ДПП IRMA #2: 0 – ок, 1 – «саботаж», 2 – «дефект», 3 – «датчик не отвечает» + optional uint32 APCStatus3 = 3; //[1] Статус ДПП IRMA #3: 0 – ок, 1 – «саботаж», 2 – «дефект», 3 – «датчик не отвечает» + optional uint32 APCStatus4 = 4; //[1] Статус ДПП IRMA #4: 0 – ок, 1 – «саботаж», 2 – «дефект», 3 – «датчик не отвечает» + optional uint32 APCNumberIn1 = 5; //[2] Количество вошедших пассажиров подсчитанное на ДПП IRMA #1 + optional uint32 APCNumberOut1 = 6; //[2] Количество вышедших пассажиров подсчитанное на ДПП IRMA #1 + optional uint32 APCNumberIn2 = 7; //[2] Количество вошедших пассажиров подсчитанное на ДПП IRMA #2 + optional uint32 APCNumberOut2 = 8; //[2] Количество вышедших пассажиров подсчитанное на ДПП IRMA #2 + optional uint32 APCNumberIn3 = 9; //[2] Количество вошедших пассажиров подсчитанное на ДПП IRMA #3 + optional uint32 APCNumberOut31 = 10; //[2] Количество вышедших пассажиров подсчитанное на ДПП IRMA #3 + optional uint32 APCNumberIn4 = 11; //[2] Количество вошедших пассажиров подсчитанное на ДПП IRMA #4 + optional uint32 APCNumberOut4 = 12; //[2] Количество вышедших пассажиров подсчитанное на ДПП IRMA #4 + } + optional group MobileEye = 6 { // Данные от MobileEye + optional uint32 MobileEyeStatus = 1; //[1] Статус MobileEye (битовая маска событий) + repeated bytes CAN700 = 2; // Данные с MobileEye адресс кэн 700 + repeated bytes CAN727 = 3; // Данные с MobileEye адресс кэн 727 + repeated bytes CAN760 = 4; // Данные с MobileEye адресс кэн 760 + } + optional group SafeDriving = 7 { // Данные о безопасном вождении + optional uint32 EventMask = 1; //[4] Инициатор посылки события (Битовая маска) 0 – Скорость, 1 – Обороты, 2 – Ускорение, 3 – Боковое ускорение, 4 - Ускорение торможения, 5 - Вертикальное ускорение + optional uint32 SpeedThreshold = 2; //[4] Порог Скорости, поле присутствует если EventMask/Бит 0 = 1 + optional uint32 RPMThreshold = 3; //[4] Порог Оборотов, поле присутствует если EventMask/Бит 1 = 1 + repeated float AccelDangThs = 4 [packed=true]; //[4] + } + optional group GenComm= 8{ // Данные о GenComm генераторе + optional uint32 GEN_OILPRESS1 = 1; + optional sint32 GEN_TEMP1 = 2; + optional float GEN_VOLT1 = 3; + optional uint32 GEN_RPM1 = 4; + optional float GEN_UL1_1 = 5; + optional float GEN_UL2_1 = 6; + optional float GEN_UL3_1 = 7; + optional float GEN_IL1_1 = 8; + optional float GEN_IL2_1 = 9; + optional float GEN_IL3_1 = 10; + optional uint32 GEN_STATUS1 = 11; + optional uint32 GEN_HOURS1 = 12; + repeated bytes GEN_ALARM1 = 13; //[28] + + optional uint32 GEN_OILPRESS2 = 14; + optional sint32 GEN_TEMP2 = 15; + optional float GEN_VOLT2 = 16; + optional uint32 GEN_RPM2 = 17; + optional float GEN_UL1_2 = 18; + optional float GEN_UL2_2 = 19; + optional float GEN_UL3_2 = 20; + optional float GEN_IL1_2 = 21; + optional float GEN_IL2_2 = 22; + optional float GEN_IL3_2 = 23; + optional uint32 GEN_STATUS2 = 24; + optional uint32 GEN_HOURS2 = 25; + repeated bytes GEN_ALARM2 = 26; //[28] + + optional uint32 GEN_OILPRESS3 = 27; + optional sint32 GEN_TEMP3 = 28; + optional float GEN_VOLT3 = 29; + optional uint32 GEN_RPM3 = 30; + optional float GEN_UL1_3 = 31; + optional float GEN_UL2_3 = 32; + optional float GEN_UL3_3 = 33; + optional float GEN_IL1_3 = 34; + optional float GEN_IL2_3 = 35; + optional float GEN_IL3_3 = 36; + optional uint32 GEN_STATUS3 = 37; + optional uint32 GEN_HOURS3 = 38; + repeated bytes GEN_ALARM3 = 39; //[28] + optional float GEN_UC = 40; // величина напряжения зарядного генератора + optional uint32 GEN_IC = 41; // ток заряда стартерных АКБ + optional float GEN_FREQ = 42; // частота выдаваемого напряжения + optional float GEN_UL1L2 = 43; // напряжения линейные + optional float GEN_UL2L3 = 44; // -- + optional float GEN_UL1L3 = 45; // -- + optional uint32 POW_ACT_L1 = 46; // активная мощность + optional uint32 POW_ACT_L2 = 47; // -- + optional uint32 POW_ACT_L3 = 48; // -- + optional uint32 POW_FULL_L1 = 49; // полная мощность + optional uint32 POW_FULL_L2 = 50; // -- + optional uint32 POW_FULL_L3 = 51; // -- + optional uint32 POW_REACT_L1 = 52; // реактивная мощность + optional uint32 POW_REACT_L2 = 53; // -- + optional uint32 POW_REACT_L3 = 54; // -- + optional float POW_KOEF = 55; // коэффициент мощности + optional uint32 POW_GEN_TOTAL = 56; // общая выработка электроэнергии + optional uint32 FUEL_LEVEL = 57; // текущий объём топлива + + optional uint32 SMS_REGS_0 = 60; // состояние регистра состояния 0 для SMS-оповещений (для отладки) + optional uint32 SMS_REGS_1 = 61; // состояние регистра состояния 1 для SMS-оповещений (для отладки) + optional uint32 SMS_REGS_2 = 62; // состояние регистра состояния 2 для SMS-оповещений (для отладки) + optional uint32 SMS_REGS_3 = 63; // состояние регистра состояния 3 для SMS-оповещений (для отладки) + optional uint32 SMS_REGS_4 = 64; // состояние регистра состояния 4 для SMS-оповещений (для отладки) + } + optional group FuelSensorModbus= 9 { // Данные о сторонних датчиках уровня топлива + optional float FuelLevel = 1; + optional float MedianLevel = 2; + optional uint32 LevelPercent = 3; + optional float FuelVolume = 4; + optional sint32 FuelTemp = 5; + optional float FuelWeight = 6; + optional float FuelDensity = 7; + optional sint32 VaporTemp = 8; + optional float VaporWeight = 9; + optional float LiquidWeight = 10; + repeated sint32 PointTemp = 11; + } + optional group WeightControl= 10 { // Данные о весовом контроле + repeated float AxelWeight = 1; + repeated float AxelLimit = 2; + optional float TotalWeight = 3; + optional float TotalWeightLimit = 4; + } + } + + optional group ICONDt = 10 { // данные ICON + optional bytes VehicleStatus = 1; //[24] строка статуса ТС. Сейчас от ICON передаётся 20 символов+NULL. [Hex2ASCII] + optional uint32 VehicleStatusID = 2; //[1] ID статуса ТС. [Hex2Dec] + optional uint32 VehicleStatusGroupID = 3; //[1] ID группы статусов ТС. Резерв. [Hex2Dec] + optional uint64 MsgID = 4; //[8] UID сообщения + optional uint32 MsgStatus = 5; //[4] флаг статуса сообщения, см CMDPBF.proto + optional uint32 StatDate = 6; //[4] Время/дата изменения статуса сообщения (в OmnicommTime) + optional bytes VehicleStatusPrev = 7; //[24] строка предыдущего статуса ТС. Сейчас от ICON передаётся 20 символов+NULL. [Hex2ASCII] + optional uint32 VehicleStatusFlags = 8; // флаг активности текущего статуса ТС (0x1 - активен, 0x0 - завершен) + } + optional group OBDDt_J1979 = 11 { // Данные шины CAN (протокол J1979) + // в формулах расчёта значений OBD используются обозначения A, B, C, D + // uint32 data = [D | C | B | A], где А - младший байт, D - старший байт + optional uint32 SID_0x01_PID_0x0D = 1;// Скорость ТС = A (km/h) - Vehicle Speed Sensor + optional uint32 SID_0x01_PID_0x31 = 2;// Пробег после сброса ошибок = (256 * A + B), (km) - Distance travelled since DTCs cleared + optional uint32 SID_0x01_PID_0x4E = 3;// Время работы двинателя после сброса ошибок = (A*256)+B (минуты) - Engine Run Time since diagnostic trouble codes cleare + optional uint32 SID_0x01_PID_0x42 = 4;// Напряжение борта, В = ((A*256) + B)/1000 (В) - Control module voltage + optional uint32 SID_0x01_PID_0x0C = 5;// Обороты = (256 * A + B) / 4 (rpm) - Engine RPM + optional uint32 SID_0x01_PID_0x2F = 6;// Объема топлива = (100 * A / 255) (%) - Fuel Level Input + optional uint32 SID_0x01_PID_0x5E = 7;// Среднее значение мгновенного расхода = (256 * A + B) *0,05 (L/h) - Engine Fuel Rate + // Терминал получает несколько значений мгновенного расхода по OBD, рассчитывает и отправляет среднее + optional uint32 SID_0x01_PID_0x5C = 8;// Температура масла = (A - 40) (°C)- Engine Oil Temperature + optional uint32 SID_0x01_PID_0x05 = 9;// Температура ОЖ = (A - 40) (°C) - Engine Coolant Temperature + optional uint32 SID_0x01_PID_0x01 = 10;// Статус неисправности Check Engine - Monitor status since DTCs cleared + /* Malfunction Indicator Lamp (MIL) Status: + Если A/бит 7 = 0, то ошибки нет + Если A/бит 7 = 1, то ошибка есть + */ + optional bytes SID_0x09_PID_0x02 = 11;// [18] VIN ТС = ASCII null-terminated string. Идут значащие символы, потом нулевой байт. Если перый байт нулувой, то строка пустая. + optional uint32 SID_0x01_PID_0x5E_quantity = 12; // Кол-во успешно полученных ответов при расчёте среднего значения мгновенного расхода (optional uint32 SID_0x01_PID_0x5E = 7) + } + optional group LOG = 16 { + repeated string Debug = 1; //[1024] Отладочный лог + optional uint32 LLSRefNum= 2; // признак наличия подключенных датчиков REF к терминалу – битовая маска. бит 0 соответсвует подключенному 1-ому датчику и т.д. + repeated uint32 LLSRefLevelBef= 3 [packed=true]; + repeated uint32 LLSRefLevelAfter= 4 [packed=true]; + repeated uint32 LLSRefKoef= 5 [packed=true]; + repeated uint32 LLSRefSens= 6 [packed=true]; + repeated uint32 LLSRefTemp= 7 [packed=true]; + } +}
\ No newline at end of file |