framework_lib 0.6.2

Library to control Framework Computer systems
Documentation
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
use core::fmt;

use num_derive::FromPrimitive;

use super::{command::*, input_deck::INPUT_DECK_SLOTS};
#[cfg(feature = "uefi")]
use core::prelude::rust_2021::derive;

#[repr(C, packed)]
pub struct EcRequestGetVersion {}

#[repr(C, packed)]
pub struct EcResponseGetVersion {
    /// Null-terminated version of the RO firmware
    pub version_string_ro: [u8; 32],
    /// Null-terminated version of the RW firmware
    pub version_string_rw: [u8; 32],
    /// Used to be the RW-B string
    pub reserved: [u8; 32],
    /// Which EC image is currently in-use. See enum EcCurrentImage
    pub current_image: u32,
}
impl EcRequest<EcResponseGetVersion> for EcRequestGetVersion {
    fn command_id() -> EcCommands {
        EcCommands::GetVersion
    }
}

#[repr(C, packed)]
pub struct EcRequestGetCmdVersionsV0 {
    pub cmd: u8,
}
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct EcResponseGetCmdVersionsV0 {
    pub version_mask: u32,
}
impl EcRequest<EcResponseGetCmdVersionsV0> for EcRequestGetCmdVersionsV0 {
    fn command_id() -> EcCommands {
        EcCommands::GetCmdVersions
    }
    fn command_version() -> u8 {
        0
    }
}

#[repr(C, packed)]
pub struct EcRequestGetCmdVersionsV1 {
    pub cmd: u32,
}
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
pub struct EcResponseGetCmdVersionsV1 {
    pub version_mask: u32,
}
impl EcRequest<EcResponseGetCmdVersionsV1> for EcRequestGetCmdVersionsV1 {
    fn command_id() -> EcCommands {
        EcCommands::GetCmdVersions
    }
    fn command_version() -> u8 {
        1
    }
}

pub struct EcRequestFlashInfo {}

#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
pub struct EcResponseFlashInfo {
    pub flash_size: u32,
    pub write_block_size: u32,
    pub erase_block_size: u32,
    pub protect_block_size: u32,
    // New fields in version 1 of the command
    pub write_ideal_size: u32,
    pub flags: u32,
}

impl EcRequest<EcResponseFlashInfo> for EcRequestFlashInfo {
    fn command_version() -> u8 {
        1
    }
    fn command_id() -> EcCommands {
        EcCommands::FlashInfo
    }
}

pub struct EcRequestFlashRead {
    pub offset: u32,
    pub size: u32,
}

impl EcRequest<()> for EcRequestFlashRead {
    fn command_id() -> EcCommands {
        EcCommands::FlashRead
    }
}

#[repr(C, packed)]
pub struct EcRequestFlashWrite {
    pub offset: u32,
    pub size: u32,
    /// Dynamically sized array (data copied after this struct)
    pub data: [u8; 0],
}
impl EcRequest<()> for EcRequestFlashWrite {
    fn command_id() -> EcCommands {
        EcCommands::FlashWrite
    }
}

#[repr(C, packed)]
pub struct EcRequestFlashErase {
    pub offset: u32,
    pub size: u32,
}

