zproto 0.2.1

A library from communicating with Zaber products in Rust.
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
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
//! Types and traits for communicating with Zaber products with Zaber's [Binary protocol](https://www.zaber.com/protocol-manual?protocol=Binary).
//!
//! The binary protocol is **deprecated** and Zaber recommends the [`ascii`](crate::ascii) protocol instead.
//!
//! ## Communicating with a Device
//!
//! All communication with Zaber products starts with a [`Port`], which can be either a serial or TCP port:
//!
//! ```
//! # use zproto::binary::Port;
//! # fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
//! let mut port = Port::open_serial("/dev/ttyUSB0")?;
//! // OR
//! let mut port = Port::open_tcp("192.168.0.1:55550")?;
//! # Ok(())
//! # }
//! ```
//!
//! You can then transmit a command to and receive a reply from devices
//! connected to that port with the [`tx_recv`](Port::tx_recv) method, or any of the
//! other `tx_recv*` methods. Commands are constructed as tuples:
//! * Commands that do not require data take the form `(u8, Command)`, where
//!   * `u8` is the device address and
//!   * `Command` is some type that implements [`Command`](traits::Command) (the
//!     constants in the [`command`] module are highly recommended but you can
//!     also use a `u8`).
//!
//! ```
//! # use zproto::{
//! #     binary::Port,
//! #     backend::Backend,
//! # };
//! # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
//! // Send the Home command to all devices (address 0)
//! use zproto::binary::command::HOME;
//! let reply = port.tx_recv((0, HOME))?;
//! # Ok(())
//! # }
//! ```
//!
//! * Commands that do require data take a form similar to above, `(u8, Command, Data)`,
//! where `u8` and `Command` are the same and `Data` is some type that implements
//! [`Data`](traits::Data). This includes types like `i32`, `bool`, [`command`],
//! and other types.
//!
//! ```
//! # use zproto::{
//! #     binary::Port,
//! #     backend::Backend,
//! # };
//! # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
//! // Move device 1 to the absolute position 10,000.
//! use zproto::binary::command::*;
//! let reply = port.tx_recv((1, MOVE_ABSOLUTE, 10000))?;
//! // OR
//! let reply = port.tx_recv((0, RETURN_SETTING, SET_TARGET_SPEED))?;
//! # Ok(())
//! # }
//! ```
//!
//! If the response is an [`ERROR`](command::ERROR) or is otherwise unexpected
//! (e.g., from a different device) an error will be returned.
//!
//! **NOTE**: Address aliases other than 0 (all devices) are presently not
//! supported. Responses to such messages will be treated as unexpected by the
//! [`tx_recv*`](Port::tx_recv) methods.
//!
//! ## Other `Port` Methods
//!
//! [`tx_recv`](Port::tx_recv) works great when you need to send one command and
//! receive one response. But, when you have a chain of devices, you may need to
//! read a response from all devices in the chain. When you know the number of
//! devices in the chain, you can use [`tx_recv_n`](Port::tx_recv_n) to read `n`
//! responses to a command. If you don't know the number of devices in the chain
//! you can use [`tx_recv_until_timeout`](Port::tx_recv_until_timeout) to read as
//! many responses as possible.
//!
//! Sometimes you only want to transmit or receive data, but not both. In those
//! cases the [`tx`](Port::tx), [`recv`](Port::recv), [`recv_n`](Port::recv_n),
//! and [`recv_until_timeout`](Port::recv_until_timeout) are very helpful.
//!
//! Finally, a common pattern is to poll a device until it is in a desired
//! state, which you can do with the [`poll_until`](Port::poll_until) and
//! [`poll_until_idle`](Port::poll_until_idle) methods.
//!
//! ## Reading Data
//!
//! Reading data from a response is as simple as calling [`data()`](Message::data)
//! on the response. If the command was sent using the strongly typed commands
//! in the [`command`] module, the library will pick the correct type conversion
//! for you at compile time.
//!
//! ```
//! # use zproto::{
//! #     binary::Port,
//! #     backend::Backend,
//! # };
//! # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
//! use zproto::binary::command::*;
//! let reply = port.tx_recv((0, RETURN_SETTING, SET_TARGET_SPEED))?;
//! let speed = reply.data()?; // `speed` is an `i32`
//! let reply = port.tx_recv((0, RETURN_SETTING, SET_HOME_STATUS))?;
//! let homed = reply.data()?;  // `homed` is a `bool`.
//! # Ok(())
//! # }
//! ```
//!
//! ## Type Safety
//!
//! The library uses Rust's type system and the strongly-typed commands in the
//! [`command`] module to help enforce proper message structure and avoid
//! run-time bugs. For instance, not passing data to commands that require data,
//! or passing the wrong data type, will result in a compile time error.
//!
//! ```compile_fail
//! # use zproto::{
//! #     binary::Port,
//! #     backend::Backend,
//! # };
//! # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
//! use zproto::binary::command::*;
//! let reply = port.tx_recv((0, MOVE_ABSOLUTE))?;  // ERROR: the data field is missing!
//! let reply = port.tx_recv((0, MOVE_ABSOLUTE, true))?;  // ERROR: the data has the incorrect type!
//! let reply = port.tx_recv((0, RESET));  // ERROR: Devices do not respond to the RESET command!
//! # Ok(())
//! # }
//! ```
//!
//! To do this, each command in the [`command`] module is given a unique type
//! that implement a set of [`traits`]. These tell the compiler what kind of
//! data the command takes, what kind of data it returns, and if it returns a
//! response at all. However, this means that the commands cannot be swapped out
//! for one another at run time or stored in a collection.
//!
//! ```compile_fail
//! // This will not compile because SET_TARGET_SPEED and SET_ACCELERATION
//! // are different types.
//! use zproto::binary::command::*;
//! let commands = [(0, SET_TARGET_SPEED, 10000), (0, SET_ACCELERATION, 5000)];
//! ```
//!
//! To accommodate situations like this, the library provides "untyped" versions
//! of the command in the [`command::untyped`] module. The commands in that
//! module are simply `u8`s and can be used anywhere their strongly-typed
//! counterparts can.
//!
//! ```
//! // This works now.
//! use zproto::binary::command::untyped::*;
//! let commands = [(0, SET_TARGET_SPEED, 10000), (0, SET_ACCELERATION, 5000)];
//! ```
//!
//! However, you will not have any of the nice compile time type safety or
//! automatic type conversion -- you will have to pick the types yourself.
//!
//! ```
//! # use zproto::{
//! #     binary::Port,
//! #     backend::Backend,
//! # };
//! # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
//! use zproto::binary::command::untyped::*;
//! let reply = port.tx_recv((0, RETURN_SETTING, SET_TARGET_SPEED))?;
//! let speed: i32 = reply.data()?; // Notice that the type must be specified.
//! // The compiler cannot tell if you have picked the wrong type so this will
//! // compile, but the data conversion will fail at run time.
//! let speed: bool = reply.data()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Handling Compile-time Errors
//!
//! The traits in this crate are named so that their meaning is hopefully clear,
//! but, nevertheless, the compiler errors can sometimes be confusing. Here are
//! some errors that you might see and suggestions for correcting them.
//!
//! #### `TakesData` is not Satisfied
//!
//! ```sh
//! the trait `TakesData<{integer}>` is not implemented for ...
//! ```
//!
//! There are two reasons for this error:
//! 1. The command does not take any data argument. Try restructuring the message from `(address, command, data)` to `(address, command)`.
//! 2. The command requires a data argument with a different type. Consult the [`documentation for the command`](command) and use the data type listed there.
//!
//! #### `TakesNoData` is not Satisfied
//!
//! ```sh
//! the trait `TakesNoData` is not implemented for ...
//! ```
//!
//! The command likely requires a data argument. Try restructuring the message from `(address, command)` to `(address, command, data)`.
//!
//! #### `ElicitsResponse` is not Satisfied
//!
//! ```sh
//! the trait `ElicitsResponse` is not implemented for ...
//! ```
//!
//! This means the command does not elicit a response from a device and the
//! [`Port::tx_recv`] family of functions would eventually time out waiting for
//! one. Try transmitting the command without reading a reply with
//! [`tx`](Port::tx) instead.
//!

