aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java
blob: 51f06a80115ed5772a1f5096e3a72188e1888f20 (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
/*
 * Copyright 2012 - 2022 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.config.Keys;
import org.traccar.helper.model.AttributeUtil;
import org.traccar.session.DeviceSession;
import org.traccar.NetworkMessage;
import org.traccar.Protocol;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.Parser;
import org.traccar.helper.PatternBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.Position;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.DatagramChannel;
import java.util.Date;
import java.util.regex.Pattern;

public class T55ProtocolDecoder extends BaseProtocolDecoder {

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

    private static final Pattern PATTERN_GPRMC = new PatternBuilder()
            .text("$GPRMC,")
            .number("(dd)(dd)(dd).?d*,")         // time (hhmmss)
            .expression("([AV]),")               // validity
            .number("(dd)(dd.d+),")              // latitude
            .expression("([NS]),")
            .number("(d{2,3})(dd.d+),")          // longitude
            .expression("([EW]),")
            .number("(d+.?d*)?,")                // speed
            .number("(d+.?d*)?,")                // course
            .number("(dd)(dd)(dd),")             // date (ddmmyy)
            .expression("[^*]+")
            .text("*")
            .expression("[^,]+")
            .number(",(d+)")                     // satellites
            .number(",(d+)")                     // imei
            .expression(",([01])")               // ignition
            .number(",(d+)")                     // fuel
            .number(",(d+)").optional(7)         // battery
            .number("((?:,d+)+)?")               // parameters
            .any()
            .compile();

    private static final Pattern PATTERN_GPGGA = new PatternBuilder()
            .text("$GPGGA,")
            .number("(dd)(dd)(dd).?d*,")         // time (hhmmss)
            .number("(d+)(dd.d+),")              // latitude
            .expression("([NS]),")
            .number("(d+)(dd.d+),")              // longitude
            .expression("([EW]),")
            .any()
            .compile();

    private static final Pattern PATTERN_GPRMA = new PatternBuilder()
            .text("$GPRMA,")
            .expression("([AV]),")               // validity
            .number("(dd)(dd.d+),")              // latitude
            .expression("([NS]),")
            .number("(ddd)(dd.d+),")             // longitude
            .expression("([EW]),,,")
            .number("(d+.?d*)?,")                // speed
            .number("(d+.?d*)?,")                // course
            .any()
            .compile();

    private static final Pattern PATTERN_TRCCR = new PatternBuilder()
            .text("$TRCCR,")
            .number("(dddd)(dd)(dd)")            // date (yyyymmdd)
            .number("(dd)(dd)(dd).?d*,")         // time (hhmmss)
            .expression("([AV]),")               // validity
            .number("(-?d+.d+),")                // latitude
            .number("(-?d+.d+),")                // longitude
            .number("(d+.d+),")                  // speed
            .number("(d+.d+),")                  // course
            .number("(-?d+.d+),")                // altitude
            .number("(d+.?d*),")                 // battery
            .any()
            .compile();

    private static final Pattern PATTERN_GPIOP = new PatternBuilder()
            .text("$GPIOP,")
            .number("[01]{8},")                  // inputs
            .number("[01]{8},")                  // outputs
            .number("d+.d+,")                    // adc 1
            .number("d+.d+,")                    // adc 2
            .number("d+.d+,")                    // adc 3
            .number("d+.d+,")                    // adc 4
            .number("(d+.d+),")                  // power
            .number("(d+.d+)")                   // battery
            .any()
            .compile();

    private static final Pattern PATTERN_QZE = new PatternBuilder()
            .text("QZE,")
            .number("(d{15}),")                  // imei
            .number("(d+),")                     // event
            .number("(dd)(dd)(dddd),")           // date (mmddyyyy)
            .number("(dd)(dd)(dd),")             // time (hhmmss)
            .number("(-?d+.d+),")                // latitude
            .number("(-?d+.d+),")                // longitude
            .number("(d+),")                     // speed
            .number("(d+),")                     // course
            .expression("([AV]),")               // validity
            .expression("([01])")                // ignition
            .compile();

    private static final Pattern PATTERN_PUBX = new PatternBuilder()
            .text("$PUBX,")
            .number("(d+),")                     // index
            .number("(dd)(dd)(dd).d+,")          // time (hhmmss)
            .number("(dd)(dd.d+),([NS]),")       // latitude
            .number("(ddd)(dd.d+),([EW]),")      // longitude
            .number("(-?d+.d+),")                // altitude
            .expression("(..),")                 // status
            .number("(d+.d+),")                  // horizontal accuracy
            .number("d+.d+,")                    // vertical accuracy
            .number("(d+.d+),")                  // speed
            .number("(d+.d+),")                  // course
            .number("-?d+.d+,")                  // vertical velocity
            .expression("[^,]*,")                // corrections age
            .number("(d+.d+),")                  // hdop
            .number("(d+.d+),")                  // vdop
            .number("d+.d+,")                    // tdop
            .number("(d+),")                     // satellites
            .number("(d+),")                     // device id
            .number("d+")
            .text("*")
            .number("xx")                        // checksum
            .compile();

    private Position position = null;

    private Position decodeGprmc(
            DeviceSession deviceSession, String sentence, SocketAddress remoteAddress, Channel channel) {

        if (deviceSession != null && channel != null && !(channel instanceof DatagramChannel)) {
            boolean ack = AttributeUtil.lookup(
                    getCacheManager(), Keys.PROTOCOL_ACK.withPrefix(getProtocolName()), deviceSession.getDeviceId());
            if (ack) {
                channel.writeAndFlush(new NetworkMessage("OK1\r\n", remoteAddress));
            }
        }

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

        Position position = new Position(getProtocolName());

        if (deviceSession != null) {
            position.setDeviceId(deviceSession.getDeviceId());
        }

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

        position.setValid(parser.next().equals("A"));
        position.setLatitude(parser.nextCoordinate());
        position.setLongitude(parser.nextCoordinate());
        position.setSpeed(parser.nextDouble(0));
        position.setCourse(parser.nextDouble(0));

        dateBuilder.setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
        position.setTime(dateBuilder.getDate());

        if (parser.hasNext(5)) {
            position.set(Position.KEY_SATELLITES, parser.nextInt());

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

            position.set(Position.KEY_IGNITION, parser.hasNext() && parser.next().equals("1"));
            position.set(Position.KEY_FUEL_LEVEL, parser.nextInt(0));
            position.set(Position.KEY_BATTERY, parser.nextInt());
        }

        if (parser.hasNext()) {
            String[] parameters = parser.next().split(",");
            for (int i = 1; i < parameters.length; i++) {
                position.set(Position.PREFIX_IO + i, parameters[i]);
            }
        }

        if (deviceSession != null) {
            return position;
        } else {
            this.position = position; // save position
            return null;
        }
    }

    private Position decodeGpgga(DeviceSession deviceSession, String sentence) {

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

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

        DateBuilder dateBuilder = new DateBuilder()
                .setCurrentDate()
                .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
        position.setTime(dateBuilder.getDate());

        position.setValid(true);
        position.setLatitude(parser.nextCoordinate());
        position.setLongitude(parser.nextCoordinate());

        return position;
    }

    private Position decodeGprma(DeviceSession deviceSession, String sentence) {

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

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

        position.setTime(new Date());
        position.setValid(parser.next().equals("A"));
        position.setLatitude(parser.nextCoordinate());
        position.setLongitude(parser.nextCoordinate());
        position.setSpeed(parser.nextDouble(0));
        position.setCourse(parser.nextDouble(0));

        return position;
    }

    private Position decodeTrccr(DeviceSession deviceSession, String sentence) {

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

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

        position.setTime(parser.nextDateTime());

        position.setValid(parser.next().equals("A"));
        position.setLatitude(parser.nextDouble(0));
        position.setLongitude(parser.nextDouble(0));
        position.setSpeed(parser.nextDouble(0));
        position.setCourse(parser.nextDouble(0));
        position.setAltitude(parser.nextDouble(0));

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

        return position;
    }

    private Position decodeGpiop(DeviceSession deviceSession, String sentence) {

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

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

        getLastLocation(position, null);

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

        return position;
    }

    private Position decodeQze(Channel channel, SocketAddress remoteAddress, String sentence) {

        Parser parser = new Parser(PATTERN_QZE, 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());

        position.set(Position.KEY_EVENT, parser.nextInt());

        position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));
        position.setLatitude(parser.nextDouble());
        position.setLongitude(parser.nextDouble());
        position.setSpeed(UnitsConverter.knotsFromKph(parser.nextInt()));
        position.setCourse(parser.nextInt());
        position.setValid(parser.next().equals("A"));

        position.set(Position.KEY_IGNITION, parser.nextInt() > 0);

        return position;
    }

    private Position decodePubx(Channel channel, SocketAddress remoteAddress, String sentence) {

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

        Position position = new Position(getProtocolName());

        position.set(Position.KEY_INDEX, parser.nextInt());

        position.setTime(parser.nextDateTime(Parser.DateTimeFormat.HMS));
        position.setLatitude(parser.nextCoordinate());
        position.setLongitude(parser.nextCoordinate());
        position.setAltitude(parser.nextDouble());
        position.setValid(!parser.next().equals("NF"));
        position.setAccuracy(parser.nextDouble());
        position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble()));
        position.setCourse(parser.nextDouble());

        position.set(Position.KEY_HDOP, parser.nextDouble());
        position.set(Position.KEY_VDOP, parser.nextDouble());
        position.set(Position.KEY_SATELLITES, parser.nextInt());

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

        return null;
    }

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

        String sentence = (String) msg;

        DeviceSession deviceSession;

        if (!sentence.startsWith("$") && sentence.contains("$")) {
            int index = sentence.indexOf("$");
            String id = sentence.substring(0, index);
            if (id.endsWith(",")) {
                id = id.substring(0, id.length() - 1);
            } else if (id.endsWith("/")) {
                id = id.substring(id.indexOf('/') + 1, id.length() - 1);
            }
            deviceSession = getDeviceSession(channel, remoteAddress, id);
            sentence = sentence.substring(index);
        } else {
            deviceSession = getDeviceSession(channel, remoteAddress);
            if (deviceSession == null && remoteAddress instanceof InetSocketAddress) {
                String host = ((InetSocketAddress) remoteAddress).getHostString();
                deviceSession = getDeviceSession(channel, remoteAddress, host);
            }
        }

        if (sentence.startsWith("$PGID")) {
            getDeviceSession(channel, remoteAddress, sentence.substring(6, sentence.length() - 3));
        } else if (sentence.startsWith("$DEVID")) {
            getDeviceSession(channel, remoteAddress, sentence.substring(7, sentence.lastIndexOf('*')));
        } else if (sentence.startsWith("$PCPTI")) {
            getDeviceSession(channel, remoteAddress, sentence.substring(7, sentence.indexOf(",", 7)));
        } else if (sentence.startsWith("IMEI")) {
            getDeviceSession(channel, remoteAddress, sentence.substring(5));
        } else if (sentence.startsWith("$IMEI")) {
            getDeviceSession(channel, remoteAddress, sentence.substring(6));
        } else if (sentence.startsWith("$GPFID")) {
            deviceSession = getDeviceSession(channel, remoteAddress, sentence.substring(7));
            if (deviceSession != null && position != null) {
                Position position = this.position;
                position.setDeviceId(deviceSession.getDeviceId());
                this.position = null;
                return position;
            }
        } else if (sentence.matches("^[0-9A-F]+$")) {
            getDeviceSession(channel, remoteAddress, sentence);
        } else if (sentence.startsWith("$GPRMC")) {
            return decodeGprmc(deviceSession, sentence, remoteAddress, channel);
        } else if (sentence.startsWith("$GPGGA") && deviceSession != null) {
            return decodeGpgga(deviceSession, sentence);
        } else if (sentence.startsWith("$GPRMA") && deviceSession != null) {
            return decodeGprma(deviceSession, sentence);
        } else if (sentence.startsWith("$TRCCR") && deviceSession != null) {
            return decodeTrccr(deviceSession, sentence);
        } else if (sentence.startsWith("$GPIOP")) {
            return decodeGpiop(deviceSession, sentence);
        } else if (sentence.startsWith("QZE")) {
            return decodeQze(channel, remoteAddress, sentence);
        } else if (sentence.startsWith("$PUBX")) {
            return decodePubx(channel, remoteAddress, sentence);
        }

        return null;
    }

}