aboutsummaryrefslogtreecommitdiff
path: root/bta/hf_client/bta_hf_client_at.cc
blob: f2fcf829543c651a6e1d874a0658a81dd39da259 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
/******************************************************************************
 *
 *  Copyright (c) 2014 The Android Open Source Project
 *  Copyright 2003-2012 Broadcom Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 ******************************************************************************/

#define LOG_TAG "bt_hf_client"

#include "bt_trace.h"  // Legacy trace logging

#include "bta/hf_client/bta_hf_client_int.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
#include "osi/include/log.h"
#include "stack/include/port_api.h"

/* Uncomment to enable AT traffic dumping */
/* #define BTA_HF_CLIENT_AT_DUMP 1 */

/* minimum length of AT event */
#define BTA_HF_CLIENT_AT_EVENT_MIN_LEN 3

/* timeout (in milliseconds) for AT response */
#define BTA_HF_CLIENT_AT_TIMEOUT 29989

/* timeout (in milliseconds) for AT hold timer */
#define BTA_HF_CLIENT_AT_HOLD_TIMEOUT 41

/******************************************************************************
 *       SUPPORTED EVENT MESSAGES
 ******************************************************************************/

/* CIND: supported indicator names */
#define BTA_HF_CLIENT_INDICATOR_BATTERYCHG "battchg"
#define BTA_HF_CLIENT_INDICATOR_SIGNAL "signal"
#define BTA_HF_CLIENT_INDICATOR_SERVICE "service"
#define BTA_HF_CLIENT_INDICATOR_CALL "call"
#define BTA_HF_CLIENT_INDICATOR_ROAM "roam"
#define BTA_HF_CLIENT_INDICATOR_CALLSETUP "callsetup"
#define BTA_HF_CLIENT_INDICATOR_CALLHELD "callheld"

/* BIND parse mode */
#define BTA_HF_CLIENT_BIND_PARSE_READ_ENABLED_IND 0
#define BTA_HF_CLIENT_BIND_PARSE_READ_SUPPOETED_IND 1

#define MIN(a, b)           \
  ({                        \
    __typeof__(a) _a = (a); \
    __typeof__(b) _b = (b); \
    (_a < _b) ? _a : _b;    \
  })

/* CIND: represents each indicators boundaries */
typedef struct {
  const char* name;
  uint8_t min;
  uint8_t max;
  uint8_t namelen;
} tBTA_HF_CLIENT_INDICATOR;

#define BTA_HF_CLIENT_AT_SUPPORTED_INDICATOR_COUNT 7

/* CIND: storage room for indicators value range and their statuses */
static const tBTA_HF_CLIENT_INDICATOR
    bta_hf_client_indicators[BTA_HF_CLIENT_AT_SUPPORTED_INDICATOR_COUNT] = {
        /* name                                | min | max | name length -
           used by parser */
        {BTA_HF_CLIENT_INDICATOR_BATTERYCHG, 0, 5,
         sizeof(BTA_HF_CLIENT_INDICATOR_BATTERYCHG)},
        {BTA_HF_CLIENT_INDICATOR_SIGNAL, 0, 5,
         sizeof(BTA_HF_CLIENT_INDICATOR_SIGNAL)},
        {BTA_HF_CLIENT_INDICATOR_SERVICE, 0, 1,
         sizeof(BTA_HF_CLIENT_INDICATOR_SERVICE)},
        {BTA_HF_CLIENT_INDICATOR_CALL, 0, 1,
         sizeof(BTA_HF_CLIENT_INDICATOR_CALL)},
        {BTA_HF_CLIENT_INDICATOR_ROAM, 0, 1,
         sizeof(BTA_HF_CLIENT_INDICATOR_ROAM)},
        {BTA_HF_CLIENT_INDICATOR_CALLSETUP, 0, 3,
         sizeof(BTA_HF_CLIENT_INDICATOR_CALLSETUP)},
        {BTA_HF_CLIENT_INDICATOR_CALLHELD, 0, 2,
         sizeof(BTA_HF_CLIENT_INDICATOR_CALLHELD)}};

/* +VGM/+VGS - gain min/max values  */
#define BTA_HF_CLIENT_VGS_MIN 0
#define BTA_HF_CLIENT_VGS_MAX 15
#define BTA_HF_CLIENT_VGM_MIN 0
#define BTA_HF_CLIENT_VGM_MAX 15

uint32_t service_index = 0;
bool service_availability = true;
/* helper functions for handling AT commands queueing */

static void bta_hf_client_handle_ok(tBTA_HF_CLIENT_CB* client_cb);

static void bta_hf_client_clear_queued_at(tBTA_HF_CLIENT_CB* client_cb) {
  tBTA_HF_CLIENT_AT_QCMD* cur = client_cb->at_cb.queued_cmd;
  tBTA_HF_CLIENT_AT_QCMD* next;

  while (cur != NULL) {
    next = cur->next;
    osi_free(cur);
    cur = next;
  }

  client_cb->at_cb.queued_cmd = NULL;
}

static void bta_hf_client_queue_at(tBTA_HF_CLIENT_CB* client_cb,
                                   tBTA_HF_CLIENT_AT_CMD cmd, const char* buf,
                                   uint16_t buf_len) {
  tBTA_HF_CLIENT_AT_QCMD* new_cmd =
      (tBTA_HF_CLIENT_AT_QCMD*)osi_malloc(sizeof(tBTA_HF_CLIENT_AT_QCMD));

  APPL_TRACE_DEBUG("%s", __func__);

  new_cmd->cmd = cmd;
  new_cmd->buf_len = buf_len;
  new_cmd->next = NULL;
  memcpy(new_cmd->buf, buf, buf_len);

  if (client_cb->at_cb.queued_cmd != NULL) {
    tBTA_HF_CLIENT_AT_QCMD* qcmd = client_cb->at_cb.queued_cmd;

    while (qcmd->next != NULL) qcmd = qcmd->next;

    qcmd->next = new_cmd;
  } else {
    client_cb->at_cb.queued_cmd = new_cmd;
  }
}

static void bta_hf_client_at_resp_timer_cback(void* data) {
  tBTA_HF_CLIENT_CB* client_cb = (tBTA_HF_CLIENT_CB*)data;
  if (client_cb->at_cb.current_cmd == BTA_HF_CLIENT_AT_CNUM) {
    LOG_INFO("%s: timed out waiting for AT+CNUM response; spoofing OK.",
             __func__);
    bta_hf_client_handle_ok(client_cb);
  } else {
    APPL_TRACE_ERROR("HFPClient: AT response timeout, disconnecting");

    tBTA_HF_CLIENT_DATA msg = {};
    msg.hdr.layer_specific = client_cb->handle;
    bta_hf_client_sm_execute(BTA_HF_CLIENT_API_CLOSE_EVT, &msg);
  }
}

static void bta_hf_client_start_at_resp_timer(tBTA_HF_CLIENT_CB* client_cb) {
  alarm_set_on_mloop(client_cb->at_cb.resp_timer, BTA_HF_CLIENT_AT_TIMEOUT,
                     bta_hf_client_at_resp_timer_cback, (void*)client_cb);
}

static void bta_hf_client_stop_at_resp_timer(tBTA_HF_CLIENT_CB* client_cb) {
  alarm_cancel(client_cb->at_cb.resp_timer);
}

static void bta_hf_client_send_at(tBTA_HF_CLIENT_CB* client_cb,
                                  tBTA_HF_CLIENT_AT_CMD cmd, const char* buf,
                                  uint16_t buf_len) {
  APPL_TRACE_DEBUG("%s", __func__);
  if ((client_cb->at_cb.current_cmd == BTA_HF_CLIENT_AT_NONE ||
       !client_cb->svc_conn) &&
      !alarm_is_scheduled(client_cb->at_cb.hold_timer)) {
    uint16_t len;

#ifdef BTA_HF_CLIENT_AT_DUMP
    APPL_TRACE_DEBUG("%s: %.*s", __func__, buf_len - 1, buf);
#endif

    client_cb->at_cb.current_cmd = cmd;
    /* Generate fake responses for these because they won't reliably work */
    if (!service_availability &&
        (cmd == BTA_HF_CLIENT_AT_CNUM || cmd == BTA_HF_CLIENT_AT_COPS)) {
      APPL_TRACE_WARNING("%s: No service, skipping %d command", __func__, cmd);
      bta_hf_client_handle_ok(client_cb);
      return;
    }

    APPL_TRACE_DEBUG("%s: writing port data to %d", __func__,
                     client_cb->conn_handle);
    PORT_WriteData(client_cb->conn_handle, buf, buf_len, &len);

    bta_hf_client_start_at_resp_timer(client_cb);

    return;
  }

  bta_hf_client_queue_at(client_cb, cmd, buf, buf_len);
}

