android-auto 0.3.8

A crate for implementing the android auto protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Code for the control channel

use super::VERSION;
use super::{AndroidAutoFrame, FrameHeader, FrameHeaderContents, FrameHeaderType};
use crate::{
    AndroidAutoConfiguration, AndroidAutoMainTrait, ChannelHandlerTrait, ChannelId, StreamMux, Wifi,
};
use protobuf::{Enum, Message};

/// A control message on the android auto protocol
#[derive(Debug)]
pub enum AndroidAutoControlMessage {
    /// A message requesting version information.
    VersionRequest,
    /// A message containing version of the compatible android auto device and compatibility status
    VersionResponse {
        /// The major version
        major: u16,
        /// The minor version
        minor: u16,
        /// The status of the version compatibility, 0xffff indicates incompatibility
        status: u16,
    },
    /// A message containing ssl handshake data
    SslHandshake(Vec<u8>),
    /// A message indicating that the ssl authentication is complete
    SslAuthComplete(bool),
    /// A request to discover all channels in operation on the head unit
    ServiceDiscoveryRequest(Wifi::ServiceDiscoveryRequest),
    /// A response to the service discovery request
    ServiceDiscoveryResponse(Wifi::ServiceDiscoveryResponse),
    /// A request to set the audio focus
    AudioFocusRequest(Wifi::AudioFocusRequest),
    /// A response to an audio focus request
    AudioFocusResponse(Wifi::AudioFocusResponse),
    /// A request for ping
    PingRequest(Wifi::PingRequest),
    /// A response to a ping response
    PingResponse(Wifi::PingResponse),
    /// A shutdown request
    ShutdownRequest(Wifi::ShutdownRequest),
    /// A shutdown response
    ShutdownResponse,
    /// Navigation focus request
    NavigationFocusRequest(Wifi::NavigationFocusRequest),
    /// Navigation focus response
    NavigationFocusResponse(Wifi::NavigationFocusResponse),
    /// A voice session request command
    VoiceSession(Wifi::VoiceSessionRequest),
}

