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
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
//! Vendor-specific events for BlueNRG controllers.
//!
//! The BlueNRG implementation defines several additional events that are packaged as
//! vendor-specific events by the Bluetooth HCI. This module defines those events and functions to
//! deserialize buffers into them.
extern crate bluetooth_hci as hci;

pub mod command;

use byteorder::{ByteOrder, LittleEndian};
use core::cmp::PartialEq;
use core::convert::{TryFrom, TryInto};
use core::fmt::{Debug, Formatter, Result as FmtResult};
use core::mem;
use core::time::Duration;

pub use hci::types::{ConnectionInterval, ConnectionIntervalError};
pub use hci::{BdAddr, BdAddrType, ConnectionHandle};

/// Vendor-specific events for the BlueNRG-MS controllers.
#[derive(Clone, Copy, Debug)]
pub enum BlueNRGEvent {
    /// When the BlueNRG-MS firmware is started normally, it gives this event to the user to
    /// indicate the system has started.
    HalInitialized(ResetReason),

    /// If the host fails to read events from the controller quickly enough, the controller will
    /// generate this event. This event is never lost; it is inserted as soon as space is available
    /// in the Tx queue.
    #[cfg(feature = "ms")]
    EventsLost(EventFlags),

    /// The fault data event is automatically sent after the
    /// [HalInitialized](BlueNRGEvent::HalInitialized) event in case of [NMI or Hard
    /// fault](ResetReason::Crash).
    #[cfg(feature = "ms")]
    CrashReport(FaultData),

    /// This event is generated by the controller when the limited discoverable mode ends due to
    /// timeout (180 seconds).
    GapLimitedDiscoverableTimeout,

    /// This event is generated when the pairing process has completed successfully or a pairing
    /// procedure timeout has occurred or the pairing has failed.  This is to notify the application
    /// that we have paired with a remote device so that it can take further actions or to notify
    /// that a timeout has occurred so that the upper layer can decide to disconnect the link.
    GapPairingComplete(GapPairingComplete),

    /// This event is generated by the Security manager to the application when a pass key is
    /// required for pairing.  When this event is received, the application has to respond with the
    /// `gap_pass_key_response` command.
    GapPassKeyRequest(ConnectionHandle),

    /// This event is generated by the Security manager to the application when the application has
    /// set that authorization is required for reading/writing of attributes. This event will be
    /// generated as soon as the pairing is complete. When this event is received,
    /// `gap_authorization_response` command should be used by the application.
    GapAuthorizationRequest(ConnectionHandle),

    /// This event is generated when the peripheral security request is successfully sent to the
    /// central device.
    GapPeripheralSecurityInitiated,

    /// This event is generated on the peripheral when a `gap_peripheral_security_request` is called
    /// to reestablish the bond with the central device but the central device has lost the
    /// bond. When this event is received, the upper layer has to issue the command
    /// `gap_allow_rebond` in order to allow the peripheral to continue the pairing process with the
    /// central device. On the central device, this event is raised when `gap_send_pairing_request`
    /// is called to reestablish a bond with a peripheral but the peripheral has lost the bond. In
    /// order to create a new bond the central device has to launch `gap_send_pairing_request` with
    /// `force_rebond` set to `true`.
    GapBondLost,

    /// The event is given by the GAP layer to the upper layers when a device is discovered during
    /// scanning as a consequence of one of the GAP procedures started by the upper layers.
    GapDeviceFound(GapDeviceFound),

    /// This event is sent by the GAP to the upper layers when a procedure previously started has
    /// been terminated by the upper layer or has completed for any other reason
    GapProcedureComplete(GapProcedureComplete),

    /// This event is sent only by a privacy enabled peripheral. The event is sent to the upper
    /// layers when the peripheral is unsuccessful in resolving the resolvable address of the peer
    /// device after connecting to it.
    #[cfg(feature = "ms")]
    GapAddressNotResolved(ConnectionHandle),

    /// This event is generated when the reconnection address is generated during the general
    /// connection establishment procedure. The same address is set to the peer device also as a
    /// part of the general connection establishment procedure. In order to make use of the
    /// reconnection address the next time while connecting to the bonded peripheral, the
    /// application needs to set its own address as well as the peer address to which it wants to
    /// connect to this reconnection address.
    #[cfg(not(feature = "ms"))]
    GapReconnectionAddress(BdAddr),

    /// This event is generated when the central device responds to the L2CAP connection update
    /// request packet. For more info see
    /// [ConnectionParameterUpdateResponse](::l2cap::ConnectionParameterUpdateResponse)
    /// and CommandReject in Bluetooth Core v4.0 spec.
    L2CapConnectionUpdateResponse(L2CapConnectionUpdateResponse),

    /// This event is generated when the central device does not respond to the connection update
    /// request within 30 seconds.
    L2CapProcedureTimeout(ConnectionHandle),

    /// The event is given by the L2CAP layer when a connection update request is received from the
    /// peripheral. The application has to respond by calling
    /// [`l2cap_connection_parameter_update_response`](::l2cap::Commands::connection_parameter_update_response).
    L2CapConnectionUpdateRequest(L2CapConnectionUpdateRequest),

    /// This event is generated to the application by the ATT server when a client modifies any
    /// attribute on the server, as consequence of one of the following ATT procedures:
    /// - write without response
    /// - signed write without response
    /// - write characteristic value
    /// - write long characteristic value
    /// - reliable write
    GattAttributeModified(GattAttributeModified),

    /// This event is generated when a ATT client procedure completes either with error or
    /// successfully.
    GattProcedureTimeout(ConnectionHandle),

    /// This event is generated in response to an Exchange MTU request.
    AttExchangeMtuResponse(AttExchangeMtuResponse),

    /// This event is generated in response to a Find Information Request. See Find Information
    /// Response in Bluetooth Core v4.0 spec.
    AttFindInformationResponse(AttFindInformationResponse),

    /// This event is generated in response to a Find By Type Value Request.
    AttFindByTypeValueResponse(AttFindByTypeValueResponse),

    /// This event is generated in response to a Read by Type Request.
    AttReadByTypeResponse(AttReadByTypeResponse),

    /// This event is generated in response to a Read Request.
    AttReadResponse(AttReadResponse),

    /// This event is generated in response to a Read Blob Request. The value in the response is the
    /// partial value starting from the offset in the request. See the Bluetooth Core v4.1 spec, Vol
    /// 3, section 3.4.4.5 and 3.4.4.6.
    AttReadBlobResponse(AttReadResponse),

    /// This event is generated in response to a Read Multiple Request. The value in the response is
    /// the set of values requested from the request. See the Bluetooth Core v4.1 spec, Vol 3,
    /// section 3.4.4.7 and 3.4.4.8.
    AttReadMultipleResponse(AttReadResponse),

    /// This event is generated in response to a Read By Group Type Request. See the Bluetooth Core
    /// v4.1 spec, Vol 3, section 3.4.4.9 and 3.4.4.10.
    AttReadByGroupTypeResponse(AttReadByGroupTypeResponse),

    /// This event is generated in response to a Prepare Write Request. See the Bluetooth Core v4.1
    /// spec, Vol 3, Part F, section 3.4.6.1 and 3.4.6.2
    AttPrepareWriteResponse(AttPrepareWriteResponse),

    /// This event is generated in response to an Execute Write Request. See the Bluetooth Core v4.1
    /// spec, Vol 3, Part F, section 3.4.6.3 and 3.4.6.4
    AttExecuteWriteResponse(ConnectionHandle),

    /// This event is generated when an indication is received from the server.
    GattIndication(AttributeValue),

    /// This event is generated when an notification is received from the server.
    GattNotification(AttributeValue),

    /// This event is generated when a GATT client procedure completes either with error or
    /// successfully.
    GattProcedureComplete(GattProcedureComplete),

    /// This event is generated when an Error Response is received from the server. The error
    /// response can be given by the server at the end of one of the GATT discovery procedures. This
    /// does not mean that the procedure ended with an error, but this error event is part of the
    /// procedure itself.
    AttErrorResponse(AttErrorResponse),

    /// This event can be generated during a "Discover Characteristics by UUID" procedure or a "Read
    /// using Characteristic UUID" procedure. The attribute value will be a service declaration as
    /// defined in Bluetooth Core v4.0 spec, Vol 3, Part G, section 3.3.1), when a "Discover
    /// Characteristics By UUID" has been started. It will be the value of the Characteristic if a
    /// "Read using Characteristic UUID" has been performed.
    ///
    /// See the Bluetooth Core v4.1 spec, Vol 3, Part G, section 4.6.2 (discover characteristics by
    /// UUID), and section 4.8.2 (read using characteristic using UUID).
    GattDiscoverOrReadCharacteristicByUuidResponse(AttributeValue),

    /// This event is given to the application when a write request, write command or signed write
    /// command is received by the server from the client. This event will be given to the
    /// application only if the event bit for this event generation is set when the characteristic
    /// was added. When this event is received, the application has to check whether the value being
    /// requested for write is allowed to be written and respond with a GATT Write Response. If the
    /// write is rejected by the application, then the value of the attribute will not be
    /// modified. In case of a write request, an error response will be sent to the client, with the
    /// error code as specified by the application. In case of write/signed write commands, no
    /// response is sent to the client but the attribute is not modified.
    ///
    /// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.5.
    AttWritePermitRequest(AttributeValue),

    /// This event is given to the application when a read request or read blob request is received
    /// by the server from the client. This event will be given to the application only if the event
    /// bit for this event generation is set when the characteristic was added. On receiving this
    /// event, the application can update the value of the handle if it desires and when done it has
    /// to use the [`allow_read`](::gatt::Commands::allow_read) command to indicate to the stack
    /// that it can send the response to the client.
    ///
    /// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
    AttReadPermitRequest(AttReadPermitRequest),

    /// This event is given to the application when a read multiple request or read by type request
    /// is received by the server from the client. This event will be given to the application only
    /// if the event bit for this event generation is set when the characteristic was added.  On
    /// receiving this event, the application can update the values of the handles if it desires and
    /// when done it has to send the [`allow_read`](::gatt::Commands::allow_read) command to
    /// indicate to the stack that it can send the response to the client.
    ///
    /// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
    AttReadMultiplePermitRequest(AttReadMultiplePermitRequest),

    /// This event is raised when the number of available TX buffers is above a threshold TH (TH =
    /// 2).  The event will be given only if a previous ACI command returned with
    /// [InsufficientResources](AttError::InsufficientResources).  On receiving this event, the
    /// application can continue to send notifications by calling `gatt_update_char_value`.
    #[cfg(feature = "ms")]
    GattTxPoolAvailable(GattTxPoolAvailable),

    /// This event is raised on the server when the client confirms the reception of an indication.
    #[cfg(feature = "ms")]
    GattServerConfirmation(ConnectionHandle),

    /// This event is given to the application when a prepare write request is received by the
    /// server from the client. This event will be given to the application only if the event bit
    /// for this event generation is set when the characteristic was added.  When this event is
    /// received, the application has to check whether the value being requested for write is
    /// allowed to be written and respond with the command `gatt_write_response`.  Based on the
    /// response from the application, the attribute value will be modified by the stack.  If the
    /// write is rejected by the application, then the value of the attribute will not be modified
    /// and an error response will be sent to the client, with the error code as specified by the
    /// application.
    #[cfg(feature = "ms")]
    AttPrepareWritePermitRequest(AttPrepareWritePermitRequest),
}

/// Enumeration of vendor-specific status codes.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum Status {
    /// The command cannot be executed due to the current state of the device.
    Failed = 0x41,
    /// Some parameters are invalid.
    InvalidParameters = 0x42,
    /// It is not allowed to start the procedure (e.g. another the procedure is ongoing or cannot be
    /// started on the given handle).
    NotAllowed = 0x46,
    /// Unexpected error.
    Error = 0x47,
    /// The address was not resolved.
    AddressNotResolved = 0x48,
    /// Failed to read from flash.
    FlashReadFailed = 0x49,
    /// Failed to write to flash.
    FlashWriteFailed = 0x4A,
    /// Failed to erase flash.
    FlashEraseFailed = 0x4B,
    /// Invalid CID
    InvalidCid = 0x50,
    /// Timer is not valid
    TimerNotValidLayer = 0x54,
    /// Insufficient resources to create the timer
    TimerInsufficientResources = 0x55,
    /// Connection signature resolving key (CSRK) is not found.
    CsrkNotFound = 0x5A,
    /// Identity resolving key (IRK) is not found
    IrkNotFound = 0x5B,
    /// The device is not in the security database.
    DeviceNotFoundInDatabase = 0x5C,
    /// The security database is full.
    SecurityDatabaseFull = 0x5D,
    /// The device is not bonded.
    DeviceNotBonded = 0x5E,
    /// The device is blacklisted.
    DeviceInBlacklist = 0x5F,
    /// The handle (service, characteristic, or descriptor) is invalid.
    InvalidHandle = 0x60,
    /// A parameter is invalid
    InvalidParameter = 0x61,
    /// The characteristic handle is not part of the service.
    OutOfHandle = 0x62,
    /// The operation is invalid
    InvalidOperation = 0x63,
    /// Insufficient resources to complete the operation.
    InsufficientResources = 0x64,
    /// The encryption key size is too small
    InsufficientEncryptionKeySize = 0x65,
    /// The characteristic already exists.
    CharacteristicAlreadyExists = 0x66,
    /// Returned when no valid slots are available (e.g. when there are no available state
    /// machines).
    NoValidSlot = 0x82,
    /// Returned when a scan window shorter than minimum allowed value has been requested
    /// (i.e. 2ms). The Rust API should prevent this error from occurring.
    ScanWindowTooShort = 0x83,
    /// Returned when the maximum requested interval to be allocated is shorter then the current
    /// anchor period and a there is no submultiple for the current anchor period that is between
    /// the minimum and the maximum requested intervals.
    NewIntervalFailed = 0x84,
    /// Returned when the maximum requested interval to be allocated is greater than the current
    /// anchor period and there is no multiple of the anchor period that is between the minimum and
    /// the maximum requested intervals.
    IntervalTooLarge = 0x85,
    /// Returned when the current anchor period or a new one can be found that is compatible to the
    /// interval range requested by the new slot but the maximum available length that can be
    /// allocated is less than the minimum requested slot length.
    LengthFailed = 0x86,
    /// MCU Library timed out.
    Timeout = 0xFF,
    /// MCU library: profile already initialized.
    ProfileAlreadyInitialized = 0xF0,
    /// MCU library: A parameter was null.
    NullParameter = 0xF1,
}

