Skip to main content

android_auto/
lib.rs

1//! This crate provides android auto functionality for devices wishing to comunicate using the android auto protocol.
2
3#![deny(missing_docs)]
4#![deny(clippy::missing_docs_in_private_items)]
5
6use std::{
7    collections::HashSet,
8    io::{Cursor, Read, Write},
9    sync::Arc,
10};
11
12mod cert;
13
14#[cfg(not(any(feature = "wireless", feature = "usb")))]
15compile_error!("One of wireless or usb features must be enabled, both is also ok");
16
17use ::protobuf::Message;
18use Wifi::ChannelDescriptor;
19#[cfg(feature = "wireless")]
20use bluetooth_rust::{
21    BluetoothRfcommConnectableTrait, BluetoothRfcommProfileTrait, BluetoothStream,
22};
23use futures::StreamExt;
24use rustls::pki_types::{CertificateDer, pem::PemObject};
25use tokio::{
26    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
27    sync::RwLockReadGuard,
28};
29
30mod avinput;
31use avinput::*;
32mod bluetooth;
33use bluetooth::*;
34mod common;
35use common::*;
36mod control;
37use control::*;
38mod input;
39use input::*;
40mod mediaaudio;
41use mediaaudio::*;
42mod mediastatus;
43use mediastatus::*;
44mod navigation;
45use navigation::*;
46mod sensor;
47use sensor::*;
48mod speechaudio;
49use speechaudio::*;
50mod sysaudio;
51use sysaudio::*;
52mod video;
53use video::*;
54
55#[cfg(feature = "usb")]
56mod usb;
57
58pub use protobuf;
59
60/// Used to implement a future that never returns
61pub struct Never<T>(std::marker::PhantomData<T>);
62
63impl<T> Never<T> {
64    /// Construct a new Self
65    pub fn new() -> Self {
66        Never(std::marker::PhantomData)
67    }
68}
69
70impl<T> std::future::Future for Never<T> {
71    type Output = T;
72
73    fn poll(
74        self: std::pin::Pin<&mut Self>,
75        _cx: &mut std::task::Context<'_>,
76    ) -> std::task::Poll<Self::Output> {
77        std::task::Poll::Pending
78    }
79}
80
81/// Errors that can occur when trying to receive frames
82#[derive(Debug)]
83pub enum FrameReceiptError {
84    /// A timeout occurred when trying to receive the frame header
85    TimeoutHeader,
86    /// The connection was disconnected
87    Disconnected,
88    /// An unexpected error receiving the frame channel id
89    UnexpectedDuringFrameChannel(std::io::Error),
90    /// An unexpected error receiving the frame header
91    UnexpectedDuringFrameHeader(std::io::Error),
92    /// An unexpected error receiving the frame length
93    UnexpectedDuringFrameLength(std::io::Error),
94    /// An unexpected error receiving the frame contents
95    UnexpectedDuringFrameContents(std::io::Error),
96    /// An error occurred calling read_tls with the received frame payload
97    TlsReadError(std::io::Error),
98    /// An error occurred processing tls data received
99    TlsProcessingError(rustls::Error),
100}
101
102/// An error that can occur when transmitting a frame
103#[derive(Debug)]
104pub enum FrameTransmissionError {
105    /// A timeout occurred while transmitting
106    Timeout,
107    /// The connection was disconnected
108    Disconnected,
109    /// An unexpected error
110    Unexpected(std::io::Error),
111}
112
113/// A sequence error in frames received
114#[derive(Debug)]
115pub enum FrameSequenceError {
116    /// Video data was received with the video channel not being open
117    VideoChannelNotOpen,
118}
119
120/// Errors that can occur when either sending or receiving frames
121#[derive(Debug)]
122pub enum FrameIoError {
123    /// An error receiving a frame
124    Rx(FrameReceiptError),
125    /// An error sending a frame
126    Tx(FrameTransmissionError),
127    /// A shutdown was requested
128    ShutdownRequested,
129    /// The client has an incompatible version
130    IncompatibleVersion(u16, u16),
131    /// An error occurred during the ssl handshake
132    SslHandshake(SslHandshakeError),
133    /// A logical error due to frames not being received in the expected order
134    Sequence(FrameSequenceError),
135    /// An error occurred opening the audio input channel
136    AudioInputOpenError,
137    /// An error occurred closing the audio input channel
138    AudioInputCloseError,
139}
140
141/// Errors that can occur during the handshake process
142#[derive(Debug)]
143pub enum SslHandshakeError {
144    /// A timeout occurred
145    Timeout,
146    /// The connection was disconnected
147    Disconnected,
148    /// An unexpected error
149    Unexpected(std::io::Error),
150}
151
152/// Errors that can occur during communication with a client
153#[derive(Debug)]
154pub enum ClientError {
155    /// The root certificate for the ssl communications was invalid
156    InvalidRootCert,
157    /// The client certificate was invalid
158    InvalidClientCertificate,
159    /// The client private key was invalid
160    InvalidClientPrivateKey,
161    /// A communication error
162    IoError(FrameIoError),
163}
164
165impl From<FrameTransmissionError> for FrameIoError {
166    fn from(value: FrameTransmissionError) -> Self {
167        Self::Tx(value)
168    }
169}
170
171impl From<SslHandshakeError> for FrameIoError {
172    fn from(value: SslHandshakeError) -> Self {
173        FrameIoError::SslHandshake(value)
174    }
175}
176
177impl From<FrameSequenceError> for FrameIoError {
178    fn from(value: FrameSequenceError) -> Self {
179        FrameIoError::Sequence(value)
180    }
181}
182
183impl From<FrameIoError> for ClientError {
184    fn from(value: FrameIoError) -> Self {
185        ClientError::IoError(value)
186    }
187}
188
189/// The list of channel handlers for the current android auto instance
190static CHANNEL_HANDLERS: tokio::sync::RwLock<Vec<ChannelHandler>> =
191    tokio::sync::RwLock::const_new(Vec::new());
192
193/// The types of connections that can exist, exists to make it possible for the usb and wireless features to work with tokio::select macro
194pub enum ConnectionType {
195    /// The variant for usb connections
196    #[cfg(feature = "usb")]
197    Usb(usb::AndroidAutoUsb),
198    /// The variant for wireless connections
199    #[cfg(feature = "wireless")]
200    Wireless(tokio::net::TcpStream),
201}
202
203impl ConnectionType {
204    /// Run the connection
205    async fn run<T: AndroidAutoMainTrait + ?Sized>(
206        self,
207        config: AndroidAutoConfiguration,
208        main: &Box<T>,
209    ) {
210        match self {
211            #[cfg(feature = "usb")]
212            ConnectionType::Usb(a) => {
213                let stream = a.into_split();
214                let _ = handle_client_generic(stream.0, stream.1, config, main).await;
215            }
216            #[cfg(feature = "wireless")]
217            ConnectionType::Wireless(w) => {
218                let stream = w.into_split();
219                let a = handle_client_generic(stream.0, stream.1, config, main).await;
220                log::error!("The error for wifi is {:?}", a);
221            }
222        }
223    }
224}
225
226/// The base trait for crate users to implement
227#[async_trait::async_trait]
228pub trait AndroidAutoMainTrait:
229    AndroidAutoSensorTrait
230    + AndroidAutoAudioOutputTrait
231    + AndroidAutoInputChannelTrait
232    + AndroidAutoAudioInputTrait
233    + AndroidAutoVideoChannelTrait
234    + Send
235    + Sync
236{
237    /// Implement this to indicate that bluetooth hardware is possible, return None if bluetooth hardware is not present
238    #[inline(always)]
239    fn supports_bluetooth(&self) -> Option<&dyn AndroidAutoBluetoothTrait> {
240        None
241    }
242
243    #[cfg(feature = "wireless")]
244    /// Implement this to support wireless android auto communications
245    #[inline(always)]
246    fn supports_wireless(&self) -> Option<Arc<dyn AndroidAutoWirelessTrait>> {
247        None
248    }
249
250    /// Implement this to support wired android auto communications
251    #[inline(always)]
252    fn supports_wired(&self) -> Option<Arc<dyn AndroidAutoWiredTrait>> {
253        None
254    }
255
256    /// Implement this to support navigation
257    fn supports_navigation(&self) -> Option<&dyn AndroidAutoNavigationTrait> {
258        None
259    }
260
261    /// A method of receiving the ping times for the head unit
262    async fn ping_time_microseconds(&self, _micros: i64) {}
263
264    /// The android auto device just connected
265    async fn connect(&self);
266
267    /// The android auto device disconnected
268    async fn disconnect(&self);
269
270    /// Retrieve the receiver so that the user can send messages to the android auto compatible device or crate
271    async fn get_receiver(&self)
272    -> Option<tokio::sync::mpsc::Receiver<SendableAndroidAutoMessage>>;
273
274    #[cfg(feature = "usb")]
275    /// Run a single usb device for android auto
276    async fn do_usb_iteration(
277        &self,
278        d: nusb::DeviceInfo,
279        config: &AndroidAutoConfiguration,
280        setup: &AndroidAutoSetup,
281    ) -> Result<ConnectionType, ()> {
282        let main = self;
283        match d.open().await {
284            Ok(d) => {
285                let aoa = usb::get_aoa_protocol(&d).await;
286                log::info!("AOA is {:?}", aoa);
287                usb::identify_accessory(&d).await;
288                usb::accessory_start(&d).await;
289            }
290            Err(e) => {
291                log::error!("Failed to open android device {e}");
292                return Err(());
293            }
294        }
295        match tokio::time::timeout(
296            std::time::Duration::from_millis(2000),
297            usb::wait_for_accessory(),
298        )
299        .await
300        {
301            Ok(Ok(newdev)) => {
302                let _ = newdev.reset().await;
303            }
304            Ok(Err(e)) => {
305                log::error!("Failed to get accessory {e}");
306                return Err(());
307            }
308            Err(_e) => {
309                log::error!("Timeout get accessory");
310                return Err(());
311            }
312        }
313        match tokio::time::timeout(
314            std::time::Duration::from_millis(2000),
315            usb::wait_for_accessory(),
316        )
317        .await
318        {
319            Ok(Ok(newdev)) => {
320                log::info!("AOA DEV IS {:?}", newdev);
321                let aoa = usb::claim_aoa_interface(&newdev).await;
322                let aauto = usb::AndroidAutoUsb::new(aoa);
323                if let Some(aauto) = aauto {
324                    log::info!("got aoa interface?");
325                    return Ok(ConnectionType::Usb(aauto));
326                } else {
327                    Err(())
328                }
329            }
330            Ok(Err(e)) => {
331                log::error!("Failed to get accessory 2 {e}");
332                Err(())
333            }
334            Err(_e) => {
335                log::error!("Timeout get accessory 2");
336                return Err(());
337            }
338        }
339    }
340
341    /// Does a usb run
342    async fn usb_run(
343        &self,
344        config: &AndroidAutoConfiguration,
345        setup: &AndroidAutoSetup,
346    ) -> (ConnectionType, AsyncFn, AsyncFn) {
347        #[cfg(feature = "usb")]
348        {
349            if self.supports_wired().is_some() {
350                if let Ok(mut watcher) = nusb::watch_devices() {
351                    use futures::StreamExt;
352                    log::info!("Looking for usb devices");
353                    let looper = async |watcher: &mut nusb::hotplug::HotplugWatch| {
354                        loop {
355                            if let Some(dev) = watcher.next().await {
356                                use nusb::hotplug::HotplugEvent;
357                                if let HotplugEvent::Connected(di) = dev {
358                                    if usb::is_android_device(&di) {
359                                        log::info!("Hotplug device {:?}", di);
360                                        tokio::time::sleep(std::time::Duration::from_millis(500))
361                                            .await;
362                                        break di;
363                                    }
364                                }
365                            }
366                        }
367                    };
368                    if let Ok(devs) = nusb::list_devices().await {
369                        let mut start_device = None;
370                        for dev in devs {
371                            if usb::is_android_device(&dev) {
372                                start_device = Some(dev);
373                            }
374                        }
375                        let d = if let Some(d) = start_device {
376                            log::info!("Startup device {:?}", d);
377                            d
378                        } else {
379                            looper(&mut watcher).await
380                        };
381                        let a = self.do_usb_iteration(d.clone(), config, setup).await;
382                        if let Ok(a) = a {
383                            let disconnect = make_disconnect_watcher(d);
384                            let kill: AsyncFn = Box::new(move || Box::pin(async move {}));
385                            return (a, disconnect, kill);
386                        }
387                        loop {
388                            let b = looper(&mut watcher).await;
389                            let a = self.do_usb_iteration(b.clone(), config, setup).await;
390                            if let Ok(a) = a {
391                                let disconnect = make_disconnect_watcher(b);
392                                let kill: AsyncFn = Box::new(move || Box::pin(async move {}));
393                                return (a, disconnect, kill);
394                            }
395                        }
396                    } else {
397                        Never::new().await
398                    }
399                } else {
400                    Never::new().await
401                }
402            } else {
403                Never::new().await
404            }
405        }
406        #[cfg(not(feature = "usb"))]
407        {
408            Never::new().await
409        }
410    }
411
412    /// does a wifi run
413    async fn wifi_run(
414        &self,
415        config: &AndroidAutoConfiguration,
416        setup: &AndroidAutoSetup,
417    ) -> (ConnectionType, AsyncFn, AsyncFn) {
418        #[cfg(feature = "wireless")]
419        {
420            if let Some(wireless) = self.supports_wireless() {
421                let psettings = bluetooth_rust::BluetoothRfcommProfileSettings {
422                    uuid: bluetooth_rust::BluetoothUuid::AndroidAuto
423                        .as_str()
424                        .to_string(),
425                    name: Some("Android Auto Bluetooth Service".to_string()),
426                    service_uuid: Some(
427                        bluetooth_rust::BluetoothUuid::AndroidAuto
428                            .as_str()
429                            .to_string(),
430                    ),
431                    channel: Some(22),
432                    psm: None,
433                    authenticate: Some(true),
434                    authorize: Some(true),
435                    auto_connect: Some(true),
436                    sdp_record: None,
437                    sdp_version: None,
438                    sdp_features: None,
439                };
440
441                if let Ok(profile) = wireless.setup_bluetooth_profile(&psettings).await {
442                    log::info!("Setup bluetooth profile is ok?");
443                    let wireless2 = wireless.clone();
444                    let kill = tokio::sync::oneshot::channel::<()>();
445                    tokio::spawn(async move {
446                        tokio::select! {
447                            e = bluetooth_service(profile, wireless2) => {
448                                log::error!("Android auto bluetooth service stopped: {:?}", e);
449                                e
450                            }
451                            _ = kill.1 => {
452                                log::error!("Kill bluetooth service");
453                                Ok(())
454                            }
455                        }
456                    });
457                    loop {
458                        let e = wifi_service(wireless.clone()).await;
459                        if let Ok(e) = e {
460                            let disconnect: AsyncFn =
461                                Box::new(move || Box::pin(async move { Never::new().await }));
462                            let kill2: AsyncFn = Box::new(move || {
463                                Box::pin(async move {
464                                    kill.0.send(());
465                                })
466                            });
467                            return (e, disconnect, kill2);
468                        }
469                    }
470                } else {
471                    Never::new().await
472                }
473            } else {
474                Never::new().await
475            }
476        }
477        #[cfg(not(feature = "wireless"))]
478        {
479            Never::new().await
480        }
481    }
482
483    /// Runs the android auto server
484    async fn run(
485        self: Box<Self>,
486        config: AndroidAutoConfiguration,
487        js: &mut tokio::task::JoinSet<Result<(), String>>,
488        setup: &AndroidAutoSetup,
489    ) -> Result<(), String> {
490        log::info!("Running android auto server");
491
492        let (d, abort, kill) = tokio::select! {
493            a = self.usb_run(&config, setup) => {
494                log::error!("usb config finished");
495                a
496            }
497            b = self.wifi_run(&config, setup) => {
498                log::error!("wifi config finished");
499                b
500            }
501        };
502
503        self.connect().await;
504        tokio::select! {
505            a = d.run(config, &self) => {
506                log::error!("Android auto finished {:?}", a);
507            }
508            b = abort() => {
509                log::error!("Android auto aborted {:?}", b);
510            }
511        }
512        kill().await;
513        self.disconnect().await;
514
515        Ok(())
516    }
517}
518
519/// this trait is implemented by users that support wired (usb) android auto
520#[async_trait::async_trait]
521pub trait AndroidAutoWiredTrait: AndroidAutoMainTrait {}
522
523/// this trait is implemented by users that support bluetooth and wifi (both are required for wireless android auto)
524#[cfg(feature = "wireless")]
525#[async_trait::async_trait]
526pub trait AndroidAutoWirelessTrait: AndroidAutoMainTrait {
527    /// The function to setup the android auto profile
528    async fn setup_bluetooth_profile(
529        &self,
530        suggestions: &bluetooth_rust::BluetoothRfcommProfileSettings,
531    ) -> Result<bluetooth_rust::BluetoothRfcommProfile, String>;
532
533    /// Returns wifi details
534    fn get_wifi_details(&self) -> NetworkInformation;
535}
536
537/// This trait is implemented by users that support navigation indicators
538#[async_trait::async_trait]
539pub trait AndroidAutoSensorTrait {
540    /// Returns the types of sensors supported
541    fn get_supported_sensors(&self) -> &SensorInformation;
542    /// Start the indicated sensor
543    async fn start_sensor(&self, stype: Wifi::sensor_type::Enum) -> Result<(), ()>;
544}
545
546/// This trait is implemented by users that support navigation indicators
547#[async_trait::async_trait]
548pub trait AndroidAutoNavigationTrait: AndroidAutoMainTrait {
549    /// A turn indication update
550    async fn turn_indication(&self, m: Wifi::NavigationTurnEvent);
551    /// A distance indication update
552    async fn distance_indication(&self, m: Wifi::NavigationDistanceEvent);
553    /// A status update
554    async fn nagivation_status(&self, m: Wifi::NavigationStatus);
555}
556
557/// This trait is implemented by users wishing to display a video stream from an android auto (phone probably).
558#[async_trait::async_trait]
559pub trait AndroidAutoVideoChannelTrait {
560    /// Parse a chunk of h264 video data
561    async fn receive_video(&self, data: Vec<u8>, timestamp: Option<u64>);
562    /// Setup the video device to receive h264 video, if anything is required. Return Ok(()) if setup was good, Err(()) if it was not good
563    async fn setup_video(&self) -> Result<(), ()>;
564    /// Tear down the video receiver, may be called without the setup having been called
565    async fn teardown_video(&self);
566    /// Wait for the video to be in focus
567    async fn wait_for_focus(&self);
568    /// Set the focus of the video stream to be as requested
569    async fn set_focus(&self, focus: bool);
570    /// Retrieve the video configuration for the channel
571    fn retrieve_video_configuration(&self) -> &VideoConfiguration;
572}
573
574/// The types of audio channels that can exist
575#[derive(Debug, serde::Serialize, serde::Deserialize)]
576pub enum AudioChannelType {
577    /// Media audio
578    Media,
579    /// System audio
580    System,
581    /// Speech audio
582    Speech,
583}
584
585/// This trait is implemented by users that have audio output capabilities
586#[async_trait::async_trait]
587pub trait AndroidAutoAudioOutputTrait {
588    /// Opens the specified channel
589    async fn open_output_channel(&self, t: AudioChannelType) -> Result<(), ()>;
590    /// Closes the specified channel
591    async fn close_output_channel(&self, t: AudioChannelType) -> Result<(), ()>;
592    /// Receive a chunk of audio data for the specified channel
593    async fn receive_output_audio(&self, t: AudioChannelType, data: Vec<u8>);
594    /// The specified audio channel will start
595    async fn start_output_audio(&self, t: AudioChannelType);
596    /// The specified audio channel will stop
597    async fn stop_output_audio(&self, t: AudioChannelType);
598}
599
600/// This trait is implemented by users that have audio input capabilities
601#[async_trait::async_trait]
602pub trait AndroidAutoAudioInputTrait {
603    /// Opens the channel
604    async fn open_input_channel(&self) -> Result<(), ()>;
605    /// Closes the channel
606    async fn close_input_channel(&self) -> Result<(), ()>;
607    /// The audio channel will start
608    async fn start_input_audio(&self);
609    /// The audio channel will stop
610    async fn stop_input_audio(&self);
611    /// The ack for the audio data
612    async fn audio_input_ack(&self, chan: u8, ack: AVMediaAckIndication);
613}
614
615/// The configuration for an input channel
616#[derive(Clone)]
617pub struct InputConfiguration {
618    /// The supported keycodes
619    pub keycodes: Vec<u32>,
620    /// The touchscreen width and height
621    pub touchscreen: Option<(u16, u16)>,
622}
623
624/// This trait is implemented by users that have inputs for their head unit
625#[async_trait::async_trait]
626pub trait AndroidAutoInputChannelTrait {
627    /// A binding request for the specified keycode, generally the same code reported in `AndroidAutoConfig::keycodes_supported`
628    async fn binding_request(&self, code: u32) -> Result<(), ()>;
629    /// Retrieve the input configuration
630    fn retrieve_input_configuration(&self) -> &InputConfiguration;
631}
632
633/// A trait that is implemented for users that somehow support bluetooth for their hardware
634#[async_trait::async_trait]
635pub trait AndroidAutoBluetoothTrait: AndroidAutoMainTrait {
636    /// Do something
637    async fn do_stuff(&self);
638    /// Get the configuration
639    fn get_config(&self) -> &BluetoothInformation;
640}
641
642#[allow(missing_docs)]
643#[allow(clippy::missing_docs_in_private_items)]
644mod protobufmod {
645    include!(concat!(env!("OUT_DIR"), "/protobuf/mod.rs"));
646}
647pub use protobufmod::*;
648
649/// The android auto version supported
650const VERSION: (u16, u16) = (1, 1);
651
652/// The types of messages that can be sent over the android auto link
653pub enum AndroidAutoMessage {
654    /// An input message
655    Input(Wifi::InputEventIndication),
656    /// An audio packet message, optional timestamp (microseconds since UNIX_EPOCH) and data
657    Audio(Option<u64>, Vec<u8>),
658    /// A sensor event message
659    Sensor(Wifi::SensorEventIndication),
660    /// An other message
661    Other,
662}
663
664/// The type of channel being sent in a sendable message
665#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
666pub enum SendableChannelType {
667    /// The input channel
668    Input,
669    /// The audio input channel
670    AudioInput,
671    /// The sensor channel
672    Sensor,
673    /// Other channel type
674    Other,
675}
676
677/// The sendable form of an `AndroidAutoMessage`
678#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
679pub struct SendableAndroidAutoMessage {
680    /// The channel id to send the message to
681    channel: SendableChannelType,
682    /// The message body to send
683    data: Vec<u8>,
684}
685
686impl SendableAndroidAutoMessage {
687    /// Convert Self into an `AndroidAutoFrame``
688    async fn into_frame(self) -> AndroidAutoFrame {
689        let mut chan = None;
690        let chans = CHANNEL_HANDLERS.read().await;
691        for (i, c) in chans.iter().enumerate() {
692            match self.channel {
693                SendableChannelType::Sensor => {
694                    if let ChannelHandler::Sensor(_) = c {
695                        chan = Some(i as u8);
696                        break;
697                    }
698                }
699                SendableChannelType::AudioInput => {
700                    if let ChannelHandler::AvInput(_) = c {
701                        chan = Some(i as u8);
702                        break;
703                    }
704                }
705                SendableChannelType::Input => {
706                    if let ChannelHandler::Input(_) = c {
707                        chan = Some(i as u8);
708                        break;
709                    }
710                }
711                SendableChannelType::Other => {
712                    todo!();
713                }
714            }
715        }
716        AndroidAutoFrame {
717            header: FrameHeader {
718                channel_id: chan.unwrap(),
719                frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
720            },
721            data: self.data,
722        }
723    }
724}
725
726/// A message sent from an app user to this crate
727#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
728pub enum AndroidAutoChannelMessageFromApp {
729    /// A message that needs to be forwarded to the android auto device
730    MessageToPhone(SendableAndroidAutoMessage),
731}
732
733impl AndroidAutoMessage {
734    /// Convert the message to something that can be sent, if possible
735    pub fn sendable(self) -> SendableAndroidAutoMessage {
736        match self {
737            Self::Sensor(m) => {
738                let mut data = m.write_to_bytes().unwrap();
739                let t = Wifi::sensor_channel_message::Enum::SENSOR_EVENT_INDICATION as u16;
740                let t = t.to_be_bytes();
741                let mut m = Vec::new();
742                m.push(t[0]);
743                m.push(t[1]);
744                m.append(&mut data);
745                SendableAndroidAutoMessage {
746                    channel: SendableChannelType::Sensor,
747                    data: m,
748                }
749            }
750            Self::Input(m) => {
751                let mut data = m.write_to_bytes().unwrap();
752                let t = Wifi::input_channel_message::Enum::INPUT_EVENT_INDICATION as u16;
753                let t = t.to_be_bytes();
754                let mut m = Vec::new();
755                m.push(t[0]);
756                m.push(t[1]);
757                m.append(&mut data);
758                SendableAndroidAutoMessage {
759                    channel: SendableChannelType::Input,
760                    data: m,
761                }
762            }
763            Self::Audio(_timestamp, mut data) => {
764                let t = Wifi::avchannel_message::Enum::AV_MEDIA_WITH_TIMESTAMP_INDICATION as u16;
765                let t = t.to_be_bytes();
766                let mut m = Vec::new();
767                m.push(t[0]);
768                m.push(t[1]);
769                m.append(&mut data);
770                SendableAndroidAutoMessage {
771                    channel: SendableChannelType::AudioInput,
772                    data: m,
773                }
774            }
775            Self::Other => todo!(),
776        }
777    }
778}
779
780/// A message sent or received in the android auto protocol
781#[cfg(feature = "wireless")]
782struct AndroidAutoRawBluetoothMessage {
783    /// The message type
784    t: u16,
785    /// The message contained in the message
786    message: Vec<u8>,
787}
788
789/// The sensor information supported by the user for android auto
790#[derive(Clone)]
791pub struct SensorInformation {
792    /// The sensor types supported
793    pub sensors: HashSet<Wifi::sensor_type::Enum>,
794}
795
796/// The wireless network information to relay to the compatible android auto device
797#[derive(Clone, Debug)]
798pub struct NetworkInformation {
799    /// The ssid of the wireless network
800    pub ssid: String,
801    /// The password for the wireless network
802    pub psk: String,
803    /// Unsure, probably the mac address of the android auto host
804    pub mac_addr: String,
805    /// The ip address of the android auto host
806    pub ip: String,
807    /// The port that the android auto host should listen on
808    pub port: u16,
809    /// The security mode for the wireless network
810    pub security_mode: Bluetooth::SecurityMode,
811    /// The access point type of the wireless network
812    pub ap_type: Bluetooth::AccessPointType,
813}
814
815/// Information about the head unit that will be providing android auto services for compatible devices
816#[derive(Clone)]
817pub struct HeadUnitInfo {
818    /// The name of the head unit
819    pub name: String,
820    /// The model of the vehicle
821    pub car_model: String,
822    /// The year of the vehicle
823    pub car_year: String,
824    /// The serial number of the vehicle
825    pub car_serial: String,
826    /// True when the vehicle is a left hand drive, false when a right hand drive
827    pub left_hand: bool,
828    /// The manufacturer of the head unit
829    pub head_manufacturer: String,
830    /// The model of the head unit
831    pub head_model: String,
832    /// The software build for the head unit
833    pub sw_build: String,
834    /// The software version for the head unit
835    pub sw_version: String,
836    /// Does the head unit support native media during vr
837    pub native_media: bool,
838    /// Should the clock be hidden?
839    pub hide_clock: Option<bool>,
840}
841
842/// The required bluetooth information
843#[derive(Clone)]
844pub struct BluetoothInformation {
845    /// The mac address of the bluetooth adapter
846    pub address: String,
847}
848
849/// The configuration data for the video stream of android auto
850#[derive(Clone)]
851pub struct VideoConfiguration {
852    /// Defines the desired resolution for the video stream
853    pub resolution: Wifi::video_resolution::Enum,
854    /// The fps for the video stream
855    pub fps: Wifi::video_fps::Enum,
856    /// The dots per inch of the display
857    pub dpi: u16,
858}
859
860/// Provides basic configuration elements for setting up an android auto head unit
861#[derive(Clone)]
862pub struct AndroidAutoConfiguration {
863    /// The head unit information
864    pub unit: HeadUnitInfo,
865    /// The android auto client certificate and private key in pem format (only if a custom one is desired)
866    pub custom_certificate: Option<(Vec<u8>, Vec<u8>)>,
867}
868
869/// The channel identifier for channels in the android auto protocol
870type ChannelId = u8;
871
872/// Specifies the type of frame header, whether the data of a packet is contained in a single frame, or if it was too large and broken up into multiple frames for transmission.
873#[derive(Debug, PartialEq)]
874#[repr(u8)]
875pub enum FrameHeaderType {
876    /// This frame is neither the first or the last of a multi-frame packet
877    Middle = 0,
878    /// This is the first frame of a multi-frame packet
879    First = 1,
880    /// This is the last frame of a multi-frame packet
881    Last = 2,
882    /// The packet is contained in a single frame
883    Single = 3,
884}
885
886impl From<u8> for FrameHeaderType {
887    fn from(value: u8) -> Self {
888        match value & 3 {
889            0 => FrameHeaderType::Middle,
890            1 => FrameHeaderType::First,
891            2 => FrameHeaderType::Last,
892            _ => FrameHeaderType::Single,
893        }
894    }
895}
896
897impl From<FrameHeaderType> for u8 {
898    fn from(value: FrameHeaderType) -> Self {
899        value as u8
900    }
901}
902
903#[allow(missing_docs)]
904/// The frame header module, because bitfield new does not make documentation yet.
905mod frame_header {
906    bitfield::bitfield! {
907        #[derive(Copy, Clone)]
908        pub struct FrameHeaderContents(u8);
909        impl Debug;
910        impl new;
911        u8;
912        /// True indicates the frame is encrypted
913        pub get_encryption, set_encryption: 3;
914        /// The frame header type
915        pub from into super::FrameHeaderType, get_frame_type, set_frame_type: 1, 0;
916        /// True when frame is for control, false when specific
917        pub get_control, set_control: 2;
918    }
919}
920use frame_header::FrameHeaderContents;
921
922#[cfg(feature = "wireless")]
923use crate::Bluetooth::Status;
924use crate::protobufmod::Wifi::AVMediaAckIndication;
925
926/// Represents the header of a frame sent to the android auto client
927#[derive(Copy, Clone, Debug)]
928struct FrameHeader {
929    /// The channelid that this frame is intended for
930    channel_id: ChannelId,
931    /// The contents of the frame header
932    frame: FrameHeaderContents,
933}
934
935impl FrameHeader {
936    /// Add self to the given buffer to build part of a complete frame
937    pub fn add_to(&self, buf: &mut Vec<u8>) {
938        buf.push(self.channel_id);
939        buf.push(self.frame.0);
940    }
941}
942
943/// Responsible for receiving frame headers in the the android auto protocol.
944struct FrameHeaderReceiver {
945    /// The channel id received for a frame header, if one has been received.
946    channel_id: Option<ChannelId>,
947}
948
949impl FrameHeaderReceiver {
950    /// Construct a new self
951    pub fn new() -> Self {
952        Self { channel_id: None }
953    }
954
955    /// Read a frame header from the compatible android auto device
956    /// Returns Ok(Some(p)) when a full frame header is actually received.
957    pub async fn read<T: AsyncRead + Unpin>(
958        &mut self,
959        stream: &mut T,
960    ) -> Result<Option<FrameHeader>, FrameReceiptError> {
961        if self.channel_id.is_none() {
962            let mut b = [0u8];
963            stream
964                .read_exact(&mut b)
965                .await
966                .map_err(|e| match e.kind() {
967                    std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
968                    std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
969                    _ => FrameReceiptError::UnexpectedDuringFrameChannel(e),
970                })?;
971            self.channel_id = ChannelId::try_from(b[0]).ok();
972        }
973        if let Some(channel_id) = &self.channel_id {
974            let mut b = [0u8];
975            stream
976                .read_exact(&mut b)
977                .await
978                .map_err(|e| match e.kind() {
979                    std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
980                    std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
981                    _ => FrameReceiptError::UnexpectedDuringFrameHeader(e),
982                })?;
983            let mut a = FrameHeaderContents::new(false, FrameHeaderType::Single, false);
984            a.0 = b[0];
985            let fh = FrameHeader {
986                channel_id: *channel_id,
987                frame: a,
988            };
989            return Ok(Some(fh));
990        }
991        Ok(None)
992    }
993}
994
995/// A frame of data for comunication in the android auto. When receiving frames, multi-frames are combined into a single frame.
996#[derive(Debug)]
997struct AndroidAutoFrame {
998    /// The header of the frame
999    header: FrameHeader,
1000    /// The data actually relayed in the frame
1001    data: Vec<u8>,
1002}
1003
1004impl AndroidAutoFrame {
1005    /// The largest payload for a single frame
1006    const MAX_FRAME_DATA_SIZE: usize = 0x4000;
1007    #[allow(dead_code)]
1008    /// Currently unused function for building a set of frames for a large packet
1009    fn build_multi_frame(f: FrameHeader, d: Vec<u8>) -> Vec<Self> {
1010        let mut m = Vec::new();
1011        if d.len() < Self::MAX_FRAME_DATA_SIZE {
1012            let fr = AndroidAutoFrame { header: f, data: d };
1013            m.push(fr);
1014        } else {
1015            let packets = d.chunks(Self::MAX_FRAME_DATA_SIZE);
1016            let max = packets.len();
1017            for (i, p) in packets.enumerate() {
1018                let first = i == 0;
1019                let last = i == (max - 1);
1020                let mut h = f;
1021                if first {
1022                    h.frame.set_frame_type(FrameHeaderType::First);
1023                } else if last {
1024                    h.frame.set_frame_type(FrameHeaderType::Last);
1025                } else {
1026                    h.frame.set_frame_type(FrameHeaderType::Middle);
1027                }
1028                let fr = AndroidAutoFrame {
1029                    header: h,
1030                    data: p.to_vec(),
1031                };
1032                m.push(fr);
1033            }
1034        }
1035        m
1036    }
1037
1038    /// Build a vec with the frame that is ready to send out over the connection to the compatible android auto device.
1039    /// If necessary, the data will be encrypted.
1040    async fn build_vec(&self, stream: Option<&mut rustls::client::ClientConnection>) -> Vec<u8> {
1041        let mut buf = Vec::new();
1042        self.header.add_to(&mut buf);
1043        if self.header.frame.get_encryption() {
1044            if let Some(stream) = stream {
1045                let mut data = Vec::new();
1046                stream.writer().write_all(&self.data).unwrap();
1047                stream.write_tls(&mut data).unwrap();
1048                let mut p = (data.len() as u16).to_be_bytes().to_vec();
1049                buf.append(&mut p);
1050                buf.append(&mut data);
1051            } else {
1052                panic!("No ssl object when encryption was required");
1053            }
1054        } else {
1055            let mut data = self.data.clone();
1056            let mut p = (data.len() as u16).to_be_bytes().to_vec();
1057            buf.append(&mut p);
1058            buf.append(&mut data);
1059        }
1060        buf
1061    }
1062}
1063
1064/// Responsible for receiving a full frame from the compatible android auto device
1065struct AndroidAutoFrameReceiver {
1066    /// The length of the frame to receive, if it is known yet
1067    len: Option<u16>,
1068    /// The data received so far for a multi-frame packet
1069    rx_sofar: Vec<Vec<u8>>,
1070}
1071
1072impl AndroidAutoFrameReceiver {
1073    /// Construct a new frame receiver
1074    fn new() -> Self {
1075        Self {
1076            len: None,
1077            rx_sofar: Vec::new(),
1078        }
1079    }
1080
1081    /// Read the contents of a frame using the details specified in the header that has already been read.
1082    async fn read<T: tokio::io::AsyncRead + Unpin>(
1083        &mut self,
1084        header: &FrameHeader,
1085        stream: &mut T,
1086        ssl_stream: &mut rustls::client::ClientConnection,
1087    ) -> Result<Option<AndroidAutoFrame>, FrameReceiptError> {
1088        if self.len.is_none() {
1089            if header.frame.get_frame_type() == FrameHeaderType::First {
1090                let mut p = [0u8; 6];
1091                stream
1092                    .read_exact(&mut p)
1093                    .await
1094                    .map_err(|e| match e.kind() {
1095                        std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
1096                        std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
1097                        _ => FrameReceiptError::UnexpectedDuringFrameLength(e),
1098                    })?;
1099                let len = u16::from_be_bytes([p[0], p[1]]);
1100                self.len.replace(len);
1101            } else {
1102                let mut p = [0u8; 2];
1103                stream
1104                    .read_exact(&mut p)
1105                    .await
1106                    .map_err(|e| match e.kind() {
1107                        std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
1108                        std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
1109                        _ => FrameReceiptError::UnexpectedDuringFrameLength(e),
1110                    })?;
1111                let len = u16::from_be_bytes(p);
1112                self.len.replace(len);
1113            }
1114        }
1115
1116        let decrypt = |ssl_stream: &mut rustls::client::ClientConnection,
1117                       _len: u16,
1118                       data_frame: Vec<u8>|
1119         -> Result<Vec<u8>, FrameReceiptError> {
1120            let mut plain_data = vec![0u8; data_frame.len()];
1121            let mut cursor = Cursor::new(&data_frame);
1122            let mut index = 0;
1123            loop {
1124                let asdf = ssl_stream
1125                    .read_tls(&mut cursor)
1126                    .map_err(|e| FrameReceiptError::TlsReadError(e))?;
1127                let _ = ssl_stream
1128                    .process_new_packets()
1129                    .map_err(|e| FrameReceiptError::TlsProcessingError(e))?;
1130                if asdf == 0 {
1131                    break;
1132                }
1133                if let Ok(l) = ssl_stream.reader().read(&mut plain_data[index..]) {
1134                    index += l;
1135                }
1136            }
1137            Ok(plain_data[0..index].to_vec())
1138        };
1139
1140        if let Some(len) = self.len.take() {
1141            let mut data_frame = vec![0u8; len as usize];
1142            stream
1143                .read_exact(&mut data_frame)
1144                .await
1145                .map_err(|e| match e.kind() {
1146                    std::io::ErrorKind::TimedOut => FrameReceiptError::TimeoutHeader,
1147                    std::io::ErrorKind::UnexpectedEof => FrameReceiptError::Disconnected,
1148                    _ => FrameReceiptError::UnexpectedDuringFrameContents(e),
1149                })?;
1150            let data = if header.frame.get_frame_type() == FrameHeaderType::Single {
1151                let data_plain = if header.frame.get_encryption() {
1152                    decrypt(ssl_stream, len, data_frame)?
1153                } else {
1154                    data_frame
1155                };
1156                let d = data_plain.clone();
1157                Some(vec![d])
1158            } else {
1159                let data_plain = if header.frame.get_encryption() {
1160                    decrypt(ssl_stream, len, data_frame)?
1161                } else {
1162                    data_frame
1163                };
1164                self.rx_sofar.push(data_plain);
1165                if header.frame.get_frame_type() == FrameHeaderType::Last {
1166                    let d = self.rx_sofar.clone();
1167                    self.rx_sofar.clear();
1168                    Some(d)
1169                } else {
1170                    None
1171                }
1172            };
1173            if let Some(data) = data {
1174                let data: Vec<u8> = data.into_iter().flatten().collect();
1175                let f = AndroidAutoFrame {
1176                    header: *header,
1177                    data,
1178                };
1179                let f = Some(f);
1180                return Ok(f);
1181            }
1182        }
1183        Ok(None)
1184    }
1185}
1186
1187#[cfg(feature = "wireless")]
1188/// A message sent or received over the android auto bluetooth connection. Used for setting up wireless android auto.
1189enum AndroidAutoBluetoothMessage {
1190    /// A request for socket information
1191    SocketInfoRequest(Bluetooth::SocketInfoRequest),
1192    /// A message relaying network information to the other party
1193    NetworkInfoMessage(Bluetooth::NetworkInfo),
1194}
1195
1196#[cfg(feature = "wireless")]
1197impl AndroidAutoBluetoothMessage {
1198    /// Build an `AndroidAutoMessage` from self
1199    fn as_message(&self) -> AndroidAutoRawBluetoothMessage {
1200        use protobuf::Message;
1201        match self {
1202            AndroidAutoBluetoothMessage::SocketInfoRequest(m) => AndroidAutoRawBluetoothMessage {
1203                t: Bluetooth::MessageId::BLUETOOTH_SOCKET_INFO_REQUEST as u16,
1204                message: m.write_to_bytes().unwrap(),
1205            },
1206            AndroidAutoBluetoothMessage::NetworkInfoMessage(m) => AndroidAutoRawBluetoothMessage {
1207                t: Bluetooth::MessageId::BLUETOOTH_NETWORK_INFO_MESSAGE as u16,
1208                message: m.write_to_bytes().unwrap(),
1209            },
1210        }
1211    }
1212}
1213
1214#[cfg(feature = "wireless")]
1215impl From<AndroidAutoRawBluetoothMessage> for Vec<u8> {
1216    fn from(value: AndroidAutoRawBluetoothMessage) -> Self {
1217        let mut buf = Vec::new();
1218        let b = value.message.len() as u16;
1219        let a = b.to_be_bytes();
1220        buf.push(a[0]);
1221        buf.push(a[1]);
1222        let a = value.t.to_be_bytes();
1223        buf.push(a[0]);
1224        buf.push(a[1]);
1225        for b in value.message {
1226            buf.push(b);
1227        }
1228        buf
1229    }
1230}
1231
1232/// The trait that all channel handlers must implement for android auto channels.
1233#[enum_dispatch::enum_dispatch]
1234trait ChannelHandlerTrait {
1235    /// Process data received that is specific to this channel. Return an error for any packets that were not handled that should cause communication to stop.
1236    async fn receive_data<
1237        T: AndroidAutoMainTrait + ?Sized,
1238        U: tokio::io::AsyncRead + Unpin,
1239        V: tokio::io::AsyncWrite + Unpin,
1240    >(
1241        &self,
1242        msg: AndroidAutoFrame,
1243        stream: &StreamMux<U, V>,
1244        _config: &AndroidAutoConfiguration,
1245        _main: &T,
1246    ) -> Result<(), FrameIoError>;
1247
1248    /// Construct the channeldescriptor with the channel handler so it can be conveyed to the compatible android auto device
1249    fn build_channel<T: AndroidAutoMainTrait + ?Sized>(
1250        &self,
1251        config: &AndroidAutoConfiguration,
1252        chanid: ChannelId,
1253        main: &T,
1254    ) -> Option<ChannelDescriptor>;
1255
1256    /// Set the list of all channels for the current channel. Only used for the control channel. This is because the control channel must be created first.
1257    fn set_channels(&self, _chans: Vec<ChannelDescriptor>) {}
1258}
1259
1260/// A message sent for an av channel
1261#[derive(Debug)]
1262enum AvChannelMessage {
1263    /// A message to start setup of the av channel
1264    SetupRequest(ChannelId, Wifi::AVChannelSetupRequest),
1265    /// A message that responds to a setup request
1266    SetupResponse(ChannelId, Wifi::AVChannelSetupResponse),
1267    /// Message requesting the focus of the video channel to be set
1268    VideoFocusRequest(ChannelId, Wifi::VideoFocusRequest),
1269    /// Message requesting to open the channel
1270    AvChannelOpen(ChannelId, Wifi::AVInputOpenRequest),
1271    /// Message indication the focus status of the video stream on the head unit
1272    VideoIndicationResponse(ChannelId, Wifi::VideoFocusIndication),
1273    /// The stream is about to start
1274    StartIndication(ChannelId, Wifi::AVChannelStartIndication),
1275    /// The stream is about to stop
1276    StopIndication(ChannelId, Wifi::AVChannelStopIndication),
1277    /// A media indication message, optionally containing a timestamp
1278    MediaIndication(ChannelId, Option<u64>, Vec<u8>),
1279    /// An acknowledgement of receiving a media indication message
1280    MediaIndicationAck(ChannelId, Wifi::AVMediaAckIndication),
1281}
1282
1283impl From<AvChannelMessage> for AndroidAutoFrame {
1284    fn from(value: AvChannelMessage) -> Self {
1285        match value {
1286            AvChannelMessage::AvChannelOpen(_, _) => unimplemented!(),
1287            AvChannelMessage::MediaIndicationAck(chan, m) => {
1288                let mut data = m.write_to_bytes().unwrap();
1289                let t = Wifi::avchannel_message::Enum::AV_MEDIA_ACK_INDICATION as u16;
1290                let t = t.to_be_bytes();
1291                let mut m = Vec::new();
1292                m.push(t[0]);
1293                m.push(t[1]);
1294                m.append(&mut data);
1295                AndroidAutoFrame {
1296                    header: FrameHeader {
1297                        channel_id: chan,
1298                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1299                    },
1300                    data: m,
1301                }
1302            }
1303            AvChannelMessage::SetupRequest(_, _) => unimplemented!(),
1304            AvChannelMessage::SetupResponse(chan, m) => {
1305                let mut data = m.write_to_bytes().unwrap();
1306                let t = Wifi::avchannel_message::Enum::SETUP_RESPONSE as u16;
1307                let t = t.to_be_bytes();
1308                let mut m = Vec::new();
1309                m.push(t[0]);
1310                m.push(t[1]);
1311                m.append(&mut data);
1312                AndroidAutoFrame {
1313                    header: FrameHeader {
1314                        channel_id: chan,
1315                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1316                    },
1317                    data: m,
1318                }
1319            }
1320            AvChannelMessage::MediaIndication(chan, timestamp, mut data) => {
1321                let (t, mut data) = if let Some(ts) = timestamp {
1322                    let mut m = Vec::new();
1323                    let mut tsb = ts.to_be_bytes().to_vec();
1324                    m.append(&mut tsb);
1325                    m.append(&mut data);
1326                    (
1327                        Wifi::avchannel_message::Enum::AV_MEDIA_WITH_TIMESTAMP_INDICATION as u16,
1328                        m,
1329                    )
1330                } else {
1331                    let mut m = Vec::new();
1332                    m.append(&mut data);
1333                    (Wifi::avchannel_message::Enum::AV_MEDIA_INDICATION as u16, m)
1334                };
1335                let t = t.to_be_bytes();
1336                let mut m = Vec::new();
1337                m.push(t[0]);
1338                m.push(t[1]);
1339                m.append(&mut data);
1340                AndroidAutoFrame {
1341                    header: FrameHeader {
1342                        channel_id: chan,
1343                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1344                    },
1345                    data: m,
1346                }
1347            }
1348            AvChannelMessage::VideoFocusRequest(_chan, _m) => unimplemented!(),
1349            AvChannelMessage::VideoIndicationResponse(chan, m) => {
1350                let mut data = m.write_to_bytes().unwrap();
1351                let t = Wifi::avchannel_message::Enum::VIDEO_FOCUS_INDICATION as u16;
1352                let t = t.to_be_bytes();
1353                let mut m = Vec::new();
1354                m.push(t[0]);
1355                m.push(t[1]);
1356                m.append(&mut data);
1357                AndroidAutoFrame {
1358                    header: FrameHeader {
1359                        channel_id: chan,
1360                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
1361                    },
1362                    data: m,
1363                }
1364            }
1365            AvChannelMessage::StartIndication(_, _) => unimplemented!(),
1366            AvChannelMessage::StopIndication(_, _) => unimplemented!(),
1367        }
1368    }
1369}
1370
1371impl TryFrom<&AndroidAutoFrame> for AvChannelMessage {
1372    type Error = String;
1373    fn try_from(value: &AndroidAutoFrame) -> Result<Self, Self::Error> {
1374        use protobuf::Enum;
1375        let mut ty = [0u8; 2];
1376        ty.copy_from_slice(&value.data[0..2]);
1377        let ty = u16::from_be_bytes(ty);
1378        if let Some(sys) = Wifi::avchannel_message::Enum::from_i32(ty as i32) {
1379            match sys {
1380                Wifi::avchannel_message::Enum::AV_MEDIA_WITH_TIMESTAMP_INDICATION => {
1381                    let mut b = [0u8; 8];
1382                    b.copy_from_slice(&value.data[2..10]);
1383                    let ts: u64 = u64::from_be_bytes(b);
1384                    Ok(Self::MediaIndication(
1385                        value.header.channel_id,
1386                        Some(ts),
1387                        value.data[10..].to_vec(),
1388                    ))
1389                }
1390                Wifi::avchannel_message::Enum::AV_MEDIA_INDICATION => Ok(Self::MediaIndication(
1391                    value.header.channel_id,
1392                    None,
1393                    value.data[2..].to_vec(),
1394                )),
1395                Wifi::avchannel_message::Enum::SETUP_REQUEST => {
1396                    let m = Wifi::AVChannelSetupRequest::parse_from_bytes(&value.data[2..]);
1397                    match m {
1398                        Ok(m) => Ok(Self::SetupRequest(value.header.channel_id, m)),
1399                        Err(e) => Err(format!("Invalid channel setup request: {}", e)),
1400                    }
1401                }
1402                Wifi::avchannel_message::Enum::START_INDICATION => {
1403                    let m = Wifi::AVChannelStartIndication::parse_from_bytes(&value.data[2..]);
1404                    match m {
1405                        Ok(m) => Ok(Self::StartIndication(value.header.channel_id, m)),
1406                        Err(e) => Err(format!("Invalid channel start request: {}", e)),
1407                    }
1408                }
1409                Wifi::avchannel_message::Enum::STOP_INDICATION => {
1410                    let m = Wifi::AVChannelStopIndication::parse_from_bytes(&value.data[2..]);
1411                    match m {
1412                        Ok(m) => Ok(Self::StopIndication(value.header.channel_id, m)),
1413                        Err(e) => Err(format!("Invalid channel stop request: {}", e)),
1414                    }
1415                }
1416                Wifi::avchannel_message::Enum::SETUP_RESPONSE => unimplemented!(),
1417                Wifi::avchannel_message::Enum::AV_MEDIA_ACK_INDICATION => {
1418                    let m = Wifi::AVMediaAckIndication::parse_from_bytes(&value.data[2..]);
1419                    match m {
1420                        Ok(m) => Ok(Self::MediaIndicationAck(value.header.channel_id, m)),
1421                        Err(e) => Err(format!("Invalid channel stop request: {}", e)),
1422                    }
1423                }
1424                Wifi::avchannel_message::Enum::AV_INPUT_OPEN_REQUEST => {
1425                    let m = Wifi::AVInputOpenRequest::parse_from_bytes(&value.data[2..]);
1426                    match m {
1427                        Ok(m) => Ok(Self::AvChannelOpen(value.header.channel_id, m)),
1428                        Err(e) => Err(format!("Invalid request: {}", e)),
1429                    }
1430                }
1431                Wifi::avchannel_message::Enum::AV_INPUT_OPEN_RESPONSE => todo!(),
1432                Wifi::avchannel_message::Enum::VIDEO_FOCUS_REQUEST => {
1433                    let m = Wifi::VideoFocusRequest::parse_from_bytes(&value.data[2..]);
1434                    match m {
1435                        Ok(m) => Ok(Self::VideoFocusRequest(value.header.channel_id, m)),
1436                        Err(e) => Err(format!("Invalid request: {}", e)),
1437                    }
1438                }
1439                Wifi::avchannel_message::Enum::VIDEO_FOCUS_INDICATION => unimplemented!(),
1440            }
1441        } else {
1442            Err(format!("Not converted message: {:x?}", value.data))
1443        }
1444    }
1445}
1446
1447/// An object that allows multiple tasks to send or receive frames
1448struct StreamMux<T: AsyncRead + Unpin, U: AsyncWrite + Unpin> {
1449    /// The reader for receiving frames from the android auto device
1450    reader: Arc<tokio::sync::Mutex<T>>,
1451    /// The writer for sending frames to the android auto device
1452    writer: Arc<tokio::sync::Mutex<U>>,
1453    /// The object used for tls communication
1454    ssl_client: Arc<tokio::sync::Mutex<rustls::client::ClientConnection>>,
1455}
1456
1457impl<T: AsyncRead + Unpin, U: AsyncWrite + Unpin> Clone for StreamMux<T, U> {
1458    fn clone(&self) -> Self {
1459        Self {
1460            reader: self.reader.clone(),
1461            writer: self.writer.clone(),
1462            ssl_client: self.ssl_client.clone(),
1463        }
1464    }
1465}
1466
1467impl<T: AsyncRead + Unpin, U: AsyncWrite + Unpin> StreamMux<T, U> {
1468    /// Construct a new self
1469    pub fn new(sr: T, ss: U, ssl_client: rustls::client::ClientConnection) -> Self {
1470        Self {
1471            reader: Arc::new(tokio::sync::Mutex::new(sr)),
1472            writer: Arc::new(tokio::sync::Mutex::new(ss)),
1473            ssl_client: Arc::new(tokio::sync::Mutex::new(ssl_client)),
1474        }
1475    }
1476
1477    /// Is the stream currently in handshake process?
1478    pub async fn is_handshaking(&self) -> bool {
1479        let ssl_stream = self.ssl_client.lock().await;
1480        ssl_stream.is_handshaking()
1481    }
1482
1483    /// Start the ssl handshake process
1484    pub async fn start_handshake(&self) -> Result<(), SslHandshakeError> {
1485        let mut w = self.writer.lock().await;
1486        let mut ssl_stream = self.ssl_client.lock().await;
1487        let mut s = Vec::new();
1488        if ssl_stream.wants_write() {
1489            let l = ssl_stream.write_tls(&mut s);
1490            if l.is_ok() {
1491                let f: AndroidAutoFrame = AndroidAutoControlMessage::SslHandshake(s).into();
1492                let d2: Vec<u8> = f.build_vec(Some(&mut *ssl_stream)).await;
1493                w.write_all(&d2).await.map_err(|e| match e.kind() {
1494                    std::io::ErrorKind::TimedOut => SslHandshakeError::Timeout,
1495                    std::io::ErrorKind::UnexpectedEof => SslHandshakeError::Disconnected,
1496                    _ => SslHandshakeError::Unexpected(e),
1497                })?;
1498                let _ = w.flush().await;
1499            }
1500        }
1501        Ok(())
1502    }
1503
1504    /// Continue the handshake process
1505    pub async fn do_handshake(&self, data: Vec<u8>) -> Result<(), SslHandshakeError> {
1506        let mut w = self.writer.lock().await;
1507        let mut ssl_stream = self.ssl_client.lock().await;
1508        if ssl_stream.wants_read() {
1509            let mut dc = std::io::Cursor::new(data);
1510            let _ = ssl_stream.read_tls(&mut dc);
1511            let _ = ssl_stream.process_new_packets();
1512        }
1513        if ssl_stream.wants_write() {
1514            let mut s = Vec::new();
1515            let l = ssl_stream.write_tls(&mut s);
1516            if l.is_ok() {
1517                let f: AndroidAutoFrame = AndroidAutoControlMessage::SslHandshake(s).into();
1518                let d2: Vec<u8> = f.build_vec(Some(&mut *ssl_stream)).await;
1519                w.write_all(&d2).await.map_err(|e| match e.kind() {
1520                    std::io::ErrorKind::TimedOut => SslHandshakeError::Timeout,
1521                    std::io::ErrorKind::UnexpectedEof => SslHandshakeError::Disconnected,
1522                    _ => SslHandshakeError::Unexpected(e),
1523                })?;
1524                let _ = w.flush().await;
1525            }
1526        }
1527        Ok(())
1528    }
1529
1530    /// Read a frame from the stream
1531    pub async fn read_frame(
1532        &self,
1533        fr2: &mut AndroidAutoFrameReceiver,
1534    ) -> Result<AndroidAutoFrame, FrameReceiptError> {
1535        let mut s = self.reader.lock().await;
1536        loop {
1537            let mut fr = FrameHeaderReceiver::new();
1538            let f = fr.read(&mut *s).await?;
1539            let f2 = if let Some(f) = f {
1540                let mut ssl_stream = self.ssl_client.lock().await;
1541                fr2.read(&f, &mut *s, &mut ssl_stream).await?
1542            } else {
1543                None
1544            };
1545            if let Some(f) = f2 {
1546                return Ok(f);
1547            }
1548        }
1549    }
1550
1551    /// Write a frame to the stream, encrypting if necessary
1552    pub async fn write_frame(&self, f: AndroidAutoFrame) -> Result<(), FrameTransmissionError> {
1553        let mut s = self.writer.lock().await;
1554        let mut ssl_stream = self.ssl_client.lock().await;
1555        let d2: Vec<u8> = f.build_vec(Some(&mut *ssl_stream)).await;
1556        let a = s.write_all(&d2).await.map_err(|e| match e.kind() {
1557            std::io::ErrorKind::TimedOut => FrameTransmissionError::Timeout,
1558            std::io::ErrorKind::UnexpectedEof => FrameTransmissionError::Disconnected,
1559            _ => FrameTransmissionError::Unexpected(e),
1560        });
1561        let _ = s.flush().await;
1562        a
1563    }
1564
1565    /// Write a frame to the stream, encrypting if necessary
1566    pub async fn write_sendable(
1567        &self,
1568        f: SendableAndroidAutoMessage,
1569    ) -> Result<(), FrameTransmissionError> {
1570        let mut s = self.writer.lock().await;
1571        let mut ssl_stream = self.ssl_client.lock().await;
1572        let d2: Vec<u8> = f.into_frame().await.build_vec(Some(&mut *ssl_stream)).await;
1573        let a = s.write_all(&d2).await.map_err(|e| match e.kind() {
1574            std::io::ErrorKind::TimedOut => FrameTransmissionError::Timeout,
1575            std::io::ErrorKind::UnexpectedEof => FrameTransmissionError::Disconnected,
1576            _ => FrameTransmissionError::Unexpected(e),
1577        });
1578        let _ = s.flush().await;
1579        a
1580    }
1581}
1582
1583/// The server verifier for android auto head units. This verifies the certificate in the android auto compatible device (probably a phone)
1584#[derive(Debug)]
1585struct AndroidAutoServerVerifier {
1586    /// The object providing most of the functionality for server verification
1587    base: Arc<rustls::client::WebPkiServerVerifier>,
1588}
1589
1590impl AndroidAutoServerVerifier {
1591    /// Build a new server verifier using the given root certificate store
1592    fn new(roots: Arc<rustls::RootCertStore>) -> Self {
1593        Self {
1594            base: rustls::client::WebPkiServerVerifier::builder(roots)
1595                .build()
1596                .unwrap(),
1597        }
1598    }
1599}
1600
1601impl rustls::client::danger::ServerCertVerifier for AndroidAutoServerVerifier {
1602    fn verify_server_cert(
1603        &self,
1604        _end_entity: &rustls::pki_types::CertificateDer<'_>,
1605        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
1606        _server_name: &rustls::pki_types::ServerName<'_>,
1607        _ocsp_response: &[u8],
1608        _now: rustls::pki_types::UnixTime,
1609    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
1610        Ok(rustls::client::danger::ServerCertVerified::assertion())
1611    }
1612
1613    fn verify_tls12_signature(
1614        &self,
1615        message: &[u8],
1616        cert: &rustls::pki_types::CertificateDer<'_>,
1617        dss: &rustls::DigitallySignedStruct,
1618    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1619        self.base.verify_tls12_signature(message, cert, dss)
1620    }
1621
1622    fn verify_tls13_signature(
1623        &self,
1624        message: &[u8],
1625        cert: &rustls::pki_types::CertificateDer<'_>,
1626        dss: &rustls::DigitallySignedStruct,
1627    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
1628        self.base.verify_tls13_signature(message, cert, dss)
1629    }
1630
1631    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
1632        self.base.supported_verify_schemes()
1633    }
1634}
1635
1636/// The channel handler type that covers all possible channel handlers
1637#[enum_dispatch::enum_dispatch(ChannelHandlerTrait)]
1638enum ChannelHandler {
1639    Control(ControlChannelHandler),
1640    Bluetooth(BluetoothChannelHandler),
1641    AvInput(AvInputChannelHandler),
1642    SystemAudio(SystemAudioChannelHandler),
1643    SpeechAudio(SpeechAudioChannelHandler),
1644    Sensor(SensorChannelHandler),
1645    Video(VideoChannelHandler),
1646    Navigation(NavigationChannelHandler),
1647    MediaStatus(MediaStatusChannelHandler),
1648    Input(InputChannelHandler),
1649    MediaAudio(MediaAudioChannelHandler),
1650}
1651
1652/// This is a wrapper around a join handle, it aborts the handle when it is dropped.
1653struct DroppingJoinHandle<T> {
1654    /// The handle for the struct
1655    handle: tokio::task::JoinHandle<T>,
1656}
1657
1658impl<T> Drop for DroppingJoinHandle<T> {
1659    fn drop(&mut self) {
1660        self.handle.abort();
1661    }
1662}
1663
1664#[cfg(feature = "wireless")]
1665/// The handler function for a single bluetooth connection
1666async fn handle_bluetooth_client(
1667    stream: &mut BluetoothStream,
1668    network2: &NetworkInformation,
1669) -> Result<(), String> {
1670    let mut s = Bluetooth::SocketInfoRequest::new();
1671    s.set_ip_address(network2.ip.clone());
1672    s.set_port(network2.port as u32);
1673    log::info!("Got a bluetooth client");
1674    let m1 = AndroidAutoBluetoothMessage::SocketInfoRequest(s);
1675    let m: AndroidAutoRawBluetoothMessage = m1.as_message();
1676    let mdata: Vec<u8> = m.into();
1677    stream.write_all(&mdata).await.map_err(|e| e.to_string())?;
1678    loop {
1679        let mut ty = [0u8; 2];
1680        let mut len = [0u8; 2];
1681        stream
1682            .read_exact(&mut len)
1683            .await
1684            .map_err(|e| e.to_string())?;
1685        stream
1686            .read_exact(&mut ty)
1687            .await
1688            .map_err(|e| e.to_string())?;
1689        let len = u16::from_be_bytes(len);
1690        let ty = u16::from_be_bytes(ty);
1691        let mut message = vec![0; len as usize];
1692        stream
1693            .read_exact(&mut message)
1694            .await
1695            .map_err(|e| e.to_string())?;
1696        use protobuf::Enum;
1697        match Bluetooth::MessageId::from_i32(ty as i32) {
1698            Some(m) => match m {
1699                Bluetooth::MessageId::BLUETOOTH_SOCKET_INFO_REQUEST => {
1700                    log::error!("Got a socket info request {:x?}", message);
1701                    break;
1702                }
1703                Bluetooth::MessageId::BLUETOOTH_NETWORK_INFO_REQUEST => {
1704                    let mut response = Bluetooth::NetworkInfo::new();
1705                    log::debug!("Network info for bluetooth response: {:?}", network2);
1706                    response.set_ssid(network2.ssid.clone());
1707                    response.set_psk(network2.psk.clone());
1708                    response.set_mac_addr(network2.mac_addr.clone());
1709                    response.set_security_mode(network2.security_mode);
1710                    response.set_ap_type(network2.ap_type);
1711                    let response = AndroidAutoBluetoothMessage::NetworkInfoMessage(response);
1712                    let m: AndroidAutoRawBluetoothMessage = response.as_message();
1713                    let mdata: Vec<u8> = m.into();
1714                    let _ = stream.write_all(&mdata).await;
1715                }
1716                Bluetooth::MessageId::BLUETOOTH_SOCKET_INFO_RESPONSE => {
1717                    let message = Bluetooth::SocketInfoResponse::parse_from_bytes(&message);
1718                    log::info!("Message is now {:?}", message);
1719                    if let Ok(m) = message {
1720                        if m.status() == Status::STATUS_SUCCESS {
1721                            break;
1722                        }
1723                    }
1724                }
1725                _ => {}
1726            },
1727            _ => {
1728                log::error!("Unknown bluetooth packet {} {:x?}", ty, message);
1729            }
1730        }
1731        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1732    }
1733    log::info!("Ending bluetooth comms");
1734    Ok(())
1735}
1736
1737#[cfg(feature = "wireless")]
1738/// Runs the bluetooth service that allows wireless android auto connections to start up
1739async fn bluetooth_service(
1740    mut profile: bluetooth_rust::BluetoothRfcommProfile,
1741    wireless: Arc<dyn AndroidAutoWirelessTrait>,
1742) -> Result<(), String> {
1743    log::info!("Starting bluetooth service");
1744    loop {
1745        if let Ok(c) = profile.connectable().await {
1746            let network2 = wireless.get_wifi_details();
1747            let mut stream = c.accept().await?;
1748            let e = handle_bluetooth_client(&mut stream, &network2).await;
1749            log::info!("Bluetooth client disconnected: {:?}", e);
1750        }
1751    }
1752}
1753
1754#[cfg(feature = "wireless")]
1755/// Runs the wifi service for android auto
1756async fn wifi_service<T: AndroidAutoWirelessTrait + Send + ?Sized>(
1757    wireless: Arc<T>,
1758) -> Result<ConnectionType, String> {
1759    let network = wireless.get_wifi_details();
1760
1761    log::info!(
1762        "Starting android auto wireless service on port {}",
1763        network.port
1764    );
1765    if let Ok(a) = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", network.port)).await {
1766        log::info!("Starting wifi listener");
1767        loop {
1768            if let Ok((stream, _addr)) = a.accept().await {
1769                let _ = stream.set_nodelay(true);
1770                return Ok(ConnectionType::Wireless(stream));
1771            }
1772        }
1773    } else {
1774        Err(format!("Failed to listen on port {} tcp", network.port))
1775    }
1776}
1777
1778/// Handle a single android auto device for a head unit
1779async fn handle_client_generic<
1780    T: AndroidAutoMainTrait + ?Sized,
1781    R: AsyncRead + Send + Unpin + 'static,
1782    W: AsyncWrite + Send + Unpin + 'static,
1783>(
1784    reader: R,
1785    writer: W,
1786    config: AndroidAutoConfiguration,
1787    main: &Box<T>,
1788) -> Result<(), ClientError> {
1789    log::info!("Got android auto client");
1790    let mut root_store =
1791        rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
1792    let aautocertder = {
1793        let mut br = std::io::Cursor::new(cert::AAUTO_CERT.to_string().as_bytes().to_vec());
1794        let aautocertpem = rustls::pki_types::pem::from_buf(&mut br)
1795            .map_err(|_| ClientError::InvalidRootCert)?
1796            .ok_or(ClientError::InvalidRootCert)?;
1797        CertificateDer::from_pem(aautocertpem.0, aautocertpem.1)
1798            .ok_or(ClientError::InvalidRootCert)?
1799    };
1800
1801    let client_cert_data_pem = if let Some(custom) = &config.custom_certificate {
1802        custom
1803    } else {
1804        &(
1805            cert::CERTIFICATE.to_string().as_bytes().to_vec(),
1806            cert::PRIVATE_KEY.to_string().as_bytes().to_vec(),
1807        )
1808    };
1809
1810    let cert = {
1811        let mut br = std::io::Cursor::new(&client_cert_data_pem.0);
1812        let aautocertpem = rustls::pki_types::pem::from_buf(&mut br)
1813            .map_err(|_| ClientError::InvalidClientCertificate)?
1814            .ok_or(ClientError::InvalidClientCertificate)?;
1815        CertificateDer::from_pem(aautocertpem.0, aautocertpem.1)
1816            .ok_or(ClientError::InvalidClientCertificate)?
1817    };
1818    let key = {
1819        let mut br = std::io::Cursor::new(&client_cert_data_pem.1);
1820        let aautocertpem = rustls::pki_types::pem::from_buf(&mut br)
1821            .map_err(|_| ClientError::InvalidClientPrivateKey)?
1822            .ok_or(ClientError::InvalidClientPrivateKey)?;
1823        rustls::pki_types::PrivateKeyDer::from_pem(aautocertpem.0, aautocertpem.1)
1824            .ok_or(ClientError::InvalidClientPrivateKey)?
1825    };
1826    let cert = vec![cert];
1827    root_store
1828        .add(aautocertder)
1829        .map_err(|_| ClientError::InvalidRootCert)?;
1830    let root_store = Arc::new(root_store);
1831    let mut ssl_client_config = rustls::ClientConfig::builder()
1832        .with_root_certificates(root_store.clone())
1833        .with_client_auth_cert(cert, key)
1834        .unwrap();
1835    let sver = Arc::new(AndroidAutoServerVerifier::new(root_store));
1836    ssl_client_config.dangerous().set_certificate_verifier(sver);
1837    let sslconfig = Arc::new(ssl_client_config);
1838    let server = "idontknow.com".try_into().unwrap();
1839    let ssl_client =
1840        rustls::ClientConnection::new(sslconfig, server).expect("Failed to build ssl client");
1841    let sm = StreamMux::new(reader, writer, ssl_client);
1842    let message_recv = main.get_receiver().await;
1843    let sm2 = sm.clone();
1844    let kill = tokio::sync::oneshot::channel::<()>();
1845    let kill2 = tokio::sync::oneshot::channel::<()>();
1846    let _task2 = if let Some(mut msgr) = message_recv {
1847        let jh: tokio::task::JoinHandle<Result<(), FrameTransmissionError>> =
1848            tokio::task::spawn(async move {
1849                while let Some(m) = msgr.recv().await {
1850                    if let Err(e) = sm2.write_sendable(m).await {
1851                        log::error!("Error passing message: {:?}", e);
1852                        let _ = kill.0.send(());
1853                        return Err(e);
1854                    }
1855                }
1856                Ok(())
1857            });
1858        Some(DroppingJoinHandle { handle: jh })
1859    } else {
1860        None
1861    };
1862
1863    let sm3 = sm.clone();
1864    tokio::spawn(async move {
1865        tokio::select! {
1866            _ = async {
1867                loop {
1868                    tokio::time::sleep(std::time::Duration::from_secs(5)).await;
1869                    let mut m = Wifi::PingRequest::new();
1870                    let timestamp = std::time::SystemTime::now()
1871                        .duration_since(std::time::UNIX_EPOCH)
1872                        .unwrap()
1873                        .as_micros() as i64;
1874                    m.set_timestamp(timestamp);
1875                    if let Err(e) = sm3
1876                        .write_frame(AndroidAutoControlMessage::PingRequest(m).into())
1877                        .await {
1878                            log::error!("Error sending ping request {:?}", e);
1879                        }
1880                }
1881            } => {}
1882            _ = kill2.1 => {
1883            }
1884        }
1885        log::info!("Exiting pinger");
1886    });
1887
1888    log::info!("Sending channel handlers");
1889    {
1890        let mut channel_handlers: Vec<ChannelHandler> = Vec::new();
1891        channel_handlers.push(ControlChannelHandler::new().into());
1892        channel_handlers.push(InputChannelHandler {}.into());
1893        channel_handlers.push(SensorChannelHandler {}.into());
1894        channel_handlers.push(VideoChannelHandler::new().into());
1895        channel_handlers.push(MediaAudioChannelHandler {}.into());
1896        channel_handlers.push(SpeechAudioChannelHandler {}.into());
1897        channel_handlers.push(SystemAudioChannelHandler {}.into());
1898        channel_handlers.push(AvInputChannelHandler {}.into());
1899        if main.supports_bluetooth().is_some() {
1900            channel_handlers.push(BluetoothChannelHandler {}.into());
1901        }
1902        if main.supports_navigation().is_some() {
1903            channel_handlers.push(NavigationChannelHandler {}.into());
1904        }
1905        channel_handlers.push(MediaStatusChannelHandler {}.into());
1906
1907        let mut chans = Vec::new();
1908        for (index, handler) in channel_handlers.iter().enumerate() {
1909            let chan: ChannelId = index as u8;
1910            if let Some(chan) = handler.build_channel(&config, chan, main.as_ref()) {
1911                chans.push(chan);
1912            }
1913        }
1914        channel_handlers.get_mut(0).unwrap().set_channels(chans);
1915        {
1916            let mut ch = CHANNEL_HANDLERS.write().await;
1917            ch.clear();
1918            log::error!(
1919                "Adding {} channels to CHANNEL_HANDLERS",
1920                channel_handlers.len()
1921            );
1922            ch.append(&mut channel_handlers);
1923        }
1924    }
1925    log::info!("Sending version request");
1926    sm.write_frame(AndroidAutoControlMessage::VersionRequest.into())
1927        .await
1928        .map_err(|e| {
1929            let e2: FrameIoError = e.into();
1930            e2
1931        })?;
1932    let mut fr2 = AndroidAutoFrameReceiver::new();
1933    let channel_handlers = CHANNEL_HANDLERS.read().await;
1934    log::debug!("Waiting on first packet from android auto client");
1935
1936    tokio::select! {
1937        a = do_android_auto_loop(fr2, channel_handlers, sm, config, main) => {
1938
1939        }
1940        _ = kill.1 => {
1941
1942        }
1943    }
1944    kill2.0.send(());
1945    Ok(())
1946}
1947
1948async fn do_android_auto_loop<
1949    T: AndroidAutoMainTrait + ?Sized,
1950    R: AsyncRead + Send + Unpin + 'static,
1951    W: AsyncWrite + Send + Unpin + 'static,
1952>(
1953    mut fr2: AndroidAutoFrameReceiver,
1954    channel_handlers: RwLockReadGuard<'_, Vec<ChannelHandler>>,
1955    sm: StreamMux<R, W>,
1956    config: AndroidAutoConfiguration,
1957    main: &Box<T>,
1958) -> Result<(), ClientError> {
1959    loop {
1960        if let Ok(f) = sm.read_frame(&mut fr2).await {
1961            if let Some(handler) = channel_handlers.get(f.header.channel_id as usize) {
1962                handler.receive_data(f, &sm, &config, main.as_ref()).await?;
1963            } else {
1964                panic!("Unknown channel id: {:?}", f.header.channel_id);
1965            }
1966        }
1967    }
1968}
1969
1970#[cfg(feature = "usb")]
1971/// Watch for a usb disconnect message from nusb
1972async fn watch_for_disconnect(device_address: Arc<nusb::DeviceInfo>) {
1973    let mut watcher = nusb::watch_devices().unwrap();
1974    while let Some(event) = watcher.next().await {
1975        match event {
1976            nusb::hotplug::HotplugEvent::Disconnected(_info) => {
1977                let devs = nusb::list_devices().await;
1978                if let Ok(mut devs) = devs {
1979                    if devs
1980                        .find(|a| {
1981                            a.busnum() == device_address.busnum()
1982                                && a.device_address() == device_address.device_address()
1983                        })
1984                        .is_none()
1985                    {
1986                        log::info!("Android Auto USB device disconnected");
1987                        break;
1988                    }
1989                } else {
1990                    break;
1991                }
1992            }
1993            _ => {}
1994        }
1995    }
1996}
1997
1998/// A helper type for operating the android auto code
1999type AsyncFn =
2000    Box<dyn FnOnce() -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
2001
2002#[cfg(feature = "usb")]
2003fn make_disconnect_watcher(device_address: nusb::DeviceInfo) -> AsyncFn {
2004    let device_address = std::sync::Arc::new(device_address);
2005    Box::new(move || {
2006        let device_address = device_address.clone();
2007        Box::pin(async move {
2008            watch_for_disconnect(device_address).await;
2009        })
2010    })
2011}
2012
2013/// Token proving that [`setup`] has been called. Required to use the library's
2014/// main entry points so that initialisation cannot be forgotten.
2015///
2016/// Constructed exclusively by [`setup`]; users cannot build this type themselves.
2017/// The token is `Copy` so it can be stored and handed to multiple container
2018/// restarts without needing to call `setup` again.
2019#[derive(Clone, Copy)]
2020pub struct AndroidAutoSetup {
2021    _private: (),
2022}
2023
2024/// Perform any setup required on startup of the library.
2025///
2026/// Returns an [`AndroidAutoSetup`] token that must be passed to [`AndroidAutoMainTrait::run`]
2027/// (and related methods). Requiring this token at the call site ensures that setup is
2028/// never accidentally skipped.
2029pub fn setup() -> AndroidAutoSetup {
2030    let cp = rustls::crypto::ring::default_provider();
2031    cp.install_default().expect("Failed to set ssl provider");
2032    AndroidAutoSetup { _private: () }
2033}