aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/traccar/protocol/MeitrackProtocolDecoder.java
blob: e9e37d18a5acd1f6b5f3357eaeb1f44787e68709 (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
572
573
574
575
576
577
578
579
580
581
582
583
/*
 * Copyright 2012 - 2023 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.session.DeviceSession;
import org.traccar.NetworkMessage;
import org.traccar.Protocol;
import org.traccar.helper.Checksum;
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 org.traccar.model.WifiAccessPoint;

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

public class MeitrackProtocolDecoder extends BaseProtocolDecoder {

    private ByteBuf photo;

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

    private static final Pattern PATTERN = new PatternBuilder()
            .text("$$").expression(".")          // flag
            .number("d+,")                       // length
            .number("(d+),")                     // imei
            .number("xxx,")                      // command
            .number("d+,").optional()
            .number("(d+),")                     // event
            .number("(-?d+.d+),")                // latitude
            .number("(-?d+.d+),")                // longitude
            .number("(dd)(dd)(dd)")              // date (yymmdd)
            .number("(dd)(dd)(dd),")             // time (hhmmss)
            .number("([AV]),")                   // validity
            .number("(d+),")                     // satellites
            .number("(d+),")                     // rssi
            .number("(d+.?d*),")                 // speed
            .number("(d+),")                     // course
            .number("(d+.?d*),")                 // hdop
            .number("(-?d+),")                   // altitude
            .number("(d+),")                     // odometer
            .number("(d+),")                     // runtime
            .number("(d+)|")                     // mcc
            .number("(d+)|")                     // mnc
            .number("(x+)?|")                    // lac
            .number("(x+)?,")                    // cid
            .number("(xx)")                      // input
            .number("(xx),")                     // output
            .groupBegin()
            .number("(d+.d+)|")                  // battery
            .number("(d+.d+)|")                  // power
            .number("d+.d+|")                    // rtc voltage
            .number("d+.d+|")                    // mcu voltage
            .number("d+.d+,")                    // gps voltage
            .or()
            .number("(x+)?|")                    // adc1
            .number("(x+)?|")                    // adc2
            .number("(x+)?|")                    // adc3
            .number("(x+)|")                     // battery
            .number("(x+)?,")                    // power
            .groupEnd()
            .groupBegin()
            .expression("([^,]+)?,").optional()  // event specific
            .expression("[^,]*,")                // reserved
            .number("(d+)?,")                    // protocol
            .number("(x{4})?")                   // fuel
            .groupBegin()
            .number(",(x{6}(?:|x{6})*)?")        // temperature
            .groupBegin()
            .number(",(d+)")                     // data count
            .expression(",([^*]*)")              // data
            .groupEnd("?")
            .groupEnd("?")
            .or()
            .any()
            .groupEnd()
            .text("*")
            .number("xx")
            .text("\r\n").optional()
            .compile();

    private String decodeAlarm(int event) {
        return switch (event) {
            case 1 -> Position.ALARM_SOS;
            case 17 -> Position.ALARM_LOW_BATTERY;
            case 18 -> Position.ALARM_LOW_POWER;
            case 19 -> Position.ALARM_OVERSPEED;
            case 20 -> Position.ALARM_GEOFENCE_ENTER;
            case 21 -> Position.ALARM_GEOFENCE_EXIT;
            case 22 -> Position.ALARM_POWER_RESTORED;
            case 23 -> Position.ALARM_POWER_CUT;
            case 36 -> Position.ALARM_TOW;
            case 44 -> Position.ALARM_JAMMING;
            case 78 -> Position.ALARM_ACCIDENT;
            case 90, 91 -> Position.ALARM_CORNERING;
            case 129 -> Position.ALARM_BRAKING;
            case 130 -> Position.ALARM_ACCELERATION;
            case 135 -> Position.ALARM_FATIGUE_DRIVING;
            default -> null;
        };
    }

    private Position decodeRegular(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

        Parser parser = new Parser(PATTERN, buf.toString(StandardCharsets.US_ASCII));
        if (!parser.matches()) {
            return null;
        }

        Position position = new Position(getProtocolName());

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

        int event = parser.nextInt();
        position.set(Position.KEY_EVENT, event);
        position.set(Position.KEY_ALARM, decodeAlarm(event));

        position.setLatitude(parser.nextDouble());
        position.setLongitude(parser.nextDouble());

        position.setTime(parser.nextDateTime());

        position.setValid(parser.next().equals("A"));

        position.set(Position.KEY_SATELLITES, parser.nextInt());
        int rssi = parser.nextInt();

        position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble()));
        position.setCourse(parser.nextDouble());

        position.set(Position.KEY_HDOP, parser.nextDouble());

        position.setAltitude(parser.nextDouble());

        position.set(Position.KEY_ODOMETER, parser.nextInt());
        position.set("runtime", parser.next());

        int mcc = parser.nextInt();
        int mnc = parser.nextInt();
        int lac = parser.nextHexInt(0);
        int cid = parser.nextHexInt(0);
        if (mcc != 0 && mnc != 0) {
            position.setNetwork(new Network(CellTower.from(mcc, mnc, lac, cid, rssi)));
        }

        position.set(Position.KEY_INPUT, parser.nextHexInt());
        position.set(Position.KEY_OUTPUT, parser.nextHexInt());

        if (parser.hasNext(2)) {

            position.set(Position.KEY_BATTERY, parser.nextDouble());
            position.set(Position.KEY_POWER, parser.nextDouble());

        } else {

            for (int i = 1; i <= 3; i++) {
                position.set(Position.PREFIX_ADC + i, parser.nextHexInt());
            }

            switch (Objects.requireNonNullElse(getDeviceModel(deviceSession), "").toUpperCase()) {
                case "MVT340", "MVT380" -> {
                    position.set(Position.KEY_BATTERY, parser.nextHexInt() * 3.0 * 2.0 / 1024.0);
                    position.set(Position.KEY_POWER, parser.nextHexInt(0) * 3.0 * 16.0 / 1024.0);
                }
                case "MT90" -> {
                    position.set(Position.KEY_BATTERY, parser.nextHexInt() * 3.3 * 2.0 / 4096.0);
                    position.set(Position.KEY_POWER, parser.nextHexInt(0));
                }
                case "T1", "T3", "MVT100", "MVT600", "MVT800", "TC68", "TC68S" -> {
                    position.set(Position.KEY_BATTERY, parser.nextHexInt() * 3.3 * 2.0 / 4096.0);
                    position.set(Position.KEY_POWER, parser.nextHexInt(0) * 3.3 * 16.0 / 4096.0);
                }
                default -> {
                    position.set(Position.KEY_BATTERY, parser.nextHexInt() / 100.0);
                    position.set(Position.KEY_POWER, parser.nextHexInt(0) / 100.0);
                }
            }

        }

        String eventData = parser.next();
        if (eventData != null && !eventData.isEmpty()) {
            switch (event) {
                case 37 -> position.set(Position.KEY_DRIVER_UNIQUE_ID, eventData);
                default -> position.set("eventData", eventData);
            }
        }

        int protocol = parser.nextInt(0);

        if (parser.hasNext()) {
            String fuel = parser.next();
            position.set(Position.KEY_FUEL_LEVEL,
                    Integer.parseInt(fuel.substring(0, 2), 16) + Integer.parseInt(fuel.substring(2), 16) * 0.01);
        }

        if (parser.hasNext()) {
            for (String temp : parser.next().split("\\|")) {
                int index = Integer.parseInt(temp.substring(0, 2), 16);
                if (protocol >= 3) {
                    double value = (short) Integer.parseInt(temp.substring(2), 16);
                    position.set(Position.PREFIX_TEMP + index, value * 0.01);
                } else {
                    double value = Byte.parseByte(temp.substring(2, 4), 16);
                    value += (value < 0 ? -0.01 : 0.01) * Integer.parseInt(temp.substring(4), 16);
                    position.set(Position.PREFIX_TEMP + index, value);
                }
            }
        }

        if (parser.hasNext(2)) {
            parser.nextInt(); // count
            decodeDataFields(position, parser.next().split(","));
        }

        return position;
    }

    private void decodeDataFields(Position position, String[] values) {

        if (values.length > 1 && !values[1].isEmpty()) {
            position.set("tempData", values[1]);
        }

        if (values.length > 5 && !values[5].isEmpty()) {
            String[] data = values[5].split("\\|");
            boolean started = data[0].charAt(1) == '0';
            position.set("taximeterOn", started);
            position.set("taximeterStart", data[1]);
            if (data.length > 2) {
                position.set("taximeterEnd", data[2]);
                position.set("taximeterDistance", Integer.parseInt(data[3]));
                position.set("taximeterFare", Integer.parseInt(data[4]));
                position.set("taximeterTrip", data[5]);
                position.set("taximeterWait", data[6]);
            }
        }

    }

    private List<Position> decodeBinaryC(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {
        List<Position> positions = new LinkedList<>();

        String flag = buf.toString(2, 1, StandardCharsets.US_ASCII);
        int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');

        String imei = buf.toString(index + 1, 15, StandardCharsets.US_ASCII);
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
        if (deviceSession == null) {
            return null;
        }

        buf.skipBytes(index + 1 + 15 + 1 + 3 + 1 + 2 + 2 + 4);

        while (buf.readableBytes() >= 0x34) {

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

            position.set(Position.KEY_EVENT, buf.readUnsignedByte());

            position.setLatitude(buf.readIntLE() * 0.000001);
            position.setLongitude(buf.readIntLE() * 0.000001);

            position.setTime(new Date((946684800 + buf.readUnsignedIntLE()) * 1000)); // 946684800 = 2000-01-01

            position.setValid(buf.readUnsignedByte() == 1);

            position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
            int rssi = buf.readUnsignedByte();

            position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShortLE()));
            position.setCourse(buf.readUnsignedShortLE());

            position.set(Position.KEY_HDOP, buf.readUnsignedShortLE() * 0.1);

            position.setAltitude(buf.readUnsignedShortLE());

            position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
            position.set("runtime", buf.readUnsignedIntLE());

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

            position.set(Position.KEY_STATUS, buf.readUnsignedShortLE());

            position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE());
            position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() * 0.01);
            position.set(Position.KEY_POWER, buf.readUnsignedShortLE());

            buf.readUnsignedIntLE(); // geo-fence

            positions.add(position);
        }

        if (channel != null) {
            StringBuilder command = new StringBuilder("@@");
            command.append(flag).append(27 + positions.size() / 10).append(",");
            command.append(imei).append(",CCC,").append(positions.size()).append("*");
            command.append(Checksum.sum(command.toString()));
            command.append("\r\n");
            channel.writeAndFlush(new NetworkMessage(command.toString(), remoteAddress));
        }

        return positions;
    }

    private List<Position> decodeBinaryE(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {
        List<Position> positions = new LinkedList<>();

        buf.readerIndex(buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',') + 1);
        String imei = buf.readSlice(15).toString(StandardCharsets.US_ASCII);
        buf.skipBytes(1 + 3 + 1);

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

        buf.readUnsignedIntLE(); // remaining cache
        int count = buf.readUnsignedShortLE();

        for (int i = 0; i < count; i++) {
            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            Network network = new Network();

            buf.readUnsignedShortLE(); // length
            buf.readUnsignedShortLE(); // index

            int paramCount = buf.readUnsignedByte();
            for (int j = 0; j < paramCount; j++) {
                boolean extension = buf.getUnsignedByte(buf.readerIndex()) == 0xFE;
                int id = extension ? buf.readUnsignedShort() : buf.readUnsignedByte();
                switch (id) {
                    case 0x01 -> position.set(Position.KEY_EVENT, buf.readUnsignedByte());
                    case 0x05 -> position.setValid(buf.readUnsignedByte() > 0);
                    case 0x06 -> position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
                    case 0x07 -> position.set(Position.KEY_RSSI, buf.readUnsignedByte());
                    case 0x14 -> position.set(Position.KEY_OUTPUT, buf.readUnsignedByte());
                    case 0x15 -> position.set(Position.KEY_INPUT, buf.readUnsignedByte());
                    case 0x47 -> {
                        int lockState = buf.readUnsignedByte();
                        if (lockState > 0) {
                            position.set(Position.KEY_LOCK, lockState == 2);
                        }
                    }
                    case 0x97 -> position.set(Position.KEY_THROTTLE, buf.readUnsignedByte());
                    case 0x9D -> position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedByte());
                    case 0xFE69 -> position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte());
                    default -> buf.readUnsignedByte();
                }
            }

            paramCount = buf.readUnsignedByte();
            for (int j = 0; j < paramCount; j++) {
                boolean extension = buf.getUnsignedByte(buf.readerIndex()) == 0xFE;
                int id = extension ? buf.readUnsignedShort() : buf.readUnsignedByte();
                switch (id) {
                    case 0x08 -> position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShortLE()));
                    case 0x09 -> position.setCourse(buf.readUnsignedShortLE());
                    case 0x0A -> position.set(Position.KEY_HDOP, buf.readUnsignedShortLE());
                    case 0x0B -> position.setAltitude(buf.readShortLE());
                    case 0x16 -> position.set(Position.PREFIX_ADC + 1, buf.readUnsignedShortLE() * 0.01);
                    case 0x17 -> position.set(Position.PREFIX_ADC + 2, buf.readUnsignedShortLE() * 0.01);
                    case 0x19 -> position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() * 0.01);
                    case 0x1A -> position.set(Position.KEY_POWER, buf.readUnsignedShortLE() * 0.01);
                    case 0x29 -> position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedShortLE() * 0.01);
                    case 0x40 -> position.set(Position.KEY_EVENT, buf.readUnsignedShortLE());
                    case 0x91, 0x92 -> position.set(Position.KEY_OBD_SPEED, buf.readUnsignedShortLE());
                    case 0x98 -> position.set(Position.KEY_FUEL_USED, buf.readUnsignedShortLE());
                    case 0x99 -> position.set(Position.KEY_RPM, buf.readUnsignedShortLE());
                    case 0x9C -> position.set(Position.KEY_COOLANT_TEMP, buf.readUnsignedShortLE());
                    case 0x9F -> position.set(Position.PREFIX_TEMP + 1, buf.readUnsignedShortLE());
                    case 0xC9 -> position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedShortLE());
                    default -> buf.readUnsignedShortLE();
                }
            }

            paramCount = buf.readUnsignedByte();
            for (int j = 0; j < paramCount; j++) {
                boolean extension = buf.getUnsignedByte(buf.readerIndex()) == 0xFE;
                int id = extension ? buf.readUnsignedShort() : buf.readUnsignedByte();
                switch (id) {
                    case 0x02 -> position.setLatitude(buf.readIntLE() * 0.000001);
                    case 0x03 -> position.setLongitude(buf.readIntLE() * 0.000001);
                    case 0x04 -> position.setTime(new Date((946684800 + buf.readUnsignedIntLE()) * 1000)); // 2000-01-01
                    case 0x0C -> position.set(Position.KEY_ODOMETER, buf.readUnsignedIntLE());
                    case 0x0D -> position.set("runtime", buf.readUnsignedIntLE());
                    case 0x25 -> position.set(Position.KEY_DRIVER_UNIQUE_ID, String.valueOf(buf.readUnsignedIntLE()));
                    case 0x9B -> position.set(Position.KEY_OBD_ODOMETER, buf.readUnsignedIntLE());
                    case 0xA0 -> position.set(Position.KEY_FUEL_USED, buf.readUnsignedIntLE() * 0.001);
                    case 0xA2 -> position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedIntLE() * 0.01);
                    case 0xFEF4 -> position.set(Position.KEY_HOURS, buf.readUnsignedIntLE() * 60000);
                    default -> buf.readUnsignedIntLE();
                }
            }

            paramCount = buf.readUnsignedByte();
            for (int j = 0; j < paramCount; j++) {
                boolean extension = buf.getUnsignedByte(buf.readerIndex()) == 0xFE;
                int id = extension ? buf.readUnsignedShort() : buf.readUnsignedByte();
                int length = buf.readUnsignedByte();
                switch (id) {
                    case 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25 -> {
                        String wifiMac = ByteBufUtil.hexDump(buf.readSlice(6)).replaceAll("(..)", "$1:");
                        network.addWifiAccessPoint(WifiAccessPoint.from(
                                wifiMac.substring(0, wifiMac.length() - 1), buf.readShortLE()));
                    }
                    case 0x0E, 0x0F, 0x10, 0x12, 0x13 -> {
                        network.addCellTower(CellTower.from(
                                buf.readUnsignedShortLE(), buf.readUnsignedShortLE(),
                                buf.readUnsignedShortLE(), buf.readUnsignedIntLE(), buf.readShortLE()));
                    }
                    case 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31 -> {
                        buf.readUnsignedByte(); // label
                        position.set(Position.PREFIX_TEMP + (id - 0x2A), buf.readShortLE() * 0.01);
                    }
                    case 0x4B -> buf.skipBytes(length); // network information
                    case 0xFE31 -> {
                        buf.readUnsignedByte(); // alarm protocol
                        buf.readUnsignedByte(); // alarm type
                        buf.skipBytes(length - 2);
                    }
                    case 0xFE73 -> {
                        buf.readUnsignedByte(); // version
                        position.set(
                                "tagName",
                                buf.readCharSequence(buf.readUnsignedByte(), StandardCharsets.US_ASCII).toString());
                        buf.skipBytes(6); // mac
                        position.set("tagBattery", buf.readUnsignedByte());
                        position.set("tagTemp", buf.readUnsignedShortLE() / 256.0);
                        position.set("tagHumidity", buf.readUnsignedShortLE() / 256.0);
                        buf.readUnsignedShortLE(); // high temperature threshold
                        buf.readUnsignedShortLE(); // low temperature threshold
                        buf.readUnsignedShortLE(); // high humidity threshold
                        buf.readUnsignedShortLE(); // low humidity threshold
                    }
                    case 0xFEA8 -> {
                        for (int k = 1; k <= 3; k++) {
                            if (buf.readUnsignedByte() > 0) {
                                String key = k == 1 ? Position.KEY_BATTERY_LEVEL : "battery" + k + "Level";
                                position.set(key, buf.readUnsignedByte());
                            } else {
                                buf.readUnsignedByte();
                            }
                        }
                        buf.readUnsignedByte(); // battery alert
                    }
                    default -> buf.skipBytes(length);
                }
            }

            if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) {
                position.setNetwork(network);
            }
            positions.add(position);
        }

        return positions;
    }

    private void requestPhotoPacket(Channel channel, SocketAddress remoteAddress, String imei, String file, int index) {
        if (channel != null) {
            String content = "D00," + file + "," + index;
            int length = 1 + imei.length() + 1 + content.length() + 5;
            String response = String.format("@@O%02d,%s,%s*", length, imei, content);
            response += Checksum.sum(response) + "\r\n";
            channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
        }
    }

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

        ByteBuf buf = (ByteBuf) msg;

        int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) ',');
        String imei = buf.toString(index + 1, 15, StandardCharsets.US_ASCII);
        index = buf.indexOf(index + 1, buf.writerIndex(), (byte) ',');
        String type = buf.toString(index + 1, 3, StandardCharsets.US_ASCII);

        return switch (type) {
            case "AAC" -> {
                if (channel != null) {
                    String response = String.format("@@z27,%s,AAC,1*", imei);
                    response += Checksum.sum(response) + "\r\n";
                    channel.writeAndFlush(new NetworkMessage(response, remoteAddress));
                }
                yield null;
            }
            case "D00" -> {
                if (photo == null) {
                    photo = Unpooled.buffer();
                }

                index = index + 1 + type.length() + 1;
                int endIndex = buf.indexOf(index, buf.writerIndex(), (byte) ',');
                String file = buf.toString(index, endIndex - index, StandardCharsets.US_ASCII);
                index = endIndex + 1;
                endIndex = buf.indexOf(index, buf.writerIndex(), (byte) ',');
                int total = Integer.parseInt(buf.toString(index, endIndex - index, StandardCharsets.US_ASCII));
                index = endIndex + 1;
                endIndex = buf.indexOf(index, buf.writerIndex(), (byte) ',');
                int current = Integer.parseInt(buf.toString(index, endIndex - index, StandardCharsets.US_ASCII));

                buf.readerIndex(endIndex + 1);
                photo.writeBytes(buf.readSlice(buf.readableBytes() - 1 - 2 - 2));

                if (current == total - 1) {
                    Position position = new Position(getProtocolName());
                    position.setDeviceId(getDeviceSession(channel, remoteAddress, imei).getDeviceId());

                    getLastLocation(position, null);

                    position.set(Position.KEY_IMAGE, writeMediaFile(imei, photo, "jpg"));
                    photo.release();
                    photo = null;

                    yield position;
                } else {
                    if ((current + 1) % 8 == 0) {
                        requestPhotoPacket(channel, remoteAddress, imei, file, current + 1);
                    }
                    yield null;
                }
            }
            case "D03" -> {
                photo = Unpooled.buffer();
                requestPhotoPacket(channel, remoteAddress, imei, "camera_picture.jpg", 0);
                yield null;
            }
            case "D82" -> {
                Position position = new Position(getProtocolName());
                position.setDeviceId(getDeviceSession(channel, remoteAddress, imei).getDeviceId());
                getLastLocation(position, null);
                String result = buf.toString(index + 1, buf.writerIndex() - index - 4, StandardCharsets.US_ASCII);
                position.set(Position.KEY_RESULT, result);
                yield position;
            }
            case "CCC" -> decodeBinaryC(channel, remoteAddress, buf);
            case "CCE" -> decodeBinaryE(channel, remoteAddress, buf);
            default -> decodeRegular(channel, remoteAddress, buf);
        };
    }

}