pub mod command;
mod port;
pub mod traits;

use std::convert::Infallible;

use crate::error;
pub use port::*;

/// A Binary Protocol message.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Message<C = u8> {
    /// The targeted device
    target: u8,
    /// The command code
    command: C,
    /// The command data
    data: [u8; 4],
    /// The message ID
    id: Option<u8>,
}

impl<C> Message<C> {
    /// Get the message target.
    pub const fn target(&self) -> u8 {
        self.target
    }

    /// Get the raw message data without decoding it.
    pub const fn raw_data(&self) -> [u8; 4] {
        self.data
    }

    /// Get the message id, if there is one.
    pub const fn id(&self) -> Option<u8> {
        self.id
    }
}

impl<C: traits::Command> Message<C> {
    /// Get the message command code.
    pub fn command(&self) -> u8 {
        self.command.command()
    }

    /// Get the decoded message data.
    ///
    /// The type `T` to decode to is determined by the implementation of
    /// `ReplyData` for the command type `C`. For the types defined in
    /// [`command`], there is only one data type. For other command types, like
    /// `u8` (the type of the commands in [`command::untyped`]) any data type is
    /// supported (though the conversion may fail at run time), so you will need
    /// to specify the appropriate data type to decode.
    ///
    /// ## Example
    ///
    /// ```
    /// # use zproto::{
    /// #     binary::Port,
    /// #     backend::Backend,
    /// # };
    /// # fn wrapper<B: Backend>(mut port: Port<B>) -> Result<(), Box<dyn std::error::Error>> {
    /// use zproto::binary::command::*;
    /// let reply = port.tx_recv((0, RETURN_SETTING, SET_HOME_STATUS))?;
    /// let homed = reply.data()?;  // `homed` is a `bool`
    /// let reply = port.tx_recv((0, RETURN_SETTING, untyped::SET_HOME_STATUS))?;
    /// let homed: bool = reply.data()?;  // The data type must be explicitly defined here
    /// # Ok(())
    /// # }
    /// ```
    pub fn data<T>(&self) -> Result<T, T::Error>
    where
        T: traits::Data,
        C: traits::ReplyData<T>,
    {
        T::try_from_data(self.data)
    }

