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
//! GAP commands and types needed for those commands.

extern crate byteorder;

pub use crate::host::{AdvertisingFilterPolicy, AdvertisingType, OwnAddressType};
use crate::host::{Channels, PeerAddrType, ScanFilterPolicy, ScanType};
pub use crate::types::{ConnectionInterval, ExpectedConnectionLength, ScanWindow};
pub use crate::{BdAddr, BdAddrType};
use crate::{ConnectionHandle, Controller};
use byteorder::{ByteOrder, LittleEndian};
use core::time::Duration;

/// GAP-specific commands for the [`ActiveBlueNRG`](crate::ActiveBlueNRG).
pub trait GapCommands {
    /// Set the device in non-discoverable mode. This command will disable the LL advertising and
    /// put the device in standby state.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetNonDiscoverable) event
    /// is generated.
    async fn gap_set_nondiscoverable(&mut self);

    /// Set the device in limited discoverable mode.
    ///
    /// Limited discoverability is defined in in GAP specification volume 3, section 9.2.3. The
    /// device will be discoverable for maximum period of TGAP (lim_adv_timeout) = 180 seconds (from
    /// errata). The advertising can be disabled at any time by issuing a
    /// [`set_nondiscoverable`](Commands::set_nondiscoverable) command.
    ///
    /// # Errors
    ///
    /// - [`BadAdvertisingType`](Error::BadAdvertisingType) if
    ///   [`advertising_type`](DiscoverableParameters::advertising_type) is one of the disallowed
    ///   types:
    ///   [ConnectableDirectedHighDutyCycle](crate::host::AdvertisingType::ConnectableDirectedHighDutyCycle)
    ///   or
    ///   [ConnectableDirectedLowDutyCycle](crate::host::AdvertisingType::ConnectableDirectedLowDutyCycle).
    /// - [`BadAdvertisingInterval`](Error::BadAdvertisingInterval) if
    ///   [`advertising_interval`](DiscoverableParameters::advertising_interval) is inverted.
    ///   That is, if the min is greater than the max.
    /// - [`BadConnectionInterval`](Error::BadConnectionInterval) if
    ///   [`conn_interval`](DiscoverableParameters::conn_interval) is inverted. That is, both the
    ///   min and max are provided, and the min is greater than the max.
    ///
    /// # Generated evenst
    ///
    /// When the controller receives the command, it will generate a [command
    /// status](crate::event::Event::CommandStatus) event. The controller starts the advertising after
    /// this and when advertising timeout happens (i.e. limited discovery period has elapsed),
    /// the controller generates an [GAP Limited Discoverable
    /// Complete](crate::vendor::stm32wb::event::BlueNRGEvent::GapLimitedDiscoverableTimeout) event.

    async fn set_limited_discoverable(
        &mut self,
        params: &DiscoverableParameters<'_, '_>,
    ) -> Result<(), Error>;