static void bta_hf_client_send_queued_at(tBTA_HF_CLIENT_CB* client_cb) {
  tBTA_HF_CLIENT_AT_QCMD* cur = client_cb->at_cb.queued_cmd;

  APPL_TRACE_DEBUG("%s", __func__);

  if (cur != NULL) {
    client_cb->at_cb.queued_cmd = cur->next;

    bta_hf_client_send_at(client_cb, cur->cmd, cur->buf, cur->buf_len);

    osi_free(cur);
  }
}

static void bta_hf_client_at_hold_timer_cback(void* data) {
  tBTA_HF_CLIENT_CB* client_cb = (tBTA_HF_CLIENT_CB*)data;
  APPL_TRACE_DEBUG("%s", __func__);
  bta_hf_client_send_queued_at(client_cb);
}

static void bta_hf_client_stop_at_hold_timer(tBTA_HF_CLIENT_CB* client_cb) {
  APPL_TRACE_DEBUG("%s", __func__);
  alarm_cancel(client_cb->at_cb.hold_timer);
}

static void bta_hf_client_start_at_hold_timer(tBTA_HF_CLIENT_CB* client_cb) {
  APPL_TRACE_DEBUG("%s", __func__);
  alarm_set_on_mloop(client_cb->at_cb.hold_timer, BTA_HF_CLIENT_AT_HOLD_TIMEOUT,
                     bta_hf_client_at_hold_timer_cback, (void*)client_cb);
}

/******************************************************************************
 *
 *          COMMON AT EVENT HANDLING funcS
 *
 *   Receives data (strings, ints, etc.) from the parser and processes this
 *   data. No buffer parsing is being done here.
 ******************************************************************************/

static void bta_hf_client_handle_ok(tBTA_HF_CLIENT_CB* client_cb) {
  APPL_TRACE_DEBUG("%s", __func__);

  bta_hf_client_stop_at_resp_timer(client_cb);

  if (!client_cb->svc_conn) {
    bta_hf_client_slc_seq(client_cb, false);
    return;
  }

  switch (client_cb->at_cb.current_cmd) {
    case BTA_HF_CLIENT_AT_BIA:
    case BTA_HF_CLIENT_AT_BCC:
      break;
    case BTA_HF_CLIENT_AT_BCS:
      bta_hf_client_start_at_hold_timer(client_cb);
      client_cb->at_cb.current_cmd = BTA_HF_CLIENT_AT_NONE;
      return;
    case BTA_HF_CLIENT_AT_CLIP:  // last cmd is post slc seq
      if (!client_cb->send_at_reply) {
        client_cb->send_at_reply = true;
      }
      break;
    case BTA_HF_CLIENT_AT_NONE:
      bta_hf_client_stop_at_hold_timer(client_cb);
      break;
    default:
      if (client_cb->send_at_reply) {
        bta_hf_client_at_result(client_cb, BTA_HF_CLIENT_AT_RESULT_OK, 0);
      }
      break;
  }

  client_cb->at_cb.current_cmd = BTA_HF_CLIENT_AT_NONE;

  bta_hf_client_send_queued_at(client_cb);
}

static void bta_hf_client_handle_error(tBTA_HF_CLIENT_CB* client_cb,
                                       tBTA_HF_CLIENT_AT_RESULT_TYPE type,
                                       uint16_t cme) {
  APPL_TRACE_DEBUG("%s: %u %u", __func__, type, cme);

  bta_hf_client_stop_at_resp_timer(client_cb);

  if (!client_cb->svc_conn) {
    bta_hf_client_slc_seq(client_cb, true);
    return;
  }

  switch (client_cb->at_cb.current_cmd) {
    case BTA_HF_CLIENT_AT_BIA:
      break;
    case BTA_HF_CLIENT_AT_BCC:
    case BTA_HF_CLIENT_AT_BCS:
      bta_hf_client_cback_sco(client_cb, BTA_HF_CLIENT_AUDIO_CLOSE_EVT);
      break;
    case BTA_HF_CLIENT_AT_CLIP:  // last cmd is post slc seq
      if (!client_cb->send_at_reply) {
        client_cb->send_at_reply = true;
      }
      break;
    default:
      if (client_cb->send_at_reply) {
        bta_hf_client_at_result(client_cb, type, cme);
      }
      break;
  }

  client_cb->at_cb.current_cmd = BTA_HF_CLIENT_AT_NONE;

  bta_hf_client_send_queued_at(client_cb);
}

static void bta_hf_client_handle_ring(tBTA_HF_CLIENT_CB* client_cb) {
  APPL_TRACE_DEBUG("%s", __func__);
  bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_RING_INDICATION, 0);
}

static void bta_hf_client_handle_brsf(tBTA_HF_CLIENT_CB* client_cb,
                                      uint32_t value) {
  APPL_TRACE_DEBUG("%s: 0x%x", __func__, value);
  client_cb->peer_features = value;
}

/* handles a single indicator descriptor - registers it for value changing
 * events */
static void bta_hf_client_handle_cind_list_item(tBTA_HF_CLIENT_CB* client_cb,
                                                char* name, uint32_t min,
                                                uint32_t max, uint32_t index) {
  uint8_t i = 0;

  APPL_TRACE_DEBUG("%s: %lu.%s <%lu:%lu>", __func__, index, name, min, max);

  /* look for a matching indicator on list of supported ones */
  for (i = 0; i < BTA_HF_CLIENT_AT_SUPPORTED_INDICATOR_COUNT; i++) {
    if (strcmp(name, BTA_HF_CLIENT_INDICATOR_SERVICE) == 0) {
      service_index = index;
    }
    /* look for a match - search one sign further than indicators name to check
     * for string end */
    /* It will distinguish 'callheld' which could be matched by strncmp as
     * 'call'.               */
    if (strncmp(name, bta_hf_client_indicators[i].name,
                bta_hf_client_indicators[i].namelen) != 0)
      continue;

    /* index - enumerates value position in the incoming sequence */
    /* if name matches one of the known indicators, add its incoming position */
    /* to lookup table for easy value->indicator matching later, when only
     * values come  */
    client_cb->at_cb.indicator_lookup[index] = i;

    return;
  }
}

static void bta_hf_client_handle_cind_value(tBTA_HF_CLIENT_CB* client_cb,
                                            uint32_t index, uint32_t value) {
  APPL_TRACE_DEBUG("%s: index: %u value: %u", __func__, index, value);

  if (index >= BTA_HF_CLIENT_AT_INDICATOR_COUNT) {
    return;
  }

  if (service_index == index) {
    if (value == 0) {
      service_availability = false;
    } else {
      service_availability = true;
    }
  }
  if (client_cb->at_cb.indicator_lookup[index] == -1) {
    return;
  }

  /* get the real array index from lookup table */
  index = client_cb->at_cb.indicator_lookup[index];

  /* Ignore out of range values */
  if (value > bta_hf_client_indicators[index].max ||
      value < bta_hf_client_indicators[index].min) {
    return;
  }

  /* tBTA_HF_CLIENT_IND_TYPE match index in bta_hf_client_indicators */
  bta_hf_client_ind(client_cb, index, value);
}

static void bta_hf_client_handle_chld(tBTA_HF_CLIENT_CB* client_cb,
                                      uint32_t mask) {
  APPL_TRACE_DEBUG("%s: 0x%x", __func__, mask);

  client_cb->chld_features |= mask;
}

static void bta_hf_client_handle_bind_read_supported_ind(
    tBTA_HF_CLIENT_CB* client_cb, int indicator_id) {
  APPL_TRACE_DEBUG("%s: %d", __func__, indicator_id);

  client_cb->peer_hf_indicators.insert(indicator_id);
}

static void bta_hf_client_handle_bind_read_enabled_ind(
    tBTA_HF_CLIENT_CB* client_cb, int indicator_id, bool enable) {
  APPL_TRACE_DEBUG("%s: %d", __func__, indicator_id);

  if (enable) {
    client_cb->enabled_hf_indicators.insert(indicator_id);
  } else {
    client_cb->enabled_hf_indicators.erase(indicator_id);
  }
}

