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
use super::*;
use std::convert::TryFrom;
use std::collections::HashSet;
pub use global_packet_number::GlobalPacketNumber;
pub use joycon_features::{JoyConFeature, IMUConfig};
use std::sync::{Mutex, MutexGuard};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Rotation {
    ///    .-..WHHHHHWa-.
    ///     zrrrrrrrrrvvzzVHJ.
    ///   (gkrrrrrrrrrtrrrrrzWn.
    ///   dMKrQWNmrrtrrtrtrrrvXH,
    ///   WMRtZH#VrtrtrrrtrrtrrzW-
    ///   WMRttrrtrrwQmmyrrtrrrru.
    ///   WMRtrtttrrMHWWMkrrtrrrwl
    ///   WMRrtrrrrrTMMMBvrrrrrrrI
    ///   JMSrOdMMMmrrrrrQHMMHwrrI
    ///   dMktdHHd@#rtrrrWHWdMSrwI
    ///   dMSrrdHMBwrAQArwHMM8rrrI
    ///   dMSrrrrrrrHHWHNwrrrrtrrI
    ///   WM0ttrtttrMHgH#wrrtrrrrI
    ///   HM0rrtrtrrrw0wrrtrttrrrI
    ///   HM0rrrtrrtrrrrrtrrrrtrvI
    ///   HM0rtrrrrrvzzzvvvrrrrtvr
    ///  .HMkrrtrrvQgHNHmyzvvrrrwr
    ///  .HMZrtrrQMMHHHH##Nkwrrrvr
    ///  .@NZrrrwMMHHHHHHHH#Zvrrvr
    ///  .@NZrrrdMHHHHHHHH##uwrrvr
    ///  .@NwrrrrUMHHHHHH#MSXrrrvr
    ///  .@NwrtrrrXHMMMMM8Xwrrtrvr
    ///   dNwrtrrrrrvrrrrrrrrrrrw)
    ///   dNrrrtrrrrrrrrrrrrrrrrw%
    ///   dMrrrrAWHHkrrrrrrrrrrrw)
    ///  .WMrrrwWMMMNkrrrrrrrrrrw)
    ///  .@MrrrrVMMM9rrrrrrtrrrrz)
    ///  .HMrrrrrrrrrrrrrtrrrrrrw)
    ///  .@Mrrrrrtrrrrtrrrtrrrrrw}
    ///  ,HMrrrrrrrrtrrrrrrrrrrrX
    ///  ,HWrrrrrrrrrrrtrrrrrrrw}
    ///  .Bvrrrrtrrtrrrrrtrrrrw>
    ///    (rrrrrrrrrtrrrrrrvZ^
    ///    (vrrrrrrrrrrrrrvZ^
    ///    (vvvvrrvrvvwZ7^
    ///    (OzuuuXuuuX
    Portrait,
    ///  `````. ``  `  ` .WQQQQQQQQQmmggggga+gQQQQmQmmmmmmgggggg&(JJJJJ.+++&+++++J,` `
    ///   ````.._++zOOrrvwVUUUUUUUUUUUUUBBBBBWWWWWWWWWWHHHHHHHHHHHHHHHHHHHHHHHMMMM5((-
    ///   ````._(zuXvrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrttrrtttrtrrwwrrtrttrrwmOrrrvZ
    ///  ` ```.~(zuXvrrrrrrrrrrtrrtwAQmyrrrrrtrrwwwwrrrrrtrttrrtrrQMHMMkrrtrrdMHMSrrrw,
    ///   ````.~(zXXvrrrrrrrrrrrrrrWMNMNRrrrrwQdHMMMNmwvrrrrtrtrtrdHkkM8rtrtrrZ9rrrrvwF
    ///  ` ```.~(zuuvrrrrrrtrrtrrrrWMMMNSrrrvdMHHHHHHMNwvrrrrrAggyrZW90rAQgyrrtrrrrrrwF
    ///   ````.~(jVwzrrrrtrrrrtrtrrrrZZrrrrvwHHHHHHHHHM#uvrtrdMMMHRrrrrdHMMMKrrtrrtrvd]
    ///  `````.~(+z!OvrrrrrrrrrrrtrrrrrrrrvrwM#HHHHHHH#HzvrrrdMHHMSrrrrdMHNM9rtrrtrrvd!
    ///   ````.._<~ .zvrrrtrrtrrrrtrrrrrrrrrvXMH#HHHHMBzvrrrtrrwwrwgHHmrrZVrrrrrtrrvqF
    ///   ```...~`   .OvrrrrrrrrrrrrrtrrrrrrvvXXHMMMHUzvvrrrrttrrrdMkHMKrrrtrtrrrrvqY
    ///  ` ```.`      `?wvrrrrrrrrrrrrrrrrrrrrrrvwwvvrrrrrtrrrrtrrZM@@HXrrrrrrrrwXd^
    ///   `              _7XwvrrrrrrrrrrrrrrrrrrrrrrrrrrrrrtrrrrrrrrrrrrrrrrrwwXV=
    ///                      _?7777777777777777777777777777777777777OOOOO77=!(=`
    Landscape,
}

/// Rumble data for vibration.
///
/// # Notice
/// Constraints exist.
/// * frequency - 0.0 < freq < 1252.0
/// * amplitude - 0.0 < amp < 1.799.0
///
/// # Example
/// ```no_run
/// use joycon_rs::prelude::{*, joycon_features::JoyConFeature};
///
/// let manager = JoyConManager::new().unwrap();
/// let (managed_devices, new_devices) = {
///     let lock = manager.lock();
///     match lock {
///         Ok(manager) =>
///             (manager.managed_devices(), manager.new_devices()),
///         Err(_) => unreachable!(),
///     }
/// };
///
/// managed_devices.into_iter()
///     .chain(new_devices)
///     .try_for_each::<_, JoyConResult<()>>(|d| {
///         let mut driver = SimpleJoyConDriver::new(&d)?;
///
///         driver.enable_feature(JoyConFeature::Vibration)?;
///
///         let rumble = Rumble::new(300.0,0.9);
///         // ₍₍(ง˘ω˘)ว⁾⁾ Rumble! ₍₍(ง˘ω˘)ว⁾⁾
///         driver.rumble((Some(rumble), Some(rumble)))?;
///
///         Ok(())
///     })
///     .unwrap();
///```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rumble {
    frequency: f32,
    amplitude: f32,
}

impl Rumble {
    pub fn frequency(&self) -> f32 {
        self.frequency
    }

    pub fn amplitude(&self) -> f32 {
        self.amplitude
    }

    /// Constructor of Rumble.
    /// If arguments not in line with constraints, args will be saturated.
    pub fn new(freq: f32, amp: f32) -> Self {
        let freq = if freq < 0.0 {
            0.0
        } else if freq > 1252.0 {
            1252.0
        } else {
            freq
        };

        let amp = if amp < 0.0 {
            0.0
        } else if amp > 1.799 {
            1.799
        } else {
            amp
        };

        Self {
            frequency: freq,
            amplitude: amp,
        }
    }

    /// The amplitudes over 1.003 are not safe for the integrity of the linear resonant actuators.
    pub fn is_safe(&self) -> bool {
        self.amplitude < 1.003
    }

    /// Generates stopper of rumbling.
    ///
    /// # Example
    /// ```ignore
    /// # use joycon_rs::prelude::*;
    /// # let mut rumbling_controller_driver: SimpleJoyConDriver;
    /// // Make JoyCon stop rambling.
    /// rumbling_controller_driver.rumble((Some(Rumble::stop()),Some(Rumble::stop()))).unwrap();
    /// ```
    pub fn stop() -> Self {
        Self {
            frequency: 0.0,
            amplitude: 0.0,
        }
    }
}