impl TryFrom<u8> for Status {
    type Error = hci::BadStatusError;

    fn try_from(value: u8) -> Result<Status, Self::Error> {
        match value {
            0x41 => Ok(Status::Failed),
            0x42 => Ok(Status::InvalidParameters),
            0x46 => Ok(Status::NotAllowed),
            0x47 => Ok(Status::Error),
            0x48 => Ok(Status::AddressNotResolved),
            0x49 => Ok(Status::FlashReadFailed),
            0x4A => Ok(Status::FlashWriteFailed),
            0x4B => Ok(Status::FlashEraseFailed),
            0x50 => Ok(Status::InvalidCid),
            0x54 => Ok(Status::TimerNotValidLayer),
            0x55 => Ok(Status::TimerInsufficientResources),
            0x5A => Ok(Status::CsrkNotFound),
            0x5B => Ok(Status::IrkNotFound),
            0x5C => Ok(Status::DeviceNotFoundInDatabase),
            0x5D => Ok(Status::SecurityDatabaseFull),
            0x5E => Ok(Status::DeviceNotBonded),
            0x5F => Ok(Status::DeviceInBlacklist),
            0x60 => Ok(Status::InvalidHandle),
            0x61 => Ok(Status::InvalidParameter),
            0x62 => Ok(Status::OutOfHandle),
            0x63 => Ok(Status::InvalidOperation),
            0x64 => Ok(Status::InsufficientResources),
            0x65 => Ok(Status::InsufficientEncryptionKeySize),
            0x66 => Ok(Status::CharacteristicAlreadyExists),
            0x82 => Ok(Status::NoValidSlot),
            0x83 => Ok(Status::ScanWindowTooShort),
            0x84 => Ok(Status::NewIntervalFailed),
            0x85 => Ok(Status::IntervalTooLarge),
            0x86 => Ok(Status::LengthFailed),
            0xFF => Ok(Status::Timeout),
            0xF0 => Ok(Status::ProfileAlreadyInitialized),
            0xF1 => Ok(Status::NullParameter),
            _ => Err(hci::BadStatusError::BadValue(value)),
        }
    }
}

impl Into<u8> for Status {
    fn into(self) -> u8 {
        self as u8
    }
}

/// Enumeration of potential errors when sending commands or deserializing events.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BlueNRGError {
    /// The event is not recoginized. Includes the unknown opcode.
    UnknownEvent(u16),

    /// For the [HalInitialized](BlueNRGEvent::HalInitialized) event: the reset reason was not
    /// recognized. Includes the unrecognized byte.
    UnknownResetReason(u8),

    /// For the [EventsLost](BlueNRGEvent::EventsLost) event: The event included unrecognized event
    /// flags. Includes the entire bitfield.
    #[cfg(feature = "ms")]
    BadEventFlags(u64),

    /// For the [CrashReport](BlueNRGEvent::CrashReport) event: The crash reason was not
    /// recognized. Includes the unrecognized byte.
    #[cfg(feature = "ms")]
    UnknownCrashReason(u8),

    /// For the [GAP Pairing Complete](BlueNRGEvent::GapPairingComplete) event: The status was not
    /// recognized. Includes the unrecognized byte.
    BadGapPairingStatus(u8),

    /// For the [GAP Device Found](BlueNRGEvent::GapDeviceFound) event: the type of event was not
    /// recognized. Includes the unrecognized byte.
    BadGapDeviceFoundEvent(u8),

    /// For the [GAP Device Found](BlueNRGEvent::GapDeviceFound) event: the type of BDADDR was not
    /// recognized. Includes the unrecognized byte.
    BadGapBdAddrType(u8),

    /// For the [GAP Procedure Complete](BlueNRGEvent::GapProcedureComplete) event: The procedure
    /// code was not recognized. Includes the unrecognized byte.
    BadGapProcedure(u8),

    /// For the [GAP Procedure Complete](BlueNRGEvent::GapProcedureComplete) event: The procedure
    /// status was not recognized. Includes the unrecognized byte.
    BadGapProcedureStatus(u8),

    /// For any L2CAP event: The event data length did not match the expected length. The first
    /// field is the required length, and the second is the actual length.
    BadL2CapDataLength(u8, u8),

    /// For any L2CAP event: The L2CAP length did not match the expected length. The first field is
    /// the required length, and the second is the actual length.
    BadL2CapLength(u16, u16),

    /// For any L2CAP response event: The L2CAP command was rejected, but the rejection reason was
    /// not recognized. Includes the unknown value.
    BadL2CapRejectionReason(u16),

    /// For the [L2CAP Connection Update Response](BlueNRGEvent::L2CapConnectionUpdateResponse)
    /// event: The code byte did not indicate either Rejected or Updated. Includes the invalid byte.
    BadL2CapConnectionResponseCode(u8),

    /// For the [L2CAP Connection Update Response](BlueNRGEvent::L2CapConnectionUpdateResponse)
    /// event: The command was accepted, but the result was not recognized. It did not indicate the
    /// parameters were either updated or rejected. Includes the unknown value.
    BadL2CapConnectionResponseResult(u16),

    /// For the [L2CAP Connection Update Request](BlueNRGEvent::L2CapConnectionUpdateRequest) event:
    /// The provided connection interval is invalid. Includes the underlying error.
    BadConnectionInterval(ConnectionIntervalError),

    /// For the [L2CAP Connection Update Request](BlueNRGEvent::L2CapConnectionUpdateRequest) event:
    /// The provided interval is invalid. Potential errors:
    /// - Either the minimum or maximum is out of range. The minimum value for either is 7.5 ms, and
    ///   the maximum is 4 s.
    /// - The min is greater than the max
    ///
    /// See the Bluetooth specification, Vol 3, Part A, Section 4.20. Versions 4.1, 4.2 and 5.0.
    ///
    /// Inclues the provided minimum and maximum, respectively.
    BadL2CapConnectionUpdateRequestInterval(Duration, Duration),

    /// For the [L2CAP Connection Update Request](BlueNRGEvent::L2CapConnectionUpdateRequest) event:
    /// The provided connection latency is invalid. The maximum value for connection latency is
    /// defined in terms of the timeout and maximum connection interval.
    /// - `connIntervalMax = Interval Max`
    /// - `connSupervisionTimeout = Timeout`
    /// - `maxConnLatency = min(500, ((connSupervisionTimeout / (2 * connIntervalMax)) - 1))`
    ///
    /// See the Bluetooth specification, Vol 3, Part A, Section 4.20. Versions 4.1, 4.2 and 5.0.
    ///
    /// Inclues the provided value and maximum allowed value, respectively.
    BadL2CapConnectionUpdateRequestLatency(u16, u16),

    /// For the [L2CAP Connection Update Request](BlueNRGEvent::L2CapConnectionUpdateRequest) event:
    /// The provided timeout is invalid. The timeout field shall have a value in the range of 100 ms
    /// to 32 seconds (inclusive).
    ///
    /// See the Bluetooth specification, Vol 3, Part A, Section 4.20. Versions 4.1, 4.2 and 5.0.
    ///
    /// Inclues the provided value.
    BadL2CapConnectionUpdateRequestTimeout(Duration),

    /// For the [ATT Find Information Response](BlueNRGEvent::AttFindInformationResponse) event: The
    /// format code is invalid. Includes the unrecognized byte.
    BadAttFindInformationResponseFormat(u8),

    /// For the [ATT Find Information Response](BlueNRGEvent::AttFindInformationResponse) event: The
    /// format code indicated 16-bit UUIDs, but the packet ends with a partial pair.
    AttFindInformationResponsePartialPair16,

    /// For the [ATT Find Information Response](BlueNRGEvent::AttFindInformationResponse) event: The
    /// format code indicated 128-bit UUIDs, but the packet ends with a partial pair.
    AttFindInformationResponsePartialPair128,

    /// For the [ATT Find by Type Value Response](BlueNRGEvent::AttFindByTypeValueResponse) event:
    /// The packet ends with a partial attribute pair.
    AttFindByTypeValuePartial,

    /// For the [ATT Read by Type Response](BlueNRGEvent::AttReadByTypeResponse) event: The packet
    /// ends with a partial attribute handle-value pair.
    AttReadByTypeResponsePartial,

    /// For the [ATT Read by Group Type Response](BlueNRGEvent::AttReadByGroupTypeResponse) event:
    /// The packet ends with a partial attribute data group.
    AttReadByGroupTypeResponsePartial,

    /// For the [GATT Procedure Complete](BlueNRGEvent::GattProcedureComplete) event: The status
    /// code was not recognized. Includes the unrecognized byte.
    BadGattProcedureStatus(u8),

    /// For the [ATT Error Response](BlueNRGEvent::AttErrorResponse) event: The request opcode was
    /// not recognized. Includes the unrecognized byte.
    BadAttRequestOpcode(u8),

    /// For the [ATT Error Response](BlueNRGEvent::AttErrorResponse) event: The error code was not
    /// recognized. Includes the unrecognized byte.
    BadAttError(u8),

    /// For the [ATT Read Multiple Permit Request](BlueNRGEvent::AttReadMultiplePermitRequest)
    /// event: The packet ends with a partial attribute handle.
    AttReadMultiplePermitRequestPartial,

    /// For the [HAL Read Config Data](::hal::Commands::read_config_data) command complete
    /// [event](command::ReturnParameters::HalReadConfigData): The returned value has a length that
    /// does not correspond to a requested parameter. Known lengths are 1, 2, 6, or 16. Includes the
    /// number of bytes returned.
    BadConfigParameterLength(usize),

    /// For the [HAL Get Link Status](::hal::Commands::get_link_status) command complete
    /// [event](command::ReturnParameters::HalGetLinkStatus): One of the bytes representing a link
    /// state does not represent a known link state. Returns the unknown value.
    UnknownLinkState(u8),

    /// For the [GAP Get Security Level](::gap::Commands::get_security_level) command complete
    /// [event](command::ReturnParameters::GapGetSecurityLevel): One of the boolean values
    /// ([`mitm_protection_required`](command::GapSecurityLevel::mitm_protection_required),
    /// [`bonding_required`](command::GapSecurityLevel::bonding_required), or
    /// [`out_of_band_data_present`](command::GapSecurityLevel::out_of_band_data_present)) was
    /// neither 0 nor 1. The unknown value is provided.
    BadBooleanValue(u8),

    /// For the [GAP Get Security Level](::gap::Commands::get_security_level) command complete
    /// [event](command::ReturnParameters::GapGetSecurityLevel): the pass key requirement field was
    /// an invalid value. The unknown byte is provided.
    BadPassKeyRequirement(u8),

    /// For the [GAP Get Bonded Devices](::gap::Commands::get_bonded_devices) command complete
    /// [event](command::ReturnParameters::GapGetBondedDevices): the packat was not long enough to
    /// contain the number of addresses it claimed to contain.
    PartialBondedDeviceAddress,

    /// For the [GAP Get Bonded Devices](::gap::Commands::get_bonded_devices) command complete
    /// [event](command::ReturnParameters::GapGetBondedDevices): one of the address type bytes was
    /// invalid. Includes the invalid byte.
    BadBdAddrType(u8),
}

macro_rules! require_len {
    ($left:expr, $right:expr) => {
        if $left.len() != $right {
            return Err(hci::event::Error::BadLength($left.len(), $right));
        }
    };
}

macro_rules! require_len_at_least {
    ($left:expr, $right:expr) => {
        if $left.len() < $right {
            return Err(hci::event::Error::BadLength($left.len(), $right));
        }
    };
}

fn first_16<T>(buffer: &[T]) -> &[T] {
    if buffer.len() < 16 {
        &buffer
    } else {
        &buffer[..16]
    }
}

impl hci::event::VendorEvent for BlueNRGEvent {
    type Error = BlueNRGError;
    type ReturnParameters = command::ReturnParameters;
    type Status = Status;

