summaryrefslogtreecommitdiff
path: root/src/rust/adaptation/mod.rs
blob: a97fa5333a47f302b0c217a7d24a503616c4da8e (plain)
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
//! Definition of UwbClientCallback

use crate::error::UwbErr;
use crate::uci::uci_hrcv;
use crate::uci::uci_logger::{UciLogMode, UciLogger, UciLoggerImpl};
use crate::uci::HalCallback;
use android_hardware_uwb::aidl::android::hardware::uwb::{
    IUwb::IUwbAsync,
    IUwbChip::IUwbChipAsync,
    IUwbClientCallback::{BnUwbClientCallback, IUwbClientCallbackAsyncServer},
    UwbEvent::UwbEvent,
    UwbStatus::UwbStatus,
};
use android_hardware_uwb::binder::{
    BinderFeatures, DeathRecipient, Interface, Result as BinderResult, Strong,
};
use async_trait::async_trait;
use binder::IBinder;
use binder_tokio::{Tokio, TokioRuntime};
use log::{error, warn};
use rustutils::system_properties;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use tokio::runtime::Handle;
use tokio::sync::{mpsc, Mutex};
use uwb_uci_packets::{
    Packet, PacketDefrager, UciCommandPacket, UciPacketChild, UciPacketHalPacket, UciPacketPacket,
};

type Result<T> = std::result::Result<T, UwbErr>;
type SyncUciLogger = Arc<dyn UciLogger + Send + Sync>;

const UCI_LOG_DEFAULT: UciLogMode = UciLogMode::Disabled;

pub struct UwbClientCallback {
    rsp_sender: mpsc::UnboundedSender<HalCallback>,
    logger: SyncUciLogger,
    defrager: Mutex<PacketDefrager>,
}

impl UwbClientCallback {
    fn new(rsp_sender: mpsc::UnboundedSender<HalCallback>, logger: SyncUciLogger) -> Self {
        UwbClientCallback { rsp_sender, logger, defrager: Default::default() }
    }

    async fn log_uci_packet(&self, packet: UciPacketPacket) {
        match packet.specialize() {
            UciPacketChild::UciResponse(pkt) => self.logger.log_uci_response(pkt).await,
            UciPacketChild::UciNotification(pkt) => self.logger.log_uci_notification(pkt).await,
            _ => {}
        }
    }
}

impl Interface for UwbClientCallback {}

#[async_trait]
impl IUwbClientCallbackAsyncServer for UwbClientCallback {
    async fn onHalEvent(&self, event: UwbEvent, event_status: UwbStatus) -> BinderResult<()> {
        self.rsp_sender
            .send(HalCallback::Event { event, event_status })
            .unwrap_or_else(|e| error!("Error sending evt callback: {:?}", e));
        Ok(())
    }

    async fn onUciMessage(&self, data: &[u8]) -> BinderResult<()> {
        if let Some(packet) = self.defrager.lock().await.defragment_packet(data) {
            // all fragments for the packet received.
            self.log_uci_packet(packet.clone()).await;
            let packet_msg = uci_hrcv::uci_message(packet);
            match packet_msg {
                Ok(uci_hrcv::UciMessage::Response(evt)) => self
                    .rsp_sender
                    .send(HalCallback::UciRsp(evt))
                    .unwrap_or_else(|e| error!("Error sending uci response: {:?}", e)),
                Ok(uci_hrcv::UciMessage::Notification(evt)) => self
                    .rsp_sender
                    .send(HalCallback::UciNtf(evt))
                    .unwrap_or_else(|e| error!("Error sending uci notification: {:?}", e)),
                _ => error!("UCI message which is neither a UCI RSP or NTF: {:?}", data),
            }
        }
        Ok(())
    }
}

async fn get_hal_service() -> Result<Strong<dyn IUwbChipAsync<Tokio>>> {
    let service_name: &str = "android.hardware.uwb.IUwb/default";
    let i_uwb: Strong<dyn IUwbAsync<Tokio>> = binder_tokio::get_interface(service_name).await?;
    let chip_names = i_uwb.getChips().await?;
    let i_uwb_chip = i_uwb.getChip(&chip_names[0]).await?.into_async();
    Ok(i_uwb_chip)
}

#[async_trait]
pub trait UwbAdaptation {
    async fn finalize(&mut self, exit_status: bool);
    async fn hal_open(&self) -> Result<()>;
    async fn hal_close(&self) -> Result<()>;
    async fn core_initialization(&self) -> Result<()>;
    async fn session_initialization(&self, session_id: i32) -> Result<()>;
    async fn send_uci_message(&self, cmd: UciCommandPacket) -> Result<()>;
}

#[derive(Clone)]
pub struct UwbAdaptationImpl {
    hal: Strong<dyn IUwbChipAsync<Tokio>>,
    #[allow(dead_code)]
    // Need to store the death recipient since link_to_death stores a weak pointer.
    hal_death_recipient: Arc<Mutex<DeathRecipient>>,
    rsp_sender: mpsc::UnboundedSender<HalCallback>,
    logger: SyncUciLogger,
}

impl UwbAdaptationImpl {
    async fn new_with_args(
        rsp_sender: mpsc::UnboundedSender<HalCallback>,
        hal: Strong<dyn IUwbChipAsync<Tokio>>,
        hal_death_recipient: Arc<Mutex<DeathRecipient>>,
    ) -> Result<Self> {
        let mode = match system_properties::read("persist.uwb.uci_logger_mode") {
            Ok(Some(logger_mode)) => match logger_mode.as_str() {
                "disabled" => UciLogMode::Disabled,
                "filtered" => UciLogMode::Filtered,
                "enabled" => UciLogMode::Enabled,
                str => {
                    warn!("Logger mode not recognized! Value: {:?}", str);
                    UCI_LOG_DEFAULT
                }
            },
            Ok(None) => UCI_LOG_DEFAULT,
            Err(e) => {
                error!("Failed to get uci_logger_mode {:?}", e);
                UCI_LOG_DEFAULT
            }
        };
        let logger = UciLoggerImpl::new(mode).await;
        Ok(UwbAdaptationImpl { hal, rsp_sender, logger: Arc::new(logger), hal_death_recipient })
    }

    pub async fn new(rsp_sender: mpsc::UnboundedSender<HalCallback>) -> Result<Self> {
        let hal = get_hal_service().await?;
        let rsp_sender_clone = rsp_sender.clone();
        let mut hal_death_recipient = DeathRecipient::new(move || {
            error!("UWB HAL died. Resetting stack...");
            // Send error HAL event to trigger stack recovery.
            rsp_sender_clone
                .send(HalCallback::Event {
                    event: UwbEvent::ERROR,
                    event_status: UwbStatus::FAILED,
                })
                .unwrap_or_else(|e| error!("Error sending error evt callback: {:?}", e));
        });
        // Register for death notification.
        hal.as_binder().link_to_death(&mut hal_death_recipient)?;
        Self::new_with_args(rsp_sender, hal, Arc::new(Mutex::new(hal_death_recipient))).await
    }
}