impl Into<[u8; 4]> for Rumble {
    fn into(self) -> [u8; 4] {
        let encoded_hex_freq = f32::round(f32::log2(self.frequency / 10.0) * 32.0) as u8;

        let hf_freq: u16 = (encoded_hex_freq as u16).saturating_sub(0x60) * 4;
        let lf_freq: u8 = encoded_hex_freq.saturating_sub(0x40);

        let encoded_hex_amp = if self.amplitude > 0.23 {
            f32::round(f32::log2(self.amplitude * 8.7) * 32.0) as u8
        } else if self.amplitude > 0.12 {
            f32::round(f32::log2(self.amplitude * 17.0) * 16.0) as u8
        } else {
            // todo study
            f32::round(f32::log2(self.amplitude * 17.0) * 16.0) as u8
        };

        let hf_amp: u16 = {
            let hf_amp: u16 = (encoded_hex_freq as u16 - 0x60) * 4;
            if hf_amp > 0x01FC {
                0x01FC
            } else { hf_amp }
        }; // encoded_hex_amp<<1;
        let lf_amp: u8 = {
            let lf_amp = encoded_hex_amp / 2 + 64;
            if lf_amp > 0x7F {
                0x7F
            } else { lf_amp }
        };      // (encoded_hex_amp>>1)+0x40;

        let mut buf = [0u8; 4];

        // HF: Byte swapping
        buf[0] = (hf_freq & 0xFF) as u8;
        // buf[1] = (hf_amp + ((hf_freq >> 8) & 0xFF)) as u8; //Add amp + 1st byte of frequency to amplitude byte
        buf[1] = (hf_amp + (hf_freq.wrapping_shr(8) & 0xFF)) as u8; //Add amp + 1st byte of frequency to amplitude byte

        // LF: Byte swapping
        buf[2] = lf_freq.saturating_add(lf_amp.wrapping_shr(8) & 0xFF);
        buf[3] = lf_amp & 0xFF;

        buf
    }
}

pub mod joycon_features {
    /// Features on Joy-Cons which needs to set up.
    /// ex. IMU(6-Axis sensor), NFC/IR, Vibration
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum JoyConFeature {
        IMUFeature(IMUConfig),
        Vibration,
    }

    pub use imu_sensitivity::IMUConfig;

    pub mod imu_sensitivity {
        use std::hash::Hash;

        /// Gyroscope sensitivity
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum GyroscopeSensitivity {
            PM250dps = 0x00,
            PM500dps = 0x01,
            PM1000dps = 0x02,
            PM2000dps = 0x03,
        }

        impl Default for GyroscopeSensitivity {
            fn default() -> Self {
                GyroscopeSensitivity::PM2000dps
            }
        }

        /// Accelerometer sensitivity
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum AccelerometerSensitivity {
            PM8G = 0x00,
            PM4G = 0x01,
            PM2G = 0x02,
            PM16G = 0x03,
        }

        impl Default for AccelerometerSensitivity {
            fn default() -> Self {
                AccelerometerSensitivity::PM8G
            }
        }

        /// Gyroscope performance rate
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum GyroscopePerformanceRate {
            F833Hz = 0x00,
            F208Hz = 0x01,
        }

        impl Default for GyroscopePerformanceRate {
            fn default() -> Self {
                GyroscopePerformanceRate::F208Hz
            }
        }

        /// Accelerometer Anti-aliasing filter bandwidth
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum AccelerometerAntiAliasingFilterBandwidth {
            F200Hz = 0x00,
            F100Hz = 0x01,
        }

        impl Default for AccelerometerAntiAliasingFilterBandwidth {
            fn default() -> Self {
                AccelerometerAntiAliasingFilterBandwidth::F100Hz
            }
        }

        /// # Notice
        /// `IMUConfig` returns constant hash value.
        #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
        pub struct IMUConfig {
            pub gyroscope_sensitivity: GyroscopeSensitivity,
            pub accelerometer_sensitivity: AccelerometerSensitivity,
            pub gyroscope_performance_rate: GyroscopePerformanceRate,
            pub accelerometer_anti_aliasing_filter_bandwidth: AccelerometerAntiAliasingFilterBandwidth,
        }

        impl Into<[u8; 4]> for IMUConfig {
            fn into(self) -> [u8; 4] {
                let IMUConfig {
                    gyroscope_sensitivity,
                    accelerometer_sensitivity,
                    gyroscope_performance_rate,
                    accelerometer_anti_aliasing_filter_bandwidth,
                } = self;

                [
                    gyroscope_sensitivity as u8,
                    accelerometer_sensitivity as u8,
                    gyroscope_performance_rate as u8,
                    accelerometer_anti_aliasing_filter_bandwidth as u8
                ]
            }
        }

        impl Hash for IMUConfig {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                // Returns constant value.
                0.hash(state);
            }
        }
    }
}

mod global_packet_number {
    use std::ops::Add;

    /// Increment by 1 for each packet sent. It loops in 0x0 - 0xF range.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct GlobalPacketNumber(pub u8);

    impl GlobalPacketNumber {
        pub fn next(self) -> GlobalPacketNumber {
            self + GlobalPacketNumber(1)
        }
    }

    impl Default for GlobalPacketNumber {
        fn default() -> Self {
            GlobalPacketNumber(0x0)
        }
    }

    impl Add for GlobalPacketNumber {
        type Output = Self;

        fn add(self, rhs: Self) -> Self::Output {
            let (GlobalPacketNumber(raw), GlobalPacketNumber(raw_rhs))
                = (self, rhs);
            let res = raw.wrapping_add(raw_rhs);

            GlobalPacketNumber(res)
        }
    }

    impl Into<u8> for GlobalPacketNumber {
        fn into(self) -> u8 {
            self.0
        }
    }
}

/// The controller user uses to play with.
/// If you're not happy with this implementation, you can use `JoyConDriver` trait.
///
/// # Examples
/// ```no_run
/// use joycon_rs::prelude::{JoyConManager, SimpleJoyConDriver, lights::*};
/// use joycon_rs::result::JoyConResult;
///
/// let manager = JoyConManager::new().unwrap();
///
/// let (managed_devices, new_devices) = {
///     let lock = manager.lock();
///     match lock {
///         Ok(manager) => (manager.managed_devices(), manager.new_devices()),
///         Err(_) => return,
///     }
/// };
///
/// managed_devices.into_iter()
///     .chain(new_devices)
///     .try_for_each::<_,JoyConResult<()>>(|device| {
///         let mut driver = SimpleJoyConDriver::new(&device)?;
///
///         // set player's lights
///         driver.set_player_lights(&vec![SimpleJoyConDriver::LIGHT_UP[0]], &vec![])?;
///
///         Ok(())
///     })
///     .unwrap();
/// ```
#[derive(Debug)]
pub struct SimpleJoyConDriver {
    /// The controller user uses
    pub joycon: Arc<Mutex<JoyConDevice>>,
    /// rotation of controller
    pub rotation: Rotation,
    rumble: (Option<Rumble>, Option<Rumble>),
    enabled_features: HashSet<JoyConFeature>,
    /// Increment by 1 for each packet sent. It loops in 0x0 - 0xF range.
    global_packet_number: GlobalPacketNumber,
}

impl SimpleJoyConDriver {
    /// Constructs a new `SimpleJoyConDriver`.
    pub fn new(joycon: &Arc<Mutex<JoyConDevice>>) -> JoyConResult<Self> {
        // joycon.set_blocking_mode(true);
        // joycon.set_blocking_mode(false);

        let mut driver = Self {
            joycon: Arc::clone(joycon),
            rotation: Rotation::Portrait,
            rumble: (None, None),
            enabled_features: HashSet::new(),
            global_packet_number: GlobalPacketNumber::default(),
        };

        driver.reset()?;

        Ok(driver)
    }

