gpsd_client 0.1.5

Simple gpsd client that get the information from a gps device.
Documentation
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

//! The `gpsd_client` module contains types and functions to connect to
//! `[gpsd]` <https://gpsd.io/index.html> to get gps coordinates and how many
//! satellites you are receiving information from and how many satellites
//! the information is being used.
//!
//! The `gps-client` uses a TcpStream to connect to the gpsd socket and read and
//! write information to `gpsd`. This package was modeled from the python3 gpsd package.
//!
//! # Update
//! You now have the ability to change the time format from %Y-%m-%dT%H:%M:%S.%fZ.
//! 
//! # Testing
//!
//! `gpsd_client` was tested with gpsd: 3.22 on Linux Debian Distro.
//!
//! From more information about gpsd just check out the documentation at <https://gpsd.io/index.html>.
//!
//! ## Example
//!
//! ```
//! use gpsd_client::*;
//! use std::thread;
//! use std::time::Duration;
//! use std::process;
//!
//! # fn main() {
//!       // Connecting to the gpsd socket server.
//!       let mut gps: GPS = match GPS::connect() {
//!           Ok(t) => t,
//!           Err(e) => {
//!               println!("{e}");
//!               process::exit(1);
//!           }
//!       };
//!
//!       let mut count: i32 = 0;
//!
//!       loop {
//!           count += 1;
//!           // Getting the data from the gps device.
//!           let data: GPSData = gps.current_data().unwrap();
//!           println!("{data:#?}");
//!           let my_time: String = data.convert_time("America/Chicago").unwrap();
//!           let mph: f32 = data.convert_speed(true);
//!           let direction: String = data.travel_direction();
//!           println!(
//!               "Lat: {}, Lon: {}, Time: {}, Speed: {:.1}, Direction: {}",
//!               data.lat, data.lon, my_time, mph, direction
//!           );
//!           if count == 5 { break; }
//!           thread::sleep(Duration::from_millis(500));
//!       }
//!
//!       // Closing the TcpStream and BufReader to the gpsd socket server.
//!       gps.close();
//! # }
//! ```

#[warn(dead_code)]
use chrono::{DateTime, Utc, NaiveDateTime};
use chrono_tz::{self, Tz};
use round::round;
use serde_json::{self, Value};

use std::fmt;
use std::fmt::Formatter;
use std::io::{self, BufRead, BufReader, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};

/// Time Format for converting the string time from the gps device to Datetime
/// so it can converted to the time zone.
const TIME_FMT: &'static str = "%Y-%m-%dT%H:%M:%S.%fZ";

/// An array that hold the direction of travel that is calculated from the heading.
const DIRECTION: [&'static str; 8] = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];

/// Possible errors that can occur for parsing the data that comes from
/// the gpsd socket server.
#[derive(Debug)]
pub enum GPSError {
    /// TcpStreamError protocol for any socket errors.
    TcpStreamError(String),
    /// Standard io error.
    BufReadError(io::Error),
    /// Means the welcome message from gpsd has failed.
    WelcomeMessageError,
    /// Standard serde_json error.
    SerdeJsonError(serde_json::Error),
    /// Trouble parsing to the users timezone.
    TimeZoneParseError(chrono_tz::ParseError),
    /// GPS had a failed watch message.
    WatchError,
    /// Couldn't convert the string to a DateTime.
    TimeConvertError(String),
}

impl From<io::Error> for GPSError {
    fn from(err: io::Error) -> Self {
        GPSError::BufReadError(err)
    }
}

impl From<serde_json::Error> for GPSError {
    fn from(err: serde_json::Error) -> Self {
        GPSError::SerdeJsonError(err)
    }
}

impl fmt::Display for GPSError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            GPSError::TcpStreamError(e) => write!(f, "{e}"),
            GPSError::BufReadError(e) => write!(f, "IO BufReader Error: {e}"),
            GPSError::WelcomeMessageError => write!(f, "Unexpected data received as welcome."),
            GPSError::SerdeJsonError(e) => write!(f, "Serde Json Error: {e}"),
            GPSError::TimeZoneParseError(e) => write!(f, "Chrono-Tz Parse Error: {e}"),
            GPSError::WatchError => write!(f, "GPSD Watch Error: No watch returned."),
            GPSError::TimeConvertError(e) => write!(f, "Time Convert Error: {e}"),
        }
    }
}