    fn new(buffer: &[u8]) -> Result<BlueNRGEvent, hci::event::Error<BlueNRGError>> {
        require_len_at_least!(buffer, 2);

        let event_code = LittleEndian::read_u16(&buffer[0..=1]);
        match event_code {
            0x0001 => Ok(BlueNRGEvent::HalInitialized(to_hal_initialized(buffer)?)),
            0x0002 => {
                #[cfg(feature = "ms")]
                {
                    Ok(BlueNRGEvent::EventsLost(to_lost_event(buffer)?))
                }

                #[cfg(not(feature = "ms"))]
                {
                    Err(hci::event::Error::Vendor(BlueNRGError::UnknownEvent(
                        event_code,
                    )))
                }
            }
            0x0003 => {
                #[cfg(feature = "ms")]
                {
                    Ok(BlueNRGEvent::CrashReport(to_crash_report(buffer)?))
                }

                #[cfg(not(feature = "ms"))]
                {
                    Err(hci::event::Error::Vendor(BlueNRGError::UnknownEvent(
                        event_code,
                    )))
                }
            }
            0x0400 => Ok(BlueNRGEvent::GapLimitedDiscoverableTimeout),
            0x0401 => Ok(BlueNRGEvent::GapPairingComplete(to_gap_pairing_complete(
                buffer,
            )?)),
            0x0402 => Ok(BlueNRGEvent::GapPassKeyRequest(to_conn_handle(buffer)?)),
            0x0403 => Ok(BlueNRGEvent::GapAuthorizationRequest(to_conn_handle(
                buffer,
            )?)),
            0x0404 => Ok(BlueNRGEvent::GapPeripheralSecurityInitiated),
            0x0405 => Ok(BlueNRGEvent::GapBondLost),
            0x0406 => Ok(BlueNRGEvent::GapDeviceFound(to_gap_device_found(buffer)?)),
            0x0407 => Ok(BlueNRGEvent::GapProcedureComplete(
                to_gap_procedure_complete(buffer)?,
            )),
            0x0408 => {
                #[cfg(feature = "ms")]
                {
                    Ok(BlueNRGEvent::GapAddressNotResolved(to_conn_handle(buffer)?))
                }

                #[cfg(not(feature = "ms"))]
                {
                    Ok(BlueNRGEvent::GapReconnectionAddress(
                        to_gap_reconnection_address(buffer)?,
                    ))
                }
            }
            0x0800 => Ok(BlueNRGEvent::L2CapConnectionUpdateResponse(
                to_l2cap_connection_update_response(buffer)?,
            )),
            0x0801 => Ok(BlueNRGEvent::L2CapProcedureTimeout(
                to_l2cap_procedure_timeout(buffer)?,
            )),
            0x0802 => Ok(BlueNRGEvent::L2CapConnectionUpdateRequest(
                to_l2cap_connection_update_request(buffer)?,
            )),
            0x0C01 => Ok(BlueNRGEvent::GattAttributeModified(
                to_gatt_attribute_modified(buffer)?,
            )),
            0x0C02 => Ok(BlueNRGEvent::GattProcedureTimeout(to_conn_handle(buffer)?)),
            0x0C03 => Ok(BlueNRGEvent::AttExchangeMtuResponse(
                to_att_exchange_mtu_resp(buffer)?,
            )),
            0x0C04 => Ok(BlueNRGEvent::AttFindInformationResponse(
                to_att_find_information_response(buffer)?,
            )),
            0x0C05 => Ok(BlueNRGEvent::AttFindByTypeValueResponse(
                to_att_find_by_value_type_response(buffer)?,
            )),
            0x0C06 => Ok(BlueNRGEvent::AttReadByTypeResponse(
                to_att_read_by_type_response(buffer)?,
            )),
            0x0C07 => Ok(BlueNRGEvent::AttReadResponse(to_att_read_response(buffer)?)),
            0x0C08 => Ok(BlueNRGEvent::AttReadBlobResponse(to_att_read_response(
                buffer,
            )?)),
            0x0C09 => Ok(BlueNRGEvent::AttReadMultipleResponse(to_att_read_response(
                buffer,
            )?)),
            0x0C0A => Ok(BlueNRGEvent::AttReadByGroupTypeResponse(
                to_att_read_by_group_type_response(buffer)?,
            )),
            0x0C0C => Ok(BlueNRGEvent::AttPrepareWriteResponse(
                to_att_prepare_write_response(buffer)?,
            )),
            0x0C0D => Ok(BlueNRGEvent::AttExecuteWriteResponse(to_conn_handle(
                buffer,
            )?)),
            0x0C0E => Ok(BlueNRGEvent::GattIndication(to_attribute_value(buffer)?)),
            0x0C0F => Ok(BlueNRGEvent::GattNotification(to_attribute_value(buffer)?)),
            0x0C10 => Ok(BlueNRGEvent::GattProcedureComplete(
                to_gatt_procedure_complete(buffer)?,
            )),
            0x0C11 => Ok(BlueNRGEvent::AttErrorResponse(to_att_error_response(
                buffer,
            )?)),
            0x0C12 => Ok(
                BlueNRGEvent::GattDiscoverOrReadCharacteristicByUuidResponse(to_attribute_value(
                    buffer,
                )?),
            ),
            0x0C13 => Ok(BlueNRGEvent::AttWritePermitRequest(
                to_write_permit_request(buffer)?,
            )),
            0x0C14 => Ok(BlueNRGEvent::AttReadPermitRequest(
                to_att_read_permit_request(buffer)?,
            )),
            0x0C15 => Ok(BlueNRGEvent::AttReadMultiplePermitRequest(
                to_att_read_multiple_permit_request(buffer)?,
            )),
            0x0C16 => {
                #[cfg(feature = "ms")]
                {
                    Ok(BlueNRGEvent::GattTxPoolAvailable(
                        to_gatt_tx_pool_available(buffer)?,
                    ))
                }

                #[cfg(not(feature = "ms"))]
                {
                    Err(hci::event::Error::Vendor(BlueNRGError::UnknownEvent(
                        event_code,
                    )))
                }
            }
            0x0C17 => {
                #[cfg(feature = "ms")]
                {
                    Ok(BlueNRGEvent::GattServerConfirmation(to_conn_handle(
                        buffer,
                    )?))
                }

                #[cfg(not(feature = "ms"))]
                {
                    Err(hci::event::Error::Vendor(BlueNRGError::UnknownEvent(
                        event_code,
                    )))
                }
            }
            0x0C18 => {
                #[cfg(feature = "ms")]
                {
                    Ok(BlueNRGEvent::AttPrepareWritePermitRequest(
                        to_att_prepare_write_permit_request(buffer)?,
                    ))
                }

                #[cfg(not(feature = "ms"))]
                {
                    Err(hci::event::Error::Vendor(BlueNRGError::UnknownEvent(
                        event_code,
                    )))
                }
            }
            _ => Err(hci::event::Error::Vendor(BlueNRGError::UnknownEvent(
                event_code,
            ))),
        }
    }
}

/// Potential reasons the controller sent the [HalInitialized](BlueNRGEvent::HalInitialized) event.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ResetReason {
    /// Firmware started properly
    Normal,
    /// Updater mode entered because of updater_start command
    Updater,
    /// Updater mode entered because of a bad BLUE flag
    UpdaterBadFlag,
    /// Updater mode entered with IRQ pin
    UpdaterPin,
    /// Reset caused by watchdog
    Watchdog,
    /// Reset due to lockup
    Lockup,
    /// Brownout reset
    Brownout,
    /// Reset caused by a crash (NMI or Hard Fault)
    Crash,
    /// Reset caused by an ECC error
    EccError,
}

impl TryFrom<u8> for ResetReason {
    type Error = BlueNRGError;

    fn try_from(value: u8) -> Result<ResetReason, Self::Error> {
        match value {
            1 => Ok(ResetReason::Normal),
            2 => Ok(ResetReason::Updater),
            3 => Ok(ResetReason::UpdaterBadFlag),
            4 => Ok(ResetReason::UpdaterPin),
            5 => Ok(ResetReason::Watchdog),
            6 => Ok(ResetReason::Lockup),
            7 => Ok(ResetReason::Brownout),
            8 => Ok(ResetReason::Crash),
            9 => Ok(ResetReason::EccError),
            _ => Err(BlueNRGError::UnknownResetReason(value)),
        }
    }
}

/// Convert a buffer to the HalInitialized BlueNRGEvent.
///
/// # Errors
///
/// - Returns a BadLength HCI error if the buffer is not exactly 3 bytes long
///
/// - Returns a UnknownResetReason BlueNRG error if the reset reason is not recognized.
fn to_hal_initialized(buffer: &[u8]) -> Result<ResetReason, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 3);

    Ok(buffer[2]
        .try_into()
        .map_err(|e| hci::event::Error::Vendor(e))?)
}

#[cfg(feature = "ms")]
bitflags! {
    /// Bitfield for the [Events Lost](BlueNRGEvent::EventsLost) event. Each bit indicates a
    /// different type of event that was not handled.
    #[derive(Default)]
    pub struct EventFlags: u64 {
        /// HCI Event: [Disconnection complete](hci::event::Event::DisconnectionComplete).
        const DISCONNECTION_COMPLETE = 1 << 0;
        /// HCI Event: [Encryption change](hci::event::Event::EncryptionChange).
        const ENCRYPTION_CHANGE = 1 << 1;
        /// HCI Event: [Read Remote Version
        /// Complete](hci::event::Event::ReadRemoteVersionInformationComplete).
        const READ_REMOTE_VERSION_COMPLETE = 1 << 2;
        /// HCI Event: [Command Complete](hci::event::Event::CommandComplete).
        const COMMAND_COMPLETE = 1 << 3;
        /// HCI Event: [Command Status](hci::event::Event::CommandStatus).
        const COMMAND_STATUS = 1 << 4;
        /// HCI Event: [Hardware Error](hci::event::Event::HardwareError).
        const HARDWARE_ERROR = 1 << 5;
        /// HCI Event: [Number of completed packets](hci::event::Event::NumberOfCompletedPackets).
        const NUMBER_OF_COMPLETED_PACKETS = 1 << 6;
        /// HCI Event: [Encryption key refresh
        /// complete](hci::event::Event::EncryptionKeyRefreshComplete).
        const ENCRYPTION_KEY_REFRESH = 1 << 7;
        /// BlueNRG-MS Event: [HAL Initialized](BlueNRGEvent::HalInitialized).
        const HAL_INITIALIZED = 1 << 8;
        /// BlueNRG Event: [GAP Set Limited Discoverable
        /// complete](BlueNRGEvent::GapLimitedDiscoverableTimeout).
        const GAP_LIMITED_DISCOVERABLE_TIMEOUT = 1 << 9;
        /// BlueNRG Event: [GAP Pairing complete](BlueNRGEvent::GapPairingComplete).
        const GAP_PAIRING_COMPLETE = 1 << 10;
        /// BlueNRG Event: [GAP Pass Key Request](BlueNRGEvent::GapPassKeyRequest).
        const GAP_PASS_KEY_REQUEST = 1 << 11;
        /// BlueNRG Event: [GAP Authorization Request](BlueNRGEvent::GapAuthorizationRequest).
        const GAP_AUTHORIZATION_REQUEST = 1 << 12;
        /// BlueNRG Event: [GAP Peripheral Security
        /// Initiated](BlueNRGEvent::GapPeripheralSecurityInitiated).
        const GAP_PERIPHERAL_SECURITY_INITIATED = 1 << 13;
        /// BlueNRG Event: [GAP Bond Lost](BlueNRGEvent::GapBondLost).
        const GAP_BOND_LOST = 1 << 14;
        /// BlueNRG Event: [GAP Procedure complete](BlueNRGEvent::GapProcedureComplete).
        const GAP_PROCEDURE_COMPLETE = 1 << 15;
        /// BlueNRG-MS Event: [GAP Address Not Resolved](BlueNRGEvent::GapAddressNotResolved).
        const GAP_ADDRESS_NOT_RESOLVED = 1 << 16;
        /// BlueNRG Event: [L2Cap Connection Update
        /// Response](BlueNRGEvent::L2CapConnectionUpdateResponse).
        const L2CAP_CONNECTION_UPDATE_RESPONSE = 1 << 17;
        /// BlueNRG Event: [L2Cap Procedure Timeout](BlueNRGEvent::L2CapProcedureTimeout).
        const L2CAP_PROCEDURE_TIMEOUT = 1 << 18;
        /// BlueNRG Event: [L2Cap Connection Update
        /// Request](BlueNRGEvent::L2CapConnectionUpdateRequest).
        const L2CAP_CONNECTION_UPDATE_REQUEST = 1 << 19;
        /// BlueNRG Event: [GATT Attribute modified](BlueNRGEvent::GattAttributeModified).
        const GATT_ATTRIBUTE_MODIFIED = 1 << 20;
        /// BlueNRG Event: [GATT timeout](BlueNRGEvent::GattProcedureTimeout).
        const GATT_PROCEDURE_TIMEOUT = 1 << 21;
        /// BlueNRG Event: [Exchange MTU Response](BlueNRGEvent::AttExchangeMtuResponse).
        const ATT_EXCHANGE_MTU_RESPONSE = 1 << 22;
        /// BlueNRG Event: [Find information response](BlueNRGEvent::AttFindInformationResponse).
        const ATT_FIND_INFORMATION_RESPONSE = 1 << 23;
        /// BlueNRG Event: [Find by type value response](BlueNRGEvent::AttFindByTypeValueResponse).
        const ATT_FIND_BY_TYPE_VALUE_RESPONSE = 1 << 24;
        /// BlueNRG Event: [Find read by type response](BlueNRGEvent::AttReadByTypeResponse).
        const ATT_READ_BY_TYPE_RESPONSE = 1 << 25;
        /// BlueNRG Event: [Read response](BlueNRGEvent::AttReadResponse).
        const ATT_READ_RESPONSE = 1 << 26;
        /// BlueNRG Event: [Read blob response](BlueNRGEvent::AttReadBlobResponse).
        const ATT_READ_BLOB_RESPONSE = 1 << 27;
        /// BlueNRG Event: [Read multiple response](BlueNRGEvent::AttReadMultipleResponse).
        const ATT_READ_MULTIPLE_RESPONSE = 1 << 28;
        /// BlueNRG Event: [Read by group type response](BlueNRGEvent::AttReadByGroupTypeResponse).
        const ATT_READ_BY_GROUP_TYPE_RESPONSE = 1 << 29;
        /// BlueNRG Event: ATT Write Response
        const ATT_WRITE_RESPONSE = 1 << 30;
        /// BlueNRG Event: [Prepare Write Response](BlueNRGEvent::AttPrepareWriteResponse).
        const ATT_PREPARE_WRITE_RESPONSE = 1 << 31;
        /// BlueNRG Event: [Execute write response](BlueNRGEvent::AttExecuteWriteResponse).
        const ATT_EXECUTE_WRITE_RESPONSE = 1 << 32;
        /// BlueNRG Event: [Indication received](BlueNRGEvent::GattIndication) from server.
        const GATT_INDICATION = 1 << 33;
        /// BlueNRG Event: [Notification received](BlueNRGEvent::GattNotification) from server.
        const GATT_NOTIFICATION = 1 << 34;
        /// BlueNRG Event: [GATT Procedure complete](BlueNRGEvent::GattProcedureComplete).
        const GATT_PROCEDURE_COMPLETE = 1 << 35;
        /// BlueNRG Event: [Error response received from server](BlueNRGEvent::AttErrorResponse).
        const GATT_ERROR_RESPONSE = 1 << 36;
        /// BlueNRG Event: [Response](BlueNRGEvent::GattDiscoverOrReadCharacteristicByUuidResponse)
        /// to either "Discover Characteristic by UUID" or "Read Characteristic by UUID" request
        const GATT_DISCOVER_OR_READ_CHARACTERISTIC_BY_UUID_RESPONSE = 1 << 37;
        /// BlueNRG Event: [Write request received](BlueNRGEvent::AttWritePermitRequest) by server.
        const GATT_WRITE_PERMIT_REQUEST = 1 << 38;
        /// BlueNRG Event: [Read request received](BlueNRGEvent::AttReadPermitRequest) by server.
        const GATT_READ_PERMIT_REQUEST = 1 << 39;
        /// BlueNRG Event: [Read multiple request
        /// received](BlueNRGEvent::AttReadMultiplePermitRequest) by server.
        const GATT_READ_MULTIPLE_PERMIT_REQUEST = 1 << 40;
        /// BlueNRG-MS Event: [TX Pool available](BlueNRGEvent::GattTxPoolAvailable) event missed.
        const GATT_TX_POOL_AVAILABLE = 1 << 41;
        /// BlueNRG-MS Event: [Server confirmation](BlueNRGEvent::GattServerConfirmation).
        const GATT_SERVER_RX_CONFIRMATION = 1 << 42;
        /// BlueNRG-MS Event: [Prepare write permit
        /// request](BlueNRGEvent::AttPrepareWritePermitRequest).
        const GATT_PREPARE_WRITE_PERMIT_REQUEST = 1 << 43;
        /// BlueNRG-MS Event: Link Layer [connection
        /// complete](hci::event::Event::LeConnectionComplete).
        const LINK_LAYER_CONNECTION_COMPLETE = 1 << 44;
        /// BlueNRG-MS Event: Link Layer [advertising
        /// report](hci::event::Event::LeAdvertisingReport).
        const LINK_LAYER_ADVERTISING_REPORT = 1 << 45;
        /// BlueNRG-MS Event: Link Layer [connection update
        /// complete](hci::event::Event::LeConnectionUpdateComplete).
        const LINK_LAYER_CONNECTION_UPDATE_COMPLETE = 1 << 46;
        /// BlueNRG-MS Event: Link Layer [read remote used
        /// features](hci::event::Event::LeReadRemoteUsedFeaturesComplete).
        const LINK_LAYER_READ_REMOTE_USED_FEATURES = 1 << 47;
        /// BlueNRG-MS Event: Link Layer [long-term key
        /// request](hci::event::Event::LeLongTermKeyRequest).
        const LINK_LAYER_LTK_REQUEST = 1 << 48;
    }
}