    pub fn joycon(&self) -> MutexGuard<JoyConDevice> {
        // todo error handling
        match self.joycon.lock() {
            Ok(joycon) => joycon,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

pub trait JoyConDriver {
    /// If a sub-command is sent and no ACK packet is returned, tread again for the number of times of this value.
    const ACK_TRY: usize = 5;

    /// Send command to Joy-Con
    fn write(&self, data: &[u8]) -> JoyConResult<usize>;

    /// Read reply from Joy-Con
    fn read(&self, buf: &mut [u8]) -> JoyConResult<usize>;

    /// Get global packet number
    fn global_packet_number(&self) -> u8;

    /// Increase global packet number. Increment by 1 for each packet sent. It loops in 0x0 - 0xF range.
    fn increase_global_packet_number(&mut self);

    /// Set rumble status.
    fn set_rumble_status(&mut self, rumble_l_r: (Option<Rumble>, Option<Rumble>));

    /// Set rumble status and send rumble command to JoyCon.
    fn rumble(&mut self, rumble_l_r: (Option<Rumble>, Option<Rumble>)) -> JoyConResult<usize> {
        self.set_rumble_status(rumble_l_r);
        self.send_command_raw(Command::Rumble as u8, 0, &[])
    }

    /// Get rumble status.
    fn get_rumble_status(&self) -> (Option<Rumble>, Option<Rumble>);

    /// Send command, sub-command, and data (sub-command's arguments) with u8 integers
    /// This returns ACK packet for the command or Error.
    fn send_command_raw(&mut self, command: u8, sub_command: u8, data: &[u8]) -> JoyConResult<usize> {
        let mut buf = [0x0; 0x40];
        // set command
        buf[0] = command;
        // set packet number
        buf[1] = self.global_packet_number();
        // increase packet number
        self.increase_global_packet_number();

        // rumble
        let (rumble_l, rumble_r) = self.get_rumble_status();
        if let Some(rumble_l) = rumble_l {
            let rumble_left: [u8; 4] = rumble_l.into();
            buf[2..6].copy_from_slice(&rumble_left);
        }
        if let Some(rumble_r) = rumble_r {
            let rumble_right: [u8; 4] = rumble_r.into();
            buf[6..10].copy_from_slice(&rumble_right);
        }

        // set sub command
        buf[10] = sub_command;
        // set data
        buf[11..11 + data.len()].copy_from_slice(data);

        // send command
        self.write(&buf)
    }

    /// Send sub-command, and data (sub-command's arguments) with u8 integers
    /// This returns ACK packet for the command or Error.
    fn send_sub_command_raw(&mut self, sub_command: u8, data: &[u8]) -> JoyConResult<[u8; 362]> {
        use input_report_mode::sub_command_mode::AckByte;

        self.send_command_raw(1, sub_command, data)?;

        // check reply
        std::iter::repeat(())
            .take(Self::ACK_TRY)
            .flat_map(|()| {
                let mut buf = [0u8; 362];
                self.read(&mut buf).ok()?;
                let ack_byte = AckByte::from(buf[13]);

                match ack_byte {
                    AckByte::Ack { .. } => Some(buf),
                    AckByte::Nack => None
                }
            })
            .next()
            .ok_or(JoyConError::SubCommandError(sub_command, Vec::new()))
    }

    /// Send command, sub-command, and data (sub-command's arguments) with `Command` and `SubCommand`
    /// This returns ACK packet for the command or Error.
    fn send_command(&mut self, command: Command, sub_command: SubCommand, data: &[u8]) -> JoyConResult<usize> {
        let command = command as u8;
        let sub_command = sub_command as u8;

        self.send_command_raw(command, sub_command, data)
    }

    /// Send sub-command, and data (sub-command's arguments) with `Command` and `SubCommand`
    /// This returns ACK packet for the command or Error.
    fn send_sub_command(&mut self, sub_command: SubCommand, data: &[u8]) -> JoyConResult<[u8; 362]> {
        self.send_sub_command_raw(sub_command as u8, data)
    }

    /// Initialize Joy-Con's status
    fn reset(&mut self) -> JoyConResult<()> {
        // disable IMU (6-Axis sensor)
        self.send_sub_command(SubCommand::EnableIMU, &[0x00])?;
        // disable vibration
        self.send_sub_command(SubCommand::EnableVibration, &[0x00])?;

        Ok(())
    }

    /// Enable Joy-Con's feature. ex. IMU(6-Axis sensor), Vibration(Rumble)
    fn enable_feature(&mut self, feature: JoyConFeature) -> JoyConResult<()>;

    /// Get Enabled features.
    fn enabled_features(&self) -> &HashSet<JoyConFeature>;

    /// Get Joy-Con devices deal with.
    fn devices(&self) -> Vec<Arc<Mutex<JoyConDevice>>>;
}

impl JoyConDriver for SimpleJoyConDriver {
    fn write(&self, data: &[u8]) -> JoyConResult<usize> {
        let joycon = self.joycon();
        Ok(joycon.write(data)?)
    }

    fn read(&self, buf: &mut [u8]) -> JoyConResult<usize> {
        Ok(self.joycon().read(buf)?)
    }

    fn global_packet_number(&self) -> u8 {
        self.global_packet_number.into()
    }

    fn increase_global_packet_number(&mut self) {
        self.global_packet_number = self.global_packet_number.next();
    }

    fn set_rumble_status(&mut self, rumble_l_r: (Option<Rumble>, Option<Rumble>)) {
        self.rumble = rumble_l_r;
    }

    fn get_rumble_status(&self) -> (Option<Rumble>, Option<Rumble>) {
        self.rumble
    }

    fn enable_feature(&mut self, feature: JoyConFeature) -> JoyConResult<()> {
        match feature {
            JoyConFeature::IMUFeature(feature) => {
                let data: [u8; 4] = feature.into();
                // enable IMU
                self.send_sub_command(SubCommand::EnableIMU, &[0x01])?;
                // set config
                self.send_sub_command(SubCommand::SetIMUSensitivity, &data)?;
            }
            JoyConFeature::Vibration => {
                // enable vibration
                self.send_sub_command(SubCommand::EnableVibration, &[0x01])?;
            }
        }

        self.enabled_features.insert(feature);

        Ok(())
    }

    fn enabled_features(&self) -> &HashSet<JoyConFeature> {
        &self.enabled_features
    }

    fn devices(&self) -> Vec<Arc<Mutex<JoyConDevice>>> {
        vec![Arc::clone(&self.joycon)]
    }
}

/// JoyCon's input report mode is divided into five main categories.
///
/// | Struct | Remarks | Frequency |
/// | :-- | :-- | :-- |
/// | [`SimpleHIDMode<D>`] | Simple HID mode. Reports pushed buttons, and stick directions (one of [8 directions]). | (Every time some button pressed) |
/// | [`StandardFullMode<D>`] | IMU(6-Axis sensor) data with standard input report | 60Hz |
/// | [`SubCommandMode<D, RD>`] | SubCommand's reply with standard input report | ? |
/// | (Unimplemented) | NFC/IR MCU FW update with standard input report  | |
/// | (Unimplemented) | NFC/IR data with standard input report | 60Hz |
///
/// Standard input report consists of input report ID, Timer, [battery level],
/// [connection info], [button status], [analog stick data], and vibrator input report.
///
/// If you want to implement input report mode, you can use [`InputReportMode<D>`].
///
/// [`SimpleHIDMode<D>`]: simple_hid_mode/struct.SimpleHIDMode.html
/// [8 directions]: simple_hid_mode/enum.StickDirection.html
/// [`StandardFullMode<D>`]: standard_full_mode/struct.StandardFullMode.html
/// [`SubCommandMode<D, RD>`]: sub_command_mode/struct.SubCommandMode.html
/// [battery level]: struct.Battery.html
/// [connection info]: struct.ConnectionInfo.html
/// [button status]: struct.PushedButtons.html
/// [analog stick data]: struct.AnalogStickData.html
/// [`InputReportMode<D>`]: trait.InputReportMode.html
pub mod input_report_mode {
    use super::*;
    pub use common::*;
    pub use self::{sub_command_mode::SubCommandMode, standard_full_mode::StandardFullMode, simple_hid_mode::SimpleHIDMode};
    use std::convert::TryFrom;
    use std::ops::{Deref, DerefMut};
    use std::hash::Hash;

    mod common {
        use super::*;
        use std::convert::TryFrom;

        /// Battery level
        #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
        pub enum BatteryLevel {
            Empty,
            Critical,
            Low,
            Medium,
            Full,
        }

        /// Battery info
        #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
        pub struct Battery {
            pub level: BatteryLevel,
            pub is_charging: bool,
        }

        impl TryFrom<u8> for Battery {
            type Error = JoyConError;

            fn try_from(value: u8) -> Result<Self, Self::Error> {
                let is_charging = value % 2 == 1;
                let value = if is_charging {
                    value - 1
                } else { value };
                let level = match value {
                    0 => BatteryLevel::Empty,
                    2 => BatteryLevel::Critical,
                    4 => BatteryLevel::Low,
                    6 => BatteryLevel::Medium,
                    8 => BatteryLevel::Full,
                    _ => Err(JoyConReportError::InvalidStandardInputReport(InvalidStandardInputReport::Battery(value)))?
                };

                Ok(Battery { level, is_charging })
            }
        }

        /// Device info
        #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
        pub enum Device {
            JoyCon,
            ProConOrChargingGrip,
        }

        /// Connection info
        #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
        pub struct ConnectionInfo {
            device: Device,
            is_powered: bool,
        }

        impl TryFrom<u8> for ConnectionInfo {
            type Error = JoyConError;

            fn try_from(value: u8) -> Result<Self, Self::Error> {
                let device = match (value >> 1) & 3 {
                    3 => Device::JoyCon,
                    0 => Device::ProConOrChargingGrip,
                    _ => Err(InvalidStandardInputReport::ConnectionInfo(value))?
                };
                let is_powered = (value & 1) == 1;

                Ok(ConnectionInfo {
                    device,
                    is_powered,
                })
            }
        }

        /// Button status
        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct PushedButtons {
            right: Vec<Buttons>,
            shared: Vec<Buttons>,
            left: Vec<Buttons>,
        }

        impl PushedButtons {
            const RIGHT_BUTTONS: [Buttons; 8] = [
                Buttons::Y,
                Buttons::X,
                Buttons::B,
                Buttons::A,
                Buttons::SR,
                Buttons::SL,
                Buttons::R,
                Buttons::ZR,
            ];
            const SHARED_BUTTONS: [Buttons; 8] = [
                Buttons::Minus,
                Buttons::Plus,
                Buttons::RStick,
                Buttons::LStick,
                Buttons::Home,
                Buttons::Capture,
                // originally none
                Buttons::Capture,
                Buttons::ChargingGrip,
            ];
            const LEFT_BUTTONS: [Buttons; 8] = [
                Buttons::Down,
                Buttons::Up,
                Buttons::Right,
                Buttons::Left,
                Buttons::SR,
                Buttons::SL,
                Buttons::L,
                Buttons::ZL,
            ];
        }

        impl From<[u8; 3]> for PushedButtons {
            fn from(value: [u8; 3]) -> Self {
                let right_val = value[0];
                let shared_val = value[1];
                let left_val = value[2];

                let right = PushedButtons::RIGHT_BUTTONS.iter()
                    .enumerate()
                    .filter(|(idx, _)| {
                        let idx = 2u8.pow(*idx as u32) as u8;
                        right_val & idx == idx
                    })
                    .map(|(_, b)| b.clone())
                    .collect();
                let shared = PushedButtons::SHARED_BUTTONS.iter()
                    .enumerate()
                    .filter(|(idx, _)| {
                        let idx = 2u8.pow(*idx as u32) as u8;
                        shared_val & idx == idx
                    })
                    .map(|(_, b)| b.clone())
                    .collect();
                let left = PushedButtons::LEFT_BUTTONS.iter()
                    .enumerate()
                    .filter(|(idx, _)| {
                        let idx = 2u8.pow(*idx as u32) as u8;
                        left_val & idx == idx
                    })
                    .map(|(_, b)| b.clone())
                    .collect();

                PushedButtons {
                    right,
                    shared,
                    left,
                }
            }
        }

        /// Analog stick data
        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct AnalogStickData {
            horizontal: u16,
            vertical: u16,
        }

        impl From<[u8; 3]> for AnalogStickData {
            fn from(value: [u8; 3]) -> Self {
                let horizontal = value[0] as u16 | ((value[1] as u16 & 0xF) << 8);
                let vertical = (value[1] as u16 >> 4) | ((value[2] as u16) << 4);

                Self {
                    horizontal,
                    vertical,
                }
            }
        }

        /// Common parts of the standard input report
        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct CommonReport {
            input_report_id: u8,
            timer: u8,
            battery: Battery,
            connection_info: ConnectionInfo,
            pushed_buttons: PushedButtons,
            left_analog_stick_data: AnalogStickData,
            right_analog_stick_data: AnalogStickData,
            vibrator_input_report: u8,
        }

        impl TryFrom<[u8; 13]> for CommonReport {
            type Error = JoyConError;

            fn try_from(report: [u8; 13]) -> JoyConResult<CommonReport> {
                let input_report_id = report[0];
                let timer = report[1];

                let (battery, connection_info) = {
                    let value = report[2];
                    let high_nibble = value / 16;
                    let low_nibble = value % 16;

                    (Battery::try_from(high_nibble)?, ConnectionInfo::try_from(low_nibble)?)
                };

                let pushed_buttons = {
                    let array = [report[3], report[4], report[5]];
                    PushedButtons::from(array)
                };

                let left_analog_stick_data = {
                    let array = [report[6], report[7], report[8]];
                    AnalogStickData::from(array)
                };
                let right_analog_stick_data = {
                    let array = [report[9], report[10], report[11]];
                    AnalogStickData::from(array)
                };

                let vibrator_input_report = report[12];

                Ok(CommonReport {
                    input_report_id,
                    timer,
                    battery,
                    connection_info,
                    pushed_buttons,
                    left_analog_stick_data,
                    right_analog_stick_data,
                    vibrator_input_report,
                })
            }
        }
    }

    pub trait InputReportMode<D: JoyConDriver>: Deref<Target=D> + DerefMut<Target=D> {
        type Mode: InputReportMode<D>;
        type Report: TryFrom<[u8; 362], Error=JoyConError>;
        type ArgsType: AsRef<[u8]>;

        const SUB_COMMAND: SubCommand;
        const ARGS: Self::ArgsType;

        /// Mode's setup operation.
        /// ex. Enable 6-Axis sensor
        /// note: There are no needs to change Joy-Con's input report mode, leave it to `InputReportMode<D>::new()`.
        fn setup(driver: D) -> JoyConResult<D>;

        /// Construct instance simply. Typically, your implementation will be ->
        /// ```ignore
        /// fn construct(driver: D) -> Self::Mode {
        ///     Self::Mode { driver }
        /// }
        /// ```
        fn construct(driver: D) -> Self::Mode;

        /// set Joy-Con's input report mode and return instance
        fn new(driver: D) -> JoyConResult<Self::Mode> {
            let mut driver = Self::Mode::setup(driver)?;

            driver.send_sub_command(Self::SUB_COMMAND, Self::ARGS.as_ref())?;

            Ok(Self::construct(driver))
        }

        /// read Joy-Con's input report
        fn read_input_report(&self) -> JoyConResult<Self::Report> {
            let mut buf = [0u8; 362];
            self.read(&mut buf)?;

            Self::Report::try_from(buf)
        }
    }

    /// Standard input report with extra report.
    pub struct StandardInputReport<EX: TryFrom<[u8; 349], Error=JoyConError>> {
        pub common: CommonReport,
        pub extra: EX,
    }

    impl<EX> TryFrom<[u8; 362]> for StandardInputReport<EX>
        where EX: TryFrom<[u8; 349], Error=JoyConError>
    {
        type Error = JoyConError;

        fn try_from(value: [u8; 362]) -> Result<Self, Self::Error> {
            // common report
            let common = {
                let mut data = [0x00; 13];
                data.copy_from_slice(&value[0..13]);
                CommonReport::try_from(data)?
            };

            // extra report
            let extra = {
                let mut data = [0x00; 349];
                data.copy_from_slice(&value[13..362]);
                EX::try_from(data)?
            };

            Ok(StandardInputReport {
                common,
                extra,
            })
        }
    }

    impl<EX> Debug for StandardInputReport<EX>
        where EX: TryFrom<[u8; 349], Error=JoyConError> + Debug
    {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(
                f,
                "StandardInputReport {{ common: {:?}, extra: {:?} }}",
                &self.common,
                &self.extra,
            )
        }
    }

    impl<EX> Clone for StandardInputReport<EX>
        where EX: TryFrom<[u8; 349], Error=JoyConError> + Clone
    {
        fn clone(&self) -> Self {
            let common = self.common.clone();
            let extra = self.extra.clone();

            StandardInputReport { common, extra }
        }
    }

    impl<EX> Hash for StandardInputReport<EX>
        where EX: TryFrom<[u8; 349], Error=JoyConError> + Hash
    {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
            self.common.hash(state);
            self.extra.hash(state);
        }
    }

    impl<EX> PartialEq for StandardInputReport<EX>
        where EX: TryFrom<[u8; 349], Error=JoyConError> + PartialEq
    {
        fn eq(&self, other: &Self) -> bool {
            self.common.eq(&other.common)
                && self.extra.eq(&other.extra)
        }
    }

    impl<EX> Eq for StandardInputReport<EX>
        where EX: TryFrom<[u8; 349], Error=JoyConError> + Eq
    {}


    /// Receive standard input report with sub-command's reply.
    ///
    /// If you want to send sub-command and get reply, imply [`SubCommandReplyData`] for your struct.
    ///
    /// [`SubCommandReplyData`]: trait.SubCommandReplyData.html
    pub mod sub_command_mode {
        use super::*;
        use std::marker::PhantomData;

        /// Ack byte. If it is ACK, it contains data type.
        #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
        pub enum AckByte {
            Ack {
                data_type: u8
            },
            Nack,
        }

        impl From<u8> for AckByte {
            fn from(u: u8) -> Self {
                if u >> 7 == 1 {
                    AckByte::Ack {
                        data_type: u & 0x7F
                    }
                } else {
                    AckByte::Nack
                }
            }
        }

        /// An interface for dealing with sub-command's reply.
        ///
        /// # Example - implement `SubCommandReplyData`
        /// ```ignore
        /// #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        /// pub struct LightsStatus {
        ///     light_up: Vec<LightUp>,
        ///     flash: Vec<Flash>,
        /// }
        ///
        /// const LIGHT_UP: [LightUp; 4] =
        ///     [LightUp::LED0, LightUp::LED1, LightUp::LED2, LightUp::LED3];
        /// const FLASH: [Flash; 4] =
        ///     [Flash::LED0, Flash::LED1, Flash::LED2, Flash::LED3];
        ///
        /// impl TryFrom<[u8; 35]> for LightsStatus {
        ///     type Error = JoyConError;
        ///
        ///     fn try_from(value: [u8; 35]) -> Result<Self, Self::Error> {
        ///         let value = value[0];
        ///
        ///         // parse reply
        ///         let light_up = LIGHT_UP.iter()
        ///             .filter(|&&l| {
        ///                 let light = l as u8;
        ///                 value & light == light
        ///             })
        ///             .cloned()
        ///             .collect();
        ///         let flash = FLASH.iter()
        ///             .filter(|&&f| {
        ///                 let flash = f as u8;
        ///                 value & flash == flash
        ///             })
        ///             .cloned()
        ///             .collect();
        ///
        ///         Ok(LightsStatus { light_up, flash })
        ///     }
        /// }
        ///
        /// impl SubCommandReplyData for LightsStatus {
        ///     type ArgsType = [u8; 0];
        ///     const SUB_COMMAND: SubCommand = SubCommand::GetPlayerLights;
        ///     const ARGS: Self::ArgsType = [];
        /// }
        /// ```
        pub trait SubCommandReplyData: TryFrom<[u8; 35], Error=JoyConError> {
            type ArgsType: AsRef<[u8]>;
            const SUB_COMMAND: SubCommand;
            const ARGS: Self::ArgsType;

            /// The mode remains the same, sending commands and receiving replies.
            fn once<D>(driver: &mut D) -> JoyConResult<StandardInputReport<SubCommandReport<Self>>>
                where Self: std::marker::Sized,
                      D: JoyConDriver
            {
                let reply = driver.send_sub_command(Self::SUB_COMMAND, Self::ARGS.as_ref())?;
                StandardInputReport::try_from(reply)
            }
        }

        /// Replies to sub-commands
        #[derive(Clone)]
        pub struct SubCommandReport<RD>
            where RD: SubCommandReplyData
        {
            pub ack_byte: AckByte,
            pub sub_command_id: u8,
            pub reply: RD,
        }

        impl<RD> Debug for SubCommandReport<RD>
            where RD: SubCommandReplyData + Debug
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
                write!(f,
                       "SubCommandReport {{\
                                \n\t ack_byte: {:?},
                                \n\t sub_command_id: {},
                                \n\t reply: {:?},
                       }}",
                       self.ack_byte,
                       self.sub_command_id,
                       &self.reply
                )
            }
        }

        impl<RD> TryFrom<[u8; 349]> for SubCommandReport<RD>
            where RD: SubCommandReplyData
        {
            type Error = JoyConError;

            fn try_from(value: [u8; 349]) -> Result<Self, Self::Error> {
                let ack_byte = AckByte::from(value[0]);
                let sub_command_id = value[1];
                let mut reply = [0x00; 35];
                reply.copy_from_slice(&value[2..37]);
                let reply = RD::try_from(reply)?;

                Ok(SubCommandReport {
                    ack_byte,
                    sub_command_id,
                    reply,
                })
            }
        }

        /// Receive standard input report with sub-command's reply.
        pub struct SubCommandMode<D, RD>
            where D: JoyConDriver, RD: SubCommandReplyData
        {
            driver: D,
            _phantom: PhantomData<RD>,
        }

        impl<D, RD> Deref for SubCommandMode<D, RD>
            where D: JoyConDriver,
                  RD: SubCommandReplyData
        {
            type Target = D;

            fn deref(&self) -> &Self::Target {
                &self.driver
            }
        }

        impl<D, RD> DerefMut for SubCommandMode<D, RD>
            where D: JoyConDriver,
                  RD: SubCommandReplyData
        {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.driver
            }
        }

        impl<D, RD> InputReportMode<D> for SubCommandMode<D, RD>
            where D: JoyConDriver,
                  RD: SubCommandReplyData
        {
            type Mode = SubCommandMode<D, RD>;
            type Report = StandardInputReport<SubCommandReport<RD>>;
            type ArgsType = RD::ArgsType;
            const SUB_COMMAND: SubCommand = RD::SUB_COMMAND;
            const ARGS: Self::ArgsType = RD::ARGS;

            fn setup(driver: D) -> JoyConResult<D> {
                Ok(driver)
            }

            fn construct(driver: D) -> Self::Mode {
                SubCommandMode {
                    driver,
                    _phantom: PhantomData,
                }
            }
        }
    }

    /// Receive standard full report (standard input report with IMU(6-Axis sensor) data).
    ///
    /// Pushes current state at 60Hz.
    pub mod standard_full_mode {
        use super::*;

        /// IMU(6-Axis sensor)'s value.
        #[derive(Debug, Clone, Copy, PartialEq)]
        pub struct AxisData {
            /// Acceleration to X measured
            pub accel_x: i16,
            /// Acceleration to Y measured
            pub accel_y: i16,
            /// Acceleration to Z measured
            pub accel_z: i16,
            /// Rotation of X measured
            pub gyro_1: i16,
            /// Rotation of Y measured
            pub gyro_2: i16,
            /// Rotation of Z measured
            pub gyro_3: i16,
        }

        impl From<[u8; 12]> for AxisData {
            fn from(value: [u8; 12]) -> Self {
                let accel_x = i16::from_le_bytes([value[0], value[1]]);
                let accel_y = i16::from_le_bytes([value[2], value[3]]);
                let accel_z = i16::from_le_bytes([value[4], value[5]]);

                let gyro_1 = i16::from_le_bytes([value[6], value[7]]);
                let gyro_2 = i16::from_le_bytes([value[8], value[9]]);
                let gyro_3 = i16::from_le_bytes([value[10], value[11]]);

                AxisData {
                    accel_x,
                    accel_y,
                    accel_z,
                    gyro_1,
                    gyro_2,
                    gyro_3,
                }
            }
        }

        /// 6-Axis data. 3 frames of 2 groups of 3 Int16LE each. Group is Acc followed by Gyro.
        #[derive(Debug, Clone)]
        pub struct IMUData {
            data: [AxisData; 3]
        }

        impl TryFrom<[u8; 349]> for IMUData {
            type Error = JoyConError;

            fn try_from(value: [u8; 349]) -> Result<Self, Self::Error> {
                let latest = {
                    let mut latest = [0x00; 12];
                    latest.copy_from_slice(&value[0..12]);
                    latest
                };
                let a_5ms_older = {
                    let mut latest = [0x00; 12];
                    latest.copy_from_slice(&value[12..24]);
                    latest
                };
                let a_10ms_older = {
                    let mut latest = [0x00; 12];
                    latest.copy_from_slice(&value[24..36]);
                    latest
                };

                let axis_data = [
                    AxisData::from(latest),
                    AxisData::from(a_5ms_older),
                    AxisData::from(a_10ms_older)
                ];

                Ok(IMUData {
                    data: axis_data,
                })
            }
        }

        /// Joy-Con emitting standard full report includes IMU(6-Axis sensor)
        ///
        /// # Example
        /// ```no_run
        /// use joycon_rs::prelude::*;
        ///
        /// let (sender, receiver) = std::sync::mpsc::channel();
        /// let _output = std::thread::spawn( move || {
        ///     while let Ok(update) = receiver.recv() {
        ///         dbg!(update);
        ///     }
        /// });
        ///
        /// let manager = JoyConManager::new().unwrap();
        ///
        /// let (managed_devices, new_devices) = {
        ///     let lock = manager.lock();
        ///     match lock {
        ///         Ok(manager) => (manager.managed_devices(), manager.new_devices()),
        ///         Err(_) => return,
        ///     }
        /// };
        ///
        /// managed_devices.into_iter()
        ///     .chain(new_devices)
        ///     .flat_map(|device| SimpleJoyConDriver::new(&device))
        ///     .try_for_each::<_, JoyConResult<()>>(|driver| {
        ///         let sender = sender.clone();
        ///
        ///         // Set Joy-Con's mode
        ///         let joycon = StandardFullMode::new(driver)?;
        ///
        ///         std::thread::spawn( move || {
        ///             loop {
        ///                 sender.send(joycon.read_input_report())
        ///                       .unwrap();
        ///             }
        ///         });
        ///
        ///         Ok(())
        ///     })
        ///     .unwrap();
        /// ```
        pub struct StandardFullMode<D: JoyConDriver> {
            driver: D,
        }

        impl<D> Deref for StandardFullMode<D>
            where D: JoyConDriver
        {
            type Target = D;

            fn deref(&self) -> &Self::Target {
                &self.driver
            }
        }

        impl<D> DerefMut for StandardFullMode<D>
            where D: JoyConDriver
        {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.driver
            }
        }

        impl<D> InputReportMode<D> for StandardFullMode<D>
            where D: JoyConDriver
        {
            type Mode = StandardFullMode<D>;
            type Report = StandardInputReport<IMUData>;
            type ArgsType = [u8; 1];
            const SUB_COMMAND: SubCommand = SubCommand::SetInputReportMode;
            const ARGS: Self::ArgsType = [0x30];

            fn setup(driver: D) -> JoyConResult<D> {
                let mut driver = driver;
                // enable IMU(6-Axis sensor)
                let imf_enabled = driver.enabled_features()
                    .iter()
                    .any(|jf| match jf {
                        JoyConFeature::IMUFeature(_) => true,
                        _ => false,
                    });
                if !imf_enabled {
                    driver.enable_feature(JoyConFeature::IMUFeature(IMUConfig::default()))?;
                }

                Ok(driver)
            }

            fn construct(driver: D) -> Self::Mode {
                Self::Mode {
                    driver
                }
            }
        }
    }

    /// Receive simple HID report.
    ///
    /// Simple HID report consists of input report id, button status,
    /// stick direction, filter data.
    ///
    /// Pushes updates with every button press.
    pub mod simple_hid_mode {
        use super::*;

        #[allow(non_camel_case_types)]
        #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
        pub enum SimpleHIDButton {
            Down,
            Right,
            Left,
            Up,
            SL,
            SR,
            Minus,
            Plus,
            LeftStick,
            RightStick,
            Home,
            Capture,
            L_R,
            ZL_ZR,
        }

        const BUTTON1: [SimpleHIDButton; 6] = {
            use SimpleHIDButton::*;
            [Down, Right, Left, Up, SL, SR, ]
        };
        const BUTTON2: [SimpleHIDButton; 8] = {
            use SimpleHIDButton::*;
            [Minus, Plus, LeftStick, RightStick, Home, Capture, L_R, ZL_ZR, ]
        };

        /// Hold your controller sideways so that SL, SYNC, and SR line up with the screen. Pushing the stick towards a direction in this table will cause that value to be sent.
        #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
        pub enum StickDirection {
            Up,
            UpperRight,
            Right,
            BottomRight,
            Bottom,
            BottomLeft,
            Left,
            UpperLeft,
            Neutral,
        }

        impl TryFrom<u8> for StickDirection {
            type Error = JoyConError;

            fn try_from(value: u8) -> Result<Self, Self::Error> {
                use StickDirection::*;

                let button = match value {
                    0 => Up,
                    1 => UpperRight,
                    2 => Right,
                    3 => BottomRight,
                    4 => Bottom,
                    5 => BottomLeft,
                    6 => Left,
                    7 => UpperLeft,
                    8 => Neutral,
                    v => Err(InvalidSimpleHIDReport::InvalidStickDirection(v))?,
                };

                Ok(button)
            }
        }

        /// Pushed buttons and stick direction.
        #[derive(Debug, Clone)]
        pub struct SimpleHIDReport {
            pub input_report_id: u8,
            pub pushed_buttons: Vec<SimpleHIDButton>,
            pub stick_direction: StickDirection,
            pub filter_data: [u8; 8],
        }

        impl TryFrom<[u8; 12]> for SimpleHIDReport {
            type Error = JoyConError;

            fn try_from(value: [u8; 12]) -> Result<Self, Self::Error> {
                let input_report_id = value[0];
                let pushed_buttons = {
                    let byte_1 = value[1];
                    let byte_2 = value[2];
                    [].iter()
                        .chain(
                            BUTTON1.iter()
                                .enumerate()
                                .filter(|(idx, _)| {
                                    let idx = 2u8.pow(*idx as u32) as u8;
                                    byte_1 & idx == idx
                                })
                                .map(|(_, b)| b)
                        )
                        .chain(
                            BUTTON2.iter()
                                .enumerate()
                                .filter(|(idx, _)| {
                                    let idx = 2u8.pow(*idx as u32) as u8;
                                    byte_2 & idx == idx
                                })
                                .map(|(_, b)| b)
                        )
                        .cloned()
                        .collect()
                };
                let stick_direction = StickDirection::try_from(value[3])?;
                let filter_data = {
                    let mut buf = [0u8; 8];
                    buf.copy_from_slice(&value[4..12]);
                    buf
                };

                Ok(SimpleHIDReport {
                    input_report_id,
                    pushed_buttons,
                    stick_direction,
                    filter_data,
                })
            }
        }

        impl TryFrom<[u8; 362]> for SimpleHIDReport {
            type Error = JoyConError;

            fn try_from(value: [u8; 362]) -> Result<Self, Self::Error> {
                let mut buf = [0u8; 12];
                buf.copy_from_slice(&value[0..12]);

                Self::try_from(buf)
            }
        }

        /// Simple HID mode pushes updates with every button press.
        ///
        /// # Example
        /// ```no_run
        /// use joycon_rs::prelude::*;
        ///
        /// let (sender, receiver) = std::sync::mpsc::channel();
        ///
        /// // Receive all Joy-Con's simple HID reports
        /// while let Ok(simple_hid_report) = receiver.recv() {
        ///     // Output reports
        ///     dbg!(simple_hid_report);
        /// }
        ///
        /// let manager = JoyConManager::new().unwrap();
        ///
        /// let (managed_devices, new_devices) = {
        ///     let lock = manager.lock();
        ///     match lock {
        ///         Ok(manager) => (manager.managed_devices(), manager.new_devices()),
        ///         Err(_) => return,
        ///     }
        /// };
        ///
        /// managed_devices.into_iter()
        ///     .chain(new_devices)
        ///     .flat_map(|d| SimpleJoyConDriver::new(&d))
        ///     .try_for_each::<_, JoyConResult<()>>(|driver| {
        ///         let sender = sender.clone();
        ///
        ///         // Set Joy-Con's mode
        ///         let simple_hid_mode_joycon = SimpleHIDMode::new(driver)?;
        ///
        ///         std::thread::spawn( move || {
        ///             loop {
        ///                 sender.send(simple_hid_mode_joycon.read_input_report())
        ///                       .unwrap();
        ///             }
        ///         });
        ///
        ///         Ok(())
        ///     })
        ///     .unwrap();
        /// ```
        pub struct SimpleHIDMode<D: JoyConDriver> {
            driver: D,
        }

        impl<D: JoyConDriver> Deref for SimpleHIDMode<D> {
            type Target = D;

            fn deref(&self) -> &Self::Target {
                &self.driver
            }
        }

        impl<D: JoyConDriver> DerefMut for SimpleHIDMode<D> {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.driver
            }
        }

        impl<D> InputReportMode<D> for SimpleHIDMode<D>
            where D: JoyConDriver
        {
            type Mode = SimpleHIDMode<D>;
            type Report = SimpleHIDReport;
            type ArgsType = [u8; 1];
            const SUB_COMMAND: SubCommand = SubCommand::SetInputReportMode;
            const ARGS: Self::ArgsType = [0x3F];

            fn setup(driver: D) -> JoyConResult<D> {
                // do nothing
                Ok(driver)
            }

            fn construct(driver: D) -> Self::Mode {
                Self::Mode {
                    driver
                }
            }
        }
    }
}

