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