forked from tinygo-org/drivers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwifinina.go
1247 lines (1086 loc) · 27.8 KB
/
wifinina.go
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
// Package wifinina implements TCP wireless communication over SPI
// with an attached separate ESP32 board using the Arduino WiFiNINA protocol.
//
// In order to use this driver, the ESP32 must be flashed with specific firmware from Arduino.
// For more information: https://github.com/arduino/nina-fw
package wifinina // import "tinygo.org/x/drivers/wifinina"
import (
"encoding/binary"
"encoding/hex"
"fmt" // used only in debug printouts and is optimized out when debugging is disabled
"strconv"
"strings"
"sync"
"time"
"machine"
"tinygo.org/x/drivers"
"tinygo.org/x/drivers/net"
)
const _debug = false
const (
MaxSockets = 4
MaxNetworks = 10
MaxAttempts = 10
MaxLengthSSID = 32
MaxLengthWPAKey = 63
MaxLengthWEPKey = 13
LengthMacAddress = 6
LengthIPV4 = 4
WlFailure = -1
WlSuccess = 1
StatusNoShield ConnectionStatus = 255
StatusIdle ConnectionStatus = 0
StatusNoSSIDAvail ConnectionStatus = 1
StatusScanCompleted ConnectionStatus = 2
StatusConnected ConnectionStatus = 3
StatusConnectFailed ConnectionStatus = 4
StatusConnectionLost ConnectionStatus = 5
StatusDisconnected ConnectionStatus = 6
EncTypeTKIP EncryptionType = 2
EncTypeCCMP EncryptionType = 4
EncTypeWEP EncryptionType = 5
EncTypeNone EncryptionType = 7
EncTypeAuto EncryptionType = 8
TCPStateClosed = 0
TCPStateListen = 1
TCPStateSynSent = 2
TCPStateSynRcvd = 3
TCPStateEstablished = 4
TCPStateFinWait1 = 5
TCPStateFinWait2 = 6
TCPStateCloseWait = 7
TCPStateClosing = 8
TCPStateLastACK = 9
TCPStateTimeWait = 10
/*
// Default state value for Wifi state field
#define NA_STATE -1
*/
FlagCmd = 0
FlagReply = 1 << 7
FlagData = 0x40
NinaCmdPos = 1
NinaParamLenPos = 2
CmdStart = 0xE0
CmdEnd = 0xEE
CmdErr = 0xEF
dummyData = 0xFF
CmdSetNet = 0x10
CmdSetPassphrase = 0x11
CmdSetKey = 0x12
CmdSetIPConfig = 0x14
CmdSetDNSConfig = 0x15
CmdSetHostname = 0x16
CmdSetPowerMode = 0x17
CmdSetAPNet = 0x18
CmdSetAPPassphrase = 0x19
CmdSetDebug = 0x1A
CmdGetTemperature = 0x1B
CmdGetReasonCode = 0x1F
// TEST_CMD = 0x13
CmdGetConnStatus = 0x20
CmdGetIPAddr = 0x21
CmdGetMACAddr = 0x22
CmdGetCurrSSID = 0x23
CmdGetCurrBSSID = 0x24
CmdGetCurrRSSI = 0x25
CmdGetCurrEncrType = 0x26
CmdScanNetworks = 0x27
CmdStartServerTCP = 0x28
CmdGetStateTCP = 0x29
CmdDataSentTCP = 0x2A
CmdAvailDataTCP = 0x2B
CmdGetDataTCP = 0x2C
CmdStartClientTCP = 0x2D
CmdStopClientTCP = 0x2E
CmdGetClientStateTCP = 0x2F
CmdDisconnect = 0x30
CmdGetIdxRSSI = 0x32
CmdGetIdxEncrType = 0x33
CmdReqHostByName = 0x34
CmdGetHostByName = 0x35
CmdStartScanNetworks = 0x36
CmdGetFwVersion = 0x37
CmdSendDataUDP = 0x39
CmdGetRemoteData = 0x3A
CmdGetTime = 0x3B
CmdGetIdxBSSID = 0x3C
CmdGetIdxChannel = 0x3D
CmdPing = 0x3E
CmdGetSocket = 0x3F
// GET_IDX_SSID_CMD = 0x31,
// GET_TEST_CMD = 0x38
// All command with DATA_FLAG 0x40 send a 16bit Len
CmdSendDataTCP = 0x44
CmdGetDatabufTCP = 0x45
CmdInsertDataBuf = 0x46
// regular format commands
CmdSetPinMode = 0x50
CmdSetDigitalWrite = 0x51
CmdSetAnalogWrite = 0x52
ErrTimeoutChipReady Error = 0x01
ErrTimeoutChipSelect Error = 0x02
ErrCheckStartCmd Error = 0x03
ErrWaitRsp Error = 0x04
ErrUnexpectedLength Error = 0xE0
ErrNoParamsReturned Error = 0xE1
ErrIncorrectSentinel Error = 0xE2
ErrCmdErrorReceived Error = 0xEF
ErrNotImplemented Error = 0xF0
ErrUnknownHost Error = 0xF1
ErrSocketAlreadySet Error = 0xF2
ErrConnectionTimeout Error = 0xF3
ErrNoData Error = 0xF4
ErrDataNotWritten Error = 0xF5
ErrCheckDataError Error = 0xF6
ErrBufferTooSmall Error = 0xF7
ErrNoSocketAvail Error = 0xFF
NoSocketAvail uint8 = 0xFF
)
const (
ProtoModeTCP = iota
ProtoModeUDP
ProtoModeTLS
ProtoModeMul
)
type ConnectionStatus uint8
func (c ConnectionStatus) String() string {
switch c {
case StatusIdle:
return "Idle"
case StatusNoSSIDAvail:
return "No SSID Available"
case StatusScanCompleted:
return "Scan Completed"
case StatusConnected:
return "Connected"
case StatusConnectFailed:
return "Connect Failed"
case StatusConnectionLost:
return "Connection Lost"
case StatusDisconnected:
return "Disconnected"
case StatusNoShield:
return "No Shield"
default:
return "Unknown"
}
}
type EncryptionType uint8
func (e EncryptionType) String() string {
switch e {
case EncTypeTKIP:
return "TKIP"
case EncTypeCCMP:
return "WPA2"
case EncTypeWEP:
return "WEP"
case EncTypeNone:
return "None"
case EncTypeAuto:
return "Auto"
default:
return "Unknown"
}
}
type IPAddress string // TODO: does WiFiNINA support ipv6???
func (addr IPAddress) String() string {
if len(addr) < 4 {
return ""
}
return strconv.Itoa(int(addr[0])) + "." + strconv.Itoa(int(addr[1])) + "." + strconv.Itoa(int(addr[2])) + "." + strconv.Itoa(int(addr[3]))
}
func ParseIPv4(s string) (IPAddress, error) {
v := strings.Split(s, ".")
v0, _ := strconv.Atoi(v[0])
v1, _ := strconv.Atoi(v[1])
v2, _ := strconv.Atoi(v[2])
v3, _ := strconv.Atoi(v[3])
return IPAddress([]byte{byte(v0), byte(v1), byte(v2), byte(v3)}), nil
}
func (addr IPAddress) AsUint32() uint32 {
if len(addr) < 4 {
return 0
}
b := []byte(string(addr))
return binary.BigEndian.Uint32(b[0:4])
}
type MACAddress uint64
func (addr MACAddress) String() string {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(addr))
encoded := hex.EncodeToString(b)
result := ""
for i := 2; i < 8; i++ {
result += encoded[i*2 : i*2+2]
if i < 7 {
result += ":"
}
}
return result
}
type Error uint8
func (err Error) Error() string {
return "wifinina error: 0x" + hex.EncodeToString([]byte{uint8(err)})
}
// Cmd Struct Message */
// ._______________________________________________________________________.
// | START CMD | C/R | CMD | N.PARAM | PARAM LEN | PARAM | .. | END CMD |
// |___________|______|______|_________|___________|________|____|_________|
// | 8 bit | 1bit | 7bit | 8bit | 8bit | nbytes | .. | 8bit |
// |___________|______|______|_________|___________|________|____|_________|
type command struct {
cmd uint8
reply bool
params []int
paramData []byte
}
type Device struct {
SPI drivers.SPI
CS machine.Pin
ACK machine.Pin
GPIO0 machine.Pin
RESET machine.Pin
buf [64]byte
ssids [10]string
sock uint8
readBuf readBuffer
proto uint8
ip uint32
port uint16
mu sync.Mutex
}
// New returns a new Wifinina device.
func New(bus drivers.SPI, csPin, ackPin, gpio0Pin, resetPin machine.Pin) *Device {
return &Device{
SPI: bus,
CS: csPin,
ACK: ackPin,
GPIO0: gpio0Pin,
RESET: resetPin,
}
}
func (d *Device) Configure() {
net.UseDriver(d)
pinUseDevice(d)
d.CS.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.ACK.Configure(machine.PinConfig{Mode: machine.PinInput})
d.RESET.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.GPIO0.Configure(machine.PinConfig{Mode: machine.PinOutput})
d.GPIO0.High()
d.CS.High()
d.RESET.Low()
time.Sleep(1 * time.Millisecond)
d.RESET.High()
time.Sleep(1 * time.Millisecond)
d.GPIO0.Low()
d.GPIO0.Configure(machine.PinConfig{Mode: machine.PinInput})
}
// ----------- client methods (should this be a separate struct?) ------------
func (d *Device) StartClient(hostname string, addr uint32, port uint16, sock uint8, mode uint8) error {
if _debug {
fmt.Printf("[StartClient] hostname: %s addr: % 02X, port: %d, sock: %d\r\n", hostname, addr, port, sock)
}
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return err
}
if len(hostname) > 0 {
d.sendCmd(CmdStartClientTCP, 5)
d.sendParamStr(hostname, false)
} else {
d.sendCmd(CmdStartClientTCP, 4)
}
d.sendParam32(addr, false)
d.sendParam16(port, false)
d.sendParam8(sock, false)
d.sendParam8(mode, true)
if len(hostname) > 0 {
d.padTo4(17 + len(hostname))
}
d.spiChipDeselect()
_, err := d.waitRspCmd1(CmdStartClientTCP)
return err
}
func (d *Device) GetSocket() (uint8, error) {
return d.getUint8(d.req0(CmdGetSocket))
}
func (d *Device) GetClientState(sock uint8) (uint8, error) {
return d.getUint8(d.reqUint8(CmdGetClientStateTCP, sock))
}
func (d *Device) SendData(buf []byte, sock uint8) (uint16, error) {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return 0, err
}
l := d.sendCmd(CmdSendDataTCP, 2)
l += d.sendParamBuf([]byte{sock}, false)
l += d.sendParamBuf(buf, true)
d.addPadding(l)
d.spiChipDeselect()
return d.getUint16(d.waitRspCmd1(CmdSendDataTCP))
}
func (d *Device) CheckDataSent(sock uint8) (bool, error) {
d.mu.Lock()
defer d.mu.Unlock()
var lastErr error
for timeout := 0; timeout < 10; timeout++ {
sent, err := d.getUint8(d.reqUint8(CmdDataSentTCP, sock))
if err != nil {
lastErr = err
}
if sent > 0 {
return true, nil
}
time.Sleep(100 * time.Microsecond)
}
return false, lastErr
}
func (d *Device) GetDataBuf(sock uint8, buf []byte) (int, error) {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return 0, err
}
p := uint16(len(buf))
l := d.sendCmd(CmdGetDatabufTCP, 2)
l += d.sendParamBuf([]byte{sock}, false)
l += d.sendParamBuf([]byte{uint8(p & 0x00FF), uint8((p) >> 8)}, true)
d.addPadding(l)
d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return 0, err
}
n, err := d.waitRspBuf16(CmdGetDatabufTCP, buf)
d.spiChipDeselect()
return int(n), err
}
func (d *Device) StopClient(sock uint8) error {
d.mu.Lock()
defer d.mu.Unlock()
if _debug {
println("[StopClient] called StopClient()\r")
}
_, err := d.getUint8(d.reqUint8(CmdStopClientTCP, sock))
return err
}
func (d *Device) StartServer(port uint16, sock uint8, mode uint8) error {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return err
}
l := d.sendCmd(CmdStartServerTCP, 3)
l += d.sendParam16(port, false)
l += d.sendParam8(sock, false)
l += d.sendParam8(mode, true)
d.addPadding(l)
d.spiChipDeselect()
_, err := d.waitRspCmd1(CmdStartClientTCP)
return err
}
// InsertDataBuf adds data to the buffer used for sending UDP data
func (d *Device) InsertDataBuf(buf []byte, sock uint8) (bool, error) {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return false, err
}
l := d.sendCmd(CmdInsertDataBuf, 2)
l += d.sendParamBuf([]byte{sock}, false)
l += d.sendParamBuf(buf, true)
d.addPadding(l)
d.spiChipDeselect()
n, err := d.getUint8(d.waitRspCmd1(CmdInsertDataBuf))
return n == 1, err
}
// SendUDPData sends the data previously added to the UDP buffer
func (d *Device) SendUDPData(sock uint8) (bool, error) {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.waitForChipSelect(); err != nil {
d.spiChipDeselect()
return false, err
}
l := d.sendCmd(CmdSendDataUDP, 1)
l += d.sendParam8(sock, true)
d.addPadding(l)
d.spiChipDeselect()
n, err := d.getUint8(d.waitRspCmd1(CmdSendDataUDP))
return n == 1, err
}
// ---------- /client methods (should this be a separate struct?) ------------
/*
static bool startServer(uint16_t port, uint8_t sock);
static uint8_t getServerState(uint8_t sock);
static bool getData(uint8_t connId, uint8_t *data, bool peek, bool* connClose);
static int getDataBuf(uint8_t connId, uint8_t *buf, uint16_t bufSize);
static bool sendData(uint8_t sock, const uint8_t *data, uint16_t len);
static bool sendDataUdp(uint8_t sock, const char* host, uint16_t port, const uint8_t *data, uint16_t len);
static uint16_t availData(uint8_t connId);
static bool ping(const char *host);
static void reset();
static void getRemoteIpAddress(IPAddress& ip);
static uint16_t getRemotePort();
*/
func (d *Device) Disconnect() error {
_, err := d.req1(CmdDisconnect)
return err
}
func (d *Device) GetFwVersion() (string, error) {
return d.getString(d.req0(CmdGetFwVersion))
}
func (d *Device) GetConnectionStatus() (ConnectionStatus, error) {
status, err := d.getUint8(d.req0(CmdGetConnStatus))
return ConnectionStatus(status), err
}
func (d *Device) GetCurrentEncryptionType() (EncryptionType, error) {
enctype, err := d.getUint8(d.req1(CmdGetCurrEncrType))
return EncryptionType(enctype), err
}
func (d *Device) GetCurrentBSSID() (MACAddress, error) {
return d.getMACAddress(d.req1(CmdGetCurrBSSID))
}
func (d *Device) GetCurrentRSSI() (int32, error) {
return d.getInt32(d.req1(CmdGetCurrRSSI))
}
func (d *Device) GetCurrentSSID() (string, error) {
return d.getString(d.req1(CmdGetCurrSSID))
}
func (d *Device) GetMACAddress() (MACAddress, error) {
return d.getMACAddress(d.req1(CmdGetMACAddr))
}
func (d *Device) GetIP() (ip, subnet, gateway IPAddress, err error) {
sl := make([]string, 3)
if l, err := d.reqRspStr1(CmdGetIPAddr, dummyData, sl); err != nil {
return "", "", "", err
} else if l != 3 {
return "", "", "", ErrUnexpectedLength
}
return IPAddress(sl[0]), IPAddress(sl[1]), IPAddress(sl[2]), err
}
func (d *Device) GetHostByName(hostname string) (IPAddress, error) {
ok, err := d.getUint8(d.reqStr(CmdReqHostByName, hostname))
if err != nil {
return "", err
}
if ok != 1 {
return "", ErrUnknownHost
}
ip, err := d.getString(d.req0(CmdGetHostByName))
return IPAddress(ip), err
}
func (d *Device) GetNetworkBSSID(idx int) (MACAddress, error) {
if idx < 0 || idx >= MaxNetworks {
return 0, nil
}
return d.getMACAddress(d.reqUint8(CmdGetIdxBSSID, uint8(idx)))
}
func (d *Device) GetNetworkChannel(idx int) (uint8, error) {
if idx < 0 || idx >= MaxNetworks {
return 0, nil
}
return d.getUint8(d.reqUint8(CmdGetIdxChannel, uint8(idx)))
}
func (d *Device) GetNetworkEncrType(idx int) (EncryptionType, error) {
if idx < 0 || idx >= MaxNetworks {
return 0, nil
}
enctype, err := d.getUint8(d.reqUint8(CmdGetIdxEncrType, uint8(idx)))
return EncryptionType(enctype), err
}
func (d *Device) GetNetworkRSSI(idx int) (int32, error) {
if idx < 0 || idx >= MaxNetworks {
return 0, nil
}
return d.getInt32(d.reqUint8(CmdGetIdxRSSI, uint8(idx)))
}
func (d *Device) GetNetworkSSID(idx int) string {
if idx < 0 || idx >= MaxNetworks {
return ""
}
return d.ssids[idx]
}
func (d *Device) GetReasonCode() (uint8, error) {
return d.getUint8(d.req0(CmdGetReasonCode))
}
// GetTime is the time as a Unix timestamp
func (d *Device) GetTime() (uint32, error) {
return d.getUint32(d.req0(CmdGetTime))
}
func (d *Device) GetTemperature() (float32, error) {
return d.getFloat32(d.req0(CmdGetTemperature))
}
func (d *Device) Ping(ip IPAddress, ttl uint8) int16 {
return 0
}
func (d *Device) SetDebug(on bool) error {
var v uint8
if on {
v = 1
}
_, err := d.reqUint8(CmdSetDebug, v)
return err
}
func (d *Device) SetNetwork(ssid string) error {
_, err := d.reqStr(CmdSetNet, ssid)
return err
}
func (d *Device) SetPassphrase(ssid string, passphrase string) error {
_, err := d.reqStr2(CmdSetPassphrase, ssid, passphrase)
return err
}
func (d *Device) SetKey(ssid string, index uint8, key string) error {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
d.sendCmd(CmdSetKey, 3)
d.sendParamStr(ssid, false)
d.sendParam8(index, false)
d.sendParamStr(key, true)
d.padTo4(8 + len(ssid) + len(key))
_, err := d.waitRspCmd1(CmdSetKey)
if err != nil {
return err
}
return nil
}
func (d *Device) SetNetworkForAP(ssid string) error {
_, err := d.reqStr(CmdSetAPNet, ssid)
return err
}
func (d *Device) SetPassphraseForAP(ssid string, passphrase string) error {
_, err := d.reqStr2(CmdSetAPPassphrase, ssid, passphrase)
return err
}
func (d *Device) SetIP(which uint8, ip uint32, gw uint32, subnet uint32) error {
return ErrNotImplemented
}
func (d *Device) SetDNS(which uint8, dns1 uint32, dns2 uint32) error {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
d.sendCmd(CmdSetDNSConfig, 3)
d.sendParam8(which, false)
d.sendParam32(dns1, false)
d.sendParam32(dns2, true)
_, err := d.waitRspCmd1(CmdSetDNSConfig)
if err != nil {
return err
}
return nil
}
func (d *Device) SetHostname(hostname string) error {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
d.sendCmd(CmdSetHostname, 3)
d.sendParamStr(hostname, true)
d.padTo4(5 + len(hostname))
_, err := d.waitRspCmd1(CmdSetHostname)
if err != nil {
return err
}
return nil
}
func (d *Device) SetPowerMode(mode uint8) error {
_, err := d.reqUint8(CmdSetPowerMode, mode)
return err
}
func (d *Device) ScanNetworks() (uint8, error) {
return d.reqRspStr0(CmdScanNetworks, d.ssids[:])
}
func (d *Device) StartScanNetworks() (uint8, error) {
return d.getUint8(d.req0(CmdStartScanNetworks))
}
func (d *Device) PinMode(pin uint8, mode uint8) error {
_, err := d.req2Uint8(CmdSetPinMode, pin, mode)
return err
}
func (d *Device) DigitalWrite(pin uint8, value uint8) error {
_, err := d.req2Uint8(CmdSetDigitalWrite, pin, value)
return err
}
func (d *Device) AnalogWrite(pin uint8, value uint8) error {
_, err := d.req2Uint8(CmdSetAnalogWrite, pin, value)
return err
}
// ------------- End of public device interface ----------------------------
func (d *Device) getString(l uint8, err error) (string, error) {
if err != nil {
return "", err
}
return string(d.buf[0:l]), err
}
func (d *Device) getUint8(l uint8, err error) (uint8, error) {
if err != nil {
return 0, err
}
if l != 1 {
if _debug {
println("expected length 1, was actually", l, "\r")
}
return 0, ErrUnexpectedLength
}
return d.buf[0], err
}
func (d *Device) getUint16(l uint8, err error) (uint16, error) {
if err != nil {
return 0, err
}
if l != 2 {
if _debug {
println("expected length 2, was actually", l, "\r")
}
return 0, ErrUnexpectedLength
}
return binary.BigEndian.Uint16(d.buf[0:2]), err
}
func (d *Device) getUint32(l uint8, err error) (uint32, error) {
if err != nil {
return 0, err
}
if l != 4 {
return 0, ErrUnexpectedLength
}
return binary.LittleEndian.Uint32(d.buf[0:4]), err
}
func (d *Device) getInt32(l uint8, err error) (int32, error) {
i, err := d.getUint32(l, err)
return int32(i), err
}
func (d *Device) getFloat32(l uint8, err error) (float32, error) {
i, err := d.getUint32(l, err)
return float32(i), err
}
func (d *Device) getMACAddress(l uint8, err error) (MACAddress, error) {
if err != nil {
return 0, err
}
if l != 6 {
return 0, ErrUnexpectedLength
}
return MACAddress(binary.LittleEndian.Uint64(d.buf[0:8]) & 0xFFFFFFFFFFFF), err
}
// req0 sends a command to the device with no request parameters
func (d *Device) req0(cmd uint8) (l uint8, err error) {
if err := d.sendCmd0(cmd); err != nil {
return 0, err
}
return d.waitRspCmd1(cmd)
}
// req1 sends a command to the device with a single dummy parameters of 0xFF
func (d *Device) req1(cmd uint8) (l uint8, err error) {
return d.reqUint8(cmd, dummyData)
}
// reqUint8 sends a command to the device with a single uint8 parameter
func (d *Device) reqUint8(cmd uint8, data uint8) (l uint8, err error) {
if err := d.sendCmdPadded1(cmd, data); err != nil {
return 0, err
}
return d.waitRspCmd1(cmd)
}
// req2Uint8 sends a command to the device with two uint8 parameters
func (d *Device) req2Uint8(cmd, p1, p2 uint8) (l uint8, err error) {
if err := d.sendCmdPadded2(cmd, p1, p2); err != nil {
return 0, err
}
return d.waitRspCmd1(cmd)
}
// reqStr sends a command to the device with a single string parameter
func (d *Device) reqStr(cmd uint8, p1 string) (uint8, error) {
if err := d.sendCmdStr(cmd, p1); err != nil {
return 0, err
}
return d.waitRspCmd1(cmd)
}
// reqStr sends a command to the device with 2 string parameters
func (d *Device) reqStr2(cmd uint8, p1 string, p2 string) (uint8, error) {
if err := d.sendCmdStr2(cmd, p1, p2); err != nil {
return 0, err
}
return d.waitRspCmd1(cmd)
}
// reqStrRsp0 sends a command passing a string slice for the response
func (d *Device) reqRspStr0(cmd uint8, sl []string) (l uint8, err error) {
if err := d.sendCmd0(cmd); err != nil {
return 0, err
}
defer d.spiChipDeselect()
if err = d.waitForChipSelect(); err != nil {
return
}
return d.waitRspStr(cmd, sl)
}
// reqStrRsp1 sends a command with a uint8 param and a string slice for the response
func (d *Device) reqRspStr1(cmd uint8, data uint8, sl []string) (uint8, error) {
if err := d.sendCmdPadded1(cmd, data); err != nil {
return 0, err
}
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return 0, err
}
return d.waitRspStr(cmd, sl)
}
func (d *Device) sendCmd0(cmd uint8) error {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
d.sendCmd(cmd, 0)
return nil
}
func (d *Device) sendCmdPadded1(cmd uint8, data uint8) error {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
d.sendCmd(cmd, 1)
d.sendParam8(data, true)
d.SPI.Transfer(dummyData)
d.SPI.Transfer(dummyData)
return nil
}
func (d *Device) sendCmdPadded2(cmd, data1, data2 uint8) error {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
l := d.sendCmd(cmd, 1)
l += d.sendParam8(data1, false)
l += d.sendParam8(data2, true)
d.SPI.Transfer(dummyData)
return nil
}
func (d *Device) sendCmdStr(cmd uint8, p1 string) (err error) {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
l := d.sendCmd(cmd, 1)
l += d.sendParamStr(p1, true)
d.padTo4(5 + len(p1))
return nil
}
func (d *Device) sendCmdStr2(cmd uint8, p1 string, p2 string) (err error) {
defer d.spiChipDeselect()
if err := d.waitForChipSelect(); err != nil {
return err
}
d.sendCmd(cmd, 2)
d.sendParamStr(p1, false)
d.sendParamStr(p2, true)
d.padTo4(6 + len(p1) + len(p2))
return nil
}
func (d *Device) waitRspCmd1(cmd uint8) (l uint8, err error) {
defer d.spiChipDeselect()
if err = d.waitForChipSelect(); err != nil {
return
}
return d.waitRspCmd(cmd, 1)
}
func (d *Device) sendCmd(cmd uint8, numParam uint8) (l int) {
if _debug {
fmt.Printf(
"sendCmd: %02X %02X %02X",
CmdStart, cmd & ^(uint8(FlagReply)), numParam)
}
l = 3
d.SPI.Transfer(CmdStart)
d.SPI.Transfer(cmd & ^(uint8(FlagReply)))
d.SPI.Transfer(numParam)
if numParam == 0 {
d.SPI.Transfer(CmdEnd)
l += 1
if _debug {
fmt.Printf(" %02X", CmdEnd)
}
}
if _debug {
fmt.Printf(" (%d)\r\n", l)
}
return
}
func (d *Device) sendParamLen16(p uint16) (l int) {
d.SPI.Transfer(uint8(p >> 8))
d.SPI.Transfer(uint8(p & 0xFF))
if _debug {
fmt.Printf(" %02X %02X", uint8(p>>8), uint8(p&0xFF))
}
return 2
}
func (d *Device) sendParamBuf(p []byte, isLastParam bool) (l int) {
if _debug {
println("sendParamBuf:")
}
l += d.sendParamLen16(uint16(len(p)))
for _, b := range p {
if _debug {
fmt.Printf(" %02X", b)
}
d.SPI.Transfer(b)
l += 1
}
if isLastParam {
if _debug {
fmt.Printf(" %02X", CmdEnd)
}
d.SPI.Transfer(CmdEnd)
l += 1
}
if _debug {
fmt.Printf(" (%d) \r\n", l)
}
return
}
func (d *Device) sendParamStr(p string, isLastParam bool) (l int) {
l = len(p)
d.SPI.Transfer(uint8(l))
if l > 0 {
d.SPI.Tx([]byte(p), nil)
}
if isLastParam {
d.SPI.Transfer(CmdEnd)
l += 1
}
return