chessnut-move 1.0.2

Typed, transport-independent SDK for Chessnut Move boards.
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
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
// Copyright 2026 Daymon Littrell-Reyes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Tokio actor for concurrent access to a Chessnut Move board.
//!
//! [`spawn`] owns a [`TokioTransport`] in one task and returns a cloneable
//! [`BoardHandle`]. Commands from multiple handles are serialized, request and
//! response helpers are correlated one at a time, and every decoded
//! [`BoardEvent`] is published to each [`EventStream`] subscriber.
//!
//! Transport failures stop the actor and are retained in [`ActorExit`].
//! Malformed protocol notifications are reported through
//! [`EventStreamError::Decode`] without stopping the actor.

use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll, ready};
use std::collections::VecDeque;
use std::time::Duration;

use thiserror::Error;
use tokio_stream::wrappers::BroadcastStream;
use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
use tokio_stream::{Stream, StreamExt};

use crate::protocol::{BatteryStatus, BoardEvent, Command, PieceStatus};
#[cfg(doc)]
use crate::transport;
use crate::transport::{
  DecodeNotificationError, DecodedNotification, MAX_NOTIFICATION_LEN, Notification,
  NotificationSource, decode_notification,
};

/// A transport whose operations can run inside a task spawned by Tokio.
///
/// Unlike [`AsyncTransport`][transport::AsyncTransport], every returned future is
/// explicitly `Send`. This keeps the runtime-neutral trait usable by local and
/// embedded executors.
///
/// # Examples
///
/// ```
/// use core::convert::Infallible;
/// use chessnut_move::protocol::Command;
/// use chessnut_move::transport::tokio::TokioTransport;
/// use chessnut_move::transport::{Notification, NotificationSource};
///
/// struct MyTransport;
///
/// impl TokioTransport for MyTransport {
///     type Error = Infallible;
///
///     async fn subscribe(
///         &mut self,
///         _source: NotificationSource,
///     ) -> Result<(), Self::Error> {
///         Ok(())
///     }
///
///     async fn write_command(
///         &mut self,
///         _command: &Command,
///     ) -> Result<(), Self::Error> {
///         Ok(())
///     }
///
///     async fn next_notification<'a>(
///         &'a mut self,
///         buffer: &'a mut [u8],
///     ) -> Result<Notification<'a>, Self::Error> {
///         buffer[..34].fill(0);
///         Ok(Notification::new(
///             NotificationSource::Position,
///             &buffer[..34],
///         ))
///     }
/// }
/// ```
pub trait TokioTransport: Send + 'static {
  /// Error returned by Bluetooth or adapter operations.
  type Error: Send + 'static;

  /// Enables notifications for one protocol source.
  ///
  /// # Errors
  ///
  /// Returns [`Self::Error`] when the adapter cannot enable the corresponding
  /// [GATT characteristic][NotificationSource::characteristic].
  fn subscribe(
    &mut self,
    source: NotificationSource,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send + '_;

  /// Disables notifications for one protocol source.
  ///
  /// The default implementation performs no operation.
  ///
  /// # Errors
  ///
  /// Returns [`Self::Error`] when the adapter cannot disable the corresponding
  /// [GATT characteristic][NotificationSource::characteristic].
  fn unsubscribe(
    &mut self,
    _source: NotificationSource,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send + '_ {
    async { Ok(()) }
  }

  /// Writes an encoded command using its
  /// [required write kind][Command::write_kind].
  ///
  /// # Errors
  ///
  /// Returns [`Self::Error`] when the command cannot be written.
  fn write_command<'a>(
    &'a mut self,
    command: &'a Command,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send + 'a;

  /// Receives the next notification into the supplied buffer.
  ///
  /// The returned [`Notification`] must borrow its bytes from `buffer`.
  /// Implementations must return an error instead of truncating a notification
  /// that exceeds the buffer.
  ///
  /// # Errors
  ///
  /// Returns [`Self::Error`] when notification delivery ends, Bluetooth I/O
  /// fails, the source is unknown, or the supplied buffer is too small.
  fn next_notification<'a>(
    &'a mut self,
    buffer: &'a mut [u8],
  ) -> impl Future<Output = Result<Notification<'a>, Self::Error>> + Send + 'a;

  /// Closes transport-owned resources after subscriptions are disabled.
  ///
  /// The default implementation performs no operation.
  ///
  /// # Errors
  ///
  /// Returns [`Self::Error`] when transport cleanup fails.
  fn close(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send + '_ {
    async { Ok(()) }
  }
}

/// Queue capacities and timeout behavior for a board actor.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use chessnut_move::transport::tokio::ActorConfig;
///
/// let config = ActorConfig {
///     request_timeout: Duration::from_secs(10),
///     ..ActorConfig::default()
/// };
/// assert_eq!(config.request_timeout, Duration::from_secs(10));
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ActorConfig {
  /// Maximum number of handle messages waiting for the actor.
  pub command_capacity: usize,

  /// Number of events retained for each lag-aware subscriber.
  pub event_capacity: usize,

  /// Maximum number of queries waiting behind the active query.
  pub query_capacity: usize,

  /// Time allowed for a battery or piece-status response.
  pub request_timeout: Duration,
}

impl Default for ActorConfig {
  fn default() -> Self {
    Self {
      command_capacity: 32,
      event_capacity: 64,
      query_capacity: 32,
      request_timeout: Duration::from_secs(5),
    }
  }
}

/// Reports invalid actor configuration supplied to [`spawn`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum SpawnError {
  /// [`ActorConfig::command_capacity`] was zero.
  #[error("command channel capacity must be greater than zero")]
  ZeroCommandCapacity,

  /// [`ActorConfig::event_capacity`] was zero.
  #[error("event channel capacity must be greater than zero")]
  ZeroEventCapacity,
}

