1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Low-level chip manager
use crate::errors::CommError as Error;
use core::fmt::Debug;
use crate::socket::Socket;
use crate::transfer::Xfer;
mod chip_access;
pub(crate) mod constants;
mod event_listener;
mod net_types;
mod requests;
mod responses;
use crate::{debug, error, trace};
use chip_access::ChipAccess;
#[cfg(feature = "experimental-ota")]
pub use constants::OtaUpdateError;
#[cfg(feature = "wep")]
pub use constants::WepKeyIndex;
pub use constants::{AuthType, PingError, SocketError, WifiChannel, WifiConnError, WifiConnState};
use constants::{IpCode, Regs, WifiRequest, WifiResponse};
#[cfg(feature = "flash-rw")]
pub(crate) use constants::FLASH_PAGE_SIZE;
#[cfg(feature = "experimental-ota")]
pub(crate) use constants::{OtaRequest, OtaResponse, OtaUpdateStatus};
pub(crate) use constants::{BootMode, PRNG_DATA_LENGTH, SOCKET_BUFFER_MAX_LENGTH};
#[cfg(feature = "ssl")]
pub(crate) use self::{
constants::{SslRequest, SslResponse},
net_types::SslCallbackInfo,
};
#[cfg(feature = "ssl")]
pub use self::{
constants::{SslCertExpiryOpt, SslCipherSuite},
net_types::{SslSockConfig, SslSockOpts},
};
#[cfg(feature = "experimental-ecc")]
pub use self::{
constants::EccRequestType,
net_types::{EccInfo, EccPoint, EcdhInfo, EcdsaSignInfo},
};
#[cfg(feature = "experimental-ecc")]
pub(crate) use net_types::EccRequest;
pub use net_types::{
AccessPoint, Credentials, HostName, MacAddress, ProvisioningInfo, S8Password, S8Username,
SocketOptions, Ssid, TcpSockOpts, UdpSockOpts, WpaKey,
};
#[cfg(feature = "wep")]
pub use net_types::WepKey;
#[cfg(feature = "ethernet")]
pub(crate) use net_types::EthernetRxInfo;
#[cfg(feature = "ethernet")]
pub use constants::MAX_TX_ETHERNET_PACKET_SIZE;
use requests::*;
use responses::*;
pub use responses::{ConnectionInfo, FirmwareInfo, IPConf, ScanResult};
use core::net::{Ipv4Addr, SocketAddrV4};
/// HIF Response Group.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, PartialEq, Default)]
pub(crate) enum HifGroup {
#[default]
Unhandled,
Wifi(WifiResponse),
Ip(IpCode),
#[cfg(feature = "experimental-ota")]
Ota(OtaResponse),
#[cfg(feature = "ssl")]
Ssl(SslResponse),
}
/// HIF Request Group.
#[derive(Copy, Clone)]
enum HifRequest {
Wifi(WifiRequest),
Ip(IpCode),
#[cfg(feature = "experimental-ota")]
Ota(OtaRequest),
#[cfg(feature = "ssl")]
Ssl(SslRequest),
}
/// Implementation to convert `HifRequest` to `u8` value.
impl From<HifRequest> for u8 {
fn from(v: HifRequest) -> Self {
match v {
HifRequest::Wifi(_) => 1,
HifRequest::Ip(_) => 2,
#[cfg(feature = "experimental-ota")]
HifRequest::Ota(_) => 4,
#[cfg(feature = "ssl")]
HifRequest::Ssl(_) => 5,
}
}
}
/// Implementation to convert `[u8; 2]` array to `HifGroup` value.
impl From<[u8; 2]> for HifGroup {
fn from(v: [u8; 2]) -> Self {
match v[0] {
1 => Self::Wifi(v[1].into()),
2 => Self::Ip(v[1].into()),
#[cfg(feature = "experimental-ota")]
4 => Self::Ota(v[1].into()),
#[cfg(feature = "ssl")]
5 => Self::Ssl(v[1].into()),
_ => Self::Unhandled,
}
}
}
/// Implementation to convert `HifGroup` to `u8` value.
impl From<HifGroup> for u8 {
fn from(v: HifGroup) -> Self {
match v {
HifGroup::Wifi(_) => 1,
HifGroup::Ip(_) => 2,
#[cfg(feature = "experimental-ota")]
HifGroup::Ota(_) => 4,
#[cfg(feature = "ssl")]
HifGroup::Ssl(_) => 5,
_ => 0xFF,
}
}
}
fn hif_header_parse(hdr: [u8; 4]) -> Result<(HifGroup, u16), Error> {
let code: [u8; 2] = hdr[..2].try_into().unwrap();
let len = u16::from_le_bytes(hdr[2..].try_into().unwrap());
Ok((code.into(), len))
}
const HIF_HEADER_OFFSET: usize = 8;
const ETHERNET_HEADER_LENGTH: usize = 14;
const ETHERNET_HEADER_OFFSET: usize = 34;
const IP_PACKET_OFFSET: usize = ETHERNET_HEADER_LENGTH + ETHERNET_HEADER_OFFSET; // - HIF_HEADER_OFFSET;
const HIF_SEND_RETRIES: usize = 1000;
#[cfg(feature = "flash-rw")]
const FLASH_REG_READ_RETRIES: usize = 10;
#[cfg(feature = "flash-rw")]
const FLASH_DUMMY_VALUE: u32 = 0x1084;
const OTP_REG_ADDR_BITS: u32 = 0x3_0000;
const DEFAULT_CHIP_CFG: u32 = 0x102; // Reserved (0x100) + ENABLE_PMU bit (0x02)
// todo this needs to be used
#[allow(dead_code)]
const TCP_SOCK_MAX: usize = 7;
#[allow(dead_code)]
const UDP_SOCK_MAX: usize = 4;
#[allow(dead_code)]
const MAX_SOCKET: usize = TCP_SOCK_MAX + UDP_SOCK_MAX;
pub trait EventListener {
fn on_rssi(&mut self, level: i8);
fn on_resolve(&mut self, ip: Ipv4Addr, host: &str);
fn on_default_connect(&mut self, status: WifiConnError);
fn on_dhcp(&mut self, conf: IPConf);
fn on_connstate_changed(&mut self, state: WifiConnState, err: WifiConnError);
fn on_connection_info(&mut self, info: ConnectionInfo);
fn on_scan_result(&mut self, result: ScanResult);
fn on_scan_done(&mut self, num_aps: u8, err: WifiConnError);
fn on_system_time(&mut self, year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8);
fn on_ip_conflict(&mut self, ip: Ipv4Addr);
fn on_ping(
&mut self,
ip: Ipv4Addr,
token: u32,
rtt: u32,
num_successful: u16,
num_failed: u16,
error: PingError,
);
fn on_bind(&mut self, sock: Socket, err: SocketError);
fn on_listen(&mut self, sock: Socket, err: SocketError);
fn on_accept(
&mut self,
address: SocketAddrV4,
listen_socket: Socket,
accepted_socket: Socket,
data_offset: u16,
);
fn on_connect(&mut self, socket: Socket, err: SocketError);
fn on_send_to(&mut self, socket: Socket, len: i16);
fn on_send(&mut self, socket: Socket, len: i16);
fn on_recv(&mut self, socket: Socket, address: SocketAddrV4, data: &[u8], err: SocketError);
fn on_recvfrom(&mut self, socket: Socket, address: SocketAddrV4, data: &[u8], err: SocketError);
fn on_prng(&mut self, data: &[u8]);
fn on_provisioning(&mut self, ssid: Ssid, key: WpaKey, security: AuthType, status: bool);
#[cfg(feature = "experimental-ota")]
fn on_ota(&mut self, status: OtaUpdateStatus, error: OtaUpdateError);
#[cfg(feature = "ssl")]
fn on_ssl(
&mut self,
ssl_res: SslResponse,
cipher_suite: Option<u32>,
#[cfg(feature = "experimental-ecc")] ecc_req: Option<EccRequest>,
);
#[cfg(feature = "ethernet")]
fn on_eth(&mut self, packet_size: u16, data_offset: u16, hif_address: u32);
}
pub struct Manager<X: Xfer> {
// cached addresses
not_a_reg_ctrl_4_dma: u32, // todo: make this dynamic/proper
chip: ChipAccess<X>,
}
/// The stages of the boot process
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub(crate) enum BootStage {
Start,
StartBootrom,
Stage2,
Stage3,
Stage4,
StageStartFirmware,
FinishFirmwareBoot,
}
/// Stores boot state for the long-running boot
/// process
pub(crate) struct BootState {
stage: BootStage,
loop_value: u32,
mode: BootMode,
}
impl BootState {
pub fn new(mode: BootMode) -> Self {
Self {
stage: BootStage::Start,
loop_value: 0,
mode,
}
}
}
impl<X: Xfer> Manager<X> {
pub fn from_xfer(xfer: X) -> Self {
Self {
not_a_reg_ctrl_4_dma: 0xbf0000,
chip: ChipAccess::new(xfer),
}
}
#[cfg(test)]
pub fn set_unit_test_mode(&mut self) {
self.chip.set_unit_test_mode();
}
// Todo: remove this
pub fn delay_us(&mut self, delay: u32) {
self.chip.delay_us(delay);
}
pub fn set_crc_state(&mut self, value: bool) {
self.chip.crc = value;
}
pub fn chip_id(&mut self) -> Result<u32, Error> {
self.chip.single_reg_read(Regs::ChipId.into())
}
pub fn chip_rev(&mut self) -> Result<u32, Error> {
self.chip.single_reg_read(Regs::ChipRev.into())
}
#[allow(dead_code)] // todo
pub fn get_firmware_ver_short(&mut self) -> Result<(Revision, Revision), Error> {
let res = self.chip.single_reg_read(Regs::NmiRev.into())?;
let unpack = res.to_le_bytes();
Ok((
Revision {
major: unpack[1],
minor: unpack[0] >> 4,
patch: unpack[0] & 0xf,
},
Revision {
major: unpack[3],
minor: unpack[2] >> 4,
patch: unpack[2] & 0xf,
},
))
}
/// Resets the chip.
///
/// # Returns
///
/// * `()` - If the chip was successfully reset.
/// * `Error` - If an error occurs while resetting the chip.
pub(crate) fn chip_reset(&mut self) -> Result<(), Error> {
self.chip.single_reg_write(Regs::ChipReset.into(), 0)?;
// back-off delay
self.chip.delay_us(50_000); // 50 msec delay
Ok(())
}
/// Halt the chip.
///
/// # Returns
///
/// * `()` - If the chip was successfully halted.
/// * `Error` - If an error occurs while halting the chip.
pub(crate) fn chip_halt(&mut self) -> Result<(), Error> {
const HALT_BIT: u32 = 1 << 0; // 0x01
const RESET_BIT: u32 = 1 << 10; // 0x400
let mut reg = self.chip.single_reg_read(Regs::ChipHalt.into())?;
self.chip
.single_reg_write(Regs::ChipHalt.into(), reg | HALT_BIT)?;
reg = self.chip.single_reg_read(Regs::ChipReset.into())?;
if (reg & RESET_BIT) == RESET_BIT {
reg &= !RESET_BIT;
self.chip.single_reg_write(Regs::ChipReset.into(), reg)?;
_ = self.chip.single_reg_read(Regs::ChipReset.into())?;
}
Ok(())
}
/// Resets the SPI bus
///
/// # Returns
///
/// * `()` - If the bus was reset successfully.
/// * `Error` - If an error occurs while resetting the SPI bus.
pub(crate) fn spi_bus_reset(&mut self) -> Result<(), Error> {
self.chip.bus_reset()
}
/// Wake up the chip.
///
/// # Returns
///
/// * `()` - If the chip is successfully woken up.
/// * `Error` - If any error occurs while waking up the chip.
pub(crate) fn chip_wake(&mut self) -> Result<(), Error> {
const WAKEUP_BIT: u32 = 1 << 0; // 0x01
const WAKEUP_CLK_BIT: u32 = 1 << 1; // 0x02
const CLK_EN_BIT: u32 = 1 << 2; // 0x04
const WAKEUP_DELAY_USEC: u32 = 2000; // 2 msec delay
let mut reg = self.chip.single_reg_read(Regs::HostToCortusComm.into())?;
// bit 0 indicates host wakeup
if (reg & WAKEUP_BIT) == 0 {
self.chip
.single_reg_write(Regs::HostToCortusComm.into(), reg | WAKEUP_BIT)?;
}
reg = self.chip.single_reg_read(Regs::WakeClock.into())?;
// Set the WAKEUP_CLK_BIT (bit 1); hardware will assert CLK_EN_BIT when ready.
if (reg & WAKEUP_CLK_BIT) == 0 {
self.chip
.single_reg_write(Regs::WakeClock.into(), reg | WAKEUP_CLK_BIT)?;
}
let mut retries = 4u8;
loop {
if retries == 0 {
error!("Reading enable clock register timed out.");
return Err(Error::OperationRetriesExceeded);
}
reg = self.chip.single_reg_read(Regs::EnableClock.into())?;
if (reg & CLK_EN_BIT) > 0 {
break;
}
retries -= 1;
// backoff delay
self.chip.delay_us(WAKEUP_DELAY_USEC);
}
// reset spi bus
self.spi_bus_reset()
}
/// Boots the chip into normal mode.
///
/// # Arguments
///
/// * `state` - Updated boot state.
///
/// # Returns
///
/// * `bool` - Whether the chip completed boot (true) or is still booting (false).
/// * `Error` - If an error occurs during the boot process.
pub(crate) fn boot_the_chip(&mut self, state: &mut BootState) -> Result<bool, Error> {
const MAX_LOOPS: u32 = 10;
const FINISH_BOOT_ROM: u32 = 0x10add09e;
debug!("Waiting for chip start .. stage: {:?}", state.stage);
match state.stage {
BootStage::Start => {
debug!("chip id {:x} rev:{:x}", self.chip_id()?, self.chip_rev()?);
self.configure_spi_packetsize()?;
state.stage = BootStage::StartBootrom;
state.loop_value = 0;
}
BootStage::StartBootrom => {
if state.loop_value >= MAX_LOOPS {
return Err(Error::BootRomStart);
}
let efuse = self.chip.single_reg_read(Regs::EFuseRead.into())? & 0x80000000;
if efuse != 0 {
state.stage = BootStage::Stage2;
}
}
BootStage::Stage2 => {
let host_wait = self.chip.single_reg_read(Regs::WaitForHost.into())? & 0x1;
if host_wait != 0 {
state.stage = BootStage::Stage4;
} else {
state.stage = BootStage::Stage3;
state.loop_value = 0;
}
}
BootStage::Stage3 => {
if state.loop_value >= MAX_LOOPS {
return Err(Error::BootRomStart);
}
let host_wait = self.chip.single_reg_read(Regs::BootRom.into())?;
if host_wait == FINISH_BOOT_ROM {
state.stage = BootStage::Stage4;
}
}
BootStage::Stage4 => {
let driver_rev = 0x13521352; // todo
self.chip
.single_reg_write(Regs::NmiState.into(), driver_rev)?;
self.chip_id()?;
// Write Boot Mode configuration.
let conf = u32::from(state.mode) | DEFAULT_CHIP_CFG;
self.chip.single_reg_write(Regs::NmiGp1.into(), conf)?;
let verify = self.chip.single_reg_read(Regs::NmiGp1.into())?;
// Verify the configuration
if verify == conf {
const START_FIRMWARE: u32 = 0xef522f61;
self.chip
.single_reg_write(Regs::BootRom.into(), START_FIRMWARE)?;
state.stage = BootStage::StageStartFirmware;
state.loop_value = 0;
} else if state.loop_value >= MAX_LOOPS {
return Err(Error::FirmwareStart);
}
}
BootStage::StageStartFirmware => {
if state.loop_value >= MAX_LOOPS {
return Err(Error::FirmwareStart);
}
const FINISH_INIT: u32 = 0x02532636;
self.delay_us(2 * 1000); // 2 msec
let reg = self.chip.single_reg_read(Regs::NmiState.into())?;
if reg == FINISH_INIT {
state.stage = BootStage::FinishFirmwareBoot;
}
}
BootStage::FinishFirmwareBoot => {
self.chip.single_reg_write(Regs::NmiState.into(), 0)?;
self.enable_interrupt_pins()?;
// After chip boot, we can go a lot faster
self.chip.switch_to_high_speed();
return Ok(true);
}
}
state.loop_value += 1;
Ok(false)
}
pub fn configure_spi_packetsize(&mut self) -> Result<(), Error> {
let mut conf = self.chip.single_reg_read(Regs::SpiConfig.into())?;
conf &= 0xFFFFFF0F; // clear
conf |= 0x00000050; // set to 8k packet size
self.chip.single_reg_write(Regs::SpiConfig.into(), conf)?;
trace!("Set spiconfig to {:x}", conf);
Ok(())
}
/// Enables interrupts on the module's pins.
///
/// # Returns
///
/// * `()` - If the interrupts were successfully enabled.
/// * `Error` - If an error occurs while enabling the interrupts.
pub fn enable_interrupt_pins(&mut self) -> Result<(), Error> {
let mut pinmux = self.chip.single_reg_read(Regs::NmiPinMux0.into())?;
pinmux |= 1u32 << 8;
self.chip
.single_reg_write(Regs::NmiPinMux0.into(), pinmux)?;
trace!("Set pinmux to {:x}", pinmux);
let mut int_enable = self.chip.single_reg_read(Regs::NmiIntrEnable.into())?;
int_enable |= 1u32 << 16;
self.chip
.single_reg_write(Regs::NmiIntrEnable.into(), int_enable)?;
trace!("Set int enable to {:x}", int_enable);
Ok(())
}
/// Disables all the interrupts in the module.
///
/// # Returns
///
/// * `()` - If the interrupts were successfully disabled.
/// * `Error` - If an error occurs while disabling the interrupts.
pub(crate) fn disable_internal_interrupt(&mut self) -> Result<(), Error> {
self.chip.single_reg_write(Regs::CortusIrq.into(), 0)
}
pub fn get_firmware_ver_full(&mut self) -> Result<FirmwareInfo, Error> {
let (_, address) = self.read_regs_from_otp_efuse()?;
debug!("Got address {:#x}", address);
let mod_address = (address & 0x0000ffff) | OTP_REG_ADDR_BITS;
let mut data = [0u8; 40];
debug!("Calculated address: {:#x}", mod_address);
self.chip.dma_block_read(mod_address, data.as_mut_slice())?;
Ok(data.into())
}
fn is_interrupt_pending(&mut self) -> Result<(bool, u32), Error> {
let val = self.chip.single_reg_read(Regs::WifiHostRcvCtrl0.into())?;
Ok((val & 0x1 == 0x1, val))
}
fn clear_interrupt_pending(&mut self, ctrlreg: u32) -> Result<(), Error> {
let setval = ctrlreg & !1;
self.chip
.single_reg_write(Regs::WifiHostRcvCtrl0.into(), setval)
}
/// Reads the MAC address and firmware OTA version register addresses
/// from the OTP (One-Time Programmable) eFuse memory.
///
/// # Returns
///
/// * `Ok((u32, u32))`:
/// - `u32`: MAC address register address.
/// - `u32`: Firmware OTA register address.
/// * `Err(Error)` - If reading the eFuse memory fails.
fn read_regs_from_otp_efuse(&mut self) -> Result<(u32, u32), Error> {
let read_addr = self.chip.single_reg_read(Regs::NmiGp2.into())?;
let mod_read_add = read_addr | OTP_REG_ADDR_BITS;
let mut data = [0u8; 8];
self.chip
.dma_block_read(mod_read_add, data.as_mut_slice())?;
let mut mac_efuse_mib = [0u8; 4];
mac_efuse_mib.copy_from_slice(&data[..4]);
let mut firmware_ota_rev = [0u8; 4];
firmware_ota_rev.copy_from_slice(&data[4..]);
Ok((
u32::from_le_bytes(mac_efuse_mib),
u32::from_le_bytes(firmware_ota_rev),
))
}
// #region read
fn read_hif_header(&mut self, ctrlreg0: u32) -> Result<(HifGroup, u16, u32), Error> {
let _size = (ctrlreg0 >> 2) & 0xfff;
let address = self.chip.single_reg_read(Regs::WifiHostRcvCtrl1.into())?;
let mut hif_header = [0u8; 4];
let slicebuffer = hif_header.as_mut_slice();
self.chip.dma_block_read(address, slicebuffer)?;
let hifhdr = hif_header_parse(hif_header)?;
Ok((hifhdr.0, hifhdr.1, address))
}
fn read_block(&mut self, address: u32, data: &mut [u8]) -> Result<(), Error> {
self.chip
.dma_block_read(address + HIF_HEADER_OFFSET as u32, data)?;
// clear rx // set rx_done
let reg = self.chip.single_reg_read(Regs::WifiHostRcvCtrl0.into())?;
self.chip
.single_reg_write(Regs::WifiHostRcvCtrl0.into(), reg | 2)
}
// tstrRecvReply
fn get_recv_reply<'b, const N: usize>(
&mut self,
address: u32,
max_block: &'b mut [u8; N],
) -> Result<(Socket, SocketAddrV4, &'b [u8], SocketError), Error> {
let mut result = [0xff; 16];
self.read_block(address, &mut result)?;
let (socket, addr, status, offset) = read_recv_reply(&result)?;
debug!("Recv reply: session: {} status:{}", socket.s, status);
let readslice = if status > 0 {
&mut max_block[0..(status as usize)]
} else {
&mut max_block[0..0]
};
let mut err = status as u8;
if status > 0 {
err = 0;
let read_address = address + offset as u32;
self.read_block(read_address, readslice)?;
}
Ok((socket, addr, readslice, err.into()))
}
// #endregion read
// #region write
/// Write region
/// Todo: This is messy
/// Sends the HIF header.
///
/// # Arguments
///
/// * `gid` - HIF Group ID. (e.g., WiFi, IP, OTA, HIF).
/// * `op` - Operation ID.
/// * `len` - Length of the data/control packet to send.
/// * `req_data` - Indicates whether to request data from the chip.
///
/// # Returns
///
/// * `Ok(())` - If the HIF header is successfully sent to the chip.
/// * `Err(Error)` - If any error occurred while preparing or sending the HIF header.
fn prep_for_hif_send(
&mut self,
gid: u8,
op: u8,
len: u16,
req_data: bool,
) -> Result<(), Error> {
// Write NMI state
let mut state: u32 = 0;
state |= gid as u32;
state |= if req_data {
((op | 0x80) as u32) << 8
} else {
(op as u32) << 8
};
state |= (len as u32) << 16;
self.chip.single_reg_write(Regs::NmiState.into(), state)?;
// Set RCV_CTRL_2 bit 1
self.chip
.single_reg_write(Regs::WifiHostRcvCtrl2.into(), 2)?;
// Wait for bit 1 in RCV_CTRL_2 to clear, with timeout
let mut retries = HIF_SEND_RETRIES;
let mut res;
loop {
res = self.chip.single_reg_read(Regs::WifiHostRcvCtrl2.into())?;
res &= 2;
if res == 0 || retries == 0 {
break;
}
// TODO: There should be a small back-off delay here
// perhaps add "delay" to Xfer trait and call into it
retries -= 1;
}
if res != 0 {
return Err(Error::HifSendFailed);
}
// Read DMA address from RCV_CTRL_4
self.not_a_reg_ctrl_4_dma = self.chip.single_reg_read(Regs::WifiHostRcvCtrl4.into())?;
trace!("Dma address: {:x}", self.not_a_reg_ctrl_4_dma);
Ok(())
}
/// Prepares and writes the HIF header.
///
/// # Arguments
///
/// * `req` - HIF request (e.g., WiFi, IP, OTA, HIF).
/// * `payload` - The request/control buffer to be sent. Maximum length: 65,535 bytes.
/// * `req_data` - Indicates whether request data is expected from the chip.
/// * `data_packet` - Optional. A tuple containing the size of the data to send and its offset. Maximum value: 65,535.
///
/// # Returns
///
/// * `Ok(())` - If the HIF header was successfully prepared and sent to the chip.
/// * `Err(Error)` - If an error occurred while preparing or writing the HIF header.
fn write_hif_header_impl(
&mut self,
req: HifRequest,
payload: &[u8],
req_data: bool,
data_packet: Option<(usize /* Data Size */, usize /* Offset */)>,
) -> Result<(), Error> {
// Length of packet to send.
let len = match data_packet {
Some((size, offset)) => HIF_HEADER_OFFSET + size + offset,
None => payload.len() + HIF_HEADER_OFFSET,
};
if len > u16::MAX as usize {
error!(
"The length of the data/control packet exceeds the maximum value: expected up to 65,535, got {}",
len
);
return Err(Error::BufferError);
}
let pkglen = (len as u16).to_le_bytes();
// Operation ID.
let opp: u8 = match req {
HifRequest::Wifi(opcode) => opcode.into(),
HifRequest::Ip(opcode) => opcode.into(),
#[cfg(feature = "experimental-ota")]
HifRequest::Ota(opcode) => opcode.into(),
#[cfg(feature = "ssl")]
HifRequest::Ssl(opcode) => opcode.into(),
};
// Group ID.
let grpval = req.into();
self.prep_for_hif_send(grpval, opp, len as u16, req_data)?;
self.chip.dma_block_write(
self.not_a_reg_ctrl_4_dma,
&[
grpval, opp, pkglen[0], pkglen[1], 0x00, // unused bytes
0x00, 0x00, 0x00,
],
)
}
/// Prepares and writes the HIF header without a data packet.
///
/// # Arguments
///
/// * `req` - The HIF request type (e.g., WiFi, IP, OTA, HIF).
/// * `payload` - The request/control buffer to be sent. Maximum length: 65,535 bytes.
/// * `req_data` - Indicates whether request data is expected from the chip.
///
/// # Returns
///
/// * `Ok(())` - If the HIF header was successfully prepared and sent to the chip.
/// * `Err(Error)` - If an error occurred while preparing or writing the HIF header.
fn write_hif_header(
&mut self,
req: HifRequest,
payload: &[u8],
req_data: bool,
) -> Result<(), Error> {
self.write_hif_header_impl(req, payload, req_data, None)
}
fn write_ctrl3(&mut self, addr: u32) -> Result<(), Error> {
let val = (addr << 2) | 2;
self.chip.single_reg_write(
Regs::WifiHostRcvCtrl3.into(),
// dma_addr come from ctrl4
//reg = dma_addr << 2; reg |= NBIT1;
val,
)
}
/// Determines the appropriate SSL `IpCode` variant for the given socket.
///
/// If the provided `socket` has SSL enabled, the function converts the
/// *base* `IpCode` (e.g., `IpCode::Connect`) into its SSL counterpart
/// (e.g., `IpCode::SslConnect`). When SSL is not active, the original `base`
/// value is returned unchanged.
///
/// # Arguments
///
/// * `_socket` – A reference to the `Socket` whose SSL configuration will be inspected.
/// * `base` – The `IpCode` command to convert to its SSL counterpart.
///
/// # Returns
///
/// * An `IpCode::Ssl...` variant when SSL is enabled.
/// * The original `base` value when SSL is disabled.
fn get_ssl_ip_code(&mut self, _socket: &Socket, base: IpCode) -> IpCode {
#[cfg(feature = "ssl")]
if (_socket.get_ssl_cfg() & u8::from(SslSockConfig::EnableSSL))
== u8::from(SslSockConfig::EnableSSL)
{
return match base {
IpCode::Connect => IpCode::SslConnect,
IpCode::Send => IpCode::SslSend,
IpCode::Recv => IpCode::SslRecv,
IpCode::Bind => IpCode::SslBind,
IpCode::Close => IpCode::SslClose,
_ => base,
};
}
base
}
pub fn send_default_connect(&mut self) -> Result<(), Error> {
self.write_hif_header(HifRequest::Wifi(WifiRequest::DefaultConnect), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a Connect request to chip.
///
/// # Arguments
///
/// * `ssid` - The SSID (network name), up to 32 bytes.
/// * `credentials` - Security credentials (e.g., passphrase or authentication data).
/// * `channel` - Wi-Fi RF channel.
/// * `dont_save_credentials` - Whether to save credentials or not.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurred while preparing or sending the connect request.
pub fn send_connect(
&mut self,
ssid: &Ssid,
credentials: &Credentials,
channel: WifiChannel,
dont_save_credentials: bool,
) -> Result<(), Error> {
let arr = write_connect_request(ssid, credentials, channel, dont_save_credentials)?;
self.write_hif_header(HifRequest::Wifi(WifiRequest::Connect), &arr, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &arr)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_get_current_rssi(&mut self) -> Result<(), Error> {
self.write_hif_header(HifRequest::Wifi(WifiRequest::CurrentRssi), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_get_conn_info(&mut self) -> Result<(), Error> {
self.write_hif_header(HifRequest::Wifi(WifiRequest::GetConnInfo), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_scan(&mut self, channel: u8, scantime: u16) -> Result<(), Error> {
let req = write_scan_req(channel, scantime)?;
self.write_hif_header(HifRequest::Wifi(WifiRequest::Scan), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_get_scan_result(&mut self, index: u8) -> Result<(), Error> {
let req = [index, 0, 0, 0];
self.write_hif_header(HifRequest::Wifi(WifiRequest::ScanResult), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
// #region ipsend
pub fn send_ping_req(
&mut self,
dest: Ipv4Addr,
ttl: u8,
count: u16,
marker: u8,
) -> Result<(), Error> {
let req = write_ping_req(dest, ttl, count, marker)?;
self.write_hif_header(HifRequest::Ip(IpCode::Ping), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_gethostbyname(&mut self, host: &str) -> Result<(), Error> {
let mut buffer = [0x0u8; 64];
let req = write_gethostbyname_req(host, &mut buffer)?;
self.write_hif_header(HifRequest::Ip(IpCode::DnsResolve), req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to bind the socket to the specified IPv4 address and port.
///
/// # Arguments
///
/// * `socket` - The socket to bind.
/// * `address` - The local IPv4 address and port to bind the socket to.
///
/// # Returns
///
/// * `Ok(())` - If the bind request was successfully sent.
/// * `Err(Error)` - If an error occurred while sending the bind request.
pub fn send_bind(&mut self, socket: Socket, address: SocketAddrV4) -> Result<(), Error> {
let req = write_bind_req(socket, address)?;
let cmd = self.get_ssl_ip_code(&socket, IpCode::Bind);
self.write_hif_header(HifRequest::Ip(cmd), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_listen(&mut self, socket: Socket, backlog: u8) -> Result<(), Error> {
let req = write_listen_req(socket, backlog)?;
self.write_hif_header(HifRequest::Ip(IpCode::Listen), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to initiate a socket connection to the specified IPv4 address.
///
/// # Arguments
///
/// * `socket` - The socket to use for connecting to the server.
/// * `address` - The IPv4 address and port to connect to.
///
/// # Returns
///
/// * `Ok(())` - If the connection request was successfully sent.
/// * `Err(Error)` - If an error occurred while sending the connection request.
pub fn send_socket_connect(
&mut self,
socket: Socket,
address: SocketAddrV4,
) -> Result<(), Error> {
let req = write_connect_req(socket, 2, address, socket.get_ssl_cfg())?;
let cmd = self.get_ssl_ip_code(&socket, IpCode::Connect);
self.write_hif_header(HifRequest::Ip(cmd), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_sendto(
&mut self,
socket: Socket,
address: SocketAddrV4,
data: &[u8],
) -> Result<(), Error> {
const UDP_IP_HEADER_LENGTH: usize = 28;
const UDP_TX_PACKET_OFFSET: usize = IP_PACKET_OFFSET + UDP_IP_HEADER_LENGTH;
let req = write_sendto_req(socket, 2, address, data.len())?;
self.write_hif_header(HifRequest::Ip(IpCode::SendTo), &req, true)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.chip.dma_block_write(
self.not_a_reg_ctrl_4_dma + UDP_TX_PACKET_OFFSET as u32,
data,
)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a TCP send request.
///
/// # Arguments
///
/// * `socket` - The socket through which the data will be sent.
/// * `data` - A byte slice containing the data to send.
///
/// # Returns
///
/// * `Ok(())` - If the data was successfully sent.
/// * `Err(Error)` - If an error occurred during the send operation.
pub fn send_send(&mut self, socket: Socket, data: &[u8]) -> Result<(), Error> {
const TCP_IP_HEADER_LENGTH: usize = 40;
const TCP_TX_PACKET_OFFSET: usize = IP_PACKET_OFFSET + TCP_IP_HEADER_LENGTH;
// todo: offset depends on UDP or TCP
let req = write_sendto_req(
socket,
2,
SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0),
data.len(),
)?;
let cmd = self.get_ssl_ip_code(&socket, IpCode::Send);
let offset = {
#[cfg(feature = "ssl")]
{
if matches!(cmd, IpCode::SslSend) {
// Offset received from connect command response.
let data_offset = socket.get_ssl_data_offset() as usize;
if data_offset == 0 {
error!("Attempted to send on an SSL socket with an invalid data offset.");
return Err(Error::Failed);
}
data_offset
} else {
TCP_TX_PACKET_OFFSET
}
}
#[cfg(not(feature = "ssl"))]
{
TCP_TX_PACKET_OFFSET
}
};
self.write_hif_header_impl(HifRequest::Ip(cmd), &req, true, Some((data.len(), offset)))?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
// The offset already includes the HIF_HEADER_OFFSET, so it is not added here.
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + offset as u32, data)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to receive data from the specified socket, with a timeout.
///
/// # Arguments
///
/// * `socket` - The socket from which to receive data.
/// * `timeout` - The timeout duration in milliseconds.
///
/// # Returns
///
/// * `Ok(())` - If the receive request was successfully sent.
/// * `Err(Error)` - If an error occurred while sending the receive request.
pub fn send_recv(&mut self, socket: Socket, timeout: u32) -> Result<(), Error> {
let req = write_recv_req(socket, timeout)?;
let cmd = self.get_ssl_ip_code(&socket, IpCode::Recv);
self.write_hif_header(HifRequest::Ip(cmd), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
pub fn send_recvfrom(&mut self, socket: Socket, timeout: u32) -> Result<(), Error> {
let req = write_recv_req(socket, timeout)?;
self.write_hif_header(HifRequest::Ip(IpCode::RecvFrom), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to close the specified socket.
///
/// # Arguments
///
/// * `socket` - The socket to close.
///
/// # Returns
///
/// * `Ok(())` - If the close request was successfully sent.
/// * `Err(Error)` - If an error occurred while sending the request.
pub fn send_close(&mut self, socket: Socket) -> Result<(), Error> {
let req = write_close_req(socket)?;
let cmd = self.get_ssl_ip_code(&socket, IpCode::Close);
self.write_hif_header(HifRequest::Ip(cmd), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Send a set socket option request to module.
///
/// # Arguments
///
/// * `socket` - The socket to which the option will be applied.
/// * `option` - A reference to the UDP socket option to be set.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurred while preparing or sending the request.
pub fn send_setsockopt(&mut self, socket: Socket, option: &UdpSockOpts) -> Result<(), Error> {
let req = write_setsockopt_req(socket, (*option).into(), option.get_value())?;
self.write_hif_header(HifRequest::Ip(IpCode::SetSocketOption), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Send a set SSL socket option request to module.
///
/// # Arguments
///
/// * `socket` - The socket to which the option will be applied.
/// * `option` - A reference to the SSL socket option to be set.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurred while preparing or sending the request.
#[cfg(feature = "ssl")]
pub fn send_ssl_setsockopt(
&mut self,
socket: Socket,
option: &SslSockOpts,
) -> Result<(), Error> {
let req = write_ssl_setsockopt_req(socket, option)?;
self.write_hif_header(HifRequest::Ip(IpCode::SslSetSockOpt), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Send a disconnect request to module.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurred while preparing or sending the request.
pub fn send_disconnect(&mut self) -> Result<(), Error> {
self.write_hif_header(HifRequest::Wifi(WifiRequest::Disconnect), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a PRNG request to the chip.
///
/// # Arguments
///
/// * `addr` - The address of the input buffer where the PRNG data will be stored.
/// * `len` - The length of the input buffer, i.e., the number of random bytes to generate.
///
/// # Warning
///
/// * It is recommended to pass the address of a valid memory location rather than
/// an arbitrary one, to avoid potential memory leaks or data corruption.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurred during the PRNG packet request or preparation.
pub fn send_prng(&mut self, addr: u32, len: u16) -> Result<(), Error> {
let req = write_prng_req(addr, len)?;
self.write_hif_header(HifRequest::Wifi(WifiRequest::GetPrng), &req, true)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to start provisioning mode.
///
/// # Arguments
///
/// * `ap` - Configuration parameters for the access point, including SSID, password, authentication type, etc.
/// * `dns` - DNS redirect URL as a string slice. Must not end with `.local`.
/// * `http_redirect` - Enables or disables HTTP redirection. If enabled, all HTTP traffic
/// (`http://<URL>`) from devices connected to the WINC access point will be redirected
/// to the HTTP provisioning web page.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurs during packet preparation or sending.
pub fn send_start_provisioning(
&mut self,
ap: &AccessPoint,
hostname: &HostName,
http_redirect: bool,
) -> Result<(), Error> {
let req = write_start_provisioning_req(ap, hostname, http_redirect)?;
self.write_hif_header(
HifRequest::Wifi(WifiRequest::StartProvisionMode),
&req,
true,
)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to stop provisioning mode.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurs during packet preparation or transmission.
pub fn send_stop_provisioning(&mut self) -> Result<(), Error> {
self.write_hif_header(HifRequest::Wifi(WifiRequest::StopProvisionMode), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to enable Access Point mode.
///
/// # Arguments
///
/// * `ap` - Configuration parameters for the access point, including SSID, password, authentication type, etc.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurs during packet preparation or sending.
pub fn send_enable_access_point(&mut self, ap: &AccessPoint) -> Result<(), Error> {
let req = write_en_ap_req(ap)?;
self.write_hif_header(HifRequest::Wifi(WifiRequest::EnableAp), &req, true)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to disable Access Point mode.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurs during packet preparation or sending.
pub fn send_disable_access_point(&mut self) -> Result<(), Error> {
self.write_hif_header(HifRequest::Wifi(WifiRequest::DisableAp), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
#[cfg(feature = "experimental-ota")]
/// Send a request to start the OTA update for either winc1500 network stack or cortus processor.
///
/// # Arguments
///
/// * `server_url` - Server URL from where firmware image will be downloaded.
/// * `cortus_update` - Whether the OTA update is for cortus processor or winc1500 stack.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurs during packet preparation or sending.
pub fn send_start_ota_update(
&mut self,
server_url: &[u8],
cortus_update: bool,
) -> Result<(), Error> {
// Check whether request is for Cortus or for network stack.
let req_id = if cortus_update {
OtaRequest::StartCortusFirmwareUpdate
} else {
OtaRequest::StartFirmwareUpdate
};
self.write_hif_header(HifRequest::Ota(req_id), server_url, false)?;
self.chip.dma_block_write(
self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32,
server_url,
)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
#[cfg(feature = "experimental-ota")]
/// Sends an OTA request (rollback, abort, switch) either for the
/// WINC1500 network stack or the Cortus processor.
///
/// # Arguments
///
/// * `request` - Type of OTA request to send.
///
/// # Returns
///
/// * `()` - If the request is successfully sent.
/// * `Error` - If an error occurs during packet preparation or sending.
pub fn send_ota_request(&mut self, request: OtaRequest) -> Result<(), Error> {
self.write_hif_header(HifRequest::Ota(request), &[], false)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
#[cfg(feature = "flash-rw")]
/// Checks the flash data transfer register.
///
/// # Returns
///
/// * `()` - If the flash transfer is complete.
/// * `Error` - If an error occurs while reading the register or the process times out.
fn check_flash_tx_complete(&mut self) -> Result<(), Error> {
let mut retries = FLASH_REG_READ_RETRIES;
let mut res = self.chip.single_reg_read(Regs::FlashTransferDone.into())?;
while res != 1 {
if retries == 0 {
error!("Reading flash transfer complete register timed out.");
return Err(Error::OperationRetriesExceeded);
}
retries -= 1;
res = self.chip.single_reg_read(Regs::FlashTransferDone.into())?;
}
Ok(())
}
#[cfg(feature = "flash-rw")]
/// Sends a command to write data (less than a page size) from Cortus memory to flash.
///
/// # Arguments
///
/// * `flash_addr` – The flash address where data will be written.
/// * `data_size` – The size of the data to write.
///
/// # Returns
///
/// * `()` - The data was successfully written to flash.
/// * `Error` - If an error occurs while writing the data from Cortus memory to flash.
fn send_flash_write_page(&mut self, flash_addr: u32, data_size: usize) -> Result<(), Error> {
if data_size > FLASH_PAGE_SIZE {
return Err(Error::ExceedsFlashPageSize);
}
let cmd = {
let b = flash_addr.to_be_bytes();
[0x02, b[1], b[2], b[3]]
};
self.chip
.single_reg_write(Regs::FlashDataCount.into(), 0x00)?;
self.chip
.single_reg_write(Regs::FlashBuffer1.into(), u32::from_le_bytes(cmd))?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x0F)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), Regs::FlashSharedMemory.into())?;
// Mask data_size to 20 bits, shift to high bytes, and set 0x84 as the low byte
let size = 0x84 | ((data_size & 0xfffff) << 8);
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), size as u32)?;
// read transfer complete register.
self.check_flash_tx_complete()
}
#[cfg(feature = "flash-rw")]
/// Sends a command to read the flash status register.
///
/// # Returns
///
/// * `u8` – The value of the status register.
/// * `Error` – If an error occurs while reading the status register.
pub(crate) fn send_flash_read_status_register(&mut self) -> Result<u8, Error> {
self.chip
.single_reg_write(Regs::FlashDataCount.into(), 0x04)?;
self.chip
.single_reg_write(Regs::FlashBuffer1.into(), 0x05)?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x01)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), FLASH_DUMMY_VALUE)?;
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), 0x81)?;
// read transfer complete register.
self.check_flash_tx_complete()?;
let res = self.chip.single_reg_read(FLASH_DUMMY_VALUE)?;
Ok((res & 0xff) as u8)
}
#[cfg(feature = "flash-rw")]
/// Sends a command to load data from flash into Cortus processor memory.
///
/// # Arguments
///
/// * `flash_addr` – The flash address to load data from.
/// * `data_size` – The size of the data to load.
///
/// # Returns
///
/// * `()` - Data is successfully loaded into Cortus processor memory.
/// * `Error` - If an error occurs while loading the flash data into Cortus memory.
fn send_flash_load_data_to_cortus_memory(
&mut self,
flash_addr: u32,
data_size: usize,
) -> Result<(), Error> {
let cmd = {
let b = flash_addr.to_be_bytes();
[0x0b, b[1], b[2], b[3]]
};
self.chip
.single_reg_write(Regs::FlashDataCount.into(), data_size as u32)?;
self.chip
.single_reg_write(Regs::FlashBuffer1.into(), u32::from_le_bytes(cmd))?;
self.chip
.single_reg_write(Regs::FlashBuffer2.into(), 0xA5)?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x1F)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), Regs::FlashSharedMemory.into())?;
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), 0x85)?;
// read transfer complete register.
self.check_flash_tx_complete()
}
#[cfg(feature = "flash-rw")]
/// Sends a command to erase a flash sector (4KB).
///
/// # Arguments
///
/// * `flash_addr` - The flash address of the sector to erase.
///
/// # Returns
///
/// * `()` - The flash sector was successfully erased.
/// * `Error` - If an error occurs while erasing the flash sector.
pub(crate) fn send_flash_erase_sector(&mut self, flash_addr: u32) -> Result<(), Error> {
let cmd = {
let b = flash_addr.to_be_bytes();
[0x20, b[1], b[2], b[3]]
};
self.chip
.single_reg_write(Regs::FlashDataCount.into(), 0x00)?;
self.chip
.single_reg_write(Regs::FlashBuffer1.into(), u32::from_le_bytes(cmd))?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x0F)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), 0)?;
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), 0x84)?;
// read transfer complete register.
self.check_flash_tx_complete()
}
#[cfg(feature = "flash-rw")]
/// Sends a command to enable or disable write access to the flash.
///
/// # Arguments
///
/// * `enable` – `true` to enable write access; `false` to disable it.
///
/// # Returns
///
/// * `()` – Write access to the flash was successfully enabled or disabled.
/// * `Error` – If an error occurs while sending the command to change write access.
pub(crate) fn send_flash_write_access(&mut self, enable: bool) -> Result<(), Error> {
let val = if enable { 0x06 } else { 0x04 };
self.chip
.single_reg_write(Regs::FlashDataCount.into(), 0x00)?;
self.chip.single_reg_write(Regs::FlashBuffer1.into(), val)?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x01)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), 0x00)?;
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), 0x81)?;
// read transfer complete register.
self.check_flash_tx_complete()
}
#[cfg(feature = "flash-rw")]
/// Sends a command to write data to a flash memory.
///
/// # Arguments
///
/// * `flash_addr` – The address in flash memory where the data will be written.
/// * `data` – The data to write. Must not exceed the flash page size (256 bytes).
///
/// # Returns
///
/// * `()` - The data was successfully written to flash memory.
/// * `Error` - If an error occurs while writing the data to flash.
pub(crate) fn send_flash_write(&mut self, flash_addr: u32, data: &[u8]) -> Result<(), Error> {
if data.is_empty() {
error!("Invalid data buffer");
return Err(Error::BufferError);
}
if data.len() > FLASH_PAGE_SIZE {
error!("Data should not be greater than the page size, which is 256 bytes.");
return Err(Error::ExceedsFlashPageSize);
}
// enable flash writing
self.send_flash_write_access(true)?;
// use shared memory
self.chip
.dma_block_write(Regs::FlashSharedMemory.into(), data)?;
// set flash address
self.send_flash_write_page(flash_addr, data.len())?;
// read status register
let mut retries = FLASH_REG_READ_RETRIES;
let mut res = self.send_flash_read_status_register()?;
while (res & 0x01) != 0 {
if retries == 0 {
return Err(Error::OperationRetriesExceeded);
}
retries -= 1;
res = self.send_flash_read_status_register()?;
}
// disable writing to flash
self.send_flash_write_access(false)
}
#[cfg(feature = "flash-rw")]
/// Sends a command to read the flash ID.
///
/// # Returns
///
/// * `u32` - The flash ID.
/// * `Error` - If an error occurs while reading the flash ID.
pub(crate) fn send_flash_read_id(&mut self) -> Result<u32, Error> {
self.chip
.single_reg_write(Regs::FlashDataCount.into(), 0x04)?;
self.chip
.single_reg_write(Regs::FlashBuffer1.into(), 0x9F)?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x01)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), FLASH_DUMMY_VALUE)?;
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), 0x81)?;
// read transfer complete register.
self.check_flash_tx_complete()?;
let value = self.chip.single_reg_read(FLASH_DUMMY_VALUE)?;
Ok(value)
}
#[cfg(feature = "flash-rw")]
/// Sends a command to the flash to enter or exit low power mode.
///
/// # Arguments
///
/// * `enable` – `true` to enter low power mode; `false` to exit it.
///
/// # Returns
///
/// * `()` – The flash successfully entered or exited low power mode.
/// * `Error` – If an error occurs while attempting to change the flash power mode.
pub(crate) fn send_flash_low_power_mode(&mut self, enable: bool) -> Result<(), Error> {
let val: u32 = if enable { 0xB9 } else { 0xAB };
self.chip
.single_reg_write(Regs::FlashDataCount.into(), 0x00)?;
self.chip.single_reg_write(Regs::FlashBuffer1.into(), val)?;
self.chip
.single_reg_write(Regs::FlashBufferDirectory.into(), 0x01)?;
self.chip
.single_reg_write(Regs::FlashDmaAddress.into(), 0)?;
self.chip
.single_reg_write(Regs::FlashCommandCount.into(), 0x81)?;
// read transfer complete register.
self.check_flash_tx_complete()
}
#[cfg(feature = "flash-rw")]
/// Sends a command to enable or disable flash pinmux.
///
/// # Arguments
///
/// * `enable` – `true` to enable pinmux; `false` to disable it.
///
/// # Returns
///
/// * `()` – Pinmux was successfully enabled or disabled on the flash.
/// * `Error` – If an error occurs while enabling or disabling the flash pinmux.
pub(crate) fn send_flash_pin_mux(&mut self, enable: bool) -> Result<(), Error> {
const GPIO_PINS_MASK: u32 = 0x7777; // GPIO15/16/17/18
const FLASH_PINMUX_ENABLE: u32 = 0x1111;
const FLASH_PINMUX_DISABLE: u32 = 0x0010;
let mut val = self.chip.single_reg_read(Regs::FlashPinMux.into())?;
val &= !((GPIO_PINS_MASK) << 12);
val |= if enable {
(FLASH_PINMUX_ENABLE) << 12
} else {
(FLASH_PINMUX_DISABLE) << 12
};
self.chip.single_reg_write(Regs::FlashPinMux.into(), val)
}
#[cfg(feature = "flash-rw")]
/// Sends a command to read data from flash memory.
///
/// # Arguments
///
/// * `flash_addr` – The address in flash memory to read from.
/// * `buffer` – A mutable buffer where the read data will be stored.
///
/// # Returns
///
/// * `()` – Data was successfully read from flash memory.
/// * `Error` – If an error occurs while reading data from the flash.
pub(crate) fn send_flash_read(
&mut self,
flash_addr: u32,
buffer: &mut [u8],
) -> Result<(), Error> {
if buffer.is_empty() {
return Err(Error::BufferError);
}
// load data to shared memory between flash and cortus processor.
self.send_flash_load_data_to_cortus_memory(flash_addr, buffer.len())?;
// read the data from th shared from memory
self.chip
.dma_block_read(Regs::FlashSharedMemory.into(), buffer)
}
/// Sends a request to create an SSL socket.
///
/// # Arguments
///
/// * `socket` - The socket to enable SSL on.
///
/// # Returns
///
/// * `Ok(())` - If the request was successfully sent.
/// * `Err(Error)` - If an error occurred while preparing or sending the request.
#[cfg(feature = "ssl")]
pub(crate) fn send_ssl_sock_create(&mut self, socket: Socket) -> Result<(), Error> {
let req: [u8; 4] = [socket.v, 0, 0, 0];
self.write_hif_header(HifRequest::Ip(IpCode::SslCreate), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends a request to configure the SSL certificate expiry option.
///
/// # Arguments
///
/// * `opt` - The SSL certificate expiry option to configure.
///
/// # Returns
///
/// * `Ok(())` - If the request was successfully sent.
/// * `Err(Error)` - If an error occurred while preparing or sending the request.
#[cfg(feature = "ssl")]
pub(crate) fn send_ssl_cert_expiry(&mut self, opt: SslCertExpiryOpt) -> Result<(), Error> {
let req = u32::to_le_bytes(opt.into());
self.write_hif_header(HifRequest::Ip(IpCode::SslExpCheck), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Sends an ECC response to the module.
///
/// # Arguments
///
/// * `ecc_info` - A reference to the ECC operation information.
/// * `ecdh_info` - An optional reference to the ECDH operation information.
/// * `resp_buffer` - A buffer containing the ECC response data to send.
///
/// # Returns
///
/// * `Ok(())` - If the response was successfully sent.
/// * `Err(Error)` - If an error occurred while preparing or sending the response.
#[cfg(feature = "experimental-ecc")]
pub(crate) fn send_ecc_resp(
&mut self,
ecc_info: &EccInfo,
ecdh_info: Option<&EcdhInfo>,
resp_buffer: &[u8],
) -> Result<(), Error> {
let req = write_ssl_ecc_resp(ecc_info, ecdh_info)?;
self.write_hif_header_impl(
HifRequest::Ssl(SslRequest::SendEccResponse),
&req,
true,
Some((resp_buffer.len(), req.len())),
)?;
// write the control packet
let mut reg = self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32;
self.chip.dma_block_write(reg, &req)?;
// write the data packet
reg += req.len() as u32;
self.chip.dma_block_write(reg, resp_buffer)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Reads ECC information (curve type, hash algorithm, and signature) from the WINC module.
///
/// # Arguments
///
/// * `address` - The register address to start reading from.
/// * `resp_buff` - A mutable buffer to store the response data.
///
/// # Returns
///
/// * `Ok(())` - If the data was successfully read.
/// * `Err(Error)` - If an error occurred while reading the data.
#[cfg(feature = "experimental-ecc")]
pub(crate) fn read_ecc_info(
&mut self,
address: u32,
resp_buff: &mut [u8],
) -> Result<(), Error> {
let result = self
.chip
.dma_block_read(address + HIF_HEADER_OFFSET as u32, resp_buff);
// Set the RX done if error occurs, this will clear the information
// from the module.
if result.is_err() {
error!("Failed to read SSL info at address {:x}", address);
error!("Sending request to stop reading from the module.");
let reg = self.chip.single_reg_read(Regs::WifiHostRcvCtrl0.into())?;
self.chip
.single_reg_write(Regs::WifiHostRcvCtrl0.into(), reg | 2)?;
return Err(Error::ReadError);
}
Ok(())
}
/// Sends a request to stop reading ECC information from the module.
///
/// # Returns
///
/// * `Ok(())` - If ECC information reading was successfully disabled.
/// * `Err(Error)` - If an error occurred while updating the module state.
#[cfg(feature = "experimental-ecc")]
pub(crate) fn send_ecc_read_complete(&mut self) -> Result<(), Error> {
let reg = self.chip.single_reg_read(Regs::WifiHostRcvCtrl0.into())?;
self.chip
.single_reg_write(Regs::WifiHostRcvCtrl0.into(), reg | 2)
}
/// Sends a request to set the desired SSL cipher suites.
///
/// # Arguments
///
/// * `cipher_bitmap` - A bitmask (`u32`) representing the cipher suites to enable.
///
/// # Returns
///
/// * `Ok(())` - If the request was successfully sent.
/// * `Err(Error)` - If an error occurred while updating the module state.
#[cfg(feature = "ssl")]
pub(crate) fn send_ssl_set_cipher_suite(&mut self, cipher_bitmap: u32) -> Result<(), Error> {
let req = cipher_bitmap.to_le_bytes();
self.write_hif_header(HifRequest::Ssl(SslRequest::SetCipherSuites), &req, false)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Reads the MAC address from the OTP (One-Time Programmable) eFuse memory.
///
/// # Returns
///
/// * `Ok(MacAddress)` - The MAC address successfully read from the eFuse.
/// * `Err(Error)` - If reading the mac address from eFuse fails.
pub(crate) fn read_otp_mac_address(
&mut self,
#[cfg(test)] test_hook: bool,
) -> Result<MacAddress, Error> {
const HIGH_WORD_MASK: u32 = 0xFFFF_0000;
let mac: u32 = {
#[cfg(not(test))]
{
self.read_regs_from_otp_efuse()?.0
}
#[cfg(test)]
{
if test_hook {
HIGH_WORD_MASK
} else {
0x0000_0000
}
}
};
let reg = match mac & HIGH_WORD_MASK {
0 => return Err(Error::BufferReadError),
r => (r >> 16) | OTP_REG_ADDR_BITS,
};
let mut mac_address = MacAddress::empty();
self.chip.dma_block_read(reg, mac_address.as_mut_slice())?;
Ok(mac_address)
}
/// Sends an Ethernet packet with a maximum size of
/// `MAX_TX_ETHERNET_PACKET_SIZE` (65,501) to the module.
///
/// # Arguments
///
/// * `net_pkt` - The Ethernet packet to send.
///
/// # Returns
///
/// * `Ok(())` - If the packet was successfully sent.
/// * `Err(Error)` - If an error occurred while sending the packet.
#[cfg(feature = "ethernet")]
pub(crate) fn send_ethernet_packet(&mut self, net_pkt: &[u8]) -> Result<(), Error> {
if net_pkt.is_empty() || (net_pkt.len() > MAX_TX_ETHERNET_PACKET_SIZE) {
return Err(Error::BufferError);
}
let req = write_send_net_pkt_req(net_pkt.len() as u16, ETHERNET_HEADER_LENGTH as u16)?;
self.write_hif_header_impl(
HifRequest::Wifi(WifiRequest::SendEthernetPacket),
&req,
true,
Some((net_pkt.len(), ETHERNET_HEADER_OFFSET - HIF_HEADER_OFFSET)),
)?;
self.chip
.dma_block_write(self.not_a_reg_ctrl_4_dma + HIF_HEADER_OFFSET as u32, &req)?;
self.chip.dma_block_write(
self.not_a_reg_ctrl_4_dma + ETHERNET_HEADER_OFFSET as u32,
net_pkt,
)?;
self.write_ctrl3(self.not_a_reg_ctrl_4_dma)
}
/// Receives an Ethernet packet from the module.
///
/// # Arguments
///
/// * `address` - The starting HIF address from which the Ethernet packet will be read.
/// * `buffer` - A mutable buffer where the received Ethernet packet will be stored.
/// * `rx_done` - Indicates whether the RX_DONE flag should be written after the packet is read.
///
/// # Returns
///
/// * `Ok(())` - If the packet is successfully read from the module.
/// * `Err(Error)` - If an error occurs while receiving the packet.
#[cfg(feature = "ethernet")]
pub(crate) fn recv_ethernet_packet(
&mut self,
address: u32,
buffer: &mut [u8],
rx_done: bool,
) -> Result<(), Error> {
self.chip.dma_block_read(address, buffer)?;
// clear RX if no more data is available to read.
if rx_done {
let reg = self.chip.single_reg_read(Regs::WifiHostRcvCtrl0.into())?;
// Todo: Clean-up the magic number of register bit.
self.chip
.single_reg_write(Regs::WifiHostRcvCtrl0.into(), reg | 2)?;
}
Ok(())
}
// #endregion write
}
#[cfg(test)]
mod tests {
use super::*;
use constants::{ENABLE_AP_PACKET_SIZE, PRNG_PACKET_SIZE};
#[test]
fn test_hif_header() {
let hif_header = [0x01u8, 0x2C, 0x16, 0x00];
assert_eq!(
hif_header_parse(hif_header),
Ok((HifGroup::Wifi(WifiResponse::ConStateChanged), 22))
);
}
type ByteWrite<'a> = &'a mut [u8];
fn make_manager<'a>(writer: ByteWrite<'a>) -> Manager<ByteWrite<'a>> {
let mut mgr = Manager::from_xfer(writer);
mgr.chip.verify = false;
mgr.chip.crc = false;
mgr.chip.check_crc = false;
mgr
}
const CMD_OFFSET: usize = 53;
const DATA_OFFSET: usize = 73;
#[test]
fn test_close() {
let mut buff = [0u8; 90];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_close(Socket::new(67, 512 + 42)).unwrap(), ());
assert_eq!(buff[CMD_OFFSET], 0x49);
let theslice = &buff[DATA_OFFSET..DATA_OFFSET + 4];
assert_eq!(theslice, &[67, 0, 42, 2]);
}
#[test]
fn test_ping() {
let mut buff = [0u8; 100];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(
mgr.send_ping_req(Ipv4Addr::new(192, 168, 5, 196), 42, 512 + 5, 0xDA),
Ok(())
);
assert_eq!(buff[CMD_OFFSET], 0x52);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 12];
assert_eq!(
slice,
&[
192, 168, 5, 196, // ip
0xDA, 0xBE, 0xBE, 0xBE, //marker
5, 2, // count
42, // ttl
0,
]
);
}
#[test]
fn test_bind() {
let mut buff = [0u8; 100];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(
mgr.send_bind(
Socket::new(42, 512 + 10),
SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 196), 0xBADE)
),
Ok(())
);
assert_eq!(buff[CMD_OFFSET], 0x41);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 12];
assert_eq!(
slice,
&[
2, 0, // address family
0xBA, 0xDE, // port
192, 168, 5, 196, // ip
42, 0, //socket + dummy
10, 2 // session
]
)
}
#[test]
fn test_listen() {
let mut buff = [0u8; 100];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_listen(Socket::new(7, 512 + 10), 42), Ok(()));
assert_eq!(buff[CMD_OFFSET], 0x42);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 4];
assert_eq!(slice, &[7, 42, 10, 2])
}
#[test]
fn test_connect() {
let mut buff = [0u8; 100];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(
mgr.send_socket_connect(
Socket::new(7, 522),
SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 196), 0xBADE)
),
Ok(())
);
assert_eq!(buff[CMD_OFFSET], 0x44);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 12];
assert_eq!(
slice,
&[
2, 0, // address family
0xBA, 0xDE, // port
192, 168, 5, 196, // ip
7, 0, // socket, ssl_flags
10, 2 // session
]
);
}
#[test]
fn test_sendto() {
let mut buff = [0u8; 120];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(
mgr.send_sendto(
Socket::new(7, 522),
SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 196), 0xBADE),
&[42]
),
Ok(())
);
assert_eq!(buff[CMD_OFFSET], 0x47);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 16];
assert_eq!(
slice,
&[
7, 0, // socket, dummy
1, 0, // length
2, 0, // address family
0xBA, 0xDE, // port
192, 168, 5, 196, // ip
10, 2, // session,
0, 0 // dummy
]
);
}
#[test]
fn test_send() {
let mut buff = [0u8; 120];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_send(Socket::new(7, 522), &[42]), Ok(()));
assert_eq!(buff[CMD_OFFSET], 0x45);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 16];
assert_eq!(
slice,
&[
7, 0, // socket, dummy
1, 0, // length
2, 0, // address family
0, 0, 0, 0, 0, 0, // port + ip zeroed
10, 2, // session,
0, 0 // dummy
]
);
}
#[test]
fn test_recv() {
let mut buff = [0u8; 120];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_recv(Socket::new(7, 522), 0x01020304), Ok(()));
assert_eq!(buff[CMD_OFFSET], 0x46);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 8];
assert_eq!(
slice,
&[
4, 3, 2, 1, // timeout
7, 0, // socket+dummy
10, 2 // session
]
);
}
#[test]
fn test_recvfrom() {
let mut buff = [0u8; 120];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_recvfrom(Socket::new(7, 522), 0x01020304), Ok(()));
assert_eq!(buff[CMD_OFFSET], 0x48);
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 8];
assert_eq!(
slice,
&[
4, 3, 2, 1, // timeout
7, 0, // socket+dummy
10, 2 // session
]
);
}
#[test]
fn test_recv_reply() {
let mut buff = [1u8; 60];
const OFFSET: usize = 10;
buff[OFFSET + 0] = 2;
buff[OFFSET + 1] = 0;
buff[OFFSET + 8] = 0xF4; // set negative status
buff[OFFSET + 9] = 0xFF;
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut test = [2u8; 20];
let (socket, _, dataslice, err) = mgr.get_recv_reply(2, &mut test).unwrap();
assert_eq!(socket, Socket::new(1, 257));
assert_eq!(err, SocketError::ConnAborted);
assert_eq!(dataslice, &[]);
}
#[test]
fn test_prng() {
let mut buff = [0u8; 100];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_prng(0x2000_65DC, 16), Ok(()));
assert_eq!(buff[CMD_OFFSET], WifiRequest::GetPrng.into());
let slice = &buff[DATA_OFFSET..DATA_OFFSET + PRNG_PACKET_SIZE];
assert_eq!(
slice,
&[
0xDC, 0x65, 0x00, 0x020, // Address
0x10, 0x00, // length
0x00, 0x00 // void
]
)
}
#[test]
fn test_send_enable_ap() {
let mut buff = [0u8; 300];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let ssid = Ssid::from("ssid").unwrap();
let key = WpaKey::from("password").unwrap();
let ap = AccessPoint::wpa(&ssid, &key);
assert_eq!(mgr.send_enable_access_point(&ap), Ok(()));
assert_eq!(buff[CMD_OFFSET], WifiRequest::EnableAp.into());
let slice = &buff[DATA_OFFSET..DATA_OFFSET + ENABLE_AP_PACKET_SIZE];
assert_eq!(
slice,
&[
// Ssid
0x73, 0x73, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // Wifi Channel
0x00, // Wep Key Index
0x08, // Wep/WPA Key Size
// Wep Key
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, // Security Type
0x00, // SSID Hidden
0xC0, 0xA8, 0x01, 0x01, // AP IP
// WPA Key
0x70, 0x61, 0x73, 0x73, 0x77, 0x6F, 0x72, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Padding
0x00, 0x00
]
)
}
#[test]
fn test_send_disable_ap() {
let mut buff = [0u8; 73];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
assert_eq!(mgr.send_disable_access_point(), Ok(()));
assert_eq!(buff[CMD_OFFSET], WifiRequest::DisableAp.into());
}
#[test]
fn test_hif_header_exceeded_len() {
let mut buff = [0u8; 73];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let req = HifRequest::Wifi(WifiRequest::Connect);
let payload = [0u8; 65535];
let data_pkt = Some((65535, 128));
let res = mgr.write_hif_header_impl(req, &payload, true, data_pkt);
assert_eq!(res, Err(Error::BufferError));
}
#[test]
fn test_get_ip_code_no_ssl() {
let mut buff = [0u8; 10];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let sock = Socket::new(1, 1);
let ip_code = IpCode::Connect;
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, ip_code);
}
#[cfg(feature = "ssl")]
#[test]
fn test_get_ip_code_ssl_enabled() {
let mut buff = [0u8; 10];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut sock = Socket::new(1, 1);
let ip_code = IpCode::Connect;
sock.set_ssl_cfg(SslSockConfig::EnableSSL.into(), true);
sock.set_ssl_cfg(SslSockConfig::BypassX509Verification.into(), true);
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, IpCode::SslConnect);
let ip_code = IpCode::Bind;
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, IpCode::SslBind);
}
#[cfg(feature = "ssl")]
#[test]
fn test_get_ip_code_ssl_not_enabled() {
let mut buff = [0u8; 10];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut sock = Socket::new(1, 1);
let ip_code = IpCode::Send;
sock.set_ssl_cfg(SslSockConfig::BypassX509Verification.into(), true);
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, ip_code);
}
#[cfg(feature = "ssl")]
#[test]
fn test_get_ip_code_ssl_not_applicable() {
let mut buff = [0u8; 10];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut sock = Socket::new(1, 1);
let ip_code = IpCode::RecvFrom;
sock.set_ssl_cfg(SslSockConfig::EnableSSL.into(), true);
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, ip_code);
}
#[cfg(feature = "ssl")]
#[test]
fn test_get_ip_code_verify_ssl_opts() {
let mut buff = [0u8; 10];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut sock = Socket::new(1, 1);
sock.set_ssl_cfg(SslSockConfig::EnableSSL.into(), true);
// Connect + Send is verified from other tests.
// Bind
let ip_code = IpCode::Bind;
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, IpCode::SslBind);
// Recv
let ip_code = IpCode::Recv;
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, IpCode::SslRecv);
// Close
let ip_code = IpCode::Close;
let new_ip_code = mgr.get_ssl_ip_code(&sock, ip_code);
assert_eq!(new_ip_code, IpCode::SslClose);
}
#[cfg(feature = "ssl")]
#[test]
fn test_ssl_send_success() {
let mut buff = [0u8; 120];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut sock = Socket::new(7, 522);
sock.set_ssl_cfg(SslSockConfig::EnableSSL.into(), true);
sock.set_ssl_data_offset(100);
assert_eq!(mgr.send_send(sock, &[42]), Ok(()));
assert_eq!(buff[CMD_OFFSET], u8::from(IpCode::SslSend));
let slice = &buff[DATA_OFFSET..DATA_OFFSET + 16];
assert_eq!(
slice,
&[
7, 0, // socket, dummy
1, 0, // length
2, 0, // address family
0, 0, 0, 0, 0, 0, // port + ip zeroed
10, 2, // session,
0, 0 // dummy
]
);
}
#[cfg(feature = "ssl")]
#[test]
fn test_ssl_send_offset_failed() {
let mut buff = [0u8; 10];
let mut writer = buff.as_mut_slice();
let mut mgr = make_manager(&mut writer);
let mut sock = Socket::new(7, 522);
sock.set_ssl_cfg(SslSockConfig::EnableSSL.into(), true);
assert_eq!(mgr.send_send(sock, &[42]), Err(Error::Failed));
}
}