    /// Set the device in discoverable mode.
    ///
    /// Limited discoverability is defined in in GAP specification volume 3, section 9.2.4. The
    /// device will be discoverable for maximum period of TGAP (lim_adv_timeout) = 180 seconds (from
    /// errata). The advertising can be disabled at any time by issuing a
    /// [`set_nondiscoverable`](Commands::set_nondiscoverable) command.
    ///
    /// # Errors
    ///
    /// - [`BadAdvertisingType`](Error::BadAdvertisingType) if
    ///   [`advertising_type`](DiscoverableParameters::advertising_type) is one of the disallowed
    ///   types:
    ///   [ConnectableDirectedHighDutyCycle](crate::host::AdvertisingType::ConnectableDirectedHighDutyCycle)
    ///   or
    ///   [ConnectableDirectedLowDutyCycle](crate::host::AdvertisingType::ConnectableDirectedLowDutyCycle).
    /// - [`BadAdvertisingInterval`](Error::BadAdvertisingInterval) if
    ///   [`advertising_interval`](DiscoverableParameters::advertising_interval) is inverted.
    ///   That is, if the min is greater than the max.
    /// - [`BadConnectionInterval`](Error::BadConnectionInterval) if
    ///   [`conn_interval`](DiscoverableParameters::conn_interval) is inverted. That is, both the
    ///   min and max are provided, and the min is greater than the max.
    ///
    /// # Generated evenst
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetDiscoverable) event is
    /// generated.
    async fn set_discoverable(
        &mut self,
        params: &DiscoverableParameters<'_, '_>,
    ) -> Result<(), Error>;

    /// Set the device in direct connectable mode.
    ///
    /// Direct connectable mode is defined in GAP specification Volume 3,
    /// Section 9.3.3). Device uses direct connectable mode to advertise using either High Duty
    /// cycle advertisement events or Low Duty cycle advertisement events and the address as
    /// what is specified in the Own Address Type parameter. The Advertising Type parameter in
    /// the command specifies the type of the advertising used.
    ///
    /// When the `ms` feature is _not_ enabled, the device will be in directed connectable mode only
    /// for 1.28 seconds. If no connection is established within this duration, the device enters
    /// non discoverable mode and advertising will have to be again enabled explicitly.
    ///
    /// When the `ms` feature _is_ enabled, the advertising interval is explicitly provided in the
    /// [parameters][DirectConnectableParameters].
    ///
    /// # Errors
    ///
    /// - [`BadAdvertisingType`](Error::BadAdvertisingType) if
    ///   [`advertising_type`](DiscoverableParameters::advertising_type) is one of the disallowed
    ///   types:
    ///   [ConnectableUndirected](crate::host::AdvertisingType::ConnectableUndirected),
    ///   [ScannableUndirected](crate::host::AdvertisingType::ScannableUndirected), or
    ///   [NonConnectableUndirected](crate::host::AdvertisingType::NonConnectableUndirected),
    /// - (`ms` feature only) [`BadAdvertisingInterval`](Error::BadAdvertisingInterval) if
    ///   [`advertising_interval`](DiscoverableParameters::advertising_interval) is
    ///   out of range (20 ms to 10.24 s) or inverted (the min is greater than the max).
    ///
    /// # Generated evenst
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetDirectConnectable) event
    /// is generated.
    async fn set_direct_connectable(
        &mut self,
        params: &DirectConnectableParameters,
    ) -> Result<(), Error>;

    /// Set the IO capabilities of the device.
    ///
    /// This command has to be given only when the device is not in a connected state.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetIoCapability) event is
    /// generated.
    async fn set_io_capability(&mut self, capability: IoCapability);

    /// Set the authentication requirements for the device.
    ///
    /// This command has to be given only when the device is not in a connected state.
    ///
    /// # Errors
    ///
    /// - [BadEncryptionKeySizeRange](Error::BadEncryptionKeySizeRange) if the
    ///   [`encryption_key_size_range`](AuthenticationRequirements::encryption_key_size_range) min
    ///   is greater than the max.
    /// - [BadFixedPin](Error::BadFixedPin) if the
    ///   [`fixed_pin`](AuthenticationRequirements::fixed_pin) is [Fixed](Pin::Fixed) with a value
    ///   greater than 999999.
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// - A [Command
    ///   Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetAuthenticationRequirement) event
    ///   is generated.
    /// - If [`fixed_pin`](AuthenticationRequirements::fixed_pin) is [Request](Pin::Requested), then
    ///   a [GAP Pass Key](crate::vendor::stm32wb::event::BlueNRGEvent::GapPassKeyRequest) event is generated.
    async fn set_authentication_requirement(
        &mut self,
        requirements: &AuthenticationRequirements,
    ) -> Result<(), Error>;

    /// Set the authorization requirements of the device.
    ///
    /// This command has to be given when connected to a device if authorization is required to
    /// access services which require authorization.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// - A [Command
    ///   Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetAuthorizationRequirement) event
    ///   is generated.
    /// - If authorization is required, then a [GAP Authorization
    ///   Request](crate::vendor::stm32wb::event::BlueNRGEvent::GapAuthorizationRequest) event is generated.
    async fn set_authorization_requirement(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        authorization_required: bool,
    );

    /// This command should be send by the host in response to the [GAP Pass Key
    /// Request](crate::vendor::stm32wb::event::BlueNRGEvent::GapPassKeyRequest) event.
    ///
    /// `pin` contains the pass key which will be used during the pairing process.
    ///
    /// # Errors
    ///
    /// - [BadFixedPin](Error::BadFixedPin) if the pin is greater than 999999.
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// - A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapPassKeyResponse) event is
    ///   generated.
    /// - When the pairing process completes, it will generate a
    ///   [PairingComplete](crate::vendor::stm32wb::event::BlueNRGEvent::GapPairingComplete) event.
    async fn pass_key_response(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        pin: u32,
    ) -> Result<(), Error>;

    /// This command should be send by the host in response to the [GAP Authorization
    /// Request](crate::vendor::stm32wb::event::BlueNRGEvent::GapAuthorizationRequest) event.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapAuthorizationResponse)
    /// event is generated.
    async fn authorization_response(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        authorization: Authorization,
    );

    /// Register the GAP service with the GATT.
    ///
    /// The device name characteristic and appearance characteristic are added by default and the
    /// handles of these characteristics are returned in the [event
    /// data](crate::vendor::stm32wb::event::command::GapInit).
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapInit) event is generated.
    async fn init(&mut self, role: Role, privacy_enabled: bool, dev_name_characteristic_len: u8);

    /// Register the GAP service with the GATT.
    ///
    /// This function exists to prevent name conflicts with other Commands traits' init methods.
    async fn init_gap(
        &mut self,
        role: Role,
        privacy_enabled: bool,
        dev_name_characteristic_len: u8,
    ) {
        self.init(role, privacy_enabled, dev_name_characteristic_len)
            .await
    }

    /// Put the device into non-connectable mode.
    ///
    /// This mode does not support connection. The privacy setting done in the
    /// [`init`](Commands::init) command plays a role in deciding the valid
    /// parameters for this command. If privacy was not enabled, `address_type` may be
    /// [Public](AddressType::Public) or [Random](AddressType::Random).  If privacy was
    /// enabled, `address_type` may be [ResolvablePrivate](AddressType::ResolvablePrivate) or
    /// [NonResolvablePrivate](AddressType::NonResolvablePrivate).
    ///
    /// # Errors
    ///
    /// - [BadAdvertisingType](Error::BadAdvertisingType) if the advertising type is not one
    ///   of the supported modes. It must be
    ///   [ScannableUndirected](AdvertisingType::ScannableUndirected) or
    ///   (NonConnectableUndirected)[AdvertisingType::NonConnectableUndirected).
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapInit) event is generated.
    async fn set_nonconnectable(
        &mut self,
        advertising_type: AdvertisingType,
        address_type: AddressType,
    ) -> Result<(), Error>;

    /// Put the device into undirected connectable mode.
    ///
    /// The privacy setting done in the [`init`](Commands::init) command plays a role
    /// in deciding the valid parameters for this command.
    ///
    /// # Errors
    ///
    /// - [BadAdvertisingFilterPolicy](Error::BadAdvertisingFilterPolicy) if the filter is
    ///   not one of the supported modes. It must be
    ///   [AllowConnectionAndScan](AdvertisingFilterPolicy::AllowConnectionAndScan) or
    ///   (WhiteListConnectionAllowScan)[AdvertisingFilterPolicy::WhiteListConnectionAllowScan).
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetUndirectedConnectable)
    /// event is generated.
    async fn set_undirected_connectable(
        &mut self,
        params: &UndirectedConnectableParameters,
    ) -> Result<(), Error>;

    /// This command has to be issued to notify the central device of the security requirements of
    /// the peripheral.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command status](crate::event::Event::CommandStatus) event will be generated when a valid
    /// command is received. On completion of the command, i.e. when the security request is
    /// successfully transmitted to the master, a [GAP Peripheral Security
    /// Initiated](crate::vendor::stm32wb::event::BlueNRGEvent::GapPeripheralSecurityInitiated) vendor-specific event
    /// will be generated.
    async fn peripheral_security_request(&mut self, conn_handle: &ConnectionHandle);

    /// This command can be used to update the advertising data for a particular AD type. If the AD
    /// type specified does not exist, then it is added to the advertising data. If the overall
    /// advertising data length is more than 31 octets after the update, then the command is
    /// rejected and the old data is retained.
    ///
    /// # Errors
    ///
    /// - [BadAdvertisingDataLength](Error::BadAdvertisingDataLength) if the provided data is longer
    ///   than 31 bytes.
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapUpdateAdvertisingData)
    /// event is generated.
    async fn update_advertising_data(&mut self, data: &[u8]) -> Result<(), Error>;

    /// This command can be used to delete the specified AD type from the advertisement data if
    /// present.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapDeleteAdType) event is
    /// generated.
    async fn delete_ad_type(&mut self, ad_type: AdvertisingDataType);

    /// This command can be used to get the current security settings of the device.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapGetSecurityLevel) event is
    /// generated.
    async fn get_security_level(&mut self, conn_handle: &ConnectionHandle);

    /// Allows masking events from the GAP.
    ///
    /// The default configuration is all the events masked.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetEventMask) event is
    /// generated.
    async fn set_event_mask(&mut self, flags: EventFlags);

    /// Allows masking events from the GAP.
    ///
    /// This function exists to prevent name conflicts with other Commands traits' set_event_mask
    /// methods.
    async fn set_gap_event_mask(&mut self, flags: EventFlags) {
        self.set_event_mask(flags).await
    }

    /// Configure the controller's white list with devices that are present in the security
    /// database.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapConfigureWhiteList) event
    /// is generated.
    async fn configure_white_list(&mut self);

    /// Command the controller to terminate the connection.
    ///
    /// # Errors
    ///
    /// - [BadTerminationReason](Error::BadTerminationReason) if provided termination reason is
    ///   invalid. Valid reasons are the same as HCI [disconnect](crate::host::crate::disconnect):
    ///   [`AuthFailure`](crate::Status::AuthFailure),
    ///   [`RemoteTerminationByUser`](crate::Status::RemoteTerminationByUser),
    ///   [`RemoteTerminationLowResources`](crate::Status::RemoteTerminationLowResources),
    ///   [`RemoteTerminationPowerOff`](crate::Status::RemoteTerminationPowerOff),
    ///   [`UnsupportedRemoteFeature`](crate::Status::UnsupportedRemoteFeature),
    ///   [`PairingWithUnitKeyNotSupported`](crate::Status::PairingWithUnitKeyNotSupported), or
    ///   [`UnacceptableConnectionParameters`](crate::Status::UnacceptableConnectionParameters).
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// The controller will generate a [command status](crate::event::Event::CommandStatus) event when
    /// the command is received and a [Disconnection
    /// Complete](crate::event::Event::DisconnectionComplete) event will be generated when the link is
    /// disconnected.
    async fn terminate(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        reason: crate::Status<crate::vendor::stm32wb::event::Status>,
    ) -> Result<(), Error>;

    /// Clear the security database. All the devices in the security database will be removed.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapClearSecurityDatabase)
    /// event is generated.
    async fn clear_security_database(&mut self);

    /// This command should be given by the application when it receives the [GAP Bond
    /// Lost](crate::vendor::stm32wb::event::BlueNRGEvent::GapBondLost) event if it wants the re-bonding to happen
    /// successfully. If this command is not given on receiving the event, the bonding procedure
    /// will timeout.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [Command Complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapAllowRebond) event is
    /// generated. Even if the command is given when it is not valid, success will be returned but
    /// internally it will have no effect.
    async fn allow_rebond(&mut self, conn_handle: crate::ConnectionHandle);

    /// Start the limited discovery procedure.
    ///
    /// The controller is commanded to start active scanning.  When this procedure is started, only
    /// the devices in limited discoverable mode are returned to the upper layers.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command status](crate::event::Event::CommandStatus) event is generated as soon as the
    /// command is given.
    ///
    /// If [Success](crate::Status::Success) is returned in the command status, the procedure is
    /// terminated when either the upper layers issue a command to terminate the procedure by
    /// issuing the command [`terminate_procedure`](Commands::terminate_procedure) with the
    /// procedure code set to [LimitedDiscovery](crate::vendor::stm32wb::event::GapProcedure::LimitedDiscovery) or a
    /// [timeout](crate::vendor::stm32wb::event::BlueNRGEvent::GapLimitedDiscoverableTimeout) happens. When the
    /// procedure is terminated due to any of the above reasons, a
    /// [ProcedureComplete](crate::vendor::stm32wb::event::BlueNRGEvent::GapProcedureComplete) event is returned with
    /// the procedure code set to [LimitedDiscovery](crate::vendor::stm32wb::event::GapProcedure::LimitedDiscovery).
    ///
    /// The device found when the procedure is ongoing is returned to the upper layers through the
    /// [LeAdvertisingReport](crate::event::Event::LeAdvertisingReport) event.
    async fn start_limited_discovery_procedure(&mut self, params: &DiscoveryProcedureParameters);

    /// Start the general discovery procedure. The controller is commanded to start active scanning.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command status](crate::event::Event::CommandStatus) event is generated as soon as the
    /// command is given.
    ///
    /// If [Success](crate::Status::Success) is returned in the command status, the procedure is
    /// terminated when either the upper layers issue a command to terminate the procedure by
    /// issuing the command [`terminate_procedure`](Commands::terminate_procedure) with the
    /// procedure code set to [GeneralDiscovery](crate::vendor::stm32wb::event::GapProcedure::GeneralDiscovery) or a
    /// timeout happens. When the procedure is terminated due to any of the above reasons, a
    /// [ProcedureComplete](crate::vendor::stm32wb::event::BlueNRGEvent::GapProcedureComplete) event is returned with
    /// the procedure code set to [GeneralDiscovery](crate::vendor::stm32wb::event::GapProcedure::GeneralDiscovery).
    ///
    /// The device found when the procedure is ongoing is returned to the upper layers through the
    /// [LeAdvertisingReport](crate::event::Event::LeAdvertisingReport) event.
    async fn start_general_discovery_procedure(&mut self, params: &DiscoveryProcedureParameters);

    /// Start the auto connection establishment procedure.
    ///
    /// The devices specified are added to the white list of the controller and a
    /// [`le_create_connection`](crate::host::crate::le_create_connection) call will be made to the
    /// controller by GAP with the [initiator filter
    /// policy](crate::host::ConnectionParameters::initiator_filter_policy) set to
    /// [WhiteList](crate::host::ConnectionFilterPolicy::WhiteList), to "use whitelist to determine
    /// which advertiser to connect to". When a command is issued to terminate the procedure by
    /// upper layer, a [`le_create_connection_cancel`](crate::host::crate::le_create_connection_cancel)
    /// call will be made to the controller by GAP.
    ///
    /// # Errors
    ///
    /// - If the [`white_list`](AutoConnectionEstablishmentParameters::white_list) is too long
    ///   (such that the serialized command would not fit in 255 bytes), a
    ///   [WhiteListTooLong](Error::WhiteListTooLong) is returned. The list cannot have more than 33
    ///   elements.
    async fn start_auto_connection_establishment_procedure(
        &mut self,
        params: &AutoConnectionEstablishmentParameters<'_>,
    ) -> Result<(), Error>;

    /// Start a general connection establishment procedure.
    ///
    /// The host [enables scanning](crate::host::crate::le_set_scan_enable) in the controller with the
    /// scanner [filter policy](crate::host::ScanParameters::filter_policy) set to
    /// [AcceptAll](crate::host::ScanFilterPolicy::AcceptAll), to "accept all advertising packets" and
    /// from the scanning results, all the devices are sent to the upper layer using the event [LE
    /// Advertising Report](crate::event::Event::LeAdvertisingReport). The upper layer then has to
    /// select one of the devices to which it wants to connect by issuing the command
    /// [`create_connection`](Commands::create_connection). If privacy is enabled,
    /// then either a private resolvable address or a non-resolvable address, based on the address
    /// type specified in the command is set as the scanner address but the GAP create connection
    /// always uses a private resolvable address if the general connection establishment procedure
    /// is active.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    async fn start_general_connection_establishment_procedure(
        &mut self,
        params: &GeneralConnectionEstablishmentParameters,
    );

    /// Start a selective connection establishment procedure.
    ///
    /// The GAP adds the specified device addresses into white list and [enables
    /// scanning](crate::host::crate::le_set_scan_enable) in the controller with the scanner [filter
    /// policy](crate::host::ScanParameters::filter_policy) set to
    /// [WhiteList](crate::host::ScanFilterPolicy::WhiteList), to "accept packets only from devices in
    /// whitelist". All the devices found are sent to the upper layer by the event [LE Advertising
    /// Report](crate::event::Event::LeAdvertisingReport). The upper layer then has to select one of
    /// the devices to which it wants to connect by issuing the command
    /// [`create_connection`](Commands::create_connection).
    ///
    /// # Errors
    ///
    /// - If the [`white_list`](SelectiveConnectionEstablishmentParameters::white_list) is too
    ///   long (such that the serialized command would not fit in 255 bytes), a
    ///   [WhiteListTooLong](Error::WhiteListTooLong) is returned. The list cannot have more than 35
    ///   elements.
    async fn start_selective_connection_establishment_procedure(
        &mut self,
        params: &SelectiveConnectionEstablishmentParameters<'_>,
    ) -> Result<(), Error>;

    /// Start the direct connection establishment procedure.
    ///
    /// A [LE Create Connection](crate::host::crate::le_create_connection) call will be made to the
    /// controller by GAP with the initiator [filter
    /// policy](crate::host::ConnectionParameters::initiator_filter_policy) set to
    /// [UseAddress](crate::host::ConnectionFilterPolicy::UseAddress) to "ignore whitelist and process
    /// connectable advertising packets only for the specified device". The procedure can be
    /// terminated explicitly by the upper layer by issuing the command
    /// [`terminate_procedure`](Commands::terminate_procedure). When a command is
    /// issued to terminate the procedure by upper layer, a
    /// [`le_create_connection_cancel`](crate::host::crate::le_create_connection_cancel) call will be
    /// made to the controller by GAP.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command status](crate::event::Event::CommandStatus) event is generated as soon as the
    /// command is given. If [Success](crate::Status::Success) is returned, on termination of the
    /// procedure, a [LE Connection Complete](crate::event::LeConnectionComplete) event is
    /// returned. The procedure can be explicitly terminated by the upper layer by issuing the
    /// command [`terminate_procedure`](Commands::terminate_procedure) with the procedure_code set
    /// to
    /// [DirectConnectionEstablishment](crate::vendor::stm32wb::event::GapProcedure::DirectConnectionEstablishment).
    async fn create_connection(&mut self, params: &ConnectionParameters);

    /// The GAP procedure(s) specified is terminated.
    ///
    /// # Errors
    ///
    /// - [NoProcedure](Error::NoProcedure) if the bitfield is empty.
    /// - Underlying communication errors
    ///
    /// # Generated events
    ///
    /// A [command complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapTerminateProcedure) event
    /// is generated for this command. If the command was successfully processed, the status field
    /// will be [Success](crate::Status::Success) and a
    /// [ProcedureCompleted](crate::vendor::stm32wb::event::BlueNRGEvent::GapProcedureComplete) event is returned
    /// with the procedure code set to the corresponding procedure.
    async fn terminate_gap_procedure(&mut self, procedure: Procedure) -> Result<(), Error>;

    /// Start the connection update procedure.
    ///
    /// A [`le_connection_update`](crate::host::crate::le_connection_update) call is be made to the
    /// controller by GAP.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command status](crate::event::Event::CommandStatus) event is generated as soon as the
    /// command is given. If [Success](crate::Status::Success) is returned, on completion of
    /// connection update, a
    /// [LeConnectionUpdateComplete](crate::event::Event::LeConnectionUpdateComplete) event is
    /// returned to the upper layer.
    async fn start_connection_update(&mut self, params: &ConnectionUpdateParameters);

    /// Send the SM pairing request to start a pairing process. The authentication requirements and
    /// I/O capabilities should be set before issuing this command using the
    /// [`set_io_capability`](Commands::set_io_capability) and
    /// [`set_authentication_requirement`](Commands::set_authentication_requirement)
    /// commands.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command status](crate::event::Event::CommandStatus) event is generated when the command is
    /// received. If [Success](crate::Status::Success) is returned in the command status event, a
    /// [Pairing Complete](crate::vendor::stm32wb::event::BlueNRGEvent::GapPairingComplete) event is returned after
    /// the pairing process is completed.
    async fn send_pairing_request(&mut self, params: &PairingRequest);

    /// This command tries to resolve the address provided with the IRKs present in its database.
    ///
    /// If the address is resolved successfully with any one of the IRKs present in the database, it
    /// returns success and also the corresponding public/static random address stored with the IRK
    /// in the database.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapResolvePrivateAddress)
    /// event is generated. If [Success](crate::Status::Success) is returned as the status, then the
    /// address is also returned in the event.
    async fn resolve_private_address(&mut self, addr: crate::BdAddr);

    /// This command puts the device into broadcast mode.
    ///
    /// # Errors
    ///
    /// - [BadAdvertisingType](Error::BadAdvertisingType) if the advertising type is not
    ///   [ScannableUndirected](crate::types::AdvertisingType::ScannableUndirected) or
    ///   [NonConnectableUndirected](crate::types::AdvertisingType::NonConnectableUndirected).
    /// - [BadAdvertisingDataLength](Error::BadAdvertisingDataLength) if the advertising data is
    ///   longer than 31 bytes.
    /// - [WhiteListTooLong](Error::WhiteListTooLong) if the length of the white list would put the
    ///   packet length over 255 bytes. The exact number of addresses that can be in the white list
    ///   can range from 35 to 31, depending on the length of the advertising data.
    /// - Underlying communication errors.
    ///
    /// # Generated events
    ///
    /// A [command complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapSetBroadcastMode) event is
    /// returned where the status indicates whether the command was successful.
    async fn set_broadcast_mode(&mut self, params: &BroadcastModeParameters) -> Result<(), Error>;

    /// Starts an Observation procedure, when the device is in Observer Role.
    ///
    /// The host enables scanning in the controller. The advertising reports are sent to the upper
    /// layer using standard LE Advertising Report Event. See Bluetooth Core v4.1, Vol. 2, part E,
    /// Ch. 7.7.65.2, LE Advertising Report Event.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapStartObservationProcedure)
    /// event is generated.
    async fn start_observation_procedure(&mut self, params: &ObservationProcedureParameters);

    /// This command gets the list of the devices which are bonded. It returns the number of
    /// addresses and the corresponding address types and values.
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapGetBondedDevices) event is
    /// generated.
    async fn get_bonded_devices(&mut self);

    /// The command finds whether the device, whose address is specified in the command, is
    /// bonded. If the device is using a resolvable private address and it has been bonded, then the
    /// command will return [Success](crate::Status::Success).
    ///
    /// # Errors
    ///
    /// Only underlying communication errors are reported.
    ///
    /// # Generated events
    ///
    /// A [command complete](crate::vendor::stm32wb::event::command::ReturnParameters::GapIsDeviceBonded) event is
    /// generated.
    async fn is_device_bonded(&mut self, addr: crate::host::PeerAddrType);

    /// This command allows the user to validate/confirm or not the numeric comparison value showed through
    /// the [`NumericComparisonValueEvent`]
    async fn numeric_comparison_value_confirm_yes_no(
        &mut self,
        params: &NumericComparisonValueConfirmYesNoParameters,
    );

    /// This command permits to signal to the Stack the input type detected during Passkey input.
    async fn passkey_input(&mut self, conn_handle: ConnectionHandle, input_type: InputType);

    /// This command is sent by the user to get (i.e. to extract from the Stack) the OOB
    /// data generated by the Stack itself.
    async fn get_oob_data(&mut self, oob_data_type: OobDataType);

    /// This command is sent (by the User) to input the OOB data arrived via OOB
    /// communication.
    async fn set_oob_data(&mut self, params: &SetOobDataParameters);

    /// This  command is used to add devices to the list of address translations
    /// used to resolve Resolvable Private Addresses in the Controller.
    async fn add_devices_to_resolving_list(
        &mut self,
        whitelist_identities: &[PeerAddrType],
        clear_resolving_list: bool,
    );

    /// This command is used to remove a specified device from bonding table
    async fn remove_bonded_device(&mut self, address: BdAddrType);

    /// This  command is used to add specific device addresses to the white and/or resolving list.
    async fn add_devices_to_list(&mut self, list_entries: &[BdAddrType], mode: AddDeviceToListMode);

    /// This command starts an advertising beacon. It allows additional advertising
    /// packets to be transmitted independently of the packets transmitted with GAP
    /// advertising commands such as ACI_GAP_SET_DISCOVERABLE or
    /// ACI_GAP_SET_LIMITED_DISCOVERABLE.
    async fn additional_beacon_start(
        &mut self,
        params: &AdditonalBeaconStartParameters,
    ) -> Result<(), Error>;

    /// This command stops the advertising beacon started with
    /// ACI_GAP_ADDITIONAL_BEACON_START.
    async fn additional_beacon_stop(&mut self);

    /// This command sets the data transmitted by the advertising beacon started
    /// with ACI_GAP_ADDITIONAL_BEACON_START. If the advertising beacon is already
    /// started, the new data is used in subsequent beacon advertising events.
    async fn additonal_beacon_set_data(&mut self, advertising_data: &[u8]);
}

