hermes-five 0.1.0

The Rust Robotics & IoT Platform
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
use crate::errors::Error;
use crate::hardware::Hardware;
use crate::io::{IoData, IoTransport, RemoteIo, IO};
use crate::io::{IoProtocol, PinModeId};
use crate::utils::{task, Range};
use crate::utils::{EventHandler, EventManager};
use parking_lot::RwLock;
use std::fmt::Display;
use std::sync::Arc;

/// Lists all events a Board can emit/listen.
pub enum BoardEvent {
    /// Triggered when the board connexion is established and the handshake has been made.
    OnReady,
    /// Triggered when the board connexion is closed (gracefully).
    OnClose,
}

/// Convert events to string to facilitate usage with [`EventManager`].
impl From<BoardEvent> for String {
    fn from(value: BoardEvent) -> Self {
        let event = match value {
            BoardEvent::OnReady => "ready",
            BoardEvent::OnClose => "close",
        };
        event.into()
    }
}

/// Represents a physical board (Arduino most-likely) where your [`crate::devices::Device`] can be attached and controlled through this API.
/// The board gives access to [`IoData`] through a communication [`IoProtocol`].
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct Board {
    /// The event manager for the board.
    #[cfg_attr(feature = "serde", serde(skip))]
    events: EventManager,
    /// The inner protocol used by this Board.
    protocol: Box<dyn IoProtocol>,
}

impl Default for Board {
    /// Default implementation for a board.
    ///
    /// This method creates a board using the default [`RemoteIo`] protocol with [`Serial`](crate::io::Serial) transport layer.
    /// The port will be auto-detected as the first available serial port matching a board.
    ///
    /// **_/!\ The board will NOT be connected until the [`Board::open`] method is called._**
    ///
    /// # Example
    ///
    /// ```
    /// use hermes_five::hardware::Board;
    /// use hermes_five::io::RemoteIo;
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     // Following lines are all equivalent:
    ///     let board = Board::run();
    ///     let board = Board::default().open();
    ///     let board = Board::new(RemoteIo::default()).open();
    /// }
    /// ```
    fn default() -> Self {
        Self::new(RemoteIo::default())
    }
}

/// Creates a board using the given transport layer with the RemoteIo protocol.
///
/// # Example
/// ```
/// use hermes_five::hardware::Board;
/// use hermes_five::io::RemoteIo;
/// use hermes_five::io::Serial;
///
/// #[hermes_five::runtime]
/// async fn main() {
///     let board = Board::from(Serial::new("/dev/ttyUSB0")).open();
/// }
/// ```
impl<T: IoTransport> From<T> for Board {
    fn from(transport: T) -> Self {
        Self {
            events: Default::default(),
            protocol: Box::new(RemoteIo::from(transport)),
        }
    }
}

impl Board {
    /// Creates and open a default board (using default protocol).
    ///
    /// This method creates a board using the default [`RemoteIo`] protocol with [`Serial`](crate::io::Serial) transport layer.
    /// The port will be auto-detected as the first available serial port matching a board.
    ///
    /// # Example
    /// ```
    /// use hermes_five::hardware::Board;
    /// use hermes_five::io::RemoteIo;
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     // Following lines are all equivalent:
    ///     let board = Board::run();
    ///     let board = Board::default().open();
    ///     let board = Board::new(RemoteIo::default()).open();
    /// }
    /// ```
    pub fn run() -> Self {
        Self::default().open()
    }