/// Convert a buffer to the EventsLost BlueNRGEvent.
///
/// # Errors
///
/// - Returns a BadLength HCI error if the buffer is not exactly 10 bytes long
///
/// - Returns BadEventFlags if a bit is set that does not represent a lost event.
#[cfg(feature = "ms")]
fn to_lost_event(buffer: &[u8]) -> Result<EventFlags, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 10);

    let bits = LittleEndian::read_u64(&buffer[2..]);
    EventFlags::from_bits(bits).ok_or(hci::event::Error::Vendor(BlueNRGError::BadEventFlags(bits)))
}

// The maximum length of [`FaultData::debug_data`]. The maximum length of an event is 255 bytes,
// and the non-variable data of the event takes up 40 bytes.
#[cfg(feature = "ms")]
const MAX_DEBUG_DATA_LEN: usize = 215;

/// Specific reason for the fault reported with [FaultData].
#[cfg(feature = "ms")]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CrashReason {
    /// The controller reset because an assertion failed.
    Assertion,
    /// The controller reset because of an NMI fault.
    NmiFault,
    /// The controller reset because of a hard fault.
    HardFault,
}

#[cfg(feature = "ms")]
impl TryFrom<u8> for CrashReason {
    type Error = BlueNRGError;

    fn try_from(value: u8) -> Result<CrashReason, Self::Error> {
        match value {
            0 => Ok(CrashReason::Assertion),

            // The documentation is conflicting for the numeric value of NMI Fault. The
            // CubeExpansion source code says 1, but the user manual says 6.
            1 | 6 => Ok(CrashReason::NmiFault),

            // The documentation is conflicting for the numeric value of hard Fault. The
            // CubeExpansion source code says 2, but the user manual says 7.
            2 | 7 => Ok(CrashReason::HardFault),
            _ => Err(BlueNRGError::UnknownCrashReason(value)),
        }
    }
}

/// Fault data reported after a crash.
#[cfg(feature = "ms")]
#[derive(Clone, Copy)]
pub struct FaultData {
    /// Fault reason.
    pub reason: CrashReason,

    /// MCP SP register
    pub sp: u32,
    /// MCU R0 register
    pub r0: u32,
    /// MCU R1 register
    pub r1: u32,
    /// MCU R2 register
    pub r2: u32,
    /// MCU R3 register
    pub r3: u32,
    /// MCU R12 register
    pub r12: u32,
    /// MCU LR register
    pub lr: u32,
    /// MCU PC register
    pub pc: u32,
    /// MCU xPSR register
    pub xpsr: u32,

    // Number of valid bytes in debug_data
    debug_data_len: usize,

    // Additional crash dump data
    debug_data_buf: [u8; MAX_DEBUG_DATA_LEN],
}

#[cfg(feature = "ms")]
impl Debug for FaultData {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "FaultData {{ reason: {:?}, sp: {:x}, r0: {:x}, r1: {:x}, r2: {:x}, r3: {:x}, ",
            self.reason, self.sp, self.r0, self.r1, self.r2, self.r3
        )?;
        write!(
            f,
            "r12: {:x}, lr: {:x}, pc: {:x}, xpsr: {:x}, debug_data: [",
            self.r12, self.lr, self.pc, self.xpsr
        )?;
        for byte in self.debug_data() {
            write!(f, " {:x}", byte)?;
        }
        write!(f, " ] }}")
    }
}

#[cfg(feature = "ms")]
impl FaultData {
    /// Returns the valid debug data.
    pub fn debug_data(&self) -> &[u8] {
        &self.debug_data_buf[..self.debug_data_len]
    }
}

#[cfg(feature = "ms")]
fn to_crash_report(buffer: &[u8]) -> Result<FaultData, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 40);

    let debug_data_len = buffer[39] as usize;
    require_len!(buffer, 40 + debug_data_len);

    let mut fault_data = FaultData {
        reason: buffer[2].try_into().map_err(hci::event::Error::Vendor)?,
        sp: LittleEndian::read_u32(&buffer[3..]),
        r0: LittleEndian::read_u32(&buffer[7..]),
        r1: LittleEndian::read_u32(&buffer[11..]),
        r2: LittleEndian::read_u32(&buffer[15..]),
        r3: LittleEndian::read_u32(&buffer[19..]),
        r12: LittleEndian::read_u32(&buffer[23..]),
        lr: LittleEndian::read_u32(&buffer[27..]),
        pc: LittleEndian::read_u32(&buffer[31..]),
        xpsr: LittleEndian::read_u32(&buffer[35..]),
        debug_data_len: debug_data_len,
        debug_data_buf: [0; MAX_DEBUG_DATA_LEN],
    };
    fault_data.debug_data_buf[..debug_data_len].copy_from_slice(&buffer[40..]);

    Ok(fault_data)
}

macro_rules! require_l2cap_event_data_len {
    ($left:expr, $right:expr) => {
        let actual = $left[4];
        if actual != $right {
            return Err(hci::event::Error::Vendor(BlueNRGError::BadL2CapDataLength(
                actual, $right,
            )));
        }
    };
}

macro_rules! require_l2cap_len {
    ($actual:expr, $expected:expr) => {
        if $actual != $expected {
            return Err(hci::event::Error::Vendor(BlueNRGError::BadL2CapLength(
                $actual, $expected,
            )));
        }
    };
}

/// This event is generated when the central device responds to the L2CAP connection update request
/// packet.
///
/// For more info see connection parameter update response and command reject in Bluetooth Core v4.0
/// spec.
#[derive(Copy, Clone, Debug)]
pub struct L2CapConnectionUpdateResponse {
    /// The connection handle related to the event
    pub conn_handle: ConnectionHandle,

    /// The result of the update request, including details about the result.
    pub result: L2CapConnectionUpdateResult,
}

/// Reasons why an L2CAP command was rejected. see the Bluetooth specification, v4.1, Vol 3, Part A,
/// Section 4.1.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum L2CapRejectionReason {
    /// The controller sent an unknown command.
    CommandNotUnderstood,
    /// When multiple commands are included in an L2CAP packet and the packet exceeds the signaling
    /// MTU (MTUsig) of the receiver, a single Command Reject packet shall be sent in response.
    SignalingMtuExceeded,
    /// Invalid CID in request
    InvalidCid,
}

impl TryFrom<u16> for L2CapRejectionReason {
    type Error = BlueNRGError;

    fn try_from(value: u16) -> Result<L2CapRejectionReason, Self::Error> {
        match value {
            0 => Ok(L2CapRejectionReason::CommandNotUnderstood),
            1 => Ok(L2CapRejectionReason::SignalingMtuExceeded),
            2 => Ok(L2CapRejectionReason::InvalidCid),
            _ => Err(BlueNRGError::BadL2CapRejectionReason(value)),
        }
    }
}

/// Potential results that can be used in the L2CAP connection update response.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum L2CapConnectionUpdateResult {
    /// The update request was rejected. The code indicates the reason for the rejection.
    CommandRejected(L2CapRejectionReason),

    /// The L2CAP connection update response is valid. The code indicates if the parameters were
    /// rejected.
    ParametersRejected,

    /// The L2CAP connection update response is valid. The code indicates if the parameters were
    /// updated.
    ParametersUpdated,
}

fn to_l2cap_connection_update_accepted_result(
    value: u16,
) -> Result<L2CapConnectionUpdateResult, BlueNRGError> {
    match value {
        0x0000 => Ok(L2CapConnectionUpdateResult::ParametersUpdated),
        0x0001 => Ok(L2CapConnectionUpdateResult::ParametersRejected),
        _ => {
            return Err(BlueNRGError::BadL2CapConnectionResponseResult(value));
        }
    }
}

fn extract_l2cap_connection_update_response_result(
    buffer: &[u8],
) -> Result<L2CapConnectionUpdateResult, BlueNRGError> {
    match buffer[5] {
        0x01 => Ok(L2CapConnectionUpdateResult::CommandRejected(
            LittleEndian::read_u16(&buffer[9..]).try_into()?,
        )),
        0x13 => to_l2cap_connection_update_accepted_result(LittleEndian::read_u16(&buffer[9..])),
        _ => Err(BlueNRGError::BadL2CapConnectionResponseCode(buffer[5])),
    }
}

fn to_l2cap_connection_update_response(
    buffer: &[u8],
) -> Result<L2CapConnectionUpdateResponse, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 11);
    require_l2cap_event_data_len!(buffer, 6);
    require_l2cap_len!(LittleEndian::read_u16(&buffer[7..]), 2);

    Ok(L2CapConnectionUpdateResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        result: extract_l2cap_connection_update_response_result(buffer)
            .map_err(hci::event::Error::Vendor)?,
    })
}

/// This event is generated when the central device does not respond to the connection update
/// request within 30 seconds.
#[derive(Copy, Clone, Debug)]
pub struct L2CapProcedureTimeout {
    /// The connection handle related to the event.
    pub conn_handle: ConnectionHandle,
}

fn to_l2cap_procedure_timeout(
    buffer: &[u8],
) -> Result<ConnectionHandle, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 5);
    require_l2cap_event_data_len!(buffer, 0);

    Ok(ConnectionHandle(LittleEndian::read_u16(&buffer[2..])))
}

/// The event is given by the L2CAP layer when a connection update request is received from the
/// peripheral.
///
/// The application has to respond by calling
/// [`l2cap_connection_parameter_update_response`](::l2cap::Commands::connection_parameter_update_response).
///
/// Defined in Vol 3, Part A, section 4.20 of the Bluetooth specification.
#[derive(Copy, Clone, Debug)]
pub struct L2CapConnectionUpdateRequest {
    /// Handle of the connection for which the connection update request has been received.  The
    /// [same handle](::l2cap::ConnectionParameterUpdateResponse::conn_handle) has to be returned
    /// while responding to the event with the command
    /// [`l2cap_connection_parameter_update_response`](::l2cap::Commands::connection_parameter_update_response).
    pub conn_handle: ConnectionHandle,

    /// This is the identifier which associates the request to the response. The [same
    /// identifier](::l2cap::ConnectionParameterUpdateResponse::identifier) has to be returned by
    /// the upper layer in the command
    /// [`l2cap_connection_parameter_update_response`](::l2cap::Commands::connection_parameter_update_response).
    pub identifier: u8,

    /// Defines the range of the connection interval, the latency, and the supervision timeout.
    pub conn_interval: ConnectionInterval,
}

fn to_l2cap_connection_update_request(
    buffer: &[u8],
) -> Result<L2CapConnectionUpdateRequest, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 16);
    require_l2cap_event_data_len!(buffer, 11);
    require_l2cap_len!(LittleEndian::read_u16(&buffer[6..]), 8);

    let interval = ConnectionInterval::from_bytes(&buffer[8..16])
        .map_err(BlueNRGError::BadConnectionInterval)
        .map_err(hci::event::Error::Vendor)?;

    Ok(L2CapConnectionUpdateRequest {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        identifier: buffer[5],
        conn_interval: interval,
    })
}