static void bta_hf_client_handle_ciev(tBTA_HF_CLIENT_CB* client_cb,
                                      uint32_t index, uint32_t value) {
  int8_t realind = -1;

  APPL_TRACE_DEBUG("%s: index: %u value: %u", __func__, index, value);

  if (index == 0 || index > BTA_HF_CLIENT_AT_INDICATOR_COUNT) {
    return;
  }

  if (service_index == index - 1) {
    service_availability = value == 0 ? false : true;
  }

  realind = client_cb->at_cb.indicator_lookup[index - 1];

  if (realind >= 0 && realind < BTA_HF_CLIENT_AT_SUPPORTED_INDICATOR_COUNT) {
    /* get the real in-array index from lookup table by index it comes at */
    /* if there is no bug it should automatically be correctly calculated    */
    if (value > bta_hf_client_indicators[realind].max ||
        value < bta_hf_client_indicators[realind].min) {
      return;
    }

    /* update service availability on +ciev from AG. */
    if (service_index == (index - 1)) {
      if (value == 1) {
        service_availability = true;
      } else {
        service_availability = false;
      }
    }

    /* tBTA_HF_CLIENT_IND_TYPE match index in bta_hf_client_indicators */
    bta_hf_client_ind(client_cb, realind, value);
  }
}

static void bta_hf_client_handle_bcs(tBTA_HF_CLIENT_CB* client_cb,
                                     uint32_t codec) {
  APPL_TRACE_DEBUG("%s: codec: %u sco listen state: %d", __func__, codec,
                   client_cb->sco_state);
  if (codec == BTM_SCO_CODEC_CVSD || codec == BTM_SCO_CODEC_MSBC) {
    client_cb->negotiated_codec = codec;
    bta_hf_client_send_at_bcs(client_cb, codec);
  } else {
    client_cb->negotiated_codec = BTM_SCO_CODEC_CVSD;
    bta_hf_client_send_at_bac(client_cb);
  }
}

static void bta_hf_client_handle_bsir(tBTA_HF_CLIENT_CB* client_cb,
                                      uint32_t provided) {
  APPL_TRACE_DEBUG("%s: %u", __func__, provided);

  bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_BSIR_EVT, provided);
}

static void bta_hf_client_handle_cmeerror(tBTA_HF_CLIENT_CB* client_cb,
                                          uint32_t code) {
  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_CME, code);
}

static void bta_hf_client_handle_vgm(tBTA_HF_CLIENT_CB* client_cb,
                                     uint32_t value) {
  APPL_TRACE_DEBUG("%s: %lu", __func__, value);

  if (value <= BTA_HF_CLIENT_VGM_MAX) {
    bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_MIC_EVT, value);
  }
}

static void bta_hf_client_handle_vgs(tBTA_HF_CLIENT_CB* client_cb,
                                     uint32_t value) {
  APPL_TRACE_DEBUG("%s: %lu", __func__, value);

  if (value <= BTA_HF_CLIENT_VGS_MAX) {
    bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_SPK_EVT, value);
  }
}

static void bta_hf_client_handle_bvra(tBTA_HF_CLIENT_CB* client_cb,
                                      uint32_t value) {
  APPL_TRACE_DEBUG("%s: %lu", __func__, value);

  if (value > 1) {
    return;
  }

  bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_VOICE_REC_EVT, value);
}

static void bta_hf_client_handle_clip(tBTA_HF_CLIENT_CB* client_cb,
                                      char* numstr, uint32_t type) {
  APPL_TRACE_DEBUG("%s: %u %s", __func__, type, numstr);

  bta_hf_client_clip(client_cb, numstr);
}

static void bta_hf_client_handle_ccwa(tBTA_HF_CLIENT_CB* client_cb,
                                      char* numstr, uint32_t type) {
  APPL_TRACE_DEBUG("%s: %u %s", __func__, type, numstr);

  bta_hf_client_ccwa(client_cb, numstr);
}

static void bta_hf_client_handle_cops(tBTA_HF_CLIENT_CB* client_cb, char* opstr,
                                      uint32_t mode) {
  APPL_TRACE_DEBUG("%s: %u %s", __func__, mode, opstr);

  bta_hf_client_operator_name(client_cb, opstr);
}

static void bta_hf_client_handle_binp(tBTA_HF_CLIENT_CB* client_cb,
                                      char* numstr) {
  APPL_TRACE_DEBUG("%s: %s", __func__, numstr);

  bta_hf_client_binp(client_cb, numstr);
}

static void bta_hf_client_handle_clcc(tBTA_HF_CLIENT_CB* client_cb,
                                      uint16_t idx, uint16_t dir,
                                      uint16_t status, uint16_t mode,
                                      uint16_t mpty, char* numstr,
                                      uint16_t type) {
  APPL_TRACE_DEBUG("%s: idx: %u dir: %u status: %u mode: %u mpty: %u", __func__,
                   idx, dir, status, mode, mpty);

  if (numstr) {
    APPL_TRACE_DEBUG("%s: number: %s  type: %u", __func__, numstr, type);
  }

  bta_hf_client_clcc(client_cb, idx, dir, status, mpty, numstr);
}

static void bta_hf_client_handle_cnum(tBTA_HF_CLIENT_CB* client_cb,
                                      char* numstr, uint16_t type,
                                      uint16_t service) {
  APPL_TRACE_DEBUG("%s: number: %s type: %u service: %u", __func__, numstr,
                   type, service);

  /* TODO: should number be modified according to type? */
  bta_hf_client_cnum(client_cb, numstr, service);
}

static void bta_hf_client_handle_btrh(tBTA_HF_CLIENT_CB* client_cb,
                                      uint16_t code) {
  APPL_TRACE_DEBUG("%s: %lu", __func__, code);

  bta_hf_client_evt_val(client_cb, BTA_HF_CLIENT_BTRH_EVT, code);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_cback_ind
 *
 * Description      Send indicator callback event to application.
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_ind(tBTA_HF_CLIENT_CB* client_cb,
                       tBTA_HF_CLIENT_IND_TYPE type, uint16_t value) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  evt.ind.type = type;
  evt.ind.value = value;

  evt.ind.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_IND_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_evt_val
 *
 * Description      Send event to application.
 *                  This is a generic helper for events with common data.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_evt_val(tBTA_HF_CLIENT_CB* client_cb,
                           tBTA_HF_CLIENT_EVT type, uint16_t value) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  evt.val.bd_addr = client_cb->peer_addr;
  evt.val.value = value;

  bta_hf_client_app_callback(type, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_operator_name
 *
 * Description      Send operator name event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_operator_name(tBTA_HF_CLIENT_CB* client_cb, char* name) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  strlcpy(evt.operator_name.name, name, BTA_HF_CLIENT_OPERATOR_NAME_LEN + 1);
  evt.operator_name.name[BTA_HF_CLIENT_OPERATOR_NAME_LEN] = '\0';

  evt.operator_name.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_OPERATOR_NAME_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_clip
 *
 * Description      Send CLIP event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_clip(tBTA_HF_CLIENT_CB* client_cb, char* number) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  strlcpy(evt.number.number, number, BTA_HF_CLIENT_NUMBER_LEN + 1);
  evt.number.number[BTA_HF_CLIENT_NUMBER_LEN] = '\0';

  evt.number.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_CLIP_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_ccwa
 *
 * Description      Send CLIP event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_ccwa(tBTA_HF_CLIENT_CB* client_cb, char* number) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  strlcpy(evt.number.number, number, BTA_HF_CLIENT_NUMBER_LEN + 1);
  evt.number.number[BTA_HF_CLIENT_NUMBER_LEN] = '\0';

  evt.number.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_CCWA_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_at_result
 *
 * Description      Send AT result event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_at_result(tBTA_HF_CLIENT_CB* client_cb,
                             tBTA_HF_CLIENT_AT_RESULT_TYPE type, uint16_t cme) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  evt.result.type = type;
  evt.result.cme = cme;

  evt.result.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_AT_RESULT_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_clcc
 *
 * Description      Send clcc event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_clcc(tBTA_HF_CLIENT_CB* client_cb, uint32_t idx,
                        bool incoming, uint8_t status, bool mpty,
                        char* number) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  evt.clcc.idx = idx;
  evt.clcc.inc = incoming;
  evt.clcc.status = status;
  evt.clcc.mpty = mpty;

  if (number) {
    evt.clcc.number_present = true;
    strlcpy(evt.clcc.number, number, BTA_HF_CLIENT_NUMBER_LEN + 1);
    evt.clcc.number[BTA_HF_CLIENT_NUMBER_LEN] = '\0';
  }

  evt.clcc.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_CLCC_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_cnum
 *
 * Description      Send cnum event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number,
                        uint16_t service) {
  tBTA_HF_CLIENT evt = {};

  evt.cnum.service = service;
  strlcpy(evt.cnum.number, number, BTA_HF_CLIENT_NUMBER_LEN + 1);
  evt.cnum.number[BTA_HF_CLIENT_NUMBER_LEN] = '\0';

  evt.cnum.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_CNUM_EVT, &evt);
}