    /// Get the message without any type constraints on it.
    pub fn to_untyped(&self) -> Message<u8> {
        Message {
            target: self.target(),
            command: self.command.command(),
            data: self.data,
            id: self.id,
        }
    }

    /// Try to construct a strongly-typed `Message` from an "untyped" one.
    pub fn try_from_untyped(
        other: Message,
    ) -> Result<Message<C>, error::BinaryUnexpectedCommandError> {
        if let Ok(command) = C::try_from(other.command()) {
            Ok(Message {
                target: other.target,
                command,
                data: other.data,
                id: other.id,
            })
        } else {
            Err(error::BinaryUnexpectedCommandError::new(other))
        }
    }
}

impl Message<u8> {
    /// Parse an array of 6 bytes into a [`Message`].
    ///
    /// Set `id` to `true` if the response is expected to contain a message ID.
    pub(crate) const fn from_bytes(bytes: &[u8; 6], id: bool) -> Message<u8> {
        Message {
            target: bytes[0],
            command: bytes[1],
            data: [bytes[2], bytes[3], bytes[4], if id { 0 } else { bytes[5] }],
            id: if id { Some(bytes[5]) } else { None },
        }
    }
}

impl<C> std::fmt::Display for Message<C>
where
    C: traits::Command,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "[{}, {}, {}",
            self.target,
            self.command.command(),
            i32::from_le_bytes(self.raw_data())
        )?;
        if let Some(id) = self.id() {
            write!(f, "{}]", id)
        } else {
            write!(f, "]")
        }
    }
}

