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