/// Current lifecycle phase of the board actor.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LifecycleState {
  /// The actor is subscribing and enabling realtime updates.
  Starting,

  /// Initialization completed and handle requests are accepted.
  Running,

  /// The actor is rejecting new requests and cleaning up the transport.
  ShuttingDown,

  /// The actor completed without a fatal error.
  Stopped,

  /// Initialization, transport I/O, or cleanup failed.
  Faulted,
}

/// Reports why a [`BoardHandle`] operation could not complete.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum HandleError {
  /// The actor task or its request channel has ended.
  #[error("the board actor has stopped")]
  ActorStopped,

  /// Graceful shutdown has started.
  #[error("the board actor is shutting down")]
  ShuttingDown,

  /// A transport operation failed.
  ///
  /// The underlying transport error is available from [`ActorExit::result`].
  #[error("the transport operation failed; inspect BoardTask for the underlying error")]
  TransportFailed,

  /// A query did not receive its matching response before the configured timeout.
  #[error("the board request timed out")]
  RequestTimedOut,

  /// The bounded queue for serialized queries is full.
  #[error("the pending query queue is full")]
  QueryQueueFull,
}

/// Reports a recoverable or terminal condition while consuming an [`EventStream`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
pub enum EventStreamError {
  /// The subscriber fell behind and older events were discarded.
  #[error("event subscriber lagged and missed {0} events")]
  Lagged(u64),

  /// A malformed notification was skipped while the actor remained running.
  #[error(transparent)]
  Decode(#[from] DecodeNotificationError),

  /// The actor closed the event channel.
  #[error("the board event stream is closed")]
  Closed,
}

/// Fatal error retained when the board actor terminates.
#[derive(Debug, Error)]
pub enum ActorError<E> {
  /// A transport operation failed during initialization, operation, or cleanup.
  #[error("transport error: {0}")]
  Transport(E),
}

/// A cloneable command and request handle for a running board actor.
///
/// Clones share one bounded request channel. Dropping the final handle closes
/// that channel; the actor then performs normal transport cleanup. Keep the
/// corresponding [`BoardTask`] when the final [`ActorExit`] result or transport
/// is needed.
///
/// # Examples
///
/// ```no_run
/// use chessnut_move::protocol::{Command, LedPattern};
/// use chessnut_move::transport::tokio::{BoardHandle, HandleError};
///
/// # async fn turn_off_leds(board: &BoardHandle) -> Result<(), HandleError> {
/// board.send(Command::set_leds(&LedPattern::default())).await
/// # }
/// ```
#[derive(Clone)]
pub struct BoardHandle {
  request_tx: ::tokio::sync::mpsc::Sender<Message>,
  lifecycle_rx: ::tokio::sync::watch::Receiver<LifecycleState>,
}

impl BoardHandle {
  /// Returns the most recently observed actor lifecycle state.
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use chessnut_move::transport::tokio::{BoardHandle, LifecycleState};
  ///
  /// # fn inspect(board: &BoardHandle) {
  /// if board.lifecycle() == LifecycleState::Running {
  ///     println!("board actor is ready");
  /// }
  /// # }
  /// ```
  pub fn lifecycle(&self) -> LifecycleState {
    *self.lifecycle_rx.borrow()
  }

  /// Subscribes to lifecycle changes from the actor.
  ///
  /// The returned
  /// [`tokio::sync::watch::Receiver`](https://docs.rs/tokio/1/tokio/sync/watch/struct.Receiver.html)
  /// immediately exposes the current state and retains only the latest state.
  pub fn subscribe_lifecycle(&self) -> ::tokio::sync::watch::Receiver<LifecycleState> {
    self.lifecycle_rx.clone()
  }

  /// Sends a command and waits for the transport write to finish.
  ///
  /// Protocol responses are published separately through [`EventStream`].
  /// Prefer [`BoardHandle::battery_status`] and
  /// [`BoardHandle::piece_status`] when sending the corresponding queries so
  /// the actor can correlate the response.
  ///
  /// # Errors
  ///
  /// Returns [`HandleError::ShuttingDown`] after shutdown begins,
  /// [`HandleError::ActorStopped`] when the actor is no longer reachable, or
  /// [`HandleError::TransportFailed`] when the write fails.
  pub async fn send(&self, command: Command) -> Result<(), HandleError> {
    trace_event!(
      command_len = command.bytes().len(),
      write_kind = ?command.write_kind(),
      "submitting command to board actor"
    );
    let (reply_tx, reply_rx) = ::tokio::sync::oneshot::channel();
    self
      .send_message(Message::Send {
        command,
        reply: reply_tx,
      })
      .await?;
    receive_reply(reply_rx).await?
  }

  /// Queries and returns the board's battery status.
  ///
  /// This helper sends [`Command::read_battery_level`] and correlates the next
  /// matching response.
  ///
  /// Queries are serialized because Move responses do not contain request IDs.
  /// The decoded response is also published as
  /// [`BoardEvent::BatteryStatus`].
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use chessnut_move::transport::tokio::{BoardHandle, HandleError};
  ///
  /// async fn report_battery(board: &BoardHandle) -> Result<(), HandleError> {
  ///     let status = board.battery_status().await?;
  ///     let state = if status.charging { "charging" } else { "on battery" };
  ///     println!("{}% ({state})", status.percentage);
  ///     Ok(())
  /// }
  /// ```
  ///
  /// # Errors
  ///
  /// Returns [`HandleError::QueryQueueFull`] when the query queue is full,
  /// [`HandleError::RequestTimedOut`] when no matching response arrives,
  /// [`HandleError::TransportFailed`] when the query write fails,
  /// [`HandleError::ShuttingDown`] after shutdown begins, or
  /// [`HandleError::ActorStopped`] when the actor is no longer reachable.
  pub async fn battery_status(&self) -> Result<BatteryStatus, HandleError> {
    debug_event!(query = "battery_status", "submitting board query");
    let (reply_tx, reply_rx) = ::tokio::sync::oneshot::channel();
    self
      .send_message(Message::Query(QueryRequest::Battery(reply_tx)))
      .await?;
    receive_reply(reply_rx).await?
  }