impl<T: Controller> GapCommands for T {
    async fn gap_set_nondiscoverable(&mut self) {
        self.controller_write(crate::vendor::stm32wb::opcode::GAP_SET_NONDISCOVERABLE, &[])
            .await
    }

    impl_validate_variable_length_params!(
        set_limited_discoverable<'a, 'b>,
        DiscoverableParameters<'a, 'b>,
        crate::vendor::stm32wb::opcode::GAP_SET_LIMITED_DISCOVERABLE
    );

    impl_validate_variable_length_params!(
        set_discoverable<'a, 'b>,
        DiscoverableParameters<'a, 'b>,
        crate::vendor::stm32wb::opcode::GAP_SET_DISCOVERABLE
    );

    impl_validate_params!(
        set_direct_connectable,
        DirectConnectableParameters,
        crate::vendor::stm32wb::opcode::GAP_SET_DIRECT_CONNECTABLE
    );

    async fn set_io_capability(&mut self, capability: IoCapability) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_SET_IO_CAPABILITY,
            &[capability as u8],
        )
        .await
    }

    impl_validate_params!(
        set_authentication_requirement,
        AuthenticationRequirements,
        crate::vendor::stm32wb::opcode::GAP_SET_AUTHENTICATION_REQUIREMENT
    );

    async fn set_authorization_requirement(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        authorization_required: bool,
    ) {
        let mut bytes = [0; 3];
        LittleEndian::write_u16(&mut bytes[0..2], conn_handle.0);
        bytes[2] = authorization_required as u8;

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_SET_AUTHORIZATION_REQUIREMENT,
            &bytes,
        )
        .await
    }

    async fn pass_key_response(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        pin: u32,
    ) -> Result<(), Error> {
        if pin > 999_999 {
            return Err(Error::BadFixedPin(pin));
        }

        let mut bytes = [0; 6];
        LittleEndian::write_u16(&mut bytes[0..2], conn_handle.0);
        LittleEndian::write_u32(&mut bytes[2..6], pin);

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_PASS_KEY_RESPONSE,
            &bytes,
        )
        .await;

        Ok(())
    }

    async fn authorization_response(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        authorization: Authorization,
    ) {
        let mut bytes = [0; 3];
        LittleEndian::write_u16(&mut bytes[0..2], conn_handle.0);
        bytes[2] = authorization as u8;

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_AUTHORIZATION_RESPONSE,
            &bytes,
        )
        .await
    }

    async fn init(&mut self, role: Role, privacy_enabled: bool, dev_name_characteristic_len: u8) {
        let mut bytes = [0; 3];
        bytes[0] = role.bits();
        bytes[1] = privacy_enabled as u8;
        bytes[2] = dev_name_characteristic_len;

        self.controller_write(crate::vendor::stm32wb::opcode::GAP_INIT, &bytes)
            .await;
    }

    async fn set_nonconnectable(
        &mut self,
        advertising_type: AdvertisingType,
        address_type: AddressType,
    ) -> Result<(), Error> {
        match advertising_type {
            AdvertisingType::ScannableUndirected | AdvertisingType::NonConnectableUndirected => (),
            _ => {
                return Err(Error::BadAdvertisingType(advertising_type));
            }
        }

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_SET_NONCONNECTABLE,
            &[advertising_type as u8, address_type as u8],
        )
        .await;

        Ok(())
    }

    impl_validate_params!(
        set_undirected_connectable,
        UndirectedConnectableParameters,
        crate::vendor::stm32wb::opcode::GAP_SET_UNDIRECTED_CONNECTABLE
    );

    async fn peripheral_security_request(&mut self, conn_handle: &ConnectionHandle) {
        let mut bytes = [0; 2];

        LittleEndian::write_u16(&mut bytes[0..2], conn_handle.0);

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_PERIPHERAL_SECURITY_REQUEST,
            &bytes,
        )
        .await
    }

    async fn update_advertising_data(&mut self, data: &[u8]) -> Result<(), Error> {
        const MAX_LENGTH: usize = 31;
        if data.len() > MAX_LENGTH {
            return Err(Error::BadAdvertisingDataLength(data.len()));
        }

        let mut bytes = [0; 1 + MAX_LENGTH];
        bytes[0] = data.len() as u8;
        bytes[1..=data.len()].copy_from_slice(data);

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_UPDATE_ADVERTISING_DATA,
            &bytes[0..=data.len()],
        )
        .await;

        Ok(())
    }

    async fn delete_ad_type(&mut self, ad_type: AdvertisingDataType) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_DELETE_AD_TYPE,
            &[ad_type as u8],
        )
        .await
    }

    async fn get_security_level(&mut self, conn_handle: &ConnectionHandle) {
        let mut bytes = [0; 2];

        LittleEndian::write_u16(&mut bytes, conn_handle.0);

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_GET_SECURITY_LEVEL,
            &bytes,
        )
        .await
    }

    async fn set_event_mask(&mut self, flags: EventFlags) {
        let mut bytes = [0; 2];
        LittleEndian::write_u16(&mut bytes, flags.bits());

        self.controller_write(crate::vendor::stm32wb::opcode::GAP_SET_EVENT_MASK, &bytes)
            .await
    }

    async fn configure_white_list(&mut self) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_CONFIGURE_WHITE_LIST,
            &[],
        )
        .await
    }

    async fn terminate(
        &mut self,
        conn_handle: crate::ConnectionHandle,
        reason: crate::Status<crate::vendor::stm32wb::event::Status>,
    ) -> Result<(), Error> {
        match reason {
            crate::Status::AuthFailure
            | crate::Status::RemoteTerminationByUser
            | crate::Status::RemoteTerminationLowResources
            | crate::Status::RemoteTerminationPowerOff
            | crate::Status::UnsupportedRemoteFeature
            | crate::Status::PairingWithUnitKeyNotSupported
            | crate::Status::UnacceptableConnectionParameters => (),
            _ => return Err(Error::BadTerminationReason(reason)),
        }

        let mut bytes = [0; 3];
        LittleEndian::write_u16(&mut bytes[0..2], conn_handle.0);
        bytes[2] = reason.into();

        self.controller_write(crate::vendor::stm32wb::opcode::GAP_TERMINATE, &bytes)
            .await;
        Ok(())
    }

    async fn clear_security_database(&mut self) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_CLEAR_SECURITY_DATABASE,
            &[],
        )
        .await
    }

    async fn allow_rebond(&mut self, conn_handle: crate::ConnectionHandle) {
        let mut bytes = [0; 2];
        LittleEndian::write_u16(&mut bytes, conn_handle.0);
        self.controller_write(crate::vendor::stm32wb::opcode::GAP_ALLOW_REBOND, &bytes)
            .await
    }

    impl_params!(
        start_limited_discovery_procedure,
        DiscoveryProcedureParameters,
        crate::vendor::stm32wb::opcode::GAP_START_LIMITED_DISCOVERY_PROCEDURE
    );

    impl_params!(
        start_general_discovery_procedure,
        DiscoveryProcedureParameters,
        crate::vendor::stm32wb::opcode::GAP_START_GENERAL_DISCOVERY_PROCEDURE
    );

    impl_validate_variable_length_params!(
        start_auto_connection_establishment_procedure<'a>,
        AutoConnectionEstablishmentParameters<'a>,
        crate::vendor::stm32wb::opcode::GAP_START_AUTO_CONNECTION_ESTABLISHMENT
    );

    impl_params!(
        start_general_connection_establishment_procedure,
        GeneralConnectionEstablishmentParameters,
        crate::vendor::stm32wb::opcode::GAP_START_GENERAL_CONNECTION_ESTABLISHMENT
    );

    impl_validate_variable_length_params!(
        start_selective_connection_establishment_procedure<'a>,
        SelectiveConnectionEstablishmentParameters<'a>,
        crate::vendor::stm32wb::opcode::GAP_START_SELECTIVE_CONNECTION_ESTABLISHMENT
    );
    impl_params!(
        create_connection,
        ConnectionParameters,
        crate::vendor::stm32wb::opcode::GAP_CREATE_CONNECTION
    );

    async fn terminate_gap_procedure(&mut self, procedure: Procedure) -> Result<(), Error> {
        if procedure.is_empty() {
            return Err(Error::NoProcedure);
        }

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_TERMINATE_PROCEDURE,
            &[procedure.bits()],
        )
        .await;

        Ok(())
    }

    impl_params!(
        start_connection_update,
        ConnectionUpdateParameters,
        crate::vendor::stm32wb::opcode::GAP_START_CONNECTION_UPDATE
    );

    impl_params!(
        send_pairing_request,
        PairingRequest,
        crate::vendor::stm32wb::opcode::GAP_SEND_PAIRING_REQUEST
    );

    async fn resolve_private_address(&mut self, addr: crate::BdAddr) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_RESOLVE_PRIVATE_ADDRESS,
            &addr.0,
        )
        .await
    }

    impl_validate_variable_length_params!(
        set_broadcast_mode<'a, 'b>,
        BroadcastModeParameters<'a, 'b>,
        crate::vendor::stm32wb::opcode::GAP_SET_BROADCAST_MODE
    );

    impl_params!(
        start_observation_procedure,
        ObservationProcedureParameters,
        crate::vendor::stm32wb::opcode::GAP_START_OBSERVATION_PROCEDURE
    );

    async fn get_bonded_devices(&mut self) {
        self.controller_write(crate::vendor::stm32wb::opcode::GAP_GET_BONDED_DEVICES, &[])
            .await
    }

    async fn is_device_bonded(&mut self, addr: crate::host::PeerAddrType) {
        let mut bytes = [0; 7];
        addr.copy_into_slice(&mut bytes);

        self.controller_write(crate::vendor::stm32wb::opcode::GAP_IS_DEVICE_BONDED, &bytes)
            .await
    }

    impl_params!(
        numeric_comparison_value_confirm_yes_no,
        NumericComparisonValueConfirmYesNoParameters,
        crate::vendor::stm32wb::opcode::GAP_NUMERIC_COMPARISON_VALUE_YES_NO
    );

    async fn passkey_input(&mut self, conn_handle: ConnectionHandle, input_type: InputType) {
        let mut bytes = [0; 3];

        LittleEndian::write_u16(&mut bytes[..2], conn_handle.0);
        bytes[2] = input_type as u8;

        self.controller_write(crate::vendor::stm32wb::opcode::GAP_PASSKEY_INPUT, &bytes)
            .await
    }

    async fn get_oob_data(&mut self, oob_data_type: OobDataType) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_GET_OOB_DATA,
            &[oob_data_type as u8],
        )
        .await
    }

    impl_params!(
        set_oob_data,
        SetOobDataParameters,
        crate::vendor::stm32wb::opcode::GAP_SET_OOB_DATA
    );

    async fn add_devices_to_resolving_list(
        &mut self,
        whitelist_identities: &[PeerAddrType],
        clear_resolving_list: bool,
    ) {
        let mut bytes = [0; 254];

        bytes[0] = whitelist_identities.len() as u8;

        let mut index = 1;
        for id in whitelist_identities {
            id.copy_into_slice(&mut bytes[index..index + 7]);
            index += 7;
        }
        bytes[index] = clear_resolving_list as u8;

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_ADD_DEVICES_TO_RESOLVING_LIST,
            &bytes[..(index + 1)],
        )
        .await;
    }

    async fn remove_bonded_device(&mut self, address: BdAddrType) {
        let mut bytes = [0; 7];

        address.copy_into_slice(&mut bytes);
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_REMOVE_BONDED_DEVICE,
            &bytes,
        )
        .await;
    }

    async fn add_devices_to_list(
        &mut self,
        list_entries: &[BdAddrType],
        mode: AddDeviceToListMode,
    ) {
        let mut bytes = [0; 254];

        bytes[0] = list_entries.len() as u8;

        let mut index = 0;
        for entry in list_entries {
            entry.copy_into_slice(&mut bytes[index..index + 7]);
            index += 7;
        }
        bytes[index] = mode as u8;

        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_ADD_DEVICES_TO_LIST,
            &bytes[..(index + 1)],
        )
        .await;
    }

    impl_validate_params!(
        additional_beacon_start,
        AdditonalBeaconStartParameters,
        crate::vendor::stm32wb::opcode::GAP_ADDITIONAL_BEACON_START
    );

    async fn additional_beacon_stop(&mut self) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_ADDITIONAL_BEACON_STOP,
            &[],
        )
        .await;
    }

    async fn additonal_beacon_set_data(&mut self, advertising_data: &[u8]) {
        self.controller_write(
            crate::vendor::stm32wb::opcode::GAP_ADDITIONAL_BEACON_SET_DATA,
            advertising_data,
        )
        .await;
    }
}