/// This event is generated when the pairing process has completed successfully or a pairing
/// procedure timeout has occurred or the pairing has failed. This is to notify the application that
/// we have paired with a remote device so that it can take further actions or to notify that a
/// timeout has occurred so that the upper layer can decide to disconnect the link.
#[derive(Copy, Clone, Debug)]
pub struct GapPairingComplete {
    /// Connection handle on which the pairing procedure completed
    pub conn_handle: ConnectionHandle,

    /// Reason the pairing is complete.
    pub status: GapPairingStatus,
}

/// Reasons the [GAP Pairing Complete](BlueNRGEvent::GapPairingComplete) event was generated.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum GapPairingStatus {
    /// Pairing with a remote device was successful.
    Success,
    /// The SMP timeout has elapsed and no further SMP commands will be processed until
    /// reconnection.
    Timeout,
    /// The pairing failed with the remote device.
    Failed,
}

impl TryFrom<u8> for GapPairingStatus {
    type Error = BlueNRGError;

    fn try_from(value: u8) -> Result<GapPairingStatus, Self::Error> {
        match value {
            0 => Ok(GapPairingStatus::Success),
            1 => Ok(GapPairingStatus::Timeout),
            2 => Ok(GapPairingStatus::Failed),
            _ => Err(BlueNRGError::BadGapPairingStatus(value)),
        }
    }
}

fn to_gap_pairing_complete(
    buffer: &[u8],
) -> Result<GapPairingComplete, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 5);
    Ok(GapPairingComplete {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        status: buffer[4].try_into().map_err(hci::event::Error::Vendor)?,
    })
}

fn to_conn_handle(buffer: &[u8]) -> Result<ConnectionHandle, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 4);
    Ok(ConnectionHandle(LittleEndian::read_u16(&buffer[2..])))
}

/// The event is given by the GAP layer to the upper layers when a device is discovered during
/// scanning as a consequence of one of the GAP procedures started by the upper layers.
#[derive(Copy, Clone, Debug)]
pub struct GapDeviceFound {
    /// Type of event
    pub event: GapDeviceFoundEvent,

    /// Address of the peer device found during scanning
    pub bdaddr: BdAddrType,

    // Length of significant data
    data_len: usize,

    // Advertising or scan response data.
    data_buf: [u8; 31],

    /// Received signal strength indicator (range: -127 - 20).
    pub rssi: Option<i8>,
}

impl GapDeviceFound {
    /// Returns the valid scan response data.
    pub fn data(&self) -> &[u8] {
        &self.data_buf[..self.data_len]
    }
}

pub use hci::event::AdvertisementEvent as GapDeviceFoundEvent;

fn to_gap_device_found(buffer: &[u8]) -> Result<GapDeviceFound, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 12);

    let data_len = buffer[10] as usize;
    require_len!(buffer, 12 + data_len);

    const RSSI_UNAVAILABLE: i8 = 127;
    let rssi = unsafe { mem::transmute::<u8, i8>(buffer[buffer.len() - 1]) };

    let mut addr = BdAddr([0; 6]);
    addr.0.copy_from_slice(&buffer[4..10]);
    let mut event = GapDeviceFound {
        event: buffer[2].try_into().map_err(|e| {
            if let hci::event::Error::BadLeAdvertisementType(code) = e {
                hci::event::Error::Vendor(BlueNRGError::BadGapDeviceFoundEvent(code))
            } else {
                unreachable!()
            }
        })?,
        bdaddr: hci::to_bd_addr_type(buffer[3], addr)
            .map_err(|e| hci::event::Error::Vendor(BlueNRGError::BadGapBdAddrType(e.0)))?,
        data_len: data_len,
        data_buf: [0; 31],
        rssi: if rssi == RSSI_UNAVAILABLE {
            None
        } else {
            Some(rssi)
        },
    };
    event.data_buf[..event.data_len].copy_from_slice(&buffer[11..buffer.len() - 1]);

    Ok(event)
}

/// This event is sent by the GAP to the upper layers when a procedure previously started has been
/// terminated by the upper layer or has completed for any other reason
#[derive(Copy, Clone, Debug)]
pub struct GapProcedureComplete {
    /// Type of procedure that completed
    pub procedure: GapProcedure,
    /// Status of the procedure
    pub status: GapProcedureStatus,
}

/// Maximum length of the name returned in the [NameDiscovery](GapProcedure::NameDiscovery)
/// procedure.
pub const MAX_NAME_LEN: usize = 248;

/// Newtype for the name buffer returned after successful
/// [NameDiscovery](GapProcedure::NameDiscovery).
#[derive(Copy, Clone)]
pub struct NameBuffer(pub [u8; MAX_NAME_LEN]);

impl Debug for NameBuffer {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        first_16(&self.0).fmt(f)
    }
}

impl PartialEq<NameBuffer> for NameBuffer {
    fn eq(&self, other: &NameBuffer) -> bool {
        if self.0.len() != other.0.len() {
            return false;
        }

        for (a, b) in self.0.iter().zip(other.0.iter()) {
            if a != b {
                return false;
            }
        }

        return true;
    }
}

/// Procedures whose completion may be reported by
/// [GapProcedureComplete](BlueNRGEvent::GapProcedureComplete).
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum GapProcedure {
    /// See Vol 3, Part C, section 9.2.5.
    LimitedDiscovery,
    /// See Vol 3, Part C, section 9.2.6.
    GeneralDiscovery,
    /// See Vol 3, Part C, section 9.2.7. Contains the number of valid bytes and buffer with enough
    /// space for the maximum length of the name that can be retuned.
    NameDiscovery(usize, NameBuffer),
    /// See Vol 3, Part C, section 9.3.5.
    AutoConnectionEstablishment,
    /// See Vol 3, Part C, section 9.3.6. Contains the reconnection address.
    GeneralConnectionEstablishment(BdAddr),
    /// See Vol 3, Part C, section 9.3.7.
    SelectiveConnectionEstablishment,
    /// See Vol 3, Part C, section 9.3.8.
    DirectConnectionEstablishment,
}

/// Possible results of a [GAP procedure](BlueNRGEvent::GapProcedureComplete).
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum GapProcedureStatus {
    /// BLE Status Success.
    Success,
    /// BLE Status Failed.
    Failed,
    /// Procedure failed due to authentication requirements.
    AuthFailure,
}

impl TryFrom<u8> for GapProcedureStatus {
    type Error = BlueNRGError;

    fn try_from(value: u8) -> Result<GapProcedureStatus, Self::Error> {
        match value {
            0x00 => Ok(GapProcedureStatus::Success),
            0x41 => Ok(GapProcedureStatus::Failed),
            0x05 => Ok(GapProcedureStatus::AuthFailure),
            _ => Err(BlueNRGError::BadGapProcedureStatus(value)),
        }
    }
}

fn to_gap_procedure_complete(
    buffer: &[u8],
) -> Result<GapProcedureComplete, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 4);

    let procedure = match buffer[2] {
        0x01 => GapProcedure::LimitedDiscovery,
        0x02 => GapProcedure::GeneralDiscovery,
        0x04 => {
            require_len_at_least!(buffer, 5);
            let name_len = buffer.len() - 4;
            let mut name = NameBuffer([0; MAX_NAME_LEN]);
            name.0[..name_len].copy_from_slice(&buffer[4..]);

            GapProcedure::NameDiscovery(name_len, name)
        }
        0x08 => GapProcedure::AutoConnectionEstablishment,
        0x10 => {
            require_len!(buffer, 10);
            let mut addr = BdAddr([0; 6]);
            addr.0.copy_from_slice(&buffer[4..10]);
            GapProcedure::GeneralConnectionEstablishment(addr)
        }
        0x20 => GapProcedure::SelectiveConnectionEstablishment,
        0x40 => GapProcedure::DirectConnectionEstablishment,
        _ => {
            return Err(hci::event::Error::Vendor(BlueNRGError::BadGapProcedure(
                buffer[2],
            )));
        }
    };

    Ok(GapProcedureComplete {
        procedure: procedure,
        status: buffer[3].try_into().map_err(hci::event::Error::Vendor)?,
    })
}

#[cfg(not(feature = "ms"))]
fn to_gap_reconnection_address(buffer: &[u8]) -> Result<BdAddr, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 8);
    let mut addr = BdAddr([0; 6]);
    addr.0.copy_from_slice(&buffer[2..]);
    Ok(addr)
}

/// This event is generated to the application by the ATT server when a client modifies any
/// attribute on the server, as consequence of one of the following ATT procedures:
/// - write without response
/// - signed write without response
/// - write characteristic value
/// - write long characteristic value
/// - reliable write
#[derive(Copy, Clone)]
pub struct GattAttributeModified {
    /// The connection handle which modified the attribute
    pub conn_handle: ConnectionHandle,
    ///  Handle of the attribute that was modified
    pub attr_handle: AttributeHandle,

    /// Offset of the reported value inside the attribute.
    #[cfg(feature = "ms")]
    pub offset: usize,

    /// If the entire value of the attribute does not fit inside a single GattAttributeModified
    /// event, this is true to notify that other GattAttributeModified events will follow to report
    /// the remaining value.
    #[cfg(feature = "ms")]
    pub continued: bool,

    /// Number of valid bytes in |data|.
    data_len: usize,
    /// The new attribute value, starting from the given offset. If compiling with "ms" support, the
    /// offset is 0.
    data_buf: [u8; MAX_ATTRIBUTE_LEN],
}

impl GattAttributeModified {
    /// Returns the valid attribute data returned by the ATT attribute modified event as a slice of
    /// bytes.
    pub fn data(&self) -> &[u8] {
        &self.data_buf[..self.data_len]
    }
}

/// Newtype for an attribute handle. These handles are IDs, not general integers, and should not be
/// manipulated as such.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct AttributeHandle(pub u16);

// Defines the maximum length of a ATT attribute value field. This is determined by the max packet
// size (255) less the minimum number of bytes used by other fields in any packet.
const MAX_ATTRIBUTE_LEN: usize = 248;

impl Debug for GattAttributeModified {
    #[cfg(feature = "ms")]
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{conn_handle: {:?}, attr_handle: {:?}, offset: {}, continued: {}, data: {:?}}}",
            self.conn_handle,
            self.attr_handle,
            self.offset,
            self.continued,
            first_16(self.data()),
        )
    }

    #[cfg(not(feature = "ms"))]
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{conn_handle: {:?}, attr_handle: {:?}, data: {:?}}}",
            self.conn_handle,
            self.attr_handle,
            first_16(self.data()),
        )
    }
}

#[cfg(feature = "ms")]
fn to_gatt_attribute_modified(
    buffer: &[u8],
) -> Result<GattAttributeModified, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 9);

    let data_len = buffer[6] as usize;
    require_len!(buffer, 9 + data_len);

    let mut data = [0; MAX_ATTRIBUTE_LEN];
    data[..data_len].copy_from_slice(&buffer[9..]);

    let offset_field = LittleEndian::read_u16(&buffer[7..]);
    Ok(GattAttributeModified {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attr_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
        offset: (offset_field & 0x7FFF) as usize,
        continued: (offset_field & 0x8000) > 0,
        data_len: data_len,
        data_buf: data,
    })
}

#[cfg(not(feature = "ms"))]
fn to_gatt_attribute_modified(
    buffer: &[u8],
) -> Result<GattAttributeModified, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 7);

    let data_len = buffer[6] as usize;
    require_len!(buffer, 7 + data_len);

    let mut data = [0; MAX_ATTRIBUTE_LEN];
    data[..data_len].copy_from_slice(&buffer[7..]);

    Ok(GattAttributeModified {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attr_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
        data_len: data_len,
        data_buf: data,
    })
}

/// This event is generated in response to an Exchange MTU request.
#[derive(Copy, Clone, Debug)]
pub struct AttExchangeMtuResponse {
    ///  The connection handle related to the response.
    pub conn_handle: ConnectionHandle,

    /// Attribute server receive MTU size.
    pub server_rx_mtu: usize,
}

fn to_att_exchange_mtu_resp(
    buffer: &[u8],
) -> Result<AttExchangeMtuResponse, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 7);
    Ok(AttExchangeMtuResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        server_rx_mtu: LittleEndian::read_u16(&buffer[5..]) as usize,
    })
}

/// This event is generated in response to a Find Information Request. See Find Information Response
/// in Bluetooth Core v4.0 spec.
#[derive(Copy, Clone, Debug)]
pub struct AttFindInformationResponse {
    /// The connection handle related to the response
    pub conn_handle: ConnectionHandle,
    /// The Find Information Response shall have complete handle-UUID pairs. Such pairs shall not be
    /// split across response packets; this also implies that a handleUUID pair shall fit into a
    /// single response packet. The handle-UUID pairs shall be returned in ascending order of
    /// attribute handles.
    handle_uuid_pairs: HandleUuidPairs,
}

impl AttFindInformationResponse {
    /// The Find Information Response shall have complete handle-UUID pairs. Such pairs shall not be
    /// split across response packets; this also implies that a handleUUID pair shall fit into a
    /// single response packet. The handle-UUID pairs shall be returned in ascending order of
    /// attribute handles.
    pub fn handle_uuid_pair_iter<'a>(&'a self) -> HandleUuidPairIterator<'a> {
        match self.handle_uuid_pairs {
            HandleUuidPairs::Format16(count, ref data) => {
                HandleUuidPairIterator::Format16(HandleUuid16PairIterator {
                    data: data,
                    count: count,
                    next_index: 0,
                })
            }
            HandleUuidPairs::Format128(count, ref data) => {
                HandleUuidPairIterator::Format128(HandleUuid128PairIterator {
                    data: data,
                    count: count,
                    next_index: 0,
                })
            }
        }
    }
}

// Assuming a maximum HCI packet size of 255, these are the maximum number of handle-UUID pairs for
// each format that can be in one packet.  Formats cannot be mixed in a single packet.
//
// Packets have 6 other bytes of data preceding the handle-UUID pairs.
//
// max = floor((255 - 6) / pair_length)
const MAX_FORMAT16_PAIR_COUNT: usize = 62;
const MAX_FORMAT128_PAIR_COUNT: usize = 13;

