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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
use self::filters::*;
use self::utils::*;
use super::*;
use chrono::{DateTime, FixedOffset};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU64, Ordering};
use Message::*;

// Auto-incrementing global counter for message sequences
static SEQ: AtomicU64 = AtomicU64::new(1);

/// Common options of an Open Protocol message.
///
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MessageOptions<'a> {
    /// Unique ID (if any) of the message for tracking and storage retrieval purposes.
    ///
    /// The iChen Server may tag certain messages with a unique tracking key that can be used to
    /// retrieve the message from persistent storage later.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<&'a str>,
    //
    /// Ever-increasing message sequence number.
    ///
    /// This number is usually auto-incremented with each message created, starting from 1.
    pub sequence: u64,
    //
    /// Priority of the message, smaller number is higher priority.  Default = 0.
    #[serde(skip_serializing_if = "is_zero")]
    #[serde(default)]
    pub priority: i32,
}

impl<'a> MessageOptions<'a> {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn new_with_priority(priority: i32) -> Self {
        Self { priority, ..Self::new() }
    }

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

impl Default for MessageOptions<'_> {
    fn default() -> Self {
        Self { id: None, sequence: SEQ.fetch_add(1, Ordering::SeqCst), priority: 0 }
    }
}

/// A data structure containing information on a production job (i.e. a *job card*).
///
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct JobCard<'a> {
    /// Unique job ID, which must not be empty or all white-spaces.
    #[serde(borrow)]
    pub job_card_id: Cow<'a, str>,
    //
    /// ID of the set of mold data to load for this job.
    #[serde(borrow)]
    pub mold_id: Cow<'a, str>,
    //
    /// Current production progress, which must not be larger than `total`.
    pub progress: u32,
    //
    /// Total production count ordered.
    pub total: u32,
}

impl<'a> JobCard<'a> {
    pub fn new(id: &'a str, mold: &'a str, progress: u32, total: u32) -> Self {
        Self { job_card_id: id.into(), mold_id: mold.into(), progress, total }
    }

    /// Validate the data structure.
    ///
    pub fn validate(&self) -> Result<'static, ()> {
        check_str_empty(&self.job_card_id, "job_card_id")?;
        check_str_empty(&self.mold_id, "mold_id")?;
        if self.progress > self.total {
            return Err(OpenProtocolError::ConstraintViolated(
                format!("JobCard progress ({}) must not be larger than total ({}).", self.progress, self.total).into(),
            ));
        }
        Ok(())
    }
}

/// A general data structure holding a key and value pair.
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyValuePair<K, V> {
    pub key: K,
    pub value: V,
}

impl<K, V> KeyValuePair<K, V> {
    pub fn new(key: K, value: V) -> Self {
        Self { key, value }
    }
}

/// A data structure containing a snapshot of the current known states of the controller.
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StateValues<'a> {
    /// Current operating mold of the controller.
    #[serde(skip_serializing_if = "OpMode::is_unknown")]
    #[serde(default)]
    pub op_mode: OpMode,
    //
    /// Current job mode of the controller.
    #[serde(skip_serializing_if = "JobMode::is_unknown")]
    #[serde(default)]
    pub job_mode: JobMode,
    //
    /// Unique ID of the current logged-in user (if any) on the controller.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator_id: Option<NonZeroU32>,
    //
    /// Current 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>>,
    //
    /// Unique 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> StateValues<'a> {
    /// Create a new `StateValues` wth no operator ID, job card ID and mold ID.
    pub fn new(op: OpMode, job: JobMode) -> Self {
        Self { op_mode: op, job_mode: job, operator_id: None, job_card_id: None, mold_id: None }
    }

    /// Create a new `StateValues` with all fields set.
    ///
    /// # Panics
    ///
    /// Panics if `operator` is `Some(0)`.
    ///
    pub fn new_with_all(
        op: OpMode,
        job: JobMode,
        operator: Option<u32>,
        job_card: Option<&'a str>,
        mold: Option<&'a str>,
    ) -> Self {
        Self {
            operator_id: operator.map(|o| NonZeroU32::new(o).unwrap()),
            job_card_id: job_card.map(|j| j.into()),
            mold_id: mold.map(|m| m.into()),
            ..Self::new(op, job)
        }
    }

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

impl Default for StateValues<'_> {
    fn default() -> Self {
        Self {
            op_mode: OpMode::Unknown,
            job_mode: JobMode::Unknown,
            operator_id: None,
            job_card_id: None,
            mold_id: None,
        }
    }
}