#[async_trait]
impl UwbAdaptation for UwbAdaptationImpl {
    async fn finalize(&mut self, _exit_status: bool) {}

    async fn hal_open(&self) -> Result<()> {
        let m_cback = BnUwbClientCallback::new_async_binder(
            UwbClientCallback::new(self.rsp_sender.clone(), self.logger.clone()),
            TokioRuntime(Handle::current()),
            BinderFeatures::default(),
        );
        Ok(self.hal.open(&m_cback).await?)
    }

    async fn hal_close(&self) -> Result<()> {
        self.logger.close_file().await;
        Ok(self.hal.close().await?)
    }

    async fn core_initialization(&self) -> Result<()> {
        Ok(self.hal.coreInit().await?)
    }

    async fn session_initialization(&self, session_id: i32) -> Result<()> {
        Ok(self.hal.sessionInit(session_id).await?)
    }

    async fn send_uci_message(&self, cmd: UciCommandPacket) -> Result<()> {
        self.logger.log_uci_command(cmd.clone()).await;
        let packet: UciPacketPacket = cmd.into();
        // fragment packet.
        let fragmented_packets: Vec<UciPacketHalPacket> = packet.into();
        for packet in fragmented_packets {
            self.hal.sendUciMessage(&packet.to_vec()).await?;
        }
        // TODO should we be validating the returned number?
        Ok(())
    }
}

enum ExpectedCall {
    Finalize {
        expected_exit_status: bool,
    },
    HalOpen {
        out: Result<()>,
    },
    HalClose {
        out: Result<()>,
    },
    CoreInitialization {
        out: Result<()>,
    },
    SessionInitialization {
        expected_session_id: i32,
        out: Result<()>,
    },
    SendUciMessage {
        expected_cmd: UciCommandPacket,
        rsp: Option<uci_hrcv::UciResponse>,
        notf: Option<uci_hrcv::UciNotification>,
        out: Result<()>,
    },
}

pub struct MockUwbAdaptation {
    rsp_sender: mpsc::UnboundedSender<HalCallback>,
    expected_calls: StdMutex<VecDeque<ExpectedCall>>,
}

impl MockUwbAdaptation {
    pub fn new(rsp_sender: mpsc::UnboundedSender<HalCallback>) -> Self {
        Self { rsp_sender, expected_calls: StdMutex::new(VecDeque::new()) }
    }

    #[allow(dead_code)]
    pub fn expect_finalize(&self, expected_exit_status: bool) {
        self.expected_calls
            .lock()
            .unwrap()
            .push_back(ExpectedCall::Finalize { expected_exit_status });
    }
    #[allow(dead_code)]
    pub fn expect_hal_open(&self, out: Result<()>) {
        self.expected_calls.lock().unwrap().push_back(ExpectedCall::HalOpen { out });
    }
    #[allow(dead_code)]
    pub fn expect_hal_close(&self, out: Result<()>) {
        self.expected_calls.lock().unwrap().push_back(ExpectedCall::HalClose { out });
    }
    #[allow(dead_code)]
    pub fn expect_core_initialization(&self, out: Result<()>) {
        self.expected_calls.lock().unwrap().push_back(ExpectedCall::CoreInitialization { out });
    }
    #[allow(dead_code)]
    pub fn expect_session_initialization(&self, expected_session_id: i32, out: Result<()>) {
        self.expected_calls
            .lock()
            .unwrap()
            .push_back(ExpectedCall::SessionInitialization { expected_session_id, out });
    }
    #[allow(dead_code)]
    pub fn expect_send_uci_message(
        &self,
        expected_cmd: UciCommandPacket,
        rsp: Option<uci_hrcv::UciResponse>,
        notf: Option<uci_hrcv::UciNotification>,
        out: Result<()>,
    ) {
        self.expected_calls.lock().unwrap().push_back(ExpectedCall::SendUciMessage {
            expected_cmd,
            rsp,
            notf,
            out,
        });
    }

    #[allow(dead_code)]
    pub fn clear_expected_calls(&self) {
        self.expected_calls.lock().unwrap().clear();
    }

    async fn send_hal_event(&self, event: UwbEvent, event_status: UwbStatus) {
        self.rsp_sender.send(HalCallback::Event { event, event_status }).unwrap();
    }

    async fn send_uci_response(&self, rsp: uci_hrcv::UciResponse) {
        self.rsp_sender.send(HalCallback::UciRsp(rsp)).unwrap();
    }

    async fn send_uci_notification(&self, ntf: uci_hrcv::UciNotification) {
        self.rsp_sender.send(HalCallback::UciNtf(ntf)).unwrap();
    }
}

impl Drop for MockUwbAdaptation {
    fn drop(&mut self) {
        assert!(self.expected_calls.lock().unwrap().is_empty());
    }
}

#[async_trait]
impl UwbAdaptation for MockUwbAdaptation {
    async fn finalize(&mut self, exit_status: bool) {
        let mut expected_calls = self.expected_calls.lock().unwrap();
        match expected_calls.pop_front() {
            Some(ExpectedCall::Finalize { expected_exit_status })
                if expected_exit_status == exit_status =>
            {
                return;
            }
            Some(call) => {
                expected_calls.push_front(call);
            }
            None => {}
        }
        warn!("unpected finalize() called");
    }

    async fn hal_open(&self) -> Result<()> {
        let expected_out = {
            let mut expected_calls = self.expected_calls.lock().unwrap();
            match expected_calls.pop_front() {
                Some(ExpectedCall::HalOpen { out }) => Some(out),
                Some(call) => {
                    expected_calls.push_front(call);
                    None
                }
                None => None,
            }
        };

        match expected_out {
            Some(out) => {
                let status = if out.is_ok() { UwbStatus::OK } else { UwbStatus::FAILED };
                self.send_hal_event(UwbEvent::OPEN_CPLT, status).await;
                out
            }
            None => {
                warn!("unpected hal_open() called");
                Err(UwbErr::Undefined)
            }
        }
    }

    async fn hal_close(&self) -> Result<()> {
        let expected_out = {
            let mut expected_calls = self.expected_calls.lock().unwrap();
            match expected_calls.pop_front() {
                Some(ExpectedCall::HalClose { out }) => Some(out),
                Some(call) => {
                    expected_calls.push_front(call);
                    None
                }
                None => None,
            }
        };

        match expected_out {
            Some(out) => {
                let status = if out.is_ok() { UwbStatus::OK } else { UwbStatus::FAILED };
                self.send_hal_event(UwbEvent::CLOSE_CPLT, status).await;
                out
            }
            None => {
                warn!("unpected hal_close() called");
                Err(UwbErr::Undefined)
            }
        }
    }