/// Operate Joy-Con's player lights (LEDs). The gist of this module is [`Lights`].
///
/// [`Lights`]: trait.Lights.html
///
/// # Usage
/// ```no_run
/// use joycon_rs::prelude::{*, lights::*};
///
/// let manager = JoyConManager::new().unwrap();
///
/// let device = manager.lock()
///                     .unwrap()
///                     .managed_devices()
///                     .remove(0);
///
/// let mut joycon_driver = SimpleJoyConDriver::new(&device).unwrap();
///
/// // Set player lights lightning and flashing.
/// joycon_driver.set_player_lights(&vec![LightUp::LED2], &vec![Flash::LED3]).unwrap();
///
/// // Get status of player lights
/// let player_lights_status = joycon_driver.get_player_lights()
///     .unwrap()
///     .extra;
/// dbg!(player_lights_status);
/// ```
pub mod lights {
    use super::{*, input_report_mode::sub_command_mode::*};
    use crate::joycon::driver::input_report_mode::StandardInputReport;

    /// LED to keep on lightning up / lightning
    #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
    pub enum LightUp {
        /// Closest led to SL Button
        LED0 = 0x01,
        /// Second closest led to SL Button
        LED1 = 0x02,
        /// Second closest led to SR Button
        LED2 = 0x04,
        /// Closest let to SR Button
        LED3 = 0x08,
    }