  /// Queries and returns the status of all tracked physical pieces.
  ///
  /// This helper sends [`Command::read_piece_status`] and correlates the next
  /// matching response.
  ///
  /// Queries are serialized because Move responses do not contain request IDs.
  /// The decoded response is also published as
  /// [`BoardEvent::PieceStatus`].
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use chessnut_move::transport::tokio::{BoardHandle, HandleError};
  ///
  /// async fn report_low_pieces(board: &BoardHandle) -> Result<(), HandleError> {
  ///     let status = board.piece_status().await?;
  ///
  ///     for tracked in status
  ///         .pieces
  ///         .iter()
  ///         .filter(|piece| piece.battery_percentage.is_some_and(|level| level < 20))
  ///     {
  ///         println!("{:?} is low", tracked.piece);
  ///     }
  ///
  ///     Ok(())
  /// }
  /// ```
  ///
  /// # Errors
  ///
  /// Returns [`HandleError::QueryQueueFull`] when the query queue is full,
  /// [`HandleError::RequestTimedOut`] when no matching response arrives,
  /// [`HandleError::TransportFailed`] when the query write fails,
  /// [`HandleError::ShuttingDown`] after shutdown begins, or
  /// [`HandleError::ActorStopped`] when the actor is no longer reachable.
  pub async fn piece_status(&self) -> Result<PieceStatus, HandleError> {
    debug_event!(query = "piece_status", "submitting board query");
    let (reply_tx, reply_rx) = ::tokio::sync::oneshot::channel();
    self
      .send_message(Message::Query(QueryRequest::Pieces(reply_tx)))
      .await?;
    receive_reply(reply_rx).await?
  }

  /// Creates a new lag-aware stream of subsequently published board events.
  ///
  /// Events published before this request is processed are not replayed.
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use std::error::Error;
  /// use chessnut_move::protocol::BoardEvent;
  /// use chessnut_move::transport::tokio::BoardHandle;
  ///
  /// async fn watch_moves(board: &BoardHandle) -> Result<(), Box<dyn Error>> {
  ///     let mut events = board.subscribe_events().await?;
  ///
  ///     loop {
  ///         if let BoardEvent::PositionChanged(position) = events.recv().await? {
  ///             println!("position: {position:?}");
  ///         }
  ///     }
  /// }
  /// ```
  ///
  /// # Errors
  ///
  /// Returns [`HandleError::ShuttingDown`] after shutdown begins or
  /// [`HandleError::ActorStopped`] when the actor is no longer reachable.
  pub async fn subscribe_events(&self) -> Result<EventStream, HandleError> {
    debug_event!("subscribing to board actor events");
    let (reply_tx, reply_rx) = ::tokio::sync::oneshot::channel();
    self
      .send_message(Message::SubscribeEvents { reply: reply_tx })
      .await?;
    receive_reply(reply_rx).await?
  }

  /// Requests graceful actor shutdown and waits for transport cleanup.
  ///
  /// The actor unsubscribes from command responses, unsubscribes from position
  /// notifications, and then calls [`TokioTransport::close`]. Other handle
  /// clones stop accepting requests once shutdown begins.
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use chessnut_move::transport::tokio::{BoardHandle, HandleError};
  ///
  /// async fn stop(board: &BoardHandle) -> Result<(), HandleError> {
  ///     board.shutdown().await
  /// }
  /// ```
  ///
  /// # Errors
  ///
  /// Returns [`HandleError::TransportFailed`] when cleanup fails,
  /// [`HandleError::ShuttingDown`] when another shutdown is already in
  /// progress, or [`HandleError::ActorStopped`] when the actor is no longer
  /// reachable.
  pub async fn shutdown(&self) -> Result<(), HandleError> {
    info_event!("requesting graceful board actor shutdown");
    let (reply_tx, reply_rx) = ::tokio::sync::oneshot::channel();
    self
      .send_message(Message::Shutdown { reply: reply_tx })
      .await?;
    receive_reply(reply_rx).await?
  }

  /// Checks lifecycle state and enqueues one handle message.
  async fn send_message(&self, message: Message) -> Result<(), HandleError> {
    let lifecycle = self.lifecycle();
    match lifecycle {
      LifecycleState::Starting | LifecycleState::Running => {}
      LifecycleState::ShuttingDown => {
        debug_event!(?lifecycle, "board actor rejected handle request");
        return Err(HandleError::ShuttingDown);
      }
      LifecycleState::Stopped | LifecycleState::Faulted => {
        debug_event!(?lifecycle, "board actor rejected handle request");
        return Err(HandleError::ActorStopped);
      }
    }

    self.request_tx.send(message).await.map_err(|_| {
      debug_event!("board actor request channel is closed");
      HandleError::ActorStopped
    })
  }
}

/// A lag-aware stream for events published by the board actor.
///
/// The stream implements
/// [`tokio_stream::Stream`](https://docs.rs/tokio-stream/0.1/tokio_stream/trait.Stream.html)
/// with
/// `Item = Result<BoardEvent, EventStreamError>`. Decode and lag errors are
/// recoverable; consumers can continue polling after receiving either one.
/// The stream ends after the actor closes its event channel.
pub struct EventStream {
  inner: BroadcastStream<Result<BoardEvent, DecodeNotificationError>>,
}

impl EventStream {
  /// Wraps one broadcast subscriber as a public lag-aware stream.
  fn new(
    receiver: ::tokio::sync::broadcast::Receiver<Result<BoardEvent, DecodeNotificationError>>,
  ) -> Self {
    Self {
      inner: BroadcastStream::new(receiver),
    }
  }