impl TryFrom<&AndroidAutoFrame> for AndroidAutoControlMessage {
    type Error = String;
    fn try_from(value: &AndroidAutoFrame) -> Result<Self, Self::Error> {
        let mut ty = [0u8; 2];
        ty.copy_from_slice(&value.data[0..2]);
        let ty = u16::from_be_bytes(ty);
        if !value.header.frame.get_control() {
            let w = Wifi::ControlMessage::from_i32(ty as i32);
            if let Some(m) = w {
                match m {
                    Wifi::ControlMessage::VERSION_REQUEST => unimplemented!(),
                    Wifi::ControlMessage::AUTH_COMPLETE => unimplemented!(),
                    Wifi::ControlMessage::MESSAGE_NONE => unimplemented!(),
                    Wifi::ControlMessage::SERVICE_DISCOVERY_RESPONSE => unimplemented!(),
                    Wifi::ControlMessage::PING_REQUEST => {
                        let m = Wifi::PingRequest::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::PingRequest(m)),
                            Err(e) => Err(format!("Invalid ping request: {}", e)),
                        }
                    }
                    Wifi::ControlMessage::NAVIGATION_FOCUS_REQUEST => {
                        let m = Wifi::NavigationFocusRequest::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::NavigationFocusRequest(m)),
                            Err(e) => Err(format!("Invalid request: {}", e)),
                        }
                    }
                    Wifi::ControlMessage::NAVIGATION_FOCUS_RESPONSE => unimplemented!(),
                    Wifi::ControlMessage::SHUTDOWN_REQUEST => {
                        let m = Wifi::ShutdownRequest::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::ShutdownRequest(m)),
                            Err(e) => Err(format!("Invalid shutdown request: {}", e)),
                        }
                    }
                    Wifi::ControlMessage::SHUTDOWN_RESPONSE => unimplemented!(),
                    Wifi::ControlMessage::VOICE_SESSION_REQUEST => {
                        let m = Wifi::VoiceSessionRequest::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::VoiceSession(m)),
                            Err(e) => Err(format!("Invalid ping response: {}", e)),
                        }
                    }
                    Wifi::ControlMessage::AUDIO_FOCUS_RESPONSE => unimplemented!(),
                    Wifi::ControlMessage::PING_RESPONSE => {
                        let m = Wifi::PingResponse::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::PingResponse(m)),
                            Err(e) => Err(format!("Invalid ping response: {}", e)),
                        }
                    }
                    Wifi::ControlMessage::AUDIO_FOCUS_REQUEST => {
                        let m = Wifi::AudioFocusRequest::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::AudioFocusRequest(m)),
                            Err(e) => Err(format!("Invalid audio focus request: {}", e)),
                        }
                    }
                    Wifi::ControlMessage::VERSION_RESPONSE => {
                        if value.data.len() == 8 {
                            let major = u16::from_be_bytes([value.data[2], value.data[3]]);
                            let minor = u16::from_be_bytes([value.data[4], value.data[5]]);
                            let status = u16::from_be_bytes([value.data[6], value.data[7]]);
                            Ok(AndroidAutoControlMessage::VersionResponse {
                                major,
                                minor,
                                status,
                            })
                        } else {
                            Err("Invalid version response packet".to_string())
                        }
                    }
                    Wifi::ControlMessage::SSL_HANDSHAKE => Ok(
                        AndroidAutoControlMessage::SslHandshake(value.data[2..].to_vec()),
                    ),
                    Wifi::ControlMessage::SERVICE_DISCOVERY_REQUEST => {
                        let m = Wifi::ServiceDiscoveryRequest::parse_from_bytes(&value.data[2..]);
                        match m {
                            Ok(m) => Ok(AndroidAutoControlMessage::ServiceDiscoveryRequest(m)),
                            Err(e) => Err(format!("Invalid service discovery request: {}", e)),
                        }
                    }
                }
            } else {
                Err(format!("Unknown packet type 0x{:x}", ty))
            }
        } else {
            Err(format!(
                "Unhandled specific message for channel {:?} {:x?}",
                value.header.channel_id, value.data
            ))
        }
    }
}

