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
use crate::lta_client::LTAClient;
use crate::utils::commons::{build_req, build_res_with_query, Result};

pub mod bus_arrival {
    use chrono::prelude::*;
    use serde::{Deserialize, Serialize};

    use crate::bus_enums::{BusFeature, BusLoad, BusType, Operator};
    use crate::utils::de::from_str;

    pub const URL: &str = "http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2";

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct ArrivalBusService {
        pub service_no: String,
        pub operator: Operator,
        pub next_bus: NextBus,
        pub next_bus_2: NextBus,
        pub next_bus_3: NextBus,
    }

    impl ArrivalBusService {
        pub fn next_bus_as_arr(&self) -> [&NextBus; 3] {
            [&self.next_bus, &self.next_bus_2, &self.next_bus_3]
        }
    }

    /// Representation is similar to the one
    /// [here](https://www.mytransport.sg/content/dam/datamall/datasets/LTA_DataMall_API_User_Guide.pdf)
    /// in order to keep it consistent with the API itself in case anyone wants to
    /// reference the original docs
    #[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct NextBus {
        /// Original response returns a `String`
        ///
        /// String is then deserialized to `u32`
        ///
        /// Represents starting bus stop code
        #[serde(deserialize_with = "from_str")]
        pub origin_code: u32,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `u32`
        ///
        /// Represents ending bus stop code
        #[serde(deserialize_with = "from_str", rename = "DestinationCode")]
        pub dest_code: u32,

        /// Represents starting bus stop code
        ///
        /// Original response returns a `String`
        ///
        /// Example response: `2019-07-21T13:12:41+08:00`
        ///
        /// String is then deserialize to `Datetime<FixedOffset>`
        #[serde(rename = "EstimatedArrival")]
        pub est_arrival: DateTime<FixedOffset>,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `f64`
        ///
        /// Represents latitude of bus
        #[serde(deserialize_with = "from_str", rename = "Latitude")]
        pub lat: f64,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `f64`
        ///
        /// Represents longitude of bus
        #[serde(deserialize_with = "from_str", rename = "Longitude")]
        pub long: f64,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `u32`
        ///
        /// Represents number of times the bus visited
        #[serde(deserialize_with = "from_str", rename = "VisitNumber")]
        pub visit_no: u32,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `BusLoad` enum
        ///
        /// Represents the load the bus has
        pub load: BusLoad,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `Option<BusFeature>`
        ///
        /// Represents features the bus has
        pub feature: Option<BusFeature>,

        /// Original response returns a `String`
        ///
        /// String is then deserialized to `BusType` enum
        ///
        /// Represents the bus type
        #[serde(rename = "Type")]
        pub bus_type: BusType,
    }

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct BusArrivalResp {
        #[serde(deserialize_with = "from_str")]
        pub bus_stop_code: u32,
        pub services: Vec<ArrivalBusService>,
    }
}

/// Returns real-time Bus Arrival information of Bus Services at a queried Bus Stop,
/// including Est. Arrival Time, Est. Current Location, Est. Current Load.
///
/// Sometimes, it may return an empty Vec
///
/// If that happens, it means that there are no services at that timing.
///
/// Update Freq: 1min
pub fn get_arrival(
    client: &LTAClient,
    bus_stop_code: u32,
    service_no: &str,
) -> Result<bus_arrival::BusArrivalResp> {
    let resp: bus_arrival::BusArrivalResp =
        build_res_with_query(client, bus_arrival::URL, |req_builder| {
            req_builder.query(&[
                ("BusStopCode", bus_stop_code.to_string()),
                ("ServiceNo", service_no.to_string()),
            ])
        })?;
    Ok(resp)
}

pub mod bus_services {
    use serde::{Deserialize, Serialize};

    use crate::bus_enums::{BusCategory, Operator};
    use crate::utils::de::{from_str, from_str_to_bus_freq};

    pub const URL: &str = "http://datamall2.mytransport.sg/ltaodataservice/BusServices";

    /// Both min and max are in terms of minutes
    #[derive(Debug, Clone, PartialEq, Serialize)]
    pub struct BusFreq {
        pub min: Option<u32>,
        pub max: Option<u32>,
    }

    impl BusFreq {
        pub fn new(min: u32, max: u32) -> Self {
            BusFreq {
                min: Some(min),
                max: Some(max),
            }
        }

        pub fn default() -> Self {
            BusFreq::new(0, 0)
        }

        pub fn no_max(min: u32) -> Self {
            BusFreq {
                min: Some(min),
                max: None,
            }
        }