  /// Receives the next event or stream condition.
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use chessnut_move::protocol::BoardEvent;
  /// use chessnut_move::transport::tokio::{
  ///     EventStream, EventStreamError,
  /// };
  ///
  /// async fn next_position(
  ///     events: &mut EventStream,
  /// ) -> Result<(), EventStreamError> {
  ///     loop {
  ///         let event = events.recv().await?;
  ///         if let BoardEvent::PositionChanged(position) = event {
  ///             println!("position: {position:?}");
  ///             return Ok(());
  ///         }
  ///     }
  /// }
  /// ```
  ///
  /// # Errors
  ///
  /// Returns [`EventStreamError::Lagged`] when older events were discarded,
  /// [`EventStreamError::Decode`] when a malformed notification was skipped,
  /// or [`EventStreamError::Closed`] after the actor closes the channel.
  pub async fn recv(&mut self) -> Result<BoardEvent, EventStreamError> {
    self.next().await.unwrap_or(Err(EventStreamError::Closed))
  }
}

impl Stream for EventStream {
  type Item = Result<BoardEvent, EventStreamError>;

  fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
    let item = ready!(Pin::new(&mut self.inner).poll_next(cx));
    Poll::Ready(match item {
      Some(Ok(Ok(event))) => Some(Ok(event)),
      Some(Ok(Err(error))) => Some(Err(EventStreamError::Decode(error))),
      Some(Err(BroadcastStreamRecvError::Lagged(count))) => {
        warn_event!(missed_events = count, "board event subscriber lagged");
        Some(Err(EventStreamError::Lagged(count)))
      }
      None => {
        debug_event!("board event stream closed");
        None
      }
    })
  }
}

/// The detailed result of a terminated actor, including its transport.
///
/// An exit always returns ownership of the transport, including after a
/// transport failure. Use [`ActorExit::result`] to inspect the outcome without
/// consuming the exit or [`ActorExit::into_parts`] to recover both values.
pub struct ActorExit<T: TokioTransport> {
  transport: T,
  result: Result<(), ActorError<T::Error>>,
}

impl<T: TokioTransport> ActorExit<T> {
  /// Returns a shared reference to the actor's transport.
  pub const fn transport(&self) -> &T {
    &self.transport
  }

  /// Consumes the exit and returns its transport, discarding the actor result.
  pub fn into_transport(self) -> T {
    self.transport
  }

  /// Consumes the exit and returns the transport and actor result.
  pub fn into_parts(self) -> (T, Result<(), ActorError<T::Error>>) {
    (self.transport, self.result)
  }

  /// Returns the actor result by reference.
  ///
  /// # Errors
  ///
  /// Returns the retained [`ActorError`] when initialization, operation, or
  /// cleanup failed.
  pub const fn result(&self) -> Result<(), &ActorError<T::Error>> {
    match &self.result {
      Ok(()) => Ok(()),
      Err(error) => Err(error),
    }
  }

  /// Consumes the exit and returns the owned actor result.
  ///
  /// # Errors
  ///
  /// Returns the retained [`ActorError`] when initialization, operation, or
  /// cleanup failed.
  pub fn into_result(self) -> Result<(), ActorError<T::Error>> {
    self.result
  }
}

/// A joinable Tokio task running the board actor.
///
/// Awaiting the task produces an [`ActorExit`] containing both the transport
/// and final result. Dropping `BoardTask` detaches the Tokio task; it does not
/// cancel the actor.
pub struct BoardTask<T: TokioTransport> {
  join: ::tokio::task::JoinHandle<ActorExit<T>>,
}

impl<T: TokioTransport> BoardTask<T> {
  /// Requests immediate task cancellation.
  ///
  /// Prefer [`BoardHandle::shutdown`] so the actor can unsubscribe and close
  /// the transport cleanly. Awaiting the task after cancellation returns a
  /// cancelled
  /// [`tokio::task::JoinError`](https://docs.rs/tokio/1/tokio/task/struct.JoinError.html).
  pub fn abort(&self) {
    self.join.abort();
  }

  /// Returns whether the actor task has completed.
  pub fn is_finished(&self) -> bool {
    self.join.is_finished()
  }
}

impl<T: TokioTransport> Future for BoardTask<T> {
  type Output = Result<ActorExit<T>, ::tokio::task::JoinError>;

  fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
    Pin::new(&mut self.join).poll(cx)
  }
}