/// This struct holds the connection to the gpsd socket server and version,
/// watch and devices information from gpsd. For more information about version,
/// watch and devices visit <https://gpsd.io/gpsd_json.html>.
#[derive(Debug)]
pub struct GPS {
    /// Socket that sends data to the gpsd socket server.
    gps_socket: TcpStream,
    /// BufReader that receives data from the gpsd socket server.
    gps_stream: BufReader<TcpStream>,
    /// The daemon ships a VERSION response to each client when the client first connects to it.
    /// Object is in json format.
    pub version: Value,
    /// It also sets or elicits a report of per-subscriber policy and the raw bit.
    /// Object is in json format.
    pub watch: Value,
    /// Device list object in json format.
    pub devices: Value,
}

impl GPS {
    /// Connects to the gpsd socket server. Returns a Result of either a GPS or GPSError.
    pub fn connect() -> Result<GPS, GPSError> {
        let host: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
        let port: u16 = 2947;
        let sock_addr: SocketAddr = SocketAddr::new(host, port);

        let mut gps_socket: TcpStream = TcpStream::connect(sock_addr)
            .map_err(|e| GPSError::TcpStreamError(format!("{e}")))?;

        let mut gps_stream: BufReader<TcpStream> = BufReader::new(
            gps_socket.try_clone()
                .map_err(|e| GPSError::BufReadError(e))?
        );

        let mut welcom_messase: String = String::new();
        gps_stream.read_line(&mut welcom_messase)?;

        let version: Value = parse_into_json(&welcom_messase)?;
        if version["class"] != "VERSION" {
            return Err(GPSError::WelcomeMessageError);

        }

        let watch_command: &[u8] ="?WATCH={\"enable\": true}\n".as_bytes();
        gps_socket.write_all(watch_command)?;
        gps_socket.flush()?;

        let (w, d) = parse_info(&mut gps_stream)?;
        let watch: Value = match w {
            Some(t) => t,
            None => return Err(GPSError::WatchError)
        };
        let devices: Value = match d {
            Some(t) => t,
            None => return Err(GPSError::WatchError)
        };

        Ok(GPS { gps_socket, gps_stream, version, watch, devices })
    }

    /// Polls the gpsd socket server for the gps data. Returns a Result that is either
    /// GPSData or GPSError.
    pub fn current_data(&mut self) -> Result<GPSData, GPSError> {
        self.gps_socket.write_all("?POLL;\n".as_bytes())?;
        self.gps_socket.flush()?;

        let mut raw: String = String::new();
        self.gps_stream.read_line(&mut raw)?;

        let raw_json: Value = parse_into_json(&raw)?;

        if raw_json["class"] != "POLL" {
            return Ok(GPSData::default());
        }

        Ok(GPSData::new(&raw_json))
    }

    /// Close the connection to the gpsd socket server.
    pub fn close(self) {
        drop(self.gps_stream);
        // drop(self.gps_socket);
        self.gps_socket.shutdown(std::net::Shutdown::Both).unwrap();
    }
}

