-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhu_aap.cpp
More file actions
1459 lines (1247 loc) · 56.6 KB
/
hu_aap.cpp
File metadata and controls
1459 lines (1247 loc) · 56.6 KB
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Android Auto Protocol Handler
#include <pthread.h>
#define LOGTAG "hu_aap"
#include <endian.h>
#include <google/protobuf/descriptor.h>
#include <fstream>
#include <iostream>
#include <memory>
#include "AndroidAuto.h"
#include "hu_ssl.h"
#include "transport/USBTransportStream.h"
#include "transport/TCPTransportStream.h"
#include "hu_uti.h"
using namespace AndroidAuto;
HUServer::HUServer(HeadunitEventCallbacks &callbacks, std::map<std::string, std::string> _settings) : callbacks(callbacks) {
settings = _settings;
// Defaults
std::map<std::string, std::string> default_settings;
default_settings["head_unit_name"] = "Computer";
default_settings["car_model"] = "libheadunit";
default_settings["car_year"] = "2017";
default_settings["car_serial"] = "007";
default_settings["driver_pos"] = "1"; // bool
default_settings["headunit_make"] = "libhu";
default_settings["headunit_model"] = "libheadunit";
default_settings["sw_build"] = "SWB1";
default_settings["sw_version"] = "SWV1";
default_settings["can_play_native_media_during_vr"] = "0"; // bool
default_settings["hide_clock"] = "0"; // bool
default_settings["ts_width"] = "800";
default_settings["ts_height"] = "480";
default_settings["resolution"] = "1"; // 800x480 = 1, 1280x720 = 2, 1920x1080 = 3
default_settings["frame_rate"] = "1"; // 30 FPS = 1, 60 FPS = 2
default_settings["margin_width"] = "0";
default_settings["margin_height"] = "0";
default_settings["dpi"] = "140";
default_settings["available_while_in_call"] = "0"; // bool
default_settings["transport_type"] = "usb"; // "usb" or "network"
default_settings["network_address"] = "127.0.0.1";
default_settings["wifi_direct"] = "0";
settings.insert(default_settings.begin(), default_settings.end());
}
int HUServer::startTransport() {
std::map<std::string, std::string> conf;
if (settings["transport_type"] == "network") {
conf["network_address"] = settings["network_address"];
logd("AA over Wifi");
transport = std::unique_ptr<AbstractTransportStream>(new TCPTransportStream(conf));
iaap_tra_recv_tmo = 1000;
iaap_tra_send_tmo = 2000;
} else if (settings["transport_type"] == "usb") {
transport = std::unique_ptr<AbstractTransportStream>(new USBTransportStream(conf));
logd("AA over USB");
iaap_tra_recv_tmo = 0; // 100;
iaap_tra_send_tmo = 2500;
} else {
loge("Unknown transport type");
return -1;
}
return transport->Start();
}
int HUServer::stopTransport() {
int ret = 0;
if (transport) {
ret = transport->Stop();
transport.reset();
}
return ret;
}
int HUServer::receiveTransportPacket(byte *buf, int len, int tmo) {
int ret = 0;
if (iaap_state != HU_STATE::hu_STATE_STARTED && iaap_state != HU_STATE::hu_STATE_STARTIN) { // Need to recv when starting
loge("CHECK: iaap_state: %d (%s)", iaap_state, state_get(iaap_state));
return (-1);
}
int readfd = transport->GetReadFD();
int errorfd = transport->GetErrorFD();
if (tmo > 0 || errorfd >= 0) {
fd_set sock_set;
FD_ZERO(&sock_set);
FD_SET(readfd, &sock_set);
int maxfd = readfd;
if (errorfd >= 0) {
maxfd = std::max(maxfd, errorfd);
FD_SET(errorfd, &sock_set);
}
timeval tv_timeout = {1, 0};
int ret = select(maxfd + 1, &sock_set, NULL, NULL, &tv_timeout);
if (ret < 0) {
loge("error when select : %s (%d)", strerror(errno), errno);
return ret;
} else if (errorfd >= 0 && FD_ISSET(errorfd, &sock_set)) {
// got an error
loge("errorf was signaled");
return -1;
} else if (ret == 0) {
loge("hu_aap_tra_recv Timeout");
return -1;
}
}
ret = read(readfd, buf, len);
if (ret < 0) {
loge("ihu_tra_recv() error so stop Transport & AAP ret: %d", ret);
stop();
}
return (ret);
}
int log_packet_info = 1;
int HUServer::sendTransportPacket(int retry, byte *buf, int len,
int tmo) { // Send Transport data: chan,flags,len,type,...
// Need to send when starting
if (iaap_state != HU_STATE::hu_STATE_STARTED && iaap_state != HU_STATE::hu_STATE_STARTIN) {
loge("CHECK: iaap_state: %d (%s)", iaap_state, state_get(iaap_state));
return (-1);
}
int ret = transport->Write(buf, len, tmo);
if (ret < 0 || ret != len) {
if (retry == 0) {
loge("Error ihu_tra_send() error so stop Transport & AAP ret: %d "
"len: "
"%d",
ret, len);
stop();
}
return (-1);
}
if (ena_log_verbo && ena_log_aap_send)
logd("OK ihu_tra_send() ret: %d len: %d", ret, len);
return (ret);
}
int HUServer::sendEncodedMessage(int retry, ServiceChannels chan, uint16_t messageCode, const google::protobuf::MessageLite &message,
int overrideTimeout) {
const int messageSize = message.ByteSizeLong();
const int requiredSize = messageSize + 2;
if (temp_assembly_buffer->size() < static_cast<unsigned int>(requiredSize)) {
temp_assembly_buffer->resize(static_cast<unsigned int>(requiredSize));
}
uint16_t *destMessageCode = reinterpret_cast<uint16_t *>(temp_assembly_buffer->data());
*destMessageCode++ = htobe16(messageCode);
if (!message.SerializeToArray(destMessageCode, messageSize)) {
loge("AppendToString failed for %s", message.GetTypeName().c_str());
return -1;
}
logd("Send %s on channel %i %s", message.GetTypeName().c_str(), chan, getChannel(chan));
// hex_dump("PB:", 80, temp_assembly_buffer->data(), requiredSize);
return sendEncoded(retry, chan, temp_assembly_buffer->data(), requiredSize, overrideTimeout);
}
int HUServer::sendEncodedMediaPacket(int retry, ServiceChannels chan, uint16_t messageCode, uint64_t timeStamp, const byte *buffer, int bufferLen,
int overrideTimeout) {
const int requiredSize = bufferLen + 2 + 8;
if (temp_assembly_buffer->size() < static_cast<unsigned int>(requiredSize)) {
temp_assembly_buffer->resize(static_cast<unsigned int>(requiredSize));
}
uint16_t *destMessageCode = reinterpret_cast<uint16_t *>(temp_assembly_buffer->data());
*destMessageCode++ = htobe16(messageCode);
uint64_t *destTimestamp = reinterpret_cast<uint64_t *>(destMessageCode);
*destTimestamp++ = htobe64(timeStamp);
memcpy(destTimestamp, buffer, bufferLen);
// logd ("Send %s on channel %i %s", message.GetTypeName().c_str(), chan,
// chan_get(chan)); hex_dump("PB:", 80, temp_assembly_buffer->data(),
// requiredSize);
return sendEncoded(retry, chan, temp_assembly_buffer->data(), requiredSize, overrideTimeout);
}
int HUServer::sendEncoded(int retry, ServiceChannels chan, byte *buf, int len,
int overrideTimeout) { // Encrypt data and send: type,...
if (iaap_state != HU_STATE::hu_STATE_STARTED) {
logw("CHECK: iaap_state: %d (%s)", iaap_state, state_get(iaap_state));
// logw ("chan: %d len: %d buf: %p", chan, len, buf);
// hex_dump (" W/ hu_aap_enc_send: ", 16, buf, len); // Byebye:
// hu_aap_enc_send: 00000000 00 0f 08 00
return (-1);
}
byte base_flags = HU_FRAME_ENCRYPTED;
uint16_t message_type = be16toh(*((uint16_t *)buf));
if (chan != ControlChannel && message_type >= 2 && message_type < 0x8000) { // If not control channel and msg_type = 0 - 255
// = control type message
base_flags |= HU_FRAME_CONTROL_MESSAGE; // Set Control Flag (On non-control
// channels, indicates generic/"control
// type" messages logd ("Setting
// control");
}
for (int frag_start = 0; frag_start < len; frag_start += MAX_FRAME_PAYLOAD_SIZE) {
byte flags = base_flags;
if (frag_start == 0) {
flags |= HU_FRAME_FIRST_FRAME;
}
int cur_len = MAX_FRAME_PAYLOAD_SIZE;
if ((frag_start + MAX_FRAME_PAYLOAD_SIZE) >= len) {
flags |= HU_FRAME_LAST_FRAME;
cur_len = len - frag_start;
}
int bytes_written = SSL_write(m_ssl, &buf[frag_start],
cur_len); // Write plaintext to SSL
if (bytes_written <= 0) {
loge("SSL_write() bytes_written: %d", bytes_written);
logSSLReturnCode(bytes_written);
logSSLInfo();
stop();
return (-1);
}
if (bytes_written != cur_len)
loge("SSL_write() cur_len: %d bytes_written: %d chan: %d %s", cur_len, bytes_written, chan, getChannel(chan));
else if (ena_log_verbo && ena_log_aap_send)
logd("SSL_write() cur_len: %d bytes_written: %d chan: %d %s", cur_len, bytes_written, chan, getChannel(chan));
enc_buf[0] = (byte)chan; // Encode channel and flags
enc_buf[1] = flags;
int header_size = 4;
if ((flags & HU_FRAME_FIRST_FRAME) & !(flags & HU_FRAME_LAST_FRAME)) {
// write total len
*((uint32_t *)&enc_buf[header_size]) = htobe32(len);
header_size += 4;
}
int bytes_read = BIO_read(m_sslReadBio, &enc_buf[header_size],
sizeof(enc_buf) - header_size); // Read encrypted from SSL BIO to enc_buf +
if (bytes_read <= 0) {
loge("BIO_read() bytes_read: %d", bytes_read);
stop();
return (-1);
}
if (ena_log_verbo && ena_log_aap_send)
logd("BIO_read() bytes_read: %d", bytes_read);
*((uint16_t *)&enc_buf[2]) = htobe16(bytes_read);
int ret = 0;
ret = sendTransportPacket(retry, enc_buf, bytes_read + header_size,
overrideTimeout < 0 ? iaap_tra_send_tmo : overrideTimeout); // Send encrypted data to AA Server
if (retry)
return (ret);
}
return (0);
}
int HUServer::sendUnencoded(int retry, ServiceChannels chan, byte *buf, int len,
int overrideTimeout) { // Encrypt data and send: type,...
if (iaap_state != HU_STATE::hu_STATE_STARTED && iaap_state != HU_STATE::hu_STATE_STARTIN) {
logw("CHECK: iaap_state: %d (%s)", iaap_state, state_get(iaap_state));
// logw ("chan: %d len: %d buf: %p", chan, len, buf);
// hex_dump (" W/ hu_aap_enc_send: ", 16, buf, len); // Byebye:
// hu_aap_enc_send: 00000000 00 0f 08 00
return (-1);
}
byte base_flags = 0;
uint16_t message_type = be16toh(*((uint16_t *)buf));
if (chan != ControlChannel && message_type >= 2 && message_type < 0x8000) { // If not control channel and msg_type = 0 - 255
// = control type message
base_flags |= HU_FRAME_CONTROL_MESSAGE; // Set Control Flag (On non-control
// channels, indicates generic/"control
// type" messages logd ("Setting
// control");
}
logd("Sending hu_aap_unenc_send %i bytes", len);
for (int frag_start = 0; frag_start < len; frag_start += MAX_FRAME_PAYLOAD_SIZE) {
byte flags = base_flags;
if (frag_start == 0) {
flags |= HU_FRAME_FIRST_FRAME;
}
int cur_len = MAX_FRAME_PAYLOAD_SIZE;
if ((frag_start + MAX_FRAME_PAYLOAD_SIZE) >= len) {
flags |= HU_FRAME_LAST_FRAME;
cur_len = len - frag_start;
}
logd("Frame %i : %i bytes", (int)flags, cur_len);
enc_buf[0] = (byte)chan; // Encode channel and flags
enc_buf[1] = flags;
*((uint16_t *)&enc_buf[2]) = htobe16(cur_len);
int header_size = 4;
if ((flags & HU_FRAME_FIRST_FRAME) & !(flags & HU_FRAME_LAST_FRAME)) {
// write total len
*((uint32_t *)&enc_buf[header_size]) = htobe32(len);
header_size += 4;
}
memcpy(&enc_buf[header_size], &buf[frag_start], cur_len);
return sendTransportPacket(retry, enc_buf, cur_len + header_size,
overrideTimeout < 0 ? iaap_tra_send_tmo : overrideTimeout); // Send encrypted data to AA Server
}
return (0);
}
int HUServer::sendUnencodedBlob(int retry, ServiceChannels chan, uint16_t messageCode, const byte *buffer, int bufferLen, int overrideTimeout) {
const int requiredSize = bufferLen + 2;
if (temp_assembly_buffer->size() < static_cast<unsigned int>(requiredSize)) {
temp_assembly_buffer->resize(static_cast<unsigned int>(requiredSize));
}
uint16_t *destMessageCode = reinterpret_cast<uint16_t *>(temp_assembly_buffer->data());
*destMessageCode++ = htobe16(messageCode);
memcpy(destMessageCode, buffer, bufferLen);
// logd ("Send %s on channel %i %s", message.GetTypeName().c_str(), chan,
// chan_get(chan)); hex_dump("PB:", 80, temp_assembly_buffer->data(),
// requiredSize);
return sendUnencoded(retry, chan, temp_assembly_buffer->data(), requiredSize, overrideTimeout);
}
int HUServer::sendUnencodedMessage(int retry, ServiceChannels chan, uint16_t messageCode, const google::protobuf::MessageLite &message,
int overrideTimeout) {
const int messageSize = message.ByteSizeLong();
const int requiredSize = messageSize + 2;
if (temp_assembly_buffer->size() < static_cast<unsigned int>(requiredSize)) {
temp_assembly_buffer->resize(static_cast<unsigned int>(requiredSize));
}
uint16_t *destMessageCode = reinterpret_cast<uint16_t *>(temp_assembly_buffer->data());
*destMessageCode++ = htobe16(messageCode);
if (!message.SerializeToArray(destMessageCode, messageSize)) {
loge("AppendToString failed for %s", message.GetTypeName().c_str());
return -1;
}
logd("Send %s on channel %i %s", message.GetTypeName().c_str(), chan, getChannel(chan));
// hex_dump("PB:", 80, temp_assembly_buffer->data(), requiredSize);
return sendUnencoded(retry, chan, temp_assembly_buffer->data(), requiredSize, overrideTimeout);
}
int HUServer::handle_VersionResponse(ServiceChannels chan, byte *buf, int len) {
logd("Version response recv len: %d", len);
hex_dump("version", 40, buf, len);
int ret = beginSSLHandshake(); // Do SSL Client Handshake with AA SSL server
if (ret) {
stop();
}
return (ret);
}
// extern int wifi_direct;// = 0;//1;//0;
int HUServer::handle_ServiceDiscoveryRequest(ServiceChannels chan, byte *buf,
int len) { // Service Discovery Request
HU::ServiceDiscoveryRequest request;
if (!request.ParseFromArray(buf, len))
loge("Service Discovery Request: %x", buf[2]);
else
logd("Service Discovery Request: %s",
request.phone_name().c_str()); // S 0 CTR b src: HU lft: 113 msg_type: 6
// Service Discovery Response S 0 CTR b 00000000
// 0a 08 08 01 12 04 0a 02 08 0b 0a 13 08 02 1a 0f
HU::ServiceDiscoveryResponse carInfo;
carInfo.set_head_unit_name(settings["head_unit_name"]);
carInfo.set_car_model(settings["car_model"]);
carInfo.set_car_year(settings["car_year"]);
carInfo.set_car_serial(settings["car_serial"]);
carInfo.set_driver_pos(std::stoi(settings["driver_pos"]));
carInfo.set_headunit_make(settings["headunit_make"]);
carInfo.set_headunit_model(settings["headunit_model"]);
carInfo.set_sw_build(settings["sw_build"]);
carInfo.set_sw_version(settings["sw_version"]);
carInfo.set_can_play_native_media_during_vr(settings["can_play_native_media_during_vr"] == "true");
carInfo.set_hide_clock(settings["hide_clock"] == "true");
carInfo.mutable_channels()->Reserve(MaximumChannel);
HU::ChannelDescriptor *inputChannel = carInfo.add_channels();
inputChannel->set_channel_id(TouchChannel);
{
auto inner = inputChannel->mutable_input_event_channel();
auto tsConfig = inner->mutable_touch_screen_config();
tsConfig->set_width(stoul(settings["ts_width"]));
tsConfig->set_height(stoul(settings["ts_height"]));
// No idea what these mean since they aren't the same as INPUT_BUTTON
inner->add_keycodes_supported(HUIB_MENU); // 0x01 Soft Left (Menu)
inner->add_keycodes_supported(HUIB_MIC1); // 0x02 Soft Right (Mic)
inner->add_keycodes_supported(HUIB_HOME); // 0x03 Home
inner->add_keycodes_supported(HUIB_BACK); // 0x04 Back
inner->add_keycodes_supported(HUIB_PHONE); // 0x05 Call
inner->add_keycodes_supported(HUIB_CALLEND); // 0x06 End Call
inner->add_keycodes_supported(HUIB_UP); // 0x13 Up
inner->add_keycodes_supported(HUIB_DOWN); // 0x14 Down
inner->add_keycodes_supported(HUIB_LEFT); // 0x15 Left (Menu)
inner->add_keycodes_supported(HUIB_RIGHT); // 0x16 Right (Mic)
inner->add_keycodes_supported(HUIB_ENTER); // 0x17 Select
inner->add_keycodes_supported(HUIB_MIC); // 0x54 Search (Mic)
inner->add_keycodes_supported(HUIB_PLAYPAUSE); // 0x55 Play/Pause
inner->add_keycodes_supported(HUIB_NEXT); // 0x57 Next Track
inner->add_keycodes_supported(HUIB_PREV); // 0x58 Prev Track
inner->add_keycodes_supported(HUIB_MUSIC); // 0xD1 Music Screen
inner->add_keycodes_supported(HUIB_SCROLLWHEEL); // 65536 Comand Knob Rotate
inner->add_keycodes_supported(HUIB_TEL); // 65537 Phone
inner->add_keycodes_supported(HUIB_NAVIGATION); // 65538 Navigation
inner->add_keycodes_supported(HUIB_MEDIA); // 65539 Media
// Might as well include these even if we dont use them
inner->add_keycodes_supported(HUIB_RADIO); // 65540 Radio (Doesn't Do Anything)
inner->add_keycodes_supported(HUIB_PRIMARY_BUTTON); // 65541 Primary (Doesn't Do Anything)
inner->add_keycodes_supported(HUIB_SECONDARY_BUTTON); // 65542 Secondary (Doesn't Do Anything)
inner->add_keycodes_supported(HUIB_TERTIARY_BUTTON); // 65543 Tertiary (Doesn't Do Anything)
inner->add_keycodes_supported(HUIB_START); // 0x7E (126) Start Media
inner->add_keycodes_supported(HUIB_STOP); // 0x7F (127) Stop Media
callbacks.CustomizeInputConfig(*inner);
}
HU::ChannelDescriptor *sensorChannel = carInfo.add_channels();
sensorChannel->set_channel_id(SensorChannel);
{
auto inner = sensorChannel->mutable_sensor_channel();
inner->add_sensor_list()->set_type(HU::SENSOR_TYPE_DRIVING_STATUS);
inner->add_sensor_list()->set_type(HU::SENSOR_TYPE_NIGHT_DATA);
inner->add_sensor_list()->set_type(HU::SENSOR_TYPE_LOCATION);
inner->add_sensor_list()->set_type(HU::SENSOR_TYPE_CAR_SPEED);
inner->add_sensor_list()->set_type(HU::SENSOR_TYPE_GEAR);
callbacks.CustomizeSensorConfig(*inner);
}
HU::ChannelDescriptor *videoChannel = carInfo.add_channels();
videoChannel->set_channel_id(VideoChannel);
{
auto inner = videoChannel->mutable_output_stream_channel();
inner->set_type(HU::STREAM_TYPE_VIDEO);
auto videoConfig = inner->add_video_configs();
videoConfig->set_resolution(
static_cast<HU::ChannelDescriptor::OutputStreamChannel::VideoConfig::VIDEO_RESOLUTION>(std::stoi(settings["resolution"])));
videoConfig->set_frame_rate(
static_cast<HU::ChannelDescriptor::OutputStreamChannel::VideoConfig::VIDEO_FPS>(std::stoi(settings["frame_rate"])));
videoConfig->set_margin_width(std::stoi(settings["margin_width"]));
videoConfig->set_margin_height(std::stoi(settings["margin_height"]));
videoConfig->set_dpi(std::stoi(settings["dpi"]));
inner->set_available_while_in_call(settings["available_while_in_call"] == "true");
callbacks.CustomizeOutputChannel(VideoChannel, *inner);
}
HU::ChannelDescriptor *audioChannel0 = carInfo.add_channels();
audioChannel0->set_channel_id(MediaAudioChannel);
{
auto inner = audioChannel0->mutable_output_stream_channel();
inner->set_type(HU::STREAM_TYPE_AUDIO);
inner->set_audio_type(HU::AUDIO_TYPE_MEDIA);
auto audioConfig = inner->add_audio_configs();
audioConfig->set_sample_rate(48000);
audioConfig->set_bit_depth(16);
audioConfig->set_channel_count(2);
inner->set_available_while_in_call(settings["available_while_in_call"] == "true");
callbacks.CustomizeOutputChannel(MediaAudioChannel, *inner);
}
HU::ChannelDescriptor *audioChannel1 = carInfo.add_channels();
audioChannel1->set_channel_id(Audio1Channel);
{
auto inner = audioChannel1->mutable_output_stream_channel();
inner->set_type(HU::STREAM_TYPE_AUDIO);
inner->set_audio_type(HU::AUDIO_TYPE_SPEECH);
auto audioConfig = inner->add_audio_configs();
audioConfig->set_sample_rate(16000);
audioConfig->set_bit_depth(16);
audioConfig->set_channel_count(1);
callbacks.CustomizeOutputChannel(Audio1Channel, *inner);
}
HU::ChannelDescriptor *micChannel = carInfo.add_channels();
micChannel->set_channel_id(MicrophoneChannel);
{
auto inner = micChannel->mutable_input_stream_channel();
inner->set_type(HU::STREAM_TYPE_AUDIO);
auto audioConfig = inner->mutable_audio_config();
audioConfig->set_sample_rate(16000);
audioConfig->set_bit_depth(16);
audioConfig->set_channel_count(1);
callbacks.CustomizeInputChannel(MicrophoneChannel, *inner);
}
HU::ChannelDescriptor *notificationChannel = carInfo.add_channels();
notificationChannel->set_channel_id(NotificationChannel);
HU::ChannelDescriptor *navigationChannel = carInfo.add_channels();
navigationChannel->set_channel_id(NavigationChannel);
{
auto inner = navigationChannel->mutable_navigation_status_service();
inner->set_minimum_interval_ms(1000);
// auto ImageOptions = inner->mutable_image_options();
// ImageOptions->set_width(100);
// ImageOptions->set_height(100);
// ImageOptions->set_colour_depth_bits(8);
inner->set_type(HU::ChannelDescriptor::NavigationStatusService::IMAGE_CODES_ONLY);
}
std::string carBTAddress = callbacks.GetCarBluetoothAddress();
if (carBTAddress.size() > 0) {
logd("Found BT address %s. Exposing Bluetooth service", carBTAddress.c_str());
HU::ChannelDescriptor *btChannel = carInfo.add_channels();
btChannel->set_channel_id(BluetoothChannel);
{
auto inner = btChannel->mutable_bluetooth_service();
inner->set_car_address(carBTAddress);
inner->add_supported_pairing_methods(HU::BLUETOOTH_PARING_METHOD_A2DP);
inner->add_supported_pairing_methods(HU::BLUETOOTH_PARING_METHOD_HFP);
callbacks.CustomizeBluetoothService(BluetoothChannel, *inner);
}
HU::ChannelDescriptor *phoneStatusChannel = carInfo.add_channels();
phoneStatusChannel->set_channel_id(PhoneStatusChannel);
} else {
logw("No Bluetooth or finding BT address failed. Not exposing Bluetooth "
"service");
}
callbacks.CustomizeCarInfo(carInfo);
return sendEncodedMessage(0, chan, PROTOCOL_MESSAGE::ServiceDiscoveryResponse, carInfo);
}
int HUServer::handle_PingRequest(ServiceChannels chan, byte *buf,
int len) { // Ping Request
HU::PingRequest request;
if (!request.ParseFromArray(buf, len))
loge("Ping Request");
else
logd("Ping Request: %d", buf[3]);
HU::PingResponse response;
response.set_timestamp(request.timestamp());
return sendEncodedMessage(0, chan, PROTOCOL_MESSAGE::PingResponse, response);
}
int HUServer::handle_NavigationFocusRequest(ServiceChannels chan, byte *buf,
int len) { // Navigation Focus Request
HU::NavigationFocusRequest request;
if (!request.ParseFromArray(buf, len))
loge("Navigation Focus Request");
else
logd("Navigation Focus Request: %d", request.focus_type());
HU::NavigationFocusResponse response;
response.set_focus_type(2); // Gained / Gained Transient ?
return sendEncodedMessage(0, chan, PROTOCOL_MESSAGE::NavigationFocusResponse, response);
}
int HUServer::handle_ShutdownRequest(ServiceChannels chan, byte *buf,
int len) { // Byebye Request
HU::ShutdownRequest request;
if (!request.ParseFromArray(buf, len))
loge("Byebye Request");
else if (request.reason() == 1)
logd("Byebye Request reason: 1 AA Exit Car Mode");
else
loge("Byebye Request reason: %d", request.reason());
HU::ShutdownResponse response;
sendEncodedMessage(0, chan, PROTOCOL_MESSAGE::ShutdownResponse, response);
ms_sleep(100); // Wait a bit for response
stop();
return (-1);
}
int HUServer::handle_VoiceSessionRequest(ServiceChannels chan, byte *buf,
int len) { // sr: 00000000 00 11 08 01 Microphone voice search usage
// sr: 00000000 00 11 08 02
HU::VoiceSessionRequest request;
if (!request.ParseFromArray(buf, len))
loge("Voice Session Notification");
else if (request.voice_status() == HU::VoiceSessionRequest::VOICE_STATUS_START)
logd("Voice Session Notification: 1 START");
else if (request.voice_status() == HU::VoiceSessionRequest::VOICE_STATUS_STOP)
logd("Voice Session Notification: 2 STOP");
else
loge("Voice Session Notification: %d", request.voice_status());
return (0);
}
int HUServer::handle_AudioFocusRequest(ServiceChannels chan, byte *buf,
int len) { // Navigation Focus Request
HU::AudioFocusRequest request;
if (!request.ParseFromArray(buf, len))
loge("AudioFocusRequest Focus Request");
else
logd("AudioFocusRequest Focus Request %s: %d", getChannel(chan), request.focus_type());
callbacks.AudioFocusRequest(chan, request);
return 0;
}
int HUServer::handle_ChannelOpenRequest(ServiceChannels chan, byte *buf,
int len) { // Channel Open Request
HU::ChannelOpenRequest request;
if (!request.ParseFromArray(buf, len))
loge("Channel Open Request");
else
logd("Channel Open Request: %d priority: %d", request.id(), request.priority());
HU::ChannelOpenResponse response;
response.set_status(HU::STATUS_OK);
int ret = sendEncodedMessage(0, chan, PROTOCOL_MESSAGE::ChannelOpenResponse, response);
if (ret) // If error, done with error
return (ret);
if (chan == SensorChannel) { // If Sensor channel...
ms_sleep(2); // 20);
HU::SensorEvent sensorEvent;
sensorEvent.add_driving_status()->set_status(HU::SensorEvent::DrivingStatus::DRIVE_STATUS_UNRESTRICTED);
return sendEncodedMessage(0, SensorChannel, SENSOR_CHANNEL_MESSAGE::SensorEvent, sensorEvent);
}
return (ret);
}
int HUServer::handle_MediaSetupRequest(ServiceChannels chan, byte *buf, int len) {
HU::MediaSetupRequest request;
if (!request.ParseFromArray(buf, len))
loge("MediaSetupRequest");
else
logd("MediaSetupRequest: %d", request.type());
HU::MediaSetupResponse response;
response.set_media_status(HU::MediaSetupResponse::MEDIA_STATUS_2);
response.set_max_unacked(1);
response.add_configs(0);
int ret = sendEncodedMessage(0, chan, MEDIA_CHANNEL_MESSAGE::MediaSetupResponse, response);
if (!ret) {
callbacks.MediaSetupComplete(chan);
}
return (ret);
}
int HUServer::handle_VideoFocusRequest(ServiceChannels chan, byte *buf, int len) {
HU::VideoFocusRequest request;
if (!request.ParseFromArray(buf, len))
loge("VideoFocusRequest");
else
logd("VideoFocusRequest: %d", request.disp_index());
callbacks.VideoFocusRequest(chan, request);
return 0;
}
int HUServer::handle_MediaStartRequest(ServiceChannels chan, byte *buf,
int len) { // sr: 00000000 00 11 08 01 Microphone voice search usage
// sr: 00000000 00 11 08 02
HU::MediaStartRequest request;
if (!request.ParseFromArray(buf, len))
loge("MediaStartRequest");
else
logd("MediaStartRequest: %d", request.session());
channel_session_id[chan] = request.session();
return callbacks.MediaStart(chan);
}
int HUServer::handle_MediaStopRequest(ServiceChannels chan, byte *buf,
int len) { // sr: 00000000 00 11 08 01 Microphone voice search usage
// sr: 00000000 00 11 08 02
HU::MediaStopRequest request;
if (!request.ParseFromArray(buf, len))
loge("MediaStopRequest");
else
logd("MediaStopRequest");
channel_session_id[chan] = 0;
return callbacks.MediaStop(chan);
}
int HUServer::handle_SensorStartRequest(ServiceChannels chan, byte *buf,
int len) { // Navigation Focus Request
HU::SensorStartRequest request;
if (!request.ParseFromArray(buf, len))
loge("SensorStartRequest Focus Request");
else
logd("SensorStartRequest Focus Request: %d", request.type());
HU::SensorStartResponse response;
response.set_status(HU::STATUS_OK);
return sendEncodedMessage(0, chan, SENSOR_CHANNEL_MESSAGE::SensorStartResponse, response);
}
int HUServer::handle_BindingRequest(ServiceChannels chan, byte *buf,
int len) { // Navigation Focus Request
HU::BindingRequest request;
if (!request.ParseFromArray(buf, len))
loge("BindingRequest Focus Request");
else
logd("BindingRequest Focus Request: %d", request.scan_codes_size());
HU::BindingResponse response;
response.set_status(HU::STATUS_OK);
return sendEncodedMessage(0, chan, INPUT_CHANNEL_MESSAGE::BindingResponse, response);
}
int HUServer::handle_MediaAck(ServiceChannels chan, byte *buf, int len) {
HU::MediaAck request;
if (!request.ParseFromArray(buf, len))
loge("MediaAck");
else
logd("MediaAck");
return (0);
}
int HUServer::handle_MicRequest(ServiceChannels chan, byte *buf, int len) {
HU::MicRequest request;
if (!request.ParseFromArray(buf, len))
loge("MicRequest");
else
logd("MicRequest");
if (!request.open()) {
logd("Mic Start/Stop Request: 0 STOP");
return callbacks.MediaStop(chan);
} else {
logd("Mic Start/Stop Request: 1 START");
return callbacks.MediaStart(chan);
}
return (0);
}
int HUServer::handle_MediaDataWithTimestamp(ServiceChannels chan, byte *buf, int len) {
uint64_t timestamp = be64toh(*((uint64_t *)buf));
logd("Media timestamp %s %llu", getChannel(chan), timestamp);
int ret = callbacks.MediaPacket(chan, timestamp, &buf[8], len - 8);
if (ret < 0) {
return ret;
}
HU::MediaAck mediaAck;
mediaAck.set_session(channel_session_id[chan]);
mediaAck.set_value(1);
return sendEncodedMessage(0, chan, MEDIA_CHANNEL_MESSAGE::MediaAck, mediaAck);
}
int HUServer::handle_MediaData(ServiceChannels chan, byte *buf, int len) {
int ret = callbacks.MediaPacket(chan, 0, buf, len);
if (ret < 0) {
return ret;
}
HU::MediaAck mediaAck;
mediaAck.set_session(channel_session_id[chan]);
mediaAck.set_value(1);
return sendEncodedMessage(0, chan, MEDIA_CHANNEL_MESSAGE::MediaAck, mediaAck);
}
int HUServer::handle_PhoneStatus(ServiceChannels chan, byte *buf, int len) {
HU::PhoneStatus request;
if (!request.ParseFromArray(buf, len)) {
loge("PhoneStatus Focus Request");
return -1;
} else {
logd("PhoneStatus Focus Request");
}
callbacks.HandlePhoneStatus(*this, request);
return 0;
}
int HUServer::handle_GenericNotificationResponse(ServiceChannels chan, byte *buf, int len) {
HU::GenericNotificationResponse request;
if (!request.ParseFromArray(buf, len)) {
loge("GenericNotificationResponse Focus Request");
return -1;
} else {
logd("GenericNotificationResponse Focus Request");
}
callbacks.HandleGenericNotificationResponse(*this, request);
return 0;
}
int HUServer::handle_StartGenericNotifications(ServiceChannels chan, byte *buf, int len) {
HU::StartGenericNotifications request;
if (!request.ParseFromArray(buf, len)) {
loge("StartGenericNotifications Focus Request");
return -1;
} else {
logd("StartGenericNotifications Focus Request");
}
callbacks.ShowingGenericNotifications(*this, true);
return 0;
}
int HUServer::handle_StopGenericNotifications(ServiceChannels chan, byte *buf, int len) {
HU::StopGenericNotifications request;
if (!request.ParseFromArray(buf, len)) {
loge("StopGenericNotifications Focus Request");
return -1;
} else {
logd("StopGenericNotifications Focus Request");
}
callbacks.ShowingGenericNotifications(*this, false);
return 0;
}
int HUServer::handle_BluetoothPairingRequest(ServiceChannels chan, byte *buf, int len) {
HU::BluetoothPairingRequest request;
if (!request.ParseFromArray(buf, len)) {
loge("BluetoothPairingRequest Focus Request");
return -1;
} else {
logd("BluetoothPairingRequest Focus Request");
}
printf("BluetoothPairingRequest: %s\n", request.DebugString().c_str());
HU::BluetoothPairingResponse response;
response.set_already_paired(true);
response.set_status(HU::BluetoothPairingResponse::PAIRING_STATUS_1);
return sendEncodedMessage(0, chan, BLUETOOTH_CHANNEL_MESSAGE::BluetoothPairingResponse, response);
}
int HUServer::handle_BluetoothAuthData(ServiceChannels chan, byte *buf, int len) {
HU::BluetoothAuthData request;
if (!request.ParseFromArray(buf, len)) {
loge("BluetoothAuthData Focus Request");
return -1;
} else {
logd("BluetoothAuthData Focus Request");
}
printf("BluetoothAuthData: %s\n", request.DebugString().c_str());
return 0;
}
int HUServer::handle_NaviStatus(ServiceChannels chan, byte *buf, int len) {
HU::NAVMessagesStatus request;
if (!request.ParseFromArray(buf, len)) {
logv("NaviStatus Request");
logv(request.DebugString().c_str());
return -1;
} else {
logv("NaviStatus Request");
}
callbacks.HandleNaviStatus(*this, request);
return 0;
}
int HUServer::handle_NaviTurn(ServiceChannels chan, byte *buf, int len) {
HU::NAVTurnMessage request;
if (!request.ParseFromArray(buf, len)) {
logv("NaviTurn Request");
logv(request.DebugString().c_str());
return -1;
} else {
logv("NaviTurn Request");
}
callbacks.HandleNaviTurn(*this, request);
return 0;
}
int HUServer::handle_NaviTurnDistance(ServiceChannels chan, byte *buf, int len) {
HU::NAVDistanceMessage request;
if (!request.ParseFromArray(buf, len)) {
logv("NaviTurnDistance Request");
logv(request.DebugString().c_str());
return -1;
} else {
logv("NaviTurnDistance Request");
}
callbacks.HandleNaviTurnDistance(*this, request);
return 0;
}
int HUServer::processMessage(ServiceChannels chan, uint16_t msg_type, byte *buf, int len) {
if (ena_log_verbo)
logd("iaap_msg_process msg_type: %d len: %d buf: %p", msg_type, len, buf);
int filter_ret = callbacks.MessageFilter(*this, iaap_state, chan, msg_type, buf, len);
if (filter_ret < 0) {
return filter_ret;
} else if (filter_ret > 0) {
return 0; // handled
}
if (iaap_state == HU_STATE::hu_STATE_STARTIN) {
switch ((INIT_MESSAGE)msg_type) {
case INIT_MESSAGE::VersionResponse:
return handle_VersionResponse(chan, buf, len);
case INIT_MESSAGE::SSLHandshake:
return handleSSLHandshake(buf, len);
default:
logw("Unknown msg_type: %d", msg_type);
return (0);
}
} else {
const bool isControlMessage = msg_type < 0x8000;
if (isControlMessage) {
switch ((PROTOCOL_MESSAGE)msg_type) {
case PROTOCOL_MESSAGE::MediaDataWithTimestamp:
return handle_MediaDataWithTimestamp(chan, buf, len);
case PROTOCOL_MESSAGE::MediaData:
return handle_MediaData(chan, buf, len);
case PROTOCOL_MESSAGE::ServiceDiscoveryRequest:
return handle_ServiceDiscoveryRequest(chan, buf, len);
case PROTOCOL_MESSAGE::ChannelOpenRequest:
return handle_ChannelOpenRequest(chan, buf, len);
case PROTOCOL_MESSAGE::PingRequest:
return handle_PingRequest(chan, buf, len);
case PROTOCOL_MESSAGE::NavigationFocusRequest:
return handle_NavigationFocusRequest(chan, buf, len);
case PROTOCOL_MESSAGE::ShutdownRequest:
return handle_ShutdownRequest(chan, buf, len);
case PROTOCOL_MESSAGE::VoiceSessionRequest:
return handle_VoiceSessionRequest(chan, buf, len);
case PROTOCOL_MESSAGE::AudioFocusRequest:
return handle_AudioFocusRequest(chan, buf, len);
default:
logw("Unknown msg_type: %d", msg_type);
return (0);
}
} else if (chan == SensorChannel) {
switch ((SENSOR_CHANNEL_MESSAGE)msg_type) {
case SENSOR_CHANNEL_MESSAGE::SensorStartRequest:
return handle_SensorStartRequest(chan, buf, len);
default:
logw("Unknown msg_type: %d", msg_type);
return (0);
}
} else if (chan == TouchChannel) {
switch ((INPUT_CHANNEL_MESSAGE)msg_type) {
case INPUT_CHANNEL_MESSAGE::BindingRequest:
return handle_BindingRequest(chan, buf, len);
default:
logw("Unknown msg_type: %d", msg_type);
return (0);
}
} else if (chan == BluetoothChannel) {
switch ((BLUETOOTH_CHANNEL_MESSAGE)msg_type) {
case BLUETOOTH_CHANNEL_MESSAGE::BluetoothPairingRequest:
return handle_BluetoothPairingRequest(chan, buf, len);
case BLUETOOTH_CHANNEL_MESSAGE::BluetoothAuthData:
return handle_BluetoothAuthData(chan, buf, len);
default:
logw("BLUETOOTH CHANNEL MESSAGE = chan %d - msg_type: %d", chan, msg_type);
return (0);
}
} else if (chan == PhoneStatusChannel) {
switch ((PHONE_STATUS_CHANNEL_MESSAGE)msg_type) {
case PHONE_STATUS_CHANNEL_MESSAGE::PhoneStatus:
return handle_PhoneStatus(chan, buf, len);
default:
logw("Unknown msg_type: %d", msg_type);
return (0);
}
} else if (chan == NotificationChannel) {