/// Spawns a concurrent board actor and returns its handle and joinable task.
///
/// Initialization runs inside the spawned task. Observe
/// [`BoardHandle::subscribe_lifecycle`] or await the [`BoardTask`] to detect an
/// initialization failure.
///
/// # Examples
///
/// ```no_run
/// use chessnut_move::transport::tokio::{
///     ActorConfig, BoardHandle, BoardTask, SpawnError, TokioTransport, spawn,
/// };
///
/// # fn start<T: TokioTransport>(
/// #     transport: T,
/// # ) -> Result<(BoardHandle, BoardTask<T>), SpawnError> {
/// spawn(transport, ActorConfig::default())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`SpawnError::ZeroCommandCapacity`] or
/// [`SpawnError::ZeroEventCapacity`] when the corresponding
/// [`ActorConfig`] capacity is zero.
///
/// # Panics
///
/// Panics when called outside a Tokio runtime.
pub fn spawn<T: TokioTransport>(
  transport: T,
  config: ActorConfig,
) -> Result<(BoardHandle, BoardTask<T>), SpawnError> {
  if config.command_capacity == 0 {
    warn_event!(
      field = "command_capacity",
      "invalid board actor configuration"
    );
    return Err(SpawnError::ZeroCommandCapacity);
  }
  if config.event_capacity == 0 {
    warn_event!(
      field = "event_capacity",
      "invalid board actor configuration"
    );
    return Err(SpawnError::ZeroEventCapacity);
  }

  info_event!(
    command_capacity = config.command_capacity,
    event_capacity = config.event_capacity,
    query_capacity = config.query_capacity,
    request_timeout = ?config.request_timeout,
    "spawning board actor"
  );
  let (request_tx, request_rx) = ::tokio::sync::mpsc::channel(config.command_capacity);
  let (event_tx, _) = ::tokio::sync::broadcast::channel(config.event_capacity);
  let (lifecycle_tx, lifecycle_rx) = ::tokio::sync::watch::channel(LifecycleState::Starting);

  let actor = run_actor(transport, config, request_rx, event_tx, lifecycle_tx);
  #[cfg(feature = "tracing")]
  let actor = {
    use ::tracing::Instrument as _;

    actor.instrument(::tracing::info_span!("board_actor"))
  };
  let join = ::tokio::spawn(actor);

  Ok((
    BoardHandle {
      request_tx,
      lifecycle_rx,
    },
    BoardTask { join },
  ))
}

/// Request sent from a handle to the actor.
enum Message {
  Send {
    command: Command,
    reply: ::tokio::sync::oneshot::Sender<Result<(), HandleError>>,
  },
  Query(QueryRequest),
  SubscribeEvents {
    reply: ::tokio::sync::oneshot::Sender<Result<EventStream, HandleError>>,
  },
  Shutdown {
    reply: ::tokio::sync::oneshot::Sender<Result<(), HandleError>>,
  },
}

/// Query whose response must be correlated by notification type.
enum QueryRequest {
  Battery(::tokio::sync::oneshot::Sender<Result<BatteryStatus, HandleError>>),
  Pieces(::tokio::sync::oneshot::Sender<Result<PieceStatus, HandleError>>),
}

/// Active serialized query and its response deadline.
struct PendingQuery {
  request: QueryRequest,
  deadline: ::tokio::time::Instant,
}

impl QueryRequest {
  /// Returns the stable tracing label for this query type.
  #[cfg(feature = "tracing")]
  const fn kind(&self) -> &'static str {
    match self {
      Self::Battery(_) => "battery_status",
      Self::Pieces(_) => "piece_status",
    }
  }

  /// Builds the command associated with this response type.
  fn command(&self) -> Command {
    match self {
      Self::Battery(_) => Command::read_battery_level(),
      Self::Pieces(_) => Command::read_piece_status(),
    }
  }

  /// Completes this query with a handle-level error.
  fn fail(self, error: HandleError) {
    match self {
      Self::Battery(reply) => {
        let _ = reply.send(Err(error));
      }
      Self::Pieces(reply) => {
        let _ = reply.send(Err(error));
      }
    }
  }
}

impl PendingQuery {
  /// Completes the active query with a handle-level error.
  fn fail(self, error: HandleError) {
    self.request.fail(error);
  }
}

/// Receives an actor reply and maps a dropped sender to actor termination.
async fn receive_reply<T>(
  reply: ::tokio::sync::oneshot::Receiver<Result<T, HandleError>>,
) -> Result<Result<T, HandleError>, HandleError> {
  reply.await.map_err(|_| HandleError::ActorStopped)
}