    /// Creates a board using a given protocol.
    ///
    /// # Example
    /// ```
    /// use hermes_five::hardware::Board;
    /// use hermes_five::io::RemoteIo;
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     let board = Board::new(RemoteIo::new("COM4")).open();
    /// }
    /// ```
    pub fn new<P: IoProtocol + 'static>(protocol: P) -> Self {
        Self {
            events: EventManager::default(),
            protocol: Box::new(protocol),
        }
    }

    /// Starts a board connexion procedure (using the appropriate configured protocol) in an asynchronous way.
    /// _Note 1:    you probably might not want to call this method yourself and use [`Self::run()`] instead._
    /// _Note 2:    after this method, you cannot consider the board to be connected until you receive the "ready" event._
    ///
    /// # Example
    ///
    /// Have a look at the examples/board folder more detailed examples.
    ///
    /// ```
    /// use hermes_five::hardware::{Board, BoardEvent};
    /// use hermes_five::io::IO;
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     let board = Board::run();
    ///     // Is equivalent to:
    ///     let mut board = Board::default().open();
    ///
    ///     // Register something to do when the board is connected.
    ///     board.on(BoardEvent::OnReady, |_: Board| async move {
    ///         // Something to do when connected.
    ///         Ok(())
    ///     });
    ///     // code here will be executed right away, before the board is actually connected.
    /// }
    /// ```
    pub fn open(self) -> Self {
        let events_clone = self.events.clone();
        let callback_board = self.clone();

        task::run(async move {
            let board = callback_board.blocking_open()?;
            events_clone.emit(BoardEvent::OnReady, board);
            Ok(())
        })
        .expect("Task failed");

        self
    }

    /// Close a board connexion (using the appropriate configured protocol) in an asynchronous way.
    /// _Note:    after this method, you cannot consider the board to be connected until you receive the "close" event._
    ///
    /// # Example
    ///
    /// Have a look at the examples/board folder more detailed examples.
    ///
    /// ```
    /// use hermes_five::pause;
    /// use hermes_five::hardware::{Board, BoardEvent};
    /// use hermes_five::io::IO;
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     let board = Board::run();
    ///     board.on(BoardEvent::OnReady, |mut board: Board| async move {
    ///         // Something to do when connected.
    ///         pause!(3000);
    ///         board.close();
    ///         Ok(())
    ///     });
    ///     board.on(BoardEvent::OnClose, |_: Board| async move {
    ///         // Something to do when connection closes.
    ///         Ok(())
    ///     });
    /// }
    /// ```
    pub fn close(self) -> Self {
        let events = self.events.clone();
        let callback_board = self.clone();
        task::run(async move {
            let board = callback_board.blocking_close()?;
            events.emit(BoardEvent::OnClose, board);
            Ok(())
        })
        .expect("Task failed");
        self
    }

    /// Blocking version of [`Self::open()`] method.
    pub fn blocking_open(mut self) -> Result<Self, Error> {
        self.protocol.open()?;
        // trace!"Board is ready: {:#?}", self.get_io());
        Ok(self)
    }

    /// Blocking version of [`Self::close()`] method.
    pub fn blocking_close(mut self) -> Result<Self, Error> {
        // Detach all pins.
        let pins: Vec<u8> = self.get_io().read().pins.keys().copied().collect();
        for id in pins {
            let _ = self.set_pin_mode(id, PinModeId::OUTPUT);
        }
        self.protocol.close()?;
        // trace!"Board is closed");
        Ok(self)
    }

    /// Registers a callback to be executed on a given event.
    ///
    /// Available events for a board are defined by the enum: [`BoardEvent`]:
    /// - **`OnRead` | `ready`:** Triggered when the board is connected and ready to run.    
    ///    _The callback must receive the following parameter: `|_: Board| { ... }`_
    /// - **`OnClose` | `close`:** Triggered when the board is disconnected.        
    ///    _The callback must receive the following parameter: `|_: Board| { ... }`_
    ///
    /// # Example
    ///
    /// ```
    /// use hermes_five::hardware::{Board, BoardEvent};
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     let board = Board::run();
    ///     board.on(BoardEvent::OnReady, |_: Board| async move {
    ///         // Here, you know the board to be connected and ready to receive data.
    ///         Ok(())
    ///     });
    /// }
    /// ```
    pub fn on<S, F, T, Fut>(&self, event: S, callback: F) -> EventHandler
    where
        S: Into<String>,
        T: 'static + Send + Sync + Clone,
        F: FnMut(T) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<(), Error>> + Send + 'static,
    {
        self.events.on(event, callback)
    }
}

impl Hardware for Board {
    fn get_protocol(&self) -> Box<dyn IoProtocol> {
        self.protocol.clone()
    }

