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