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
//
// Copyright (c) 2021 Murilo Ijanc' <mbsd@m0x.ru>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

use std::fmt;

use nom::bits::{bits, streaming};
use nom::error::Error;
use nom::IResult;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "chrono")]
use chrono::{DateTime, TimeZone, Utc};

use crate::utils;

#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FixStatus {
    /// Bit is set when the position update has a horizontal position accuracy estimate that is
    /// less that the Horizontal Position Accuracy Threshold defined in S-Register 142 (and the
    /// threshold is non-zero).
    pub predicted: bool,

    /// This bit is set when WAAS DGPS is enabled (S-Register 139) and the position has been
    /// differentially corrected
    pub diff_corrected: bool,

    /// This bit is set when the current GPS fix is invalid but a previous fix’s value is
    /// available.
    pub last_know: bool,

    /// This bit is set only after a power-up or reset before a valid fix is obtained.
    pub invalid_fix: bool,

    /// This bit is set when 3 or fewer satellites are seen/used in the GPS fix. (i.e. with 3
    /// satellites or less, an altitude value cannot be calculated)
    pub twod_fix: bool,

    /// This bit is set when the message has been logged by the LMU.
    pub historic: bool,

    /// This bit is set only after a power-up or reset before a valid time-sync has been obtained.
    pub invalid_time: bool,
}

impl FixStatus {
    pub fn parse(input: &[u8]) -> IResult<&[u8], FixStatus> {
        #[allow(clippy::type_complexity)]
        let (i, b): (&[u8], (u8, u8, u8, u8, u8, u8, u8)) =
            bits::<_, _, Error<(&[u8], usize)>, _, _>(nom::sequence::tuple((
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
            )))(input)?;
        Ok((
            i,
            FixStatus {
                predicted: b.6 == 1,
                diff_corrected: b.5 == 1,
                last_know: b.4 == 1,
                invalid_fix: b.3 == 1,
                twod_fix: b.2 == 1,
                historic: b.1 == 1,
                invalid_time: b.0 == 1,
            },
        ))
    }
}

#[derive(PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum NetworkTechnology {
    /// 2G
    CdmaGsm,

    /// 3G
    Umts,

    /// 4G
    Lte,

    /// Reserved network
    Reserved,
}

impl NetworkTechnology {
    pub fn parse(input: u8) -> NetworkTechnology {
        match input {
            0 => NetworkTechnology::CdmaGsm,
            1 => NetworkTechnology::Umts,
            10 => NetworkTechnology::Lte,
            11 => NetworkTechnology::Reserved,
            _ => panic!("not found"),
        }
    }
}

impl fmt::Display for NetworkTechnology {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            NetworkTechnology::CdmaGsm => {
                write!(f, "NetworkTechnology::CdmaGsm")
            }
            NetworkTechnology::Umts => write!(f, "NetworkTechnology::Umts"),
            NetworkTechnology::Lte => write!(f, "NetworkTechnology::Lte"),
            NetworkTechnology::Reserved => {
                write!(f, "NetworkTechnology::Reserved")
            }
        }
    }
}

impl fmt::Debug for NetworkTechnology {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            NetworkTechnology::CdmaGsm => {
                write!(f, "NetworkTechnology::CdmaGsm")
            }
            NetworkTechnology::Umts => write!(f, "NetworkTechnology::Umts"),
            NetworkTechnology::Lte => write!(f, "NetworkTechnology::Lte"),
            NetworkTechnology::Reserved => {
                write!(f, "NetworkTechnology::Reserved")
            }
        }
    }
}

#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CommState {
    /// Available
    pub available: bool,

    /// Network service
    pub network_service: bool,

    /// Data service
    pub data_service: bool,

    /// Connected
    pub connected: bool,

    /// Voice call active
    pub voice_call_active: bool,

    /// Roaming
    pub roaming: bool,

    /// Network Technology
    pub network_technology: NetworkTechnology,
}

impl CommState {
    pub fn parse(input: &[u8]) -> IResult<&[u8], CommState> {
        #[allow(clippy::type_complexity)]
        let (i, b): (&[u8], (u8, u8, u8, u8, u8, u8, u8)) =
            bits::<_, _, Error<(&[u8], usize)>, _, _>(nom::sequence::tuple((
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(2u8),
            )))(input)?;
        Ok((
            i,
            CommState {
                available: b.6 == 1,
                network_service: b.5 == 1,
                data_service: b.4 == 1,
                connected: b.3 == 1,
                voice_call_active: b.2 == 1,
                roaming: b.1 == 1,
                network_technology: NetworkTechnology::parse(b.0),
            },
        ))
    }
}