    #[cfg(not(tarpaulin_include))]
    fn set_protocol(&mut self, protocol: Box<dyn IoProtocol>) {
        self.protocol = protocol;
    }
}

// Note: no need to test cover: those are simple pass through only.
#[cfg(not(tarpaulin_include))]
impl IO for Board {
    /// Easy access to hardware through the board.
    ///
    /// # Example
    /// ```
    /// use hermes_five::hardware::Board;
    /// use hermes_five::hardware::BoardEvent;
    /// use hermes_five::io::IO;
    ///
    /// #[hermes_five::runtime]
    /// async fn main() {
    ///     let board = Board::run();
    ///     board.on(BoardEvent::OnReady, |mut board: Board| async move {
    ///         println!("Board connected: {}", board);
    ///         println!("Pins {:#?}", board.get_io().read().pins);
    ///         Ok(())
    ///     });
    /// }
    fn get_io(&self) -> &Arc<RwLock<IoData>> {
        self.protocol.get_io()
    }

    fn is_connected(&self) -> bool {
        self.protocol.is_connected()
    }

    fn set_pin_mode(&mut self, pin: u8, mode: PinModeId) -> Result<(), Error> {
        self.protocol.set_pin_mode(pin, mode)
    }

    fn digital_write(&mut self, pin: u8, level: bool) -> Result<(), Error> {
        self.protocol.digital_write(pin, level)
    }

    fn analog_write(&mut self, pin: u8, level: u16) -> Result<(), Error> {
        self.protocol.analog_write(pin, level)
    }

    #[cfg(not(tarpaulin_include))]
    fn digital_read(&mut self, _: u8) -> Result<bool, Error> {
        unimplemented!()
    }

    #[cfg(not(tarpaulin_include))]
    fn analog_read(&mut self, _: u8) -> Result<u16, Error> {
        unimplemented!()
    }

    fn servo_config(&mut self, pin: u8, pwm_range: Range<u16>) -> Result<(), Error> {
        self.protocol.servo_config(pin, pwm_range)
    }

    fn i2c_config(&mut self, delay: u16) -> Result<(), Error> {
        self.protocol.i2c_config(delay)
    }

    fn i2c_read(&mut self, address: u8, size: u16) -> Result<(), Error> {
        self.protocol.i2c_read(address, size)
    }

    fn i2c_write(&mut self, address: u8, data: &[u16]) -> Result<(), Error> {
        self.protocol.i2c_write(address, data)
    }
}

impl Display for Board {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Board ({})", self.protocol)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::Serial;
    use crate::io::IO;
    use crate::mocks::plugin_io::MockIoProtocol;
    use crate::mocks::transport_layer::MockTransportLayer;
    use crate::pause;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    #[test]
    fn test_board_default() {
        // Default board can be created.
        let board = Board::default();
        assert_eq!(
            board.get_protocol_name(),
            "RemoteIo",
            "Default board uses the default protocol"
        );
    }

    #[test]
    fn test_board_from() {
        // Custom protocol can be used.
        let board = Board::new(MockIoProtocol::default());
        assert_eq!(
            board.get_protocol_name(),
            "MockIoProtocol",
            "Board can be created with a custom protocol"
        );
        // Custom transport can be used.
        let board = Board::from(Serial::default());
        assert_eq!(
            board.get_protocol_name(),
            "RemoteIo",
            "Board can be created with a custom transport"
        );
    }

    #[hermes_five_macros::test]
    async fn test_board_open() {
        let mut transport = MockTransportLayer {
            read_index: 10,
            ..Default::default()
        };
        // Result for query firmware
        transport.read_buf[10..15].copy_from_slice(&[0xF0, 0x79, 0x01, 0x0C, 0xF7]);
        // Result for report capabilities
        transport.read_buf[15..26].copy_from_slice(&[
            0xF0, 0x6C, 0x00, 0x08, 0x7F, 0x00, 0x08, 0x01, 0x08, 0x7F, 0xF7,
        ]);
        // Result for analog mapping
        transport.read_buf[26..32].copy_from_slice(&[0xF0, 0x6A, 0x7F, 0x7F, 0x7F, 0xF7]);

        let flag = Arc::new(AtomicBool::new(false));
        let moved_flag = flag.clone();
        let board = Board::new(RemoteIo::from(transport)).open();
        board.on(BoardEvent::OnReady, move |board: Board| {
            let captured_flag = moved_flag.clone();
            async move {
                captured_flag.store(true, Ordering::SeqCst);
                assert!(board.is_connected());
                Ok(())
            }
        });
        pause!(500);
        assert!(flag.load(Ordering::SeqCst));
    }