    /// LED to flash / flashing
    #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
    pub enum Flash {
        /// Closest led to SL Button
        LED0 = 0x10,
        /// Second closest led to SL Button
        LED1 = 0x20,
        /// Second closest led to SR Button
        LED2 = 0x40,
        /// Closest let to SR Button
        LED3 = 0x80,
    }

    /// Status of player lights.
    #[derive(Debug, Clone, Hash, Eq, PartialEq)]
    pub struct LightsStatus {
        pub light_up: Vec<LightUp>,
        pub flash: Vec<Flash>,
    }

    const LIGHT_UP: [LightUp; 4] =
        [LightUp::LED0, LightUp::LED1, LightUp::LED2, LightUp::LED3];
    const FLASH: [Flash; 4] =
        [Flash::LED0, Flash::LED1, Flash::LED2, Flash::LED3];

    impl TryFrom<[u8; 35]> for LightsStatus {
        type Error = JoyConError;

        fn try_from(value: [u8; 35]) -> Result<Self, Self::Error> {
            let value = value[0];

            // parse reply
            let light_up = LIGHT_UP.iter()
                .filter(|&&l| {
                    let light = l as u8;
                    value & light == light
                })
                .cloned()
                .collect();
            let flash = FLASH.iter()
                .filter(|&&f| {
                    let flash = f as u8;
                    value & flash == flash
                })
                .cloned()
                .collect();

            Ok(LightsStatus { light_up, flash })
        }
    }