void bta_hf_client_unknown_response(tBTA_HF_CLIENT_CB* client_cb,
                                    const char* evt_buffer) {
  tBTA_HF_CLIENT evt = {};

  strlcpy(evt.unknown.event_string, evt_buffer,
          BTA_HF_CLIENT_UNKOWN_EVENT_LEN + 1);
  evt.unknown.event_string[BTA_HF_CLIENT_UNKOWN_EVENT_LEN] = '\0';

  evt.unknown.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_UNKNOWN_EVT, &evt);
}

/*******************************************************************************
 *
 * Function         bta_hf_client_binp
 *
 * Description      Send BINP event to application.
 *
 *
 * Returns          void
 *
 ******************************************************************************/
void bta_hf_client_binp(tBTA_HF_CLIENT_CB* client_cb, char* number) {
  tBTA_HF_CLIENT evt;

  memset(&evt, 0, sizeof(evt));

  strlcpy(evt.number.number, number, BTA_HF_CLIENT_NUMBER_LEN + 1);
  evt.number.number[BTA_HF_CLIENT_NUMBER_LEN] = '\0';

  evt.number.bd_addr = client_cb->peer_addr;
  bta_hf_client_app_callback(BTA_HF_CLIENT_BINP_EVT, &evt);
}

/******************************************************************************
 *
 *          COMMON AT EVENTS PARSING FUNCTIONS
 *
 ******************************************************************************/

/* Check if prefix match and skip spaces if any */
#define AT_CHECK_EVENT(buf, event)                                             \
  do {                                                                         \
    if (strncmp("\r\n" event, buf, sizeof("\r\n" event) - 1) != 0) return buf; \
    (buf) += sizeof("\r\n" event) - 1;                                         \
    while (*(buf) == ' ') (buf)++;                                             \
  } while (0)

/* check for <cr><lf> and forward buffer if match */
#define AT_CHECK_RN(buf)                                      \
  do {                                                        \
    if (strncmp("\r\n", buf, sizeof("\r\n") - 1) != 0) {      \
      APPL_TRACE_DEBUG("%s: missing end <cr><lf>", __func__); \
      return NULL;                                            \
    }                                                         \
    (buf) += sizeof("\r\n") - 1;                              \
  } while (0)

/* skip rest of AT string up to <cr> */
#define AT_SKIP_REST(buf)           \
  do {                              \
    while (*(buf) != '\r') (buf)++; \
  } while (0)

static char* bta_hf_client_parse_ok(tBTA_HF_CLIENT_CB* client_cb,
                                    char* buffer) {
  AT_CHECK_EVENT(buffer, "OK");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ok(client_cb);

  return buffer;
}

static char* bta_hf_client_parse_error(tBTA_HF_CLIENT_CB* client_cb,
                                       char* buffer) {
  AT_CHECK_EVENT(buffer, "ERROR");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_ERROR, 0);

  return buffer;
}

static char* bta_hf_client_parse_ring(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "RING");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ring(client_cb);

  return buffer;
}

/* generic uint32 parser */
static char* bta_hf_client_parse_uint32(
    tBTA_HF_CLIENT_CB* client_cb, char* buffer,
    void (*handler_callback)(tBTA_HF_CLIENT_CB*, uint32_t)) {
  uint32_t value;
  int res;
  int offset;

  res = sscanf(buffer, "%u%n", &value, &offset);
  if (res < 1) {
    return NULL;
  }

  buffer += offset;

  AT_CHECK_RN(buffer);

  handler_callback(client_cb, value);
  return buffer;
}

static char* bta_hf_client_parse_brsf(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+BRSF:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_brsf);
}

static char* bta_hf_client_parse_cind_values(tBTA_HF_CLIENT_CB* client_cb,
                                             char* buffer) {
  /* value and its position */
  uint16_t index = 0;
  uint32_t value = 0;

  int offset;
  int res;

  while ((res = sscanf(buffer, "%u%n", &value, &offset)) > 0) {
    /* decides if its valid index and value, if yes stores it */
    bta_hf_client_handle_cind_value(client_cb, index, value);

    buffer += offset;

    /* check if more values are present */
    if (*buffer != ',') {
      break;
    }

    index++;
    buffer++;
  }

  if (res > 0) {
    AT_CHECK_RN(buffer);
    return buffer;
  }

  return NULL;
}

static char* bta_hf_client_parse_cind_list(tBTA_HF_CLIENT_CB* client_cb,
                                           char* buffer) {
  int offset = 0;
  char name[129];
  uint32_t min, max;
  uint32_t index = 0;
  int res;

  while ((res = sscanf(buffer, "(\"%128[^\"]\",(%u%*[-,]%u))%n", name, &min,
                       &max, &offset)) > 2) {
    bta_hf_client_handle_cind_list_item(client_cb, name, min, max, index);
    if (offset == 0) {
      APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
      return NULL;
    }

    buffer += offset;
    index++;

    if (*buffer != ',') {
      break;
    }

    buffer++;
  }

  if (res > 2) {
    AT_CHECK_RN(buffer);
    return buffer;
  }

  return NULL;
}

static char* bta_hf_client_parse_cind(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+CIND:");

  if (*buffer == '(') return bta_hf_client_parse_cind_list(client_cb, buffer);

  return bta_hf_client_parse_cind_values(client_cb, buffer);
}

static char* bta_hf_client_parse_chld(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+CHLD:");

  if (*buffer != '(') {
    return NULL;
  }

  buffer++;

  while (*buffer != '\0') {
    if (strncmp("0", buffer, 1) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_REL);
      buffer++;
    } else if (strncmp("1x", buffer, 2) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_REL_X);
      buffer += 2;
    } else if (strncmp("1", buffer, 1) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_REL_ACC);
      buffer++;
    } else if (strncmp("2x", buffer, 2) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_PRIV_X);
      buffer += 2;
    } else if (strncmp("2", buffer, 1) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_HOLD_ACC);
      buffer++;
    } else if (strncmp("3", buffer, 1) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_MERGE);
      buffer++;
    } else if (strncmp("4", buffer, 1) == 0) {
      bta_hf_client_handle_chld(client_cb, BTA_HF_CLIENT_CHLD_MERGE_DETACH);
      buffer++;
    } else {
      return NULL;
    }

    if (*buffer == ',') {
      buffer++;
      continue;
    }

    if (*buffer == ')') {
      buffer++;
      break;
    }

    return NULL;
  }

  AT_CHECK_RN(buffer);

  return buffer;
}

static char* bta_hf_client_parse_bind(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+BIND:");

  uint8_t mode = BTA_HF_CLIENT_BIND_PARSE_READ_ENABLED_IND;

  int idx = -1;

  while (*buffer != 0) {
    switch (*buffer) {
      case '(':
        mode = BTA_HF_CLIENT_BIND_PARSE_READ_SUPPOETED_IND;
        break;
      case ')':
        break;
      case '0':
      case '1':
      case '2':
        if (mode == BTA_HF_CLIENT_BIND_PARSE_READ_SUPPOETED_IND) {
          // +BIND: (id0, id1, ...)
          bta_hf_client_handle_bind_read_supported_ind(client_cb,
                                                       (*buffer - '0'));
        } else if (idx == -1) {
          // +BIND: [id]...
          idx = *buffer - '0';
        } else {
          // +BIND: ...[status]
          bta_hf_client_handle_bind_read_enabled_ind(client_cb, idx,
                                                     *buffer - '0');
        }
        break;
      default:
        break;
    }
    buffer++;
  }

  return buffer;
}