        pub fn no_timing() -> Self {
            BusFreq {
                min: None,
                max: None,
            }
        }
    }

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct BusService {
        pub service_no: String,

        pub operator: Operator,

        #[serde(rename = "Direction")]
        pub no_direction: u32,

        pub category: BusCategory,

        #[serde(deserialize_with = "from_str")]
        pub origin_code: u32,

        #[serde(deserialize_with = "from_str", rename = "DestinationCode")]
        pub dest_code: u32,

        #[serde(rename = "AM_Peak_Freq", deserialize_with = "from_str_to_bus_freq")]
        pub am_peak_freq: BusFreq,

        #[serde(rename = "AM_Offpeak_Freq", deserialize_with = "from_str_to_bus_freq")]
        pub am_offpeak_freq: BusFreq,

        #[serde(rename = "PM_Peak_Freq", deserialize_with = "from_str_to_bus_freq")]
        pub pm_peak_freq: BusFreq,

        #[serde(rename = "PM_Offpeak_Freq", deserialize_with = "from_str_to_bus_freq")]
        pub pm_offpeak_freq: BusFreq,

        pub loop_desc: Option<String>,
    }

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    pub struct BusServiceResp {
        pub value: Vec<BusService>,
    }
}

/// Returns detailed service information for all buses currently in
/// operation, including: first stop, last stop, peak / offpeak frequency of
/// dispatch.
///
/// Update freq: Ad-Hoc
pub fn get_bus_services(client: &LTAClient) -> Result<Vec<bus_services::BusService>> {
    let resp: bus_services::BusServiceResp = build_req(client, bus_services::URL)?;
    Ok(resp.value)
}

pub mod bus_routes {
    use chrono::prelude::*;
    use serde::{Deserialize, Serialize};

    use crate::bus_enums::Operator;
    use crate::utils::de::{from_str, from_str_to_time};
    use crate::utils::ser::from_time_to_str;

    pub const URL: &str = "http://datamall2.mytransport.sg/ltaodataservice/BusRoutes";

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct BusRoute {
        pub service_no: String,

        pub operator: Operator,

        pub direction: u32,

        #[serde(rename = "StopSequence")]
        pub stop_seq: u32,

        #[serde(deserialize_with = "from_str")]
        pub bus_stop_code: u32,

        #[serde(rename = "Distance")]
        pub dist: f64,

        #[serde(
            rename = "WD_FirstBus",
            deserialize_with = "from_str_to_time",
            serialize_with = "from_time_to_str"
        )]
        pub wd_first: Option<NaiveTime>,

        #[serde(
            rename = "WD_LastBus",
            deserialize_with = "from_str_to_time",
            serialize_with = "from_time_to_str"
        )]
        pub wd_last: Option<NaiveTime>,

        #[serde(
            rename = "SAT_FirstBus",
            deserialize_with = "from_str_to_time",
            serialize_with = "from_time_to_str"
        )]
        pub sat_first: Option<NaiveTime>,

        #[serde(
            rename = "SAT_LastBus",
            deserialize_with = "from_str_to_time",
            serialize_with = "from_time_to_str"
        )]
        pub sat_last: Option<NaiveTime>,

        #[serde(
            rename = "SUN_FirstBus",
            deserialize_with = "from_str_to_time",
            serialize_with = "from_time_to_str"
        )]
        pub sun_first: Option<NaiveTime>,

        #[serde(
            rename = "SUN_LastBus",
            deserialize_with = "from_str_to_time",
            serialize_with = "from_time_to_str"
        )]
        pub sun_last: Option<NaiveTime>,
    }

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    pub struct BusRouteResp {
        pub value: Vec<BusRoute>,
    }
}

/// Returns detailed route information for all services currently in operation,
/// including: all bus stops along each route, first/last bus timings for each stop
///
/// Update freq: Ad-Hoc
pub fn get_bus_routes(client: &LTAClient) -> Result<Vec<bus_routes::BusRoute>> {
    let resp: bus_routes::BusRouteResp = build_req(client, bus_routes::URL)?;
    Ok(resp.value)
}

pub mod bus_stops {
    use serde::{Deserialize, Serialize};

    use crate::utils::commons::Coordinates;
    use crate::utils::de::from_str;

    pub const URL: &str = "http://datamall2.mytransport.sg/ltaodataservice/BusStops";

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    pub struct BusStop {
        #[serde(deserialize_with = "from_str")]
        pub bus_stop_code: u32,

        pub road_name: String,

        #[serde(rename = "Description")]
        pub desc: String,

        #[serde(rename = "Latitude")]
        pub lat: f64,

        #[serde(rename = "Longitude")]
        pub long: f64,
    }

    impl BusStop {
        pub fn coordinates(&self) -> Coordinates {
            Coordinates::new(self.lat, self.long)
        }
    }

    #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
    pub struct BusStopsResp {
        pub value: Vec<BusStop>,
    }
}

/// Returns detailed information for all bus stops currently being serviced by
/// buses, including: Bus Stop Code, location coordinates.
///
/// Update freq: Ad-Hoc
pub fn get_bus_stops(client: &LTAClient) -> Result<Vec<bus_stops::BusStop>> {
    let resp: bus_stops::BusStopsResp = build_req(client, bus_stops::URL)?;
    Ok(resp.value)
}