impl From<AndroidAutoControlMessage> for AndroidAutoFrame {
    fn from(value: AndroidAutoControlMessage) -> Self {
        match value {
            AndroidAutoControlMessage::VoiceSession(_) => unimplemented!(),
            AndroidAutoControlMessage::NavigationFocusRequest(_) => unimplemented!(),
            AndroidAutoControlMessage::NavigationFocusResponse(m) => {
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::NAVIGATION_FOCUS_RESPONSE as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::ShutdownRequest(_) => unimplemented!(),
            AndroidAutoControlMessage::ShutdownResponse => {
                let m = Wifi::ShutdownResponse::new();
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::SHUTDOWN_RESPONSE as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::PingResponse(m) => {
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::PING_RESPONSE as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(false, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::PingRequest(m) => {
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::PING_REQUEST as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(false, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::AudioFocusResponse(m) => {
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::AUDIO_FOCUS_RESPONSE as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::AudioFocusRequest(_) => unimplemented!(),
            AndroidAutoControlMessage::ServiceDiscoveryResponse(m) => {
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::SERVICE_DISCOVERY_RESPONSE as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(true, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::VersionRequest => {
                let mut m = Vec::with_capacity(4);
                let t = Wifi::ControlMessage::VERSION_REQUEST as u16;
                let t = t.to_be_bytes();
                let major = VERSION.0.to_be_bytes();
                let minor = VERSION.1.to_be_bytes();
                m.push(t[0]);
                m.push(t[1]);
                m.push(major[0]);
                m.push(major[1]);
                m.push(minor[0]);
                m.push(minor[1]);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(false, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::SslHandshake(mut data) => {
                let mut m = Vec::with_capacity(4);
                let t = Wifi::ControlMessage::SSL_HANDSHAKE as u16;
                let t = t.to_be_bytes();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(false, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::SslAuthComplete(status) => {
                let mut m = Wifi::AuthCompleteIndication::new();
                let status = if status {
                    Wifi::AuthCompleteIndicationStatus::OK
                } else {
                    Wifi::AuthCompleteIndicationStatus::FAIL
                };
                m.set_status(status);
                let mut data = m.write_to_bytes().unwrap();
                let t = Wifi::ControlMessage::AUTH_COMPLETE as u16;
                let t = t.to_be_bytes();
                let mut m = Vec::new();
                m.push(t[0]);
                m.push(t[1]);
                m.append(&mut data);
                AndroidAutoFrame {
                    header: FrameHeader {
                        channel_id: 0,
                        frame: FrameHeaderContents::new(false, FrameHeaderType::Single, false),
                    },
                    data: m,
                }
            }
            AndroidAutoControlMessage::ServiceDiscoveryRequest(_) => unimplemented!(),
            AndroidAutoControlMessage::VersionResponse {
                major: _,
                minor: _,
                status: _,
            } => {
                unimplemented!();
            }
        }
    }
}

/// The inner data for the channel handler
struct InnerChannelHandler {
    /// The list of all channels for the head unit. This is filled out after the control channel is created
    channels: Vec<Wifi::ChannelDescriptor>,
}

impl InnerChannelHandler {
    /// Construct a new self
    pub fn new() -> Self {
        Self {
            channels: Vec::new(),
        }
    }
}

/// Handles the control channel of the android auto protocol
pub struct ControlChannelHandler {
    /// The inner protected data
    inner: std::sync::Mutex<InnerChannelHandler>,
}

impl ControlChannelHandler {
    /// Construct a new self
    pub fn new() -> Self {
        Self {
            inner: std::sync::Mutex::new(InnerChannelHandler::new()),
        }
    }
}

impl ChannelHandlerTrait for ControlChannelHandler {
    fn set_channels(&self, chans: Vec<Wifi::ChannelDescriptor>) {
        let mut inner = self.inner.lock().unwrap();
        inner.channels = chans;
    }

    fn build_channel<T: AndroidAutoMainTrait + ?Sized>(
        &self,
        _config: &AndroidAutoConfiguration,
        _chanid: ChannelId,
        _main: &T,
    ) -> Option<Wifi::ChannelDescriptor> {
        None
    }

    async fn receive_data<T: AndroidAutoMainTrait + ?Sized>(
        &self,
        msg: AndroidAutoFrame,
        stream: &crate::WriteHalf,
        config: &AndroidAutoConfiguration,
        main: &T,
    ) -> Result<(), super::FrameIoError> {
        let msg2: Result<AndroidAutoControlMessage, String> = (&msg).try_into();
        if let Ok(msg2) = msg2 {
            match msg2 {
                AndroidAutoControlMessage::VoiceSession(m) => {
                    log::error!("Received voice session request {:?}", m);
                }
                AndroidAutoControlMessage::NavigationFocusResponse(_) => unimplemented!(),
                AndroidAutoControlMessage::NavigationFocusRequest(m) => {
                    log::error!("Received navigation focus request {}", m.type_());
                    let mut m2 = Wifi::NavigationFocusResponse::new();
                    m2.set_type(2);
                    stream
                        .write_frame(AndroidAutoControlMessage::NavigationFocusResponse(m2).into())
                        .await?;
                }
                AndroidAutoControlMessage::ShutdownResponse => unimplemented!(),
                AndroidAutoControlMessage::ShutdownRequest(m) => {
                    if m.reason() == Wifi::shutdown_reason::Enum::QUIT {
                        stream
                            .write_frame(AndroidAutoControlMessage::ShutdownResponse.into())
                            .await?;
                        return Err(super::FrameIoError::ShutdownRequested);
                    }
                }
                AndroidAutoControlMessage::PingResponse(m) => {
                    let t = m.timestamp();
                    let delta = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap()
                        .as_micros() as i64
                        - t;
                    main.ping_time_microseconds(delta).await;
                }
                AndroidAutoControlMessage::PingRequest(a) => {
                    let mut m = Wifi::PingResponse::new();
                    m.set_timestamp(a.timestamp());
                    stream
                        .write_frame(AndroidAutoControlMessage::PingResponse(m).into())
                        .await?;
                }
                AndroidAutoControlMessage::AudioFocusResponse(_) => unimplemented!(),
                AndroidAutoControlMessage::AudioFocusRequest(m) => {
                    let mut m2 = Wifi::AudioFocusResponse::new();
                    let s = if m.has_audio_focus_type() {
                        match m.audio_focus_type() {
                            Wifi::audio_focus_type::Enum::NONE => {
                                Wifi::audio_focus_state::Enum::NONE
                            }
                            Wifi::audio_focus_type::Enum::GAIN => {
                                Wifi::audio_focus_state::Enum::GAIN
                            }
                            Wifi::audio_focus_type::Enum::GAIN_TRANSIENT => {
                                Wifi::audio_focus_state::Enum::GAIN_TRANSIENT
                            }
                            Wifi::audio_focus_type::Enum::GAIN_NAVI => {
                                Wifi::audio_focus_state::Enum::GAIN
                            }
                            Wifi::audio_focus_type::Enum::RELEASE => {
                                Wifi::audio_focus_state::Enum::LOSS
                            }
                        }
                    } else {
                        Wifi::audio_focus_state::Enum::NONE
                    };
                    m2.set_audio_focus_state(s);
                    stream
                        .write_frame(AndroidAutoControlMessage::AudioFocusResponse(m2).into())
                        .await?;
                }
                AndroidAutoControlMessage::ServiceDiscoveryResponse(_) => unimplemented!(),
                AndroidAutoControlMessage::ServiceDiscoveryRequest(_m) => {
                    let mut m2 = Wifi::ServiceDiscoveryResponse::new();
                    m2.set_car_model(config.unit.car_model.clone());
                    m2.set_can_play_native_media_during_vr(config.unit.native_media);
                    m2.set_car_serial(config.unit.car_serial.clone());
                    m2.set_car_year(config.unit.car_year.clone());
                    m2.set_head_unit_name(config.unit.name.clone());
                    m2.set_headunit_manufacturer(config.unit.head_manufacturer.clone());
                    m2.set_headunit_model(config.unit.head_model.clone());
                    if let Some(hide) = config.unit.hide_clock {
                        m2.set_hide_clock(hide);
                    }
                    m2.set_left_hand_drive_vehicle(config.unit.left_hand);
                    m2.set_sw_build(config.unit.sw_build.clone());
                    m2.set_sw_version(config.unit.sw_version.clone());
                    {
                        let inner = self.inner.lock().unwrap();
                        for s in &inner.channels {
                            m2.channels.push(s.clone());
                        }
                    }
                    stream
                        .write_frame(AndroidAutoControlMessage::ServiceDiscoveryResponse(m2).into())
                        .await?;
                }
                AndroidAutoControlMessage::SslAuthComplete(_) => unimplemented!(),
                AndroidAutoControlMessage::SslHandshake(data) => {
                    stream.do_handshake(data).await?;
                }
                AndroidAutoControlMessage::VersionRequest => unimplemented!(),
                AndroidAutoControlMessage::VersionResponse {
                    major,
                    minor,
                    status,
                } => {
                    if status == 0xFFFF {
                        log::error!("Version mismatch");
                        return Err(super::FrameIoError::IncompatibleVersion(major, minor));
                    }
                    log::info!("Android auto client version: {}.{}", major, minor);
                    stream.start_handshake().await?;
                }
            }
        } else {
            todo!("{:?} {:x?}", msg2.err(), msg);
        }
        Ok(())
    }
}