/// Potential errors from parameter validation.
///
/// Before some commands are sent to the controller, the parameters are validated. This type
/// enumerates the potential validation errors. Must be specialized on the types of communication
/// errors.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// For the [GAP Set Limited Discoverable](Commands::set_limited_discoverable) and
    /// [GAP Set Discoverable](Commands::set_discoverable) commands, the connection
    /// interval is inverted (the min is greater than the max).  Return the provided min as the
    /// first element, max as the second.
    BadConnectionInterval(Duration, Duration),

    /// For the [GAP Set Limited Discoverable](Commands::set_limited_discoverable) and
    /// [GAP Set Broadcast Mode](Commands::set_broadcast_mode) commands, the advertising
    /// type is disallowed.  Returns the invalid advertising type.
    BadAdvertisingType(crate::types::AdvertisingType),

    /// For the [GAP Set Limited Discoverable](Commands::set_limited_discoverable)
    /// command, the advertising interval is inverted (that is, the max is less than the
    /// min). Includes the provided range.
    BadAdvertisingInterval(Duration, Duration),

    /// For the [GAP Set Authentication
    /// Requirement](Commands::set_authentication_requirement) command, the encryption
    /// key size range is inverted (the max is less than the min). Includes the provided range.
    BadEncryptionKeySizeRange(u8, u8),

    /// For the [GAP Set Authentication
    /// Requirement](GapCommands::set_authentication_requirement) command, the address type
    /// must be either Public or Random
    BadAddressType(AddressType),

    BadPowerAmplifierLevel(u8),

    /// For the [GAP Set Authentication
    /// Requirement](Commands::set_authentication_requirement) and [GAP Pass Key
    /// Response](Commands::pass_key_response) commands, the provided fixed pin is out of
    /// range (must be less than or equal to 999999).  Includes the provided PIN.
    BadFixedPin(u32),

    /// For the [GAP Set Undirected Connectable](Commands::set_undirected_connectable) command, the
    /// advertising filter policy is not one of the allowed values. Only
    /// [AllowConnectionAndScan](crate::AdvertisingFilterPolicy::AllowConnectionAndScan) and
    /// [WhiteListConnectionAndScan](crate::AdvertisingFilterPolicy::WhiteListConnectionAndScan) are
    /// allowed.
    BadAdvertisingFilterPolicy(crate::host::AdvertisingFilterPolicy),

    /// For the [GAP Update Advertising Data](Commands::update_advertising_data) and [GAP
    /// Set Broadcast Mode](Commands::set_broadcast_mode) commands, the advertising data
    /// is too long. It must be 31 bytes or less. The length of the provided data is returned.
    BadAdvertisingDataLength(usize),

    /// For the [GAP Terminate](Commands::terminate) command, the termination reason was
    /// not one of the allowed reason. The reason is returned.
    BadTerminationReason(crate::Status<crate::vendor::stm32wb::event::Status>),

    /// For the [GAP Start Auto Connection
    /// Establishment](Commands::start_auto_connection_establishment) or [GAP Start
    /// Selective Connection
    /// Establishment](Commands::start_selective_connection_establishment) commands, the
    /// provided [white list](AutoConnectionEstablishmentParameters::white_list) has more than 33
    /// or 35 entries, respectively, which would cause the command to be longer than 255 bytes.
    ///
    /// For the [GAP Set Broadcast Mode](Commands::set_broadcast_mode), the provided
    /// [white list](BroadcastModeParameters::white_list) the maximum number of entries ranges
    /// from 31 to 35, depending on the length of the advertising data.
    WhiteListTooLong,

    /// For the [GAP Terminate Procedure](Commands::terminate_procedure) command, the
    /// provided bitfield had no bits set.
    NoProcedure,
}

