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
use self::utils::*;
use super::*;
use chrono::{DateTime, FixedOffset};
use lazy_static::*;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::HashMap;
use std::error::Error;
use std::net::IpAddr;
use std::num::NonZeroU32;
use std::str::FromStr;

/// A data structure containing information on a single user on the system.
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Operator<'a> {
    /// Unique user ID, which cannot be zero.
    pub operator_id: NonZeroU32,
    //
    /// Name of the user.
    pub operator_name: Option<&'a str>,
}

impl<'a> Operator<'a> {
    /// Create an `Opereator` with just an ID and no name.
    ///
    /// # Panics
    ///
    /// Panics if `id` is zero.
    ///
    pub fn new(id: u32) -> Self {
        Self { operator_id: NonZeroU32::new(id).unwrap(), operator_name: None }
    }

    /// Create an `Opereator` with name.
    ///
    /// # Panics
    ///
    /// Panics if `id` is zero.
    ///
    pub fn new_with_name(id: u32, name: &'a str) -> Self {
        Self { operator_name: Some(name), ..Self::new(id) }
    }
}

/// A data structure containing a single physical geo-location.
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GeoLocation {
    /// Latitude
    pub geo_latitude: f64,
    //
    /// Longitude
    pub geo_longitude: f64,
}

impl GeoLocation {
    pub fn new(latitude: f64, longitude: f64) -> Self {
        GeoLocation { geo_latitude: latitude, geo_longitude: longitude }
    }

    /// Validate the data structure.
    ///
    pub fn validate(&self) -> Result<'static, ()> {
        check_f64(self.geo_latitude, "geo_latitude")?;
        check_f64(self.geo_longitude, "geo_longitude")
    }
}

/// A data structure containing the current known status of a controller.
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Controller<'a> {
    /// Unique ID of the controller, which cannot be zero.
    pub controller_id: NonZeroU32,
    //
    /// User-specified human-friendly name for the machine.
    pub display_name: &'a str,
    //
    /// Controller type.
    ///
    /// # Examples
    ///
    /// * `Ai01`
    /// * `Ai12`
    /// * `CDC2000WIN`
    /// * `MPC7`
    pub controller_type: &'a str,
    //
    /// Version of the controller's firmware.
    pub version: &'a str,
    //
    /// Machine model.
    pub model: &'a str,
    //
    /// Address of the controller.
    ///
    /// For a network-connected controller, this is usually the IP address and port, in the format `x.x.x.x:port`.
    ///
    /// For a serial-connected controller, this is usually the serial port device name, such as `COM1`, `ttyS0`.
    #[serde(rename = "IP")]
    pub address: &'a str,
    //
    /// Physical geo-location of the controller (if any).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(flatten)]
    pub geo_location: Option<GeoLocation>,
    //
    /// Current operating mode of the controller.
    pub op_mode: OpMode,
    //
    /// Current job mode of the controller.
    pub job_mode: JobMode,
    //
    /// Last set of cycle data (if any) received from the controller.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_cycle_data: Option<HashMap<&'a str, f64>>,
    //
    /// Last-known states (if any) of controller variables.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variables: Option<HashMap<&'a str, f64>>,
    //
    /// Time of last connection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_connection_time: Option<DateTime<FixedOffset>>,
    //
    /// Current logged-in user (if any) on the controller
    #[serde(flatten)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<Operator<'a>>,
    //
    /// Active job ID (if any) on the controller.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub job_card_id: Option<Cow<'a, str>>,
    //
    /// ID of the set of mold data currently loaded (if any) on the controller.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(borrow)]
    pub mold_id: Option<Cow<'a, str>>,
}

impl<'a> Controller<'a> {
    /// Validate the data structure.
    ///
    pub fn validate(&self) -> Result<'a, ()> {
        // String fields should not be empty
        check_str_empty(self.controller_type, "controller_type")?;
        check_str_empty(self.display_name, "display_name")?;
        check_str_empty(self.version, "version")?;
        check_str_empty(self.model, "version")?;
        check_optional_str_empty(&self.job_card_id, "job_card_id")?;
        check_optional_str_empty(&self.mold_id, "mold_id")?;

        // Check Geo-location
        if let Some(geo) = &self.geo_location {
            geo.validate()?;
        }

        // Check IP address
        check_str_empty(self.address, "address")?;