static char* bta_hf_client_parse_ciev(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  uint32_t index, value;
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+CIEV:");

  res = sscanf(buffer, "%u,%u%n", &index, &value, &offset);
  if (res < 2) {
    return NULL;
  }

  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;

  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ciev(client_cb, index, value);
  return buffer;
}

static char* bta_hf_client_parse_bcs(tBTA_HF_CLIENT_CB* client_cb,
                                     char* buffer) {
  AT_CHECK_EVENT(buffer, "+BCS:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_bcs);
}

static char* bta_hf_client_parse_bsir(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+BSIR:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_bsir);
}

static char* bta_hf_client_parse_cmeerror(tBTA_HF_CLIENT_CB* client_cb,
                                          char* buffer) {
  AT_CHECK_EVENT(buffer, "+CME ERROR:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_cmeerror);
}

static char* bta_hf_client_parse_vgm(tBTA_HF_CLIENT_CB* client_cb,
                                     char* buffer) {
  AT_CHECK_EVENT(buffer, "+VGM:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_vgm);
}

static char* bta_hf_client_parse_vgme(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+VGM=");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_vgm);
}

static char* bta_hf_client_parse_vgs(tBTA_HF_CLIENT_CB* client_cb,
                                     char* buffer) {
  AT_CHECK_EVENT(buffer, "+VGS:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_vgs);
}

static char* bta_hf_client_parse_vgse(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+VGS=");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_vgs);
}

static char* bta_hf_client_parse_bvra(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "+BVRA:");

  return bta_hf_client_parse_uint32(client_cb, buffer,
                                    bta_hf_client_handle_bvra);
}

static char* bta_hf_client_parse_clip(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  /* spec forces 32 chars, plus \0 here */
  char number[33];
  uint32_t type = 0;
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+CLIP:");

  /* there might be something more after %lu but HFP doesn't care */
  res = sscanf(buffer, "\"%32[^\"]\",%u%n", number, &type, &offset);
  if (res < 2) {
    return NULL;
  }

  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;

  AT_SKIP_REST(buffer);

  AT_CHECK_RN(buffer);

  bta_hf_client_handle_clip(client_cb, number, type);
  return buffer;
}

/* in HFP context there is no difference between ccwa and clip */
static char* bta_hf_client_parse_ccwa(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  /* ac to spec 32 chars max, plus \0 here */
  char number[33];
  uint32_t type = 0;
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+CCWA:");

  /* there might be something more after %lu but HFP doesn't care */
  res = sscanf(buffer, "\"%32[^\"]\",%u%n", number, &type, &offset);
  if (res < 2) {
    return NULL;
  }

  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;

  AT_SKIP_REST(buffer);

  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ccwa(client_cb, number, type);
  return buffer;
}

static char* bta_hf_client_parse_cops(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  uint8_t mode;
  /* spec forces 16 chars max, plus \0 here */
  char opstr[17];
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+COPS:");

  /* TODO: Not sure if operator string actually can contain escaped " char
   * inside */
  res = sscanf(buffer, "%hhi,0,\"%16[^\"]\"%n", &mode, opstr, &offset);
  if (res < 2) {
    return NULL;
  }
  /* Abort in case offset not set because of format error */
  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;

  AT_SKIP_REST(buffer);

  AT_CHECK_RN(buffer);

  bta_hf_client_handle_cops(client_cb, opstr, mode);
  // check for OK Response in end
  AT_CHECK_EVENT(buffer, "OK");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ok(client_cb);

  return buffer;
}

static char* bta_hf_client_parse_binp(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  /* HFP only supports phone number as BINP data */
  /* phone number is 32 chars plus one for \0*/
  char numstr[33];
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+BINP:");

  res = sscanf(buffer, "\"%32[^\"]\"\r\n%n", numstr, &offset);
  if (res < 1) {
    return NULL;
  }

  /* Abort in case offset not set because of format error */
  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;

  /* some phones might sent type as well, just skip it */
  AT_SKIP_REST(buffer);

  AT_CHECK_RN(buffer);

  bta_hf_client_handle_binp(client_cb, numstr);

  // check for OK response in end
  AT_CHECK_EVENT(buffer, "OK");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ok(client_cb);

  return buffer;
}

static char* bta_hf_client_parse_clcc(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  uint16_t idx, dir, status, mode, mpty;
  char numstr[33]; /* spec forces 32 chars, plus one for \0*/
  uint16_t type;
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+CLCC:");

  res = sscanf(buffer, "%hu,%hu,%hu,%hu,%hu%n", &idx, &dir, &status, &mode,
               &mpty, &offset);
  if (res < 5) {
    return NULL;
  }

  /* Abort in case offset not set because of format error */
  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;
  offset = 0;

  /* check optional part */
  if (*buffer == ',') {
    int res2 = sscanf(buffer, ",\"%32[^\"]\",%hu%n", numstr, &type, &offset);
    if (res2 < 0) return NULL;

    if (res2 == 0) {
      res2 = sscanf(buffer, ",\"\",%hu%n", &type, &offset);
      if (res2 < 0) return NULL;

      /* numstr is not matched in second attempt, correct this */
      res2++;
      numstr[0] = '\0';
    }

    if (res2 >= 2) {
      res += res2;
      /* Abort in case offset not set because of format error */
      if (offset == 0) {
        APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
        return NULL;
      }

      buffer += offset;
    }
  }

  /* Skip any remaing param,as they are not defined by BT HFP spec */
  AT_SKIP_REST(buffer);
  AT_CHECK_RN(buffer);

  if (res > 6) {
    /* we also have last two optional parameters */
    bta_hf_client_handle_clcc(client_cb, idx, dir, status, mode, mpty, numstr,
                              type);
  } else {
    /* we didn't get the last two parameters */
    bta_hf_client_handle_clcc(client_cb, idx, dir, status, mode, mpty, NULL, 0);
  }

  // check for OK response in end
  AT_CHECK_EVENT(buffer, "OK");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ok(client_cb);
  return buffer;
}

static char* bta_hf_client_parse_cnum(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  char numstr[33]; /* spec forces 32 chars, plus one for \0*/
  uint16_t type;
  uint16_t service =
      0; /* 0 in case this optional parameter is not being sent */
  int res;
  int offset = 0;

  AT_CHECK_EVENT(buffer, "+CNUM:");

  res = sscanf(buffer, ",\"%32[^\"]\",%hu,,%hu%n", numstr, &type, &service,
               &offset);
  if (res < 0) {
    return NULL;
  }

  if (res == 0) {
    res = sscanf(buffer, ",\"\",%hu,,%hu%n", &type, &service, &offset);
    if (res < 0) {
      return NULL;
    }

    /* numstr is not matched in second attempt, correct this */
    res++;
    numstr[0] = '\0';
  }

  if (res < 3) {
    return NULL;
  }

  /* Abort in case offset not set because of format error */
  if (offset == 0) {
    APPL_TRACE_ERROR("%s: Format Error %s", __func__, buffer);
    return NULL;
  }

  buffer += offset;

  AT_CHECK_RN(buffer);

  /* service is optional */
  if (res == 2) {
    bta_hf_client_handle_cnum(client_cb, numstr, type, service);
    return buffer;
  }

  if (service != 4 && service != 5) {
    return NULL;
  }

  bta_hf_client_handle_cnum(client_cb, numstr, type, service);

  // check for OK response in end
  AT_CHECK_EVENT(buffer, "OK");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_ok(client_cb);
  return buffer;
}

static char* bta_hf_client_parse_btrh(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  uint16_t code = 0;
  int res;
  int offset;

  AT_CHECK_EVENT(buffer, "+BTRH:");

  res = sscanf(buffer, "%hu%n", &code, &offset);
  if (res < 1) {
    return NULL;
  }

  buffer += offset;

  AT_CHECK_RN(buffer);

  bta_hf_client_handle_btrh(client_cb, code);
  return buffer;
}

static char* bta_hf_client_parse_busy(tBTA_HF_CLIENT_CB* client_cb,
                                      char* buffer) {
  AT_CHECK_EVENT(buffer, "BUSY");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_BUSY, 0);

  return buffer;
}

static char* bta_hf_client_parse_delayed(tBTA_HF_CLIENT_CB* client_cb,
                                         char* buffer) {
  AT_CHECK_EVENT(buffer, "DELAYED");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_DELAY, 0);

  return buffer;
}

static char* bta_hf_client_parse_no_carrier(tBTA_HF_CLIENT_CB* client_cb,
                                            char* buffer) {
  AT_CHECK_EVENT(buffer, "NO CARRIER");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_NO_CARRIER, 0);

  return buffer;
}