#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Inputs {
    pub ignition: bool,
    pub input_1: bool,
    pub input_2: bool,
    pub input_3: bool,
    pub input_4: bool,
    pub input_5: bool,
    pub input_6: bool,
    pub input_7: bool,
}

impl Inputs {
    pub fn parse(input: &[u8]) -> IResult<&[u8], Inputs> {
        #[allow(clippy::type_complexity)]
        let (i, b): (&[u8], (u8, u8, u8, u8, u8, u8, u8, u8)) =
            bits::<_, _, Error<(&[u8], usize)>, _, _>(nom::sequence::tuple((
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
            )))(input)?;
        Ok((
            i,
            Inputs {
                ignition: b.7 == 1,
                input_1: b.6 == 1,
                input_2: b.5 == 1,
                input_3: b.4 == 1,
                input_4: b.3 == 1,
                input_5: b.2 == 1,
                input_6: b.1 == 1,
                input_7: b.0 == 1,
            },
        ))
    }
}

#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct UnitStatus {
    /// LMU32: HTTP OTA Update Status (0=OK, 1=Error), LMU8: Unused
    pub ota_update: bool,

    /// GPS Antenna Status (0=OK, 1=Error)
    pub gps_antenna: bool,

    /// GPS Receiver Self-Test (0=OK, 1=Error) (LMU32 only)
    pub gps_self_test: bool,

    /// GPS Receiver Tracking (0=Yes, 1=No)
    pub gps_tracking: bool,

    /// Reserved, Currently Unused
    pub reserved_1: bool,

    /// Reserved, Currently Unused
    pub reserved_2: bool,

    /// Reserved, Currently Unused
    pub reserved_3: bool,

    /// Unused
    pub unused: bool,
}

impl UnitStatus {
    pub fn parse(input: &[u8]) -> IResult<&[u8], UnitStatus> {
        #[allow(clippy::type_complexity)]
        let (i, b): (&[u8], (u8, u8, u8, u8, u8, u8, u8, u8)) =
            bits::<_, _, Error<(&[u8], usize)>, _, _>(nom::sequence::tuple((
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
                streaming::take(1u8),
            )))(input)?;
        Ok((
            i,
            UnitStatus {
                ota_update: b.7 == 0,
                gps_antenna: b.6 == 0,
                gps_self_test: b.5 == 0,
                gps_tracking: b.4 == 0,
                reserved_1: b.3 == 0,
                reserved_2: b.2 == 0,
                reserved_3: b.1 == 0,
                unused: b.0 == 0,
            },
        ))
    }
}