/// Represents a version of firmware.
///
/// For convenience it is comparable to [`f32`].
///
/// ```
/// # use zproto::binary::Version;
/// let version = Version::new(7, 24).unwrap();
/// assert_eq!(version, 7.24);
/// ```
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Version(i32);

impl Version {
    /// Create a new version
    pub fn new(major: i32, minor: i32) -> Result<Self, std::num::TryFromIntError> {
        if minor % 100 != minor {
            Err(u8::try_from(-1).unwrap_err())
        } else {
            Ok(Version(major * 100 + minor % 100))
        }
    }

    /// Get the major version
    pub fn major(&self) -> i32 {
        self.0 / 100
    }
    /// Get the minor version
    pub fn minor(&self) -> i32 {
        self.0 % 100
    }
}

impl traits::Data for Version {
    type Error = Infallible;
    fn fill_data(&self, _: &mut [u8]) {
        // This type can never be sent
        unimplemented!();
    }
    fn try_from_data(buffer: [u8; 4]) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        Ok(Version(i32::try_from_data(buffer)?))
    }
}

impl PartialEq<f32> for Version {
    // Ignore clippy warnings about allocating just for comparison -- it is a
    // false positive in this case.
    #[allow(clippy::cmp_owned)]
    fn eq(&self, other: &f32) -> bool {
        f32::from(*self) == *other
    }
}

impl PartialEq<Version> for f32 {
    // Ignore clippy warnings about allocating just for comparison -- it is a
    // false positive in this case.
    #[allow(clippy::cmp_owned)]
    fn eq(&self, other: &Version) -> bool {
        *self == f32::from(*other)
    }
}

impl From<Version> for f32 {
    fn from(other: Version) -> Self {
        other.major() as f32 + other.minor() as f32 / 100f32
    }
}

/// Define an enum for device status and all associated traits.
macro_rules! define_status {
    (pub enum $name:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
        /// The status of a device.
        #[derive(Debug, Copy, Clone, PartialEq)]
        #[non_exhaustive]
        #[allow(missing_docs)]
        pub enum $name {
            $($variant = $value),+
        }

        impl From<$name> for i32 {
            fn from(value: $name) -> i32 {
                value as i32
            }
        }

        impl PartialEq<i32> for $name {
            fn eq(&self, other: &i32) -> bool {
                *self as i32 == *other
            }
        }

        impl PartialEq<$name> for i32 {
            fn eq(&self, other: &$name) -> bool {
                other == self
            }
        }

        impl TryFrom<i32> for $name {
            type Error = std::num::TryFromIntError;

            fn try_from(value: i32) -> Result<Self, Self::Error> {
                match value {
                    $($value => Ok($name::$variant)),+
                    ,
                    _ => Err(u8::try_from(-1).unwrap_err()),
                }
            }
        }

        impl traits::Data for $name {
            type Error = std::num::TryFromIntError;
            fn fill_data(&self, _: &mut[u8]) {
                // This data type should never be sent to a device.
                unimplemented!();
            }

            fn try_from_data(buffer: [u8; 4]) -> Result<Self, Self::Error> {
                $name::try_from(i32::from_le_bytes(buffer))
            }
        }
    };
}

define_status! {
    pub enum Status {
        Idle = 0,
        ExecutingHoming = 1,
        ExecutingManualVelocityMove = 10,
        ExecutingManualDisplacementMove = 11,
        StalledStoppedOrDisplacedWhileStationary = 13,
        ExecutingMoveStored = 18,
        ExecutingMoveAbsolute = 20,
        ExecutingMoveRelative = 21,
        ExecutingMoveConstantSpeed = 22,
        ExecutingStop = 23,
        Parked = 65,
        ExecutingMoveIndex = 78,
        DriverDisabled = 90,
        PeripheralInactive = 93,
        ExecutingMotion = 99,
    }
}