fn to_conn_interval_value(d: Duration) -> u16 {
    // Connection interval value: T = N * 1.25 ms
    // We have T, we need to return N.
    // N = T / 1.25 ms
    //   = 4 * T / 5 ms
    let millis = (d.as_secs() * 1000) as u32 + d.subsec_millis();
    (4 * millis / 5) as u16
}

fn to_connection_length_value(d: Duration) -> u16 {
    // Connection interval value: T = N * 0.625 ms
    // We have T, we need to return N.
    // N = T / 0.625 ms
    //   = T / 625 us
    // 1600 = 1_000_000 / 625
    (1600 * d.as_secs() as u32 + (d.subsec_micros() / 625)) as u16
}

/// Parameters for the
/// [`set_limited_discoverable`](Commands::set_limited_discoverable) and
/// [`set_discoverable`](Commands::set_discoverable) commands.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DiscoverableParameters<'a, 'b> {
    /// Advertising method for the device.
    ///
    /// Must be
    /// [ConnectableUndirected](crate::host::AdvertisingType::ConnectableUndirected),
    /// [ScannableUndirected](crate::host::AdvertisingType::ScannableUndirected), or
    /// [NonConnectableUndirected](crate::host::AdvertisingType::NonConnectableUndirected).
    pub advertising_type: AdvertisingType,

    /// Range of advertising for non-directed advertising.
    ///
    /// If not provided, the GAP will use default values (1.28 seconds).
    ///
    /// Range for both limits: 20 ms to 10.24 seconds.  The second value must be greater than or
    /// equal to the first.
    pub advertising_interval: Option<(Duration, Duration)>,

    /// Address type for this device.
    pub address_type: OwnAddressType,

    /// Filter policy for this device.
    pub filter_policy: AdvertisingFilterPolicy,

    /// Name of the device.
    pub local_name: Option<LocalName<'a>>,

    /// Service UUID list as defined in the Bluetooth spec, v4.1, Vol 3, Part C, Section 11.
    ///
    /// Must be 31 bytes or fewer.
    pub advertising_data: &'b [u8],

    /// Expected length of the connection to the peripheral.
    pub conn_interval: (Option<Duration>, Option<Duration>),
}

impl<'a, 'b> DiscoverableParameters<'a, 'b> {
    // 14 fixed-size parameters, one parameter of up to 31 bytes, and one of up to 248 bytes.
    const MAX_LENGTH: usize = 14 + 31 + 248;

    fn validate(&self) -> Result<(), Error> {
        match self.advertising_type {
            AdvertisingType::ConnectableUndirected
            | AdvertisingType::ScannableUndirected
            | AdvertisingType::NonConnectableUndirected => (),
            _ => return Err(Error::BadAdvertisingType(self.advertising_type)),
        }

        if let Some(interval) = self.advertising_interval {
            if interval.0 > interval.1 {
                return Err(Error::BadAdvertisingInterval(interval.0, interval.1));
            }
        }

        if let (Some(min), Some(max)) = self.conn_interval {
            if min > max {
                return Err(Error::BadConnectionInterval(min, max));
            }
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) -> usize {
        const NO_SPECIFIC_CONN_INTERVAL: u16 = 0x0000;

        let len = self.required_len();
        assert!(len <= bytes.len());

        let no_duration = Duration::from_secs(0);
        let no_interval: (Duration, Duration) = (no_duration, no_duration);

        bytes[0] = self.advertising_type as u8;
        LittleEndian::write_u16(
            &mut bytes[1..],
            to_connection_length_value(self.advertising_interval.unwrap_or(no_interval).0),
        );
        LittleEndian::write_u16(
            &mut bytes[3..],
            to_connection_length_value(self.advertising_interval.unwrap_or(no_interval).1),
        );
        bytes[5] = self.address_type as u8;
        bytes[6] = self.filter_policy as u8;
        let advertising_data_len_index = match self.local_name {
            None => {
                bytes[7] = 0;
                7
            }
            Some(LocalName::Shortened(name)) => {
                const AD_TYPE_SHORTENED_LOCAL_NAME: u8 = 0x08;
                bytes[7] = 1 + name.len() as u8;
                bytes[8] = AD_TYPE_SHORTENED_LOCAL_NAME;
                bytes[9..9 + name.len()].copy_from_slice(name);
                9 + name.len()
            }
            Some(LocalName::Complete(name)) => {
                const AD_TYPE_COMPLETE_LOCAL_NAME: u8 = 0x09;
                bytes[7] = 1 + name.len() as u8;
                bytes[8] = AD_TYPE_COMPLETE_LOCAL_NAME;
                bytes[9..9 + name.len()].copy_from_slice(name);
                9 + name.len()
            }
        };
        bytes[advertising_data_len_index] = self.advertising_data.len() as u8;
        bytes[(advertising_data_len_index + 1)
            ..(advertising_data_len_index + 1 + self.advertising_data.len())]
            .copy_from_slice(self.advertising_data);
        let conn_interval_index = advertising_data_len_index + 1 + self.advertising_data.len();
        LittleEndian::write_u16(
            &mut bytes[conn_interval_index..],
            if self.conn_interval.0.is_some() {
                to_conn_interval_value(self.conn_interval.0.unwrap())
            } else {
                NO_SPECIFIC_CONN_INTERVAL
            },
        );
        LittleEndian::write_u16(
            &mut bytes[(conn_interval_index + 2)..],
            if self.conn_interval.1.is_some() {
                to_conn_interval_value(self.conn_interval.1.unwrap())
            } else {
                NO_SPECIFIC_CONN_INTERVAL
            },
        );

        len
    }

    fn required_len(&self) -> usize {
        let fixed_len = 13;

        fixed_len + self.name_len() + self.advertising_data.len()
    }

    fn name_len(&self) -> usize {
        // The serialized name includes one byte indicating the type of name. That byte is not
        // included if the name is empty.
        match self.local_name {
            Some(LocalName::Shortened(bytes)) | Some(LocalName::Complete(bytes)) => 1 + bytes.len(),
            None => 0,
        }
    }
}

/// Allowed types for the local name.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum LocalName<'a> {
    /// The shortened local name.
    Shortened(&'a [u8]),

    /// The complete local name.
    Complete(&'a [u8]),
}

/// Parameters for the
/// [`set_undirected_connectable`](GapCommands::set_undirected_connectable) command.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct UndirectedConnectableParameters {
    /// Range of advertising interval for advertising.
    ///
    /// Range for both limits: 20 ms to 10.24 seconds.  The second value must be greater than or
    /// equal to the first.
    pub advertising_interval: (Duration, Duration),

    /// Address type of this device.
    pub own_address_type: OwnAddressType,

    /// filter policy for this device
    pub filter_policy: AdvertisingFilterPolicy,
}

impl UndirectedConnectableParameters {
    const LENGTH: usize = 6;

