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