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