    fn validate(&self) -> Result<(), Error> {
        const MIN_DURATION: Duration = Duration::from_millis(20);
        const MAX_DURATION: Duration = Duration::from_millis(10240);

        match self.filter_policy {
            AdvertisingFilterPolicy::AllowConnectionAndScan
            | AdvertisingFilterPolicy::WhiteListConnectionAndScan => {}
            _ => return Err(Error::BadAdvertisingFilterPolicy(self.filter_policy)),
        }

        if self.advertising_interval.0 < MIN_DURATION
            || self.advertising_interval.1 > MAX_DURATION
            || self.advertising_interval.0 > self.advertising_interval.1
        {
            return Err(Error::BadAdvertisingInterval(
                self.advertising_interval.0,
                self.advertising_interval.1,
            ));
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert_eq!(bytes.len(), Self::LENGTH);

        LittleEndian::write_u16(
            &mut bytes[0..],
            to_connection_length_value(self.advertising_interval.0),
        );
        LittleEndian::write_u16(
            &mut bytes[2..],
            to_connection_length_value(self.advertising_interval.1),
        );

        bytes[4] = self.own_address_type as u8;
        bytes[5] = self.filter_policy as u8;
    }
}

/// Parameters for the
/// [`set_direct_connectable`](GapCommands::set_direct_connectable) command.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DirectConnectableParameters {
    /// Address type of this device.
    pub own_address_type: OwnAddressType,

    /// Advertising method for the device.
    ///
    /// Must be
    /// [ConnectableDirectedHighDutyCycle](crate::host::AdvertisingType::ConnectableDirectedHighDutyCycle),
    /// or
    /// [ConnectableDirectedLowDutyCycle](crate::host::AdvertisingType::ConnectableDirectedLowDutyCycle).
    pub advertising_type: AdvertisingType,

    /// Initiator's Bluetooth address.
    pub initiator_address: BdAddrType,

    /// Range of advertising interval for advertising.
    ///
    /// Range for both limits: 20 ms to 10.24 seconds.  The second value must be greater than or
    /// equal to the first.
    pub advertising_interval: (Duration, Duration),
}

impl DirectConnectableParameters {
    const LENGTH: usize = 13;

    fn validate(&self) -> Result<(), Error> {
        const MIN_DURATION: Duration = Duration::from_millis(20);
        const MAX_DURATION: Duration = Duration::from_millis(10240);

        match self.advertising_type {
            AdvertisingType::ConnectableDirectedHighDutyCycle
            | AdvertisingType::ConnectableDirectedLowDutyCycle => (),
            _ => return Err(Error::BadAdvertisingType(self.advertising_type)),
        }

        if self.advertising_interval.0 < MIN_DURATION
            || self.advertising_interval.1 > MAX_DURATION
            || self.advertising_interval.0 > self.advertising_interval.1
        {
            return Err(Error::BadAdvertisingInterval(
                self.advertising_interval.0,
                self.advertising_interval.1,
            ));
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert_eq!(bytes.len(), Self::LENGTH);

        bytes[0] = self.own_address_type as u8;

        bytes[1] = self.advertising_type as u8;
        self.initiator_address.copy_into_slice(&mut bytes[2..9]);
        LittleEndian::write_u16(
            &mut bytes[9..],
            to_connection_length_value(self.advertising_interval.0),
        );
        LittleEndian::write_u16(
            &mut bytes[11..],
            to_connection_length_value(self.advertising_interval.1),
        );
    }
}

/// I/O capabilities available for the [GAP Set I/O
/// Capability](Commands::set_io_capability) command.
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum IoCapability {
    /// Display Only
    Display = 0x00,
    /// Display yes/no
    DisplayConfirm = 0x01,
    /// Keyboard Only
    Keyboard = 0x02,
    /// No Input, no output
    None = 0x03,
    /// Keyboard display
    KeyboardDisplay = 0x04,
}

/// Parameters for the [GAP Set Authentication
/// Requirement](Commands::set_authentication_requirement) command.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AuthenticationRequirements {
    /// Is bonding required?
    pub bonding_required: bool,

    /// Is MITM (man-in-the-middle) protection required?
    pub mitm_protection_required: bool,

    /// is secure connection support required
    pub secure_connection_support: SecureConnectionSupport,

    /// is keypress notification support required
    pub keypress_notification_support: bool,

    /// Minimum and maximum size of the encryption key.
    pub encryption_key_size_range: (u8, u8),

    /// Pin to use during the pairing process.
    pub fixed_pin: Pin,

    /// identity address type.
    pub identity_address_type: AddressType,
}

impl AuthenticationRequirements {
    const LENGTH: usize = 12;

    fn validate(&self) -> Result<(), Error> {
        if self.encryption_key_size_range.0 > self.encryption_key_size_range.1 {
            return Err(Error::BadEncryptionKeySizeRange(
                self.encryption_key_size_range.0,
                self.encryption_key_size_range.1,
            ));
        }

        if let Pin::Fixed(pin) = self.fixed_pin {
            if pin > 999_999 {
                return Err(Error::BadFixedPin(pin));
            }
        }

        if self.identity_address_type != AddressType::Public
            && self.identity_address_type != AddressType::Random
        {
            return Err(Error::BadAddressType(self.identity_address_type));
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert_eq!(bytes.len(), Self::LENGTH);

        bytes[0] = self.bonding_required as u8;
        bytes[1] = self.mitm_protection_required as u8;
        bytes[2] = self.secure_connection_support as u8;
        bytes[3] = self.keypress_notification_support as u8;
        bytes[4] = self.encryption_key_size_range.0;
        bytes[5] = self.encryption_key_size_range.1;
        match self.fixed_pin {
            Pin::Requested => {
                bytes[6] = 1;
                bytes[7..11].copy_from_slice(&[0; 4]);
            }
            Pin::Fixed(pin) => {
                bytes[6] = 0;
                LittleEndian::write_u32(&mut bytes[7..11], pin);
            }
        }
        bytes[11] = self.identity_address_type as u8;
    }
}

/// Options for [`out_of_band_auth`](AuthenticationRequirements::out_of_band_auth).
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum OutOfBandAuthentication {
    /// Out Of Band authentication not enabled
    Disabled,
    /// Out Of Band authentication enabled; includes the OOB data.
    Enabled([u8; 16]),
}

/// Options for [`secure_connection_support`](AuthenticationRequirements)
#[derive(Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SecureConnectionSupport {
    NotSupported = 0x00,
    Optional = 0x01,
    Mandatory = 0x02,
}

/// Options for [`fixed_pin`](AuthenticationRequirements).
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Pin {
    /// Do not use fixed pin during the pairing process.  In this case, GAP will generate a [GAP
    /// Pass Key Request](crate::vendor::stm32wb::event::BlueNRGEvent::GapPassKeyRequest) event to the host.
    Requested,

    /// Use a fixed pin during pairing. The provided value is used as the PIN, and must be 999999 or
    /// less.
    Fixed(u32),
}

/// Options for the [GAP Authorization Response](Commands::authorization_response).
#[repr(u8)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Authorization {
    /// Accept the connection.
    Authorized = 0x01,
    /// Reject the connection.
    Rejected = 0x02,
}

#[cfg(not(feature = "defmt"))]
bitflags::bitflags! {
    /// Roles for a [GAP service](Commands::init).
    pub struct Role: u8 {
        /// Peripheral
        const PERIPHERAL = 0x01;
        /// Broadcaster
        const BROADCASTER = 0x02;
        /// Central Device
        const CENTRAL = 0x04;
        /// Observer
        const OBSERVER = 0x08;
    }
}

#[cfg(feature = "defmt")]
defmt::bitflags! {
    /// Roles for a [GAP service](Commands::init).
    pub struct Role: u8 {
        /// Peripheral
        const PERIPHERAL = 0x01;
        /// Broadcaster
        const BROADCASTER = 0x02;
        /// Central Device
        const CENTRAL = 0x04;
        /// Observer
        const OBSERVER = 0x08;
    }
}

/// Indicates the type of address being used in the advertising packets, for the
/// [`set_nonconnectable`](Commands::set_nonconnectable).
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AddressType {
    /// Public device address.
    Public = 0x00,
    /// Static random device address.
    Random = 0x01,
    /// Controller generates Resolvable Private Address.
    ResolvablePrivate = 0x02,
    /// Controller generates Resolvable Private Address. based on the local IRK from resolving
    /// list.
    NonResolvablePrivate = 0x03,
}

/// Available types of advertising data.
#[repr(u8)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AdvertisingDataType {
    /// Flags
    Flags = 0x01,
    /// 16-bit service UUID
    Uuid16 = 0x02,
    /// Complete list of 16-bit service UUIDs
    UuidCompleteList16 = 0x03,
    /// 32-bit service UUID
    Uuid32 = 0x04,
    /// Complete list of 32-bit service UUIDs
    UuidCompleteList32 = 0x05,
    /// 128-bit service UUID
    Uuid128 = 0x06,
    /// Complete list of 128-bit service UUIDs.
    UuidCompleteList128 = 0x07,
    /// Shortened local name
    ShortenedLocalName = 0x08,
    /// Complete local name
    CompleteLocalName = 0x09,
    /// Transmitter power level
    TxPowerLevel = 0x0A,
    /// Serurity Manager TK Value
    SecurityManagerTkValue = 0x10,
    /// Serurity Manager out-of-band flags
    SecurityManagerOutOfBandFlags = 0x11,
    /// Connection interval
    PeripheralConnectionInterval = 0x12,
    /// Service solicitation list, 16-bit UUIDs
    SolicitUuidList16 = 0x14,
    /// Service solicitation list, 32-bit UUIDs
    SolicitUuidList32 = 0x15,
    /// Service data
    ServiceData = 0x16,
    /// Manufacturer-specific data
    ManufacturerSpecificData = 0xFF,
}

