aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/traccar/protocol/UlbotechProtocolDecoder.java
blob: 7fec0bf8bbdf44caa64825c62eb5423983fa720b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
 * Copyright 2015 - 2018 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.helper.BitUtil;
import org.traccar.helper.Checksum;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.ObdDecoder;
import org.traccar.helper.Parser;
import org.traccar.helper.PatternBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.CellTower;
import org.traccar.model.Network;
import org.traccar.model.Position;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.regex.Pattern;

public class UlbotechProtocolDecoder extends BaseProtocolDecoder {

    public UlbotechProtocolDecoder(Protocol protocol) {
        super(protocol);
    }

    private static final short DATA_GPS = 0x01;
    private static final short DATA_LBS = 0x02;
    private static final short DATA_STATUS = 0x03;
    private static final short DATA_ODOMETER = 0x04;
    private static final short DATA_ADC = 0x05;
    private static final short DATA_GEOFENCE = 0x06;
    private static final short DATA_OBD2 = 0x07;
    private static final short DATA_FUEL = 0x08;
    private static final short DATA_OBD2_ALARM = 0x09;
    private static final short DATA_HARSH_DRIVER = 0x0A;
    private static final short DATA_CANBUS = 0x0B;
    private static final short DATA_J1708 = 0x0C;
    private static final short DATA_VIN = 0x0D;
    private static final short DATA_RFID = 0x0E;
    private static final short DATA_EVENT = 0x10;

    private void decodeObd(Position position, ByteBuf buf, int length) {

        int end = buf.readerIndex() + length;

        while (buf.readerIndex() < end) {
            int parameterLength = buf.getUnsignedByte(buf.readerIndex()) >> 4;
            int mode = buf.readUnsignedByte() & 0x0F;
            position.add(ObdDecoder.decode(mode, ByteBufUtil.hexDump(buf.readSlice(parameterLength - 1))));
        }
    }

    private void decodeJ1708(Position position, ByteBuf buf, int length) {

        int end = buf.readerIndex() + length;

        while (buf.readerIndex() < end) {
            int mark = buf.readUnsignedByte();
            int len = BitUtil.between(mark, 0, 6);
            int type = BitUtil.between(mark, 6, 8);
            int id = buf.readUnsignedByte();
            if (type == 3) {
                id += 256;
            }
            String value = ByteBufUtil.hexDump(buf.readSlice(len - 1));
            if (type == 2 || type == 3) {
                position.set("pid" + id, value);
            }
        }
    }

    private void decodeDriverBehavior(Position position, ByteBuf buf) {

        int value = buf.readUnsignedByte();

        if (BitUtil.check(value, 0)) {
            position.set("rapidAcceleration", true);
        }
        if (BitUtil.check(value, 1)) {
            position.set("roughBraking", true);
        }
        if (BitUtil.check(value, 2)) {
            position.set("harshCourse", true);
        }
        if (BitUtil.check(value, 3)) {
            position.set("noWarmUp", true);
        }
        if (BitUtil.check(value, 4)) {
            position.set("longIdle", true);
        }
        if (BitUtil.check(value, 5)) {
            position.set("fatigueDriving", true);
        }
        if (BitUtil.check(value, 6)) {
            position.set("roughTerrain", true);
        }
        if (BitUtil.check(value, 7)) {
            position.set("highRpm", true);
        }
    }

    private String decodeAlarm(int alarm) {
        if (BitUtil.check(alarm, 0)) {
            return Position.ALARM_POWER_OFF;
        }
        if (BitUtil.check(alarm, 1)) {
            return Position.ALARM_MOVEMENT;
        }
        if (BitUtil.check(alarm, 2)) {
            return Position.ALARM_OVERSPEED;
        }
        if (BitUtil.check(alarm, 4)) {
            return Position.ALARM_GEOFENCE;
        }
        if (BitUtil.check(alarm, 10)) {
            return Position.ALARM_SOS;
        }
        return null;
    }

    private void decodeAdc(Position position, ByteBuf buf, int length) {
        for (int i = 0; i < length / 2; i++) {
            int value = buf.readUnsignedShort();
            int id = BitUtil.from(value, 12);
            value = BitUtil.to(value, 12);
            switch (id) {
                case 0:
                    position.set(Position.KEY_POWER, value * (100 + 10) / 4096.0 - 10);
                    break;
                case 1:
                    position.set(Position.PREFIX_TEMP + 1, value * (125 + 55) / 4096.0 - 55);
                    break;
                case 2:
                    position.set(Position.KEY_BATTERY, value * (100 + 10) / 4096.0 - 10);
                    break;
                case 3:
                    position.set(Position.PREFIX_ADC + 1, value * (100 + 10) / 4096.0 - 10);
                    break;
                default:
                    position.set(Position.PREFIX_IO + id, value);
                    break;
            }
        }
    }

    private static final Pattern PATTERN = new PatternBuilder()
            .text("*TS")
            .number("dd,")                       // protocol version
            .number("(d{15}),")                  // device id
            .number("(dd)(dd)(dd)")              // time
            .number("(dd)(dd)(dd),")             // date
            .expression("([^#]+)")               // command
            .text("#")
            .compile();