/// Data from the gps device.
#[derive(Debug, Default, Clone)]
pub struct GPSData {
    /// NMEA mode:
    /// 0=unknown,
    /// 1=no fix,
    /// 2=2D,
    /// 3=3D.
    pub mode: Fix,
    /// The number of satellites received by the GPS unit
    pub sats: u8,
    /// The number of satellites with valid information.
    pub sats_valid: u8,
    /// Longitude in degrees.
    pub lon: f64,
    /// Latitude in degrees
    pub lat: f64,
    /// Altitude, height above ellipsoid, in meters.
    pub alt_hae: f64,
    /// MSL Altitude in meters. The geoid used is rarely specified and is often inaccurate.
    pub alt_msl: f64,
    /// Deprecated. Altitude in meters. Use altHAE or altMSL.
    pub alt: f32,
    /// Course over ground, degrees from true north
    pub track: f32,
    /// Speed over ground, meters per second
    pub speed: f32,
    /// Climb (positive) or sink (negative) rate, meters per second
    pub climb: f32,
    /// Time/date stamp in ISO8601 format, UTC. May have a fractional part of up to .001sec precision.
    pub time: String,
    /// Climb/sink error estimate in meters/sec, 95% confidence.
    pub epc: f32,
    /// Speed error estimated in meters/sec, 95% confidence.
    pub eps: f32,
    /// Estimated timestamp error (%f, seconds, 95% confidence).
    pub ept: f32,
    /// Estimated vertical error in meters, 95% confidence. Present if mode is 3 and DOPs can be
    /// calculated from the satellite view.
    pub epv: f32,
    /// Longitude error estimate in meters, 95% confidence. Present if mode is 2 or 3 and DOPs
    /// can be calculated from the satellite view.
    pub epx: f32,
    /// Latitude error estimate in meters, 95% confidence. Present if mode is 2 or 3 and DOPs
    /// can be calculated from the satellite view.
    pub epy: f32,
}

impl GPSData {
    fn new(values: &Value) -> Self {
        let sky: Value = values["sky"][0].to_owned();
        let tpv: Value = values["tpv"][0].to_owned();
        let fix: u8 = if tpv.get("mode").is_some() { parse_value_to_u8(&tpv["mode"]) } else { 0 };
        let mode: Fix = Fix::new(fix);
        let sats: u8 = if sky.get("nSat").is_some() { parse_value_to_u8(&sky["nSat"]) } else { 0 };
        let sats_valid: u8 = if sky.get("satellites").is_some() { get_valid_satellites(&sky["satellites"]) } else { 0 };
        let lon: f64 = if fix >= 2 { parse_value_to_f64(&tpv["lon"]) } else { 0.0 };
        let lat: f64 = if fix >= 2 { parse_value_to_f64(&tpv["lat"]) } else { 0.0 };
        let alt_hae: f64 = if tpv.get("altHAE").is_some() { parse_value_to_f64(&tpv["altHAE"]) } else { 0.0 };
        let alt_msl: f64 = if tpv.get("altMSL").is_some() { parse_value_to_f64(&tpv["altMSL"]) } else { 0.0 };
        let alt: f32 = if fix >= 3 { parse_value_to_f32(&tpv["alt"]) } else { 0.0 };
        let track: f32 = if fix >= 2 { parse_value_to_f32(&tpv["track"]) } else { 0.0 };
        let speed: f32 = if fix >= 2 { parse_value_to_f32(&tpv["speed"]) } else { 0.0 };
        let climb: f32 = if fix >= 3 { parse_value_to_f32(&tpv["climb"]) } else { 0.0 };
        let time: String = if fix >= 2 { parse_value_to_string_time(&tpv["time"]) } else { get_time() };
        let epc: f32 = if tpv.get("epc").is_some() { parse_value_to_f32(&tpv["epc"]) } else { 0.0 };
        let eps: f32 = if tpv.get("eps").is_some() { parse_value_to_f32(&tpv["eps"]) } else { 0.0 };
        let ept: f32 = if tpv.get("ept").is_some() { parse_value_to_f32(&tpv["ept"]) } else { 0.0 };
        let epv: f32 = if tpv.get("epv").is_some() { parse_value_to_f32(&tpv["epv"]) } else { 0.0 };
        let epx: f32 = if tpv.get("epx").is_some() { parse_value_to_f32(&tpv["epx"]) } else { 0.0 };
        let epy: f32 = if tpv.get("epy").is_some() { parse_value_to_f32(&tpv["epy"]) } else { 0.0 };
        GPSData{ mode, sats, sats_valid, lon, lat, alt_hae, alt_msl, alt, track, speed, climb, time, epc, eps, ept, epv, epx, epy}
    }

    /// Converts the speed from the gps device to miles per hour or kilometers per hour.
    /// If mph is true then it's mph else it's km/h.
    pub fn convert_speed(&self, mph: bool) -> f32 {
        let speed: f32 = match mph {
            true => self.speed * 2.237,
            _ => self.speed * 3.6
        };
        round(speed as f64, 1) as f32
    }