    impl SubCommandReplyData for LightsStatus {
        type ArgsType = [u8; 0];
        const SUB_COMMAND: SubCommand = SubCommand::GetPlayerLights;
        const ARGS: Self::ArgsType = [];
    }

    pub mod home_button {
        use super::*;

        #[allow(non_camel_case_types)]
        #[derive(Copy, Clone, Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]
        pub struct u4(u8);

        impl u4 {
            const MAX: Self = u4(15);
        }

        impl From<u8> for u4 {
            fn from(v: u8) -> Self {
                let value = u4(v);

                if value > Self::MAX {
                    Self::MAX
                } else { value }
            }
        }

        impl Into<u8> for u4 {
            fn into(self) -> u8 {
                self.0
            }
        }

        /// Element of HOME light emitting pattern.
        /// The LED Duration Multiplier and the Fading Multiplier use the same algorithm:
        /// Global Mini Cycle Duration ms * Multiplier value.
        ///
        /// Example: GMCD is set to xF = 175ms and LED Duration Multiplier is set to x4.
        /// The Duration that the LED will stay on it's configured intensity is then 175 * 4 = 700ms.
        #[derive(Clone, Debug, Hash, Eq, PartialEq)]
        pub struct LightEmittingPhase {
            /// LED intensity. x0 -> 0%, xF -> 100%
            pub led_intensity: u4,
            /// Fading Transition Duration. Value is a Multiplier of Global Mini Cycle Duration.
            pub fading_transition_duration: u4,
            /// LED Duration Multiplier
            pub led_duration: u4,
        }

