1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
//! Vendor-specific events for BlueNRG controllers.
//!
//! The BlueNRG implementation defines several additional events that are packaged as
//! vendor-specific events by the Bluetooth HCI. This module defines those events and functions to
//! deserialize buffers into them.
pub mod command;
use byteorder::{ByteOrder, LittleEndian};
use core::cmp::PartialEq;
use core::convert::{TryFrom, TryInto};
use core::fmt::{Debug, Formatter, Result as FmtResult};
use core::mem;
use core::time::Duration;
pub use crate::types::{ConnectionInterval, ConnectionIntervalError};
pub use crate::{BdAddr, BdAddrType, ConnectionHandle};
/// Vendor-specific events for the STM32WB5x radio coprocessor.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Stm32Wb5xEvent {
/// When the radio coprocessor firmware is started normally, it gives this event to the user to
/// indicate the system has started.
CoprocessorReady(FirmwareKind),
/// If the host fails to read events from the controller quickly enough, the controller will
/// generate this event. This event is never lost; it is inserted as soon as space is available
/// in the Tx queue.
EventsLost(EventFlags),
/// The fault data event is automatically sent after the
/// [HalInitialized](Stm32Wb5xEvent::HalInitialized) event in case of [NMI or Hard
/// fault](ResetReason::Crash).
// CrashReport(FaultData),
/// This event is generated by the controller when the limited discoverable mode ends due to
/// timeout (180 seconds).
GapLimitedDiscoverableTimeout,
/// This event is generated when the pairing process has completed successfully or a pairing
/// procedure timeout has occurred or the pairing has failed. This is to notify the application
/// that we have paired with a remote device so that it can take further actions or to notify
/// that a timeout has occurred so that the upper layer can decide to disconnect the link.
GapPairingComplete(GapPairingComplete),
/// This event is generated by the Security manager to the application when a pass key is
/// required for pairing. When this event is received, the application has to respond with the
/// `gap_pass_key_response` command.
GapPassKeyRequest(ConnectionHandle),
/// This event is generated by the Security manager to the application when the application has
/// set that authorization is required for reading/writing of attributes. This event will be
/// generated as soon as the pairing is complete. When this event is received,
/// `gap_authorization_response` command should be used by the application.
GapAuthorizationRequest(ConnectionHandle),
/// This event is generated when the peripheral security request is successfully sent to the
/// central device.
GapPeripheralSecurityInitiated,
/// This event is generated on the peripheral when a `gap_peripheral_security_request` is called
/// to reestablish the bond with the central device but the central device has lost the
/// bond. When this event is received, the upper layer has to issue the command
/// `gap_allow_rebond` in order to allow the peripheral to continue the pairing process with the
/// central device. On the central device, this event is raised when `gap_send_pairing_request`
/// is called to reestablish a bond with a peripheral but the peripheral has lost the bond. In
/// order to create a new bond the central device has to launch `gap_send_pairing_request` with
/// `force_rebond` set to `true`.
GapBondLost,
/// The event is given by the GAP layer to the upper layers when a device is discovered during
/// scanning as a consequence of one of the GAP procedures started by the upper layers.
GapDeviceFound(GapDeviceFound),
/// This event is sent by the GAP to the upper layers when a procedure previously started has
/// been terminated by the upper layer or has completed for any other reason
GapProcedureComplete(GapProcedureComplete),
/// This event is sent only by a privacy enabled peripheral. The event is sent to the upper
/// layers when the peripheral is unsuccessful in resolving the resolvable address of the peer
/// device after connecting to it.
GapAddressNotResolved(ConnectionHandle),
NumericComparisonValue(NumericComparisonValue),
KeypressNotification(u8),
/// This event is generated when the central device responds to the L2CAP connection update
/// request packet. For more info see
/// [ConnectionParameterUpdateResponse](crate::l2cap::ConnectionParameterUpdateResponse)
/// and CommandReject in Bluetooth Core v4.0 spec.
L2CapConnectionUpdateResponse(L2CapConnectionUpdateResponse),
/// This event is generated when the central device does not respond to the connection update
/// request within 30 seconds.
L2CapProcedureTimeout(ConnectionHandle),
/// The event is given by the L2CAP layer when a connection update request is received from the
/// peripheral. The application has to respond by calling
/// [`l2cap_connection_parameter_update_response`](crate::l2cap::Commands::connection_parameter_update_response).
L2CapConnectionUpdateRequest(L2CapConnectionUpdateRequest),
L2CapCommandReject(L2CapCommandReject),
/// This event is generated to the application by the ATT server when a client modifies any
/// attribute on the server, as consequence of one of the following ATT procedures:
/// - write without response
/// - signed write without response
/// - write characteristic value
/// - write long characteristic value
/// - reliable write
GattAttributeModified(GattAttributeModified),
/// This event is generated when a ATT client procedure completes either with error or
/// successfully.
GattProcedureTimeout(ConnectionHandle),
/// This event is generated in response to an Exchange MTU request.
AttExchangeMtuResponse(AttExchangeMtuResponse),
/// This event is generated in response to a Find Information Request. See Find Information
/// Response in Bluetooth Core v4.0 spec.
AttFindInformationResponse(AttFindInformationResponse),
/// This event is generated in response to a Find By Type Value Request.
AttFindByTypeValueResponse(AttFindByTypeValueResponse),
/// This event is generated in response to a Read by Type Request.
AttReadByTypeResponse(AttReadByTypeResponse),
/// This event is generated in response to a Read Request.
AttReadResponse(AttReadResponse),
/// This event is generated in response to a Read Blob Request. The value in the response is the
/// partial value starting from the offset in the request. See the Bluetooth Core v4.1 spec, Vol
/// 3, section 3.4.4.5 and 3.4.4.6.
AttReadBlobResponse(AttReadResponse),
/// This event is generated in response to a Read Multiple Request. The value in the response is
/// the set of values requested from the request. See the Bluetooth Core v4.1 spec, Vol 3,
/// section 3.4.4.7 and 3.4.4.8.
AttReadMultipleResponse(AttReadResponse),
/// This event is generated in response to a Read By Group Type Request. See the Bluetooth Core
/// v4.1 spec, Vol 3, section 3.4.4.9 and 3.4.4.10.
AttReadByGroupTypeResponse(AttReadByGroupTypeResponse),
/// This event is generated in response to a Prepare Write Request. See the Bluetooth Core v4.1
/// spec, Vol 3, Part F, section 3.4.6.1 and 3.4.6.2
AttPrepareWriteResponse(AttPrepareWriteResponse),
/// This event is generated in response to an Execute Write Request. See the Bluetooth Core v4.1
/// spec, Vol 3, Part F, section 3.4.6.3 and 3.4.6.4
AttExecuteWriteResponse(ConnectionHandle),
/// This event is generated when an indication is received from the server.
GattIndication(AttributeValue),
/// This event is generated when an notification is received from the server.
GattNotification(AttributeValue),
/// This event is generated when a GATT client procedure completes either with error or
/// successfully.
GattProcedureComplete(GattProcedureComplete),
/// This event is generated when an Error Response is received from the server. The error
/// response can be given by the server at the end of one of the GATT discovery procedures. This
/// does not mean that the procedure ended with an error, but this error event is part of the
/// procedure itself.
AttErrorResponse(AttErrorResponse),
/// This event can be generated during a "Discover Characteristics by UUID" procedure or a "Read
/// using Characteristic UUID" procedure. The attribute value will be a service declaration as
/// defined in Bluetooth Core v4.0 spec, Vol 3, Part G, section 3.3.1), when a "Discover
/// Characteristics By UUID" has been started. It will be the value of the Characteristic if a
/// "Read using Characteristic UUID" has been performed.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part G, section 4.6.2 (discover characteristics by
/// UUID), and section 4.8.2 (read using characteristic using UUID).
GattDiscoverOrReadCharacteristicByUuidResponse(AttributeValue),
/// This event is given to the application when a write request, write command or signed write
/// command is received by the server from the client. This event will be given to the
/// application only if the event bit for this event generation is set when the characteristic
/// was added. When this event is received, the application has to check whether the value being
/// requested for write is allowed to be written and respond with a GATT Write Response. If the
/// write is rejected by the application, then the value of the attribute will not be
/// modified. In case of a write request, an error response will be sent to the client, with the
/// error code as specified by the application. In case of write/signed write commands, no
/// response is sent to the client but the attribute is not modified.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.5.
AttWritePermitRequest(AttributeValue),
/// This event is given to the application when a read request or read blob request is received
/// by the server from the client. This event will be given to the application only if the event
/// bit for this event generation is set when the characteristic was added. On receiving this
/// event, the application can update the value of the handle if it desires and when done it has
/// to use the [`allow_read`](crate::gatt::Commands::allow_read) command to indicate to the
/// stack that it can send the response to the client.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
AttReadPermitRequest(AttReadPermitRequest),
/// This event is given to the application when a read multiple request or read by type request
/// is received by the server from the client. This event will be given to the application only
/// if the event bit for this event generation is set when the characteristic was added. On
/// receiving this event, the application can update the values of the handles if it desires and
/// when done it has to send the [`allow_read`](crate::gatt::Commands::allow_read) command to
/// indicate to the stack that it can send the response to the client.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
AttReadMultiplePermitRequest(AttReadMultiplePermitRequest),
/// This event is raised when the number of available TX buffers is above a threshold TH (TH =
/// 2). The event will be given only if a previous ACI command returned with
/// [InsufficientResources](AttError::InsufficientResources). On receiving this event, the
/// application can continue to send notifications by calling `gatt_update_char_value`.
GattTxPoolAvailable(GattTxPoolAvailable),
/// This event is raised on the server when the client confirms the reception of an indication.
GattServerConfirmation(ConnectionHandle),
/// This event is given to the application when a prepare write request is received by the
/// server from the client. This event will be given to the application only if the event bit
/// for this event generation is set when the characteristic was added. When this event is
/// received, the application has to check whether the value being requested for write is
/// allowed to be written and respond with the command `gatt_write_response`. Based on the
/// response from the application, the attribute value will be modified by the stack. If the
/// write is rejected by the application, then the value of the attribute will not be modified
/// and an error response will be sent to the client, with the error code as specified by the
/// application.
AttPrepareWritePermitRequest(AttPrepareWritePermitRequest),
}
/// Enumeration of vendor-specific status codes.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Status {
/// The command cannot be executed due to the current state of the device.
Failed = 0x41,
/// Some parameters are invalid.
InvalidParameters = 0x42,
/// It is not allowed to start the procedure (e.g. another the procedure is ongoing or cannot be
/// started on the given handle).
NotAllowed = 0x46,
/// Unexpected error.
Error = 0x47,
/// The address was not resolved.
AddressNotResolved = 0x48,
/// Failed to read from flash.
FlashReadFailed = 0x49,
/// Failed to write to flash.
FlashWriteFailed = 0x4A,
/// Failed to erase flash.
FlashEraseFailed = 0x4B,
/// Invalid CID
InvalidCid = 0x50,
/// Timer is not valid
TimerNotValidLayer = 0x54,
/// Insufficient resources to create the timer
TimerInsufficientResources = 0x55,
/// Connection signature resolving key (CSRK) is not found.
CsrkNotFound = 0x5A,
/// Identity resolving key (IRK) is not found
IrkNotFound = 0x5B,
/// The device is not in the security database.
DeviceNotFoundInDatabase = 0x5C,
/// The security database is full.
SecurityDatabaseFull = 0x5D,
/// The device is not bonded.
DeviceNotBonded = 0x5E,
/// The device is blacklisted.
DeviceInBlacklist = 0x5F,
/// The handle (service, characteristic, or descriptor) is invalid.
InvalidHandle = 0x60,
/// A parameter is invalid
InvalidParameter = 0x61,
/// The characteristic handle is not part of the service.
OutOfHandle = 0x62,
/// The operation is invalid
InvalidOperation = 0x63,
/// Insufficient resources to complete the operation.
InsufficientResources = 0x64,
/// The encryption key size is too small
InsufficientEncryptionKeySize = 0x65,
/// The characteristic already exists.
CharacteristicAlreadyExists = 0x66,
/// Returned when no valid slots are available (e.g. when there are no available state
/// machines).
NoValidSlot = 0x82,
/// Returned when a scan window shorter than minimum allowed value has been requested
/// (i.e. 2ms). The Rust API should prevent this error from occurring.
ScanWindowTooShort = 0x83,
/// Returned when the maximum requested interval to be allocated is shorter then the current
/// anchor period and a there is no submultiple for the current anchor period that is between
/// the minimum and the maximum requested intervals.
NewIntervalFailed = 0x84,
/// Returned when the maximum requested interval to be allocated is greater than the current
/// anchor period and there is no multiple of the anchor period that is between the minimum and
/// the maximum requested intervals.
IntervalTooLarge = 0x85,
/// Returned when the current anchor period or a new one can be found that is compatible to the
/// interval range requested by the new slot but the maximum available length that can be
/// allocated is less than the minimum requested slot length.
LengthFailed = 0x86,
/// MCU Library timed out.
Timeout = 0xFF,
/// MCU library: profile already initialized.
ProfileAlreadyInitialized = 0xF0,
/// MCU library: A parameter was null.
NullParameter = 0xF1,
}
impl TryFrom<u8> for Status {
type Error = crate::BadStatusError;
fn try_from(value: u8) -> Result<Self, <Self as TryFrom<u8>>::Error> {
match value {
0x41 => Ok(Status::Failed),
0x42 => Ok(Status::InvalidParameters),
0x46 => Ok(Status::NotAllowed),
0x47 => Ok(Status::Error),
0x48 => Ok(Status::AddressNotResolved),
0x49 => Ok(Status::FlashReadFailed),
0x4A => Ok(Status::FlashWriteFailed),
0x4B => Ok(Status::FlashEraseFailed),
0x50 => Ok(Status::InvalidCid),
0x54 => Ok(Status::TimerNotValidLayer),
0x55 => Ok(Status::TimerInsufficientResources),
0x5A => Ok(Status::CsrkNotFound),
0x5B => Ok(Status::IrkNotFound),
0x5C => Ok(Status::DeviceNotFoundInDatabase),
0x5D => Ok(Status::SecurityDatabaseFull),
0x5E => Ok(Status::DeviceNotBonded),
0x5F => Ok(Status::DeviceInBlacklist),
0x60 => Ok(Status::InvalidHandle),
0x61 => Ok(Status::InvalidParameter),
0x62 => Ok(Status::OutOfHandle),
0x63 => Ok(Status::InvalidOperation),
0x64 => Ok(Status::InsufficientResources),
0x65 => Ok(Status::InsufficientEncryptionKeySize),
0x66 => Ok(Status::CharacteristicAlreadyExists),
0x82 => Ok(Status::NoValidSlot),
0x83 => Ok(Status::ScanWindowTooShort),
0x84 => Ok(Status::NewIntervalFailed),
0x85 => Ok(Status::IntervalTooLarge),
0x86 => Ok(Status::LengthFailed),
0xFF => Ok(Status::Timeout),
0xF0 => Ok(Status::ProfileAlreadyInitialized),
0xF1 => Ok(Status::NullParameter),
_ => Err(crate::BadStatusError::BadValue(value)),
}
}
}
impl From<Status> for u8 {
fn from(val: Status) -> Self {
val as u8
}
}
/// Enumeration of potential errors when sending commands or deserializing events.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Stm32Wb5xError {
/// The event is not recognized. Includes the unknown opcode.
UnknownEvent(u16),
/// For the [CoprocessorReady](Stm32Wb5xEvent::CoprocessorReady) event: the kind of firmware
/// running on radio coprocessor is not recognized.
UnknownFirmwareKind(u8),
/// For the [GAP Pairing Complete](Stm32Wb5xEvent::GapPairingComplete) event: The status was not
/// recognized. Includes the unrecognized byte.
BadGapPairingStatus(u8),
/// For the [GAP Device Found](Stm32Wb5xEvent::GapDeviceFound) event: the type of event was not
/// recognized. Includes the unrecognized byte.
BadGapDeviceFoundEvent(u8),
/// For the [GAP Device Found](Stm32Wb5xEvent::GapDeviceFound) event: the type of BDADDR was not
/// recognized. Includes the unrecognized byte.
BadGapBdAddrType(u8),
/// For the [GAP Procedure Complete](Stm32Wb5xEvent::GapProcedureComplete) event: The procedure
/// code was not recognized. Includes the unrecognized byte.
BadGapProcedure(u8),
/// For the [GAP Procedure Complete](Stm32Wb5xEvent::GapProcedureComplete) event: The procedure
/// status was not recognized. Includes the unrecognized byte.
BadGapProcedureStatus(u8),
/// For any L2CAP event: The event data length did not match the expected length. The first
/// field is the required length, and the second is the actual length.
BadL2CapDataLength(u8, u8),
/// For any L2CAP event: The L2CAP length did not match the expected length. The first field is
/// the required length, and the second is the actual length.
BadL2CapLength(u16, u16),
/// For any L2CAP response event: The L2CAP command was rejected, but the rejection reason was
/// not recognized. Includes the unknown value.
BadL2CapRejectionReason(u16),
/// For the [L2CAP Connection Update Response](Stm32Wb5xEvent::L2CapConnectionUpdateResponse)
/// event: The code byte did not indicate either Rejected or Updated. Includes the invalid byte.
BadL2CapConnectionResponseCode(u8),
/// For the [L2CAP Connection Update Response](Stm32Wb5xEvent::L2CapConnectionUpdateResponse)
/// event: The command was accepted, but the result was not recognized. It did not indicate the
/// parameters were either updated or rejected. Includes the unknown value.
BadL2CapConnectionResponseResult(u16),
/// For the [L2CAP Connection Update Request](Stm32Wb5xEvent::L2CapConnectionUpdateRequest) event:
/// The provided connection interval is invalid. Includes the underlying error.
BadConnectionInterval(ConnectionIntervalError),
/// For the [L2CAP Connection Update Request](Stm32Wb5xEvent::L2CapConnectionUpdateRequest) event:
/// The provided interval is invalid. Potential errors:
/// - Either the minimum or maximum is out of range. The minimum value for either is 7.5 ms, and
/// the maximum is 4 s.
/// - The min is greater than the max
///
/// See the Bluetooth specification, Vol 3, Part A, Section 4.20. Versions 4.1, 4.2 and 5.0.
///
/// Inclues the provided minimum and maximum, respectively.
BadL2CapConnectionUpdateRequestInterval(Duration, Duration),
/// For the [L2CAP Connection Update Request](Stm32Wb5xEvent::L2CapConnectionUpdateRequest) event:
/// The provided connection latency is invalid. The maximum value for connection latency is
/// defined in terms of the timeout and maximum connection interval.
/// - `connIntervalMax = Interval Max`
/// - `connSupervisionTimeout = Timeout`
/// - `maxConnLatency = min(500, ((connSupervisionTimeout / (2 * connIntervalMax)) - 1))`
///
/// See the Bluetooth specification, Vol 3, Part A, Section 4.20. Versions 4.1, 4.2 and 5.0.
///
/// Inclues the provided value and maximum allowed value, respectively.
BadL2CapConnectionUpdateRequestLatency(u16, u16),
/// For the [L2CAP Connection Update Request](Stm32Wb5xEvent::L2CapConnectionUpdateRequest) event:
/// The provided timeout is invalid. The timeout field shall have a value in the range of 100 ms
/// to 32 seconds (inclusive).
///
/// See the Bluetooth specification, Vol 3, Part A, Section 4.20. Versions 4.1, 4.2 and 5.0.
///
/// Inclues the provided value.
BadL2CapConnectionUpdateRequestTimeout(Duration),
/// For the [ATT Find Information Response](Stm32Wb5xEvent::AttFindInformationResponse) event: The
/// format code is invalid. Includes the unrecognized byte.
BadAttFindInformationResponseFormat(u8),
/// For the [ATT Find Information Response](Stm32Wb5xEvent::AttFindInformationResponse) event: The
/// format code indicated 16-bit UUIDs, but the packet ends with a partial pair.
AttFindInformationResponsePartialPair16,
/// For the [ATT Find Information Response](Stm32Wb5xEvent::AttFindInformationResponse) event: The
/// format code indicated 128-bit UUIDs, but the packet ends with a partial pair.
AttFindInformationResponsePartialPair128,
/// For the [ATT Find by Type Value Response](Stm32Wb5xEvent::AttFindByTypeValueResponse) event:
/// The packet ends with a partial attribute pair.
AttFindByTypeValuePartial,
/// For the [ATT Read by Type Response](Stm32Wb5xEvent::AttReadByTypeResponse) event: The packet
/// ends with a partial attribute handle-value pair.
AttReadByTypeResponsePartial,
/// For the [ATT Read by Group Type Response](Stm32Wb5xEvent::AttReadByGroupTypeResponse) event:
/// The packet ends with a partial attribute data group.
AttReadByGroupTypeResponsePartial,
/// For the [GATT Procedure Complete](Stm32Wb5xEvent::GattProcedureComplete) event: The status
/// code was not recognized. Includes the unrecognized byte.
BadGattProcedureStatus(u8),
/// For the [ATT Error Response](Stm32Wb5xEvent::AttErrorResponse) event: The request opcode was
/// not recognized. Includes the unrecognized byte.
BadAttRequestOpcode(u8),
/// For the [ATT Error Response](Stm32Wb5xEvent::AttErrorResponse) event: The error code was not
/// recognized. Includes the unrecognized byte.
BadAttError(u8),
/// For the [ATT Read Multiple Permit Request](Stm32Wb5xEvent::AttReadMultiplePermitRequest)
/// event: The packet ends with a partial attribute handle.
AttReadMultiplePermitRequestPartial,
/// For the [HAL Read Config Data](crate::hal::Commands::read_config_data) command complete
/// [event](command::ReturnParameters::HalReadConfigData): The returned value has a length that
/// does not correspond to a requested parameter. Known lengths are 1, 2, 6, or 16. Includes the
/// number of bytes returned.
BadConfigParameterLength(usize),
/// For the [HAL Get Link Status](crate::hal::Commands::get_link_status) command complete
/// [event](command::ReturnParameters::HalGetLinkStatus): One of the bytes representing a link
/// state does not represent a known link state. Returns the unknown value.
UnknownLinkState(u8),
/// For the [GAP Get Security Level](crate::gap::Commands::get_security_level) command complete
/// [event](command::ReturnParameters::GapGetSecurityLevel): One of the boolean values
/// ([`mitm_protection_required`](command::GapSecurityLevel::mitm_protection_required),
/// [`bonding_required`](command::GapSecurityLevel::bonding_required), or
/// [`out_of_band_data_present`](command::GapSecurityLevel::out_of_band_data_present)) was
/// neither 0 nor 1. The unknown value is provided.
BadBooleanValue(u8),
/// For the [GAP Get Security Level](crate::gap::Commands::get_security_level) command complete
/// [event](command::ReturnParameters::GapGetSecurityLevel): the pass key requirement field was
/// an invalid value. The unknown byte is provided.
BadPassKeyRequirement(u8),
/// For the [GAP Get Bonded Devices](crate::gap::Commands::get_bonded_devices) command complete
/// [event](command::ReturnParameters::GapGetBondedDevices): the packat was not long enough to
/// contain the number of addresses it claimed to contain.
PartialBondedDeviceAddress,
/// For the [GAP Get Bonded Devices](crate::gap::Commands::get_bonded_devices) command complete
/// [event](command::ReturnParameters::GapGetBondedDevices): one of the address type bytes was
/// invalid. Includes the invalid byte.
BadBdAddrType(u8),
}
macro_rules! require_len {
($left:expr, $right:expr) => {
if $left.len() != $right {
return Err(crate::event::Error::BadLength($left.len(), $right));
}
};
}
macro_rules! require_len_at_least {
($left:expr, $right:expr) => {
if $left.len() < $right {
return Err(crate::event::Error::BadLength($left.len(), $right));
}
};
}
fn first_16<T>(buffer: &[T]) -> &[T] {
if buffer.len() < 16 {
buffer
} else {
&buffer[..16]
}
}
impl crate::event::VendorEvent for Stm32Wb5xEvent {
type Error = Stm32Wb5xError;
type Status = Status;
type ReturnParameters = command::ReturnParameters;
fn new(buffer: &[u8]) -> Result<Self, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 2);
let event_code = LittleEndian::read_u16(&buffer[0..=1]);
match event_code {
// SHCI "C2 Ready" event
0x9200 => Ok(Stm32Wb5xEvent::CoprocessorReady(to_coprocessor_ready(
buffer,
)?)),
0x0400 => Ok(Stm32Wb5xEvent::GapLimitedDiscoverableTimeout),
0x0401 => Ok(Stm32Wb5xEvent::GapPairingComplete(to_gap_pairing_complete(
buffer,
)?)),
0x0402 => Ok(Stm32Wb5xEvent::GapPassKeyRequest(to_conn_handle(buffer)?)),
0x0403 => Ok(Stm32Wb5xEvent::GapAuthorizationRequest(to_conn_handle(
buffer,
)?)),
0x0404 => Ok(Stm32Wb5xEvent::GapPeripheralSecurityInitiated),
0x0405 => Ok(Stm32Wb5xEvent::GapBondLost),
0x0406 => Ok(Stm32Wb5xEvent::GapDeviceFound(to_gap_device_found(buffer)?)),
0x0407 => Ok(Stm32Wb5xEvent::GapProcedureComplete(
to_gap_procedure_complete(buffer)?,
)),
0x0408 => Ok(Stm32Wb5xEvent::GapAddressNotResolved(to_conn_handle(
buffer,
)?)),
0x0409 => Ok(Stm32Wb5xEvent::NumericComparisonValue(
to_numeric_comparison_value(buffer)?,
)),
0x040A => Ok(Stm32Wb5xEvent::KeypressNotification(
to_keypress_notification(buffer)?,
)),
0x0800 => Ok(Stm32Wb5xEvent::L2CapConnectionUpdateResponse(
to_l2cap_connection_update_response(buffer)?,
)),
0x0801 => Ok(Stm32Wb5xEvent::L2CapProcedureTimeout(
to_l2cap_procedure_timeout(buffer)?,
)),
0x0802 => Ok(Stm32Wb5xEvent::L2CapConnectionUpdateRequest(
to_l2cap_connection_update_request(buffer)?,
)),
0x080A => Ok(Stm32Wb5xEvent::L2CapCommandReject(to_l2cap_command_reject(
buffer,
)?)),
0x0810 => todo!(),
0x0811 => todo!(),
0x0812 => todo!(),
0x0813 => todo!(),
0x0814 => todo!(),
0x0815 => todo!(),
0x0816 => todo!(),
0x0817 => todo!(),
0x0C01 => Ok(Stm32Wb5xEvent::GattAttributeModified(
to_gatt_attribute_modified(buffer)?,
)),
0x0C02 => Ok(Stm32Wb5xEvent::GattProcedureTimeout(to_conn_handle(
buffer,
)?)),
0x0C03 => Ok(Stm32Wb5xEvent::AttExchangeMtuResponse(
to_att_exchange_mtu_resp(buffer)?,
)),
0x0C04 => Ok(Stm32Wb5xEvent::AttFindInformationResponse(
to_att_find_information_response(buffer)?,
)),
0x0C05 => Ok(Stm32Wb5xEvent::AttFindByTypeValueResponse(
to_att_find_by_value_type_response(buffer)?,
)),
0x0C06 => Ok(Stm32Wb5xEvent::AttReadByTypeResponse(
to_att_read_by_type_response(buffer)?,
)),
0x0C07 => Ok(Stm32Wb5xEvent::AttReadResponse(to_att_read_response(
buffer,
)?)),
0x0C08 => Ok(Stm32Wb5xEvent::AttReadBlobResponse(to_att_read_response(
buffer,
)?)),
0x0C09 => Ok(Stm32Wb5xEvent::AttReadMultipleResponse(
to_att_read_response(buffer)?,
)),
0x0C0A => Ok(Stm32Wb5xEvent::AttReadByGroupTypeResponse(
to_att_read_by_group_type_response(buffer)?,
)),
0x0C0C => Ok(Stm32Wb5xEvent::AttPrepareWriteResponse(
to_att_prepare_write_response(buffer)?,
)),
0x0C0D => Ok(Stm32Wb5xEvent::AttExecuteWriteResponse(to_conn_handle(
buffer,
)?)),
0x0C0E => Ok(Stm32Wb5xEvent::GattIndication(to_attribute_value(buffer)?)),
0x0C0F => Ok(Stm32Wb5xEvent::GattNotification(to_attribute_value(
buffer,
)?)),
0x0C10 => Ok(Stm32Wb5xEvent::GattProcedureComplete(
to_gatt_procedure_complete(buffer)?,
)),
0x0C11 => Ok(Stm32Wb5xEvent::AttErrorResponse(to_att_error_response(
buffer,
)?)),
0x0C12 => Ok(
Stm32Wb5xEvent::GattDiscoverOrReadCharacteristicByUuidResponse(to_attribute_value(
buffer,
)?),
),
0x0C13 => Ok(Stm32Wb5xEvent::AttWritePermitRequest(
to_write_permit_request(buffer)?,
)),
0x0C14 => Ok(Stm32Wb5xEvent::AttReadPermitRequest(
to_att_read_permit_request(buffer)?,
)),
0x0C15 => Ok(Stm32Wb5xEvent::AttReadMultiplePermitRequest(
to_att_read_multiple_permit_request(buffer)?,
)),
0x0C16 => Ok(Stm32Wb5xEvent::GattTxPoolAvailable(
to_gatt_tx_pool_available(buffer)?,
)),
0x0C17 => Ok(Stm32Wb5xEvent::GattServerConfirmation(to_conn_handle(
buffer,
)?)),
0x0C18 => Ok(Stm32Wb5xEvent::AttPrepareWritePermitRequest(
to_att_prepare_write_permit_request(buffer)?,
)),
0x0C19 => todo!(),
0x0C1A => todo!(),
0x0C1D => todo!(),
0x0C1E => todo!(),
0x0C1F => todo!(),
_ => Err(crate::event::Error::Vendor(Stm32Wb5xError::UnknownEvent(
event_code,
))),
}
}
}
/// Potential firmware kinds for [`CoprocessorReady`](Stm32Wb5xEvent::CoprocessorReady)
/// event.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FirmwareKind {
/// Wireless firmware (BLE, Thread, etc.)
Wireless,
/// RCC firmware.
Rcc,
}
impl TryFrom<u8> for FirmwareKind {
type Error = Stm32Wb5xError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(FirmwareKind::Wireless),
1 => Ok(FirmwareKind::Rcc),
_ => Err(Stm32Wb5xError::UnknownFirmwareKind(value)),
}
}
}
/// Convert a buffer to the `CoprocessorReady` `Stm32Wb5xEvent`.
///
/// # Errors
///
/// - Returns a `BadLength` HCI error if the buffer is not exactly 3 bytes long
/// - Returns a `UnknownFirmwareKind` CPU2 error if the firmware kind is not recognized.
fn to_coprocessor_ready(
buffer: &[u8],
) -> Result<FirmwareKind, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 3);
buffer[0].try_into().map_err(crate::event::Error::Vendor)
}
macro_rules! require_l2cap_event_data_len {
($left:expr, $right:expr) => {
let actual = $left[4];
if actual != $right {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::BadL2CapDataLength(actual, $right),
));
}
};
}
macro_rules! require_l2cap_len {
($actual:expr, $expected:expr) => {
if $actual != $expected {
return Err(crate::event::Error::Vendor(Stm32Wb5xError::BadL2CapLength(
$actual, $expected,
)));
}
};
}
/// This event is generated when the central device responds to the L2CAP connection update request
/// packet.
///
/// For more info see connection parameter update response and command reject in Bluetooth Core v4.0
/// spec.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct L2CapConnectionUpdateResponse {
/// The connection handle related to the event
pub conn_handle: ConnectionHandle,
/// The result of the update request, including details about the result.
pub result: L2CapConnectionUpdateResult,
}
/// Reasons why an L2CAP command was rejected. see the Bluetooth specification, v4.1, Vol 3, Part A,
/// Section 4.1.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum L2CapRejectionReason {
/// The controller sent an unknown command.
CommandNotUnderstood,
/// When multiple commands are included in an L2CAP packet and the packet exceeds the signaling
/// MTU (MTUsig) of the receiver, a single Command Reject packet shall be sent in response.
SignalingMtuExceeded,
/// Invalid CID in request
InvalidCid,
}
impl TryFrom<u16> for L2CapRejectionReason {
type Error = Stm32Wb5xError;
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
0 => Ok(L2CapRejectionReason::CommandNotUnderstood),
1 => Ok(L2CapRejectionReason::SignalingMtuExceeded),
2 => Ok(L2CapRejectionReason::InvalidCid),
_ => Err(Stm32Wb5xError::BadL2CapRejectionReason(value)),
}
}
}
/// Potential results that can be used in the L2CAP connection update response.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum L2CapConnectionUpdateResult {
/// The update request was rejected. The code indicates the reason for the rejection.
CommandRejected(L2CapRejectionReason),
/// The L2CAP connection update response is valid. The code indicates if the parameters were
/// rejected.
ParametersRejected,
/// The L2CAP connection update response is valid. The code indicates if the parameters were
/// updated.
ParametersUpdated,
}
fn to_l2cap_connection_update_accepted_result(
value: u16,
) -> Result<L2CapConnectionUpdateResult, Stm32Wb5xError> {
match value {
0x0000 => Ok(L2CapConnectionUpdateResult::ParametersUpdated),
0x0001 => Ok(L2CapConnectionUpdateResult::ParametersRejected),
_ => Err(Stm32Wb5xError::BadL2CapConnectionResponseResult(value)),
}
}
fn extract_l2cap_connection_update_response_result(
buffer: &[u8],
) -> Result<L2CapConnectionUpdateResult, Stm32Wb5xError> {
match buffer[5] {
0x01 => Ok(L2CapConnectionUpdateResult::CommandRejected(
LittleEndian::read_u16(&buffer[9..]).try_into()?,
)),
0x13 => to_l2cap_connection_update_accepted_result(LittleEndian::read_u16(&buffer[9..])),
_ => Err(Stm32Wb5xError::BadL2CapConnectionResponseCode(buffer[5])),
}
}
fn to_l2cap_connection_update_response(
buffer: &[u8],
) -> Result<L2CapConnectionUpdateResponse, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 11);
require_l2cap_event_data_len!(buffer, 6);
require_l2cap_len!(LittleEndian::read_u16(&buffer[7..]), 2);
Ok(L2CapConnectionUpdateResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
result: extract_l2cap_connection_update_response_result(buffer)
.map_err(crate::event::Error::Vendor)?,
})
}
/// This event is generated when the central device does not respond to the connection update
/// request within 30 seconds.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct L2CapProcedureTimeout {
/// The connection handle related to the event.
pub conn_handle: ConnectionHandle,
}
fn to_l2cap_procedure_timeout(
buffer: &[u8],
) -> Result<ConnectionHandle, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 5);
require_l2cap_event_data_len!(buffer, 0);
Ok(ConnectionHandle(LittleEndian::read_u16(&buffer[2..])))
}
/// The event is given by the L2CAP layer when a connection update request is received from the
/// peripheral.
///
/// The application has to respond by calling
/// [`l2cap_connection_parameter_update_response`](crate::l2cap::Commands::connection_parameter_update_response).
///
/// Defined in Vol 3, Part A, section 4.20 of the Bluetooth specification.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct L2CapConnectionUpdateRequest {
/// Handle of the connection for which the connection update request has been received. The
/// [same handle](crate::l2cap::ConnectionParameterUpdateResponse::conn_handle) has to be
/// returned while responding to the event with the command
/// [`l2cap_connection_parameter_update_response`](crate::l2cap::Commands::connection_parameter_update_response).
pub conn_handle: ConnectionHandle,
/// This is the identifier which associates the request to the response. The [same
/// identifier](crate::l2cap::ConnectionParameterUpdateResponse::identifier) has to be returned
/// by the upper layer in the command
/// [`l2cap_connection_parameter_update_response`](crate::l2cap::Commands::connection_parameter_update_response).
pub identifier: u8,
/// Defines the range of the connection interval, the latency, and the supervision timeout.
pub conn_interval: ConnectionInterval,
}
fn to_l2cap_connection_update_request(
buffer: &[u8],
) -> Result<L2CapConnectionUpdateRequest, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 16);
require_l2cap_event_data_len!(buffer, 11);
require_l2cap_len!(LittleEndian::read_u16(&buffer[6..]), 8);
let interval = ConnectionInterval::from_bytes(&buffer[8..16])
.map_err(Stm32Wb5xError::BadConnectionInterval)
.map_err(crate::event::Error::Vendor)?;
Ok(L2CapConnectionUpdateRequest {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
identifier: buffer[5],
conn_interval: interval,
})
}
/// This event is generated when the pairing process has completed successfully or a pairing
/// procedure timeout has occurred or the pairing has failed. This is to notify the application that
/// we have paired with a remote device so that it can take further actions or to notify that a
/// timeout has occurred so that the upper layer can decide to disconnect the link.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GapPairingComplete {
/// Connection handle on which the pairing procedure completed
pub conn_handle: ConnectionHandle,
/// Reason the pairing is complete.
pub status: GapPairingStatus,
}
/// Reasons the [GAP Pairing Complete](Stm32Wb5xEvent::GapPairingComplete) event was generated.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum GapPairingStatus {
/// Pairing with a remote device was successful.
Success,
/// The SMP timeout has elapsed and no further SMP commands will be processed until
/// reconnection.
Timeout,
/// The pairing failed with the remote device.
Failed,
}
impl TryFrom<u8> for GapPairingStatus {
type Error = Stm32Wb5xError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(GapPairingStatus::Success),
1 => Ok(GapPairingStatus::Timeout),
2 => Ok(GapPairingStatus::Failed),
_ => Err(Stm32Wb5xError::BadGapPairingStatus(value)),
}
}
}
fn to_gap_pairing_complete(
buffer: &[u8],
) -> Result<GapPairingComplete, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 6);
Ok(GapPairingComplete {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
status: buffer[4].try_into().map_err(crate::event::Error::Vendor)?,
})
}
fn to_conn_handle(buffer: &[u8]) -> Result<ConnectionHandle, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 4);
Ok(ConnectionHandle(LittleEndian::read_u16(&buffer[2..])))
}
/// The event is given by the GAP layer to the upper layers when a device is discovered during
/// scanning as a consequence of one of the GAP procedures started by the upper layers.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GapDeviceFound {
/// Type of event
pub event: GapDeviceFoundEvent,
/// Address of the peer device found during scanning
pub bdaddr: BdAddrType,
// Length of significant data
data_len: usize,
// Advertising or scan response data.
data_buf: [u8; 31],
/// Received signal strength indicator (range: -127 - 20).
pub rssi: Option<i8>,
}
impl GapDeviceFound {
/// Returns the valid scan response data.
pub fn data(&self) -> &[u8] {
&self.data_buf[..self.data_len]
}
}
pub use crate::event::AdvertisementEvent as GapDeviceFoundEvent;
use super::command::gap::EventFlags;
fn to_gap_device_found(
buffer: &[u8],
) -> Result<GapDeviceFound, crate::event::Error<Stm32Wb5xError>> {
const RSSI_UNAVAILABLE: i8 = 127;
require_len_at_least!(buffer, 12);
let data_len = buffer[10] as usize;
require_len!(buffer, 12 + data_len);
let rssi = unsafe { mem::transmute::<u8, i8>(buffer[buffer.len() - 1]) };
let mut addr = BdAddr([0; 6]);
addr.0.copy_from_slice(&buffer[4..10]);
let mut event = GapDeviceFound {
event: buffer[2].try_into().map_err(|e| {
if let crate::event::Error::BadLeAdvertisementType(code) = e {
crate::event::Error::Vendor(Stm32Wb5xError::BadGapDeviceFoundEvent(code))
} else {
unreachable!()
}
})?,
bdaddr: crate::to_bd_addr_type(buffer[3], addr)
.map_err(|e| crate::event::Error::Vendor(Stm32Wb5xError::BadGapBdAddrType(e.0)))?,
data_len,
data_buf: [0; 31],
rssi: if rssi == RSSI_UNAVAILABLE {
None
} else {
Some(rssi)
},
};
event.data_buf[..event.data_len].copy_from_slice(&buffer[11..buffer.len() - 1]);
Ok(event)
}
/// This event is sent by the GAP to the upper layers when a procedure previously started has been
/// terminated by the upper layer or has completed for any other reason
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GapProcedureComplete {
/// Type of procedure that completed
pub procedure: GapProcedure,
/// Status of the procedure
pub status: GapProcedureStatus,
}
/// Maximum length of the name returned in the [`NameDiscovery`](GapProcedure::NameDiscovery)
/// procedure.
pub const MAX_NAME_LEN: usize = 248;
/// Newtype for the name buffer returned after successful
/// [`NameDiscovery`](GapProcedure::NameDiscovery).
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct NameBuffer(pub [u8; MAX_NAME_LEN]);
impl Debug for NameBuffer {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
first_16(&self.0).fmt(f)
}
}
impl PartialEq<NameBuffer> for NameBuffer {
fn eq(&self, other: &Self) -> bool {
if self.0.len() != other.0.len() {
return false;
}
for (a, b) in self.0.iter().zip(other.0.iter()) {
if a != b {
return false;
}
}
true
}
}
/// Procedures whose completion may be reported by
/// [`GapProcedureComplete`](Stm32Wb5xEvent::GapProcedureComplete).
#[allow(clippy::large_enum_variant)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum GapProcedure {
/// See Vol 3, Part C, section 9.2.5.
LimitedDiscovery,
/// See Vol 3, Part C, section 9.2.6.
GeneralDiscovery,
/// See Vol 3, Part C, section 9.2.7. Contains the number of valid bytes and buffer with enough
/// space for the maximum length of the name that can be retuned.
NameDiscovery(usize, NameBuffer),
/// See Vol 3, Part C, section 9.3.5.
AutoConnectionEstablishment,
/// See Vol 3, Part C, section 9.3.6. Contains the reconnection address.
GeneralConnectionEstablishment,
/// See Vol 3, Part C, section 9.3.7.
SelectiveConnectionEstablishment,
/// See Vol 3, Part C, section 9.3.8.
DirectConnectionEstablishment,
Observation,
}
/// Possible results of a [GAP procedure](Stm32Wb5xEvent::GapProcedureComplete).
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum GapProcedureStatus {
/// BLE Status Success.
Success,
/// BLE Status Failed.
Failed,
/// Procedure failed due to authentication requirements.
AuthFailure,
}
impl TryFrom<u8> for GapProcedureStatus {
type Error = Stm32Wb5xError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(GapProcedureStatus::Success),
0x41 => Ok(GapProcedureStatus::Failed),
0x05 => Ok(GapProcedureStatus::AuthFailure),
_ => Err(Stm32Wb5xError::BadGapProcedureStatus(value)),
}
}
}
fn to_gap_procedure_complete(
buffer: &[u8],
) -> Result<GapProcedureComplete, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 4);
let procedure = match buffer[2] {
0x01 => GapProcedure::LimitedDiscovery,
0x02 => GapProcedure::GeneralDiscovery,
0x04 => {
require_len_at_least!(buffer, 5);
let name_len = buffer.len() - 4;
let mut name = NameBuffer([0; MAX_NAME_LEN]);
name.0[..name_len].copy_from_slice(&buffer[4..]);
GapProcedure::NameDiscovery(name_len, name)
}
0x08 => GapProcedure::AutoConnectionEstablishment,
0x10 => GapProcedure::GeneralConnectionEstablishment,
0x20 => GapProcedure::SelectiveConnectionEstablishment,
0x40 => GapProcedure::DirectConnectionEstablishment,
0x80 => GapProcedure::Observation,
_ => {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::BadGapProcedure(buffer[2]),
));
}
};
Ok(GapProcedureComplete {
procedure,
status: buffer[3].try_into().map_err(crate::event::Error::Vendor)?,
})
}
/// This event is generated to the application by the ATT server when a client modifies any
/// attribute on the server, as consequence of one of the following ATT procedures:
/// - write without response
/// - signed write without response
/// - write characteristic value
/// - write long characteristic value
/// - reliable write
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GattAttributeModified {
/// The connection handle which modified the attribute
pub conn_handle: ConnectionHandle,
/// Handle of the attribute that was modified
pub attr_handle: AttributeHandle,
offset: u16,
/// Number of valid bytes in |data|.
data_len: usize,
/// The new attribute value, starting from the given offset. If compiling with "ms" support, the
/// offset is 0.
data_buf: [u8; MAX_ATTRIBUTE_LEN],
}
impl GattAttributeModified {
/// Returns the valid attribute data returned by the ATT attribute modified event as a slice of
/// bytes.
pub fn data(&self) -> &[u8] {
&self.data_buf[..self.data_len]
}
}
/// Newtype for an attribute handle. These handles are IDs, not general integers, and should not be
/// manipulated as such.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttributeHandle(pub u16);
// Defines the maximum length of a ATT attribute value field. This is determined by the max packet
// size (255) less the minimum number of bytes used by other fields in any packet.
const MAX_ATTRIBUTE_LEN: usize = 248;
impl Debug for GattAttributeModified {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.debug_struct("GattAttributeModified")
.field("conn_handle", &self.conn_handle)
.field("attr_handle", &self.attr_handle)
.field("offset", &self.offset)
.field("data", &first_16(self.data()))
.finish()
}
}
fn to_gatt_attribute_modified(
buffer: &[u8],
) -> Result<GattAttributeModified, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 10);
let data_len = LittleEndian::read_u16(&buffer[8..]) as usize;
require_len!(buffer, 10 + data_len);
let mut data = [0; MAX_ATTRIBUTE_LEN];
data[..data_len].copy_from_slice(&buffer[10..]);
let offset_field = LittleEndian::read_u16(&buffer[6..]);
Ok(GattAttributeModified {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
attr_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
offset: (offset_field & 0x7FFF),
data_len,
data_buf: data,
})
}
/// This event is generated in response to an Exchange MTU request.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttExchangeMtuResponse {
/// The connection handle related to the response.
pub conn_handle: ConnectionHandle,
/// Attribute server receive MTU size.
pub server_rx_mtu: usize,
}
fn to_att_exchange_mtu_resp(
buffer: &[u8],
) -> Result<AttExchangeMtuResponse, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 6);
Ok(AttExchangeMtuResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
server_rx_mtu: LittleEndian::read_u16(&buffer[4..]) as usize,
})
}
/// This event is generated in response to a Find Information Request. See Find Information Response
/// in Bluetooth Core v4.0 spec.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttFindInformationResponse {
/// The connection handle related to the response
pub conn_handle: ConnectionHandle,
/// The Find Information Response shall have complete handle-UUID pairs. Such pairs shall not be
/// split across response packets; this also implies that a handleUUID pair shall fit into a
/// single response packet. The handle-UUID pairs shall be returned in ascending order of
/// attribute handles.
handle_uuid_pairs: HandleUuidPairs,
}
impl AttFindInformationResponse {
/// The Find Information Response shall have complete handle-UUID pairs. Such pairs shall not be
/// split across response packets; this also implies that a handleUUID pair shall fit into a
/// single response packet. The handle-UUID pairs shall be returned in ascending order of
/// attribute handles.
pub fn handle_uuid_pair_iter(&self) -> HandleUuidPairIterator {
match self.handle_uuid_pairs {
HandleUuidPairs::Format16(count, ref data) => {
HandleUuidPairIterator::Format16(HandleUuid16PairIterator {
data,
count,
next_index: 0,
})
}
HandleUuidPairs::Format128(count, ref data) => {
HandleUuidPairIterator::Format128(HandleUuid128PairIterator {
data,
count,
next_index: 0,
})
}
}
}
}
// Assuming a maximum HCI packet size of 255, these are the maximum number of handle-UUID pairs for
// each format that can be in one packet. Formats cannot be mixed in a single packet.
//
// Packets have 6 other bytes of data preceding the handle-UUID pairs.
//
// max = floor((255 - 6) / pair_length)
const MAX_FORMAT16_PAIR_COUNT: usize = 62;
const MAX_FORMAT128_PAIR_COUNT: usize = 13;
/// One format of the handle-UUID pairs in the [`AttFindInformationResponse`] event. The UUIDs are
/// 16 bits.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleUuid16Pair {
/// Attribute handle
pub handle: AttributeHandle,
/// Attribute UUID
pub uuid: Uuid16,
}
/// One format of the handle-UUID pairs in the [`AttFindInformationResponse`] event. The UUIDs are
/// 128 bits.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleUuid128Pair {
/// Attribute handle
pub handle: AttributeHandle,
/// Attribute UUID
pub uuid: Uuid128,
}
/// Newtype for the 16-bit UUID buffer.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Uuid16(pub u16);
/// Newtype for the 128-bit UUID buffer.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Uuid128(pub [u8; 16]);
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum HandleUuidPairs {
Format16(usize, [HandleUuid16Pair; MAX_FORMAT16_PAIR_COUNT]),
Format128(usize, [HandleUuid128Pair; MAX_FORMAT128_PAIR_COUNT]),
}
impl Debug for HandleUuidPairs {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{{")?;
match *self {
HandleUuidPairs::Format16(count, pairs) => {
for handle_uuid_pair in &pairs[..count] {
write!(
f,
"{{{:?}, {:?}}}",
handle_uuid_pair.handle, handle_uuid_pair.uuid
)?
}
}
HandleUuidPairs::Format128(count, pairs) => {
for handle_uuid_pair in &pairs[..count] {
write!(
f,
"{{{:?}, {:?}}}",
handle_uuid_pair.handle, handle_uuid_pair.uuid
)?
}
}
}
write!(f, "}}")
}
}
/// Possible iterators over handle-UUID pairs that can be returnedby the [ATT find information
/// response](AttFindInformationResponse). All pairs from the same event have the same format.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum HandleUuidPairIterator<'a> {
/// The event contains 16-bit UUIDs.
Format16(HandleUuid16PairIterator<'a>),
/// The event contains 128-bit UUIDs.
Format128(HandleUuid128PairIterator<'a>),
}
/// Iterator over handle-UUID pairs for 16-bit UUIDs.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleUuid16PairIterator<'a> {
data: &'a [HandleUuid16Pair; MAX_FORMAT16_PAIR_COUNT],
count: usize,
next_index: usize,
}
impl<'a> Iterator for HandleUuid16PairIterator<'a> {
type Item = HandleUuid16Pair;
fn next(&mut self) -> Option<Self::Item> {
if self.next_index >= self.count {
return None;
}
let index = self.next_index;
self.next_index += 1;
Some(self.data[index])
}
}
/// Iterator over handle-UUID pairs for 128-bit UUIDs.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleUuid128PairIterator<'a> {
data: &'a [HandleUuid128Pair; MAX_FORMAT128_PAIR_COUNT],
count: usize,
next_index: usize,
}
impl<'a> Iterator for HandleUuid128PairIterator<'a> {
type Item = HandleUuid128Pair;
fn next(&mut self) -> Option<Self::Item> {
if self.next_index >= self.count {
return None;
}
let index = self.next_index;
self.next_index += 1;
Some(self.data[index])
}
}
fn to_att_find_information_response(
buffer: &[u8],
) -> Result<AttFindInformationResponse, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 4);
let data_len = buffer[5] as usize;
require_len!(buffer, 6 + data_len);
Ok(AttFindInformationResponse {
conn_handle: to_conn_handle(buffer)?,
handle_uuid_pairs: match buffer[4] {
1 => to_handle_uuid16_pairs(&buffer[6..]).map_err(crate::event::Error::Vendor)?,
2 => to_handle_uuid128_pairs(&buffer[6..]).map_err(crate::event::Error::Vendor)?,
_ => {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::BadAttFindInformationResponseFormat(buffer[4]),
));
}
},
})
}
// [0x4, 0xc, 0x1, 0x8, 0x1, 0x8, 0x12, 0x0, 0x3, 0x5, 0x13, 0x0, 0x2, 0x29]
fn to_handle_uuid16_pairs(buffer: &[u8]) -> Result<HandleUuidPairs, Stm32Wb5xError> {
const PAIR_LEN: usize = 4;
if buffer.len() % PAIR_LEN != 0 {
return Err(Stm32Wb5xError::AttFindInformationResponsePartialPair16);
}
let count = buffer.len() / PAIR_LEN;
let mut pairs = [HandleUuid16Pair {
handle: AttributeHandle(0),
uuid: Uuid16(0),
}; MAX_FORMAT16_PAIR_COUNT];
for (i, pair) in pairs.iter_mut().enumerate().take(count) {
let index = i * PAIR_LEN;
pair.handle = AttributeHandle(LittleEndian::read_u16(&buffer[index..]));
pair.uuid = Uuid16(LittleEndian::read_u16(&buffer[2 + index..]));
}
Ok(HandleUuidPairs::Format16(count, pairs))
}
fn to_handle_uuid128_pairs(buffer: &[u8]) -> Result<HandleUuidPairs, Stm32Wb5xError> {
const PAIR_LEN: usize = 18;
if buffer.len() % PAIR_LEN != 0 {
return Err(Stm32Wb5xError::AttFindInformationResponsePartialPair128);
}
let count = buffer.len() / PAIR_LEN;
let mut pairs = [HandleUuid128Pair {
handle: AttributeHandle(0),
uuid: Uuid128([0; 16]),
}; MAX_FORMAT128_PAIR_COUNT];
for (i, pair) in pairs.iter_mut().enumerate().take(count) {
let index = i * PAIR_LEN;
let next_index = (i + 1) * PAIR_LEN;
pair.handle = AttributeHandle(LittleEndian::read_u16(&buffer[index..]));
pair.uuid.0.copy_from_slice(&buffer[2 + index..next_index]);
}
Ok(HandleUuidPairs::Format128(count, pairs))
}
/// This event is generated in response to a Find By Type Value Request.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttFindByTypeValueResponse {
/// The connection handle related to the response.
pub conn_handle: ConnectionHandle,
/// The number of valid pairs that follow.
handle_pair_count: usize,
/// Handles Information List as defined in Bluetooth Core v4.1 spec.
handles: [HandleInfoPair; MAX_HANDLE_INFO_PAIR_COUNT],
}
impl AttFindByTypeValueResponse {
/// Returns an iterator over the Handles Information List as defined in Bluetooth Core v4.1
/// spec.
pub fn handle_pairs_iter(&self) -> HandleInfoPairIterator {
HandleInfoPairIterator {
event: self,
next_index: 0,
}
}
}
impl Debug for AttFindByTypeValueResponse {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{{.conn_handle = {:?}, ", self.conn_handle)?;
for handle_pair in self.handle_pairs_iter() {
write!(f, "{:?}", handle_pair)?;
}
write!(f, "}}")
}
}
// Assuming a maximum HCI packet size of 255, these are the maximum number of handle pairs that can
// be in one packet.
//
// Packets have 5 other bytes of data preceding the handle-UUID pairs.
//
// max = floor((255 - 5) / 4)
const MAX_HANDLE_INFO_PAIR_COUNT: usize = 62;
/// Simple container for the handle information returned in [`AttFindByTypeValueResponse`].
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleInfoPair {
/// Attribute handle
pub attribute: AttributeHandle,
/// Group End handle
pub group_end: GroupEndHandle,
}
/// Newtype for Group End handles
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GroupEndHandle(pub u16);
/// Iterator into valid [`HandleInfoPair`] structs returned in the [ATT Find By Type Value
/// Response](AttFindByTypeValueResponse) event.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleInfoPairIterator<'a> {
event: &'a AttFindByTypeValueResponse,
next_index: usize,
}
impl<'a> Iterator for HandleInfoPairIterator<'a> {
type Item = HandleInfoPair;
fn next(&mut self) -> Option<Self::Item> {
if self.next_index >= self.event.handle_pair_count {
return None;
}
let index = self.next_index;
self.next_index += 1;
Some(self.event.handles[index])
}
}
fn to_att_find_by_value_type_response(
buffer: &[u8],
) -> Result<AttFindByTypeValueResponse, crate::event::Error<Stm32Wb5xError>> {
const PAIR_LEN: usize = 4;
require_len_at_least!(buffer, 5);
let data_len = buffer[4] as usize;
require_len!(buffer, 5 + data_len);
let pair_buffer = &buffer[5..];
if pair_buffer.len() % PAIR_LEN != 0 {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::AttFindByTypeValuePartial,
));
}
let count = pair_buffer.len() / PAIR_LEN;
let mut pairs = [HandleInfoPair {
attribute: AttributeHandle(0),
group_end: GroupEndHandle(0),
}; MAX_HANDLE_INFO_PAIR_COUNT];
for (i, pair) in pairs.iter_mut().enumerate().take(count) {
let index = i * PAIR_LEN;
pair.attribute = AttributeHandle(LittleEndian::read_u16(&pair_buffer[index..]));
pair.group_end = GroupEndHandle(LittleEndian::read_u16(&pair_buffer[2 + index..]));
}
Ok(AttFindByTypeValueResponse {
conn_handle: to_conn_handle(buffer)?,
handle_pair_count: count,
handles: pairs,
})
}
/// This event is generated in response to a Read By Type Request.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttReadByTypeResponse {
/// The connection handle related to the response.
pub conn_handle: ConnectionHandle,
// Number of valid bytes in `handle_value_pair_buf`
data_len: usize,
// Length of each value in `handle_value_pair_buf`
value_len: usize,
// Raw data of the response. Contains 2 octets for the attribute handle followed by `value_len`
// octets of value data. These pairs repeat for `data_len` bytes.
handle_value_pair_buf: [u8; MAX_HANDLE_VALUE_PAIR_BUF_LEN],
}
// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_HANDLE_VALUE_PAIR_BUF_LEN: usize = 249;
impl Debug for AttReadByTypeResponse {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{{.conn_handle = {:?}, ", self.conn_handle)?;
for handle_value_pair in self.handle_value_pair_iter() {
write!(
f,
"{{handle: {:?}, value: {:?}}}",
handle_value_pair.handle,
first_16(handle_value_pair.value)
)?;
}
write!(f, "}}")
}
}
impl AttReadByTypeResponse {
/// Return an iterator over all valid handle-value pairs returned with the response.
pub fn handle_value_pair_iter(&self) -> HandleValuePairIterator {
HandleValuePairIterator {
event: self,
index: 0,
}
}
}
/// Iterator over the valid handle-value pairs returned with the [ATT Read by Type
/// response](AttReadByTypeResponse).
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleValuePairIterator<'a> {
event: &'a AttReadByTypeResponse,
index: usize,
}
impl<'a> Iterator for HandleValuePairIterator<'a> {
type Item = HandleValuePair<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.event.data_len {
return None;
}
let handle_index = self.index;
let value_index = self.index + 2;
self.index += 2 + self.event.value_len;
let next_index = self.index;
Some(HandleValuePair {
handle: AttributeHandle(LittleEndian::read_u16(
&self.event.handle_value_pair_buf[handle_index..],
)),
value: &self.event.handle_value_pair_buf[value_index..next_index],
})
}
}
/// A single handle-value pair returned by the [ATT Read by Type response](AttReadByTypeResponse).
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HandleValuePair<'a> {
/// Attribute handle
pub handle: AttributeHandle,
/// Attribute value. The caller must interpret the value correctly, depending on the expected
/// type of the attribute.
pub value: &'a [u8],
}
impl<'a> HandleValuePair<'a> {
pub fn uuid(&self) -> u16 {
LittleEndian::read_u16(&self.value[3..])
}
}
fn to_att_read_by_type_response(
buffer: &[u8],
) -> Result<AttReadByTypeResponse, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 6);
let data_len = buffer[5] as usize;
require_len!(buffer, 6 + data_len);
let handle_value_pair_len = buffer[4] as usize;
let handle_value_pair_buf = &buffer[6..];
if handle_value_pair_buf.len() % handle_value_pair_len != 0 {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::AttReadByTypeResponsePartial,
));
}
let mut full_handle_value_pair_buf = [0; MAX_HANDLE_VALUE_PAIR_BUF_LEN];
full_handle_value_pair_buf[..handle_value_pair_buf.len()]
.copy_from_slice(handle_value_pair_buf);
Ok(AttReadByTypeResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
data_len: handle_value_pair_buf.len(),
value_len: handle_value_pair_len - 2,
handle_value_pair_buf: full_handle_value_pair_buf,
})
}
/// This event is generated in response to a Read Request.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttReadResponse {
/// The connection handle related to the response.
pub conn_handle: ConnectionHandle,
/// The number of valid bytes in the value buffer.
value_len: usize,
/// Buffer containing the value data.
value_buf: [u8; MAX_READ_RESPONSE_LEN],
}
// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_READ_RESPONSE_LEN: usize = 250;
impl Debug for AttReadResponse {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{{.conn_handle = {:?}, value = {:?}}}",
self.conn_handle,
first_16(self.value())
)
}
}
impl AttReadResponse {
/// Returns the valid part of the value data.
pub fn value(&self) -> &[u8] {
&self.value_buf[..self.value_len]
}
}
fn to_att_read_response(
buffer: &[u8],
) -> Result<AttReadResponse, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 5);
let data_len = buffer[4] as usize;
require_len!(buffer, 5 + data_len);
let mut value_buf = [0; MAX_READ_RESPONSE_LEN];
value_buf[..data_len].copy_from_slice(&buffer[5..]);
Ok(AttReadResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
value_len: data_len,
value_buf,
})
}
/// This event is generated in response to a Read By Group Type Request. See the Bluetooth Core v4.1
/// spec, Vol 3, section 3.4.4.9 and 3.4.4.10.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttReadByGroupTypeResponse {
/// The connection handle related to the response.
pub conn_handle: ConnectionHandle,
// Length of the attribute data group in `attribute_data_buf`, including the attribute and group
// end handles.
attribute_group_len: usize,
// Number of valid bytes in `attribute_data_buf`
data_len: usize,
// List of attribute data which is a repetition of:
// 1. 2 octets for attribute handle.
// 2. 2 octets for end group handle.
// 3. (attribute_group_len - 4) octets for attribute value.
attribute_data_buf: [u8; MAX_ATTRIBUTE_DATA_BUF_LEN],
}
// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_ATTRIBUTE_DATA_BUF_LEN: usize = 249;
impl AttReadByGroupTypeResponse {
/// Create and return an iterator for the attribute data returned with the response.
pub fn attribute_data_iter(&self) -> AttributeDataIterator {
AttributeDataIterator {
event: self,
next_index: 0,
}
}
}
impl Debug for AttReadByGroupTypeResponse {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{{.conn_handle = {:?}, ", self.conn_handle)?;
for attribute_data in self.attribute_data_iter() {
write!(
f,
"{{.attribute_handle = {:?}, .attribute_end_handle = {:?}, .value = {:?}}}",
attribute_data.attribute_handle,
attribute_data.attribute_end_handle,
first_16(attribute_data.value)
)?;
}
write!(f, "}}")
}
}
/// Iterator over the attribute data returned in the [`AttReadByGroupTypeResponse`].
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttributeDataIterator<'a> {
event: &'a AttReadByGroupTypeResponse,
next_index: usize,
}
impl<'a> Iterator for AttributeDataIterator<'a> {
type Item = AttributeData<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.next_index >= self.event.data_len {
return None;
}
let attr_handle_index = self.next_index;
let group_end_index = 2 + attr_handle_index;
let value_index = 2 + group_end_index;
self.next_index += self.event.attribute_group_len;
Some(AttributeData {
attribute_handle: AttributeHandle(LittleEndian::read_u16(
&self.event.attribute_data_buf[attr_handle_index..],
)),
attribute_end_handle: AttributeHandle(LittleEndian::read_u16(
&self.event.attribute_data_buf[group_end_index..],
)),
value: &self.event.attribute_data_buf[value_index..self.next_index],
})
}
}
/// Attribute data returned in the [`AttReadByGroupTypeResponse`] event.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttributeData<'a> {
/// Attribute handle
pub attribute_handle: AttributeHandle,
/// Group end handle
pub attribute_end_handle: AttributeHandle,
/// Attribute value
pub value: &'a [u8],
}
impl<'a> AttributeData<'a> {
pub fn uuid(&self) -> u16 {
LittleEndian::read_u16(&self.value[0..])
}
}
fn to_att_read_by_group_type_response(
buffer: &[u8],
) -> Result<AttReadByGroupTypeResponse, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 6);
let data_len = buffer[5] as usize;
require_len!(buffer, 6 + data_len);
let attribute_group_len = buffer[4] as usize;
if buffer[6..].len() % attribute_group_len != 0 {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::AttReadByGroupTypeResponsePartial,
));
}
let mut attribute_data_buf = [0; MAX_ATTRIBUTE_DATA_BUF_LEN];
attribute_data_buf[..data_len].copy_from_slice(&buffer[6..]);
Ok(AttReadByGroupTypeResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
data_len: data_len, // lose 1 byte to attribute_group_len
attribute_group_len,
attribute_data_buf,
})
}
/// This event is generated in response to a Prepare Write Request. See the Bluetooth Core v4.1
/// spec, Vol 3, Part F, section 3.4.6.1 and 3.4.6.2
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttPrepareWriteResponse {
/// The connection handle related to the response.
pub conn_handle: ConnectionHandle,
/// The handle of the attribute to be written.
pub attribute_handle: AttributeHandle,
/// The offset of the first octet to be written.
pub offset: usize,
/// Number of valid bytes in |value_buf|
value_len: usize,
value_buf: [u8; MAX_WRITE_RESPONSE_VALUE_LEN],
}
// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_WRITE_RESPONSE_VALUE_LEN: usize = 246;
impl Debug for AttPrepareWriteResponse {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{{.conn_handle = {:?}, .attribute_handle = {:?}, .offset = {}, .value = {:?}}}",
self.conn_handle,
self.attribute_handle,
self.offset,
first_16(self.value())
)
}
}
impl AttPrepareWriteResponse {
/// Returns the partial value of the attribute to be written.
pub fn value(&self) -> &[u8] {
&self.value_buf[..self.value_len]
}
}
fn to_att_prepare_write_response(
buffer: &[u8],
) -> Result<AttPrepareWriteResponse, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 9);
let data_len = buffer[4] as usize;
require_len!(buffer, 5 + data_len);
let value_len = data_len - 4;
let mut value_buf = [0; MAX_WRITE_RESPONSE_VALUE_LEN];
value_buf[..value_len].copy_from_slice(&buffer[9..]);
Ok(AttPrepareWriteResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[5..])),
offset: LittleEndian::read_u16(&buffer[7..]) as usize,
value_len,
value_buf,
})
}
/// Defines the attribute value returned by a [GATT Indication](Stm32Wb5xEvent::GattIndication) or
/// [GATT Notification](Stm32Wb5xEvent::GattNotification) event.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttributeValue {
/// The connection handle related to the event.
pub conn_handle: ConnectionHandle,
/// The handle of the attribute.
pub attribute_handle: AttributeHandle,
// Number of valid bytes in value_buf
value_len: usize,
// Current value of the attribute. Only the first value_len bytes are valid.
value_buf: [u8; MAX_ATTRIBUTE_VALUE_LEN],
}
// The maximum amount of data in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_ATTRIBUTE_VALUE_LEN: usize = 248;
impl Debug for AttributeValue {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{{.conn_handle = {:?}, .attribute_handle = {:?}, .value = {:?}}}",
self.conn_handle,
self.attribute_handle,
first_16(self.value())
)
}
}
impl AttributeValue {
/// Returns the current value of the attribute.
pub fn value(&self) -> &[u8] {
&self.value_buf[..self.value_len]
}
}
fn to_attribute_value(
buffer: &[u8],
) -> Result<AttributeValue, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 7);
let data_len = buffer[4] as usize;
require_len!(buffer, 5 + data_len);
let value_len = data_len - 2;
let mut value_buf = [0; MAX_ATTRIBUTE_VALUE_LEN];
value_buf[..value_len].copy_from_slice(&buffer[7..]);
Ok(AttributeValue {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[5..])),
value_len,
value_buf,
})
}
fn to_write_permit_request(
buffer: &[u8],
) -> Result<AttributeValue, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 7);
let data_len = buffer[6] as usize;
require_len!(buffer, 7 + data_len);
let value_len = data_len;
let mut value_buf = [0; MAX_ATTRIBUTE_VALUE_LEN];
value_buf[..value_len].copy_from_slice(&buffer[7..]);
Ok(AttributeValue {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
value_len,
value_buf,
})
}
/// This event is generated when a GATT client procedure completes either with error or
/// successfully.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GattProcedureComplete {
/// The connection handle for which the GATT procedure has completed.
pub conn_handle: ConnectionHandle,
/// Indicates whether the procedure completed with [error](GattProcedureStatus::Failed) or was
/// [successful](GattProcedureStatus::Success).
pub status: GattProcedureStatus,
}
/// Allowed status codes for the [GATT Procedure Complete](Stm32Wb5xEvent::GattProcedureComplete)
/// event.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum GattProcedureStatus {
/// BLE Status Success
Success,
/// BLE Status Failed
Failed,
}
impl TryFrom<u8> for GattProcedureStatus {
type Error = Stm32Wb5xError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x00 => Ok(GattProcedureStatus::Success),
0x41 => Ok(GattProcedureStatus::Failed),
_ => Err(Stm32Wb5xError::BadGattProcedureStatus(value)),
}
}
}
fn to_gatt_procedure_complete(
buffer: &[u8],
) -> Result<GattProcedureComplete, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 5);
Ok(GattProcedureComplete {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
status: buffer[4].try_into().map_err(crate::event::Error::Vendor)?,
})
}
/// The Error Response is used to state that a given request cannot be performed, and to provide the
/// reason. See the Bluetooth Core Specification, v4.1, Vol 3, Part F, Section 3.4.1.1.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttErrorResponse {
/// The connection handle related to the event.
pub conn_handle: ConnectionHandle,
/// The request that generated this error response.
pub request: AttRequest,
///The attribute handle that generated this error response.
pub attribute_handle: AttributeHandle,
/// The reason why the request has generated an error response.
pub error: AttError,
}
/// Potential error codes for the [ATT Error Response](Stm32Wb5xEvent::AttErrorResponse). See Table
/// 3.3 in the Bluetooth Core Specification, v4.1, Vol 3, Part F, Section 3.4.1.1 and The Bluetooth
/// Core Specification Supplement, Table 1.1.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AttError {
/// The attribute handle given was not valid on this server.
InvalidHandle = 0x01,
/// The attribute cannot be read.
ReadNotPermitted = 0x02,
/// The attribute cannot be written.
WriteNotPermitted = 0x03,
/// The attribute PDU was invalid.
InvalidPdu = 0x04,
/// The attribute requires authentication before it can be read or written.
InsufficientAuthentication = 0x05,
/// Attribute server does not support the request received from the client.
RequestNotSupported = 0x06,
/// Offset specified was past the end of the attribute.
InvalidOffset = 0x07,
/// The attribute requires authorization before it can be read or written.
InsufficientAuthorization = 0x08,
/// Too many prepare writes have been queued.
PrepareQueueFull = 0x09,
/// No attribute found within the given attribute handle range.
AttributeNotFound = 0x0A,
/// The attribute cannot be read or written using the Read Blob Request.
AttributeNotLong = 0x0B,
/// The Encryption Key Size used for encrypting this link is insufficient.
InsufficientEncryptionKeySize = 0x0C,
/// The attribute value length is invalid for the operation.
InvalidAttributeValueLength = 0x0D,
/// The attribute request that was requested has encountered an error that was unlikely, and
/// therefore could not be completed as requested.
UnlikelyError = 0x0E,
/// The attribute requires encryption before it can be read or written.
InsufficientEncryption = 0x0F,
/// The attribute type is not a supported grouping attribute as defined by a higher layer
/// specification.
UnsupportedGroupType = 0x10,
/// Insufficient Resources to complete the request.
InsufficientResources = 0x11,
/// Application error code defined by a higher layer specification.
ApplicationError0x80 = 0x80,
/// Application error code defined by a higher layer specification.
ApplicationError0x81 = 0x81,
/// Application error code defined by a higher layer specification.
ApplicationError0x82 = 0x82,
/// Application error code defined by a higher layer specification.
ApplicationError0x83 = 0x83,
/// Application error code defined by a higher layer specification.
ApplicationError0x84 = 0x84,
/// Application error code defined by a higher layer specification.
ApplicationError0x85 = 0x85,
/// Application error code defined by a higher layer specification.
ApplicationError0x86 = 0x86,
/// Application error code defined by a higher layer specification.
ApplicationError0x87 = 0x87,
/// Application error code defined by a higher layer specification.
ApplicationError0x88 = 0x88,
/// Application error code defined by a higher layer specification.
ApplicationError0x89 = 0x89,
/// Application error code defined by a higher layer specification.
ApplicationError0x8A = 0x8A,
/// Application error code defined by a higher layer specification.
ApplicationError0x8B = 0x8B,
/// Application error code defined by a higher layer specification.
ApplicationError0x8C = 0x8C,
/// Application error code defined by a higher layer specification.
ApplicationError0x8D = 0x8D,
/// Application error code defined by a higher layer specification.
ApplicationError0x8E = 0x8E,
/// Application error code defined by a higher layer specification.
ApplicationError0x8F = 0x8F,
/// Application error code defined by a higher layer specification.
ApplicationError0x90 = 0x90,
/// Application error code defined by a higher layer specification.
ApplicationError0x91 = 0x91,
/// Application error code defined by a higher layer specification.
ApplicationError0x92 = 0x92,
/// Application error code defined by a higher layer specification.
ApplicationError0x93 = 0x93,
/// Application error code defined by a higher layer specification.
ApplicationError0x94 = 0x94,
/// Application error code defined by a higher layer specification.
ApplicationError0x95 = 0x95,
/// Application error code defined by a higher layer specification.
ApplicationError0x96 = 0x96,
/// Application error code defined by a higher layer specification.
ApplicationError0x97 = 0x97,
/// Application error code defined by a higher layer specification.
ApplicationError0x98 = 0x98,
/// Application error code defined by a higher layer specification.
ApplicationError0x99 = 0x99,
/// Application error code defined by a higher layer specification.
ApplicationError0x9A = 0x9A,
/// Application error code defined by a higher layer specification.
ApplicationError0x9B = 0x9B,
/// Application error code defined by a higher layer specification.
ApplicationError0x9C = 0x9C,
/// Application error code defined by a higher layer specification.
ApplicationError0x9D = 0x9D,
/// Application error code defined by a higher layer specification.
ApplicationError0x9E = 0x9E,
/// Application error code defined by a higher layer specification.
ApplicationError0x9F = 0x9F,
/// The requested write operation cannot be fulfilled for reasons other than permissions.
WriteRequestRejected = 0xFC,
/// A Client Characteristic Configuration descriptor is not configured according to the
/// requirements of the profile or service.
ClientCharacteristicConfigurationDescriptorImproperlyConfigured = 0xFD,
/// A profile or service request cannot be serviced because an operation that has been
/// previously triggered is still in progress.
ProcedureAlreadyInProgress = 0xFE,
/// An attribute value is out of range as defined by a profile or service specification.
OutOfRange = 0xFF,
}
impl TryFrom<u8> for AttError {
type Error = u8;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x01 => Ok(AttError::InvalidHandle),
0x02 => Ok(AttError::ReadNotPermitted),
0x03 => Ok(AttError::WriteNotPermitted),
0x04 => Ok(AttError::InvalidPdu),
0x05 => Ok(AttError::InsufficientAuthentication),
0x06 => Ok(AttError::RequestNotSupported),
0x07 => Ok(AttError::InvalidOffset),
0x08 => Ok(AttError::InsufficientAuthorization),
0x09 => Ok(AttError::PrepareQueueFull),
0x0A => Ok(AttError::AttributeNotFound),
0x0B => Ok(AttError::AttributeNotLong),
0x0C => Ok(AttError::InsufficientEncryptionKeySize),
0x0D => Ok(AttError::InvalidAttributeValueLength),
0x0E => Ok(AttError::UnlikelyError),
0x0F => Ok(AttError::InsufficientEncryption),
0x10 => Ok(AttError::UnsupportedGroupType),
0x11 => Ok(AttError::InsufficientResources),
0x80 => Ok(AttError::ApplicationError0x80),
0x81 => Ok(AttError::ApplicationError0x81),
0x82 => Ok(AttError::ApplicationError0x82),
0x83 => Ok(AttError::ApplicationError0x83),
0x84 => Ok(AttError::ApplicationError0x84),
0x85 => Ok(AttError::ApplicationError0x85),
0x86 => Ok(AttError::ApplicationError0x86),
0x87 => Ok(AttError::ApplicationError0x87),
0x88 => Ok(AttError::ApplicationError0x88),
0x89 => Ok(AttError::ApplicationError0x89),
0x8A => Ok(AttError::ApplicationError0x8A),
0x8B => Ok(AttError::ApplicationError0x8B),
0x8C => Ok(AttError::ApplicationError0x8C),
0x8D => Ok(AttError::ApplicationError0x8D),
0x8E => Ok(AttError::ApplicationError0x8E),
0x8F => Ok(AttError::ApplicationError0x8F),
0x90 => Ok(AttError::ApplicationError0x90),
0x91 => Ok(AttError::ApplicationError0x91),
0x92 => Ok(AttError::ApplicationError0x92),
0x93 => Ok(AttError::ApplicationError0x93),
0x94 => Ok(AttError::ApplicationError0x94),
0x95 => Ok(AttError::ApplicationError0x95),
0x96 => Ok(AttError::ApplicationError0x96),
0x97 => Ok(AttError::ApplicationError0x97),
0x98 => Ok(AttError::ApplicationError0x98),
0x99 => Ok(AttError::ApplicationError0x99),
0x9A => Ok(AttError::ApplicationError0x9A),
0x9B => Ok(AttError::ApplicationError0x9B),
0x9C => Ok(AttError::ApplicationError0x9C),
0x9D => Ok(AttError::ApplicationError0x9D),
0x9E => Ok(AttError::ApplicationError0x9E),
0x9F => Ok(AttError::ApplicationError0x9F),
0xFC => Ok(AttError::WriteRequestRejected),
0xFD => Ok(AttError::ClientCharacteristicConfigurationDescriptorImproperlyConfigured),
0xFE => Ok(AttError::ProcedureAlreadyInProgress),
0xFF => Ok(AttError::OutOfRange),
_ => Err(value),
}
}
}
/// Possible ATT requests. See Table 3.37 in the Bluetooth Core Spec v4.1, Vol 3, Part F, Section
/// 3.4.8.
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AttRequest {
/// Section 3.4.1.1
ErrorResponse = 0x01,
/// Section 3.4.2.1
ExchangeMtuRequest = 0x02,
/// Section 3.4.2.2
ExchangeMtuResponse = 0x03,
/// Section 3.4.3.1
FindInformationRequest = 0x04,
/// Section 3.4.3.2
FindInformationResponse = 0x05,
/// Section 3.4.3.3
FindByTypeValueRequest = 0x06,
/// Section 3.4.3.4
FindByTypeValueResponse = 0x07,
/// Section 3.4.4.1
ReadByTypeRequest = 0x08,
/// Section 3.4.4.2
ReadByTypeResponse = 0x09,
/// Section 3.4.4.3
ReadRequest = 0x0A,
/// Section 3.4.4.4
ReadResponse = 0x0B,
/// Section 3.4.4.5
ReadBlobRequest = 0x0C,
/// Section 3.4.4.6
ReadBlobResponse = 0x0D,
/// Section 3.4.4.7
ReadMultipleRequest = 0x0E,
/// Section 3.4.4.8
ReadMultipleResponse = 0x0F,
/// Section 3.4.4.9
ReadByGroupTypeRequest = 0x10,
/// Section 3.4.4.10
ReadByGroupTypeResponse = 0x11,
/// Section 3.4.5.1
WriteRequest = 0x12,
/// Section 3.4.5.2
WriteResponse = 0x13,
/// Section 3.4.5.3
WriteCommand = 0x52,
/// Section 3.4.5.4
SignedWriteCommand = 0xD2,
/// Section 3.4.6.1
PrepareWriteRequest = 0x16,
/// Section 3.4.6.2
PrepareWriteResponse = 0x17,
/// Section 3.4.6.3
ExecuteWriteRequest = 0x18,
/// Section 3.4.6.4
ExecuteWriteResponse = 0x19,
/// Section 3.4.7.1
HandleValueNotification = 0x1B,
/// Section 3.4.7.2
HandleValueIndication = 0x1D,
/// Section 3.4.7.3
HandleValueConfirmation = 0x1E,
}
impl TryFrom<u8> for AttRequest {
type Error = Stm32Wb5xError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x01 => Ok(AttRequest::ErrorResponse),
0x02 => Ok(AttRequest::ExchangeMtuRequest),
0x03 => Ok(AttRequest::ExchangeMtuResponse),
0x04 => Ok(AttRequest::FindInformationRequest),
0x05 => Ok(AttRequest::FindInformationResponse),
0x06 => Ok(AttRequest::FindByTypeValueRequest),
0x07 => Ok(AttRequest::FindByTypeValueResponse),
0x08 => Ok(AttRequest::ReadByTypeRequest),
0x09 => Ok(AttRequest::ReadByTypeResponse),
0x0A => Ok(AttRequest::ReadRequest),
0x0B => Ok(AttRequest::ReadResponse),
0x0C => Ok(AttRequest::ReadBlobRequest),
0x0D => Ok(AttRequest::ReadBlobResponse),
0x0E => Ok(AttRequest::ReadMultipleRequest),
0x0F => Ok(AttRequest::ReadMultipleResponse),
0x10 => Ok(AttRequest::ReadByGroupTypeRequest),
0x11 => Ok(AttRequest::ReadByGroupTypeResponse),
0x12 => Ok(AttRequest::WriteRequest),
0x13 => Ok(AttRequest::WriteResponse),
0x52 => Ok(AttRequest::WriteCommand),
0xD2 => Ok(AttRequest::SignedWriteCommand),
0x16 => Ok(AttRequest::PrepareWriteRequest),
0x17 => Ok(AttRequest::PrepareWriteResponse),
0x18 => Ok(AttRequest::ExecuteWriteRequest),
0x19 => Ok(AttRequest::ExecuteWriteResponse),
0x1B => Ok(AttRequest::HandleValueNotification),
0x1D => Ok(AttRequest::HandleValueIndication),
0x1E => Ok(AttRequest::HandleValueConfirmation),
_ => Err(Stm32Wb5xError::BadAttRequestOpcode(value)),
}
}
}
fn to_att_error_response(
buffer: &[u8],
) -> Result<AttErrorResponse, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 8);
Ok(AttErrorResponse {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
request: buffer[4].try_into().map_err(crate::event::Error::Vendor)?,
attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[5..])),
error: buffer[7]
.try_into()
.map_err(Stm32Wb5xError::BadAttError)
.map_err(crate::event::Error::Vendor)?,
})
}
/// This event is given to the application when a read request or read blob request is received by
/// the server from the client. This event will be given to the application only if the event bit
/// for this event generation is set when the characteristic was added. On receiving this event, the
/// application can update the value of the handle if it desires and when done it has to use the
/// [`allow_read`](crate::gatt::Commands::allow_read) command to indicate to the stack that it can
/// send the response to the client.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
/// See STM AN5270, section 3.4.19
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttReadPermitRequest {
/// Handle of the connection on which there was the request to read the attribute
pub conn_handle: ConnectionHandle,
/// The handle of the attribute that has been requested by the client to be read.
pub attribute_handle: AttributeHandle,
/// Contains the offset from which the read has been requested.
pub offset: usize,
}
fn to_att_read_permit_request(
buffer: &[u8],
) -> Result<AttReadPermitRequest, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 8);
Ok(AttReadPermitRequest {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
offset: LittleEndian::read_u16(&buffer[6..]) as usize,
})
}
/// This event is given to the application when a read multiple request or read by type request is
/// received by the server from the client. This event will be given to the application only if the
/// event bit for this event generation is set when the characteristic was added. On receiving this
/// event, the application can update the values of the handles if it desires and when done it has
/// to send the `gatt_allow_read` command to indicate to the stack that it can send the response to
/// the client.
///
/// See the Bluetooth Core v4.1 spec, Vol 3, Part F, section 3.4.4.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttReadMultiplePermitRequest {
/// Handle of the connection which requested to read the attribute.
pub conn_handle: ConnectionHandle,
/// Number of valid handles in handles_buf
handles_len: usize,
/// Attribute handles returned by the ATT Read Multiple Permit Request. Only the first
/// `handles_len` handles are valid.
handles_buf: [AttributeHandle; MAX_ATTRIBUTE_HANDLE_BUFFER_LEN],
}
// The maximum number of handles in the buffer is the max HCI packet size (255) less the other data in
// the packet divided by the length of an attribute handle (2).
const MAX_ATTRIBUTE_HANDLE_BUFFER_LEN: usize = 125;
impl Debug for AttReadMultiplePermitRequest {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{{.conn_handle = {:?}, .handles = {:?}",
self.conn_handle,
first_16(self.handles())
)
}
}
impl AttReadMultiplePermitRequest {
/// Returns the valid attribute handles returned by the ATT Read Multiple Permit Request event.
pub fn handles(&self) -> &[AttributeHandle] {
&self.handles_buf[..self.handles_len]
}
}
fn to_att_read_multiple_permit_request(
buffer: &[u8],
) -> Result<AttReadMultiplePermitRequest, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 5);
let data_len = buffer[4] as usize;
if data_len % 2 != 0 {
return Err(crate::event::Error::Vendor(
Stm32Wb5xError::AttReadMultiplePermitRequestPartial,
));
}
let handle_len = data_len / 2;
let mut handles = [AttributeHandle(0); MAX_ATTRIBUTE_HANDLE_BUFFER_LEN];
for (i, handle) in handles.iter_mut().enumerate().take(handle_len) {
let index = 5 + 2 * i;
*handle = AttributeHandle(LittleEndian::read_u16(&buffer[index..]));
}
Ok(AttReadMultiplePermitRequest {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
handles_len: handle_len,
handles_buf: handles,
})
}
/// This event is raised when the number of available TX buffers is above a threshold TH (TH = 2).
/// The event will be given only if a previous ACI command returned with
/// [`InsufficientResources`](AttError::InsufficientResources).
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct GattTxPoolAvailable {
/// Connection handle on which the GATT procedure is running.
pub conn_handle: ConnectionHandle,
/// Indicates the number of elements available in the attrTxPool List.
pub available_buffers: usize,
}
fn to_gatt_tx_pool_available(
buffer: &[u8],
) -> Result<GattTxPoolAvailable, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 6);
Ok(GattTxPoolAvailable {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
available_buffers: LittleEndian::read_u16(&buffer[4..]) as usize,
})
}
/// This event is given to the application when a prepare write request is received by the server
/// from the client.
///
/// This event will be given to the application only if the event bit for this event generation is
/// set when the characteristic was added. When this event is received, the application has to
/// check whether the value being requested for write is allowed to be written and respond with the
/// command `gatt_write_response`. Based on the response from the application, the attribute value
/// will be modified by the stack. If the write is rejected by the application, then the value of
/// the attribute will not be modified and an error response will be sent to the client, with the
/// error code as specified by the application.
#[derive(Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttPrepareWritePermitRequest {
/// Connection handle on which the GATT procedure is running.
pub conn_handle: ConnectionHandle,
/// The handle of the attribute to be written.
pub attribute_handle: AttributeHandle,
/// The offset of the first octet to be written.
pub offset: usize,
// Number of valid bytes in `value_buf`
value_len: usize,
// The data to be written. Only the first `value_len` bytes are valid.
value_buf: [u8; MAX_PREPARE_WRITE_PERMIT_REQ_VALUE_LEN],
}
// The maximum number of bytes in the buffer is the max HCI packet size (255) less the other data in
// the packet.
const MAX_PREPARE_WRITE_PERMIT_REQ_VALUE_LEN: usize = 246;
impl Debug for AttPrepareWritePermitRequest {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{{.conn_handle = {:?}, .attribute_handle = {:?}, .offset = {:?}, .value = {:?}",
self.conn_handle,
self.attribute_handle,
self.offset,
first_16(self.value())
)
}
}
impl AttPrepareWritePermitRequest {
/// Returns the data to be written.
pub fn value(&self) -> &[u8] {
&self.value_buf[..self.value_len]
}
}
fn to_att_prepare_write_permit_request(
buffer: &[u8],
) -> Result<AttPrepareWritePermitRequest, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 9);
let data_len = buffer[8] as usize;
require_len!(buffer, 9 + data_len);
let mut value_buf = [0; MAX_PREPARE_WRITE_PERMIT_REQ_VALUE_LEN];
value_buf[..data_len].copy_from_slice(&buffer[9..]);
Ok(AttPrepareWritePermitRequest {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
attribute_handle: AttributeHandle(LittleEndian::read_u16(&buffer[4..])),
offset: LittleEndian::read_u16(&buffer[6..]) as usize,
value_len: data_len,
value_buf,
})
}
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct NumericComparisonValue {
pub connection_handle: ConnectionHandle,
pub numeric_value: u32,
}
fn to_numeric_comparison_value(
buffer: &[u8],
) -> Result<NumericComparisonValue, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 8);
Ok(NumericComparisonValue {
connection_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[2..])),
numeric_value: LittleEndian::read_u32(&buffer[4..]),
})
}
fn to_keypress_notification(buffer: &[u8]) -> Result<u8, crate::event::Error<Stm32Wb5xError>> {
require_len!(buffer, 1);
Ok(buffer[0])
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct L2CapCommandReject {
pub conn_handle: ConnectionHandle,
pub identifier: u8,
pub reason: u16,
pub data: [u8; 247],
}
fn to_l2cap_command_reject(
buffer: &[u8],
) -> Result<L2CapCommandReject, crate::event::Error<Stm32Wb5xError>> {
require_len_at_least!(buffer, 6);
let mut data = [0; 247];
let len = buffer[5] as usize;
data[..len].copy_from_slice(&buffer[6..(6 + len)]);
Ok(L2CapCommandReject {
conn_handle: ConnectionHandle(LittleEndian::read_u16(&buffer[0..])),
identifier: buffer[2],
reason: LittleEndian::read_u16(&buffer[3..]),
data,
})
}