    async fn core_initialization(&self) -> Result<()> {
        let expected_out = {
            let mut expected_calls = self.expected_calls.lock().unwrap();
            match expected_calls.pop_front() {
                Some(ExpectedCall::CoreInitialization { out }) => Some(out),
                Some(call) => {
                    expected_calls.push_front(call);
                    None
                }
                None => None,
            }
        };

        match expected_out {
            Some(out) => {
                let status = if out.is_ok() { UwbStatus::OK } else { UwbStatus::FAILED };
                self.send_hal_event(UwbEvent::POST_INIT_CPLT, status).await;
                out
            }
            None => {
                warn!("unpected core_initialization() called");
                Err(UwbErr::Undefined)
            }
        }
    }

    async fn session_initialization(&self, session_id: i32) -> Result<()> {
        let expected_out = {
            let mut expected_calls = self.expected_calls.lock().unwrap();
            match expected_calls.pop_front() {
                Some(ExpectedCall::SessionInitialization { expected_session_id, out })
                    if expected_session_id == session_id =>
                {
                    Some(out)
                }
                Some(call) => {
                    expected_calls.push_front(call);
                    None
                }
                None => None,
            }
        };

        match expected_out {
            Some(out) => out,
            None => {
                warn!("unpected session_initialization() called");
                Err(UwbErr::Undefined)
            }
        }
    }

    async fn send_uci_message(&self, cmd: UciCommandPacket) -> Result<()> {
        let expected_out = {
            let mut expected_calls = self.expected_calls.lock().unwrap();
            match expected_calls.pop_front() {
                Some(ExpectedCall::SendUciMessage {
                    expected_cmd,
                    rsp,
                    notf,
                    out,
                    // PDL generated packets do not implement PartialEq, so use the raw bytes for comparison.
                }) if expected_cmd.clone().to_bytes() == cmd.to_bytes() => Some((rsp, notf, out)),
                Some(call) => {
                    expected_calls.push_front(call);
                    None
                }
                None => None,
            }
        };

        match expected_out {
            Some((rsp, notf, out)) => {
                if let Some(notf) = notf {
                    self.send_uci_notification(notf).await;
                }
                if let Some(rsp) = rsp {
                    self.send_uci_response(rsp).await;
                }
                out
            }
            None => {
                warn!("unpected send_uci_message() called");
                Err(UwbErr::Undefined)
            }
        }
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use android_hardware_uwb::aidl::android::hardware::uwb::IUwbClientCallback::IUwbClientCallback;
    use binder::{SpIBinder, StatusCode};
    use bytes::Bytes;
    use uwb_uci_packets::*;
    enum ExpectedHalCall {
        Open { out: BinderResult<()> },
        Close { out: BinderResult<()> },
        CoreInit { out: BinderResult<()> },
        SessionInit { expected_session_id: i32, out: BinderResult<()> },
        SendUciMessage { expected_data: Vec<u8>, out: BinderResult<i32> },
    }
    use crate::uci::uci_logger::MockUciLogger;

    #[cfg(test)]
    fn create_uwb_client_callback(
        rsp_sender: mpsc::UnboundedSender<HalCallback>,
    ) -> UwbClientCallback {
        // Add tests for the mock logger.
        UwbClientCallback::new(rsp_sender, Arc::new(MockUciLogger::new()))
    }

    pub struct MockHal {
        expected_calls: StdMutex<VecDeque<ExpectedHalCall>>,
    }

    impl MockHal {
        pub fn new() -> Self {
            Self { expected_calls: StdMutex::new(VecDeque::new()) }
        }

        #[allow(dead_code)]
        pub fn expect_open(&self, out: BinderResult<()>) {
            self.expected_calls.lock().unwrap().push_back(ExpectedHalCall::Open { out });
        }
        #[allow(dead_code)]
        pub fn expect_close(&self, out: BinderResult<()>) {
            self.expected_calls.lock().unwrap().push_back(ExpectedHalCall::Close { out });
        }
        #[allow(dead_code)]
        pub fn expect_core_init(&self, out: BinderResult<()>) {
            self.expected_calls.lock().unwrap().push_back(ExpectedHalCall::CoreInit { out });
        }
        #[allow(dead_code)]
        pub fn expect_session_init(&self, expected_session_id: i32, out: BinderResult<()>) {
            self.expected_calls
                .lock()
                .unwrap()
                .push_back(ExpectedHalCall::SessionInit { expected_session_id, out });
        }
        #[allow(dead_code)]
        pub fn expect_send_uci_message(&self, expected_data: Vec<u8>, out: BinderResult<i32>) {
            self.expected_calls
                .lock()
                .unwrap()
                .push_back(ExpectedHalCall::SendUciMessage { expected_data, out });
        }
    }

    impl Drop for MockHal {
        fn drop(&mut self) {
            assert!(self.expected_calls.lock().unwrap().is_empty());
        }
    }
    impl Default for MockHal {
        fn default() -> Self {
            Self::new()
        }
    }

    impl binder::Interface for MockHal {}

    impl binder::FromIBinder for MockHal {
        fn try_from(_ibinder: SpIBinder) -> std::result::Result<Strong<Self>, binder::StatusCode> {
            Err(binder::StatusCode::OK)
        }
    }

    #[async_trait]
    impl<P: binder::BinderAsyncPool> IUwbChipAsync<P> for MockHal {
        fn getName(&self) -> binder::BoxFuture<BinderResult<String>> {
            Box::pin(std::future::ready(Ok("default".into())))
        }

        fn open<'a>(
            &'a self,
            _cb: &'a binder::Strong<dyn IUwbClientCallback>,
        ) -> binder::BoxFuture<'a, BinderResult<()>> {
            let expected_out = {
                let mut expected_calls = self.expected_calls.lock().unwrap();
                match expected_calls.pop_front() {
                    Some(ExpectedHalCall::Open { out }) => Some(out),
                    Some(call) => {
                        expected_calls.push_front(call);
                        None
                    }
                    None => None,
                }
            };

            match expected_out {
                Some(out) => Box::pin(std::future::ready(out)),
                None => Box::pin(std::future::ready(Err(StatusCode::UNKNOWN_ERROR.into()))),
            }
        }

        fn close(&self) -> binder::BoxFuture<BinderResult<()>> {
            let expected_out = {
                let mut expected_calls = self.expected_calls.lock().unwrap();
                match expected_calls.pop_front() {
                    Some(ExpectedHalCall::Close { out }) => Some(out),
                    Some(call) => {
                        expected_calls.push_front(call);
                        None
                    }
                    None => None,
                }
            };

            match expected_out {
                Some(out) => Box::pin(std::future::ready(out)),
                None => Box::pin(std::future::ready(Err(StatusCode::UNKNOWN_ERROR.into()))),
            }
        }