    #[test]
    fn test_board_blocking_open() {
        let mut transport = MockTransportLayer {
            read_index: 10,
            ..Default::default()
        };
        // Result for query firmware
        transport.read_buf[10..15].copy_from_slice(&[0xF0, 0x79, 0x01, 0x0C, 0xF7]);
        // Result for report capabilities
        transport.read_buf[15..26].copy_from_slice(&[
            0xF0, 0x6C, 0x00, 0x08, 0x7F, 0x00, 0x08, 0x01, 0x08, 0x7F, 0xF7,
        ]);
        // Result for analog mapping
        transport.read_buf[26..32].copy_from_slice(&[0xF0, 0x6A, 0x7F, 0x7F, 0x7F, 0xF7]);

        let protocol = RemoteIo::from(transport);
        let board = Board::new(protocol).blocking_open().unwrap();
        assert!(board.is_connected());
    }

    #[hermes_five_macros::test]
    async fn test_board_close() {
        let flag = Arc::new(AtomicBool::new(false));
        let moved_flag = flag.clone();

        let board = Board::new(MockIoProtocol::default()).open().close();

        board.on(BoardEvent::OnClose, move |board: Board| {
            let captured_flag = moved_flag.clone();
            async move {
                captured_flag.store(true, Ordering::SeqCst);
                assert!(!board.is_connected());
                Ok(())
            }
        });

        pause!(1000);
        assert!(flag.load(Ordering::SeqCst));
        assert!(!board.is_connected());
    }

    #[hermes_five_macros::test]
    fn test_board_run() {
        let board = Board::run();
        assert_eq!(board.get_protocol_name(), "RemoteIo");
        board.close();
    }

    #[test]
    fn test_board_get_hardware() {
        let board = Board::new(MockIoProtocol::default());
        assert_eq!(board.get_io().read().protocol_version, "fake.1.0");
    }

    #[test]
    fn test_board_display() {
        let board = Board::new(MockIoProtocol::default());
        let output = format!("{}", board);
        assert_eq!(
            output,
            "Board (MockIoProtocol [firmware=Fake protocol, version=fake.2.3, protocol=fake.1.0])"
        );
    }
}

#[cfg(feature = "serde")]
#[cfg(test)]
mod serde_tests {
    use crate::hardware::{Board, Hardware};
    use crate::io::RemoteIo;
    use crate::mocks::plugin_io::MockIoProtocol;

    #[test]
    fn test_board_serialize() {
        let board = Board::new(RemoteIo::new("mock"));
        let json = serde_json::to_string(&board).unwrap();
        assert_eq!(
            json,
            r#"{"protocol":{"type":"RemoteIo","transport":{"type":"Serial","port":"mock"}}}"#
        );

        let board = Board::new(MockIoProtocol::default());
        let json = serde_json::to_string(&board).unwrap();
        assert_eq!(json, r#"{"protocol":{"type":"MockIoProtocol"}}"#);
    }

    #[test]
    fn test_board_deserialize() {
        let json =
            r#"{"protocol":{"type":"RemoteIo","transport":{"type":"Serial","port":"mock"}}}"#;
        let board: Board = serde_json::from_str(json).unwrap();
        assert_eq!(board.get_protocol_name(), "RemoteIo");

        let json = r#"{"protocol":{"type":"MockIoProtocol"}}"#;
        let board: Board = serde_json::from_str(json).unwrap();
        assert_eq!(board.get_protocol_name(), "MockIoProtocol");
    }
}