#[cfg(not(feature = "defmt"))]
bitflags::bitflags! {
    /// Event types for [GAP Set Event Mask](Commands::set_event_mask).
    #[derive(Debug, Clone, Copy)]
    pub struct EventFlags: u16 {
        /// [Limited Discoverable](::event::BlueNRGEvent::GapLimitedDiscoverableTimeout)
        const LIMITED_DISCOVERABLE_TIMEOUT = 0x0001;
        /// [Pairing Complete](::event::BlueNRGEvent::GapPairingComplete)
        const PAIRING_COMPLETE = 0x0002;
        /// [Pass Key Request](::event::BlueNRGEvent::GapPassKeyRequest)
        const PASS_KEY_REQUEST = 0x0004;
        /// [Authorization Request](::event::BlueNRGEvent::GapAuthorizationRequest)
        const AUTHORIZATION_REQUEST = 0x0008;
        /// [Peripheral Security Initiated](::event::BlueNRGEvent::GapPeripheralSecurityInitiated).
        const PERIPHERAL_SECURITY_INITIATED = 0x0010;
        /// [Bond Lost](::event::BlueNRGEvent::GapBondLost)
        const BOND_LOST = 0x0020;
    }
}

#[cfg(feature = "defmt")]
defmt::bitflags! {
    /// Event types for [GAP Set Event Mask](Commands::set_event_mask).
    pub struct EventFlags: u16 {
        /// [Limited Discoverable](::event::BlueNRGEvent::GapLimitedDiscoverableTimeout)
        const LIMITED_DISCOVERABLE_TIMEOUT = 0x0001;
        /// [Pairing Complete](::event::BlueNRGEvent::GapPairingComplete)
        const PAIRING_COMPLETE = 0x0002;
        /// [Pass Key Request](::event::BlueNRGEvent::GapPassKeyRequest)
        const PASS_KEY_REQUEST = 0x0004;
        /// [Authorization Request](::event::BlueNRGEvent::GapAuthorizationRequest)
        const AUTHORIZATION_REQUEST = 0x0008;
        /// [Peripheral Security Initiated](::event::BlueNRGEvent::GapPeripheralSecurityInitiated).
        const PERIPHERAL_SECURITY_INITIATED = 0x0010;
        /// [Bond Lost](::event::BlueNRGEvent::GapBondLost)
        const BOND_LOST = 0x0020;
    }
}

/// Parameters for the [GAP Limited
/// Discovery](GapCommands::start_limited_discovery_procedure) and [GAP General
/// Discovery](GapCommands::start_general_discovery_procedure) procedures.
pub struct DiscoveryProcedureParameters {
    /// Scanning window for the discovery procedure.
    pub scan_window: ScanWindow,

    /// Address type of this device.
    pub own_address_type: crate::host::OwnAddressType,

    /// If true, duplicate devices are filtered out.
    pub filter_duplicates: bool,
}

impl DiscoveryProcedureParameters {
    const LENGTH: usize = 6;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert_eq!(bytes.len(), Self::LENGTH);

        self.scan_window.copy_into_slice(&mut bytes[0..4]);
        bytes[4] = self.own_address_type as u8;
        bytes[5] = self.filter_duplicates as u8;
    }
}

/// Parameters for the [GAP Name Discovery](Commands::start_name_discovery_procedure)
/// procedure.
pub struct NameDiscoveryProcedureParameters {
    /// Scanning window for the discovery procedure.
    pub scan_window: ScanWindow,

    /// Address of the connected device
    pub peer_address: crate::host::PeerAddrType,

    /// Address type of this device.
    pub own_address_type: crate::host::OwnAddressType,

    /// Connection interval parameters.
    pub conn_interval: ConnectionInterval,

    /// Expected connection length
    pub expected_connection_length: ExpectedConnectionLength,
}

impl NameDiscoveryProcedureParameters {
    const LENGTH: usize = 24;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert_eq!(bytes.len(), Self::LENGTH);

        self.scan_window.copy_into_slice(&mut bytes[0..4]);
        self.peer_address.copy_into_slice(&mut bytes[4..11]);
        bytes[11] = self.own_address_type as u8;
        self.conn_interval.copy_into_slice(&mut bytes[12..20]);
        self.expected_connection_length
            .copy_into_slice(&mut bytes[20..24]);
    }
}

/// Parameters for the [GAP Start Auto Connection
/// Establishment](Commands::start_auto_connection_establishment) command.
pub struct AutoConnectionEstablishmentParameters<'a> {
    /// Scanning window for connection establishment.
    pub scan_window: ScanWindow,

    /// Address type of this device.
    pub own_address_type: crate::host::OwnAddressType,

    /// Connection interval parameters.
    pub conn_interval: ConnectionInterval,

    /// Expected connection length
    pub expected_connection_length: ExpectedConnectionLength,

    /// Addresses to white-list for automatic connection.
    pub white_list: &'a [crate::host::PeerAddrType],
}

impl<'a> AutoConnectionEstablishmentParameters<'a> {
    const MAX_LENGTH: usize = 249;

    fn validate(&self) -> Result<(), Error> {
        const MAX_WHITE_LIST_LENGTH: usize = 33;
        if self.white_list.len() > MAX_WHITE_LIST_LENGTH {
            return Err(Error::WhiteListTooLong);
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) -> usize {
        let len = self.len();
        assert!(bytes.len() >= len);

        self.scan_window.copy_into_slice(&mut bytes[0..4]);
        bytes[4] = self.own_address_type as u8;
        self.conn_interval.copy_into_slice(&mut bytes[5..13]);
        self.expected_connection_length
            .copy_into_slice(&mut bytes[13..17]);

        let index = 17;

        bytes[index] = self.white_list.len() as u8;
        let index = index + 1;
        for i in 0..self.white_list.len() {
            self.white_list[i].copy_into_slice(&mut bytes[(index + 7 * i)..(index + 7 * (i + 1))]);
        }

        len
    }

    fn len(&self) -> usize {
        let reconn_addr_len = 0;
        18 + reconn_addr_len + 7 * self.white_list.len()
    }
}

/// Parameters for the [GAP Start General Connection
/// Establishment](Commands::start_general_connection_establishment) command.
pub struct GeneralConnectionEstablishmentParameters {
    /// passive or active scanning. With passive scanning, no scan request PDUs are sent
    pub scan_type: ScanType,

    /// Scanning window for connection establishment.
    pub scan_window: ScanWindow,

    /// Address type of this device.
    pub own_address_type: crate::host::OwnAddressType,

    /// Scanning filter policy.
    ///
    /// # Note
    /// if privacy is enabled, filter policy can only assume values
    /// [Accept All](ScanFilterPolicy::AcceptAll) or
    /// [Addressed To This Device](ScanFilterPolicy::AddressedToThisDevice)
    pub filter_policy: ScanFilterPolicy,

    /// If true, only report unique devices.
    pub filter_duplicates: bool,
}

impl GeneralConnectionEstablishmentParameters {
    const LENGTH: usize = 8;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= Self::LENGTH);

        bytes[0] = self.scan_type as u8;
        self.scan_window.copy_into_slice(&mut bytes[1..5]);
        bytes[5] = self.filter_policy as u8;
        bytes[6] = self.own_address_type as u8;
        bytes[7] = self.filter_duplicates as u8;
    }
}

/// Parameters for the [GAP Start Selective Connection
/// Establishment](Commands::start_selective_connection_establishment) command.
pub struct SelectiveConnectionEstablishmentParameters<'a> {
    /// Type of scanning
    pub scan_type: crate::host::ScanType,

    /// Scanning window for connection establishment.
    pub scan_window: ScanWindow,

    /// Address type of this device.
    pub own_address_type: crate::host::OwnAddressType,

    /// Scanning filter policy.
    ///
    /// # Note
    /// if privacy is enabled, filter policy can only assume values
    /// [Accept All](ScanFilterPolicy::AcceptAll) or
    /// [Whitelist Addressed to this Device](ScanFilterPolicy::WhiteListAddressedToThisDevice)
    pub filter_policy: ScanFilterPolicy,

    /// If true, only report unique devices.
    pub filter_duplicates: bool,

    /// Addresses to white-list for automatic connection.
    pub white_list: &'a [crate::host::PeerAddrType],
}

impl<'a> SelectiveConnectionEstablishmentParameters<'a> {
    const MAX_LENGTH: usize = 254;

    fn validate(&self) -> Result<(), Error> {
        const MAX_WHITE_LIST_LENGTH: usize = 35;
        if self.white_list.len() > MAX_WHITE_LIST_LENGTH {
            return Err(Error::WhiteListTooLong);
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) -> usize {
        let len = self.len();
        assert!(bytes.len() >= len);

        bytes[0] = self.scan_type as u8;
        self.scan_window.copy_into_slice(&mut bytes[1..5]);
        bytes[5] = self.own_address_type as u8;
        bytes[6] = self.filter_policy as u8;
        bytes[7] = self.filter_duplicates as u8;
        bytes[8] = self.white_list.len() as u8;
        for i in 0..self.white_list.len() {
            self.white_list[i].copy_into_slice(&mut bytes[(9 + 7 * i)..(9 + 7 * (i + 1))]);
        }

        len
    }

    fn len(&self) -> usize {
        9 + 7 * self.white_list.len()
    }
}

/// The parameters for the [GAP Name Discovery](Commands::start_name_discovery_procedure)
/// and [GAP Create Connection](Commands::create_connection) commands are identical.
pub type ConnectionParameters = NameDiscoveryProcedureParameters;

#[cfg(not(feature = "defmt"))]
bitflags::bitflags! {
    /// Roles for a [GAP service](Commands::init).
    pub struct Procedure: u8 {
        /// [Limited Discovery](Commands::start_limited_discovery_procedure) procedure.
        const LIMITED_DISCOVERY = 0x01;
        /// [General Discovery](Commands::start_general_discovery_procedure) procedure.
        const GENERAL_DISCOVERY = 0x02;
        /// [Name Discovery](Commands::start_name_discovery_procedure) procedure.
        const NAME_DISCOVERY = 0x04;
        /// [Auto Connection Establishment](Commands::auto_connection_establishment).
        const AUTO_CONNECTION_ESTABLISHMENT = 0x08;
        /// [General Connection
        /// Establishment](Commands::general_connection_establishment).
        const GENERAL_CONNECTION_ESTABLISHMENT = 0x10;
        /// [Selective Connection
        /// Establishment](Commands::selective_connection_establishment).
        const SELECTIVE_CONNECTION_ESTABLISHMENT = 0x20;
        /// [Direct Connection
        /// Establishment](Commands::direct_connection_establishment).
        const DIRECT_CONNECTION_ESTABLISHMENT = 0x40;
        /// [Observation](Commands::start_observation_procedure) procedure.
        const OBSERVATION = 0x80;
    }
}

#[cfg(feature = "defmt")]
defmt::bitflags! {
    /// Roles for a [GAP service](Commands::init).
    pub struct Procedure: u8 {
        /// [Limited Discovery](Commands::start_limited_discovery_procedure) procedure.
        const LIMITED_DISCOVERY = 0x01;
        /// [General Discovery](Commands::start_general_discovery_procedure) procedure.
        const GENERAL_DISCOVERY = 0x02;
        /// [Name Discovery](Commands::start_name_discovery_procedure) procedure.
        const NAME_DISCOVERY = 0x04;
        /// [Auto Connection Establishment](Commands::auto_connection_establishment).
        const AUTO_CONNECTION_ESTABLISHMENT = 0x08;
        /// [General Connection
        /// Establishment](Commands::general_connection_establishment).
        const GENERAL_CONNECTION_ESTABLISHMENT = 0x10;
        /// [Selective Connection
        /// Establishment](Commands::selective_connection_establishment).
        const SELECTIVE_CONNECTION_ESTABLISHMENT = 0x20;
        /// [Direct Connection
        /// Establishment](Commands::direct_connection_establishment).
        const DIRECT_CONNECTION_ESTABLISHMENT = 0x40;
        /// [Observation](Commands::start_observation_procedure) procedure.
        const OBSERVATION = 0x80;
    }
}

/// Parameters for the [`start_connection_update`](Commands::start_connection_update)
/// command.
pub struct ConnectionUpdateParameters {
    /// Handle of the connection for which the update procedure has to be started.
    pub conn_handle: crate::ConnectionHandle,

