aboutsummaryrefslogtreecommitdiff
path: root/src/org/traccar/protocol/CastelProtocolDecoder.java
blob: 1be66b17dc336ef35e69a6d7109928907276dc28 (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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*
 * 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.helper.Checksum;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.ObdDecoder;
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.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CastelProtocolDecoder extends BaseProtocolDecoder {

    private static final Map<Integer, Integer> PID_LENGTH_MAP = new HashMap<>();

    static {
        int[] l1 = {
            0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0b, 0x0d,
            0x0e, 0x0f, 0x11, 0x12, 0x13, 0x1c, 0x1d, 0x1e, 0x2c,
            0x2d, 0x2e, 0x2f, 0x30, 0x33, 0x43, 0x45, 0x46,
            0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x51, 0x52,
            0x5a
        };
        int[] l2 = {
            0x02, 0x03, 0x0a, 0x0c, 0x10, 0x14, 0x15, 0x16,
            0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1f, 0x21, 0x22,
            0x23, 0x31, 0x32, 0x3c, 0x3d, 0x3e, 0x3f, 0x42,
            0x44, 0x4d, 0x4e, 0x50, 0x53, 0x54, 0x55, 0x56,
            0x57, 0x58, 0x59
        };
        int[] l4 = {
            0x00, 0x01, 0x20, 0x24, 0x25, 0x26, 0x27, 0x28,
            0x29, 0x2a, 0x2b, 0x34, 0x35, 0x36, 0x37, 0x38,
            0x39, 0x3a, 0x3b, 0x40, 0x41, 0x4f
        };
        for (int i : l1) {
            PID_LENGTH_MAP.put(i, 1);
        }
        for (int i : l2) {
            PID_LENGTH_MAP.put(i, 2);
        }
        for (int i : l4) {
            PID_LENGTH_MAP.put(i, 4);
        }
    }

    public CastelProtocolDecoder(CastelProtocol protocol) {
        super(protocol);
    }

    public static final short MSG_SC_LOGIN = 0x1001;
    public static final short MSG_SC_LOGIN_RESPONSE = (short) 0x9001;
    public static final short MSG_SC_LOGOUT = 0x1002;
    public static final short MSG_SC_HEARTBEAT = 0x1003;
    public static final short MSG_SC_HEARTBEAT_RESPONSE = (short) 0x9003;
    public static final short MSG_SC_GPS = 0x4001;
    public static final short MSG_SC_PID_DATA = 0x4002;
    public static final short MSG_SC_SUPPORTED_PID = 0x4004;
    public static final short MSG_SC_OBD_DATA = 0x4005;
    public static final short MSG_SC_DTCS_PASSENGER = 0x4006;
    public static final short MSG_SC_DTCS_COMMERCIAL = 0x400B;
    public static final short MSG_SC_ALARM = 0x4007;
    public static final short MSG_SC_CELL = 0x4008;
    public static final short MSG_SC_GPS_SLEEP = 0x4009;
    public static final short MSG_SC_FUEL = 0x400E;
    public static final short MSG_SC_AGPS_REQUEST = 0x5101;
    public static final short MSG_SC_QUERY_RESPONSE = (short) 0xA002;
    public static final short MSG_SC_CURRENT_LOCATION = (short) 0xB001;

    public static final short MSG_CC_LOGIN = 0x4001;
    public static final short MSG_CC_LOGIN_RESPONSE = (short) 0x8001;
    public static final short MSG_CC_HEARTBEAT = 0x4206;
    public static final short MSG_CC_PETROL_CONTROL = 0x4583;
    public static final short MSG_CC_HEARTBEAT_RESPONSE = (short) 0x8206;

    private Position readPosition(DeviceSession deviceSession, ByteBuf buf) {

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

        DateBuilder dateBuilder = new DateBuilder()
                .setDateReverse(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte())
                .setTime(buf.readUnsignedByte(), buf.readUnsignedByte(), buf.readUnsignedByte());
        position.setTime(dateBuilder.getDate());

        double lat = buf.readUnsignedIntLE() / 3600000.0;
        double lon = buf.readUnsignedIntLE() / 3600000.0;
        position.setSpeed(UnitsConverter.knotsFromCps(buf.readUnsignedShortLE()));
        position.setCourse(buf.readUnsignedShortLE() * 0.1);

        int flags = buf.readUnsignedByte();
        if ((flags & 0x02) == 0) {
            lat = -lat;
        }
        if ((flags & 0x01) == 0) {
            lon = -lon;
        }
        position.setLatitude(lat);
        position.setLongitude(lon);
        position.setValid((flags & 0x0C) > 0);
        position.set(Position.KEY_SATELLITES, flags >> 4);

        return position;
    }

    private Position createPosition(DeviceSession deviceSession) {

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

        getLastLocation(position, null);

        return position;
    }

    private void decodeObd(Position position, ByteBuf buf, boolean groups) {

        int count = buf.readUnsignedByte();

        int[] pids = new int[count];
        for (int i = 0; i < count; i++) {
            pids[i] = buf.readUnsignedShortLE() & 0xff;
        }

        if (groups) {
            buf.readUnsignedByte(); // group count
            buf.readUnsignedByte(); // group size
        }

        for (int i = 0; i < count; i++) {
            int value;
            switch (PID_LENGTH_MAP.get(pids[i])) {
                case 1:
                    value = buf.readUnsignedByte();
                    break;
                case 2:
                    value = buf.readUnsignedShortLE();
                    break;
                case 4:
                    value = buf.readIntLE();
                    break;
                default:
                    value = 0;
                    break;
            }
            position.add(ObdDecoder.decodeData(pids[i], value, false));
        }
    }

    private void decodeStat(Position position, ByteBuf buf) {

        buf.readUnsignedIntLE(); // ACC ON time
        buf.readUnsignedIntLE(); // UTC time
        position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
        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());
        buf.skipBytes(8);
    }

    private void sendResponse(
            Channel channel, SocketAddress remoteAddress,
            int version, ByteBuf id, short type, ByteBuf content) {

        if (channel != null) {
            int length = 2 + 2 + 1 + id.readableBytes() + 2 + 2 + 2;
            if (content != null) {
                length += content.readableBytes();
            }

            ByteBuf response = Unpooled.buffer(length);
            response.writeByte('@'); response.writeByte('@');
            response.writeShortLE(length);
            response.writeByte(version);
            response.writeBytes(id);
            response.writeShort(type);
            if (content != null) {
                response.writeBytes(content);
            }
            response.writeShortLE(
                    Checksum.crc16(Checksum.CRC16_X25, response.nioBuffer(0, response.writerIndex())));
            response.writeByte(0x0D); response.writeByte(0x0A);
            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }
    }

    private void sendResponse(
            Channel channel, SocketAddress remoteAddress, ByteBuf id, short type) {

        if (channel != null) {
            int length = 2 + 2 + id.readableBytes() + 2 + 4 + 8 + 2 + 2;

            ByteBuf response = Unpooled.buffer(length);
            response.writeByte('@'); response.writeByte('@');
            response.writeShortLE(length);
            response.writeBytes(id);
            response.writeShort(type);
            response.writeIntLE(0);
            for (int i = 0; i < 8; i++) {
                response.writeByte(0xff);
            }
            response.writeShortLE(
                    Checksum.crc16(Checksum.CRC16_X25, response.nioBuffer(0, response.writerIndex())));
            response.writeByte(0x0D); response.writeByte(0x0A);
            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }
    }

    private void decodeAlarm(Position position, int alarm) {
        switch (alarm) {
            case 0x01:
                position.set(Position.KEY_ALARM, Position.ALARM_OVERSPEED);
                break;
            case 0x02:
                position.set(Position.KEY_ALARM, Position.ALARM_LOW_POWER);
                break;
            case 0x03:
                position.set(Position.KEY_ALARM, Position.ALARM_TEMPERATURE);
                break;
            case 0x04:
                position.set(Position.KEY_ALARM, Position.ALARM_ACCELERATION);
                break;
            case 0x05:
                position.set(Position.KEY_ALARM, Position.ALARM_BRAKING);
                break;
            case 0x06:
                position.set(Position.KEY_ALARM, Position.ALARM_IDLE);
                break;
            case 0x07:
                position.set(Position.KEY_ALARM, Position.ALARM_TOW);
                break;
            case 0x08:
                position.set(Position.KEY_ALARM, Position.ALARM_HIGH_RPM);
                break;
            case 0x09:
                position.set(Position.KEY_ALARM, Position.ALARM_POWER_ON);
                break;
            case 0x0B:
                position.set(Position.KEY_ALARM, Position.ALARM_LANE_CHANGE);
                break;
            case 0x0C:
                position.set(Position.KEY_ALARM, Position.ALARM_CORNERING);
                break;
            case 0x0E:
                position.set(Position.KEY_ALARM, Position.ALARM_POWER_OFF);
                break;
            case 0x16:
                position.set(Position.KEY_IGNITION, true);
                break;
            case 0x17:
                position.set(Position.KEY_IGNITION, false);
                break;
            default:
                break;
        }
    }

    private Object decodeSc(
            Channel channel, SocketAddress remoteAddress, ByteBuf buf,
            int version, ByteBuf id, short type, DeviceSession deviceSession) {

        if (type == MSG_SC_HEARTBEAT) {

            sendResponse(channel, remoteAddress, version, id, MSG_SC_HEARTBEAT_RESPONSE, null);

        } else if (type == MSG_SC_LOGIN || type == MSG_SC_LOGOUT || type == MSG_SC_GPS
                || type == MSG_SC_ALARM || type == MSG_SC_CURRENT_LOCATION || type == MSG_SC_FUEL) {

            if (type == MSG_SC_LOGIN) {
                ByteBuf response = Unpooled.buffer(10); // TODO ref count
                response.writeIntLE(0xFFFFFFFF);
                response.writeShortLE(0);
                response.writeIntLE((int) (System.currentTimeMillis() / 1000));
                sendResponse(channel, remoteAddress, version, id, MSG_SC_LOGIN_RESPONSE, response);
            }

            if (type == MSG_SC_GPS) {
                buf.readUnsignedByte(); // historical
            } else if (type == MSG_SC_ALARM) {
                buf.readUnsignedIntLE(); // alarm
            } else if (type == MSG_SC_CURRENT_LOCATION) {
                buf.readUnsignedShortLE();
            }

            buf.readUnsignedIntLE(); // ACC ON time
            buf.readUnsignedIntLE(); // UTC time
            long odometer = buf.readUnsignedIntLE();
            long tripOdometer = buf.readUnsignedIntLE();
            long fuelConsumption = buf.readUnsignedIntLE();
            buf.readUnsignedShortLE(); // current fuel consumption
            long status = buf.readUnsignedIntLE();
            buf.skipBytes(8);

            int count = buf.readUnsignedByte();

            List<Position> positions = new LinkedList<>();

            for (int i = 0; i < count; i++) {
                Position position = readPosition(deviceSession, buf);
                position.set(Position.KEY_ODOMETER, odometer);
                position.set(Position.KEY_ODOMETER_TRIP, tripOdometer);
                position.set(Position.KEY_FUEL_CONSUMPTION, fuelConsumption);
                position.set(Position.KEY_STATUS, status);
                positions.add(position);
            }

            if (type == MSG_SC_ALARM) {
                int alarmCount = buf.readUnsignedByte();
                for (int i = 0; i < alarmCount; i++) {
                    if (buf.readUnsignedByte() != 0) {
                        int alarm = buf.readUnsignedByte();
                        for (Position position : positions) {
                            decodeAlarm(position, alarm);
                        }
                        buf.readUnsignedShortLE(); // description
                        buf.readUnsignedShortLE(); // threshold
                    }
                }
            } else if (type == MSG_SC_FUEL) {
                for (Position position : positions) {
                    position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE());
                }
            }

            if (!positions.isEmpty()) {
                return positions;
            }

        } else if (type == MSG_SC_GPS_SLEEP) {

            buf.readUnsignedIntLE(); // device time

            return readPosition(deviceSession, buf);

        } else if (type == MSG_SC_AGPS_REQUEST) {

            return readPosition(deviceSession, buf);

        } else if (type == MSG_SC_PID_DATA) {

            Position position = createPosition(deviceSession);

            decodeStat(position, buf);

            buf.readUnsignedShortLE(); // sample rate
            decodeObd(position, buf, true);

            return position;

        } else if (type == MSG_SC_DTCS_PASSENGER) {

            Position position = createPosition(deviceSession);

            decodeStat(position, buf);

            buf.readUnsignedByte(); // flag
            position.add(ObdDecoder.decodeCodes(ByteBufUtil.hexDump(buf.readSlice(buf.readUnsignedByte()))));

            return position;

        } else if (type == MSG_SC_OBD_DATA) {

            Position position = createPosition(deviceSession);

            decodeStat(position, buf);

            buf.readUnsignedByte(); // flag
            decodeObd(position, buf, false);

            return position;

        } else if (type == MSG_SC_CELL) {

            Position position = createPosition(deviceSession);

            decodeStat(position, buf);

            position.setNetwork(new Network(
                    CellTower.fromLacCid(buf.readUnsignedShortLE(), buf.readUnsignedShortLE())));

            return position;

        } else if (type == MSG_SC_QUERY_RESPONSE) {

            Position position = createPosition(deviceSession);

            buf.readUnsignedShortLE(); // index
            buf.readUnsignedByte(); // response count
            buf.readUnsignedByte(); // response index

            int failureCount = buf.readUnsignedByte();
            for (int i = 0; i < failureCount; i++) {
                buf.readUnsignedShortLE(); // tag
            }

            int successCount = buf.readUnsignedByte();
            for (int i = 0; i < successCount; i++) {
                buf.readUnsignedShortLE(); // tag
                position.set(Position.KEY_RESULT,
                        buf.readSlice(buf.readUnsignedShortLE()).toString(StandardCharsets.US_ASCII));
            }

            return position;

        }

        return null;
    }

    private Object decodeCc(
            Channel channel, SocketAddress remoteAddress, ByteBuf buf,
            int version, ByteBuf id, short type, DeviceSession deviceSession) {

        if (type == MSG_CC_HEARTBEAT) {

            sendResponse(channel, remoteAddress, version, id, MSG_CC_HEARTBEAT_RESPONSE, null);

            buf.readUnsignedByte(); // 0x01 for history
            int count = buf.readUnsignedByte();

            List<Position> positions = new LinkedList<>();

            for (int i = 0; i < count; i++) {
                Position position = readPosition(deviceSession, buf);

                position.set(Position.KEY_STATUS, buf.readUnsignedIntLE());
                position.set(Position.KEY_BATTERY, buf.readUnsignedByte());
                position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());

                buf.readUnsignedByte(); // geo-fencing id
                buf.readUnsignedByte(); // geo-fencing flags
                buf.readUnsignedByte(); // additional flags

                position.setNetwork(new Network(
                        CellTower.fromLacCid(buf.readUnsignedShortLE(), buf.readUnsignedShortLE())));

                positions.add(position);
            }

            return positions;

        } else if (type == MSG_CC_LOGIN) {

            sendResponse(channel, remoteAddress, version, id, MSG_CC_LOGIN_RESPONSE, null);

            Position position = readPosition(deviceSession, buf);

            position.set(Position.KEY_STATUS, buf.readUnsignedIntLE());
            position.set(Position.KEY_BATTERY, buf.readUnsignedByte());
            position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());

            buf.readUnsignedByte(); // geo-fencing id
            buf.readUnsignedByte(); // geo-fencing flags
            buf.readUnsignedByte(); // additional flags

            // GSM_CELL_CODE
            // STR_Z - firmware version
            // STR_Z - hardware version

            return position;

        }

        return null;
    }

    private Object decodeMpip(
            Channel channel, SocketAddress remoteAddress, ByteBuf buf,
            int version, ByteBuf id, short type, DeviceSession deviceSession) {

        if (type == 0x4001) {

            sendResponse(channel, remoteAddress, version, id, (short) type, null);

            return readPosition(deviceSession, buf);

        } else if (type == 0x2001) {

            sendResponse(channel, remoteAddress, id, (short) 0x1001);

            buf.readUnsignedIntLE(); // index
            buf.readUnsignedIntLE(); // unix time
            buf.readUnsignedByte();

            return readPosition(deviceSession, buf);

        } else if (type == 0x4201 || type == 0x4202 || type == 0x4206) {

            return readPosition(deviceSession, buf);

        } else if (type == 0x4204) {

            List<Position> positions = new LinkedList<>();

            for (int i = 0; i < 8; i++) {
                Position position = readPosition(deviceSession, buf);
                buf.skipBytes(31);
                positions.add(position);
            }

            return positions;

        }

        return null;
    }

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

        ByteBuf buf = (ByteBuf) msg;

        int header = buf.readUnsignedShortLE();
        buf.readUnsignedShortLE(); // length

        int version = -1;
        if (header == 0x4040) {
            version = buf.readUnsignedByte();
        }

        ByteBuf id = buf.readSlice(20);
        short type = buf.readShort();

        DeviceSession deviceSession = getDeviceSession(
                channel, remoteAddress, id.toString(StandardCharsets.US_ASCII).trim());
        if (deviceSession == null) {
            return null;
        }

        switch (version) {
            case -1:
                return decodeMpip(channel, remoteAddress, buf, version, id, type, deviceSession);
            case 3:
            case 4:
                return decodeSc(channel, remoteAddress, buf, version, id, type, deviceSession);
            default:
                return decodeCc(channel, remoteAddress, buf, version, id, type, deviceSession);
        }
    }

}