flipdot 0.8.0

A library for interacting with Luminator flip-dot and LED signs over RS-485
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
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
use std::cell::RefCell;
use std::iter;
use std::rc::Rc;

use log::warn;
use thiserror::Error;

use crate::core::{Address, ChunkCount, Data, Message, Offset, Operation, Page, PageFlipStyle, PageId, SignBus, SignType, State};

/// Errors related to [`Sign`]s.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SignError {
    /// The sign bus failed to process a message.
    #[error("Sign bus failed to process message")]
    Bus {
        /// The underlying bus error.
        #[from]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Sign did not respond properly according to the protocol.
    #[error(
        "Sign did not respond properly according to the protocol: Expected {}, got {}",
        expected,
        actual
    )]
    UnexpectedResponse {
        /// The expected response according to the protocol.
        expected: String,

        /// The actual response received.
        actual: String,
    },
}

/// A single sign on an associated bus.
///
/// Basic operation consists of configuring the sign, sending one or more pages of a message,
/// then requesting a page flip as desired. The types of signs that are supported are "dumb"
/// in that they don't have any display logic of their own; all operations are remotely controlled.
///
/// # Examples
///
/// ```no_run
/// use std::cell::RefCell;
/// use std::rc::Rc;
/// use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType, SerialSignBus};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #
/// // Set up bus. Because the bus can be shared among
/// // multiple signs, it must be wrapped in an Rc<RefCell>.
/// let port = serial::open("/dev/ttyUSB0")?;
/// let bus = SerialSignBus::try_new(port)?;
/// let bus = Rc::new(RefCell::new(bus));
///
/// // Create a sign with the appropriate address and type.
/// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
///
/// // First, the configuration data must be sent to the sign.
/// sign.configure()?;
///
/// // Next, we can create some pages, turn on pixels, and send them to the sign.
/// let mut page1 = sign.create_page(PageId(0));
/// page1.set_pixel(0, 0, true);
/// let mut page2 = sign.create_page(PageId(1));
/// page2.set_pixel(1, 1, true);
/// if sign.send_pages(&[page1, page2])? == PageFlipStyle::Manual {
///     // The first page is now loaded in the sign's memory and can be shown.
///     sign.show_loaded_page()?;
///
///     // Load the second page into memory, then show it.
///     sign.load_next_page()?;
///     sign.show_loaded_page()?;
/// }
/// #
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct Sign {
    address: Address,
    sign_type: SignType,
    bus: Rc<RefCell<dyn SignBus>>,
}

impl Sign {
    /// Creates a new `Sign` with the given address and type, which will represent and control
    /// an actual sign on the provided [`SignBus`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageId, Sign, SignType};
    /// # use flipdot_testing::VirtualSignBus;
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> { Rc::new(RefCell::new(VirtualSignBus::new(vec![]))) }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// #
    /// # Ok(()) }
    /// ```
    pub fn new(bus: Rc<RefCell<dyn SignBus>>, address: Address, sign_type: SignType) -> Self {
        Sign { address, sign_type, bus }
    }

    /// Returns the sign's address.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageId, Sign, SignType};
    /// # use flipdot_testing::VirtualSignBus;
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> { Rc::new(RefCell::new(VirtualSignBus::new(vec![]))) }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// assert_eq!(Address(3), sign.address());
    /// #
    /// # Ok(()) }
    /// ```
    pub fn address(&self) -> Address {
        self.address
    }

    /// Returns the sign's type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageId, Sign, SignType};
    /// # use flipdot_testing::VirtualSignBus;
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> { Rc::new(RefCell::new(VirtualSignBus::new(vec![]))) }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// assert_eq!(SignType::Max3000Side90x7, sign.sign_type());
    /// #
    /// # Ok(()) }
    /// ```
    pub fn sign_type(&self) -> SignType {
        self.sign_type
    }

    /// Returns the width in pixels of the sign's display area.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageId, Sign, SignType};
    /// # use flipdot_testing::VirtualSignBus;
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> { Rc::new(RefCell::new(VirtualSignBus::new(vec![]))) }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// assert_eq!(90, sign.width());
    /// #
    /// # Ok(()) }
    /// ```
    pub fn width(&self) -> u32 {
        self.sign_type.dimensions().0
    }