/// One format of the handle-UUID pairs in the [`AttFindInformationResponse`] event. The UUIDs are
/// 16 bits.
#[derive(Copy, Clone, Debug)]
pub struct HandleUuid16Pair {
    /// Attribute handle
    pub handle: AttributeHandle,
    /// Attribute UUID
    pub uuid: Uuid16,
}

/// One format of the handle-UUID pairs in the [`AttFindInformationResponse`] event. The UUIDs are
/// 128 bits.
#[derive(Copy, Clone, Debug)]
pub struct HandleUuid128Pair {
    /// Attribute handle
    pub handle: AttributeHandle,
    /// Attribute UUID
    pub uuid: Uuid128,
}

/// Newtype for the 16-bit UUID buffer.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Uuid16(pub u16);

/// Newtype for the 128-bit UUID buffer.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Uuid128(pub [u8; 16]);

#[derive(Copy, Clone)]
enum HandleUuidPairs {
    Format16(usize, [HandleUuid16Pair; MAX_FORMAT16_PAIR_COUNT]),
    Format128(usize, [HandleUuid128Pair; MAX_FORMAT128_PAIR_COUNT]),
}

impl Debug for HandleUuidPairs {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{{")?;
        match *self {
            HandleUuidPairs::Format16(count, pairs) => {
                for handle_uuid_pair in &pairs[..count] {
                    write!(
                        f,
                        "{{{:?}, {:?}}}",
                        handle_uuid_pair.handle, handle_uuid_pair.uuid
                    )?
                }
            }
            HandleUuidPairs::Format128(count, pairs) => {
                for handle_uuid_pair in &pairs[..count] {
                    write!(
                        f,
                        "{{{:?}, {:?}}}",
                        handle_uuid_pair.handle, handle_uuid_pair.uuid
                    )?
                }
            }
        }
        write!(f, "}}")
    }
}

/// Possible iterators over handle-UUID pairs that can be returnedby the [ATT find information
/// response](AttFindInformationResponse). All pairs from the same event have the same format.
pub enum HandleUuidPairIterator<'a> {
    /// The event contains 16-bit UUIDs.
    Format16(HandleUuid16PairIterator<'a>),
    /// The event contains 128-bit UUIDs.
    Format128(HandleUuid128PairIterator<'a>),
}

/// Iterator over handle-UUID pairs for 16-bit UUIDs.
pub struct HandleUuid16PairIterator<'a> {
    data: &'a [HandleUuid16Pair; MAX_FORMAT16_PAIR_COUNT],
    count: usize,
    next_index: usize,
}

impl<'a> Iterator for HandleUuid16PairIterator<'a> {
    type Item = HandleUuid16Pair;
    fn next(&mut self) -> Option<Self::Item> {
        if self.next_index >= self.count {
            return None;
        }

        let index = self.next_index;
        self.next_index += 1;
        Some(self.data[index])
    }
}

/// Iterator over handle-UUID pairs for 128-bit UUIDs.
pub struct HandleUuid128PairIterator<'a> {
    data: &'a [HandleUuid128Pair; MAX_FORMAT128_PAIR_COUNT],
    count: usize,
    next_index: usize,
}

impl<'a> Iterator for HandleUuid128PairIterator<'a> {
    type Item = HandleUuid128Pair;
    fn next(&mut self) -> Option<Self::Item> {
        if self.next_index >= self.count {
            return None;
        }

        let index = self.next_index;
        self.next_index += 1;
        Some(self.data[index])
    }
}

fn to_att_find_information_response(
    buffer: &[u8],
) -> Result<AttFindInformationResponse, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 6);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    Ok(AttFindInformationResponse {
        conn_handle: to_conn_handle(buffer)?,
        handle_uuid_pairs: match buffer[5] {
            1 => to_handle_uuid16_pairs(&buffer[6..]).map_err(hci::event::Error::Vendor)?,
            2 => to_handle_uuid128_pairs(&buffer[6..]).map_err(hci::event::Error::Vendor)?,
            _ => {
                return Err(hci::event::Error::Vendor(
                    BlueNRGError::BadAttFindInformationResponseFormat(buffer[5]),
                ));
            }
        },
    })
}

fn to_handle_uuid16_pairs(buffer: &[u8]) -> Result<HandleUuidPairs, BlueNRGError> {
    const PAIR_LEN: usize = 4;
    if buffer.len() % PAIR_LEN != 0 {
        return Err(BlueNRGError::AttFindInformationResponsePartialPair16);
    }

    let count = buffer.len() / PAIR_LEN;
    let mut pairs = [HandleUuid16Pair {
        handle: AttributeHandle(0),
        uuid: Uuid16(0),
    }; MAX_FORMAT16_PAIR_COUNT];
    for i in 0..count {
        let index = i * PAIR_LEN;
        pairs[i].handle = AttributeHandle(LittleEndian::read_u16(&buffer[index..]));
        pairs[i].uuid = Uuid16(LittleEndian::read_u16(&buffer[2 + index..]));
    }

    Ok(HandleUuidPairs::Format16(count, pairs))
}

fn to_handle_uuid128_pairs(buffer: &[u8]) -> Result<HandleUuidPairs, BlueNRGError> {
    const PAIR_LEN: usize = 18;
    if buffer.len() % PAIR_LEN != 0 {
        return Err(BlueNRGError::AttFindInformationResponsePartialPair128);
    }

    let count = buffer.len() / PAIR_LEN;
    let mut pairs = [HandleUuid128Pair {
        handle: AttributeHandle(0),
        uuid: Uuid128([0; 16]),
    }; MAX_FORMAT128_PAIR_COUNT];
    for i in 0..count {
        let index = i * PAIR_LEN;
        let next_index = (i + 1) * PAIR_LEN;
        pairs[i].handle = AttributeHandle(LittleEndian::read_u16(&buffer[index..]));
        pairs[i]
            .uuid
            .0
            .copy_from_slice(&buffer[2 + index..next_index]);
    }

    Ok(HandleUuidPairs::Format128(count, pairs))
}

/// This event is generated in response to a Find By Type Value Request.
#[derive(Copy, Clone)]
pub struct AttFindByTypeValueResponse {
    /// The connection handle related to the response.
    pub conn_handle: ConnectionHandle,

    /// The number of valid pairs that follow.
    handle_pair_count: usize,

    /// Handles Information List as defined in Bluetooth Core v4.1 spec.
    handles: [HandleInfoPair; MAX_HANDLE_INFO_PAIR_COUNT],
}

impl AttFindByTypeValueResponse {
    /// Returns an iterator over the Handles Information List as defined in Bluetooth Core v4.1
    /// spec.
    pub fn handle_pairs_iter<'a>(&'a self) -> HandleInfoPairIterator<'a> {
        HandleInfoPairIterator {
            event: &self,
            next_index: 0,
        }
    }
}

impl Debug for AttFindByTypeValueResponse {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{{.conn_handle = {:?}, ", self.conn_handle)?;
        for handle_pair in self.handle_pairs_iter() {
            write!(f, "{:?}", handle_pair)?;
        }
        write!(f, "}}")
    }
}

// Assuming a maximum HCI packet size of 255, these are the maximum number of handle pairs that can
// be in one packet.
//
// Packets have 5 other bytes of data preceding the handle-UUID pairs.
//
// max = floor((255 - 5) / 4)
const MAX_HANDLE_INFO_PAIR_COUNT: usize = 62;

/// Simple container for the handle information returned in [`AttFindByTypeValueResponse`].
#[derive(Copy, Clone, Debug)]
pub struct HandleInfoPair {
    /// Attribute handle
    pub attribute: AttributeHandle,
    /// Group End handle
    pub group_end: GroupEndHandle,
}

/// Newtype for Group End handles
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct GroupEndHandle(pub u16);

/// Iterator into valid [`HandleInfoPair`] structs returned in the [ATT Find By Type Value
/// Response](AttFindByTypeValueResponse) event.
pub struct HandleInfoPairIterator<'a> {
    event: &'a AttFindByTypeValueResponse,
    next_index: usize,
}

impl<'a> Iterator for HandleInfoPairIterator<'a> {
    type Item = HandleInfoPair;

    fn next(&mut self) -> Option<Self::Item> {
        if self.next_index >= self.event.handle_pair_count {
            return None;
        }

        let index = self.next_index;
        self.next_index += 1;
        Some(self.event.handles[index])
    }
}

fn to_att_find_by_value_type_response(
    buffer: &[u8],
) -> Result<AttFindByTypeValueResponse, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 5);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    const PAIR_LEN: usize = 4;
    let pair_buffer = &buffer[5..];
    if pair_buffer.len() % PAIR_LEN != 0 {
        return Err(hci::event::Error::Vendor(
            BlueNRGError::AttFindByTypeValuePartial,
        ));
    }

    let count = pair_buffer.len() / PAIR_LEN;
    let mut pairs = [HandleInfoPair {
        attribute: AttributeHandle(0),
        group_end: GroupEndHandle(0),
    }; MAX_HANDLE_INFO_PAIR_COUNT];
    for i in 0..count {
        let index = i * PAIR_LEN;
        pairs[i].attribute = AttributeHandle(LittleEndian::read_u16(&pair_buffer[index..]));
        pairs[i].group_end = GroupEndHandle(LittleEndian::read_u16(&pair_buffer[2 + index..]));
    }
    Ok(AttFindByTypeValueResponse {
        conn_handle: to_conn_handle(buffer)?,
        handle_pair_count: count,
        handles: pairs,
    })
}

/// This event is generated in response to a Read By Type Request.
#[derive(Copy, Clone)]
pub struct AttReadByTypeResponse {
    /// The connection handle related to the response.
    pub conn_handle: ConnectionHandle,

    // Number of valid bytes in `handle_value_pair_buf`
    data_len: usize,
    // Length of each value in `handle_value_pair_buf`
    value_len: usize,
    // Raw data of the response. Contains 2 octets for the attribute handle followed by `value_len`
    // octets of value data. These pairs repeat for `data_len` bytes.
    handle_value_pair_buf: [u8; MAX_HANDLE_VALUE_PAIR_BUF_LEN],
}

// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_HANDLE_VALUE_PAIR_BUF_LEN: usize = 249;

impl Debug for AttReadByTypeResponse {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{{.conn_handle = {:?}, ", self.conn_handle)?;
        for handle_value_pair in self.handle_value_pair_iter() {
            write!(
                f,
                "{{handle: {:?}, value: {:?}}}",
                handle_value_pair.handle,
                first_16(handle_value_pair.value)
            )?;
        }
        write!(f, "}}")
    }
}

impl AttReadByTypeResponse {
    /// Return an iterator over all valid handle-value pairs returned with the response.
    pub fn handle_value_pair_iter<'a>(&'a self) -> HandleValuePairIterator<'a> {
        HandleValuePairIterator {
            event: &self,
            index: 0,
        }
    }
}

/// Iterator over the valid handle-value pairs returned with the [ATT Read by Type
/// response](AttReadByTypeResponse).
pub struct HandleValuePairIterator<'a> {
    event: &'a AttReadByTypeResponse,
    index: usize,
}

impl<'a> Iterator for HandleValuePairIterator<'a> {
    type Item = HandleValuePair<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.event.data_len {
            return None;
        }

        let handle_index = self.index;
        let value_index = self.index + 2;
        self.index += 2 + self.event.value_len;
        let next_index = self.index;
        Some(HandleValuePair {
            handle: AttributeHandle(LittleEndian::read_u16(
                &self.event.handle_value_pair_buf[handle_index..],
            )),
            value: &self.event.handle_value_pair_buf[value_index..next_index],
        })
    }
}

/// A single handle-value pair returned by the [ATT Read by Type response](AttReadByTypeResponse).
pub struct HandleValuePair<'a> {
    /// Attribute handle
    pub handle: AttributeHandle,
    /// Attribute value. The caller must interpret the value correctly, depending on the expected
    /// type of the attribute.
    pub value: &'a [u8],
}

fn to_att_read_by_type_response(
    buffer: &[u8],
) -> Result<AttReadByTypeResponse, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 6);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    let handle_value_pair_len = buffer[5] as usize;
    let handle_value_pair_buf = &buffer[6..];
    if handle_value_pair_buf.len() % handle_value_pair_len != 0 {
        return Err(hci::event::Error::Vendor(
            BlueNRGError::AttReadByTypeResponsePartial,
        ));
    }

    let mut full_handle_value_pair_buf = [0; MAX_HANDLE_VALUE_PAIR_BUF_LEN];
    full_handle_value_pair_buf[..handle_value_pair_buf.len()]
        .copy_from_slice(&handle_value_pair_buf);

    Ok(AttReadByTypeResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        data_len: handle_value_pair_buf.len(),
        value_len: handle_value_pair_len - 2,
        handle_value_pair_buf: full_handle_value_pair_buf,
    })
}

/// This event is generated in response to a Read Request.
#[derive(Copy, Clone)]
pub struct AttReadResponse {
    /// The connection handle related to the response.
    pub conn_handle: ConnectionHandle,

    /// The number of valid bytes in the value buffer.
    value_len: usize,

    /// Buffer containing the value data.
    value_buf: [u8; MAX_READ_RESPONSE_LEN],
}

// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_READ_RESPONSE_LEN: usize = 250;

impl Debug for AttReadResponse {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{.conn_handle = {:?}, value = {:?}}}",
            self.conn_handle,
            first_16(self.value())
        )
    }
}

impl AttReadResponse {
    /// Returns the valid part of the value data.
    pub fn value(&self) -> &[u8] {
        &self.value_buf[..self.value_len]
    }
}

fn to_att_read_response(buffer: &[u8]) -> Result<AttReadResponse, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 5);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    let mut value_buf = [0; MAX_READ_RESPONSE_LEN];
    value_buf[..data_len].copy_from_slice(&buffer[5..]);

    Ok(AttReadResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        value_len: data_len,
        value_buf: value_buf,
    })
}