    /// Updated connection interval for the connection.
    pub conn_interval: ConnectionInterval,

    /// Expected length of connection event needed for this connection.
    pub expected_connection_length: ExpectedConnectionLength,
}

impl ConnectionUpdateParameters {
    const LENGTH: usize = 14;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        LittleEndian::write_u16(&mut bytes[0..2], self.conn_handle.0);
        self.conn_interval.copy_into_slice(&mut bytes[2..10]);
        self.expected_connection_length
            .copy_into_slice(&mut bytes[10..14]);
    }
}

/// Parameters for the [`send_pairing_request`](Commands::send_pairing_request)
/// command.
pub struct PairingRequest {
    /// Handle of the connection for which the pairing request has to be sent.
    pub conn_handle: crate::ConnectionHandle,

    /// Whether pairing request has to be sent if the device is previously bonded or not. If false,
    /// the pairing request is sent only if the device has not previously bonded.
    pub force_rebond: bool,
}

impl PairingRequest {
    const LENGTH: usize = 2;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= Self::LENGTH);

        LittleEndian::write_u16(&mut bytes[0..2], self.conn_handle.0);
    }
}

/// Parameters for the [GAP Set Broadcast Mode](Commands::set_broadcast_mode) command.
pub struct BroadcastModeParameters<'a, 'b> {
    /// Advertising type and interval.
    ///
    /// Only the [ScannableUndirected](crate::types::AdvertisingType::ScannableUndirected) and
    /// [NonConnectableUndirected](crate::types::AdvertisingType::NonConnectableUndirected).
    pub advertising_interval: crate::types::AdvertisingInterval,

    /// Type of this device's address.
    ///
    /// A privacy enabled device uses either a [resolvable private
    /// address](AddressType::ResolvablePrivate) or a [non-resolvable
    /// private](AddressType::NonResolvablePrivate) address.
    pub own_address_type: AddressType,

    /// Advertising data used by the device when advertising.
    ///
    /// Must be 31 bytes or fewer.
    pub advertising_data: &'a [u8],

    /// Addresses to add to the white list.
    ///
    /// Each address takes up 7 bytes (1 byte for the type, 6 for the address). The full length of
    /// this packet must not exceed 255 bytes. The white list must be less than a maximum of between
    /// 31 and 35 entries, depending on the length of
    /// [`advertising_data`](BroadcastModeParameters::advertising_data). Shorter advertising data
    /// allows more white list entries.
    pub white_list: &'b [crate::host::PeerAddrType],
}

impl<'a, 'b> BroadcastModeParameters<'a, 'b> {
    const MAX_LENGTH: usize = 255;

    fn validate(&self) -> Result<(), Error> {
        const MAX_ADVERTISING_DATA_LENGTH: usize = 31;

        match self.advertising_interval.advertising_type() {
            crate::types::AdvertisingType::ScannableUndirected
            | crate::types::AdvertisingType::NonConnectableUndirected => (),
            other => return Err(Error::BadAdvertisingType(other)),
        }

        if self.advertising_data.len() > MAX_ADVERTISING_DATA_LENGTH {
            return Err(Error::BadAdvertisingDataLength(self.advertising_data.len()));
        }

        if self.len() > Self::MAX_LENGTH {
            return Err(Error::WhiteListTooLong);
        }

        Ok(())
    }

    fn len(&self) -> usize {
        5 + // advertising_interval
            1 + // own_address_type
            1 + self.advertising_data.len() + // advertising_data
            1 + 7 * self.white_list.len() // white_list
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) -> usize {
        assert!(self.len() <= bytes.len());

        self.advertising_interval.copy_into_slice(&mut bytes[0..5]);
        bytes[5] = self.own_address_type as u8;
        bytes[6] = self.advertising_data.len() as u8;
        bytes[7..7 + self.advertising_data.len()].copy_from_slice(self.advertising_data);
        bytes[7 + self.advertising_data.len()] = self.white_list.len() as u8;

        let mut index = 8 + self.advertising_data.len();
        for addr in self.white_list.iter() {
            addr.copy_into_slice(&mut bytes[index..index + 7]);
            index += 7;
        }

        index
    }
}

/// Parameters for the [GAP Start Observation Procedure](Commands::start_observation_procedure)
/// command.
pub struct ObservationProcedureParameters {
    /// Scanning window.
    pub scan_window: crate::types::ScanWindow,

    /// Active or passive scanning
    pub scan_type: crate::host::ScanType,

    /// Address type of this device.
    pub own_address_type: AddressType,

    /// If true, do not report duplicate events in the [advertising
    /// report](crate::event::Event::LeAdvertisingReport).
    pub filter_duplicates: bool,

    /// Scanning filter policy
    pub filter_policy: ScanFilterPolicy,
}

impl ObservationProcedureParameters {
    const LENGTH: usize = 8;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= Self::LENGTH);

        self.scan_window.copy_into_slice(&mut bytes[0..4]);
        bytes[4] = self.scan_type as u8;
        bytes[5] = self.own_address_type as u8;
        bytes[6] = self.filter_duplicates as u8;
        bytes[7] = self.filter_policy as u8;
    }
}

/// Parameters for [GAP Numeric Comparison Confirm Yes or No](crate::vendor::stm32wb::command::gap::GapCommands::numeric_comparison_value_confirm_yes_no)
pub struct NumericComparisonValueConfirmYesNoParameters {
    conn_handle: ConnectionHandle,
    confirm_yes_no: bool,
}

impl NumericComparisonValueConfirmYesNoParameters {
    const LENGTH: usize = 3;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= Self::LENGTH);

        LittleEndian::write_u16(&mut bytes[0..2], self.conn_handle.0);
        bytes[2] = self.confirm_yes_no as u8;
    }
}

/// Parameter for [GAP Passkey Input](GapCommands::passkey_input)
pub enum InputType {
    EntryStarted = 0x00,
    DigitEntered = 0x01,
    DigitErased = 0x02,
    Cleared = 0x03,
    EntryCompleted = 0x04,
}

#[derive(Clone, Copy)]
pub enum OobDataType {
    /// TK (LP v.4.1)
    TK,
    /// Random (SC)
    Random,
    /// Confirm (SC)
    Confirm,
}

#[derive(Clone, Copy)]
pub enum OobDeviceType {
    Local = 0x00,
    Remote = 0x01,
}

/// Parameters for [GAP Set OOB Data](GapCommands::set_oob_data)
pub struct SetOobDataParameters {
    /// OOB Device type
    device_type: OobDeviceType,
    /// Identity address
    address: BdAddrType,
    /// OOB Data type
    oob_data_type: OobDataType,
    /// Pairing Data received through OOB from remote device
    oob_data: [u8; 16],
}

impl SetOobDataParameters {
    const LENGTH: usize = 26;

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= Self::LENGTH);

        bytes[0] = self.device_type as u8;
        self.address.copy_into_slice(&mut bytes[1..8]);
        bytes[9] = self.oob_data_type as u8;
        bytes[10..26].copy_from_slice(&self.oob_data)
    }
}

/// Parameter for [GAP Add Devices to List](GapCommands::add_devices_to_list)
pub enum AddDeviceToListMode {
    /// Append to the resolving list only
    AppendResoling = 0x00,
    /// clear and set the resolving list only
    ClearAndSetResolving = 0x01,
    /// append to the whitelist only
    AppendWhitelist = 0x02,
    /// clear and set the whitelist only
    ClearAndSetWhitelist = 0x03,
    /// apppend to both resolving and white lists
    AppendBoth = 0x04,
    /// clear and set both resolving and white lists
    ClearAndSetBoth = 0x05,
}

/// Parameters for [GAP Additional Beacon Start](GapCommands::additional_beacon_start)
pub struct AdditonalBeaconStartParameters {
    /// Advertising interval
    pub advertising_interval: (Duration, Duration),
    /// advertising channel map
    pub advertising_channel_map: Channels,
    /// Own address type
    pub own_address_type: BdAddrType,
    /// Power amplifier output level. Range: 0x00 .. 0x23
    pub pa_level: u8,
}

impl AdditonalBeaconStartParameters {
    const LENGTH: usize = 13;

    fn validate(&self) -> Result<(), Error> {
        const AMPLIFIER_MAX: u8 = 0x23;

        if self.pa_level > AMPLIFIER_MAX {
            return Err(Error::BadPowerAmplifierLevel(self.pa_level));
        }

        Ok(())
    }

    fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= Self::LENGTH);

        LittleEndian::write_u16(
            &mut bytes[0..],
            to_connection_length_value(self.advertising_interval.0),
        );
        LittleEndian::write_u16(
            &mut bytes[2..],
            to_connection_length_value(self.advertising_interval.1),
        );
        bytes[4] = self.advertising_channel_map.bits();
        self.own_address_type.copy_into_slice(&mut bytes[5..12]);
        bytes[12] = self.pa_level;
    }
}