/// The state of multiple digital I/O channels.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct IoStates(u32);

impl IoStates {
    /// Return whether a channel is high.
    ///
    /// The `channel` index is one-based. This function will panic if `channel`
    /// is 0 or greater than 32.
    pub fn is_high(&self, channel: usize) -> bool {
        self.is_high_checked(channel)
            .expect("`channel` must be in the range (1, 32)")
    }

    /// Return whether a channel is high.
    ///
    /// The `channel` index is one-based. `None` is returned if `channel` is 0
    /// or greater than 32.
    pub const fn is_high_checked(&self, channel: usize) -> Option<bool> {
        if channel > 0 && channel <= 32 {
            Some(self.0 & (1 << (channel - 1)) != 0)
        } else {
            None
        }
    }
}

impl traits::Data for IoStates {
    type Error = Infallible;
    fn fill_data(&self, _: &mut [u8]) {
        // This type can never be sent
        unimplemented!();
    }
    fn try_from_data(buffer: [u8; 4]) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        Ok(IoStates(i32::try_from_data(buffer)? as u32))
    }
}

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

    #[test]
    fn version() {
        let version = Version(723);
        assert_eq!(version.major(), 7);
        assert_eq!(version.minor(), 23);

        assert_eq!(version, 7.23);
        assert_eq!(version, Version::new(7, 23).unwrap());

        assert!(Version::new(7, 100).is_err());
    }

    #[test]
    fn io_states() {
        let states = IoStates(0b101);
        assert_eq!(states.is_high(1), true);
        assert_eq!(states.is_high(2), false);
        assert_eq!(states.is_high(3), true);
        assert_eq!(states.is_high(4), false);
        assert_eq!(states.is_high(32), false);
    }

    #[test]
    #[should_panic]
    fn io_state_index_0() {
        let states = IoStates(1);
        states.is_high(0);
    }

    #[test]
    #[should_panic]
    fn io_state_index_gt_32() {
        let states = IoStates(1);
        states.is_high(33);
    }

    #[test]
    fn device_message_parsing_invalid_command_code() {
        use crate::binary::command::{types::*, untyped};

        // Incorrect command value results in an error.
        let err = Message::<SetHomeSpeed>::try_from_untyped(Message::from_bytes(
            &[3, untyped::SET_ACCELERATION, 0, 0, 0, 1],
            false,
        ))
        .unwrap_err();
        assert_eq!(
            Message::from(err),
            Message::from_bytes(&[3, untyped::SET_ACCELERATION, 0, 0, 0, 1], false)
        );
    }

    #[test]
    fn device_message_passing_with_id() {
        use crate::binary::command::{types::*, untyped};

        // Parsing a message with an ID works properly.
        let message: Message<SetHomeSpeed> = Message::try_from_untyped(Message::from_bytes(
            &[3, untyped::SET_HOME_SPEED, 2, 0, 0, 1],
            true,
        ))
        .unwrap();
        assert_eq!(message.target(), 3);
        assert_eq!(message.id(), Some(1));
        assert_eq!(message.command(), untyped::SET_HOME_SPEED);
        assert_eq!(message.data().unwrap(), 2);
    }

    #[test]
    fn device_message_passing_without_id() {
        use crate::binary::command::{types::*, untyped};

        // Parsing a message without an ID works properly.
        let message: Message<SetHomeSpeed> = Message::try_from_untyped(Message::from_bytes(
            &[3, untyped::SET_HOME_SPEED, 2, 0, 0, 1],
            false,
        ))
        .unwrap();
        assert_eq!(message.target(), 3);
        assert_eq!(message.id(), None);
        assert_eq!(message.command(), untyped::SET_HOME_SPEED);
        assert_eq!(message.data().unwrap(), i32::from_le_bytes([2, 0, 0, 1]));
    }
}