/// All Open Protocol message types.
///
/// See [this document](https://github.com/chenhsong/OpenProtocol/blob/master/cs/doc/messages_reference.md) for details.
///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "$type")]
pub enum Message<'a> {
    #[serde(rename_all = "camelCase")]
    /// The `ALIVE` message, sent periodically as the keep-alive mechanism.
    Alive {
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `CNTRLER_ACTION` message, sent by the server whenever the current *action* of a controller changes.
    #[serde(rename_all = "camelCase")]
    ControllerAction {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        /// Unique action code.
        ///
        /// See [this document](https://github.com/chenhsong/OpenProtocol/blob/master/doc/actions.md) for details.
        action_id: i32,
        //
        /// Time-stamp of the event.
        timestamp: DateTime<FixedOffset>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `REQ_CNTRLER_LIST` message, sent to the server to request a list of controllers (i.e. machines)
    /// within the user's organization.
    #[serde(rename_all = "camelCase")]
    RequestControllersList {
        /// Unique ID of the controller to request.
        ///
        /// If omitted, all controllers of the user's organization will be returned.
        #[serde(skip_serializing_if = "Option::is_none")]
        controller_id: Option<NonZeroU32>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `RESP_CNTRLER_LIST` message, sent by the server in response to a `RequestControllersList` message.
    #[serde(rename_all = "camelCase")]
    ControllersList {
        /// List of controllers requested by a previous `RequestControllersList` message.
        ///
        /// Each controller data structure contains the last-known values of the controller's state.
        data: HashMap<&'a str, Controller<'a>>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `UPD_CNTRLER` message, sent by the server whenever the status of a connected controller changes.
    ///
    /// Only the changed fields will be set, with other fields/properties being set to `None` as they are not relevant.
    #[serde(rename_all = "camelCase")]
    ControllerStatus {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// Human-friendly name for display (or `None` if not relevant).
        #[allow(clippy::option_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        display_name: Option<&'a str>,
        //
        /// If true, the controller has disconnected from the iChen® Server.
        #[serde(skip_serializing_if = "Option::is_none")]
        is_connected: Option<bool>,
        //
        /// Current operation mode of the controller (or `None` if not relevant).
        #[serde(skip_serializing_if = "Option::is_none")]
        op_mode: Option<OpMode>,
        //
        /// Current job mode of the controller (or `None` if not relevant).
        #[serde(skip_serializing_if = "Option::is_none")]
        job_mode: Option<JobMode>,
        //
        /// State of an alarm (if any) on the controller (or `None` if not relevant).
        ///
        /// See [this document](https://github.com/chenhsong/OpenProtocol/blob/master/doc/alarms.md) for valid alarm codes.
        #[serde(skip_serializing_if = "Option::is_none")]
        alarm: Option<KeyValuePair<&'a str, bool>>,
        //
        /// Change of a setting (if any) on the controller for audit trail purpose (or `None` if not relevant).
        #[serde(skip_serializing_if = "Option::is_none")]
        audit: Option<KeyValuePair<&'a str, f64>>,
        //
        /// Change of a variable (if any) on the controller (or `None` if not relevant).
        #[serde(skip_serializing_if = "Option::is_none")]
        variable: Option<KeyValuePair<&'a str, f64>>,
        //
        /// Unique ID of the current logged-on user, `Some(None)` if a user has logged out (or `None` if not relevant).
        #[allow(clippy::option_option)]
        #[serde(skip_serializing_if = "Option::is_none")]
        operator_id: Option<Option<NonZeroU32>>,
        //
        /// Name of the current logged-on user, `Some(None)` if the current user has no name (or `None` if not relevant).
        #[allow(clippy::option_option)]
        #[serde(deserialize_with = "deserialize_null_to_none")]
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(default)]
        operator_name: Option<Option<&'a str>>,
        //
        /// Unique ID of the current job card loaded, `Some(None)` if no job card is currently loaded (or `None` if not relevant).
        #[allow(clippy::option_option)]
        #[serde(deserialize_with = "deserialize_null_to_cow_none")]
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(default)]
        #[serde(borrow)]
        job_card_id: Option<Option<Cow<'a, str>>>,
        //
        /// Unique ID of the current mold data set loaded, `Some(None)` if no mold data set is currently loaded (or `None` if not relevant).
        #[allow(clippy::option_option)]
        #[serde(deserialize_with = "deserialize_null_to_cow_none")]
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(default)]
        #[serde(borrow)]
        mold_id: Option<Option<Cow<'a, str>>>,
        //
        /// Snapshot of the current known states of the controller.
        state: StateValues<'a>,
        //
        /// A `Controller` data structure containing the last-known state of the controller.
        ///
        /// This field is only sent once by the server as soon as a new controller has connected into the network.
        /// All subsequent messages have this field set to `None`.
        ///
        /// If this field is not `None`, then all other info fields should be `None`.
        #[serde(skip_serializing_if = "Option::is_none")]
        controller: Option<Box<Controller<'a>>>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `CYCLE_DATA` message, sent by the server at the end of each machine cycle.
    #[serde(rename_all = "camelCase")]
    CycleData {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// A data dictionary containing a set of cycle data.Alive
        ///
        /// See [this document](https://github.com/chenhsong/OpenProtocol/blob/master/doc/cycledata.md) for examples.
        data: HashMap<&'a str, f64>,
        //
        /// Time-stamp of the event.
        timestamp: DateTime<FixedOffset>,
        //
        /// Snapshot of the current known states of the controller.
        #[serde(flatten)]
        state: StateValues<'a>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `REQ_JOBCARDS_LIST` message, sent by the server when a connected controller requests a list of job cards.
    #[serde(rename_all = "camelCase")]
    RequestJobCardsList {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `RESP_JOBSLIST` message, sent to the server in response to a `RequestJobCardsList` message.
    #[serde(rename_all = "camelCase")]
    JobCardsList {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// A data dictionary containing a set of `JobCard` data structures.
        data: HashMap<&'a str, JobCard<'a>>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `JOIN` message, sent to log onto the server.
    #[serde(rename_all = "camelCase")]
    Join {
        /// Organization ID (if any).
        #[serde(skip_serializing_if = "Option::is_none")]
        org_id: Option<&'a str>,
        //
        /// The maximum protocol version supported, in the format `x.x.x.x`.
        ///
        /// The current protocol version implemnted is in the constant `PROTOCOL_VERSION`.
        version: &'a str,
        //
        /// Password to log onto the server.
        password: &'a str,
        //
        /// Language encoding.
        language: Language,
        //
        /// A collection of `Filter` values containing what type(s) of messages to receive.
        #[serde(serialize_with = "serialize_to_flatten_array")]
        #[serde(deserialize_with = "deserialize_flattened_array")]
        #[serde(borrow)]
        filter: Cow<'a, [Filter]>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `RESP_JOIN` message, sent by the Server in response to a `Join` message.
    #[serde(rename_all = "camelCase")]
    JoinResponse {
        /// Result code, >= 100 indicates success.
        result: u32,
        #[serde(skip_serializing_if = "Option::is_none")]
        //
        /// The allowed access level for this client.
        level: Option<u32>,
        //
        /// A message (mostly likely an error message in case of failure), if any.
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(borrow)]
        message: Option<Cow<'a, str>>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `REQ_MOLD` message, sent to the server to request the set of mold settings data of a controller.
    #[serde(rename_all = "camelCase")]
    RequestMoldData {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `RESP_MOLD` message, sent by the server in response to a `RequestMoldData` message
    /// or a `ReadMoldData` message with `field` set to `None` (meaning read all).
    #[serde(rename_all = "camelCase")]
    MoldData {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// A data dictionary containing a set of mold settings.
        data: HashMap<&'a str, f64>,
        //
        /// Time-stamp of the event.
        timestamp: DateTime<FixedOffset>,
        //
        /// Snapshot of the current known states of the controller.
        #[serde(flatten)]
        state: StateValues<'a>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `READ_MOLD_DATA` message, sent to the server to read the current value of a particular mold setting.
    ///
    /// The server keeps a cache of the states of all mold settings for each controller.
    /// The value returned is based on the server cache.
    /// No command is sent to controller to poll the latest value.
    #[serde(rename_all = "camelCase")]
    ReadMoldData {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// Name of the mold setting to read, `None` for all.
        field: Option<&'a str>,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `RESP_MOLD_DATA_VALUE` message, sent by the server in response to a `ReadMoldData` message.
    #[serde(rename_all = "camelCase")]
    MoldDataValue {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// Name of the mold setting to read.
        field: &'a str,
        //
        /// Current cached value of the mold setting.
        value: f64,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `REQ_PWD_LEVEL` message, sent by server when a connected controller attempts to authenticate and authorize a user password.
    #[serde(rename_all = "camelCase")]
    LoginOperator {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// User password.
        password: &'a str,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
    /// The `RESP_PWD_LEVEL` message, sent to the server in response to a `LoginOperator` message.
    #[serde(rename_all = "camelCase")]
    OperatorInfo {
        /// Unique ID of the controller.
        controller_id: NonZeroU32,
        //
        /// Unique ID of the authenticated user.
        #[serde(skip_serializing_if = "Option::is_none")]
        operator_id: Option<NonZeroU32>,
        //
        /// Name of the user.
        name: &'a str,
        //
        /// User password.
        password: &'a str,
        //
        /// Allowed access level for the user (0-10).
        level: u8,
        //
        /// Message configuration options.
        #[serde(flatten)]
        options: MessageOptions<'a>,
    },
}

impl<'a> Message<'a> {
    /// Current protocol version: 4.0.
    pub const PROTOCOL_VERSION: &'static str = "4.0";

    /// Default language to use: `Language::EN`.
    pub const DEFAULT_LANGUAGE: Language = Language::EN;

    /// Maximum operator level: 10.
    pub const MAX_OPERATOR_LEVEL: u8 = 10;

    /// Parse a JSON string into a `Message`.
    ///
    /// # Errors
    ///
    /// Returns [`Err(OpenProtocolError)`] if there is an error, which may be one of the following:
    ///
    /// * `JsonError`: Error during parsing, which may be due to malformed JSON text, missing fields,
    ///   wrong data types for fields etc.
    /// * `EmptyField`: A mandatory `String` field is empty (i.e. zero-length) or all white-spaces.
    /// * `InvalidField`: The value of a field is inappropriate for that field, although there is no syntax error.
    ///   For example, encountering `NaN` on a numeric field usually yields this error.
    /// * `ConstraintViolated`: An integrity constraint is violated by the data structure.
    ///   For example, if current progress (`progress`) field of a `JobCard` structure is larger than
    ///   its total production count (`total`) field.
    ///
    pub fn parse_from_json_str(json: &'a str) -> Result<'a, Self> {
        match serde_json::from_str::<Message>(json) {
            // Do validation check if successfully parsed
            Ok(m) => m.validate().map(|_| m),
            // Otherwise return error
            Err(err) => Err(OpenProtocolError::JsonError(err)),
        }
    }

    /// Validate all the fields in the `Message`, then serialize it into a JSON string.
    ///
    /// # Errors
    ///
    /// Returns [`Err(OpenProtocolError)`] if there is an error, which may be one of the following:
    ///
    /// * `JsonError`: Error during parsing, which may be due to malformed JSON text, missing fields,
    ///   wrong data types for fields etc.
    /// * `EmptyField`: A mandatory `String` field is empty (i.e. zero-length) or all white-spaces.
    /// * `InvalidField`: The value of a field is inappropriate for that field, although there is no syntax error.
    ///   For example, encountering `NaN` on a numeric field usually yields this error.
    /// * `ConstraintViolated`: An integrity constraint is violated by the data structure.
    ///   For example, if current progress (`progress`) field of a `JobCard` structure is larger than
    ///   its total production count (`total`) field.
    ///
    pub fn to_json_str(&self) -> Result<'_, String> {
        self.validate()?;

        serde_json::to_string(self).map_err(OpenProtocolError::JsonError)
    }

    /// Create an `ALIVE` message.
    ///
    pub fn new_alive() -> Self {
        Alive { options: Default::default() }
    }

    /// Create a `JOIN` message with default language and protocol version.
    ///
    pub fn new_join(password: &'a str, filter: &'a [Filter]) -> Self {
        Self::new_join_with_org(password, filter, None)
    }

    /// Create a `JOIN` message with non-default organization.
    ///
    pub fn new_join_with_org(password: &'a str, filter: &'a [Filter], org: Option<&'a str>) -> Self {
        Join {
            org_id: org,
            version: Self::PROTOCOL_VERSION,
            password,
            language: Self::DEFAULT_LANGUAGE,
            filter: filter.into(),
            options: Default::default(),
        }
    }

    /// Validate the data structure.
    ///
    pub fn validate(&self) -> Result<'a, ()> {
        match self {
            Alive { options, .. }
            | ControllerAction { options, .. }
            | RequestControllersList { options, .. }
            | RequestJobCardsList { options, .. }
            | JoinResponse { options, .. }
            | RequestMoldData { options, .. } => options.validate(),
            ControllersList { options, data, .. } => {
                for c in data {
                    c.1.validate()?;
                }
                options.validate()
            }
            ControllerStatus {
                options,
                display_name,
                alarm,
                audit,
                variable,
                operator_name,
                job_card_id,
                mold_id,
                state,
                controller,
                ..
            } => {
                check_optional_str_empty(display_name, "display_name")?;
                if let Some(x) = operator_name {
                    check_optional_str_whitespace(x, "operator_name")?;
                }
                if let Some(x) = job_card_id {
                    check_optional_str_whitespace(x, "job_card_id")?;
                }
                if let Some(x) = mold_id {
                    check_optional_str_whitespace(x, "mold_id")?;
                }
                state.validate()?;

                if let Some(kv) = alarm {
                    check_str_empty(kv.key, "alarm.key")?;
                }
                if let Some(kv) = audit {
                    check_str_empty(kv.key, "audit.key")?;
                    check_f64(kv.value, "audit.value")?;
                }
                if let Some(kv) = variable {
                    check_str_empty(kv.key, "variable.key")?;
                    check_f64(kv.value, "variable.value")?;
                }
                if let Some(c) = controller {
                    c.validate()?;
                }

                options.validate()
            }
            CycleData { options, data, state, .. } => {
                for d in data {
                    check_f64(*d.1, d.0)?;
                }
                check_optional_str_empty(&state.job_card_id, "job_card_id")?;
                check_optional_str_empty(&state.mold_id, "mold_id")?;
                options.validate()
            }
            JobCardsList { options, data, .. } => {
                for jc in data {
                    jc.1.validate()?;
                }
                options.validate()
            }
            Join { options, org_id, version, password, language, filter, .. } => {
                check_optional_str_empty(org_id, "org_id")?;
                check_str_empty(version, "version")?;
                check_str_empty(password, "password")?;
                // Check for invalid language
                if *language == Language::Unknown {
                    return Err(OpenProtocolError::InvalidField {
                        field: "language".into(),
                        value: "Unknown".into(),
                        description: "Language cannot be Unknown.".into(),
                    });
                }
                // Check filters list for duplications
                let mut list: Vec<Filter> = filter.iter().cloned().collect();
                list.dedup();
                if filter.len() != list.len() {
                    return Err(OpenProtocolError::ConstraintViolated("filter list contains duplications.".into()));
                }

                options.validate()
            }
            MoldData { options, data, state, .. } => {
                for d in data {
                    check_f64(*d.1, d.0)?;
                }
                check_optional_str_empty(&state.job_card_id, "job_card_id")?;
                check_optional_str_empty(&state.mold_id, "mold_id")?;
                options.validate()
            }
            ReadMoldData { options, field, .. } => {
                check_optional_str_empty(field, "field")?;
                options.validate()
            }
            MoldDataValue { options, field, value, .. } => {
                check_str_empty(field, "field")?;
                check_f64(*value, "value")?;
                options.validate()
            }
            LoginOperator { options, password, .. } => {
                check_str_empty(&password, "password")?;
                options.validate()
            }
            OperatorInfo { options, name, password, level, .. } => {
                check_str_empty(name, "name")?;
                check_optional_str_whitespace(&Some(*password), "password")?;
                if *level > Self::MAX_OPERATOR_LEVEL {
                    return Err(OpenProtocolError::ConstraintViolated(
                        format!("Level {} is too high - must be between 0 and {}.", level, Self::MAX_OPERATOR_LEVEL)
                            .into(),
                    ));
                }
                options.validate()
            }
        }
    }
}

// Tests

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

    #[test]
    fn test_alive() {
        let m = Alive { options: MessageOptions { id: Some("Hello"), sequence: 999, priority: 20 } };

        let serialized = serde_json::to_string(&m).unwrap();

        assert_eq!(r#"{"$type":"Alive","id":"Hello","sequence":999,"priority":20}"#, serialized);
    }

    #[test]
    fn test_mold_data() {
        let mut map = HashMap::<&str, f64>::new();

        map.insert("Hello", 123.0);
        map.insert("World", -987.6543);
        map.insert("foo", 0.0);

        let m = MoldData {
            controller_id: NonZeroU32::new(123).unwrap(),
            data: map,

            timestamp: DateTime::parse_from_rfc3339("2019-02-26T02:03:04+08:00").unwrap(),

            state: StateValues {
                job_card_id: Some("Hello World!".into()),
                mold_id: None,
                operator_id: Some(NonZeroU32::new(42).unwrap()),
                op_mode: OpMode::SemiAutomatic,
                job_mode: JobMode::Offline,
            },

            options: MessageOptions { id: None, sequence: 999, priority: -20 },
        };

        let serialized = serde_json::to_string(&m).unwrap();

        assert_eq!(
            r#"{"$type":"MoldData","controllerId":123,"data":{"foo":0.0,"Hello":123.0,"World":-987.6543},"timestamp":"2019-02-26T02:03:04+08:00","jobCardId":"Hello World!","operatorId":42,"opMode":"SemiAutomatic","jobMode":"Offline","sequence":999,"priority":-20}"#,
            serialized
        );

        let m2: Message = serde_json::from_str(&serialized).unwrap();
        m2.validate().unwrap();

        assert_eq!(m, m2);
    }

    #[test]
    fn test_controllers_list() {
        let json = r#"{"$type":"ControllersList","data":{"12345":{"controllerId":12345,"displayName":"Hello","controllerType":"Ai12","version":"1.0.0","model":"JM128-Ai","IP":"192.168.5.1","opMode":"Manual","jobMode":"ID11","lastCycleData":{"Z_QDGODCNT":8567,"Z_QDCYCTIM":979,"Z_QDINJTIM":5450,"Z_QDPLSTIM":7156,"Z_QDINJENDPOS":8449,"Z_QDPLSENDPOS":2212,"Z_QDFLAG":8988,"Z_QDPRDCNT":65500,"Z_QDCOLTIM":4435,"Z_QDMLDOPNTIM":652,"Z_QDMLDCLSTIM":2908,"Z_QDVPPOS":4732,"Z_QDMLDOPNENDPOS":6677,"Z_QDMAXINJSPD":7133,"Z_QDMAXPLSRPM":641,"Z_QDNOZTEMP":6693,"Z_QDTEMPZ01":9964,"Z_QDTEMPZ02":7579,"Z_QDTEMPZ03":4035,"Z_QDTEMPZ04":5510,"Z_QDTEMPZ05":8460,"Z_QDTEMPZ06":9882,"Z_QDBCKPRS":2753,"Z_QDHLDTIM":9936},"lastConnectionTime":"2016-03-06T23:11:27.1442177+08:00"},"22334":{"controllerId":22334,"displayName":"World","controllerType":1,"version":"1.0.0","model":"JM128-Ai","IP":"192.168.5.2","opMode":"SemiAutomatic","jobMode":"ID12","lastCycleData":{"Z_QDGODCNT":6031,"Z_QDCYCTIM":7526,"Z_QDINJTIM":4896,"Z_QDPLSTIM":5196,"Z_QDINJENDPOS":1250,"Z_QDPLSENDPOS":8753,"Z_QDFLAG":3314,"Z_QDPRDCNT":65500,"Z_QDCOLTIM":3435,"Z_QDMLDOPNTIM":7854,"Z_QDMLDCLSTIM":4582,"Z_QDVPPOS":7504,"Z_QDMLDOPNENDPOS":7341,"Z_QDMAXINJSPD":7322,"Z_QDMAXPLSRPM":6024,"Z_QDNOZTEMP":3406,"Z_QDTEMPZ01":3067,"Z_QDTEMPZ02":9421,"Z_QDTEMPZ03":2080,"Z_QDTEMPZ04":8845,"Z_QDTEMPZ05":4478,"Z_QDTEMPZ06":3126,"Z_QDBCKPRS":2807,"Z_QDHLDTIM":3928},"lastConnectionTime":"2016-03-06T23:11:27.149218+08:00"}},"sequence":68568}"#;

        let m: Message = serde_json::from_str(&json).unwrap();
        m.validate().unwrap();

        if let ControllersList { data, .. } = m {
            assert_eq!(2, data.len());
            let c = data.get("12345").unwrap();
            assert_eq!("Hello", c.display_name);
        } else {
            panic!("Expected ControllersList, got {:#?}", m);
        }
    }

    #[test]
    fn test_cycle_data() {
        let json = r#"{"$type":"CycleData","timestamp":"2016-02-26T01:12:23+08:00","opMode":"Automatic","jobMode":"ID02","controllerId":123,"data":{"Z_QDGODCNT":123,"Z_QDCYCTIM":12.33,"Z_QDINJTIM":3,"Z_QDPLSTIM":4.4,"Z_QDINJENDPOS":30.1,"Z_QDPLSENDPOS":20.3,"Z_QDFLAG":1,"Z_QDPRDCNT":500,"Z_QDCOLTIM":12.12,"Z_QDMLDOPNTIM":2.1,"Z_QDMLDCLSTIM":1.3,"Z_QDVPPOS":12.11,"Z_QDMLDOPNENDPOS":130.1,"Z_QDMAXINJSPD":213.12,"Z_QDMAXPLSRPM":551,"Z_QDNOZTEMP":256,"Z_QDTEMPZ01":251,"Z_QDTEMPZ02":252,"Z_QDTEMPZ03":253,"Z_QDTEMPZ04":254,"Z_QDTEMPZ05":255,"Z_QDTEMPZ06":256,"Z_QDBCKPRS":54,"Z_QDHLDTIM":2.3,"Z_QDCPT01":231,"Z_QDCPT02":232,"Z_QDCPT03":233,"Z_QDCPT04":234,"Z_QDCPT05":235,"Z_QDCPT06":236,"Z_QDCPT07":237,"Z_QDCPT08":238,"Z_QDCPT09":239,"Z_QDCPT10":240,"Z_QDCPT11":241,"Z_QDCPT12":242,"Z_QDCPT13":243,"Z_QDCPT14":244,"Z_QDCPT15":245,"Z_QDCPT16":246,"Z_QDCPT17":247,"Z_QDCPT18":248,"Z_QDCPT19":249,"Z_QDCPT20":250,"Z_QDCPT21":251,"Z_QDCPT22":252,"Z_QDCPT23":253,"Z_QDCPT24":254,"Z_QDCPT25":255,"Z_QDCPT26":256,"Z_QDCPT27":257,"Z_QDCPT28":258,"Z_QDCPT29":259,"Z_QDCPT30":260,"Z_QDCPT31":261,"Z_QDCPT32":262,"Z_QDCPT33":263,"Z_QDCPT34":264,"Z_QDCPT35":265,"Z_QDCPT36":266,"Z_QDCPT37":267,"Z_QDCPT38":268,"Z_QDCPT39":269,"Z_QDCPT40":270},"sequence":1}"#;

        let m: Message = serde_json::from_str(&json).unwrap();
        m.validate().unwrap();

        if let CycleData { options, controller_id, data, .. } = m {
            assert_eq!(0, options.priority);
            assert_eq!(123, controller_id.get());
            assert_eq!(64, data.len());
            assert!((*data.get("Z_QDCPT13").unwrap() - 243.0).abs() < std::f64::EPSILON);
        } else {
            panic!("Expected CycleData, got {:#?}", m);
        }
    }

    #[test]
    fn test_controller_status() {
        let json = r#"{"$type":"ControllerStatus","controllerId":123,"displayName":"Testing","opMode":"Automatic","jobMode":"ID05","jobCardId":"XYZ","moldId":"Mold-123","state":{"opMode":"Automatic","jobMode":"ID05","jobCardId":"XYZ","moldId":"Mold-123"},"controller":{"controllerId":123,"displayName":"Testing","controllerType":"Ai02","version":"2.2","model":"JM138Ai","IP":"192.168.1.1:12345","geoLatitude":123.0,"geoLongitude":-21.0,"opMode":"Automatic","jobMode":"ID05","jobCardId":"XYZ","lastCycleData":{"INJ":5,"CLAMP":400},"moldId":"Mold-123"},"sequence":1,"priority":50}"#;

        let m: Message = serde_json::from_str(&json).unwrap();
        m.validate().unwrap();

        if let ControllerStatus { options, controller_id, display_name, controller, .. } = m {
            assert_eq!(50, options.priority);
            assert_eq!(1, options.sequence);
            assert_eq!(123, controller_id.get());
            assert_eq!(Some("Testing"), display_name);
            let c = controller.unwrap();
            assert_eq!("JM138Ai", c.model);
            let d = c.last_cycle_data.unwrap();
            assert!(c.operator.is_none());
            assert_eq!(2, d.len());
            assert!((*d.get("INJ").unwrap() - 5.0).abs() < std::f64::EPSILON);
        } else {
            panic!("Expected ControllerStatus, got {:#?}", m);
        }
    }
}