        lazy_static! {
            static ref IP_REGEX: Regex = Regex::new(r#"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}$"#).unwrap();
            static ref TTY_REGEX: Regex = Regex::new(r#"^tty\w+$"#).unwrap();
            static ref COM_REGEX: Regex = Regex::new(r#"^COM(\d+)$"#).unwrap();
        }

        if !IP_REGEX.is_match(self.address) {
            if !TTY_REGEX.is_match(self.address) && !COM_REGEX.is_match(self.address) {
                return Err(OpenProtocolError::InvalidField {
                    field: "ip".into(),
                    value: self.address.into(),
                    description: "".into(),
                });
            }
        } else {
            // Check IP address validity
            let (address, port) = self.address.split_at(self.address.find(':').unwrap());

            let unspecified: bool;

            match IpAddr::from_str(address) {
                Ok(addr) => unspecified = addr.is_unspecified(),
                Err(err) => {
                    return Err(OpenProtocolError::InvalidField {
                        field: "ip[address]".into(),
                        value: address.into(),
                        description: format!("{} ({})", address, err.description()).into(),
                    })
                }
            }

            // Allow port 0 on unspecified addresses only
            let port = &port[1..];

            match u16::from_str(port) {
                Ok(n) => {
                    if n == 0 && !unspecified {
                        return Err(OpenProtocolError::InvalidField {
                            field: "ip[port]".into(),
                            value: port.into(),
                            description: "IP port cannot be zero.".into(),
                        });
                    } else if n > 0 && unspecified {
                        return Err(OpenProtocolError::InvalidField {
                            field: "ip[port]".into(),
                            value: port.into(),
                            description: "Null IP must have zero port number.".into(),
                        });
                    }
                }
                Err(err) => {
                    return Err(OpenProtocolError::InvalidField {
                        field: "ip[port]".into(),
                        value: port.into(),
                        description: err.description().to_string().into(),
                    })
                }
            }
        }

        Ok(())
    }
}

impl Default for Controller<'_> {
    fn default() -> Self {
        Controller {
            controller_id: NonZeroU32::new(1).unwrap(),
            display_name: "Unknown",
            controller_type: "Unknown",
            version: "Unknown",
            model: "Unknown",
            address: "0.0.0.0:0",
            geo_location: None,
            op_mode: OpMode::Unknown,
            job_mode: JobMode::Unknown,
            job_card_id: None,
            last_cycle_data: None,
            variables: None,
            last_connection_time: None,
            operator: None,
            mold_id: None,
        }
    }
}

// Tests

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

    #[test]
    fn test_controller_serialize() {
        let c = Controller {
            op_mode: OpMode::Automatic,
            job_mode: JobMode::ID02,
            operator: Some(Operator::new_with_name(123, "John")),
            ..Default::default()
        };
        c.validate().unwrap();
        let serialized = serde_json::to_string(&c).unwrap();
        assert_eq!(
            r#"{"controllerId":1,"controllerType":"Unknown","version":"Unknown","model":"Unknown","IP":"0.0.0.0:1","opMode":"Automatic","jobMode":"ID02","operatorId":123,"operatorName":"John"}"#,
            serialized);
    }

    #[test]
    fn test_controller_deserialize() {
        let c: Controller = serde_json::from_str(r#"{"controllerId":1,"displayName":"Hello","controllerType":"Unknown","version":"Unknown","model":"Unknown","IP":"127.0.0.1:123","opMode":"Automatic","jobMode":"ID02","operatorId":123,"operatorName":"John"}"#).unwrap();
        c.validate().unwrap();

        assert_eq!(
            r#"Controller { controller_id: 1, display_name: "Hello", controller_type: "Unknown", version: "Unknown", model: "Unknown", address: "127.0.0.1:123", geo_location: None, op_mode: Automatic, job_mode: ID02, last_cycle_data: None, variables: None, last_connection_time: None, operator: Some(Operator { operator_id: 123, operator_name: Some("John") }), job_card_id: None, mold_id: None }"#,
            format!("{:?}", &c));
    }

    #[test]
    fn test_controller_check() {
        let c: Controller = Default::default();
        c.validate().unwrap();
    }

    #[test]
    fn test_controller_check_operator() {
        let c = Controller {
            operator: Some(Operator { operator_id: NonZeroU32::new(123).unwrap(), operator_name: Some("John") }),
            ..Default::default()
        };
        c.validate().unwrap();
    }

    #[test]
    fn test_controller_check_ip() {
        let mut c: Controller = Default::default();

        // 1.02.003.004:05
        c.address = "1.02.003.004:05";
        c.validate().unwrap();

        // 1.02.003.004:0 - should fail
        c.address = "1.02.003.004:0";
        assert!(c.validate().is_err());

        // 0.0.0.0:0
        c.address = "0.0.0.0:0";
        c.validate().unwrap();

        // 0.0.0.0:123 - should fail
        c.address = "0.0.0.0:123";
        assert!(c.validate().is_err());

        // COM123
        c.address = "COM123";
        c.validate().unwrap();

        // ttyABC
        c.address = "ttyABC";
        c.validate().unwrap();
    }
}