        /// HOME light emitting pattern.
        #[derive(Clone, Debug, Hash, Eq, PartialEq)]
        pub struct LightEmittingPattern {
            phases_len: Option<u4>,
            phases: Vec<LightEmittingPhase>,
            /// Global Mini Cycle Duration. 8ms - 175ms. Value x0 = 0ms/OFF
            global_mini_cycle_duration: u4,
            /// LED Start Intensity. Value x0=0% - xF=100%
            led_start_intensity: u4,
            repeat_count: u4,
        }

        impl LightEmittingPattern {
            /// Constructor of `LightEmittingPattern`.
            ///
            /// * global_mini_cycle_duration (*ms*) - 0 <= global_mini_cycle_duration <= 175
            /// * led_start_intensity (*%*) - 0 <= led_start_intensity <= 100
            /// * repeat_count - 0 <= repeat_count <= 15: Value `0` is repeat forever.
            pub fn new(global_mini_cycle_duration: u8, led_start_intensity: u8, repeat_count: u4) -> Self {
                let global_mini_cycle_duration = if global_mini_cycle_duration == 0 {
                    0.into()
                } else {
                    ((global_mini_cycle_duration - 7) / 12 + 1).into()
                };

                let led_start_intensity = {
                    let saturated = if 100 < led_start_intensity { 100 } else { led_start_intensity } as f32;
                    ((saturated / 6.25) as u8).into()
                };

                LightEmittingPattern {
                    phases_len: None,
                    phases: Vec::with_capacity(15),
                    global_mini_cycle_duration,
                    led_start_intensity,
                    repeat_count,
                }
            }

            pub fn push_phase(&mut self, phase: LightEmittingPhase) {
                self.phases.push(phase);
            }

            /// Add emitting phase to pattern.
            ///
            /// * led_intensity (*%*) - 0 <= led_intensity <= 100
            /// * fading_transition_duration (*ms*) - 0 < fading_transition_duration < self.global_mini_cycle_duration (ms) * 15
            /// * led_duration (*ms*) - 0 < fading_transition_duration < self.global_mini_cycle_duration (ms) * 15
            pub fn add_phase(mut self, led_intensity: u8, fading_transition_duration: u16, led_duration: u16) -> Self {
                let led_intensity = {
                    let saturated = if 100 < led_intensity { 100 } else { led_intensity } as f32;
                    ((saturated / 6.25) as u8).into()
                };
                let fading_transition_duration: u4 = {
                    let gmcd: u8 = self.global_mini_cycle_duration.into();
                    (fading_transition_duration / gmcd as u16) as u8
                }.into();
                let led_duration = {
                    let gmcd: u8 =  self.global_mini_cycle_duration.into();
                    (led_duration / gmcd as u16) as u8
                }.into();

                let phase = LightEmittingPhase {
                    led_intensity,
                    fading_transition_duration,
                    led_duration,
                };

                self.push_phase(phase);

                self
            }

            /// Does the 1st phase and then the LED stays on with LED Start Intensity.
            pub fn emit_first_phase(&self) -> Self {
                let mut pattern = self.clone();
                pattern.phases_len = Some(0u8.into());
                pattern.repeat_count = 0u8.into();

                pattern
            }
        }

        impl Into<[u8; 25]> for LightEmittingPattern {
            fn into(self) -> [u8; 25] {
                fn nibbles_to_u8(high: u4, low: u4) -> u8 {
                    let high = {
                        let high :u8 = high.into();
                        (high & 0x0F) << 4
                    };
                    let low = {
                        let low: u8 = low.into();
                        low & 0x0F
                    };

                    high | low
                }

                let mut buf = [0u8; 25];

                let number_of_phases =
                    if let Some(p) = self.phases_len {
                        p
                    } else {
                        (self.phases.len() as u8).into()
                    };
                buf[0] = nibbles_to_u8(number_of_phases, self.global_mini_cycle_duration);

                buf[1] = nibbles_to_u8(self.led_start_intensity, self.repeat_count);

                let mut even_phases = self.phases.iter()
                    .take(15)
                    .enumerate()
                    .filter(|(idx, _)| idx % 2 == 0)
                    .map(|e| e.1);
                let mut odd_phases = self.phases.iter()
                    .take(15)
                    .enumerate()
                    .filter(|(idx, _)| idx % 2 == 1)
                    .map(|e| e.1);


                let mut buf_index = 2;
                while let (Some(even), odd) = (even_phases.next(), odd_phases.next()) {
                    // LED intensities
                    {
                        let even_led_intensity = even.led_intensity;
                        let odd_led_intensity = odd.map(|odd| odd.led_intensity)
                            .unwrap_or(0u8.into());

                        buf[buf_index] = nibbles_to_u8(even_led_intensity, odd_led_intensity);
                        buf_index += 1;
                    }

                    // Even fading & led
                    {
                        let fading = even.fading_transition_duration;
                        let led = even.led_duration;
                        buf[buf_index] = nibbles_to_u8(fading, led);
                        buf_index += 1;
                    }

                    // Odd fading & led
                    if let Some(odd) = odd {
                        let fading = odd.fading_transition_duration;
                        let led = odd.led_duration;
                        buf[buf_index] = nibbles_to_u8(fading, led);
                        buf_index += 1;
                    }
                }

                buf
            }
        }
    }