    /// Returns the height in pixels of the sign's display area.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageId, Sign, SignType};
    /// # use flipdot_testing::VirtualSignBus;
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> { Rc::new(RefCell::new(VirtualSignBus::new(vec![]))) }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// assert_eq!(7, sign.height());
    /// #
    /// # Ok(()) }
    /// ```
    pub fn height(&self) -> u32 {
        self.sign_type.dimensions().1
    }

    /// Creates a page with the given ID that matches the sign's dimensions.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageId, Sign, SignType};
    /// # use flipdot_testing::VirtualSignBus;
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> { Rc::new(RefCell::new(VirtualSignBus::new(vec![]))) }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// let mut page = sign.create_page(PageId(1));
    ///
    /// assert_eq!(PageId(1), page.id());
    /// assert_eq!(page.width(), sign.width());
    /// assert_eq!(page.height(), sign.height());
    ///
    /// page.set_pixel(1, 5, true);
    /// #
    /// # Ok(()) }
    /// ```
    pub fn create_page<'a>(&self, id: PageId) -> Page<'a> {
        let (x, y) = self.sign_type.dimensions();
        Page::new(id, x, y)
    }

    /// Opens communications with the sign and sends the necessary configuration.
    ///
    /// This or [`configure_if_needed`](Self::configure_if_needed) must be called first before communicating with the sign.
    /// If the sign has already been configured, it will be reset and its page memory will be cleared.
    ///
    /// This method will ensure you have a clean slate no matter how the sign was previously configured.
    ///
    /// # Errors
    ///
    /// Returns:
    /// * [`SignError::Bus`] if the underlying bus failed to process a message.
    /// * [`SignError::UnexpectedResponse`] if the sign did not send the expected response according
    ///   to the protocol. In this case it is recommended to re-[`configure`](Self::configure) the sign and start over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType};
    /// # use flipdot_testing::{VirtualSign, VirtualSignBus};
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> {
    /// #     Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
    /// # }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// sign.configure()?;
    /// // Sign is now ready to receive pages.
    /// #
    /// # Ok(()) }
    /// ```
    pub fn configure(&self) -> Result<(), SignError> {
        self.ensure_unconfigured()?;

        let config = self.sign_type.to_bytes();
        self.send_data(
            &iter::once(config),
            Operation::ReceiveConfig,
            State::ConfigReceived,
            State::ConfigFailed,
        )
    }

    /// Opens communications with the sign and sends the necessary configuration if needed.
    ///
    /// This or [`configure`](Self::configure) must be called first before communicating with the sign.
    /// If the sign has already been configured and is in a state where it can receive pages,
    /// nothing will happen. Otherwise, it will be reset and its page memory will be cleared.
    ///
    /// Use this if you are confident that the sign is already in a good state and doesn't need a full reset
    /// (e.g. updating periodically via a cron job).
    ///
    /// # Errors
    ///
    /// Returns:
    /// * [`SignError::Bus`] if the underlying bus failed to process a message.
    /// * [`SignError::UnexpectedResponse`] if the sign did not send the expected response according
    ///   to the protocol. In this case it is recommended to re-[`configure`](Self::configure) the sign and start over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType};
    /// # use flipdot_testing::{VirtualSign, VirtualSignBus};
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> {
    /// #     Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
    /// # }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// sign.configure_if_needed()?;
    /// // Sign is now ready to receive pages.
    /// #
    /// # Ok(()) }
    /// ```
    pub fn configure_if_needed(&self) -> Result<(), SignError> {
        let response = self.send_message(Message::Hello(self.address))?;
        match response {
            Some(Message::ReportState(address, State::ConfigReceived))
            | Some(Message::ReportState(address, State::ShowingPages))
            | Some(Message::ReportState(address, State::PageLoaded))
            | Some(Message::ReportState(address, State::PageShowInProgress))
            | Some(Message::ReportState(address, State::PageShown))
            | Some(Message::ReportState(address, State::PageLoadInProgress))
                if address == self.address => {}

            _ => self.configure()?,
        }
        Ok(())
    }

    /// Sends one or more pages of pixel data to the sign.
    ///
    /// Can be called at any time after [`configure`](Self::configure). Replaces any pages that had been previously sent.
    /// Upon return, the first page will be loaded and ready to be shown.
    ///
    /// # Errors
    ///
    /// Returns:
    /// * [`SignError::Bus`] if the underlying bus failed to process a message.
    /// * [`SignError::UnexpectedResponse`] if the sign did not send the expected response according
    ///   to the protocol. In this case it is recommended to re-[`configure`](Self::configure) the sign and start over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType};
    /// # use flipdot_testing::{VirtualSign, VirtualSignBus};
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> {
    /// #     Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
    /// # }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// sign.configure()?;
    ///
    /// let page = sign.create_page(PageId(1));
    /// if sign.send_pages(&[page])? == PageFlipStyle::Manual {
    ///     // Page has now been loaded but not shown.
    /// } else {
    ///     // Sign is now showing the page automatically.
    /// }
    /// #
    /// # Ok(()) }
    /// ```
    pub fn send_pages<'a, I>(&self, pages: I) -> Result<PageFlipStyle, SignError>
    where
        I: IntoIterator<Item = &'a Page<'a>>,
        <I as IntoIterator>::IntoIter: Clone,
    {
        let data = pages.into_iter().map(Page::as_bytes);
        self.send_data(&data, Operation::ReceivePixels, State::PixelsReceived, State::PixelsFailed)?;

        self.send_message_expect_response(Message::PixelsComplete(self.address), &None)?;

        let response = self.send_message(Message::QueryState(self.address))?;
        match response {
            Some(Message::ReportState(address, state)) if address == self.address && state == State::ShowingPages => {
                Ok(PageFlipStyle::Automatic)
            }
            _ => Ok(PageFlipStyle::Manual),
        }
    }

    /// Loads the next page into memory.
    ///
    /// Once a page has been shown, this is called to prepare the next page to be shown.
    ///
    /// If [`send_pages`](Self::send_pages) returned [`PageFlipStyle::Automatic`], you should not call this function since the sign will show and flip pages itself.
    ///
    /// # Errors
    ///
    /// Returns:
    /// * [`SignError::Bus`] if the underlying bus failed to process a message.
    /// * [`SignError::UnexpectedResponse`] if the sign did not send the expected response according
    ///   to the protocol. In this case it is recommended to re-[`configure`](Self::configure) the sign and start over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType};
    /// # use flipdot_testing::{VirtualSign, VirtualSignBus};
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> {
    /// #     Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
    /// # }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// sign.configure()?;
    ///
    /// let pages = [sign.create_page(PageId(1)), sign.create_page(PageId(2))];
    /// if sign.send_pages(&pages)? == PageFlipStyle::Manual {
    ///     sign.show_loaded_page()?;
    ///
    ///     sign.load_next_page()?;
    ///     // Page 1 is now shown and page 2 is loaded.
    /// }
    /// #
    /// # Ok(()) }
    /// ```
    pub fn load_next_page(&self) -> Result<(), SignError> {
        self.switch_page(State::PageLoaded, State::PageShown, Operation::LoadNextPage)
    }

    /// Shows the currently loaded page on the display.
    ///
    /// Once a page has been loaded (either via [`send_pages`](Self::send_pages) or [`load_next_page`](Self::load_next_page)), this method will make it visible.
    ///
    /// If [`send_pages`](Self::send_pages) returned [`PageFlipStyle::Automatic`], you should not call this function since the sign will show and flip pages itself.
    ///
    /// # Errors
    ///
    /// Returns:
    /// * [`SignError::Bus`] if the underlying bus failed to process a message.
    /// * [`SignError::UnexpectedResponse`] if the sign did not send the expected response according
    ///   to the protocol. In this case it is recommended to re-[`configure`](Self::configure) the sign and start over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType};
    /// # use flipdot_testing::{VirtualSign, VirtualSignBus};
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> {
    /// #     Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
    /// # }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// sign.configure()?;
    ///
    /// let page = sign.create_page(PageId(1));
    /// if sign.send_pages(&[page])? == PageFlipStyle::Manual {
    ///     sign.show_loaded_page()?;
    /// }
    /// // Page is now shown.
    /// #
    /// # Ok(()) }
    /// ```
    pub fn show_loaded_page(&self) -> Result<(), SignError> {
        self.switch_page(State::PageShown, State::PageLoaded, Operation::ShowLoadedPage)
    }

    /// Blanks the display and shuts the sign down.
    ///
    /// The sign will not be usable for 30 seconds after calling this method.
    /// Generally optional as disconnecting switched power from the sign should have the same effect.
    ///
    /// # Errors
    ///
    /// Returns:
    /// * [`SignError::Bus`] if the underlying bus failed to process a message.
    /// * [`SignError::UnexpectedResponse`] if the sign did not send the expected response according
    ///   to the protocol. In this case it is recommended to re-[`configure`](Self::configure) the sign and start over.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::cell::RefCell;
    /// # use std::rc::Rc;
    /// # use flipdot::{Address, PageFlipStyle, PageId, Sign, SignType};
    /// # use flipdot_testing::{VirtualSign, VirtualSignBus};
    /// #
    /// # // Placeholder bus for expository purposes
    /// # fn get_bus<'a>() -> Rc<RefCell<VirtualSignBus<'a>>> {
    /// #     Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
    /// # }
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #
    /// let bus = get_bus();
    /// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
    /// sign.configure()?;
    ///
    /// let page = sign.create_page(PageId(1));
    /// if sign.send_pages(&[page])? == PageFlipStyle::Manual {
    ///     sign.show_loaded_page()?;
    /// }
    ///
    /// sign.shut_down()?;
    /// // Sign is now blanked.
    /// #
    /// # Ok(()) }
    /// ```
    pub fn shut_down(&self) -> Result<(), SignError> {
        self.send_message_expect_response(Message::Goodbye(self.address), &None)
    }

    /// Borrows the bus mutably and sends a message.
    ///
    /// Enforces that only leaf calls borrow the bus to avoid runtime errors,
    /// and conveniently localizes the error chaining on failure.
    fn send_message(&self, message: Message<'_>) -> Result<Option<Message<'_>>, SignError> {
        let mut bus = self.bus.borrow_mut();
        Ok(bus.process_message(message)?)
    }

    /// Borrows the bus mutably, sends a message, and verifies that the response is as expected.
    ///
    /// Serves the same purpose as `send_message` when exactly one response is expected.
    fn send_message_expect_response(
        &self,
        message: Message<'_>,
        expected_response: &Option<Message<'_>>,
    ) -> Result<(), SignError> {
        let response = self.send_message(message)?;
        verify_response(expected_response, &response)
    }

    /// Ensures that the sign is in the `Unconfigured` state.
    ///
    /// If it already is, nothing to do. Otherwise start or finish a reset as appropriate.
    /// This ensures that the sign is in a known good state before we begin configuring it.
    fn ensure_unconfigured(&self) -> Result<(), SignError> {
        let response = self.send_message(Message::Hello(self.address))?;
        match response {
            Some(Message::ReportState(address, State::Unconfigured)) if address == self.address => {}

            Some(Message::ReportState(address, State::ReadyToReset)) if address == self.address => {
                self.send_message_expect_response(
                    Message::RequestOperation(self.address, Operation::FinishReset),
                    &Some(Message::AckOperation(self.address, Operation::FinishReset)),
                )?;

                self.send_message_expect_response(
                    Message::Hello(self.address),
                    &Some(Message::ReportState(self.address, State::Unconfigured)),
                )?;
            }

            _ => {
                self.send_message_expect_response(
                    Message::RequestOperation(self.address, Operation::StartReset),
                    &Some(Message::AckOperation(self.address, Operation::StartReset)),
                )?;

                self.send_message_expect_response(
                    Message::Hello(self.address),
                    &Some(Message::ReportState(self.address, State::ReadyToReset)),
                )?;

                self.send_message_expect_response(
                    Message::RequestOperation(self.address, Operation::FinishReset),
                    &Some(Message::AckOperation(self.address, Operation::FinishReset)),
                )?;

                self.send_message_expect_response(
                    Message::Hello(self.address),
                    &Some(Message::ReportState(self.address, State::Unconfigured)),
                )?;
            }
        };
        Ok(())
    }

    /// Sends a chunk of data and verifies proper receipt with retries.
    ///
    /// Requests `operation` from the sign and fails if it does not acknowledge.
    /// Sends `data` in 16-byte chunks, then queries the sign's state.
    /// If `success`, we're done. If `failure`, repeat the process a fixed number
    /// of times in case the data was corrupted in transit. Fails after exhausting
    /// the retries or if any other state is reported.
    fn send_data<'a, I>(&self, data: &I, operation: Operation, success: State, failure: State) -> Result<(), SignError>
    where
        I: Iterator<Item = &'a [u8]> + Clone,
    {
        const MAX_ATTEMPTS: u32 = 3;
        let mut attempts = 1;
        loop {
            self.send_message_expect_response(
                Message::RequestOperation(self.address, operation),
                &Some(Message::AckOperation(self.address, operation)),
            )?;

            let mut chunks_sent = 0;
            for item in data.clone() {
                for (i, chunk) in item.chunks(16).enumerate() {
                    // Safe to unwrap the Data creation as the chunk will obviously always be less than 255 bytes.
                    self.send_message_expect_response(
                        Message::SendData(Offset((i * 16) as u16), Data::try_new(chunk).unwrap()),
                        &None,
                    )?;
                    chunks_sent += 1;
                }
            }

            self.send_message_expect_response(Message::DataChunksSent(ChunkCount(chunks_sent)), &None)?;

            let response = self.send_message(Message::QueryState(self.address))?;
            if response == Some(Message::ReportState(self.address, failure)) && attempts < MAX_ATTEMPTS {
                attempts += 1;
            } else {
                verify_response(&Some(Message::ReportState(self.address, success)), &response)?;
                break;
            }
        }

        Ok(())
    }

    /// Loads or shows a page and waits for the operation to complete.
    ///
    /// Queries the sign's current state. If `target`, we're done. If `trigger`, request `operation`.
    /// Continue looping while the state is `PageLoadInProgress` or `PageShowInProgress`, waiting
    /// to enter `target`. Fails if any other state is reported.
    fn switch_page(&self, target: State, trigger: State, operation: Operation) -> Result<(), SignError> {
        loop {
            let response = self.send_message(Message::QueryState(self.address))?;
            match response {
                Some(Message::ReportState(address, state)) if address == self.address && state == State::ShowingPages => {
                    warn!("Sign flips its own pages automatically; show_loaded_page/load_next_page have no effect.");
                    break;
                }

                Some(Message::ReportState(address, state)) if address == self.address && state == target => {
                    break;
                }

                Some(Message::ReportState(address, state)) if address == self.address && state == trigger => {
                    self.send_message_expect_response(
                        Message::RequestOperation(self.address, operation),
                        &Some(Message::AckOperation(self.address, operation)),
                    )?;
                }

                Some(Message::ReportState(address, State::PageLoadInProgress))
                | Some(Message::ReportState(address, State::PageShowInProgress))
                    if address == self.address => {}

                _ => {
                    return Err(SignError::UnexpectedResponse {
                        expected: format!("Some(ReportState({:?}, Page*))", self.address),
                        actual: format!("{:?}", response),
                    });
                }
            };
        }
        Ok(())
    }
}

/// Fails with an `UnexpectedResponse` error if `response` is not equal to `expected`.
fn verify_response(expected: &Option<Message<'_>>, response: &Option<Message<'_>>) -> Result<(), SignError> {
    if response == expected {
        Ok(())
    } else {
        Err(SignError::UnexpectedResponse {
            expected: format!("{:?}", expected),
            actual: format!("{:?}", response),
        })
    }
}