    /// Converts the track/heading of travel to the direction N, NE, E, SE, S, SW, W, NW.
    pub fn travel_direction(&self) -> String {
        let degree: f64 = (self.track / 45.0) as f64;
        let index: usize = (round(degree, 0) as usize) % 8;
        DIRECTION[index].to_string()
    }

    /// Takes the time that gps receiver has and converts it to the Time Zone
    /// that was given. For more information about the time zone string you can pass
    /// check out the crate chrono-tz.
    pub fn convert_time(&self, timezone: &str) -> Result<String, GPSError> {
        let time_zone: Tz = timezone.parse().map_err(|e| GPSError::TimeZoneParseError(e))?;

        let native_time: NaiveDateTime = NaiveDateTime::parse_from_str(&self.time, TIME_FMT)
            .map_err(|_| GPSError::TimeConvertError(format!("Could not convert the time {}", self.time)))?;

        let utc_time: DateTime<Utc> = DateTime::from_naive_utc_and_offset(native_time, Utc);
        let current_time: DateTime<Tz> = utc_time.with_timezone(&time_zone);

        Ok(current_time.format(TIME_FMT).to_string())
    }

}

/// Type of fix the gps device has.
#[derive(Debug, Default, Clone, Copy)]
pub enum Fix {
    #[default]
    /// No Fix. Mode is either 0 or 1.
    None,
    /// 2 dimensional fix. Mode is 2.
    Fix2D,
    /// 3 dimensional fix. Mode is 3.
    Fix3D
}

impl fmt::Display for Fix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Fix::None => write!(f, "None"),
            Fix::Fix2D => write!(f, "Fix 2D"),
            Fix::Fix3D => write!(f, "Fix 2D"),
        }
    }
}

impl Fix {
    fn new(mode: u8) -> Self {
        match mode {
            2 => Fix::Fix2D,
            3 => Fix::Fix3D,
            _ => Fix::None,
        }
    }
}

/// Converts the time from this format "%Y-%m-%dT%H:%M:%S.%fZ" to what ever format you want.
/// Just make sure if your converting the time to your Time Zone you did it first.
/// Then run this function.
pub fn format_time(time: &str, new_format: &str) -> Result<String, GPSError> {
    let native_time: NaiveDateTime = NaiveDateTime::parse_from_str(time, TIME_FMT)
        .map_err(|_| GPSError::TimeConvertError(format!("Could not convert the time {}", time)))?;
    let current: DateTime<Utc> = DateTime::from_naive_utc_and_offset(native_time, Utc);
    Ok(current.format(new_format).to_string())
}

fn parse_into_json(info: &str) -> Result<Value, GPSError> {
    let value: Value = serde_json::from_str(info)
        .map_err(|e| GPSError::SerdeJsonError(e))?;
    Ok(value)
}

fn parse_info(gps_stream: &mut BufReader<TcpStream>) -> Result<(Option<Value>, Option<Value>), GPSError> {
    let mut watch: Option<Value> = None;
    let mut devices: Option<Value> = None;

    for _ in 0..2 {
        let mut raw = String::new();
        gps_stream.read_line(&mut raw)?;
        let parsed: Value = parse_into_json(&raw)?;
        if parsed["class"] == "DEVICES" { devices = Some(parsed.to_owned()) }
        if parsed["class"] == "WATCH" { watch = Some(parsed.to_owned()) }
    }

    Ok((watch, devices))
}

fn parse_value_to_u8(value: &Value) -> u8 {
    match value {
        Value::Number(x) => {
            let numb: u64 = x.as_u64().unwrap();
            match numb <= u8::MAX as u64 {
                true => numb as u8,
                _ => 0
            }
        }
        _ => 0
    }
}

fn parse_value_to_f32(value: &Value) -> f32 {
    match value {
        Value::Number(x) => {
            let number: f64 = x.as_f64().unwrap();
            if number <= f32::MAX as f64 {
                number as f32
            } else {
                0.0
            }
        },
        _ => 0.0
    }
}

fn parse_value_to_f64(value: &Value) -> f64 {
    match value {
        Value::Number(x) => x.as_f64().unwrap(),
        _ => 0.0
    }
}