impl EcRequest<()> for EcRequestFlashErase {
    fn command_id() -> EcCommands {
        EcCommands::FlashErase
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum FlashProtectFlags {
    ProtectRoAtBoot = 1 << 0,
    ProtectRoNow = 1 << 1,
    ProtectAllNow = 1 << 2,
    ProtectGpioAsserted = 1 << 3,
    /// At least one flash bank is stuck and can't be unlocked
    ErrorStruck = 1 << 4,
    ErrorInconsistent = 1 << 5,
    ProtectAllAtBoot = 1 << 6,
}

#[repr(C, packed)]
pub struct EcRequestFlashProtect {
    pub mask: u32,
    pub flags: u32,
}

pub struct EcResponseFlashProtect {
    /// Current flash protect flags
    pub flags: u32,
    /// Flags that are valid on this platform
    pub valid_flags: u32,
    /// Flags that can be currently written (depending on protection status)
    pub writeable_flags: u32,
}

impl EcRequest<EcResponseFlashProtect> for EcRequestFlashProtect {
    fn command_id() -> EcCommands {
        EcCommands::FlashProtect
    }
}

#[repr(C, packed)]
pub struct EcRequestPwmSetKeyboardBacklight {
    pub percent: u8,
}

impl EcRequest<()> for EcRequestPwmSetKeyboardBacklight {
    fn command_id() -> EcCommands {
        EcCommands::PwmSetKeyboardBacklight
    }
}

#[repr(C, packed)]
pub struct EcRequestPwmGetKeyboardBacklight {}

#[repr(C, packed)]
pub struct EcResponsePwmGetKeyboardBacklight {
    pub percent: u8,
    pub enabled: u8,
}

#[repr(u8)]
pub enum PwmType {
    Generic = 0,
    KbLight,
    DisplayLight,
}

impl EcRequest<EcResponsePwmGetKeyboardBacklight> for EcRequestPwmGetKeyboardBacklight {
    fn command_id() -> EcCommands {
        EcCommands::PwmGetKeyboardBacklight
    }
}

#[repr(C, packed)]
pub struct EcRequestPwmSetFanTargetRpmV0 {
    /// Duty cycle in percent
    pub rpm: u32,
}

impl EcRequest<()> for EcRequestPwmSetFanTargetRpmV0 {
    fn command_id() -> EcCommands {
        EcCommands::PwmSetFanTargetRpm
    }
}

pub struct EcRequestPwmSetFanTargetRpmV1 {
    /// Fan RPM
    pub rpm: u32,
    /// Fan index
    pub fan_idx: u32,
}

impl EcRequest<()> for EcRequestPwmSetFanTargetRpmV1 {
    fn command_id() -> EcCommands {
        EcCommands::PwmSetFanTargetRpm
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(C, packed)]
pub struct EcRequestPwmSetFanDutyV0 {
    /// Duty cycle in percent
    pub percent: u32,
}

impl EcRequest<()> for EcRequestPwmSetFanDutyV0 {
    fn command_id() -> EcCommands {
        EcCommands::PwmSetFanDuty
    }
}

#[repr(C, packed)]
pub struct EcRequestPwmSetFanDutyV1 {
    /// Duty cycle in percent
    pub percent: u32,
    /// Fan index
    pub fan_idx: u32,
}

impl EcRequest<()> for EcRequestPwmSetFanDutyV1 {
    fn command_id() -> EcCommands {
        EcCommands::PwmSetFanDuty
    }
    fn command_version() -> u8 {
        1
    }
}

pub const PWM_MAX_DUTY: u16 = 0xFFFF;

pub fn percent_to_duty(percent: u8) -> u16 {
    let duty = percent as u32 * PWM_MAX_DUTY as u32;
    (duty / 100) as u16
}

pub fn duty_to_percent(duty: u16) -> u8 {
    let percent = duty as u32 * 100;
    (percent / PWM_MAX_DUTY as u32) as u8
}

#[repr(C, packed)]
pub struct EcRequestPwmSetDuty {
    /// Duty cycle, min 0, max 0xFFFF
    pub duty: u16,
    /// See enum PwmType
    pub pwm_type: u8,
    /// Type-specific index, or 0 if unique
    pub index: u8,
}

impl EcRequest<()> for EcRequestPwmSetDuty {
    fn command_id() -> EcCommands {
        EcCommands::PwmSetDuty
    }
}

#[repr(C, packed)]
pub struct EcRequestPwmGetDuty {
    /// See enum PwmType
    pub pwm_type: u8,
    /// Type-specific index, or 0 if unique
    pub index: u8,
}

#[repr(C, packed)]
pub struct EcResponsePwmGetDuty {
    /// Duty cycle, min 0, max 0xFFFF
    pub duty: u16,
}

impl EcRequest<EcResponsePwmGetDuty> for EcRequestPwmGetDuty {
    fn command_id() -> EcCommands {
        EcCommands::PwmGetDuty
    }
}

#[repr(u8)]
pub enum MotionSenseCmd {
    Dump = 0,
    Info = 1,
}

#[repr(C, packed)]
pub struct EcRequestMotionSenseDump {
    /// MotionSenseCmd::Dump
    pub cmd: u8,
    /// Maximal number of sensor the host is expecting.
    /// 0 means the host is only interested in the number
    /// of sensors controlled by the EC.
    pub max_sensor_count: u8,
}

#[repr(C, packed)]
pub struct EcResponseMotionSenseDump {
    /// Flags representing the motion sensor module
    pub module_flags: u8,

    /// Number of sensors managed directly by the EC
    pub sensor_count: u8,

    /// Sensor data is truncated if response_max is too small
    /// for holding all the data.
    pub sensor: [u8; 0],
}

impl EcRequest<EcResponseMotionSenseDump> for EcRequestMotionSenseDump {
    fn command_id() -> EcCommands {
        EcCommands::MotionSense
    }
    fn command_version() -> u8 {
        1
    }
}

#[derive(Debug, FromPrimitive, PartialEq)]
pub enum MotionSenseType {
    Accel = 0,
    Gyro = 1,
    Mag = 2,
    Prox = 3,
    Light = 4,
    Activity = 5,
    Baro = 6,
    Sync = 7,
    LightRgb = 8,
}

#[derive(Debug, FromPrimitive)]
pub enum MotionSenseLocation {
    Base = 0,
    Lid = 1,
    Camera = 2,
}

#[derive(Debug, FromPrimitive)]
pub enum MotionSenseChip {
    Kxcj9 = 0,
    Lsm6ds0 = 1,
    Bmi160 = 2,
    Si1141 = 3,
    Si1142 = 4,
    Si1143 = 5,
    Kx022 = 6,
    L3gd20h = 7,
    Bma255 = 8,
    Bmp280 = 9,
    Opt3001 = 10,
    Bh1730 = 11,
    Gpio = 12,
    Lis2dh = 13,
    Lsm6dsm = 14,
    Lis2de = 15,
    Lis2mdl = 16,
    Lsm6ds3 = 17,
    Lsm6dso = 18,
    Lng2dm = 19,
    Tcs3400 = 20,
    Lis2dw12 = 21,
    Lis2dwl = 22,
    Lis2ds = 23,
    Bmi260 = 24,
    Icm426xx = 25,
    Icm42607 = 26,
    Bma422 = 27,
    Bmi323 = 28,
    Bmi220 = 29,
    Cm32183 = 30,
    Veml3328 = 31,
}

#[repr(C, packed)]
pub struct EcRequestMotionSenseInfo {
    /// MotionSenseCmd::Info
    pub cmd: u8,
    /// Sensor index
    pub sensor_num: u8,
}

#[repr(C)]
pub struct EcResponseMotionSenseInfo {
    /// See enum MotionSenseInfo
    pub sensor_type: u8,
    /// See enum MotionSenseLocation
    pub location: u8,
    /// See enum MotionSenseChip
    pub chip: u8,
}

#[derive(Debug)]
pub struct MotionSenseInfo {
    pub sensor_type: MotionSenseType,
    pub location: MotionSenseLocation,
    pub chip: MotionSenseChip,
}

impl EcRequest<EcResponseMotionSenseInfo> for EcRequestMotionSenseInfo {
    fn command_id() -> EcCommands {
        EcCommands::MotionSense
    }
    fn command_version() -> u8 {
        1
    }
}

pub enum TabletModeOverride {
    Default = 0,
    ForceTablet = 1,
    ForceClamshell = 2,
}

#[repr(C, packed)]
pub struct EcRequestSetTabletMode {
    /// See TabletModeOverride
    pub mode: u8,
}

impl EcRequest<()> for EcRequestSetTabletMode {
    fn command_id() -> EcCommands {
        EcCommands::SetTabletMode
    }
}

#[repr(C, packed)]
pub struct EcRequestAutoFanCtrlV0 {}

impl EcRequest<()> for EcRequestAutoFanCtrlV0 {
    fn command_id() -> EcCommands {
        EcCommands::AutoFanCtrl
    }
}

#[repr(C, packed)]
pub struct EcRequestAutoFanCtrlV1 {
    /// Fan id
    pub fan_idx: u8,
}

impl EcRequest<()> for EcRequestAutoFanCtrlV1 {
    fn command_id() -> EcCommands {
        EcCommands::AutoFanCtrl
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(C, packed)]
pub struct EcRequestGpioSetV0 {
    pub name: [u8; 32],
    pub value: u8,
}

impl EcRequest<()> for EcRequestGpioSetV0 {
    fn command_id() -> EcCommands {
        EcCommands::GpioSet
    }
}

#[repr(C, packed)]
pub struct EcRequestGpioGetV0 {
    pub name: [u8; 32],
}

#[repr(C, packed)]
pub struct EcResponseGpioGetV0 {
    pub val: u8,
}

impl EcRequest<EcResponseGpioGetV0> for EcRequestGpioGetV0 {
    fn command_id() -> EcCommands {
        EcCommands::GpioGet
    }
    fn command_version() -> u8 {
        0
    }
}

pub enum GpioGetSubCommand {
    ByName = 0,
    Count = 1,
    Info = 2,
}

#[repr(C, packed)]
pub struct EcRequestGpioGetV1Count {
    pub subcmd: u8,
}

#[repr(C, packed)]
pub struct EcRequestGpioGetV1ByName {
    pub subcmd: u8,
    pub name: [u8; 32],
}

#[repr(C, packed)]
pub struct EcRequestGpioGetV1Info {
    pub subcmd: u8,
    pub index: u8,
}

#[repr(C)]
pub struct EcResponseGpioGetV1Info {
    pub val: u8,
    pub name: [u8; 32],
    pub flags: u32,
}

impl EcRequest<EcResponseGpioGetV0> for EcRequestGpioGetV1Count {
    fn command_id() -> EcCommands {
        EcCommands::GpioGet
    }
    fn command_version() -> u8 {
        1
    }
}
impl EcRequest<EcResponseGpioGetV0> for EcRequestGpioGetV1ByName {
    fn command_id() -> EcCommands {
        EcCommands::GpioGet
    }
    fn command_version() -> u8 {
        1
    }
}
impl EcRequest<EcResponseGpioGetV1Info> for EcRequestGpioGetV1Info {
    fn command_id() -> EcCommands {
        EcCommands::GpioGet
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(C, packed)]
pub struct EcRequestReboot {}

impl EcRequest<()> for EcRequestReboot {
    fn command_id() -> EcCommands {
        EcCommands::Reboot
    }
}

pub struct EcRequestConsoleSnapshot {}
impl EcRequest<()> for EcRequestConsoleSnapshot {
    fn command_id() -> EcCommands {
        EcCommands::ConsoleSnapshot
    }
}

pub enum ConsoleReadSubCommand {
    ConsoleReadNext = 0,
    ConsoleReadRecent = 1,
}

pub struct EcRequestConsoleRead {
    pub subcmd: u8,
}

impl EcRequest<()> for EcRequestConsoleRead {
    fn command_id() -> EcCommands {
        EcCommands::ConsoleRead
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(u8)]
pub enum ChargeStateCmd {
    GetState = 0,
    GetParam,
    SetParam,
    NumCmds,
}

#[repr(C, packed)]
pub struct EcRequestChargeStateGetV0 {
    pub cmd: u8,
    pub param: u32,
}

#[repr(C, packed)]
pub struct EcResponseChargeStateGetV0 {
    pub ac: u32,
    pub chg_voltage: u32,
    pub chg_current: u32,
    pub chg_input_current: u32,
    pub batt_state_of_charge: u32,
}

impl EcRequest<EcResponseChargeStateGetV0> for EcRequestChargeStateGetV0 {
    fn command_id() -> EcCommands {
        EcCommands::ChargeState
    }
    fn command_version() -> u8 {
        0
    }
}

pub struct EcRequestCurrentLimitV0 {
    /// Current limit in mA
    pub current: u32,
}

impl EcRequest<()> for EcRequestCurrentLimitV0 {
    fn command_id() -> EcCommands {
        EcCommands::ChargeCurrentLimit
    }
}

pub struct EcRequestCurrentLimitV1 {
    /// Current limit in mA
    pub current: u32,
    /// Battery state of charge is the minimum charge percentage at which
    /// the battery charge current limit will apply.
    /// When not set, the limit will apply regardless of state of charge.
    pub battery_soc: u8,
}

impl EcRequest<()> for EcRequestCurrentLimitV1 {
    fn command_id() -> EcCommands {
        EcCommands::ChargeCurrentLimit
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(C, packed)]
pub struct EcRequesetHibernationDelay {
    /// Seconds in G3 after EC turns off, 0 to read current
    pub seconds: u32,
}

#[repr(C, packed)]
pub struct EcResponseHibernationDelay {
    pub time_g3: u32,
    pub time_remaining: u32,
    /// How long to wait in G3 until turn off
    pub hibernation_delay: u32,
}

impl EcRequest<EcResponseHibernationDelay> for EcRequesetHibernationDelay {
    fn command_id() -> EcCommands {
        EcCommands::HibernationDelay
    }
}

#[repr(C, packed)]
pub struct EcRequestS0ixCounter {
    /// If 0x01 then reset the counter, otherwise get it
    pub flags: u32,
}

#[repr(C, packed)]
pub struct EcResponseS0ixCounter {
    pub s0ix_counter: u32,
}

pub const EC_S0IX_COUNTER_RESET: u32 = 0x01;

impl EcRequest<EcResponseS0ixCounter> for EcRequestS0ixCounter {
    fn command_id() -> EcCommands {
        EcCommands::S0ixCounter
    }
}

/// Supported features
#[derive(Debug, FromPrimitive)]
pub enum EcFeatureCode {
    /// This image contains a limited set of features. Another image
    /// in RW partition may support more features.
    Limited = 0,
    /// Commands for probing/reading/writing/erasing the flash in the
    /// EC are present.
    Flash = 1,
    /// Can control the fan speed directly.
    PwmFan = 2,
    /// Can control the intensity of the keyboard backlight.
    PwmKeyboardBacklight = 3,
    /// Support Google lightbar, introduced on Pixel.
    Lightbar = 4,
    /// Control of LEDs
    Led = 5,
    /// Exposes an interface to control gyro and sensors.
    /// The host goes through the EC to access these sensors.
    /// In addition, the EC may provide composite sensors, like lid angle.
    MotionSense = 6,
    /// The keyboard is controlled by the EC
    Keyboard = 7,
    /// The AP can use part of the EC flash as persistent storage.
    PersistentStorage = 8,
    /// The EC monitors BIOS port 80h, and can return POST codes.
    Port80 = 9,
    /// Thermal management: include TMP specific commands.
    /// Higher level than direct fan control.
    Thermal = 10,
    /// Can switch the screen backlight on/off
    BacklightSwitch = 11,
    /// Can switch the wifi module on/off
    WifiSwitch = 12,
    /// Monitor host events, through for example SMI or SCI
    HostEvents = 13,
    /// The EC exposes GPIO commands to control/monitor connected devices.
    Gpio = 14,
    /// The EC can send i2c messages to downstream devices.
    I2c = 15,
    /// Command to control charger are included
    Charger = 16,
    /// Simple battery support.
    Battery = 17,
    /// Support Smart battery protocol
    /// (Common Smart Battery System Interface Specification)
    SmartBattery = 18,
    /// EC can detect when the host hangs.
    HangDetect = 19,
    /// Report power information, for pit only
    Pmu = 20,
    /// Another Cros EC device is present downstream of this one
    SubMcu = 21,
    /// Support USB Power delivery (PD) commands
    UsbPd = 22,
    /// Control USB multiplexer, for audio through USB port for instance.
    UsbMux = 23,
    /// Motion Sensor code has an internal software FIFO
    MotionSenseFifo = 24,
    /// Support temporary secure vstore
    SecureVstore = 25,
    /// EC decides on USB-C SS mux state, muxes configured by host
    UsbcSsMuxVirtual = 26,
    /// EC has RTC feature that can be controlled by host commands
    Rtc = 27,
    /// The MCU exposes a Fingerprint sensor
    Fingerprint = 28,
    /// The MCU exposes a Touchpad
    Touchpad = 29,
    /// The MCU has RWSIG task enabled
    RwSig = 30,
    /// EC has device events support
    DeviceEvent = 31,
    /// EC supports the unified wake masks for LPC/eSPI systems
    UnifiedWakeMasks = 32,
    /// EC supports 64-bit host events
    HostEvent64 = 33,
    /// EC runs code in RAM (not in place, a.k.a. XIP)
    ExecInRam = 34,
    /// EC supports CEC commands
    Cec = 35,
    /// EC supports tight sensor timestamping.
    MotionSenseTightTimesStamps = 36,
    ///
    /// EC supports tablet mode detection aligned to Chrome and allows
    /// setting of threshold by host command using
    /// MOTIONSENSE_CMD_TABLET_MODE_LID_ANGLE.
    RefinedTabletModeHysteresis = 37,
    /// Early Firmware Selection ver.2. Enabled by CONFIG_VBOOT_EFS2.
    /// Note this is a RO feature. So, a query (EC_CMD_GET_FEATURES) should
    /// be sent to RO to be precise.
    Efs2 = 38,
    /// The MCU is a System Companion Processor (SCP).
    Scp = 39,
    /// The MCU is an Integrated Sensor Hub
    Ish = 40,
    /// New TCPMv2 TYPEC_ prefaced commands supported
    TypecCmd = 41,
    /// The EC will wait for direction from the AP to enter Type-C alternate
    /// modes or USB4.
    TypecRequireApModeEntry = 42,
    /// The EC will wait for an acknowledge from the AP after setting the
    /// mux.
    TypeCMuxRequireApAck = 43,
    /// The EC supports entering and residing in S4.
    S4Residency = 44,
    /// The EC supports the AP directing mux sets for the board.
    TypeCApMuxSet = 45,
    /// The EC supports the AP composing VDMs for us to send.
    TypeCApVdmSend = 46,
    /// The EC supports system safe mode panic recovery.
    SystemSafeMode = 47,
    /// The EC will reboot on runtime assertion failures.
    AssertReboots = 48,
    /// The EC image is built with tokenized logging enabled.
    TokenizedLogging = 49,
    /// The EC supports triggering an STB dump.
    AmdStbDump = 50,
    /// The EC supports memory dump commands.
    MemoryDump = 51,
    /// The EC supports DP2.1 capability
    Dp21 = 52,
    /// The MCU is System Companion Processor Core 1
    ScpC1 = 53,
    /// The EC supports UCSI PPM.
    UcsiPpm = 54,
}

pub struct EcRequestGetFeatures {}

pub struct EcResponseGetFeatures {
    pub flags: [u32; 2],
}

impl EcRequest<EcResponseGetFeatures> for EcRequestGetFeatures {
    fn command_id() -> EcCommands {
        EcCommands::GetFeatures
    }
}

#[repr(u8)]
pub enum RebootEcCmd {
    /// Cancel a pending reboot
    Cancel = 0,
    /// Jump to RO firmware without rebooting
    JumpRo = 1,
    /// Jump to RW firmware without rebooting
    JumpRw = 2,
    /// DEPRECATED: Was jump to RW-B
    DeprecatedJumpToRwB = 3,
    /// Cold reboot of the EC. Causes host reset as well
    ColdReboot = 4,
    /// Disable jumping until the next EC reboot
    DisableJump = 5,
    /// Hibernate the EC
    Hibernate = 6,
    /// DEPRECATED: Hibernate EC and clears AP_IDLE flag.
    /// Use EC_REBOOT_HIBERNATE and EC_REBOOT_FLAG_CLEAR_AP_IDLE, instead.
    DeprecatedClearApOff = 7,
    ///  Cold-reboot and don't boot AP
    ColdApOff = 8,
    /// Do nothing but apply the flags
    NoOp = 9,
}

#[repr(u8)]
pub enum RebootEcFlags {
    /// Default
    None = 0x00,
    DeprecatedRecoveryRequest = 0x01,
    /// Reboot after AP shutdown
    OnApShutdown = 0x02,
    /// Switch RW slot
    SwitchRwSlot = 0x04,
    /// Clear AP_IDLE flag
    ClearApidle = 0x08,
}

pub struct EcRequestRebootEc {
    /// See enum RebootEcCmd
    pub cmd: u8,
    pub flags: u8,
}

impl EcRequest<()> for EcRequestRebootEc {
    fn command_id() -> EcCommands {
        EcCommands::RebootEc
    }
    fn command_version() -> u8 {
        0
    }
}

#[repr(C, packed)]
pub struct EcRequestUsbPdPowerInfo {
    pub port: u8,
}

#[repr(C, packed)]
pub struct _UsbChargeMeasures {
    pub voltage_max: u16,
    pub voltage_now: u16,
    pub current_max: u16,
    pub current_lim: u16,
}

#[repr(C, packed)]
pub struct EcResponseUsbPdPowerInfo {
    pub role: u8,          // UsbPowerRoles
    pub charging_type: u8, // UsbChargingType
    pub dualrole: u8,      // I think this is a boolean?
    pub reserved1: u8,
    pub meas: _UsbChargeMeasures,
    pub max_power: u32,
}

impl EcRequest<EcResponseUsbPdPowerInfo> for EcRequestUsbPdPowerInfo {
    fn command_id() -> EcCommands {
        EcCommands::UsbPdPowerInfo
    }
}

#[repr(usize)]
#[derive(Debug, FromPrimitive)]
pub enum EcResetFlag {
    /// Other known reason
    Other,
    /// Reset pin asserted
    ResetPin,
    /// Brownout
    Brownout,
    /// Power-on reset
    PowerOn,
    /// Watchdog timer reset
    Watchdog,
    /// Soft reset trigger by core
    Soft,
    /// Wake from hibernate
    Hibernate,
    /// RTC alarm wake
    RtcAlarm,
    /// Wake pin triggered wake
    WakePin,
    /// Low battery triggered wake
    LowBattery,
    /// Jumped directly to this image
    Sysjump,
    /// Hard reset from software
    Hard,
    /// Do not power on AP
    APOff,
    /// Some reset flags preserved from previous boot
    Preserved,
    /// USB resume triggered wake
    UsbResume,
    /// USB Type-C debug cable
    Rdd,
    /// Fixed Reset Functionality
    Rbox,
    /// Security threat
    Security,
    /// AP experienced a watchdog reset
    ApWatchdog,
    /// Do not select RW in EFS. This enables PD in RO for Chromebox
    StayInRo,
    /// Jumped to this image by EFS
    Efs,
    /// Leave alone AP
    ApIdle,
    /// EC had power, then was reset
    InitialPwr,
    Count,
}

#[repr(u16)]
#[derive(Debug, FromPrimitive)]
pub enum ResetCause {
    ResetUnknown = 0x0000,
    /// Custom reason defined by a board.c or baseboard.c file
    ResetBoardCustom,
    /// Believe that the AP has hung
    ResetHangReboot,
    /// Reset by EC console command
    ResetConsoleCommand,
    /// Reset by EC host command
    ResetHostCommand,
    /// Keyboard module reset key combination
    ResetKeyboardSysReset,
    /// Keyboard module warm reboot
    ResetKeyboardWarmBoot,
    /// Debug module warm reboot
    ResetDebugWarmBoot,
    /// I cannot self-terminate. You must lower me into the steel
    ResetApReq,
    /// Reset as side-effect of startup sequence
    ResetInit,
    /// EC detected an AP watchdog event
    ResetApWatchdog,

    ShutdownPowerFail = 0x8000,
    /// Forcing a shutdown as part of EC initialization
    ShutdownInit,
    /// Custom reason on a per-board basis.
    ShutdownBoardCustom,
    /// This is a reason to inhibit startup, not cause shut down.
    ShutdownBatteryInhibit,
    /// A power_wait_signal is being asserted
    ShutdownWait,
    /// Critical battery level.
    ShutdownBatteryCritical,
    /// Because you told me to.
    ShutdownConsoleCommand,
    /// Forcing a shutdown to effect entry to G3.
    ShutdownG3,
    /// Force shutdown due to over-temperature.
    ShutdownThermal,
    /// Force a chipset shutdown from the power button through EC
    ShutdownButton,
}

#[repr(C)]
pub struct EcRequestGetUptimeInfo {}

#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
pub struct ApResetLogEntry {
    pub reset_cause: u16,
    pub reserved: u16,
    pub reset_time_ms: u32,
}

#[repr(C, packed)]
#[derive(Debug)]
pub struct EcResponseGetUptimeInfo {
    pub time_since_ec_boot: u32,
    /// How often the AP was reset by the EC since last EC boot
    /// The first AP boot may count as more than one
    pub ap_resets_since_ec_boot: u32,
    pub ec_reset_flags: u32,
    pub recent_ap_resets: [ApResetLogEntry; 4],
}

impl EcRequest<EcResponseGetUptimeInfo> for EcRequestGetUptimeInfo {
    fn command_id() -> EcCommands {
        EcCommands::GetUptimeInfo
    }
}

#[repr(C, packed)]
pub struct EcRequestAdcRead {
    /// ADC Channel, specific to each mainboard schematic
    pub adc_channel: u8,
}

pub struct EcResponseAdcRead {
    pub adc_value: i32,
}

impl EcRequest<EcResponseAdcRead> for EcRequestAdcRead {
    fn command_id() -> EcCommands {
        EcCommands::AdcRead
    }
}

#[repr(C)]
pub struct EcRequestApReset {}

impl EcRequest<()> for EcRequestApReset {
    fn command_id() -> EcCommands {
        EcCommands::ApReset
    }
}

#[repr(C)]
pub struct EcRequestRebootApOnG3V0 {}

impl EcRequest<()> for EcRequestRebootApOnG3V0 {
    fn command_id() -> EcCommands {
        EcCommands::RebootApOnG3
    }
    fn command_version() -> u8 {
        0
    }
}

#[repr(C)]
pub struct EcRequestRebootApOnG3V1 {
    /// Delay in seconds after entering G3 state
    pub delay: u32,
}

impl EcRequest<()> for EcRequestRebootApOnG3V1 {
    fn command_id() -> EcCommands {
        EcCommands::RebootApOnG3
    }
    fn command_version() -> u8 {
        1
    }
}

// TODO: Actually 128, but if we go above ~80 EC returns REQUEST_TRUNCATED
// At least when I use the portio driver
pub const EC_RGBKBD_MAX_KEY_COUNT: usize = 64;

#[repr(C, packed)]
#[derive(Default, Clone, Copy, Debug)]
pub struct RgbS {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

#[repr(C, packed)]
pub struct EcRequestRgbKbdSetColor {
    /// Specifies the starting key ID whose color is being changed
    pub start_key: u8,
    /// Specifies # of elements in color
    pub length: u8,
    /// RGB color data array of length up to MAX_KEY_COUNT
    pub color: [RgbS; EC_RGBKBD_MAX_KEY_COUNT],
}

#[repr(C, packed)]
pub struct EcResponseRgbKbdSetColor {}

impl EcRequest<EcResponseRgbKbdSetColor> for EcRequestRgbKbdSetColor {
    fn command_id() -> EcCommands {
        EcCommands::RgbKbdSetColor
    }
}

// --- Framework Specific commands ---

#[repr(C, packed)]
pub struct EcRequestFlashNotify {
    // TODO: Use types to help build the flags
    pub flags: u8,
}

#[repr(C, packed)]
pub struct EcResponseFlashNotify {}

impl EcRequest<EcResponseFlashNotify> for EcRequestFlashNotify {
    fn command_id() -> EcCommands {
        EcCommands::FlashNotified
    }
}

#[repr(C, packed)]
pub struct KeyboardMatrixMap {
    pub row: u8,
    pub col: u8,
    pub scanset: u16,
}
#[repr(C, packed)]
pub struct EcRequestUpdateKeyboardMatrix {
    pub num_items: u32,
    pub write: u32,
    pub scan_update: [KeyboardMatrixMap; 1],
}
#[repr(C, packed)]
pub struct EcResponseUpdateKeyboardMatrix {
    pub num_items: u32,
    pub write: u32,
    pub scan_update: [KeyboardMatrixMap; 32],
}

impl EcRequest<EcResponseUpdateKeyboardMatrix> for EcRequestUpdateKeyboardMatrix {
    fn command_id() -> EcCommands {
        EcCommands::UpdateKeyboardMatrix
    }
}

#[repr(C, packed)]
pub struct EcRequestChassisOpenCheck {}

#[repr(C, packed)]
pub struct EcResponseChassisOpenCheck {
    pub status: u8,
}

impl EcRequest<EcResponseChassisOpenCheck> for EcRequestChassisOpenCheck {
    fn command_id() -> EcCommands {
        EcCommands::ChassisOpenCheck
    }
}

#[repr(C, packed)]
pub struct EcRequestChassisIntrusionControl {
    pub clear_magic: u8,
    pub clear_chassis_status: u8,
}

#[repr(C, packed)]
pub struct EcResponseChassisIntrusionControl {
    pub chassis_ever_opened: u8,
    pub coin_batt_ever_remove: u8,
    pub total_open_count: u8,
    pub vtr_open_count: u8,
}

impl EcRequest<EcResponseChassisIntrusionControl> for EcRequestChassisIntrusionControl {
    fn command_id() -> EcCommands {
        EcCommands::ChassisIntrusion
    }
}

#[repr(u8)]
pub enum RetimerControlMode {
    /// AMD and Intel
    EntryFwUpdateMode = 0x01,
    /// AMD and Intel
    ExitFwUpdateMode = 0x02,
    /// Intel only
    EnableComplianceMode = 0x04,
    /// Intel only
    DisableComplianceMode = 0x08,
    /// Check if in FwUpdateMode
    CheckStatus = 0x80,
}

#[repr(C, packed)]
pub struct EcRequestRetimerControl {
    /// 0 (right) or 1 (left)
    pub controller: u8,
    /// See RetimerControlMode
    pub mode: u8,
}

#[repr(C, packed)]
pub struct EcResponseRetimerControlStatus {
    pub status: u8,
}

impl EcRequest<EcResponseRetimerControlStatus> for EcRequestRetimerControl {
    fn command_id() -> EcCommands {
        EcCommands::RetimerControl
    }
}

#[repr(C, packed)]
pub struct EcRequestReadPdVersionV0 {}

#[repr(C, packed)]
pub struct _EcResponseReadPdVersionV0 {
    pub controller01: [u8; 8],
    pub controller23: [u8; 8],
}

impl EcRequest<_EcResponseReadPdVersionV0> for EcRequestReadPdVersionV0 {
    fn command_id() -> EcCommands {
        EcCommands::ReadPdVersion
    }
    fn command_version() -> u8 {
        0
    }
}

#[repr(C, packed)]
pub struct EcRequestReadPdVersionV1 {}
#[repr(C, packed)]
pub struct _EcResponseReadPdVersionV1 {
    pub pd_chip_count: u8,
    pub pd_controllers: [u8; 0],
}

impl EcRequest<_EcResponseReadPdVersionV1> for EcRequestReadPdVersionV1 {
    fn command_id() -> EcCommands {
        EcCommands::ReadPdVersion
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(C, packed)]
pub struct EcRequestGetPdPortState {
    pub port: u8,
}

#[repr(C, packed)]
pub struct EcResponseGetPdPortState {
    pub c_state: u8,
    pub pd_state: u8,
    pub power_role: u8,
    pub data_role: u8,
    pub vconn: u8,
    pub epr_active: u8,
    pub epr_support: u8,
    pub cc_polarity: u8,
    pub voltage: u16,
    pub current: u16,
    pub active_port: u8,
    pub pd_alt_mode_status: u8,
}

impl EcRequest<EcResponseGetPdPortState> for EcRequestGetPdPortState {
    fn command_id() -> EcCommands {
        EcCommands::GetPdPortState
    }
}

#[repr(C, packed)]
pub struct EcRequestPrivacySwitches {}

#[repr(C, packed)]
pub struct EcResponsePrivacySwitches {
    pub microphone: u8,
    pub camera: u8,
}

impl EcRequest<EcResponsePrivacySwitches> for EcRequestPrivacySwitches {
    fn command_id() -> EcCommands {
        EcCommands::PriavcySwitchesCheckMode
    }
}

#[repr(u8)]
pub enum DeckStateMode {
    ReadOnly = 0x00,
    Required = 0x01,
    ForceOn = 0x02,
    ForceOff = 0x04,
}

#[repr(C, packed)]
pub struct EcRequestDeckState {
    pub mode: DeckStateMode,
}

#[repr(C, packed)]
pub struct EcResponseDeckState {
    pub board_id: [u8; INPUT_DECK_SLOTS],
    pub deck_state: u8,
}

impl EcRequest<EcResponseDeckState> for EcRequestDeckState {
    fn command_id() -> EcCommands {
        EcCommands::CheckDeckState
    }
}

// TODO
#[repr(C, packed)]
pub struct EcRequestUefiAppMode {
    pub enable: u8,
}

impl EcRequest<()> for EcRequestUefiAppMode {
    fn command_id() -> EcCommands {
        EcCommands::UefiAppMode
    }
}

#[repr(C, packed)]
pub struct EcRequestUefiAppBtnStatus {}

#[repr(C, packed)]
pub struct EcResponseUefiAppBtnStatus {
    pub status: u8,
}

impl EcRequest<EcResponseUefiAppBtnStatus> for EcRequestUefiAppBtnStatus {
    fn command_id() -> EcCommands {
        EcCommands::UefiAppBtnStatus
    }
}

#[derive(Debug)]
pub enum ExpansionByStates {
    ModuleEnabled = 0x01,
    ModuleFault = 0x02,
    HatchSwitchClosed = 0x04,
}
#[derive(Debug)]
pub enum ExpansionBayBoard {
    DualInterposer,
    SingleInterposer,
    UmaFans,
}

#[derive(Debug)]
pub enum ExpansionBayIssue {
    NoModule,
    BadConnection(u8, u8),
}

// pub to disable unused warnings
pub const BOARD_VERSION_0: u8 = 0;
pub const BOARD_VERSION_1: u8 = 1;
pub const BOARD_VERSION_2: u8 = 2;
pub const BOARD_VERSION_3: u8 = 3;
pub const BOARD_VERSION_4: u8 = 4;
pub const BOARD_VERSION_5: u8 = 5;
pub const BOARD_VERSION_6: u8 = 6;
pub const BOARD_VERSION_7: u8 = 7;
pub const BOARD_VERSION_8: u8 = 8;
pub const BOARD_VERSION_9: u8 = 9;
pub const BOARD_VERSION_10: u8 = 10;
pub const BOARD_VERSION_11: u8 = 11;
pub const BOARD_VERSION_12: u8 = 12;
pub const BOARD_VERSION_13: u8 = 13;
pub const BOARD_VERSION_14: u8 = 14;
pub const BOARD_VERSION_15: u8 = 15;

#[repr(C, packed)]
pub struct EcRequestExpansionBayStatus {}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseExpansionBayStatus {
    pub state: u8,
    pub board_id_0: u8,
    pub board_id_1: u8,
}

impl EcResponseExpansionBayStatus {
    pub fn module_enabled(&self) -> bool {
        self.state & (ExpansionByStates::ModuleEnabled as u8) != 0
    }
    pub fn module_fault(&self) -> bool {
        self.state & (ExpansionByStates::ModuleFault as u8) != 0
    }
    pub fn hatch_switch_closed(&self) -> bool {
        self.state & (ExpansionByStates::HatchSwitchClosed as u8) != 0
    }
    pub fn expansion_bay_board(&self) -> Result<ExpansionBayBoard, ExpansionBayIssue> {
        match (self.board_id_0, self.board_id_1) {
            (BOARD_VERSION_12, BOARD_VERSION_12) => Ok(ExpansionBayBoard::DualInterposer),
            (BOARD_VERSION_13, BOARD_VERSION_15) => Ok(ExpansionBayBoard::UmaFans),
            (BOARD_VERSION_11, BOARD_VERSION_15) => Ok(ExpansionBayBoard::SingleInterposer),
            (BOARD_VERSION_15, BOARD_VERSION_15) => Err(ExpansionBayIssue::NoModule),
            // Invalid board IDs. Something wrong, could be interposer not connected
            _ => Err(ExpansionBayIssue::BadConnection(
                self.board_id_0,
                self.board_id_1,
            )),
        }
    }
}

impl EcRequest<EcResponseExpansionBayStatus> for EcRequestExpansionBayStatus {
    fn command_id() -> EcCommands {
        EcCommands::ExpansionBayStatus
    }
}

pub const DIAGNOSTICS_START: usize = 0;
pub const DIAGNOSTICS_HW_NO_BATTERY: usize = 1;
pub const DIAGNOSTICS_HW_PGOOD_3V5V: usize = 2;
pub const DIAGNOSTICS_VCCIN_AUX_VR: usize = 3;
pub const DIAGNOSTICS_SLP_S4: usize = 4;
pub const DIAGNOSTICS_HW_PGOOD_VR: usize = 5;

// Lotus: Start
pub const DIAGNOSTICS_INPUT_MODULE_FAULT: usize = 6;
pub const DIAGNOSTICS_NO_LEFT_FAN: usize = 7;
pub const DIAGNOSTICS_NO_RIGHT_FAN: usize = 8;
pub const DIAGNOSTICS_GPU_MODULE_FAULT: usize = 9;
// Lotus: End
// Azalea: Start
pub const DIAGNOSTICS_TOUCHPAD: usize = 6;
pub const DIAGNOSTICS_AUDIO_DAUGHTERBOARD: usize = 7;
pub const DIAGNOSTICS_THERMAL_SENSOR: usize = 8;
pub const DIAGNOSTICS_NOFAN: usize = 9;
// Azalea: End

// Different on azalea and lotus
// pub const DIAGNOSTICS_NO_S0: usize = 10;
// pub const DIAGNOSTICS_NO_DDR: usize = 11;
// pub const DIAGNOSTICS_NO_EDP: usize = 12;
// pub const DIAGNOSTICS_HW_FINISH: usize = 13;
/*BIOS BITS*/
// pub const DIAGNOSTICS_BIOS_BIT0: usize = 18;
// pub const DIAGNOSTICS_BIOS_BIT1: usize = 19;
// pub const DIAGNOSTICS_BIOS_BIT2: usize = 21;
// pub const DIAGNOSTICS_BIOS_BIT3: usize = 22;
// pub const DIAGNOSTICS_BIOS_BIT4: usize = 23;
// pub const DIAGNOSTICS_BIOS_BIT5: usize = 24;
// pub const DIAGNOSTICS_BIOS_BIT6: usize = 25;
// pub const DIAGNOSTICS_BIOS_BIT7: usize = 26;

#[repr(C, packed)]
pub struct EcRequestGetHwDiag {}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseGetHwDiag {
    pub hw_diag: u32,
    pub bios_complete: u8,
    pub device_complete: u8,
}

impl EcResponseGetHwDiag {
    pub fn fan_fault(&self) -> (bool, bool) {
        (
            self.hw_diag & (1 << DIAGNOSTICS_NO_LEFT_FAN) != 0,
            self.hw_diag & (1 << DIAGNOSTICS_NO_RIGHT_FAN) != 0,
        )
    }
}
impl fmt::Display for EcResponseGetHwDiag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (left_fan, right_fan) = self.fan_fault();
        write!(
            f,
            "BIOS Done: {}, Fan Fault Left: {}, Right: {}",
            self.bios_complete != 0,
            left_fan,
            right_fan
        )
    }
}

impl EcRequest<EcResponseGetHwDiag> for EcRequestGetHwDiag {
    fn command_id() -> EcCommands {
        EcCommands::GetHwDiag
    }
}

#[repr(u8)]
pub enum ChargeLimitControlModes {
    /// Disable all settings, handled automatically
    Disable = 0x01,
    /// Set maxiumum and minimum percentage
    Set = 0x02,
    /// Get current setting
    /// ATTENTION!!! This is the only mode that will return a response
    Get = 0x08,
    /// Allow charge to full this time
    Override = 0x80,
}

#[repr(C, packed)]
pub struct EcRequestChargeLimitControl {
    pub modes: u8,
    pub max_percentage: u8,
    pub min_percentage: u8,
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseChargeLimitControl {
    pub max_percentage: u8,
    pub min_percentage: u8,
}

impl EcRequest<EcResponseChargeLimitControl> for EcRequestChargeLimitControl {
    fn command_id() -> EcCommands {
        EcCommands::ChargeLimitControl
    }
}

/// Configure the behavior of the charge limit control.
/// TODO: Use this
pub const EC_CHARGE_LIMIT_RESTORE: u8 = 0x7F;

#[repr(C, packed)]
pub struct EcRequestDisablePs2Emulation {
    pub disable: u8,
}

impl EcRequest<()> for EcRequestDisablePs2Emulation {
    fn command_id() -> EcCommands {
        EcCommands::DisablePs2Emulation
    }
}

#[repr(u8)]
#[derive(Debug, FromPrimitive)]
pub enum FpLedBrightnessLevel {
    High = 0,
    Medium = 1,
    Low = 2,
    UltraLow = 3,
    /// Custom: Only get, never set
    Custom = 0xFE,
    Auto = 0xFF,
}

#[repr(C, packed)]
pub struct EcRequestFpLedLevelControlV0 {
    /// See enum FpLedBrightnessLevel
    pub set_level: u8,
    /// Boolean. >1 to get the level
    pub get_level: u8,
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseFpLedLevelControlV0 {
    /// Current brightness, 1-100%
    pub percentage: u8,
}

impl EcRequest<EcResponseFpLedLevelControlV0> for EcRequestFpLedLevelControlV0 {
    fn command_id() -> EcCommands {
        EcCommands::FpLedLevelControl
    }
    fn command_version() -> u8 {
        0
    }
}

#[repr(C, packed)]
pub struct EcRequestFpLedLevelControlV1 {
    /// Percentage 1-100
    pub set_percentage: u8,
    /// Boolean. >1 to get the level
    pub get_level: u8,
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseFpLedLevelControlV1 {
    /// Current brightness, 1-100%
    pub percentage: u8,
    /// Requested level. See enum FpLedBrightnessLevel
    pub level: u8,
}

impl EcRequest<EcResponseFpLedLevelControlV1> for EcRequestFpLedLevelControlV1 {
    fn command_id() -> EcCommands {
        EcCommands::FpLedLevelControl
    }
    fn command_version() -> u8 {
        1
    }
}

#[repr(C, packed)]
pub struct EcRequestGetGpuSerial {
    pub idx: u8,
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseGetGpuSerial {
    pub idx: u8,
    pub valid: u8,
    pub serial: [u8; 20],
}

impl EcRequest<EcResponseGetGpuSerial> for EcRequestGetGpuSerial {
    fn command_id() -> EcCommands {
        EcCommands::GetGpuSerial
    }
}

#[repr(C, packed)]
pub struct EcRequestGetGpuPcie {}

#[repr(u8)]
#[derive(Debug, FromPrimitive)]
pub enum GpuPcieConfig {
    /// PCIe 8x1
    Pcie8x1 = 0,
    /// PCIe 4x1
    Pcie4x1 = 1,
    /// PCIe 4x2
    Pcie4x2 = 2,
}

#[repr(u8)]
#[derive(Debug, FromPrimitive, PartialEq)]
pub enum GpuVendor {
    Initializing = 0x00,
    FanOnly = 0x01,
    GpuAmdR23M = 0x02,
    SsdHolder = 0x03,
    PcieAccessory = 0x4,
    NvidiaGn22 = 0x5,
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseGetGpuPcie {
    pub gpu_pcie_config: u8,
    pub gpu_vendor: u8,
}

impl EcRequest<EcResponseGetGpuPcie> for EcRequestGetGpuPcie {
    fn command_id() -> EcCommands {
        EcCommands::GetGpuPcie
    }
}

#[repr(u8)]
pub enum SetGpuSerialMagic {
    /// 7700S config magic value
    WriteGPUConfig = 0x0D,
    /// SSD config magic value
    WriteSSDConfig = 0x55,
}

#[repr(C, packed)]
pub struct EcRequestSetGpuSerial {
    pub magic: u8,
    pub idx: u8,
    pub serial: [u8; 20],
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseSetGpuSerial {
    pub valid: u8,
}

impl EcRequest<EcResponseSetGpuSerial> for EcRequestSetGpuSerial {
    fn command_id() -> EcCommands {
        EcCommands::ProgramGpuEeprom
    }
}

#[repr(u8)]
#[derive(Debug, Clone, Copy)]
pub enum BoardIdType {
    /// Mainboard - any system
    Mainboard = 0,
    /// Power button board - Framework 12
    PowerButtonBoard = 1,
    /// Touchpad - Framework 12, 13, 16
    Touchpad = 2,
    /// Audio Board - Framework 12, 13
    AudioBoard = 3,
    /// dGPU board - Framework 16
    DGpu0 = 4,
    /// dGPU board - Framework 16
    DGpu1 = 5,
}

#[repr(C, packed)]
pub struct EcRequestReadBoardId {
    /// See BoardIdType
    pub board_id_type: u8,
}

#[repr(C, packed)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct EcResponseReadBoardId {
    /// Board ID: -1 invalid, 0–14 valid, 15 not present
    pub board_id: i8,
}

impl EcRequest<EcResponseReadBoardId> for EcRequestReadBoardId {
    fn command_id() -> EcCommands {
        EcCommands::ReadBoardId
    }
}