static char* bta_hf_client_parse_no_answer(tBTA_HF_CLIENT_CB* client_cb,
                                           char* buffer) {
  AT_CHECK_EVENT(buffer, "NO ANSWER");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_NO_ANSWER, 0);

  return buffer;
}

static char* bta_hf_client_parse_rejectlisted(tBTA_HF_CLIENT_CB* client_cb,
                                              char* buffer) {
  AT_CHECK_EVENT(buffer, "REJECTLISTED");
  AT_CHECK_RN(buffer);

  bta_hf_client_handle_error(client_cb, BTA_HF_CLIENT_AT_RESULT_REJECTLISTED,
                             0);

  return buffer;
}

static char* bta_hf_client_skip_unknown(tBTA_HF_CLIENT_CB* client_cb,
                                        char* buffer) {
  char* start;
  char* tmp;

  tmp = strstr(buffer, "\r\n");
  if (tmp == NULL) {
    return NULL;
  }

  buffer += 2;
  start = buffer;

  tmp = strstr(buffer, "\r\n");
  if (tmp == NULL) {
    return NULL;
  }

  buffer = tmp + 2;

  APPL_TRACE_DEBUG("%s: %.*s", __func__, buffer - start - 2, start);

  return buffer;
}

static char* bta_hf_client_process_unknown(tBTA_HF_CLIENT_CB* client_cb,
                                           char* buffer) {
  char* start = strstr(buffer, "\r\n");
  if (start == NULL) {
    return NULL;
  }
  start += sizeof("\r\n") - 1;

  char* end = strstr(start, "\r\n");
  if (end == NULL) {
    return NULL;
  }

  int evt_size = end - start + 1;

  char tmp_buf[BTA_HF_CLIENT_UNKOWN_EVENT_LEN];
  if (evt_size < BTA_HF_CLIENT_UNKOWN_EVENT_LEN) {
    strlcpy(tmp_buf, start, evt_size);
    bta_hf_client_unknown_response(client_cb, tmp_buf);
    AT_CHECK_RN(end);
  } else {
    APPL_TRACE_ERROR("%s: exceed event buffer size. (%d, %d)", __func__,
                     evt_size, BTA_HF_CLIENT_UNKOWN_EVENT_LEN);
  }

  APPL_TRACE_DEBUG("%s: %s", __func__, buffer);

  return end;
}

/******************************************************************************
 *       SUPPORTED EVENT MESSAGES
 ******************************************************************************/

/* returned values are as follow:
 * != NULL && != buf  : match and parsed ok
 * == NULL            : match but parse failed
 * != NULL && == buf  : no match
 */
typedef char* (*tBTA_HF_CLIENT_PARSER_CALLBACK)(tBTA_HF_CLIENT_CB*, char*);

static const tBTA_HF_CLIENT_PARSER_CALLBACK bta_hf_client_parser_cb[] = {
    bta_hf_client_parse_ok,        bta_hf_client_parse_error,
    bta_hf_client_parse_ring,      bta_hf_client_parse_brsf,
    bta_hf_client_parse_cind,      bta_hf_client_parse_ciev,
    bta_hf_client_parse_chld,      bta_hf_client_parse_bcs,
    bta_hf_client_parse_bsir,      bta_hf_client_parse_cmeerror,
    bta_hf_client_parse_vgm,       bta_hf_client_parse_vgme,
    bta_hf_client_parse_vgs,       bta_hf_client_parse_vgse,
    bta_hf_client_parse_bvra,      bta_hf_client_parse_clip,
    bta_hf_client_parse_ccwa,      bta_hf_client_parse_cops,
    bta_hf_client_parse_binp,      bta_hf_client_parse_clcc,
    bta_hf_client_parse_cnum,      bta_hf_client_parse_btrh,
    bta_hf_client_parse_bind,      bta_hf_client_parse_busy,
    bta_hf_client_parse_delayed,   bta_hf_client_parse_no_carrier,
    bta_hf_client_parse_no_answer, bta_hf_client_parse_rejectlisted,
    bta_hf_client_process_unknown};

/* calculate supported event list length */
static const uint16_t bta_hf_client_parser_cb_count =
    sizeof(bta_hf_client_parser_cb) / sizeof(bta_hf_client_parser_cb[0]);

#ifdef BTA_HF_CLIENT_AT_DUMP
static void bta_hf_client_dump_at(tBTA_HF_CLIENT_CB* client_cb) {
  char dump[(4 * BTA_HF_CLIENT_AT_PARSER_MAX_LEN) + 1];
  char *p1, *p2;

  p1 = client_cb->at_cb.buf;
  p2 = dump;

  while (*p1 != '\0') {
    if (*p1 == '\r') {
      strlcpy(p2, "<cr>", 4);
      p2 += 4;
    } else if (*p1 == '\n') {
      strlcpy(p2, "<lf>", 4);
      p2 += 4;
    } else {
      *p2 = *p1;
      p2++;
    }
    p1++;
  }

  *p2 = '\0';

  APPL_TRACE_DEBUG("%s: %s", __func__, dump);
}
#endif

static void bta_hf_client_at_parse_start(tBTA_HF_CLIENT_CB* client_cb) {
  char* buf = client_cb->at_cb.buf;

  APPL_TRACE_DEBUG("%s", __func__);

#ifdef BTA_HF_CLIENT_AT_DUMP
  bta_hf_client_dump_at(client_cb);
#endif

  while (*buf != '\0') {
    int i;
    char* tmp = NULL;

    for (i = 0; i < bta_hf_client_parser_cb_count; i++) {
      tmp = bta_hf_client_parser_cb[i](client_cb, buf);
      if (tmp == NULL) {
        APPL_TRACE_ERROR("HFPCient: AT event/reply parsing failed, skipping");
        tmp = bta_hf_client_skip_unknown(client_cb, buf);
        break;
      }

      /* matched or unknown skipped, if unknown failed tmp is NULL so
         this is also handled */
      if (tmp != buf) {
        buf = tmp;
        break;
      }
    }

    /* could not skip unknown (received garbage?)... disconnect */
    if (tmp == NULL) {
      APPL_TRACE_ERROR(
          "HFPCient: could not skip unknown AT event, disconnecting");
      bta_hf_client_at_reset(client_cb);

      tBTA_HF_CLIENT_DATA msg = {};
      msg.hdr.layer_specific = client_cb->handle;
      bta_hf_client_sm_execute(BTA_HF_CLIENT_API_CLOSE_EVT, &msg);
      return;
    }

    buf = tmp;
  }
}

static bool bta_hf_client_check_at_complete(tBTA_HF_CLIENT_CB* client_cb) {
  bool ret = false;
  tBTA_HF_CLIENT_AT_CB* at_cb = &client_cb->at_cb;

  if (at_cb->offset >= BTA_HF_CLIENT_AT_EVENT_MIN_LEN) {
    if (at_cb->buf[at_cb->offset - 2] == '\r' &&
        at_cb->buf[at_cb->offset - 1] == '\n') {
      ret = true;
    }
  }

  APPL_TRACE_DEBUG("%s: %d", __func__, ret);

  return ret;
}

static void bta_hf_client_at_clear_buf(tBTA_HF_CLIENT_CB* client_cb) {
  memset(client_cb->at_cb.buf, 0, sizeof(client_cb->at_cb.buf));
  client_cb->at_cb.offset = 0;
}

/******************************************************************************
 *
 *          MAIN PARSING FUNCTION
 *
 *
 ******************************************************************************/