/// Event Report messages
///
/// Initiated by the LMU and are generated by the LMU’s Programmable Event
/// Generator (PEG). They can be either Acknowledged or Unacknowledged Requests.
/// The Server should respond to an Acknowledged Event Report Request with an
/// Acknowledge Message.
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EventReport {
    /// The time tag of the message in seconds.
    #[cfg(feature = "chrono")]
    pub update_time: DateTime<Utc>,
    #[cfg(not(feature = "chrono"))]
    pub update_time: u32,

    /// The last known time of fix from the GPS satellites.
    #[cfg(feature = "chrono")]
    pub time_of_fix: DateTime<Utc>,
    #[cfg(not(feature = "chrono"))]
    pub time_of_fix: u32,

    /// The latitude reading of the GPS receiver, measured in degrees with a
    /// 1x10^-7 degree lsb, signed 2’s complement.
    pub latitude: f32,

    /// The longitude reading of the GPS receiver, measured in degrees with a
    /// 1x10^-7 degree lsb, signed 2’s complement.
    pub longitude: f32,

    /// The altitude reading of the GPS receiver measured in centimeters above
    /// the WGS-84 Datum, signed 2’s complement.
    pub altitude: f32,

    /// The speed as reported by the GPS receiver, measured in centimeters per
    /// second.
    pub speed: f32,

    /// The heading value reported in degrees from true North.
    pub heading: u16,

    /// The number of satellites used in the GPS solution.
    pub satellites: u8,

    /// The current fix status of the GPS receiver bitmapped as follows
    pub fix_status: FixStatus,

    /// The identifier of the Carrier/Operator the wireless modem is currently
    /// using. For GSM, HSPA, and LTE networks, this is the MNC (mobile network
    /// code). For CDMA networks this is the SID (system identification number).
    pub carrier: u16,

    // pub carrier_ms: u16,
    /// The received signal strength of the wireless modem in dBm. This value is
    /// signed in a 2’s complement format.
    pub rssi: i16,

    /// The current state of the wireless modem bit mapped as follows
    ///
    /// Bit 0 – Available
    ///
    /// Bit 1 – Network Service
    ///
    /// Bit 2 – Data Service
    ///
    /// Bit 3 – Connected (PPP Session Up)
    ///
    /// Bit 4 – Voice Call is Active
    ///
    /// Bit 5 – Roaming
    ///
    /// Bits 6-7 – Network Technology
    ///
    /// 00 = 2G Network (CDMA or GSM)
    ///
    /// 01 = 3G Network (UMTS)
    ///
    /// 10 = 4G Network (LTE)
    ///
    /// 11 = Reserved
    pub comm_state: CommState,

    /// The GPS Horizontal Dilution of Precision - it is a unit-less value
    /// reported with a 0.1 lsb.
    pub hdop: u8,

    /// The current state of the inputs, bit mapped as follows:
    ///
    /// Bit 0 – Ignition
    ///
    /// Bit 1 – Input 1
    ///
    /// Bit 2 – Input 2
    ///
    /// Bit 3 – Input 3
    ///
    /// Bit 4 – Input 4
    ///
    /// Bit 5 – Input 5
    ///
    /// Bit 6 – Input 6
    ///
    /// Bit 7 – Input 7
    pub inputs: Inputs,

    /// Status of key modules within the unit:
    ///
    /// Bit 0 – LMU32: HTTP OTA Update Status (0=OK, 1=Error), LMU8: Unused
    ///
    /// Bit 1 – GPS Antenna Status (0=OK, 1=Error)
    ///
    /// Bit 2 – GPS Receiver Self-Test (0=OK, 1=Error) (LMU32 only)
    ///
    /// Bit 3 – GPS Receiver Tracking (0=Yes, 1=No)
    ///
    /// Bit 4 – Reserved, Currently Unused
    ///
    /// Bit 5 – Reserved, Currently Unused
    ///
    /// Bit 6 – Reserved, Currently Unused
    ///
    /// Bit 7 – Unused
    pub unit_status: UnitStatus,

    /// The index number of the event that generated the report; values should
    /// range from 0-249. 255 represents a Real Time PEG Action request.
    pub event_index: u8,

    /// The event code assigned to the report as specified by the event’s Action
    /// Parameter
    pub event_code: u8,

    /// The number of 4-byte values in the AccumList and the Accumulator
    /// Reporting Format Type (upper 2 bits).
    pub accums: u8,

    /// This bit-mapped byte is used to indicate the presence, when
    /// corresponding bit is set, of specific data types appended to the end of
    /// the Event Report following the list of accumulators. Each data type
    /// starts with a single length byte followed by the data. If multiple data
    /// types are present, they shall appear in order of the bits set in the
    /// 'Append' byte, starting with bit 0.
    ///
    /// Bit 0 – Cell Info (see 'Appended Data' section below).
    ///
    /// Bit 1 thru 7 – reserved, set to zero (0).
    pub append: u8,

    /// A list of ‘n’ 4-byte fields where ‘n’ is defined in the Accums field.
    /// The format for this list is dependent upon the Accumulator Reporting
    /// Format Type also defined in the Accums field. Refer to Appendix G,
    /// 'Accumulator Reporting Formats' for details.
    pub accum_list: Vec<u32>,
}