/// Owns the transport and runs the complete actor lifecycle.
///
/// Only transport errors are fatal. Decode failures are broadcast to event
/// subscribers and the receive loop continues. Query responses are published
/// as events after satisfying the active query.
async fn run_actor<T: TokioTransport>(
  mut transport: T,
  config: ActorConfig,
  mut request_rx: ::tokio::sync::mpsc::Receiver<Message>,
  event_tx: ::tokio::sync::broadcast::Sender<Result<BoardEvent, DecodeNotificationError>>,
  lifecycle_tx: ::tokio::sync::watch::Sender<LifecycleState>,
) -> ActorExit<T> {
  info_event!("board actor is starting");
  let mut notification_buffer = [0; MAX_NOTIFICATION_LEN];
  let mut pending_query: Option<PendingQuery> = None;
  let mut queued_queries: VecDeque<QueryRequest> = VecDeque::new();
  let mut shutdown_reply = None;

  let mut result = initialize_transport(&mut transport)
    .await
    .map_err(ActorError::Transport);

  if result.is_ok() {
    lifecycle_tx.send_replace(LifecycleState::Running);
    info_event!("board actor is running");

    result = loop {
      if pending_query.is_none()
        && let Some(query) = queued_queries.pop_front()
      {
        debug_event!(
          query = query.kind(),
          queued_queries = queued_queries.len(),
          "starting queued board query"
        );
        match start_query(&mut transport, query, config.request_timeout).await {
          Ok(query) => pending_query = Some(query),
          Err(error) => break Err(error),
        }
      }

      let deadline = pending_query
        .as_ref()
        .map(|query| query.deadline)
        .unwrap_or_else(::tokio::time::Instant::now);

      ::tokio::select! {
        message = request_rx.recv() => {
          match message {
            Some(Message::Send { command, reply }) => {
              trace_event!(
                command_len = command.bytes().len(),
                write_kind = ?command.write_kind(),
                "board actor is writing a command"
              );
              match transport.write_command(&command).await {
                Ok(()) => {
                  let _ = reply.send(Ok(()));
                }
                Err(error) => {
                  error_event!(operation = "write_command", "board transport failed");
                  let _ = reply.send(Err(HandleError::TransportFailed));
                  break Err(ActorError::Transport(error));
                }
              }
            }
            Some(Message::Query(query)) => {
              debug_event!(
                query = query.kind(),
                queued_queries = queued_queries.len(),
                has_active_query = pending_query.is_some(),
                "board actor received a query"
              );
              if pending_query.is_none() && queued_queries.is_empty() {
                match start_query(&mut transport, query, config.request_timeout).await {
                  Ok(query) => pending_query = Some(query),
                  Err(error) => break Err(error),
                }
              } else if queued_queries.len() < config.query_capacity {
                queued_queries.push_back(query);
              } else {
                warn_event!(
                  query = query.kind(),
                  query_capacity = config.query_capacity,
                  "board query queue is full"
                );
                query.fail(HandleError::QueryQueueFull);
              }
            }
            Some(Message::SubscribeEvents { reply }) => {
              debug_event!(
                subscribers = event_tx.receiver_count() + 1,
                "creating board event subscription"
              );
              let _ = reply.send(Ok(EventStream::new(event_tx.subscribe())));
            }
            Some(Message::Shutdown { reply }) => {
              info_event!("board actor received shutdown request");
              shutdown_reply = Some(reply);
              break Ok(());
            }
            None => {
              info_event!("all board handles were dropped");
              break Ok(());
            }
          }
        }
        notification = transport.next_notification(&mut notification_buffer) => {
          let notification = match notification {
            Ok(notification) => notification,
            Err(error) => {
              error_event!(operation = "next_notification", "board transport failed");
              break Err(ActorError::Transport(error));
            }
          };
          trace_event!(
            source = ?notification.source(),
            notification_len = notification.bytes().len(),
            "board actor received a notification"
          );
          let event = match decode_notification(notification) {
            Ok(DecodedNotification::Event(event)) => event,
            Ok(DecodedNotification::RealtimeUpdatesAcknowledged) => continue,
            Err(error) => {
              warn_event!(error = ?error, "board actor skipped a malformed notification");
              let _ = event_tx.send(Err(error));
              continue;
            }
          };

          resolve_query(&mut pending_query, event);
          let _ = event_tx.send(Ok(event));
        }
        _ = ::tokio::time::sleep_until(deadline), if pending_query.is_some() => {
          if let Some(query) = pending_query.take() {
            warn_event!(query = query.request.kind(), "board query timed out");
            query.fail(HandleError::RequestTimedOut);
          }
        }
      }
    };
  } else {
    error_event!(
      operation = "initialize",
      "board actor initialization failed"
    );
  }

  lifecycle_tx.send_replace(LifecycleState::ShuttingDown);
  info_event!("board actor is shutting down");
  request_rx.close();

  if let Some(query) = pending_query.take() {
    query.fail(HandleError::ShuttingDown);
  }
  for query in queued_queries {
    query.fail(HandleError::ShuttingDown);
  }
  while let Ok(message) = request_rx.try_recv() {
    fail_message(message, HandleError::ShuttingDown);
  }

  let cleanup_result = shutdown_transport(&mut transport)
    .await
    .map_err(ActorError::Transport);
  if cleanup_result.is_err() {
    error_event!(operation = "shutdown", "board transport cleanup failed");
  }
  if result.is_ok() {
    result = cleanup_result;
  }

  let final_state = if result.is_ok() {
    LifecycleState::Stopped
  } else {
    LifecycleState::Faulted
  };
  lifecycle_tx.send_replace(final_state);
  match final_state {
    LifecycleState::Stopped => info_event!("board actor stopped"),
    LifecycleState::Faulted => error_event!("board actor stopped after a fatal error"),
    _ => {}
  }

  if let Some(reply) = shutdown_reply {
    let reply_result = if result.is_ok() {
      Ok(())
    } else {
      Err(HandleError::TransportFailed)
    };
    let _ = reply.send(reply_result);
  }

  ActorExit { transport, result }
}

/// Performs the protocol-required startup sequence.
///
/// Command responses are subscribed after the realtime-enable write because
/// the board may emit an undocumented `0x23` acknowledgement on that
/// characteristic. The decoder also recognizes delayed acknowledgements.
async fn initialize_transport<T: TokioTransport>(transport: &mut T) -> Result<(), T::Error> {
  trace_event!(
    operation = "subscribe",
    source = ?NotificationSource::Position,
    "initializing board transport"
  );
  transport.subscribe(NotificationSource::Position).await?;
  trace_event!(
    operation = "enable_realtime_updates",
    "initializing board transport"
  );
  transport
    .write_command(&Command::enable_realtime_updates())
    .await?;
  trace_event!(
    operation = "subscribe",
    source = ?NotificationSource::CommandResponse,
    "initializing board transport"
  );
  transport
    .subscribe(NotificationSource::CommandResponse)
    .await
}

/// Performs ordered best-effort-compatible transport cleanup.
///
/// Cleanup returns at the first transport error. The transport is still
/// retained in [`ActorExit`] so callers can perform adapter-specific recovery.
async fn shutdown_transport<T: TokioTransport>(transport: &mut T) -> Result<(), T::Error> {
  trace_event!(
    operation = "unsubscribe",
    source = ?NotificationSource::CommandResponse,
    "shutting down board transport"
  );
  transport
    .unsubscribe(NotificationSource::CommandResponse)
    .await?;
  trace_event!(
    operation = "unsubscribe",
    source = ?NotificationSource::Position,
    "shutting down board transport"
  );
  transport.unsubscribe(NotificationSource::Position).await?;
  trace_event!(operation = "close", "shutting down board transport");
  transport.close().await
}

/// Writes the next serialized query and records its response deadline.
async fn start_query<T: TokioTransport>(
  transport: &mut T,
  query: QueryRequest,
  timeout: Duration,
) -> Result<PendingQuery, ActorError<T::Error>> {
  debug_event!(
    query = query.kind(),
    timeout = ?timeout,
    "writing serialized board query"
  );
  if let Err(error) = transport.write_command(&query.command()).await {
    error_event!(
      operation = "write_query",
      query = query.kind(),
      "board transport failed"
    );
    query.fail(HandleError::TransportFailed);
    return Err(ActorError::Transport(error));
  }

  Ok(PendingQuery {
    request: query,
    deadline: ::tokio::time::Instant::now() + timeout,
  })
}