    /// Operations of player lights.
    pub trait Lights: JoyConDriver {
        const LIGHT_UP: [LightUp; 4] = LIGHT_UP;
        const FLASH: [Flash; 4] = FLASH;

        /// Light up or flash LEDs on controller, vice versa.
        ///
        /// # Example
        /// If you run this code,
        ///
        /// ```no_run
        /// use joycon_rs::prelude::{*, lights::*};
        ///
        /// // some code omitted
        /// # let manager = JoyConManager::new().unwrap();
        /// #
        /// # let device = manager.lock()
        /// #                     .unwrap()
        /// #                     .managed_devices()
        /// #                     .remove(0);
        /// #
        /// # let mut joycon_driver = SimpleJoyConDriver::new(&device).unwrap();
        /// joycon_driver.set_player_lights(&vec![LightUp::LED0],&vec![]).unwrap();
        /// ```
        ///
        /// player lights will be...
        /// > [SL Button] 💡🤔🤔🤔 [SR Button]
        ///
        ///
        /// For another example,
        /// ```no_run
        /// # use joycon_rs::prelude::{*, lights::*};
        /// #
        /// # let manager = JoyConManager::new().unwrap();
        /// #
        /// # let device = manager.lock()
        /// #                     .unwrap()
        /// #                     .managed_devices()
        /// #                     .remove(0);
        /// #
        /// # let mut joycon_driver = SimpleJoyConDriver::new(&device).unwrap();
        /// joycon_driver.set_player_lights(&vec![LightUp::LED2], &vec![Flash::LED3]).unwrap();
        /// ```
        ///
        /// player lights will be...
        /// > [SL Button] 🤔🤔💡📸 [SR Button]
        ///
        /// ## Duplication
        ///
        /// If a command to a certain LED is duplicated, the lighting command takes precedence.
        ///
        /// ```no_run
        /// # use joycon_rs::prelude::{*, lights::*};
        /// #
        /// # let manager = JoyConManager::new().unwrap();
        /// #
        /// # let device = manager.lock()
        /// #                     .unwrap()
        /// #                     .managed_devices()
        /// #                     .remove(0);
        /// #
        /// # let mut joycon_driver = SimpleJoyConDriver::new(&device).unwrap();
        /// joycon_driver.set_player_lights(&vec![LightUp::LED1], &vec![Flash::LED1]).unwrap();
        /// ```
        ///
        /// Player lights will be...
        /// > [SL Button] 🤔💡🤔🤔 [SR Button]
        ///
        fn set_player_lights(&mut self, light_up: &Vec<LightUp>, flash: &Vec<Flash>) -> JoyConResult<[u8; 362]> {
            let arg = light_up.iter()
                .map(|&lu| lu as u8)
                .sum::<u8>()
                + flash.iter()
                .map(|&f| f as u8)
                .sum::<u8>();

            let reply = self.send_sub_command(SubCommand::SetPlayerLights, &[arg])?;
            Ok(reply)
        }

        /// Get status of player lights on controller.
        ///
        /// # Example
        ///
        /// ```no_run
        /// use joycon_rs::prelude::{*, lights::*};
        ///
        /// # let manager = JoyConManager::new().unwrap();
        /// #
        /// # let device = manager.lock()
        /// #                     .unwrap()
        /// #                     .managed_devices()
        /// #                     .remove(0);
        /// #
        /// # let mut joycon_driver = SimpleJoyConDriver::new(&device).unwrap();
        /// let player_lights_status = joycon_driver.get_player_lights()
        ///     .unwrap()
        ///     .extra;
        /// dbg!(player_lights_status);
        /// ```
        ///
        fn get_player_lights(&mut self) -> JoyConResult<StandardInputReport<SubCommandReport<LightsStatus>>>
            where Self: std::marker::Sized
        {
            LightsStatus::once(self)
        }

        /// Set HOME light.
        ///
        /// # Example
        /// ```no_run
        /// use joycon_rs::prelude::{*, lights::{*, home_button::*}};
        ///
        /// # let manager = JoyConManager::new().unwrap();
        /// #
        /// # let device = manager.lock()
        /// #                     .unwrap()
        /// #                     .managed_devices()
        /// #                     .remove(0);
        /// #
        /// # let mut joycon_driver = SimpleJoyConDriver::new(&device).unwrap();
        /// let pattern =
        ///     // loop pattern forever
        ///     LightEmittingPattern::new(100, 0, 0u8.into())
        ///         // 0.5 seconds to light up
        ///         .add_phase(100,500,0)
        ///         // 0.5 seconds to turn off
        ///         .add_phase(0,500,0);
        /// let player_lights_status = joycon_driver.set_home_light(&pattern);
        /// ```
        fn set_home_light(&mut self, pattern: &home_button::LightEmittingPattern) -> JoyConResult<[u8; 362]> {
            let arg: [u8;25] = pattern.clone().into();
            self.send_sub_command(SubCommand::SetHOMELight, &arg)
        }
    }

    impl<D> Lights for D where D: JoyConDriver {}
}

pub mod device_info {
    use super::{*, input_report_mode::sub_command_mode::*};

    impl TryFrom<u8> for JoyConDeviceType {
        type Error = ();

        fn try_from(value: u8) -> Result<Self, Self::Error> {
            let kind = match value {
                0 => JoyConDeviceType::JoyConL,
                1 => JoyConDeviceType::JoyConR,
                2 => JoyConDeviceType::ProCon,
                _ => Err(())?
            };

            Ok(kind)
        }
    }

    #[derive(Debug, Clone, Hash, Eq, PartialEq)]
    pub struct JoyConMacAddress(pub [u8; 6]);

    #[derive(Debug, Clone, Hash, Eq, PartialEq)]
    pub struct JoyConDeviceInfo {
        pub firmware_version: u16,
        pub device_type: JoyConDeviceType,
        pub mac_address: JoyConMacAddress,
        pub colors_in_spi: bool,
    }

    impl TryFrom<[u8; 35]> for JoyConDeviceInfo {
        type Error = JoyConError;

        fn try_from(value: [u8; 35]) -> Result<Self, Self::Error> {
            let firmware_version = u16::from_be_bytes([value[0], value[1]]);
            let device_kind = JoyConDeviceType::try_from(value[2])
                .map_err(|()| {
                    JoyConError::SubCommandError(SubCommand::RequestDeviceInfo as u8, value.to_vec())
                })?;
            let mac_address = {
                let mut buf = [0u8; 6];
                buf.copy_from_slice(&value[4..10]);
                JoyConMacAddress(buf)
            };
            let colors_in_spi = value[12] == 1;

            Ok(JoyConDeviceInfo {
                firmware_version,
                device_type: device_kind,
                mac_address,
                colors_in_spi,
            })
        }
    }

    impl SubCommandReplyData for JoyConDeviceInfo {
        type ArgsType = [u8; 0];
        const SUB_COMMAND: SubCommand = SubCommand::RequestDeviceInfo;
        const ARGS: Self::ArgsType = [];
    }
}

#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
pub enum Command {
    RumbleAndSubCommand = 1,
    NFC_IR_MCU_FW_Update = 3,
    Rumble = 16,
    RumbleAndRequestSpecificDataFromThe_NFC_IR_MCU = 17,
}

/// ref. https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_subcommands_notes.md
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
pub enum SubCommand {
    GetOnlyControllerState = 0,
    BluetoothManualPairing = 1,
    RequestDeviceInfo = 2,
    SetInputReportMode = 3,
    TriggerButtonsElapsedTime = 4,
    GetPageListState = 5,
    SetHCIState = 6,
    ResetPairingInfo = 7,
    SetShipmentLowPowerState = 8,
    SPIFlashRead = 10,
    SPIFlashWrite = 11,
    SPISectorErase = 12,
    ResetNFC_IR_MCU = 32,
    Set_NFC_IR_MCUConfiguration = 33,
    Set_NFC_IR_MCUState = 34,
    Get_x28_NFC_IR_MCUData = 41,
    Set_GPIO_PinOutputValue = 42,
    Get_x29_NFC_IR_MCUData = 43,
    SetPlayerLights = 48,
    GetPlayerLights = 49,
    SetHOMELight = 56,
    EnableIMU = 64,
    SetIMUSensitivity = 65,
    WriteToIMURegisters = 66,
    ReadIMURegisters = 67,
    EnableVibration = 72,
    GetRegulatedVoltage = 80,
    SetGPIOPinOutputValue = 81,
    GetGPIOPinInput_OutputValue = 82,
}