    private Object decodeText(Channel channel, SocketAddress remoteAddress, String sentence) {

        Parser parser = new Parser(PATTERN, sentence);
        if (!parser.matches()) {
            return null;
        }

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
        if (deviceSession == null) {
            return null;
        }

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        DateBuilder dateBuilder = new DateBuilder()
                .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0))
                .setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));

        getLastLocation(position, dateBuilder.getDate());

        position.set(Position.KEY_RESULT, parser.next());

        return position;
    }

    private Object decodeBinary(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

        buf.readUnsignedByte(); // header
        buf.readUnsignedByte(); // version
        buf.readUnsignedByte(); // type

        String imei = ByteBufUtil.hexDump(buf.readSlice(8)).substring(1);

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
        if (deviceSession == null) {
            return null;
        }

        if (deviceSession.getTimeZone() == null) {
            deviceSession.setTimeZone(getTimeZone(deviceSession.getDeviceId()));
        }

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        long seconds = buf.readUnsignedInt() & 0x7fffffffL;
        seconds += 946684800L; // 2000-01-01 00:00
        seconds -= deviceSession.getTimeZone().getRawOffset() / 1000;
        Date time = new Date(seconds * 1000);

        boolean hasLocation = false;

        while (buf.readableBytes() > 3) {

            int type = buf.readUnsignedByte();
            int length = type == DATA_CANBUS ? buf.readUnsignedShort() : buf.readUnsignedByte();

            switch (type) {

                case DATA_GPS:
                    hasLocation = true;
                    position.setLatitude(buf.readInt() / 1000000.0);
                    position.setLongitude(buf.readInt() / 1000000.0);
                    position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort()));
                    position.setCourse(buf.readUnsignedShort());
                    int hdop = buf.readUnsignedShort();
                    position.setValid(hdop < 9999);
                    position.set(Position.KEY_HDOP, hdop * 0.01);
                    break;

                case DATA_LBS:
                    if (length == 11) {
                        position.setNetwork(new Network(CellTower.from(
                                buf.readUnsignedShort(), buf.readUnsignedShort(),
                                buf.readUnsignedShort(), buf.readUnsignedInt(), -buf.readUnsignedByte())));
                    } else {
                        position.setNetwork(new Network(CellTower.from(
                                buf.readUnsignedShort(), buf.readUnsignedShort(),
                                buf.readUnsignedShort(), buf.readUnsignedShort(), -buf.readUnsignedByte())));
                    }
                    if (length > 9 && length != 11) {
                        buf.skipBytes(length - 9);
                    }
                    break;

                case DATA_STATUS:
                    int status = buf.readUnsignedShort();
                    position.set(Position.KEY_IGNITION, BitUtil.check(status, 9));
                    position.set(Position.KEY_STATUS, status);
                    position.set(Position.KEY_ALARM, decodeAlarm(buf.readUnsignedShort()));
                    break;

                case DATA_ODOMETER:
                    position.set(Position.KEY_ODOMETER, buf.readUnsignedInt());
                    break;

                case DATA_ADC:
                    decodeAdc(position, buf, length);
                    break;

                case DATA_GEOFENCE:
                    position.set("geofenceIn", buf.readUnsignedInt());
                    position.set("geofenceAlarm", buf.readUnsignedInt());
                    break;

                case DATA_OBD2:
                    decodeObd(position, buf, length);
                    break;

                case DATA_FUEL:
                    position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedInt() / 10000.0);
                    break;

                case DATA_OBD2_ALARM:
                    decodeObd(position, buf, length);
                    break;

                case DATA_HARSH_DRIVER:
                    decodeDriverBehavior(position, buf);
                    break;

                case DATA_CANBUS:
                    position.set("can", ByteBufUtil.hexDump(buf.readSlice(length)));
                    break;

                case DATA_J1708:
                    decodeJ1708(position, buf, length);
                    break;

                case DATA_VIN:
                    position.set(Position.KEY_VIN, buf.readSlice(length).toString(StandardCharsets.US_ASCII));
                    break;

                case DATA_RFID:
                    position.set(Position.KEY_DRIVER_UNIQUE_ID,
                            buf.readSlice(length - 1).toString(StandardCharsets.US_ASCII));
                    position.set("authorized", buf.readUnsignedByte() != 0);
                    break;

                case DATA_EVENT:
                    position.set(Position.KEY_EVENT, buf.readUnsignedByte());
                    if (length > 1) {
                        position.set("eventMask", buf.readUnsignedInt());
                    }
                    break;

                default:
                    buf.skipBytes(length);
                    break;
            }
        }

        if (!hasLocation) {
            getLastLocation(position, time);
        } else {
            position.setTime(time);
        }

        return position;
    }

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        ByteBuf buf = (ByteBuf) msg;

        if (buf.getUnsignedByte(buf.readerIndex()) == 0xF8) {

            if (channel != null) {
                ByteBuf response = Unpooled.buffer();
                response.writeByte(0xF8);
                response.writeByte(DATA_GPS);
                response.writeByte(0xFE);
                response.writeShort(buf.getShort(response.writerIndex() - 1 - 2));
                response.writeShort(Checksum.crc16(Checksum.CRC16_XMODEM, response.nioBuffer(1, 4)));
                response.writeByte(0xF8);
                channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
            }

            return decodeBinary(channel, remoteAddress, buf);
        } else {

            if (channel != null) {
                channel.writeAndFlush(new NetworkMessage(Unpooled.copiedBuffer(String.format("*TS01,ACK:%04X#",
                        Checksum.crc16(Checksum.CRC16_XMODEM, buf.nioBuffer(1, buf.writerIndex() - 2))),
                        StandardCharsets.US_ASCII), remoteAddress));
            }

            return decodeText(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII));
        }
    }

}