        fn coreInit(&self) -> binder::BoxFuture<BinderResult<()>> {
            let expected_out = {
                let mut expected_calls = self.expected_calls.lock().unwrap();
                match expected_calls.pop_front() {
                    Some(ExpectedHalCall::CoreInit { out }) => Some(out),
                    Some(call) => {
                        expected_calls.push_front(call);
                        None
                    }
                    None => None,
                }
            };

            match expected_out {
                Some(out) => Box::pin(std::future::ready(out)),
                None => Box::pin(std::future::ready(Err(StatusCode::UNKNOWN_ERROR.into()))),
            }
        }

        fn sessionInit(&self, session_id: i32) -> binder::BoxFuture<BinderResult<()>> {
            let expected_out = {
                let mut expected_calls = self.expected_calls.lock().unwrap();
                match expected_calls.pop_front() {
                    Some(ExpectedHalCall::SessionInit { expected_session_id, out })
                        if expected_session_id == session_id =>
                    {
                        Some(out)
                    }
                    Some(call) => {
                        expected_calls.push_front(call);
                        None
                    }
                    None => None,
                }
            };

            match expected_out {
                Some(out) => Box::pin(std::future::ready(out)),
                None => Box::pin(std::future::ready(Err(StatusCode::UNKNOWN_ERROR.into()))),
            }
        }

        fn getSupportedAndroidUciVersion(&self) -> binder::BoxFuture<BinderResult<i32>> {
            Box::pin(std::future::ready(Ok(0)))
        }