impl EventReport {
    /// Parse event report
    pub fn parse(input: &[u8]) -> std::io::Result<EventReport> {
        let mut accum_list: Vec<u32> = vec![];
        #[cfg(feature = "chrono")]
        let (i, update_time) = utils::pdt(input).unwrap();
        #[cfg(not(feature = "chrono"))]
        let (i, update_time) = utils::pu32(input).unwrap();
        let (i, time_of_fix) = utils::pu32(i).unwrap();
        let (i, latitude) = utils::pf32(i).unwrap();
        let (i, longitude) = utils::pf32(i).unwrap();
        let (i, altitude) = utils::pf32(i).unwrap();
        let (i, speed) = utils::pf32(i).unwrap();
        let (i, heading) = utils::pu16(i).unwrap();
        let (i, satellites) = utils::pu8(i).unwrap();
        let (i, fix_status) = FixStatus::parse(i).unwrap();
        let (i, carrier) = utils::pu16(i).unwrap();
        let (i, rssi) = utils::p16(i).unwrap();
        let (i, comm_state) = CommState::parse(i).unwrap();
        let (i, hdop) = utils::pu8(i).unwrap();
        let (i, inputs) = Inputs::parse(i).unwrap();
        let (i, unit_status) = UnitStatus::parse(i).unwrap();
        let (i, event_index) = utils::pu8(i).unwrap();
        let (i, event_code) = utils::pu8(i).unwrap();
        let (i, accums) = utils::pu8(i).unwrap();
        let (i, append) = utils::pu8(i).unwrap();
        let mut inp = i;
        for _ in 0..accums {
            let (x, v) = utils::pu32(inp).unwrap();
            inp = x;
            accum_list.push(v);
        }

        Ok(EventReport {
            update_time,
            time_of_fix,
            latitude,
            longitude,
            altitude,
            speed,
            heading,
            satellites,
            fix_status,
            carrier,
            rssi,
            comm_state,
            hdop,
            inputs,
            unit_status,
            event_index,
            event_code,
            accums,
            append,
            accum_list,
        })
    }
}

#[cfg(test)]
mod tests {

    use super::EventReport;
    use crate::message_header::MessageHeader;
    use crate::messages::event_report::NetworkTechnology;
    use crate::options_header::OptionsHeader;

    #[test]
    fn test_parse_event_report_message() {
        let data: [u8; 117] = [
            0x83, 0x05, 0x46, 0x34, 0x66, 0x32, 0x35, 0x01, 0x01, 0x01, 0x02,
            0x3a, 0x86, 0x5f, 0xf1, 0x3a, 0x54, 0x5f, 0xf1, 0x3a, 0x57, 0xf1,
            0xe2, 0x85, 0x78, 0xe4, 0x22, 0xd6, 0x40, 0x00, 0x01, 0x36, 0xf8,
            0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x06, 0x20, 0x00, 0x00, 0xff,
            0x8d, 0x02, 0x1e, 0x1e, 0x00, 0x7b, 0x21, 0x10, 0x00, 0x00, 0x00,
            0x31, 0xe0, 0x00, 0x00, 0x10, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x22, 0x2a, 0x32, 0x00, 0x00, 0x03, 0xf1, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x01, 0xc8, 0x2d, 0x3f, 0x01, 0xc8, 0x2d,
            0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let (i, _) = OptionsHeader::parse(&data).unwrap();
        let (i, _) = MessageHeader::parse(i).unwrap();
        let event_report = EventReport::parse(i).unwrap();

        assert_eq!(event_report.update_time, 1609644628);
        assert_eq!(event_report.time_of_fix, 1609644631);
        approx::assert_relative_eq!(event_report.latitude, -23.6812936);
        approx::assert_relative_eq!(
            event_report.longitude,
            -46.747897599999995
        );
        approx::assert_relative_eq!(event_report.altitude, 0.0079608);
        approx::assert_relative_eq!(event_report.speed, 0.0000011);
        assert_eq!(event_report.heading, 0);
        assert_eq!(event_report.satellites, 6);
        assert_eq!(event_report.fix_status.twod_fix, true);
        assert_eq!(event_report.carrier, 0);
        assert_eq!(event_report.rssi, -115);
        assert_eq!(event_report.comm_state.available, false);
        assert_eq!(
            event_report.comm_state.network_technology,
            NetworkTechnology::CdmaGsm
        );
        assert_eq!(event_report.hdop, 30);
        assert_eq!(event_report.inputs.ignition, false);
        assert_eq!(event_report.unit_status.gps_antenna, true);
        assert_eq!(event_report.event_index, 123);
        assert_eq!(event_report.event_code, 33);
        assert_eq!(event_report.accums, 16);
        assert_eq!(event_report.append, 0);
        assert_eq!(event_report.accum_list.len(), 16);
    }
}