void bta_hf_client_at_parse(tBTA_HF_CLIENT_CB* client_cb, char* buf,
                            unsigned int len) {
  APPL_TRACE_DEBUG("%s: offset: %u len: %u", __func__, client_cb->at_cb.offset,
                   len);

  if (len + client_cb->at_cb.offset > BTA_HF_CLIENT_AT_PARSER_MAX_LEN) {
    char tmp_buff[BTA_HF_CLIENT_AT_PARSER_MAX_LEN];
    unsigned int tmp = client_cb->at_cb.offset;
    unsigned int space_left =
        BTA_HF_CLIENT_AT_PARSER_MAX_LEN - client_cb->at_cb.offset;

    APPL_TRACE_DEBUG("%s: overrun, trying to recover", __func__);

    /* fill up parser buffer */
    memcpy(client_cb->at_cb.buf + client_cb->at_cb.offset, buf, space_left);
    len -= space_left;
    buf += space_left;
    client_cb->at_cb.offset += space_left;

    /* find end of last complete command before proceeding */
    while (!bta_hf_client_check_at_complete(client_cb)) {
      if (client_cb->at_cb.offset == 0) {
        APPL_TRACE_ERROR("HFPClient: AT parser buffer overrun, disconnecting");

        bta_hf_client_at_reset(client_cb);

        tBTA_HF_CLIENT_DATA msg = {};
        msg.hdr.layer_specific = client_cb->handle;
        bta_hf_client_sm_execute(BTA_HF_CLIENT_API_CLOSE_EVT, &msg);
        return;
      }

      client_cb->at_cb.offset--;
    }

    /* cut buffer to complete AT event and keep cut data */
    tmp += space_left - client_cb->at_cb.offset;
    memcpy(tmp_buff, client_cb->at_cb.buf + client_cb->at_cb.offset, tmp);
    client_cb->at_cb.buf[client_cb->at_cb.offset] = '\0';

    /* parse */
    bta_hf_client_at_parse_start(client_cb);
    bta_hf_client_at_clear_buf(client_cb);

    /* recover cut data */
    memcpy(client_cb->at_cb.buf, tmp_buff, tmp);
    client_cb->at_cb.offset += tmp;
  }

  memcpy(client_cb->at_cb.buf + client_cb->at_cb.offset, buf, len);
  client_cb->at_cb.offset += len;

  /* If last event is complete, parsing can be started */
  if (bta_hf_client_check_at_complete(client_cb)) {
    bta_hf_client_at_parse_start(client_cb);
    bta_hf_client_at_clear_buf(client_cb);
  }
}

void bta_hf_client_send_at_brsf(tBTA_HF_CLIENT_CB* client_cb,
                                tBTA_HF_CLIENT_FEAT features) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  at_len = snprintf(buf, sizeof(buf), "AT+BRSF=%u\r", features);
  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BRSF, buf, at_len);
}

void bta_hf_client_send_at_bac(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "AT+BAC=1,2\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BAC, buf, strlen(buf));
}

void bta_hf_client_send_at_bcs(tBTA_HF_CLIENT_CB* client_cb, uint32_t codec) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  at_len = snprintf(buf, sizeof(buf), "AT+BCS=%u\r", codec);
  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BCS, buf, at_len);
}

void bta_hf_client_send_at_cind(tBTA_HF_CLIENT_CB* client_cb, bool status) {
  const char* buf;
  tBTA_HF_CLIENT_AT_CMD cmd;

  APPL_TRACE_DEBUG("%s", __func__);

  if (status) {
    buf = "AT+CIND?\r";
    cmd = BTA_HF_CLIENT_AT_CIND_STATUS;
  } else {
    buf = "AT+CIND=?\r";
    cmd = BTA_HF_CLIENT_AT_CIND;
  }

  bta_hf_client_send_at(client_cb, cmd, buf, strlen(buf));
}

void bta_hf_client_send_at_cmer(tBTA_HF_CLIENT_CB* client_cb, bool activate) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (activate)
    buf = "AT+CMER=3,0,0,1\r";
  else
    buf = "AT+CMER=3,0,0,0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CMER, buf, strlen(buf));
}

void bta_hf_client_send_at_chld(tBTA_HF_CLIENT_CB* client_cb, char cmd,
                                uint32_t idx) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  if (idx > 0)
    at_len = snprintf(buf, sizeof(buf), "AT+CHLD=%c%u\r", cmd, idx);
  else
    at_len = snprintf(buf, sizeof(buf), "AT+CHLD=%c\r", cmd);

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CHLD, buf, at_len);
}

void bta_hf_client_send_at_bind(tBTA_HF_CLIENT_CB* client_cb, int step) {
  std::string buf;
  tBTA_HF_CLIENT_AT_CMD cmd = BTA_HF_CLIENT_AT_BIND_SET_IND;

  APPL_TRACE_DEBUG("%s", __func__);

  switch (step) {
    case 0:  // List HF supported indicators
      // TODO: Add flags to determine enabled HF features
      buf = "AT+BIND=1,2\r";
      cmd = BTA_HF_CLIENT_AT_BIND_SET_IND;
      break;
    case 1:  // Read AG supported indicators
      buf = "AT+BIND=?\r";
      cmd = BTA_HF_CLIENT_AT_BIND_READ_SUPPORTED_IND;
      break;
    case 2:  // Read AG enabled/disabled status of indicators
      buf = "AT+BIND?\r";
      cmd = BTA_HF_CLIENT_AT_BIND_READ_ENABLED_IND;
      break;
    default:
      break;
  }
  bta_hf_client_send_at(client_cb, cmd, buf.c_str(), buf.size());
}

void bta_hf_client_send_at_biev(tBTA_HF_CLIENT_CB* client_cb, int indicator_id,
                                int indicator_value) {
  char buf[32];
  tBTA_HF_CLIENT_AT_CMD cmd = BTA_HF_CLIENT_AT_BIEV;

  if ((client_cb->peer_features & BTA_HF_CLIENT_FEAT_HF_IND) == 0) {
    APPL_TRACE_ERROR("%s peer does not support HF Indicators", __func__);
    return;
  }

  if (client_cb->enabled_hf_indicators.count(indicator_id) <= 0) {
    APPL_TRACE_ERROR("%s HF indicators %d is disabled", __func__, indicator_id);
    return;
  }

  APPL_TRACE_DEBUG("%s", __func__);

  int len = sprintf(buf, "AT+BIEV=%d,%d\r", indicator_id, indicator_value);

  bta_hf_client_send_at(client_cb, cmd, buf, len);
}

void bta_hf_client_send_at_clip(tBTA_HF_CLIENT_CB* client_cb, bool activate) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (activate)
    buf = "AT+CLIP=1\r";
  else
    buf = "AT+CLIP=0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CLIP, buf, strlen(buf));
}

void bta_hf_client_send_at_ccwa(tBTA_HF_CLIENT_CB* client_cb, bool activate) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (activate)
    buf = "AT+CCWA=1\r";
  else
    buf = "AT+CCWA=0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CCWA, buf, strlen(buf));
}

void bta_hf_client_send_at_cmee(tBTA_HF_CLIENT_CB* client_cb, bool activate) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (activate)
    buf = "AT+CMEE=1\r";
  else
    buf = "AT+CMEE=0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CMEE, buf, strlen(buf));
}

void bta_hf_client_send_at_cops(tBTA_HF_CLIENT_CB* client_cb, bool query) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (query)
    buf = "AT+COPS?\r";
  else
    buf = "AT+COPS=3,0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_COPS, buf, strlen(buf));
}

void bta_hf_client_send_at_clcc(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "AT+CLCC\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CLCC, buf, strlen(buf));
}

void bta_hf_client_send_at_bvra(tBTA_HF_CLIENT_CB* client_cb, bool enable) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (enable)
    buf = "AT+BVRA=1\r";
  else
    buf = "AT+BVRA=0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BVRA, buf, strlen(buf));
}

void bta_hf_client_send_at_vgs(tBTA_HF_CLIENT_CB* client_cb, uint32_t volume) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  at_len = snprintf(buf, sizeof(buf), "AT+VGS=%u\r", volume);
  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VGS, buf, at_len);
}

void bta_hf_client_send_at_vgm(tBTA_HF_CLIENT_CB* client_cb, uint32_t volume) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  at_len = snprintf(buf, sizeof(buf), "AT+VGM=%u\r", volume);
  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VGM, buf, at_len);
}

void bta_hf_client_send_at_atd(tBTA_HF_CLIENT_CB* client_cb, char* number,
                               uint32_t memory) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  if (number[0] != '\0') {
    at_len = snprintf(buf, sizeof(buf), "ATD%s;\r", number);
  } else {
    at_len = snprintf(buf, sizeof(buf), "ATD>%u;\r", memory);
  }

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: error preparing ATD command", __func__);
    return;
  }

  at_len = MIN((size_t)at_len, sizeof(buf));

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }
  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_ATD, buf, at_len);
}

void bta_hf_client_send_at_bldn(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "AT+BLDN\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BLDN, buf, strlen(buf));
}

void bta_hf_client_send_at_ata(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "ATA\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_ATA, buf, strlen(buf));
}