/// This event is generated in response to a Read By Group Type Request. See the Bluetooth Core v4.1
/// spec, Vol 3, section 3.4.4.9 and 3.4.4.10.
#[derive(Copy, Clone)]
pub struct AttReadByGroupTypeResponse {
    ///  The connection handle related to the response.
    pub conn_handle: ConnectionHandle,

    // Number of valid bytes in `attribute_data_buf`
    data_len: usize,

    // Length of the attribute data group in `attribute_data_buf`, including the attribute and group
    // end handles.
    attribute_group_len: usize,

    // List of attribute data which is a repetition of:
    // 1. 2 octets for attribute handle.
    // 2. 2 octets for end group handle.
    // 3. (attribute_group_len - 4) octets for attribute value.
    attribute_data_buf: [u8; MAX_ATTRIBUTE_DATA_BUF_LEN],
}

// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_ATTRIBUTE_DATA_BUF_LEN: usize = 249;

impl AttReadByGroupTypeResponse {
    /// Create and return an iterator for the attribute data returned with the response.
    pub fn attribute_data_iter<'a>(&'a self) -> AttributeDataIterator<'a> {
        AttributeDataIterator {
            event: self,
            next_index: 0,
        }
    }
}

impl Debug for AttReadByGroupTypeResponse {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{{.conn_handle = {:?}, ", self.conn_handle)?;
        for attribute_data in self.attribute_data_iter() {
            write!(
                f,
                "{{.attribute_handle = {:?}, .group_end_handle = {:?}, .value = {:?}}}",
                attribute_data.attribute_handle,
                attribute_data.group_end_handle,
                first_16(attribute_data.value)
            )?;
        }
        write!(f, "}}")
    }
}

/// Iterator over the attribute data returned in the [`AttReadByGroupTypeResponse`].
pub struct AttributeDataIterator<'a> {
    event: &'a AttReadByGroupTypeResponse,
    next_index: usize,
}

impl<'a> Iterator for AttributeDataIterator<'a> {
    type Item = AttributeData<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.next_index >= self.event.data_len {
            return None;
        }

        let attr_handle_index = self.next_index;
        let group_end_index = 2 + attr_handle_index;
        let value_index = 2 + group_end_index;
        self.next_index += self.event.attribute_group_len;
        Some(AttributeData {
            attribute_handle: AttributeHandle(LittleEndian::read_u16(
                &self.event.attribute_data_buf[attr_handle_index..],
            )),
            group_end_handle: GroupEndHandle(LittleEndian::read_u16(
                &self.event.attribute_data_buf[group_end_index..],
            )),
            value: &self.event.attribute_data_buf[value_index..self.next_index],
        })
    }
}

/// Attribute data returned in the [AttReadByGroupTypeResponse] event.
pub struct AttributeData<'a> {
    /// Attribute handle
    pub attribute_handle: AttributeHandle,
    /// Group end handle
    pub group_end_handle: GroupEndHandle,
    /// Attribute value
    pub value: &'a [u8],
}

fn to_att_read_by_group_type_response(
    buffer: &[u8],
) -> Result<AttReadByGroupTypeResponse, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 6);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    let attribute_group_len = buffer[5] as usize;

    if &buffer[6..].len() % attribute_group_len != 0 {
        return Err(hci::event::Error::Vendor(
            BlueNRGError::AttReadByGroupTypeResponsePartial,
        ));
    }

    let mut attribute_data_buf = [0; MAX_ATTRIBUTE_DATA_BUF_LEN];
    attribute_data_buf[..data_len - 1].copy_from_slice(&buffer[6..]);
    Ok(AttReadByGroupTypeResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        data_len: data_len - 1, // lose 1 byte to attribute_group_len
        attribute_group_len: attribute_group_len,
        attribute_data_buf: attribute_data_buf,
    })
}

/// This event is generated in response to a Prepare Write Request. See the Bluetooth Core v4.1
/// spec, Vol 3, Part F, section 3.4.6.1 and 3.4.6.2
#[derive(Copy, Clone)]
pub struct AttPrepareWriteResponse {
    /// The connection handle related to the response.
    pub conn_handle: ConnectionHandle,
    /// The handle of the attribute to be written.
    pub attribute_handle: AttributeHandle,
    /// The offset of the first octet to be written.
    pub offset: usize,

    /// Number of valid bytes in |value_buf|
    value_len: usize,
    value_buf: [u8; MAX_WRITE_RESPONSE_VALUE_LEN],
}

// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_WRITE_RESPONSE_VALUE_LEN: usize = 246;

impl Debug for AttPrepareWriteResponse {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{.conn_handle = {:?}, .attribute_handle = {:?}, .offset = {}, .value = {:?}}}",
            self.conn_handle,
            self.attribute_handle,
            self.offset,
            first_16(self.value())
        )
    }
}

impl AttPrepareWriteResponse {
    /// Returns the partial value of the attribute to be written.
    pub fn value(&self) -> &[u8] {
        &self.value_buf[..self.value_len]
    }
}

fn to_att_prepare_write_response(
    buffer: &[u8],
) -> Result<AttPrepareWriteResponse, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 9);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    let value_len = data_len - 4;
    let mut value_buf = [0; MAX_WRITE_RESPONSE_VALUE_LEN];
    value_buf[..value_len].copy_from_slice(&buffer[9..]);
    Ok(AttPrepareWriteResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[5..])),
        offset: LittleEndian::read_u16(&buffer[7..]) as usize,
        value_len: value_len,
        value_buf: value_buf,
    })
}

/// Defines the attribute value returned by a [GATT Indication](BlueNRGEvent::GattIndication) or
/// [GATT Notification](BlueNRGEvent::GattNotification) event.
#[derive(Copy, Clone)]
pub struct AttributeValue {
    /// The connection handle related to the event.
    pub conn_handle: ConnectionHandle,
    /// The handle of the attribute.
    pub attribute_handle: AttributeHandle,

    // Number of valid bytes in value_buf
    value_len: usize,
    // Current value of the attribute. Only the first value_len bytes are valid.
    value_buf: [u8; MAX_ATTRIBUTE_VALUE_LEN],
}

// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_ATTRIBUTE_VALUE_LEN: usize = 248;

impl Debug for AttributeValue {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{.conn_handle = {:?}, .attribute_handle = {:?}, .value = {:?}}}",
            self.conn_handle,
            self.attribute_handle,
            first_16(self.value())
        )
    }
}

impl AttributeValue {
    /// Returns the current value of the attribute.
    pub fn value(&self) -> &[u8] {
        &self.value_buf[..self.value_len]
    }
}

fn to_attribute_value(buffer: &[u8]) -> Result<AttributeValue, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 7);

    let data_len = buffer[4] as usize;
    require_len!(buffer, 5 + data_len);

    let value_len = data_len - 2;
    let mut value_buf = [0; MAX_ATTRIBUTE_VALUE_LEN];
    value_buf[..value_len].copy_from_slice(&buffer[7..]);
    Ok(AttributeValue {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[5..])),
        value_len: value_len,
        value_buf: value_buf,
    })
}

fn to_write_permit_request(
    buffer: &[u8],
) -> Result<AttributeValue, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 7);

    let data_len = buffer[6] as usize;
    require_len!(buffer, 7 + data_len);

    let value_len = data_len;
    let mut value_buf = [0; MAX_ATTRIBUTE_VALUE_LEN];
    value_buf[..value_len].copy_from_slice(&buffer[7..]);
    Ok(AttributeValue {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
        value_len: value_len,
        value_buf: value_buf,
    })
}

/// This event is generated when a GATT client procedure completes either with error or
/// successfully.
#[derive(Copy, Clone, Debug)]
pub struct GattProcedureComplete {
    /// The connection handle for which the GATT procedure has completed.
    pub conn_handle: ConnectionHandle,

    /// Indicates whether the procedure completed with [error](GattProcedureStatus::Failed) or was
    /// [successful](GattProcedureStatus::Success).
    pub status: GattProcedureStatus,
}

/// Allowed status codes for the [GATT Procedure Complete](BlueNRGEvent::GattProcedureComplete)
/// event.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum GattProcedureStatus {
    /// BLE Status Success
    Success,
    /// BLE Status Failed
    Failed,
}

impl TryFrom<u8> for GattProcedureStatus {
    type Error = BlueNRGError;

    fn try_from(value: u8) -> Result<GattProcedureStatus, Self::Error> {
        match value {
            0x00 => Ok(GattProcedureStatus::Success),
            0x41 => Ok(GattProcedureStatus::Failed),
            _ => Err(BlueNRGError::BadGattProcedureStatus(value)),
        }
    }
}

fn to_gatt_procedure_complete(
    buffer: &[u8],
) -> Result<GattProcedureComplete, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 6);

    Ok(GattProcedureComplete {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        status: buffer[5].try_into().map_err(hci::event::Error::Vendor)?,
    })
}

/// The Error Response is used to state that a given request cannot be performed, and to provide the
/// reason. See the Bluetooth Core Specification, v4.1, Vol 3, Part F, Section 3.4.1.1.
#[derive(Copy, Clone, Debug)]
pub struct AttErrorResponse {
    /// The connection handle related to the event.
    pub conn_handle: ConnectionHandle,
    /// The request that generated this error response.
    pub request: AttRequest,
    ///The attribute handle that generated this error response.
    pub attribute_handle: AttributeHandle,
    /// The reason why the request has generated an error response.
    pub error: AttError,
}

/// Potential error codes for the [ATT Error Response](BlueNRGEvent::AttErrorResponse). See Table
/// 3.3 in the Bluetooth Core Specification, v4.1, Vol 3, PartF, Section 3.4.1.1 and The Bluetooth
/// Core Specification Supplement, Table 1.1.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AttError {
    /// The attribute handle given was not valid on this server.
    InvalidHandle = 0x01,
    /// The attribute cannot be read.
    ReadNotPermitted = 0x02,
    /// The attribute cannot be written.
    WriteNotPermitted = 0x03,
    /// The attribute PDU was invalid.
    InvalidPdu = 0x04,
    /// The attribute requires authentication before it can be read or written.
    InsufficientAuthentication = 0x05,
    /// Attribute server does not support the request received from the client.
    RequestNotSupported = 0x06,
    /// Offset specified was past the end of the attribute.
    InvalidOffset = 0x07,
    /// The attribute requires authorization before it can be read or written.
    InsufficientAuthorization = 0x08,
    /// Too many prepare writes have been queued.
    PrepareQueueFull = 0x09,
    /// No attribute found within the given attribute handle range.
    AttributeNotFound = 0x0A,
    /// The attribute cannot be read or written using the Read Blob Request.
    AttributeNotLong = 0x0B,
    /// The Encryption Key Size used for encrypting this link is insufficient.
    InsufficientEncryptionKeySize = 0x0C,
    /// The attribute value length is invalid for the operation.
    InvalidAttributeValueLength = 0x0D,
    /// The attribute request that was requested has encountered an error that was unlikely, and
    /// therefore could not be completed as requested.
    UnlikelyError = 0x0E,
    /// The attribute requires encryption before it can be read or written.
    InsufficientEncryption = 0x0F,
    /// The attribute type is not a supported grouping attribute as defined by a higher layer
    /// specification.
    UnsupportedGroupType = 0x10,
    /// Insufficient Resources to complete the request.
    InsufficientResources = 0x11,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x80 = 0x80,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x81 = 0x81,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x82 = 0x82,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x83 = 0x83,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x84 = 0x84,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x85 = 0x85,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x86 = 0x86,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x87 = 0x87,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x88 = 0x88,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x89 = 0x89,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x8A = 0x8A,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x8B = 0x8B,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x8C = 0x8C,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x8D = 0x8D,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x8E = 0x8E,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x8F = 0x8F,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x90 = 0x90,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x91 = 0x91,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x92 = 0x92,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x93 = 0x93,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x94 = 0x94,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x95 = 0x95,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x96 = 0x96,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x97 = 0x97,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x98 = 0x98,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x99 = 0x99,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x9A = 0x9A,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x9B = 0x9B,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x9C = 0x9C,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x9D = 0x9D,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x9E = 0x9E,
    /// Application error code defined by a higher layer specification.
    ApplicationError0x9F = 0x9F,
    /// The requested write operation cannot be fulfilled for reasons other than permissions.
    WriteRequestRejected = 0xFC,
    /// A Client Characteristic Configuration descriptor is not configured according to the
    /// requirements of the profile or service.
    ClientCharacteristicConfigurationDescriptorImproperlyConfigured = 0xFD,
    /// A profile or service request cannot be serviced because an operation that has been
    /// previously triggered is still in progress.
    ProcedureAlreadyInProgress = 0xFE,
    /// An attribute value is out of range as defined by a profile or service specification.
    OutOfRange = 0xFF,
}

impl TryFrom<u8> for AttError {
    type Error = u8;