/// Completes the active query when an event has its expected response type.
///
/// Move query responses do not carry request IDs, so at most one query can be
/// active. Nonmatching events remain public events and leave the query pending.
fn resolve_query(pending: &mut Option<PendingQuery>, event: BoardEvent) {
  let matches = matches!(
    (pending.as_ref().map(|query| &query.request), event),
    (Some(QueryRequest::Battery(_)), BoardEvent::BatteryStatus(_))
      | (Some(QueryRequest::Pieces(_)), BoardEvent::PieceStatus(_))
  );

  if !matches {
    return;
  }

  let query = pending.take().expect("matching pending query exists");
  debug_event!(
    query = query.request.kind(),
    "board query received its response"
  );
  match (query.request, event) {
    (QueryRequest::Battery(reply), BoardEvent::BatteryStatus(status)) => {
      let _ = reply.send(Ok(status));
    }
    (QueryRequest::Pieces(reply), BoardEvent::PieceStatus(status)) => {
      let _ = reply.send(Ok(status));
    }
    _ => unreachable!("query and event variants were checked before taking the query"),
  }
}

/// Rejects a queued handle message during shutdown or actor failure.
fn fail_message(message: Message, error: HandleError) {
  match message {
    Message::Send { reply, .. } | Message::Shutdown { reply } => {
      let _ = reply.send(Err(error));
    }
    Message::Query(query) => query.fail(error),
    Message::SubscribeEvents { reply } => {
      let _ = reply.send(Err(error));
    }
  }
}

#[cfg(test)]
mod tests {
  use std::sync::{Arc, Mutex};

  use super::*;

  #[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
  #[error("mock notification channel closed")]
  struct MockError;

  struct OwnedNotification {
    source: NotificationSource,
    bytes: Vec<u8>,
  }

  #[derive(Debug, PartialEq, Eq)]
  enum Operation {
    Subscribe(NotificationSource),
    Write(Vec<u8>),
  }

  #[derive(Default)]
  struct Record {
    subscriptions: Vec<NotificationSource>,
    unsubscriptions: Vec<NotificationSource>,
    writes: Vec<Vec<u8>>,
    operations: Vec<Operation>,
    closed: bool,
  }

  struct MockTransport {
    record: Arc<Mutex<Record>>,
    notification_rx: ::tokio::sync::mpsc::Receiver<OwnedNotification>,
  }

  impl MockTransport {
    fn new() -> (
      Self,
      Arc<Mutex<Record>>,
      ::tokio::sync::mpsc::Sender<OwnedNotification>,
    ) {
      let record = Arc::new(Mutex::new(Record::default()));
      let (notification_tx, notification_rx) = ::tokio::sync::mpsc::channel(8);

      (
        Self {
          record: Arc::clone(&record),
          notification_rx,
        },
        record,
        notification_tx,
      )
    }
  }

  impl TokioTransport for MockTransport {
    type Error = MockError;

    async fn subscribe(&mut self, source: NotificationSource) -> Result<(), Self::Error> {
      let mut record = self.record.lock().unwrap();
      record.subscriptions.push(source);
      record.operations.push(Operation::Subscribe(source));
      Ok(())
    }

    async fn unsubscribe(&mut self, source: NotificationSource) -> Result<(), Self::Error> {
      self.record.lock().unwrap().unsubscriptions.push(source);
      Ok(())
    }

    async fn write_command(&mut self, command: &Command) -> Result<(), Self::Error> {
      let bytes = command.bytes().to_vec();
      let mut record = self.record.lock().unwrap();
      record.writes.push(bytes.clone());
      record.operations.push(Operation::Write(bytes));
      Ok(())
    }