        fn sendUciMessage(&self, cmd: &[u8]) -> binder::BoxFuture<BinderResult<i32>> {
            let expected_out = {
                let mut expected_calls = self.expected_calls.lock().unwrap();
                match expected_calls.pop_front() {
                    Some(ExpectedHalCall::SendUciMessage { expected_data, out })
                        if expected_data == cmd =>
                    {
                        Some(out)
                    }
                    Some(call) => {
                        expected_calls.push_front(call);
                        None
                    }
                    None => None,
                }
            };
            match expected_out {
                Some(out) => Box::pin(std::future::ready(out)),
                None => Box::pin(std::future::ready(Err(StatusCode::UNKNOWN_ERROR.into()))),
            }
        }
    }

    fn setup_client_callback() -> (mpsc::UnboundedReceiver<HalCallback>, UwbClientCallback) {
        // TODO: Remove this once we call it somewhere real.
        logger::init(
            logger::Config::default()
                .with_tag_on_device("uwb_test")
                .with_min_level(log::Level::Debug),
        );
        let (rsp_sender, rsp_receiver) = mpsc::unbounded_channel::<HalCallback>();
        let uwb_client_callback = create_uwb_client_callback(rsp_sender);
        (rsp_receiver, uwb_client_callback)
    }

    #[tokio::test]
    async fn test_on_hal_event() {
        let event = UwbEvent(0);
        let event_status = UwbStatus(1);
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onHalEvent(event, event_status).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(response, Some(HalCallback::Event { event: _, event_status: _ })));
    }

    #[tokio::test]
    async fn test_get_device_info_rsp() {
        let data = [
            0x40, 0x02, 0x00, 0x0b, 0x01, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x01,
            0x0a,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::GetDeviceInfoRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_get_caps_info_rsp() {
        let data = [0x40, 0x03, 0x00, 0x05, 0x00, 0x01, 0x00, 0x01, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::GetCapsInfoRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_set_config_rsp() {
        let data = [0x40, 0x04, 0x00, 0x04, 0x01, 0x01, 0x01, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SetConfigRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_get_config_rsp() {
        let data = [0x40, 0x05, 0x00, 0x05, 0x01, 0x01, 0x00, 0x01, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::GetConfigRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_device_reset_rsp() {
        let data = [0x40, 0x00, 0x00, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::DeviceResetRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_init_rsp() {
        let data = [0x41, 0x00, 0x00, 0x01, 0x11];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SessionInitRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_deinit_rsp() {
        let data = [0x41, 0x01, 0x00, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SessionDeinitRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_get_app_config_rsp() {
        let data = [0x41, 0x04, 0x00, 0x02, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SessionGetAppConfigRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_set_app_config_rsp() {
        let data = [0x41, 0x03, 0x00, 0x04, 0x01, 0x01, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SessionSetAppConfigRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_get_state_rsp() {
        let data = [0x41, 0x06, 0x00, 0x02, 0x00, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SessionGetStateRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_get_count_rsp() {
        let data = [0x41, 0x05, 0x00, 0x02, 0x00, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::SessionGetCountRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_update_controller_multicast_list_rsp() {
        let data = [0x41, 0x07, 0x00, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(
                uci_hrcv::UciResponse::SessionUpdateControllerMulticastListRsp(_)
            ))
        ));
    }

    #[tokio::test]
    async fn test_range_start_rsp() {
        let data = [0x42, 0x00, 0x00, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::RangeStartRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_range_stop_rsp() {
        let data = [0x42, 0x01, 0x00, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::RangeStopRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_android_set_country_code_rsp() {
        let data = [0x4c, 0x01, 0x00, 0x01, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::AndroidSetCountryCodeRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_android_get_power_stats_rsp() {
        let data = [
            0x4c, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::AndroidGetPowerStatsRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_raw_vendor_rsp_fragmented_packet() {
        let fragment_1 = [
            0x59, 0x01, 0x00, 0xff, 0x81, 0x93, 0xf8, 0x56, 0x53, 0x74, 0x5d, 0xcf, 0x45, 0xfa,
            0x34, 0xbd, 0xf1, 0x56, 0x53, 0x8f, 0x13, 0xff, 0x9b, 0xdd, 0xee, 0xaf, 0x0e, 0xff,
            0x1e, 0x63, 0xb6, 0xd7, 0xd4, 0x7b, 0xb7, 0x78, 0x30, 0xc7, 0x92, 0xd0, 0x8a, 0x5e,
            0xf0, 0x00, 0x1d, 0x05, 0xea, 0xf9, 0x56, 0xce, 0x8b, 0xbc, 0x8b, 0x1b, 0xc2, 0xd4,
            0x2a, 0xb8, 0x14, 0x82, 0x8b, 0xed, 0x12, 0xe5, 0x83, 0xe6, 0xb0, 0xb8, 0xa0, 0xb9,
            0xd0, 0x90, 0x6e, 0x09, 0x4e, 0x2e, 0x22, 0x38, 0x39, 0x03, 0x66, 0xf5, 0x95, 0x14,
            0x1c, 0xd7, 0x60, 0xbf, 0x28, 0x58, 0x9d, 0x47, 0x18, 0x1a, 0x93, 0x59, 0xbb, 0x0d,
            0x88, 0xf7, 0x7c, 0xce, 0x13, 0xa8, 0x2f, 0x3d, 0x0e, 0xd9, 0x5c, 0x19, 0x45, 0x5d,
            0xe8, 0xc3, 0xe0, 0x3a, 0xf3, 0x71, 0x09, 0x6e, 0x73, 0x07, 0x96, 0xa9, 0x1f, 0xf4,
            0x57, 0x84, 0x2e, 0x59, 0x6a, 0xf6, 0x90, 0x28, 0x47, 0xc1, 0x51, 0x7c, 0x59, 0x7e,
            0x95, 0xfc, 0xa6, 0x4d, 0x1b, 0xe6, 0xfe, 0x97, 0xa0, 0x39, 0x91, 0xa8, 0x28, 0xc9,
            0x1d, 0x7e, 0xfc, 0xec, 0x71, 0x1d, 0x43, 0x38, 0xcb, 0xbd, 0x50, 0xea, 0x02, 0xfd,
            0x2c, 0x7a, 0xde, 0x06, 0xdd, 0x77, 0x69, 0x4d, 0x2f, 0x57, 0xf5, 0x4b, 0x97, 0x51,
            0x58, 0x66, 0x7a, 0x8a, 0xcb, 0x7b, 0x91, 0x18, 0xbe, 0x4e, 0x94, 0xe4, 0xf1, 0xed,
            0x52, 0x06, 0xa7, 0xe8, 0x6b, 0xe1, 0x8f, 0x4a, 0x06, 0xe8, 0x2c, 0x9f, 0xc7, 0xcb,
            0xd2, 0x10, 0xb0, 0x0b, 0x71, 0x80, 0x2c, 0xd1, 0xf1, 0x03, 0xc2, 0x79, 0x7e, 0x7f,
            0x70, 0xf4, 0x8c, 0xc9, 0xcf, 0x9f, 0xcf, 0xa2, 0x8e, 0x6a, 0xe4, 0x1a, 0x28, 0x05,
            0xa8, 0xfe, 0x7d, 0xec, 0xd9, 0x5f, 0xa7, 0xd0, 0x29, 0x63, 0x1a, 0xba, 0x39, 0xf7,
            0xfa, 0x5e, 0xff, 0xb8, 0x5a, 0xbd, 0x35,
        ];
        let fragment_2 = [
            0x49, 0x01, 0x00, 0x91, 0xe7, 0x26, 0xfb, 0xc4, 0x48, 0x68, 0x42, 0x93, 0x23, 0x1f,
            0x87, 0xf6, 0x12, 0x5e, 0x60, 0xc8, 0x6a, 0x9d, 0x98, 0xbb, 0xb2, 0xb0, 0x47, 0x2f,
            0xaa, 0xa5, 0xce, 0xdb, 0x32, 0x88, 0x86, 0x0d, 0x6a, 0x5a, 0xfe, 0xc8, 0xda, 0xa1,
            0xc0, 0x06, 0x37, 0x08, 0xda, 0x67, 0x49, 0x6a, 0xa7, 0x04, 0x62, 0x95, 0xf3, 0x1e,
            0xcd, 0x71, 0x00, 0x99, 0x68, 0xb4, 0x03, 0xb3, 0x15, 0x64, 0x8b, 0xde, 0xbc, 0x8f,
            0x41, 0x64, 0xdf, 0x34, 0x6e, 0xff, 0x48, 0xc8, 0xe2, 0xbf, 0x02, 0x15, 0xc5, 0xbc,
            0x0f, 0xf8, 0xa1, 0x49, 0x91, 0x71, 0xdd, 0xb4, 0x37, 0x1c, 0xfa, 0x60, 0xcb, 0x0f,
            0xce, 0x6a, 0x0e, 0x90, 0xaf, 0x14, 0x30, 0xf2, 0x5b, 0x21, 0x6f, 0x85, 0xd3, 0x1b,
            0x89, 0xc9, 0xba, 0x3f, 0x07, 0x11, 0xbd, 0x56, 0xda, 0xdc, 0x88, 0xb4, 0xb0, 0x57,
            0x0b, 0x0c, 0x44, 0xd9, 0xb9, 0xd2, 0x38, 0x4c, 0xb6, 0xff, 0x83, 0xfe, 0xc8, 0x65,
            0xbc, 0x2a, 0x10, 0xed, 0x18, 0x62, 0xd2, 0x1b, 0x87,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result1 = uwb_client_callback.onUciMessage(&fragment_1).await;
        assert_eq!(result1, Ok(()));
        let result2 = uwb_client_callback.onUciMessage(&fragment_2).await;
        assert_eq!(result2, Ok(()));
        // One defragmented packet sent as response
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciRsp(uci_hrcv::UciResponse::RawVendorRsp(_)))
        ));
    }

    #[tokio::test]
    async fn test_generic_error_ntf() {
        let data = [0x60, 0x07, 0x00, 0x01, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(uci_hrcv::UciNotification::GenericError(_)))
        ));
    }

    #[tokio::test]
    async fn test_device_status_ntf() {
        let data = [0x60, 0x01, 0x00, 0x01, 0x01];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(uci_hrcv::UciNotification::DeviceStatusNtf(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_status_ntf() {
        let data = [0x61, 0x02, 0x00, 0x06, 0x01, 0x02, 0x03, 0x04, 0x02, 0x21];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(uci_hrcv::UciNotification::SessionStatusNtf(_)))
        ));
    }

    #[tokio::test]
    async fn test_session_update_controller_multicast_list_ntf() {
        let data = [0x61, 0x07, 0x00, 0x06, 0x00, 0x01, 0x02, 0x03, 0x04, 0x00];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(
                uci_hrcv::UciNotification::SessionUpdateControllerMulticastListNtf(_)
            ))
        ));
    }

    #[tokio::test]
    async fn test_short_mac_two_way_range_data_ntf() {
        let data = [
            0x62, 0x00, 0x00, 0x19, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x0a,
            0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(uci_hrcv::UciNotification::ShortMacTwoWayRangeDataNtf(_)))
        ));
    }

    #[tokio::test]
    async fn test_extended_mac_two_way_range_data_ntf() {
        let data = [
            0x62, 0x00, 0x00, 0x19, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x0a,
            0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(uci_hrcv::UciNotification::ExtendedMacTwoWayRangeDataNtf(_)))
        ));
    }

    #[tokio::test]
    async fn test_raw_vendor_ntf_fragmented_packet() {
        let fragment_1 = [
            0x79, 0x01, 0x00, 0xff, 0x81, 0x93, 0xf8, 0x56, 0x53, 0x74, 0x5d, 0xcf, 0x45, 0xfa,
            0x34, 0xbd, 0xf1, 0x56, 0x53, 0x8f, 0x13, 0xff, 0x9b, 0xdd, 0xee, 0xaf, 0x0e, 0xff,
            0x1e, 0x63, 0xb6, 0xd7, 0xd4, 0x7b, 0xb7, 0x78, 0x30, 0xc7, 0x92, 0xd0, 0x8a, 0x5e,
            0xf0, 0x00, 0x1d, 0x05, 0xea, 0xf9, 0x56, 0xce, 0x8b, 0xbc, 0x8b, 0x1b, 0xc2, 0xd4,
            0x2a, 0xb8, 0x14, 0x82, 0x8b, 0xed, 0x12, 0xe5, 0x83, 0xe6, 0xb0, 0xb8, 0xa0, 0xb9,
            0xd0, 0x90, 0x6e, 0x09, 0x4e, 0x2e, 0x22, 0x38, 0x39, 0x03, 0x66, 0xf5, 0x95, 0x14,
            0x1c, 0xd7, 0x60, 0xbf, 0x28, 0x58, 0x9d, 0x47, 0x18, 0x1a, 0x93, 0x59, 0xbb, 0x0d,
            0x88, 0xf7, 0x7c, 0xce, 0x13, 0xa8, 0x2f, 0x3d, 0x0e, 0xd9, 0x5c, 0x19, 0x45, 0x5d,
            0xe8, 0xc3, 0xe0, 0x3a, 0xf3, 0x71, 0x09, 0x6e, 0x73, 0x07, 0x96, 0xa9, 0x1f, 0xf4,
            0x57, 0x84, 0x2e, 0x59, 0x6a, 0xf6, 0x90, 0x28, 0x47, 0xc1, 0x51, 0x7c, 0x59, 0x7e,
            0x95, 0xfc, 0xa6, 0x4d, 0x1b, 0xe6, 0xfe, 0x97, 0xa0, 0x39, 0x91, 0xa8, 0x28, 0xc9,
            0x1d, 0x7e, 0xfc, 0xec, 0x71, 0x1d, 0x43, 0x38, 0xcb, 0xbd, 0x50, 0xea, 0x02, 0xfd,
            0x2c, 0x7a, 0xde, 0x06, 0xdd, 0x77, 0x69, 0x4d, 0x2f, 0x57, 0xf5, 0x4b, 0x97, 0x51,
            0x58, 0x66, 0x7a, 0x8a, 0xcb, 0x7b, 0x91, 0x18, 0xbe, 0x4e, 0x94, 0xe4, 0xf1, 0xed,
            0x52, 0x06, 0xa7, 0xe8, 0x6b, 0xe1, 0x8f, 0x4a, 0x06, 0xe8, 0x2c, 0x9f, 0xc7, 0xcb,
            0xd2, 0x10, 0xb0, 0x0b, 0x71, 0x80, 0x2c, 0xd1, 0xf1, 0x03, 0xc2, 0x79, 0x7e, 0x7f,
            0x70, 0xf4, 0x8c, 0xc9, 0xcf, 0x9f, 0xcf, 0xa2, 0x8e, 0x6a, 0xe4, 0x1a, 0x28, 0x05,
            0xa8, 0xfe, 0x7d, 0xec, 0xd9, 0x5f, 0xa7, 0xd0, 0x29, 0x63, 0x1a, 0xba, 0x39, 0xf7,
            0xfa, 0x5e, 0xff, 0xb8, 0x5a, 0xbd, 0x35,
        ];
        let fragment_2 = [
            0x69, 0x01, 0x00, 0x91, 0xe7, 0x26, 0xfb, 0xc4, 0x48, 0x68, 0x42, 0x93, 0x23, 0x1f,
            0x87, 0xf6, 0x12, 0x5e, 0x60, 0xc8, 0x6a, 0x9d, 0x98, 0xbb, 0xb2, 0xb0, 0x47, 0x2f,
            0xaa, 0xa5, 0xce, 0xdb, 0x32, 0x88, 0x86, 0x0d, 0x6a, 0x5a, 0xfe, 0xc8, 0xda, 0xa1,
            0xc0, 0x06, 0x37, 0x08, 0xda, 0x67, 0x49, 0x6a, 0xa7, 0x04, 0x62, 0x95, 0xf3, 0x1e,
            0xcd, 0x71, 0x00, 0x99, 0x68, 0xb4, 0x03, 0xb3, 0x15, 0x64, 0x8b, 0xde, 0xbc, 0x8f,
            0x41, 0x64, 0xdf, 0x34, 0x6e, 0xff, 0x48, 0xc8, 0xe2, 0xbf, 0x02, 0x15, 0xc5, 0xbc,
            0x0f, 0xf8, 0xa1, 0x49, 0x91, 0x71, 0xdd, 0xb4, 0x37, 0x1c, 0xfa, 0x60, 0xcb, 0x0f,
            0xce, 0x6a, 0x0e, 0x90, 0xaf, 0x14, 0x30, 0xf2, 0x5b, 0x21, 0x6f, 0x85, 0xd3, 0x1b,
            0x89, 0xc9, 0xba, 0x3f, 0x07, 0x11, 0xbd, 0x56, 0xda, 0xdc, 0x88, 0xb4, 0xb0, 0x57,
            0x0b, 0x0c, 0x44, 0xd9, 0xb9, 0xd2, 0x38, 0x4c, 0xb6, 0xff, 0x83, 0xfe, 0xc8, 0x65,
            0xbc, 0x2a, 0x10, 0xed, 0x18, 0x62, 0xd2, 0x1b, 0x87,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result1 = uwb_client_callback.onUciMessage(&fragment_1).await;
        assert_eq!(result1, Ok(()));
        let result2 = uwb_client_callback.onUciMessage(&fragment_2).await;
        assert_eq!(result2, Ok(()));
        // One defragmented packet sent as response
        let response = rsp_receiver.recv().await;
        assert!(matches!(
            response,
            Some(HalCallback::UciNtf(uci_hrcv::UciNotification::RawVendorNtf(_)))
        ));
    }

    #[tokio::test]
    async fn test_on_uci_message_bad() {
        let data = [
            0x42, 0x02, 0x00, 0x0b, 0x01, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x01,
            0x0a,
        ];
        let (mut rsp_receiver, uwb_client_callback) = setup_client_callback();
        let result = uwb_client_callback.onUciMessage(&data).await;
        assert_eq!(result, Ok(()));
        let response = rsp_receiver.try_recv();
        assert!(response.is_err());
    }

    async fn setup_adaptation_impl(config_fn: impl Fn(&MockHal)) -> Result<UwbAdaptationImpl> {
        // TODO: Remove this once we call it somewhere real.
        logger::init(
            logger::Config::default()
                .with_tag_on_device("uwb_test")
                .with_min_level(log::Level::Debug),
        );
        let (rsp_sender, _) = mpsc::unbounded_channel::<HalCallback>();
        let mock_hal = MockHal::new();
        config_fn(&mock_hal);

        UwbAdaptationImpl::new_with_args(
            rsp_sender,
            binder::Strong::new(Box::new(mock_hal)),
            Arc::new(Mutex::new(DeathRecipient::new(|| {}))),
        )
        .await
    }

    #[tokio::test]
    async fn test_send_uci_message() {
        let cmd: UciCommandPacket = GetDeviceInfoCmdBuilder {}.build().into();
        let adaptation_impl = setup_adaptation_impl(|mock_hal| {
            let cmd_packet: UciPacketPacket = cmd.clone().into();
            let mut cmd_frag_packets: Vec<UciPacketHalPacket> = cmd_packet.into();
            let cmd_frag_data = cmd_frag_packets.pop().unwrap().to_vec();
            let cmd_frag_data_len = cmd_frag_data.len();
            mock_hal
                .expect_send_uci_message(cmd_frag_data, Ok(cmd_frag_data_len.try_into().unwrap()));
        })
        .await
        .unwrap();
        adaptation_impl.send_uci_message(cmd).await.unwrap();
    }

    #[tokio::test]
    async fn test_send_uci_message_fragmented_packet() {
        let (rsp_sender, _) = mpsc::unbounded_channel::<HalCallback>();
        let mock_hal = MockHal::new();

        let cmd_payload: [u8; 400] = [
            0x81, 0x93, 0xf8, 0x56, 0x53, 0x74, 0x5d, 0xcf, 0x45, 0xfa, 0x34, 0xbd, 0xf1, 0x56,
            0x53, 0x8f, 0x13, 0xff, 0x9b, 0xdd, 0xee, 0xaf, 0x0e, 0xff, 0x1e, 0x63, 0xb6, 0xd7,
            0xd4, 0x7b, 0xb7, 0x78, 0x30, 0xc7, 0x92, 0xd0, 0x8a, 0x5e, 0xf0, 0x00, 0x1d, 0x05,
            0xea, 0xf9, 0x56, 0xce, 0x8b, 0xbc, 0x8b, 0x1b, 0xc2, 0xd4, 0x2a, 0xb8, 0x14, 0x82,
            0x8b, 0xed, 0x12, 0xe5, 0x83, 0xe6, 0xb0, 0xb8, 0xa0, 0xb9, 0xd0, 0x90, 0x6e, 0x09,
            0x4e, 0x2e, 0x22, 0x38, 0x39, 0x03, 0x66, 0xf5, 0x95, 0x14, 0x1c, 0xd7, 0x60, 0xbf,
            0x28, 0x58, 0x9d, 0x47, 0x18, 0x1a, 0x93, 0x59, 0xbb, 0x0d, 0x88, 0xf7, 0x7c, 0xce,
            0x13, 0xa8, 0x2f, 0x3d, 0x0e, 0xd9, 0x5c, 0x19, 0x45, 0x5d, 0xe8, 0xc3, 0xe0, 0x3a,
            0xf3, 0x71, 0x09, 0x6e, 0x73, 0x07, 0x96, 0xa9, 0x1f, 0xf4, 0x57, 0x84, 0x2e, 0x59,
            0x6a, 0xf6, 0x90, 0x28, 0x47, 0xc1, 0x51, 0x7c, 0x59, 0x7e, 0x95, 0xfc, 0xa6, 0x4d,
            0x1b, 0xe6, 0xfe, 0x97, 0xa0, 0x39, 0x91, 0xa8, 0x28, 0xc9, 0x1d, 0x7e, 0xfc, 0xec,
            0x71, 0x1d, 0x43, 0x38, 0xcb, 0xbd, 0x50, 0xea, 0x02, 0xfd, 0x2c, 0x7a, 0xde, 0x06,
            0xdd, 0x77, 0x69, 0x4d, 0x2f, 0x57, 0xf5, 0x4b, 0x97, 0x51, 0x58, 0x66, 0x7a, 0x8a,
            0xcb, 0x7b, 0x91, 0x18, 0xbe, 0x4e, 0x94, 0xe4, 0xf1, 0xed, 0x52, 0x06, 0xa7, 0xe8,
            0x6b, 0xe1, 0x8f, 0x4a, 0x06, 0xe8, 0x2c, 0x9f, 0xc7, 0xcb, 0xd2, 0x10, 0xb0, 0x0b,
            0x71, 0x80, 0x2c, 0xd1, 0xf1, 0x03, 0xc2, 0x79, 0x7e, 0x7f, 0x70, 0xf4, 0x8c, 0xc9,
            0xcf, 0x9f, 0xcf, 0xa2, 0x8e, 0x6a, 0xe4, 0x1a, 0x28, 0x05, 0xa8, 0xfe, 0x7d, 0xec,
            0xd9, 0x5f, 0xa7, 0xd0, 0x29, 0x63, 0x1a, 0xba, 0x39, 0xf7, 0xfa, 0x5e, 0xff, 0xb8,
            0x5a, 0xbd, 0x35, 0xe7, 0x26, 0xfb, 0xc4, 0x48, 0x68, 0x42, 0x93, 0x23, 0x1f, 0x87,
            0xf6, 0x12, 0x5e, 0x60, 0xc8, 0x6a, 0x9d, 0x98, 0xbb, 0xb2, 0xb0, 0x47, 0x2f, 0xaa,
            0xa5, 0xce, 0xdb, 0x32, 0x88, 0x86, 0x0d, 0x6a, 0x5a, 0xfe, 0xc8, 0xda, 0xa1, 0xc0,
            0x06, 0x37, 0x08, 0xda, 0x67, 0x49, 0x6a, 0xa7, 0x04, 0x62, 0x95, 0xf3, 0x1e, 0xcd,
            0x71, 0x00, 0x99, 0x68, 0xb4, 0x03, 0xb3, 0x15, 0x64, 0x8b, 0xde, 0xbc, 0x8f, 0x41,
            0x64, 0xdf, 0x34, 0x6e, 0xff, 0x48, 0xc8, 0xe2, 0xbf, 0x02, 0x15, 0xc5, 0xbc, 0x0f,
            0xf8, 0xa1, 0x49, 0x91, 0x71, 0xdd, 0xb4, 0x37, 0x1c, 0xfa, 0x60, 0xcb, 0x0f, 0xce,
            0x6a, 0x0e, 0x90, 0xaf, 0x14, 0x30, 0xf2, 0x5b, 0x21, 0x6f, 0x85, 0xd3, 0x1b, 0x89,
            0xc9, 0xba, 0x3f, 0x07, 0x11, 0xbd, 0x56, 0xda, 0xdc, 0x88, 0xb4, 0xb0, 0x57, 0x0b,
            0x0c, 0x44, 0xd9, 0xb9, 0xd2, 0x38, 0x4c, 0xb6, 0xff, 0x83, 0xfe, 0xc8, 0x65, 0xbc,
            0x2a, 0x10, 0xed, 0x18, 0x62, 0xd2, 0x1b, 0x87,
        ];
        let cmd: UciCommandPacket = UciVendor_9_CommandBuilder {
            opcode: 1,
            payload: Some(Bytes::from(cmd_payload.to_vec())),
        }
        .build()
        .into();

        let cmd_frag_data_1 = [
            0x39, 0x01, 0x00, 0xff, 0x81, 0x93, 0xf8, 0x56, 0x53, 0x74, 0x5d, 0xcf, 0x45, 0xfa,
            0x34, 0xbd, 0xf1, 0x56, 0x53, 0x8f, 0x13, 0xff, 0x9b, 0xdd, 0xee, 0xaf, 0x0e, 0xff,
            0x1e, 0x63, 0xb6, 0xd7, 0xd4, 0x7b, 0xb7, 0x78, 0x30, 0xc7, 0x92, 0xd0, 0x8a, 0x5e,
            0xf0, 0x00, 0x1d, 0x05, 0xea, 0xf9, 0x56, 0xce, 0x8b, 0xbc, 0x8b, 0x1b, 0xc2, 0xd4,
            0x2a, 0xb8, 0x14, 0x82, 0x8b, 0xed, 0x12, 0xe5, 0x83, 0xe6, 0xb0, 0xb8, 0xa0, 0xb9,
            0xd0, 0x90, 0x6e, 0x09, 0x4e, 0x2e, 0x22, 0x38, 0x39, 0x03, 0x66, 0xf5, 0x95, 0x14,
            0x1c, 0xd7, 0x60, 0xbf, 0x28, 0x58, 0x9d, 0x47, 0x18, 0x1a, 0x93, 0x59, 0xbb, 0x0d,
            0x88, 0xf7, 0x7c, 0xce, 0x13, 0xa8, 0x2f, 0x3d, 0x0e, 0xd9, 0x5c, 0x19, 0x45, 0x5d,
            0xe8, 0xc3, 0xe0, 0x3a, 0xf3, 0x71, 0x09, 0x6e, 0x73, 0x07, 0x96, 0xa9, 0x1f, 0xf4,
            0x57, 0x84, 0x2e, 0x59, 0x6a, 0xf6, 0x90, 0x28, 0x47, 0xc1, 0x51, 0x7c, 0x59, 0x7e,
            0x95, 0xfc, 0xa6, 0x4d, 0x1b, 0xe6, 0xfe, 0x97, 0xa0, 0x39, 0x91, 0xa8, 0x28, 0xc9,
            0x1d, 0x7e, 0xfc, 0xec, 0x71, 0x1d, 0x43, 0x38, 0xcb, 0xbd, 0x50, 0xea, 0x02, 0xfd,
            0x2c, 0x7a, 0xde, 0x06, 0xdd, 0x77, 0x69, 0x4d, 0x2f, 0x57, 0xf5, 0x4b, 0x97, 0x51,
            0x58, 0x66, 0x7a, 0x8a, 0xcb, 0x7b, 0x91, 0x18, 0xbe, 0x4e, 0x94, 0xe4, 0xf1, 0xed,
            0x52, 0x06, 0xa7, 0xe8, 0x6b, 0xe1, 0x8f, 0x4a, 0x06, 0xe8, 0x2c, 0x9f, 0xc7, 0xcb,
            0xd2, 0x10, 0xb0, 0x0b, 0x71, 0x80, 0x2c, 0xd1, 0xf1, 0x03, 0xc2, 0x79, 0x7e, 0x7f,
            0x70, 0xf4, 0x8c, 0xc9, 0xcf, 0x9f, 0xcf, 0xa2, 0x8e, 0x6a, 0xe4, 0x1a, 0x28, 0x05,
            0xa8, 0xfe, 0x7d, 0xec, 0xd9, 0x5f, 0xa7, 0xd0, 0x29, 0x63, 0x1a, 0xba, 0x39, 0xf7,
            0xfa, 0x5e, 0xff, 0xb8, 0x5a, 0xbd, 0x35,
        ];
        let cmd_frag_data_len_1 = cmd_frag_data_1.len();

        let cmd_frag_data_2 = [
            0x29, 0x01, 0x00, 0x91, 0xe7, 0x26, 0xfb, 0xc4, 0x48, 0x68, 0x42, 0x93, 0x23, 0x1f,
            0x87, 0xf6, 0x12, 0x5e, 0x60, 0xc8, 0x6a, 0x9d, 0x98, 0xbb, 0xb2, 0xb0, 0x47, 0x2f,
            0xaa, 0xa5, 0xce, 0xdb, 0x32, 0x88, 0x86, 0x0d, 0x6a, 0x5a, 0xfe, 0xc8, 0xda, 0xa1,
            0xc0, 0x06, 0x37, 0x08, 0xda, 0x67, 0x49, 0x6a, 0xa7, 0x04, 0x62, 0x95, 0xf3, 0x1e,
            0xcd, 0x71, 0x00, 0x99, 0x68, 0xb4, 0x03, 0xb3, 0x15, 0x64, 0x8b, 0xde, 0xbc, 0x8f,
            0x41, 0x64, 0xdf, 0x34, 0x6e, 0xff, 0x48, 0xc8, 0xe2, 0xbf, 0x02, 0x15, 0xc5, 0xbc,
            0x0f, 0xf8, 0xa1, 0x49, 0x91, 0x71, 0xdd, 0xb4, 0x37, 0x1c, 0xfa, 0x60, 0xcb, 0x0f,
            0xce, 0x6a, 0x0e, 0x90, 0xaf, 0x14, 0x30, 0xf2, 0x5b, 0x21, 0x6f, 0x85, 0xd3, 0x1b,
            0x89, 0xc9, 0xba, 0x3f, 0x07, 0x11, 0xbd, 0x56, 0xda, 0xdc, 0x88, 0xb4, 0xb0, 0x57,
            0x0b, 0x0c, 0x44, 0xd9, 0xb9, 0xd2, 0x38, 0x4c, 0xb6, 0xff, 0x83, 0xfe, 0xc8, 0x65,
            0xbc, 0x2a, 0x10, 0xed, 0x18, 0x62, 0xd2, 0x1b, 0x87,
        ];
        let cmd_frag_data_len_2 = cmd_frag_data_2.len();

        mock_hal.expect_send_uci_message(
            cmd_frag_data_1.to_vec(),
            Ok(cmd_frag_data_len_1.try_into().unwrap()),
        );
        mock_hal.expect_send_uci_message(
            cmd_frag_data_2.to_vec(),
            Ok(cmd_frag_data_len_2.try_into().unwrap()),
        );
        let adaptation_impl = UwbAdaptationImpl::new_with_args(
            rsp_sender,
            binder::Strong::new(Box::new(mock_hal)),
            Arc::new(Mutex::new(DeathRecipient::new(|| {}))),
        )
        .await
        .unwrap();
        adaptation_impl.send_uci_message(cmd).await.unwrap();
    }
}