fn parse_value_to_string_time(value: &Value) -> String {
    match value {
        Value::String(x) => x.to_string(),
        _ => get_time()
    }
}

fn get_time() -> String {
    let current_time: DateTime<Utc> = Utc::now();
    current_time.format(TIME_FMT).to_string()
}

fn get_valid_satellites(values: &Value) -> u8 {
    let mut count: u8 = 0;
    let sat_array: &Vec<Value> = values.as_array().unwrap();

    for i in sat_array.iter() {
        if i["used"] == true {
            count += 1;
        }
    }

    count
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn checking_satellites() {
        let value: Value = serde_json::from_str(
            "{\"Test\": [\
            {\"used\":true,\"gnssid\":0,\"svid\":5},\
            {\"used\":true,\"gnssid\":0,\"svid\":5},\
            {\"used\":false,\"gnssid\":0,\"svid\":5},\
            {\"used\":false,\"gnssid\":0,\"svid\":5},\
            {\"used\":true,\"gnssid\":0,\"svid\":5}\
            ]}"
        ).unwrap();
        let results: u8 = get_valid_satellites(&value["Test"]);
        assert_eq!(results, 3);
    }

    #[test]
    fn check_parse_to_json() {
        let value: Value = parse_into_json(
            "{\"Test\": [\
            {\"used\":true,\"gnssid\":0,\"svid\":5},\
            {\"used\":true,\"gnssid\":0,\"svid\":5},\
            {\"used\":false,\"gnssid\":0,\"svid\":5},\
            {\"used\":false,\"gnssid\":0,\"svid\":5},\
            {\"used\":true,\"gnssid\":0,\"svid\":5}\
            ]}"
        ).unwrap();
        assert_eq!(value.is_object(), true);
    }

    #[test]
    fn check_my_time() {
        let gps_data: GPSData = GPSData{
            mode: Fix::Fix2D,
            sats: 0,
            sats_valid: 0,
            lon: 0.0,
            lat: 0.0,
            alt_hae: 0.0,
            alt_msl: 0.0,
            alt: 0.0,
            track: 0.0,
            speed: 0.0,
            climb: 0.0,
            time: String::from("2024-01-07T00:59:47.0000Z"),
            epc: 0.0,
            eps: 0.0,
            ept: 0.0,
            epv: 0.0,
            epx: 0.0,
            epy: 0.0,
        };
        let my_time: String = gps_data.convert_time("America/New_York")
            .unwrap()
            .split(".")
            .next()
            .unwrap()
            .to_string();
        assert_eq!(my_time, "2024-01-06T19:59:47".to_string());
    }

    #[test]
    fn check_speed() {
        let gps_data: GPSData = GPSData{
            mode: Fix::Fix2D,
            sats: 0,
            sats_valid: 0,
            lon: 0.0,
            lat: 0.0,
            alt_hae: 0.0,
            alt_msl: 0.0,
            alt: 0.0,
            track: 0.0,
            speed: 32.9,
            climb: 0.0,
            time: String::from("2024-01-07T00:59:47.0000Z"),
            epc: 0.0,
            eps: 0.0,
            ept: 0.0,
            epv: 0.0,
            epx: 0.0,
            epy: 0.0,
        };
        let mph: f32 = gps_data.convert_speed(true);
        let kmh: f32 = gps_data.convert_speed(false);
        assert_eq!(mph, 73.6);
        assert_eq!(kmh, 118.4);
    }

    #[test]
    fn check_travel_direction() {
        let gps_data: GPSData = GPSData{
            mode: Fix::Fix2D,
            sats: 0,
            sats_valid: 0,
            lon: 0.0,
            lat: 0.0,
            alt_hae: 0.0,
            alt_msl: 0.0,
            alt: 0.0,
            track: 38.7,
            speed: 32.9,
            climb: 0.0,
            time: String::from("2024-01-07T00:59:47.0000Z"),
            epc: 0.0,
            eps: 0.0,
            ept: 0.0,
            epv: 0.0,
            epx: 0.0,
            epy: 0.0,
        };
        let direction: String = gps_data.travel_direction();
        assert_eq!(direction, "NE");
    }
}