    async fn next_notification<'a>(
      &'a mut self,
      buffer: &'a mut [u8],
    ) -> Result<Notification<'a>, Self::Error> {
      let notification = self.notification_rx.recv().await.ok_or(MockError)?;
      buffer[..notification.bytes.len()].copy_from_slice(&notification.bytes);
      Ok(Notification::new(
        notification.source,
        &buffer[..notification.bytes.len()],
      ))
    }

    async fn close(&mut self) -> Result<(), Self::Error> {
      self.record.lock().unwrap().closed = true;
      Ok(())
    }
  }

  #[::tokio::test]
  async fn actor_correlates_queries_without_stealing_events() {
    let (transport, record, notification_tx) = MockTransport::new();
    let (handle, task) = spawn(transport, ActorConfig::default()).unwrap();
    let mut events = handle.subscribe_events().await.unwrap();
    wait_until_running(&handle).await;

    assert_eq!(
      record.lock().unwrap().operations[..3],
      [
        Operation::Subscribe(NotificationSource::Position),
        Operation::Write(Command::enable_realtime_updates().bytes().to_vec()),
        Operation::Subscribe(NotificationSource::CommandResponse),
      ]
    );

    notification_tx
      .send(OwnedNotification {
        source: NotificationSource::CommandResponse,
        bytes: vec![0x23, 0x01, 0x00],
      })
      .await
      .unwrap();

    let query_handle = handle.clone();
    let query = ::tokio::spawn(async move { query_handle.battery_status().await });
    wait_for_write(&record, Command::read_battery_level().bytes()).await;

    notification_tx
      .send(OwnedNotification {
        source: NotificationSource::Position,
        bytes: vec![0; 34],
      })
      .await
      .unwrap();

    assert!(matches!(
      events.recv().await,
      Ok(BoardEvent::PositionChanged(_))
    ));
    assert!(!query.is_finished());

    notification_tx
      .send(OwnedNotification {
        source: NotificationSource::CommandResponse,
        bytes: vec![0x41, 0x03, 0x0c, 0x01, 88],
      })
      .await
      .unwrap();

    assert_eq!(
      query.await.unwrap(),
      Ok(BatteryStatus {
        charging: true,
        percentage: 88,
      })
    );
    assert_eq!(
      events.recv().await,
      Ok(BoardEvent::BatteryStatus(BatteryStatus {
        charging: true,
        percentage: 88,
      }))
    );

    let query_handle = handle.clone();
    let query = ::tokio::spawn(async move { query_handle.piece_status().await });
    wait_for_write(&record, Command::read_piece_status().bytes()).await;
    notification_tx
      .send(OwnedNotification {
        source: NotificationSource::CommandResponse,
        bytes: piece_status_response(),
      })
      .await
      .unwrap();

    let piece_status = query.await.unwrap().unwrap();
    assert_eq!(piece_status.pieces[0].battery_percentage, Some(50));
    assert_eq!(piece_status.pieces[33].battery_percentage, Some(83));
    assert!(matches!(
      events.recv().await,
      Ok(BoardEvent::PieceStatus(_))
    ));

    handle.shutdown().await.unwrap();
    let exit = task.await.unwrap();
    assert!(exit.result().is_ok());
    assert_eq!(handle.lifecycle(), LifecycleState::Stopped);
    assert_eq!(events.recv().await, Err(EventStreamError::Closed));

    let record = record.lock().unwrap();
    assert_eq!(
      record.subscriptions,
      [
        NotificationSource::Position,
        NotificationSource::CommandResponse,
      ]
    );
    assert_eq!(
      record.unsubscriptions,
      [
        NotificationSource::CommandResponse,
        NotificationSource::Position,
      ]
    );
    assert!(record.closed);
  }

  #[::tokio::test(start_paused = true)]
  async fn request_timeout_does_not_stop_the_actor() {
    let (transport, record, _notification_tx) = MockTransport::new();
    let config = ActorConfig {
      request_timeout: Duration::from_secs(5),
      ..ActorConfig::default()
    };
    let (handle, task) = spawn(transport, config).unwrap();
    wait_until_running(&handle).await;

    let query_handle = handle.clone();
    let query = ::tokio::spawn(async move { query_handle.battery_status().await });
    wait_for_write(&record, Command::read_battery_level().bytes()).await;

    ::tokio::time::advance(Duration::from_secs(6)).await;
    assert_eq!(query.await.unwrap(), Err(HandleError::RequestTimedOut));
    assert_eq!(handle.lifecycle(), LifecycleState::Running);

    handle.shutdown().await.unwrap();
    assert!(task.await.unwrap().result().is_ok());
  }

  #[::tokio::test]
  async fn malformed_notification_is_reported_without_stopping_actor() {
    let (transport, _record, notification_tx) = MockTransport::new();
    let (handle, task) = spawn(transport, ActorConfig::default()).unwrap();
    let mut events = handle.subscribe_events().await.unwrap();
    wait_until_running(&handle).await;

    notification_tx
      .send(OwnedNotification {
        source: NotificationSource::Position,
        bytes: vec![0; 29],
      })
      .await
      .unwrap();

    assert!(matches!(
      events.recv().await,
      Err(EventStreamError::Decode(DecodeNotificationError::Position(
        crate::protocol::DecodePositionNotificationError::NotificationTooShort(
          crate::protocol::NotificationTooShortError {
            expected: 34,
            actual: 29,
          }
        )
      )))
    ));
    assert_eq!(handle.lifecycle(), LifecycleState::Running);

    handle.shutdown().await.unwrap();
    assert!(task.await.unwrap().result().is_ok());
  }

  #[::tokio::test]
  async fn event_stream_reports_lag() {
    let (sender, receiver) = ::tokio::sync::broadcast::channel(1);
    let mut events = EventStream::new(receiver);

    sender
      .send(Ok(BoardEvent::BatteryStatus(BatteryStatus {
        charging: false,
        percentage: 10,
      })))
      .unwrap();
    sender
      .send(Ok(BoardEvent::BatteryStatus(BatteryStatus {
        charging: false,
        percentage: 11,
      })))
      .unwrap();

    assert_eq!(events.recv().await, Err(EventStreamError::Lagged(1)));
    assert_eq!(
      events.recv().await,
      Ok(BoardEvent::BatteryStatus(BatteryStatus {
        charging: false,
        percentage: 11,
      }))
    );
  }

  async fn wait_until_running(handle: &BoardHandle) {
    let mut lifecycle = handle.subscribe_lifecycle();
    while *lifecycle.borrow() != LifecycleState::Running {
      lifecycle.changed().await.unwrap();
    }
  }

  async fn wait_for_write(record: &Arc<Mutex<Record>>, expected: &[u8]) {
    loop {
      if record
        .lock()
        .unwrap()
        .writes
        .iter()
        .any(|write| write == expected)
      {
        return;
      }
      ::tokio::task::yield_now().await;
    }
  }

  fn piece_status_response() -> Vec<u8> {
    const IDENTITIES: [u8; 34] = [
      1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 10,
      10, 11, 11, 12,
    ];

    let mut response = vec![0; MAX_NOTIFICATION_LEN];
    response[..3].copy_from_slice(&[0x41, 0x89, 0x0b]);
    for (index, identity) in IDENTITIES.iter().copied().enumerate() {
      let offset = 3 + index * 4;
      response[offset] = identity;
      response[offset + 1] = index as u8;
      response[offset + 2] = u8::MAX - index as u8;
      response[offset + 3] = 50 + index as u8;
    }
    response
  }
}