    fn try_from(value: u8) -> Result<AttError, Self::Error> {
        match value {
            0x01 => Ok(AttError::InvalidHandle),
            0x02 => Ok(AttError::ReadNotPermitted),
            0x03 => Ok(AttError::WriteNotPermitted),
            0x04 => Ok(AttError::InvalidPdu),
            0x05 => Ok(AttError::InsufficientAuthentication),
            0x06 => Ok(AttError::RequestNotSupported),
            0x07 => Ok(AttError::InvalidOffset),
            0x08 => Ok(AttError::InsufficientAuthorization),
            0x09 => Ok(AttError::PrepareQueueFull),
            0x0A => Ok(AttError::AttributeNotFound),
            0x0B => Ok(AttError::AttributeNotLong),
            0x0C => Ok(AttError::InsufficientEncryptionKeySize),
            0x0D => Ok(AttError::InvalidAttributeValueLength),
            0x0E => Ok(AttError::UnlikelyError),
            0x0F => Ok(AttError::InsufficientEncryption),
            0x10 => Ok(AttError::UnsupportedGroupType),
            0x11 => Ok(AttError::InsufficientResources),
            0x80 => Ok(AttError::ApplicationError0x80),
            0x81 => Ok(AttError::ApplicationError0x81),
            0x82 => Ok(AttError::ApplicationError0x82),
            0x83 => Ok(AttError::ApplicationError0x83),
            0x84 => Ok(AttError::ApplicationError0x84),
            0x85 => Ok(AttError::ApplicationError0x85),
            0x86 => Ok(AttError::ApplicationError0x86),
            0x87 => Ok(AttError::ApplicationError0x87),
            0x88 => Ok(AttError::ApplicationError0x88),
            0x89 => Ok(AttError::ApplicationError0x89),
            0x8A => Ok(AttError::ApplicationError0x8A),
            0x8B => Ok(AttError::ApplicationError0x8B),
            0x8C => Ok(AttError::ApplicationError0x8C),
            0x8D => Ok(AttError::ApplicationError0x8D),
            0x8E => Ok(AttError::ApplicationError0x8E),
            0x8F => Ok(AttError::ApplicationError0x8F),
            0x90 => Ok(AttError::ApplicationError0x90),
            0x91 => Ok(AttError::ApplicationError0x91),
            0x92 => Ok(AttError::ApplicationError0x92),
            0x93 => Ok(AttError::ApplicationError0x93),
            0x94 => Ok(AttError::ApplicationError0x94),
            0x95 => Ok(AttError::ApplicationError0x95),
            0x96 => Ok(AttError::ApplicationError0x96),
            0x97 => Ok(AttError::ApplicationError0x97),
            0x98 => Ok(AttError::ApplicationError0x98),
            0x99 => Ok(AttError::ApplicationError0x99),
            0x9A => Ok(AttError::ApplicationError0x9A),
            0x9B => Ok(AttError::ApplicationError0x9B),
            0x9C => Ok(AttError::ApplicationError0x9C),
            0x9D => Ok(AttError::ApplicationError0x9D),
            0x9E => Ok(AttError::ApplicationError0x9E),
            0x9F => Ok(AttError::ApplicationError0x9F),
            0xFC => Ok(AttError::WriteRequestRejected),
            0xFD => Ok(AttError::ClientCharacteristicConfigurationDescriptorImproperlyConfigured),
            0xFE => Ok(AttError::ProcedureAlreadyInProgress),
            0xFF => Ok(AttError::OutOfRange),
            _ => Err(value),
        }
    }
}

/// Possible ATT requests.  See Table 3.37 in the Bluetooth Core Spec v4.1, Vol 3, Part F, Section
/// 3.4.8.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AttRequest {
    /// Section 3.4.1.1
    ErrorResponse = 0x01,
    /// Section 3.4.2.1
    ExchangeMtuRequest = 0x02,
    /// Section 3.4.2.2
    ExchangeMtuResponse = 0x03,
    /// Section 3.4.3.1
    FindInformationRequest = 0x04,
    /// Section 3.4.3.2
    FindInformationResponse = 0x05,
    /// Section 3.4.3.3
    FindByTypeValueRequest = 0x06,
    /// Section 3.4.3.4
    FindByTypeValueResponse = 0x07,
    /// Section 3.4.4.1
    ReadByTypeRequest = 0x08,
    /// Section 3.4.4.2
    ReadByTypeResponse = 0x09,
    /// Section 3.4.4.3
    ReadRequest = 0x0A,
    /// Section 3.4.4.4
    ReadResponse = 0x0B,
    /// Section 3.4.4.5
    ReadBlobRequest = 0x0C,
    /// Section 3.4.4.6
    ReadBlobResponse = 0x0D,
    /// Section 3.4.4.7
    ReadMultipleRequest = 0x0E,
    /// Section 3.4.4.8
    ReadMultipleResponse = 0x0F,
    /// Section 3.4.4.9
    ReadByGroupTypeRequest = 0x10,
    /// Section 3.4.4.10
    ReadByGroupTypeResponse = 0x11,
    /// Section 3.4.5.1
    WriteRequest = 0x12,
    /// Section 3.4.5.2
    WriteResponse = 0x13,
    /// Section 3.4.5.3
    WriteCommand = 0x52,
    /// Section 3.4.5.4
    SignedWriteCommand = 0xD2,
    /// Section 3.4.6.1
    PrepareWriteRequest = 0x16,
    /// Section 3.4.6.2
    PrepareWriteResponse = 0x17,
    /// Section 3.4.6.3
    ExecuteWriteRequest = 0x18,
    /// Section 3.4.6.4
    ExecuteWriteResponse = 0x19,
    /// Section 3.4.7.1
    HandleValueNotification = 0x1B,
    /// Section 3.4.7.2
    HandleValueIndication = 0x1D,
    /// Section 3.4.7.3
    HandleValueConfirmation = 0x1E,
}

impl TryFrom<u8> for AttRequest {
    type Error = BlueNRGError;

    fn try_from(value: u8) -> Result<AttRequest, Self::Error> {
        match value {
            0x01 => Ok(AttRequest::ErrorResponse),
            0x02 => Ok(AttRequest::ExchangeMtuRequest),
            0x03 => Ok(AttRequest::ExchangeMtuResponse),
            0x04 => Ok(AttRequest::FindInformationRequest),
            0x05 => Ok(AttRequest::FindInformationResponse),
            0x06 => Ok(AttRequest::FindByTypeValueRequest),
            0x07 => Ok(AttRequest::FindByTypeValueResponse),
            0x08 => Ok(AttRequest::ReadByTypeRequest),
            0x09 => Ok(AttRequest::ReadByTypeResponse),
            0x0A => Ok(AttRequest::ReadRequest),
            0x0B => Ok(AttRequest::ReadResponse),
            0x0C => Ok(AttRequest::ReadBlobRequest),
            0x0D => Ok(AttRequest::ReadBlobResponse),
            0x0E => Ok(AttRequest::ReadMultipleRequest),
            0x0F => Ok(AttRequest::ReadMultipleResponse),
            0x10 => Ok(AttRequest::ReadByGroupTypeRequest),
            0x11 => Ok(AttRequest::ReadByGroupTypeResponse),
            0x12 => Ok(AttRequest::WriteRequest),
            0x13 => Ok(AttRequest::WriteResponse),
            0x52 => Ok(AttRequest::WriteCommand),
            0xD2 => Ok(AttRequest::SignedWriteCommand),
            0x16 => Ok(AttRequest::PrepareWriteRequest),
            0x17 => Ok(AttRequest::PrepareWriteResponse),
            0x18 => Ok(AttRequest::ExecuteWriteRequest),
            0x19 => Ok(AttRequest::ExecuteWriteResponse),
            0x1B => Ok(AttRequest::HandleValueNotification),
            0x1D => Ok(AttRequest::HandleValueIndication),
            0x1E => Ok(AttRequest::HandleValueConfirmation),
            _ => Err(BlueNRGError::BadAttRequestOpcode(value)),
        }
    }
}

fn to_att_error_response(
    buffer: &[u8],
) -> Result<AttErrorResponse, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 9);
    Ok(AttErrorResponse {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        request: buffer[5].try_into().map_err(hci::event::Error::Vendor)?,
        attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[6..])),
        error: buffer[8]
            .try_into()
            .map_err(|e| BlueNRGError::BadAttError(e))
            .map_err(hci::event::Error::Vendor)?,
    })
}

/// This event is given to the application when a read request or read blob request is received by
/// the server from the client. This event will be given to the application only if the event bit
/// for this event generation is set when the characteristic was added. On receiving this event, the
/// application can update the value of the handle if it desires and when done it has to use the
/// [`allow_read`](::gatt::Commands::allow_read) command to indicate to the stack that it can send
/// the response to the client.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
#[derive(Copy, Clone, Debug)]
pub struct AttReadPermitRequest {
    /// Handle of the connection on which there was the request to read the attribute
    pub conn_handle: ConnectionHandle,

    /// The handle of the attribute that has been requested by the client to be read.
    pub attribute_handle: AttributeHandle,

    /// Contains the offset from which the read has been requested.
    pub offset: usize,
}

fn to_att_read_permit_request(
    buffer: &[u8],
) -> Result<AttReadPermitRequest, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 9);
    Ok(AttReadPermitRequest {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
        offset: LittleEndian::read_u16(&buffer[7..]) as usize,
    })
}

/// This event is given to the application when a read multiple request or read by type request is
/// received by the server from the client. This event will be given to the application only if the
/// event bit for this event generation is set when the characteristic was added.  On receiving this
/// event, the application can update the values of the handles if it desires and when done it has
/// to send the `gatt_allow_read` command to indicate to the stack that it can send the response to
/// the client.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
#[derive(Copy, Clone)]
pub struct AttReadMultiplePermitRequest {
    /// Handle of the connection which requested to read the attribute.
    pub conn_handle: ConnectionHandle,

    /// Number of valid handles in handles_buf
    handles_len: usize,
    /// Attribute handles returned by the ATT Read Multiple Permit Request. Only the first
    /// `handles_len` handles are valid.
    handles_buf: [AttributeHandle; MAX_ATTRIBUTE_HANDLE_BUFFER_LEN],
}

// The maximum number of handles in the buffer is the max HCI packet size (255) less the other data in
// the packet divided by the length of an attribute handle (2).
const MAX_ATTRIBUTE_HANDLE_BUFFER_LEN: usize = 125;

impl Debug for AttReadMultiplePermitRequest {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{.conn_handle = {:?}, .handles = {:?}",
            self.conn_handle,
            first_16(self.handles())
        )
    }
}

impl AttReadMultiplePermitRequest {
    /// Returns the valid attribute handles returned by the ATT Read Multiple Permit Request event.
    pub fn handles(&self) -> &[AttributeHandle] {
        &self.handles_buf[..self.handles_len]
    }
}

fn to_att_read_multiple_permit_request(
    buffer: &[u8],
) -> Result<AttReadMultiplePermitRequest, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 5);

    let data_len = buffer[4] as usize;
    if data_len % 2 != 0 {
        return Err(hci::event::Error::Vendor(
            BlueNRGError::AttReadMultiplePermitRequestPartial,
        ));
    }

    let handle_len = data_len / 2;
    let mut handles = [AttributeHandle(0); MAX_ATTRIBUTE_HANDLE_BUFFER_LEN];
    for i in 0..handle_len {
        let index = 5 + 2 * i;
        handles[i] = AttributeHandle(LittleEndian::read_u16(&buffer[index..]));
    }

    Ok(AttReadMultiplePermitRequest {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        handles_len: handle_len,
        handles_buf: handles,
    })
}

/// This event is raised when the number of available TX buffers is above a threshold TH (TH = 2).
/// The event will be given only if a previous ACI command returned with
/// [InsufficientResources](AttError::InsufficientResources).
#[cfg(feature = "ms")]
#[derive(Copy, Clone, Debug)]
pub struct GattTxPoolAvailable {
    /// Connection handle on which the GATT procedure is running.
    pub conn_handle: ConnectionHandle,
    /// Indicates the number of elements available in the attrTxPool List.
    pub available_buffers: usize,
}

#[cfg(feature = "ms")]
fn to_gatt_tx_pool_available(
    buffer: &[u8],
) -> Result<GattTxPoolAvailable, hci::event::Error<BlueNRGError>> {
    require_len!(buffer, 6);
    Ok(GattTxPoolAvailable {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        available_buffers: LittleEndian::read_u16(&buffer[4..]) as usize,
    })
}

/// This event is given to the application when a prepare write request is received by the server
/// from the client.
///
/// This event will be given to the application only if the event bit for this event generation is
/// set when the characteristic was added.  When this event is received, the application has to
/// check whether the value being requested for write is allowed to be written and respond with the
/// command `gatt_write_response`.  Based on the response from the application, the attribute value
/// will be modified by the stack.  If the write is rejected by the application, then the value of
/// the attribute will not be modified and an error response will be sent to the client, with the
/// error code as specified by the application.
#[cfg(feature = "ms")]
#[derive(Copy, Clone)]
pub struct AttPrepareWritePermitRequest {
    /// Connection handle on which the GATT procedure is running.
    pub conn_handle: ConnectionHandle,
    /// The handle of the attribute to be written.
    pub attribute_handle: AttributeHandle,
    /// The offset of the first octet to be written.
    pub offset: usize,

    // Number of valid bytes in `value_buf`
    value_len: usize,
    // The data to be written. Only the first `value_len` bytes are valid.
    value_buf: [u8; MAX_PREPARE_WRITE_PERMIT_REQ_VALUE_LEN],
}

// The maximum number of bytes in the buffer is the max HCI packet size (255) less the other data in
// the packet.
#[cfg(feature = "ms")]
const MAX_PREPARE_WRITE_PERMIT_REQ_VALUE_LEN: usize = 246;

#[cfg(feature = "ms")]
impl Debug for AttPrepareWritePermitRequest {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(
            f,
            "{{.conn_handle = {:?}, .attribute_handle = {:?}, .offset = {:?}, .value = {:?}",
            self.conn_handle,
            self.attribute_handle,
            self.offset,
            first_16(self.value())
        )
    }
}

#[cfg(feature = "ms")]
impl AttPrepareWritePermitRequest {
    /// Returns the data to be written.
    pub fn value(&self) -> &[u8] {
        &self.value_buf[..self.value_len]
    }
}

#[cfg(feature = "ms")]
fn to_att_prepare_write_permit_request(
    buffer: &[u8],
) -> Result<AttPrepareWritePermitRequest, hci::event::Error<BlueNRGError>> {
    require_len_at_least!(buffer, 9);

    let data_len = buffer[8] as usize;
    require_len!(buffer, 9 + data_len);

    let mut value_buf = [0; MAX_PREPARE_WRITE_PERMIT_REQ_VALUE_LEN];
    value_buf[..data_len].copy_from_slice(&buffer[9..]);
    Ok(AttPrepareWritePermitRequest {
        conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
        attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
        offset: LittleEndian::read_u16(&buffer[6..]) as usize,
        value_len: data_len,
        value_buf: value_buf,
    })
}