void bta_hf_client_send_at_chup(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "AT+CHUP\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CHUP, buf, strlen(buf));
}

void bta_hf_client_send_at_btrh(tBTA_HF_CLIENT_CB* client_cb, bool query,
                                uint32_t val) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  if (query) {
    at_len = snprintf(buf, sizeof(buf), "AT+BTRH?\r");
  } else {
    at_len = snprintf(buf, sizeof(buf), "AT+BTRH=%u\r", val);
  }

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BTRH, buf, at_len);
}

void bta_hf_client_send_at_vts(tBTA_HF_CLIENT_CB* client_cb, char code) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  at_len = snprintf(buf, sizeof(buf), "AT+VTS=%c\r", code);

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VTS, buf, at_len);
}

void bta_hf_client_send_at_bcc(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "AT+BCC\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BCC, buf, strlen(buf));
}

void bta_hf_client_send_at_cnum(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  buf = "AT+CNUM\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_CNUM, buf, strlen(buf));
}

void bta_hf_client_send_at_nrec(tBTA_HF_CLIENT_CB* client_cb) {
  const char* buf;

  APPL_TRACE_DEBUG("%s", __func__);

  if (!(client_cb->peer_features & BTA_HF_CLIENT_PEER_FEAT_ECNR)) {
    APPL_TRACE_ERROR("%s: Remote does not support NREC.", __func__);
    return;
  }

  buf = "AT+NREC=0\r";

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_NREC, buf, strlen(buf));
}

void bta_hf_client_send_at_binp(tBTA_HF_CLIENT_CB* client_cb, uint32_t action) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;

  APPL_TRACE_DEBUG("%s", __func__);

  at_len = snprintf(buf, sizeof(buf), "AT+BINP=%u\r", action);

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BINP, buf, at_len);
}

void bta_hf_client_send_at_bia(tBTA_HF_CLIENT_CB* client_cb) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];
  int at_len;
  int i;

  APPL_TRACE_DEBUG("%s", __func__);
  if (client_cb->peer_version < HFP_VERSION_1_6) {
    APPL_TRACE_DEBUG("Remote does not Support AT+BIA");
    return;
  }

  at_len = snprintf(buf, sizeof(buf), "AT+BIA=");

  for (i = 0; i < BTA_HF_CLIENT_AT_INDICATOR_COUNT; i++) {
    int sup = client_cb->at_cb.indicator_lookup[i] == -1 ? 0 : 1;

/* If this value matches the position of SIGNAL in the indicators array,
 * then hardcode disable signal strength indicators.
 * indicator_lookup[i] points to the position in the bta_hf_client_indicators
 * array defined at the top of this file */
#ifdef BTA_HF_CLIENT_INDICATOR_SIGNAL_POS
    if (client_cb->at_cb.indicator_lookup[i] ==
        BTA_HF_CLIENT_INDICATOR_SIGNAL_POS) {
      sup = 0;
    }
#endif

    at_len += snprintf(buf + at_len, sizeof(buf) - at_len, "%u,", sup);
  }

  buf[at_len - 1] = '\r';

  if (at_len < 0) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BIA, buf, at_len);
}

void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb,
                                               const char* str) {
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];

  APPL_TRACE_DEBUG("%s", __func__);

  int at_len = snprintf(buf, sizeof(buf), "AT%s", str);

  if (at_len < 1) {
    APPL_TRACE_ERROR("%s: AT command Framing error", __func__);
    return;
  }

  buf[at_len - 1] = '\r';

  bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VENDOR_SPECIFIC, buf,
                        at_len);
}

void bta_hf_client_at_init(tBTA_HF_CLIENT_CB* client_cb) {
  alarm_free(client_cb->at_cb.resp_timer);
  alarm_free(client_cb->at_cb.hold_timer);
  memset(&(client_cb->at_cb), 0, sizeof(tBTA_HF_CLIENT_AT_CB));
  client_cb->at_cb.resp_timer = alarm_new("bta_hf_client.scb_at_resp_timer");
  client_cb->at_cb.hold_timer = alarm_new("bta_hf_client.scb_at_hold_timer");
  bta_hf_client_at_reset(client_cb);
}

void bta_hf_client_at_reset(tBTA_HF_CLIENT_CB* client_cb) {
  int i;

  bta_hf_client_stop_at_resp_timer(client_cb);
  bta_hf_client_stop_at_hold_timer(client_cb);

  bta_hf_client_clear_queued_at(client_cb);

  bta_hf_client_at_clear_buf(client_cb);

  for (i = 0; i < BTA_HF_CLIENT_AT_INDICATOR_COUNT; i++) {
    client_cb->at_cb.indicator_lookup[i] = -1;
  }

  client_cb->at_cb.current_cmd = BTA_HF_CLIENT_AT_NONE;
}

void bta_hf_client_send_at_cmd(tBTA_HF_CLIENT_DATA* p_data) {
  tBTA_HF_CLIENT_CB* client_cb =
      bta_hf_client_find_cb_by_handle(p_data->hdr.layer_specific);
  if (!client_cb) {
    APPL_TRACE_ERROR("%s: cb not found for handle %d", __func__,
                     p_data->hdr.layer_specific);
    return;
  }

  tBTA_HF_CLIENT_DATA_VAL* p_val = (tBTA_HF_CLIENT_DATA_VAL*)p_data;
  char buf[BTA_HF_CLIENT_AT_MAX_LEN];

  APPL_TRACE_DEBUG("%s: at cmd: %d", __func__, p_val->uint8_val);
  switch (p_val->uint8_val) {
    case BTA_HF_CLIENT_AT_CMD_VTS:
      bta_hf_client_send_at_vts(client_cb, (char)p_val->uint32_val1);
      break;
    case BTA_HF_CLIENT_AT_CMD_BTRH:
      bta_hf_client_send_at_btrh(client_cb, false, p_val->uint32_val1);
      break;
    case BTA_HF_CLIENT_AT_CMD_CHUP:
      bta_hf_client_send_at_chup(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_CHLD:
      /* expects ascii code for command */
      bta_hf_client_send_at_chld(client_cb, '0' + p_val->uint32_val1,
                                 p_val->uint32_val2);
      break;
    case BTA_HF_CLIENT_AT_CMD_BIEV:
      /* expects ascii code for command */
      bta_hf_client_send_at_biev(client_cb, p_val->uint32_val1,
                                 p_val->uint32_val2);
      break;
    case BTA_HF_CLIENT_AT_CMD_BCC:
      bta_hf_client_send_at_bcc(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_CNUM:
      bta_hf_client_send_at_cnum(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_ATA:
      bta_hf_client_send_at_ata(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_COPS:
      bta_hf_client_send_at_cops(client_cb, true);
      break;
    case BTA_HF_CLIENT_AT_CMD_ATD:
      bta_hf_client_send_at_atd(client_cb, p_val->str, p_val->uint32_val1);
      break;
    case BTA_HF_CLIENT_AT_CMD_VGM:
      bta_hf_client_send_at_vgm(client_cb, p_val->uint32_val1);
      break;
    case BTA_HF_CLIENT_AT_CMD_VGS:
      bta_hf_client_send_at_vgs(client_cb, p_val->uint32_val1);
      break;
    case BTA_HF_CLIENT_AT_CMD_BVRA:
      bta_hf_client_send_at_bvra(client_cb,
                                 p_val->uint32_val1 == 0 ? false : true);
      break;
    case BTA_HF_CLIENT_AT_CMD_CLCC:
      bta_hf_client_send_at_clcc(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_BINP:
      bta_hf_client_send_at_binp(client_cb, p_val->uint32_val1);
      break;
    case BTA_HF_CLIENT_AT_CMD_BLDN:
      bta_hf_client_send_at_bldn(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_NREC:
      bta_hf_client_send_at_nrec(client_cb);
      break;
    case BTA_HF_CLIENT_AT_CMD_VENDOR_SPECIFIC_CMD:
      bta_hf_client_send_at_vendor_specific_cmd(client_cb, p_val->str);
      break;
    default:
      APPL_TRACE_ERROR("Default case");
      snprintf(buf, BTA_HF_CLIENT_AT_MAX_LEN,
               "Cmd %d 1st arg %u 2nd arg %u string arg %s", p_val->uint8_val,
               p_val->uint32_val1, p_val->uint32_val2, p_val->str);
      APPL_TRACE_ERROR("%s: AT buffer: %s ", __func__, buf);
      break;
  }
}