forked from electricimp/Wiznet_5500
-
Notifications
You must be signed in to change notification settings - Fork 0
/
W5500.device.lib.nut
2613 lines (2197 loc) · 93.6 KB
/
W5500.device.lib.nut
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
// MIT License
//
// Copyright 2016-2017 Electric Imp
//
// SPDX-License-Identifier: MIT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// BLOCK SELECT BITS
const W5500_COMMON_REGISTER = 0x00;
const W5500_S0_REGISTER = 0x08;
const W5500_S0_TX_BUFFER = 0x10;
const W5500_S0_RX_BUFFER = 0x18;
const W5500_S1_REGISTER = 0x28;
const W5500_S1_TX_BUFFER = 0x30;
const W5500_S1_RX_BUFFER = 0x38;
const W5500_S2_REGISTER = 0x48;
const W5500_S2_TX_BUFFER = 0x50;
const W5500_S2_RX_BUFFER = 0x58;
const W5500_S3_REGISTER = 0x68;
const W5500_S3_TX_BUFFER = 0x70;
const W5500_S3_RX_BUFFER = 0x78;
const W5500_S4_REGISTER = 0x88;
const W5500_S4_TX_BUFFER = 0x90;
const W5500_S4_RX_BUFFER = 0x98;
const W5500_S5_REGISTER = 0xA8;
const W5500_S5_TX_BUFFER = 0xB0;
const W5500_S5_RX_BUFFER = 0xB8;
const W5500_S6_REGISTER = 0xC8;
const W5500_S6_TX_BUFFER = 0xD0;
const W5500_S6_RX_BUFFER = 0xD8;
const W5500_S7_REGISTER = 0xE8;
const W5500_S7_TX_BUFFER = 0xF0;
const W5500_S7_RX_BUFFER = 0xF8;
// READ/WRITE BIT
const W5500_READ_COMMAND = 0x00;
const W5500_WRITE_COMMAND = 0x04;
// SPI OPPERATION MODE
const W5500_VARIABLE_DATA_LENGTH = 0x00;
const W5500_FIXED_DATA_LENGTH_1 = 0x01;
const W5500_FIXED_DATA_LENGTH_2 = 0x02;
const W5500_FIXED_DATA_LENGTH_4 = 0x03;
// COMMON REGISTERS OFFSET ADDRESSES
// MR
const W5500_MODE = 0x0000;
// GWR
const W5500_GATEWAY_ADDR_0 = 0x0001;
const W5500_GATEWAY_ADDR_1 = 0x0002;
const W5500_GATEWAY_ADDR_2 = 0x0003;
const W5500_GATEWAY_ADDR_3 = 0x0004;
// SUBR
const W5500_SUBNET_MASK_ADDR_0 = 0x0005;
const W5500_SUBNET_MASK_ADDR_1 = 0x0006;
const W5500_SUBNET_MASK_ADDR_2 = 0x0007;
const W5500_SUBNET_MASK_ADDR_3 = 0x0008;
// SHAR
const W5500_SOURCE_HW_ADDR_0 = 0x0009;
const W5500_SOURCE_HW_ADDR_1 = 0x000A;
const W5500_SOURCE_HW_ADDR_2 = 0x000B;
const W5500_SOURCE_HW_ADDR_3 = 0x000C;
const W5500_SOURCE_HW_ADDR_4 = 0x000D;
const W5500_SOURCE_HW_ADDR_5 = 0x000E;
// SIPR
const W5500_SOURCE_IP_ADDR_0 = 0x000F;
const W5500_SOURCE_IP_ADDR_1 = 0x0010;
const W5500_SOURCE_IP_ADDR_2 = 0x0011;
const W5500_SOURCE_IP_ADDR_3 = 0x0012;
// INTLEVEL
const W5500_INTERRUPT_LOW_LEVEL_TIMER_0 = 0x0013;
const W5500_INTERRUPT_LOW_LEVEL_TIMER_1 = 0x0014;
// IR
const W5500_INTERRUPT = 0x0015;
// IMR
const W5500_INTERRUPT_MASK = 0x0016;
// SIR
const W5500_SOCKET_INTERRUPT = 0x0017;
// SIMR
const W5500_SOCKET_INTERRUPT_MASK = 0x0018;
// RTR
const W5500_RETRY_TIME_0 = 0x0019;
const W5500_RETRY_TIME_1 = 0x001A;
// RCR
const W5500_RETRY_COUNT = 0x001B;
// PHYSICAL CONFIG
const W5500_PHYSICAL_CONFIG = 0x002E;
// VERSION
const W5500_CHIP_VERSION = 0x0039;
// SOCKET REGISTER OFFSET ADDRESSES
const W5500_SOCKET_MODE = 0x0000;
const W5500_SOCKET_COMMAND = 0x0001;
const W5500_SOCKET_N_INTERRUPT = 0x0002;
const W5500_SOCKET_STATUS = 0x0003;
const W5500_SOCKET_SOURCE_PORT_0 = 0x0004;
const W5500_SOCKET_SOURCE_PORT_1 = 0x0005;
const W5500_SOCKET_DEST_HW_ADDR_0 = 0x0006;
const W5500_SOCKET_DEST_HW_ADDR_1 = 0x0007;
const W5500_SOCKET_DEST_HW_ADDR_2 = 0x0008;
const W5500_SOCKET_DEST_HW_ADDR_3 = 0x0009;
const W5500_SOCKET_DEST_HW_ADDR_4 = 0x000A;
const W5500_SOCKET_DEST_HW_ADDR_5 = 0x000B;
const W5500_SOCKET_DEST_IP_ADDR_0 = 0x000C;
const W5500_SOCKET_DEST_IP_ADDR_1 = 0x000D;
const W5500_SOCKET_DEST_IP_ADDR_2 = 0x000E;
const W5500_SOCKET_DEST_IP_ADDR_3 = 0x000F;
const W5500_SOCKET_DEST_PORT_0 = 0x0010;
const W5500_SOCKET_DEST_PORT_1 = 0x0011;
const W5500_SOCKET_RX_BUFFER_SIZE = 0x001E;
const W5500_SOCKET_TX_BUFFER_SIZE = 0x001F;
// SOCKET TX FREE SIZE REGISTER (Sn_TX_FREE_SIZE)
const W5500_SOCKET_TX_SIZE_R1 = 0x0020;
const W5500_SOCKET_TX_SIZE_R2 = 0x0021;
// SOCKET TX READ POINTER
const W5500_SOCKET_TX_RP_R1 = 0x0022;
const W5500_SOCKET_TX_RP_R2 = 0x0023;
// SOCKET TX WRITE POINTER
const W5500_SOCKET_TX_WP_R1 = 0x0024;
const W5500_SOCKET_TX_WP_R2 = 0x0025;
// SOCKET RX RECEIVED SIZE REGISTER (Sn_RX_RSR)
const W5500_SOCKET_RX_SIZE_R1 = 0x0026;
const W5500_SOCKET_RX_SIZE_R2 = 0x0027;
// SOCKET RX READ POINTER (Sn_RX_RD)
const W5500_SOCKET_RX_RP_R1 = 0x0028;
const W5500_SOCKET_RX_RP_R2 = 0x0029;
// SOCKET N INTERRUPT MASK (Sn_IMR)
const W5500_SOCKET_N_INTERRUPT_MASK = 0x002C;
// MODES
const W5500_SW_RESET = 0x80;
const W5500_WAKE_ON_LAN = 0x20;
const W5500_PING_BLOCK = 0x10;
const W5500_PPPoE = 0x08;
const W5500_FORCE_ARP = 0x01;
const W5500_DEFAULT_MODE = 0x00;
// SOCKET MODES (Sn_MR)
const W5500_SOCKET_MODE_MULTI = 0x80;
const W5500_SOCKET_MODE_BROADCAST_BLOCKING = 0x40;
const W5500_SOCKET_MODE_NO_DELAY_ACK = 0x20;
const W5500_SOCKET_MODE_UNICAST_BLOCKING = 0x10;
const W5500_SOCKET_MODE_CLOSED = 0x00;
const W5500_SOCKET_MODE_TCP = 0x01;
const W5500_SOCKET_MODE_UDP = 0x02;
const W5500_SOCKET_MODE_MACRAW = 0x03;
// SOCKET COMMANDS (Sn_CR)
const W5500_SOCKET_OPEN = 0x01;
const W5500_SOCKET_LISTEN = 0x02;
const W5500_SOCKET_CONNECT = 0x04;
const W5500_SOCKET_DISCONNECT = 0x08;
const W5500_SOCKET_CLOSE = 0x10;
const W5500_SOCKET_SEND = 0x20;
const W5500_SOCKET_SEND_MAC = 0x21;
const W5500_SOCKET_SEND_KEEP = 0x22;
const W5500_SOCKET_RECEIVE = 0x40;
// SOCKET STATUS (Sn_SR)
const W5500_SOCKET_STATUS_CLOSED = 0x00;
const W5500_SOCKET_STATUS_INIT = 0x13;
const W5500_SOCKET_STATUS_LISTEN = 0x14;
const W5500_SOCKET_STATUS_ESTABLISHED = 0x17;
const W5500_SOCKET_STATUS_CLOSE_WAIT = 0x1C;
const W5500_SOCKET_STATUS_UDP = 0x22;
const W5500_SOCKET_STATUS_MACRAW = 0x42;
const W5500_SOCKET_STATUS_SYNSENT = 0x15;
const W5500_SOCKET_STATUS_SYNRECV = 0x16;
const W5500_SOCKET_STATUS_FIN_WAIT = 0x18;
const W5500_SOCKET_STATUS_CLOSING = 0x1A;
const W5500_SOCKET_STATUS_TIME_WAIT = 0x1B;
const W5500_SOCKET_STATUS_LAST_ACK = 0x1D;
// INTERRUPT TYPES
const W5500_CONFLICT_INT_TYPE = 0x80;
const W5500_UNREACH_INT_TYPE = 0x40;
const W5500_PPPoE_INT_TYPE = 0x20;
const W5500_MAGIC_PACKET_TYPE = 0x10;
const W5500_NONE_INT_TYPE = 0x00;
// SOCKET INTERRUPTS
const W5500_DISABLE_SOCKET_INTERRUPTS = 0x00;
const W5500_S0_INTERRUPT = 0x01;
const W5500_S1_INTERRUPT = 0x02;
const W5500_S2_INTERRUPT = 0x04;
const W5500_S3_INTERRUPT = 0x08;
const W5500_S4_INTERRUPT = 0x10;
const W5500_S5_INTERRUPT = 0x20;
const W5500_S6_INTERRUPT = 0x40;
const W5500_S7_INTERRUPT = 0x80;
// SOCKET INTERRUPT TYPES
const W5500_SEND_COMPLETE_INT_TYPE = 0x10;
const W5500_TIMEOUT_INT_TYPE = 0x08;
const W5500_DATA_RECEIVED_INT_TYPE = 0x04;
const W5500_DISCONNECTED_INT_TYPE = 0x02;
const W5500_CONNECTED_INT_TYPE = 0x01;
const W5500_ALL_INT_TYPES = 0x1F;
// Socket states
enum W5500_SOCKET_STATES {
CLOSED,
INIT,
CONNECTING,
LISTENING,
ESTABLISHED,
DISCONNECTING
}
// Error messages
const W5500_ERR_INVALID_PARAMETERS = "Provide 'ip', 'port', 'mode' and a callback";
const W5500_ERR_CANNOT_CONNECT_STILL_CLEANING = "Cannot open a connection. Still cleaning up";
const W5500_ERR_CANNOT_CONNECT_SOCKETS_IN_USE = "Cannot open a connection. All connection sockets in use";
const W5500_ERR_CANNOT_CONNECT_TIMEOUT = "Connection timeout";
const W5500_ERR_TRANSMIT_TIMEOUT = "Transmit timeout";
const W5500_ERR_RECEIVE_TIMEOUT = "Receive timeout";
const W5500_ERR_COMMAND_TIMEOUT = "Command timeout";
const W5500_ERR_NOT_CONNECTED = "Not connected";
// Miscellaneous constants
const W5500_CONNECT_TIMEOUT = 60;
const W5500_TRANSMIT_TIMEOUT = 8;
const W5500_COMMAND_TIMEOUT = 3;
const W5500_INTERRUPT_POLL_TIME_IDLE = 0.5;
const W5500_INTERRUPT_POLL_TIME_ACTIVE = 0.01;
// ==============================================================================
// CLASS: W5500
// ==============================================================================
class W5500 {
static VERSION = "2.1.0";
_driver = null;
_isReady = false; // set to true once the driver is loaded and connection to chip made
_readyCb = null; // callback for when isReady becomes true
_networkSettings = null;
// TODO: implement this
_autoRetry = false;
// ***************************************************************************
// Constructor
// Returns: null
// Parameters:
// interruptPin - interrupt pin
// spi - configured spi bus, chip supports spi mode 0 or 3
// csPin(optional) - chip select pin, pass in if not using imp005
// resetPin(optional) - reset pin
// autoRetry(optional) - not implemented yet.
// setMac(optional) - set the MAC address of the chip to the imp's own
// MAC, with the last bit flipped.
// ***************************************************************************
constructor(interruptPin, spi, csPin = null, resetPin = null, autoRetry = false, setMac = true) {
// Initialise the driver
_driver = W5500.Driver(interruptPin, spi, csPin, resetPin, setMac);
_driver.init(function() {
// Let the caller know the device is ready
_isReady = true;
if (_readyCb) imp.wakeup(0, _readyCb);
}.bindenv(this));
}
// ***************************************************************************
// reset, note this is blocking for 0.2s
// Returns: this
// Parameters:
// sw(optional) - boolean if true forces a software reset
// Note: Datasheet states that SW reset should not be used
// on the W5500.
// ***************************************************************************
function reset(sw = false) {
// Initialise the driver
_isReady = false;
_driver.reset(sw, function() {
_driver.init(function() {
// Let the caller know the device is ready
_isReady = true;
if (_readyCb) imp.wakeup(0, _readyCb);
}.bindenv(this));
}.bindenv(this));
}
// ***************************************************************************
// onReady
// Returns: this
// Parameters:
// cb - function to be called when the Wiznet device is initialised
// ***************************************************************************
function onReady(cb) {
local _cb = cb;
if (_networkSettings != null) {
// Slip the network settings into the _cb
_cb = function() {
if ("availableSockets" in _networkSettings) {
_driver.setNumberOfAvailableSockets(_networkSettings.availableSockets);
}
if ("sourceIP" in _networkSettings) {
configureNetworkSettings(_networkSettings.sourceIP, _networkSettings.subnetMask, _networkSettings.gatewayIP, _networkSettings.mac);
}
_networkSettings = null;
cb();
}.bindenv(this);
}
if (_isReady) imp.wakeup(0, _cb);
else _readyCb = _cb;
return this;
}
// ***************************************************************************
// setNumberOfAvailableSockets - configures interrupts and memory for each connection
// Returns: number of actual connections configured
// Parameters:
// numSockets - number of desired connections
// **************************************************************************
function setNumberOfAvailableSockets(numSockets = null) {
if (_isReady) {
return _driver.setNumberOfAvailableSockets(numSockets);
} else {
if (_networkSettings == null) {
_networkSettings = {};
}
_networkSettings.availableSockets <- numSockets;
}
}
// ***************************************************************************
// isPhysicallyConnected
// Returns: true if there is a cable plugged in
// Parameters:
// none
// ***************************************************************************
function isPhysicallyConnected() {
return _driver.getPhysicalLinkStatus();
}
// ***************************************************************************
// forceCloseAllSockets
// Returns: nothing
// Parameters:
// none
// ***************************************************************************
function forceCloseAllSockets() {
return _driver.forceCloseAllSockets();
}
// ***************************************************************************
// configureNetworkSettings
// Returns: this
// Parameters:
// sourceIP - ip adress of the Wiznet
// subnetMask - subnetMask for the Wiznet
// gatewayIP - gatewayIP for the Wiznet
// mac - mac adress for the wiznet
// ***************************************************************************
function configureNetworkSettings(sourceIP, subnetMask = null, gatewayIP = null, mac = null) {
if (_isReady) {
if (gatewayIP) _driver.setGatewayAddr(gatewayIP);
if (mac) _driver.setSourceHWAddr(mac);
else _driver.setSourceHWAddr(imp.getmacaddress(), true);
if (subnetMask) _driver.setSubnetMask(subnetMask);
if (sourceIP) _driver.setSourceIP(sourceIP);
_networkSettings = null;
} else {
if (_networkSettings == null) _networkSettings = {};
_networkSettings.sourceIP <- sourceIP;
_networkSettings.subnetMask <- subnetMask;
_networkSettings.gatewayIP <- gatewayIP;
_networkSettings.mac <- mac;
}
return this;
}
// ***************************************************************************
// openConnection
// Returns: connection instance
// Parameters:
// ip - the ip address of the destination
// port - the port of the destination
// mode - TCP or UDP
// cb - function to be called when connection successfully
// established or a timeout has occurred
// ****************************************************************************
function openConnection(ip, port, mode = W5500_SOCKET_MODE_TCP, cb = null) {
if (!_isReady) throw "Wiznet driver not ready";
if ((mode == null && cb == null) || (typeof mode != "function" && cb == null)) {
if (cb) cb(W5500_ERR_INVALID_PARAMETERS, null);
else throw W5500_ERR_INVALID_PARAMETERS;
return;
} else if (typeof mode == "function") {
cb = mode;
mode = W5500_SOCKET_MODE_TCP;
}
// Create a socket, a connection object & a handler
_driver.openConnection(ip, port, mode, cb);
}
// ***************************************************************************
// listen
// Returns: this
// Parameters:
// sourcePort - the port to listen on
// cb - function to be called when connection successfully established
// ****************************************************************************
function listen(sourcePort, cb) {
if (!_isReady) throw "Wiznet driver not ready";
// Create a socket, a connection object & a handler
_driver.listen(sourcePort, cb);
}
// ***************************************************************************
// getNumSockets -
// Returns: returns the total number of sockets available
// Parameters:
// none
// **************************************************************************
function getNumSockets() {
return _driver._noOfSockets;
}
// ***************************************************************************
// getNumSocketsFree -
// Returns: returns the number of unused sockets
// Parameters:
// none
// **************************************************************************
function getNumSocketsFree() {
return _driver._noOfSockets - _driver._connections.len();
}
}
// ==============================================================================
// CLASS: W5500.Driver
// ==============================================================================
class W5500.Driver {
// Chip can support 8 sockets
static TOTAL_SUPPORTED_SOCKETS = 8;
static MAX_TX_MEM_BUFFER = 16;
static MAX_RX_MEM_BUFFER = 16;
// CLASS VARIABLES
_interruptPin = null;
_spi = null;
_cs = null;
_resetPin = null;
_setMac = null;
_connections = null; // open connections
_availableSockets = null; // array of sockets available
_maxNoOfSockets = 0; // max number of sockets wiznet may use
_noOfSockets = 0; // number of sockets
_socketMemory = null; // amount of memeory each socket has
// ***************************************************************************
// Constructor
// Returns: null
// Parameters:
// interruptPin - interrupt pin
// spi - configured spi, W5500 supports spi mode 0 or 3
// cs(optional) - configured chip select pin
// reset(optional) - configured reset pin
// setMac(optional) - set the MAC address of the chip to the imp's own
// MAC, with the last bit flipped.
// ***************************************************************************
constructor(interruptPin, spi, cs = null, resetPin = null, setMac = true) {
_interruptPin = interruptPin;
_spi = spi;
_cs = cs;
_resetPin = resetPin;
_setMac = setMac;
_connections = {};
_availableSockets = [];
// Check the pins
if (resetPin) _resetPin.configure(DIGITAL_OUT, 1);
// TODO: When imp.info() is available, change this code.
local imp005 = ("spi0" in hardware);
if (_cs != null) {
_cs.configure(DIGITAL_OUT, 1);
} else if (!imp005) {
throw "You must pass in a chip select pin."
}
// Reset the hardware
reset();
}
// ***************************************************************************
// reset, note this is blocking for 0.2s
// Returns: this
// Parameters:
// sw(optional) - boolean if true forces a software reset
// Note: datasheet for W5500 states that software reset is
// unreliable - don't use
// **************************************************************************
function reset(sw = false, cb = null) {
// Wrangle the parameters
if (typeof sw == "function") {
cb = sw;
sw = false;
}
// Stop the interrupt pin from firing
_interruptPin.configure(DIGITAL_IN);
// Clear the connections and sockets
_connections = {};
_availableSockets = [];
// Force disconnect/close all ports
forceCloseAllSockets();
if (cb) {
// Asynchronouse reset
if (sw || _resetPin == null) {
setMode(W5500_SW_RESET);
// Allow things to settle down again
imp.wakeup(1.0, function() {
// Reset the default memory allocation
_setMemDefaults();
cb();
}.bindenv(this));
} else {
// hold at least 500us after assert low
_resetPin.write(0);
imp.wakeup(0.3, function() {
_resetPin.write(1);
// Allow things to settle down again
imp.wakeup(1.0, function() {
// Reset the default memory allocation
_setMemDefaults();
cb();
}.bindenv(this));
}.bindenv(this));
}
} else {
// Synchronous reset
if (sw || _resetPin == null) {
setMode(W5500_SW_RESET);
// Allow things to settle down again
imp.sleep(1.0);
// Reset the default memory allocation
_setMemDefaults();
} else {
// hold at least 500us after assert low
_resetPin.write(0);
imp.sleep(0.3);
_resetPin.write(1);
// Allow things to settle down again
imp.sleep(1.0);
// Reset the default memory allocation
_setMemDefaults();
}
}
return this;
}
// ***************************************************************************
// init(cb) - initialises the device to basic defaults ready for use after boot or reset
// Returns: nothing
// Parameters:
// cb - callback function
//
// ***************************************************************************
function init(cb) {
// Configure interrupts
setInterrupt(W5500_CONFLICT_INT_TYPE);
clearInterrupt();
clearSocketInterrupts();
_interruptPin.configure(DIGITAL_IN_PULLUP, handleInterrupt.bindenv(this));
// Set the default mac address
if (_setMac){
setSourceHWAddr(imp.getmacaddress(), true);
}
// Set the defaults
setNumberOfAvailableSockets(TOTAL_SUPPORTED_SOCKETS);
// Done
imp.wakeup(0, cb);
}
// ***************************************************************************
// forceCloseAllSockets, note this is blocking for 1.1s+
// Returns: this
// Parameters:
// none
// **************************************************************************
function forceCloseAllSockets() {
_maxNoOfSockets = getTotalSupportedSockets();
for (local socket = 0; socket < _maxNoOfSockets; socket++) {
sendSocketCommand(socket, W5500_SOCKET_DISCONNECT);
}
imp.sleep(1);
for (local socket = 0; socket < _maxNoOfSockets; socket++) {
sendSocketCommand(socket, W5500_SOCKET_CLOSE);
}
imp.sleep(0.1);
}
// ***************************************************************************
// getPhysicalLinkStatus
// Returns: true or false
// Parameters:
// none
// ***************************************************************************
function getPhysicalLinkStatus() {
local status = readReg(W5500_PHYSICAL_CONFIG, W5500_COMMON_REGISTER);
return (status & 0x01) == 0x01;
}
// ***************************************************************************
// openConnection
// Returns: this
// Parameters:
// destIP - the ip address of the destination
// destPort - the port of the destination
// mode - TCP or UDP
// sourcePort(optional) - the port to send from
// cb - function to be called when connection successfully established
// ****************************************************************************
function openConnection(destIP, destPort, mode, sourcePort = null, cb = null) {
// shuffle oarameters around
if (typeof sourcePort == "function") {
cb = sourcePort;
sourcePort = null;
}
// check for available socket
if (_availableSockets.len() == 0) {
if (cb) return cb(W5500_ERR_CANNOT_CONNECT_SOCKETS_IN_USE, null);
else throw W5500_ERR_CANNOT_CONNECT_SOCKETS_IN_USE;
}
// Create the connection object and assign it to a spare socket
local socket = _availableSockets.pop();
_connections[socket] <- W5500.Connection(this, socket, destIP, destPort, mode);
if (typeof sourcePort == "integer") {
_connections[socket].setSourcePort(sourcePort);
}
_connections[socket].open(cb);
}
// ***************************************************************************
// listen
// Returns: this
// Parameters:
// sourcePort - the port to listen on
// cb - function to be called when connection successfully established
// ****************************************************************************
function listen(sourcePort, cb) {
// check for available socket
if (_availableSockets.len() == 0) {
return cb(W5500_ERR_CANNOT_CONNECT_SOCKETS_IN_USE, null);
}
local socket = _availableSockets.pop();
// Create the connection object and assign it to a spare socket
_connections[socket] <- W5500.Connection(this, socket, null, null, W5500_SOCKET_MODE_TCP);
_connections[socket].setSourcePort(sourcePort);
_connections[socket].listen(cb);
}
// ***************************************************************************
// closeConnection
// Returns: this
// Parameters:
// socket - the socket of the connection to close
// cb(optional) - function
// ***************************************************************************
function closeConnection(socket, cb = null) {
if (getSocketStatus(socket) == W5500_SOCKET_STATUS_ESTABLISHED) {
sendSocketCommand(socket, W5500_SOCKET_DISCONNECT);
} else {
sendSocketCommand(socket, W5500_SOCKET_CLOSE);
}
local started = hardware.millis();
waitForSocketStatus(socket, W5500_SOCKET_STATUS_CLOSED, function(success) {
// Wait a second from the start
local waitfor = 1000 - (hardware.millis() - started);
if (waitfor < 0) waitfor = 0;
imp.wakeup(waitfor / 1000.0, function() {
deregisterSocket(socket);
if (cb) cb();
}.bindenv(this));
}.bindenv(this));
return this;
}
// ***************************************************************************
// deregisterSocket
// Returns:
// Parameters:
// socket - the socket of the connection to deregister
// ***************************************************************************
function deregisterSocket(socket) {
// Return this to the available pool
if (_availableSockets.find(socket) == null) {
_availableSockets.push(socket);
}
if (socket in _connections) {
_connections.rawdelete(socket);
}
}
// GETTERS AND SETTERS
// ---------------------------------------------
// ***************************************************************************
// setMemory
// Returns: this
// Parameters:
// memory - an array of four integers with the desired transmit memory
// allotment for each socket (supported values are 0, 1, 2, 4, 8, 16)
// dir - a string containing the transmition direction, accepted values
// are "tx" or "rx"
// ***************************************************************************
function setMemory(memory, dir) {
local memoryBufferSize = 16;
local addr = (dir == "rx") ? W5500_SOCKET_RX_BUFFER_SIZE : W5500_SOCKET_TX_BUFFER_SIZE;
local bits = 0x00;
local total = 0;
foreach (socket, mem_size in memory) {
local socket_mem = 0x00;
local bytes = 0;
// adjust memory size if total memory is used up
if (total + mem_size > memoryBufferSize) {
mem_size = memoryBufferSize - total;
if (mem_size < 0) mem_size = 0;
}
if (mem_size == memoryBufferSize) {
bytes = 16384;
} else if (mem_size >= 8) {
mem_size = 8;
bytes = 8192;
} else if (mem_size >= 4) {
mem_size = 4;
bytes = 4096;
} else if (mem_size >= 2) {
mem_size = 2;
bytes = 2048;
} else if (mem_size >= 1) {
mem_size = 1;
bytes = 1024;
} else {
mem_size = 0;
bytes = 0;
}
total += mem_size;
_socketMemory[dir][socket] = bytes;
local bsb = _getSocketRegBlockSelectBit(socket);
writeReg(addr, bsb, mem_size);
}
return this;
}
// ***************************************************************************
// getMemory
// Returns: the buffer size
// Parameters:
// dir - a string containing the transmition direction, accepted values
// are "tx" or "rx"
// ***************************************************************************
function getMemory(dir, socket) {
return _socketMemory[dir][socket];
}
// ***************************************************************************
// setMode
// Returns: this
// Parameters:
// mode - select mode using MODE constants or-ed together
// ***************************************************************************
function setMode(mode) {
writeReg(W5500_MODE, W5500_COMMON_REGISTER, mode);
return this;
}
// ***************************************************************************
// setRetries
// Returns: this
// Parameters:
// time - amount of time (in ms) for each attempt (default: 2000ms)
// count - the number of retry attempts (default: 5x)
// ***************************************************************************
function setRetries(time = 3000, count = 5) {
local time_us = time * 1000 / 100;
writeReg(W5500_RETRY_TIME_0, W5500_COMMON_REGISTER, ((time_us & 0xFF00) >> 8));
writeReg(W5500_RETRY_TIME_1, W5500_COMMON_REGISTER, (time_us & 0x00FF));
writeReg(W5500_RETRY_COUNT, W5500_COMMON_REGISTER, count);
return this;
}
// ***************************************************************************
// setSocketMode
// Returns: this
// Parameters:
// socket - select the socket using an integer 0-3
// mode - select mode using W5500_SOCKET_MODE constant
// ***************************************************************************
function setSocketMode(socket, mode) {
local bsb = _getSocketRegBlockSelectBit(socket)
writeReg(W5500_SOCKET_MODE, bsb, mode);
return this;
}
// ***************************************************************************
// setGatewayAddr
// Returns: this
// Parameters:
// addr - an array of four integers with the gateway IP address
// ***************************************************************************
function setGatewayAddr(addr) {
local addr = _addrToIP(addr);
// Check that the address is actually different
local old_addr = getGatewayAddr();
if (_areObjectsEqual(addr, old_addr)) return;
writeReg(W5500_GATEWAY_ADDR_0, W5500_COMMON_REGISTER, addr[0]);
writeReg(W5500_GATEWAY_ADDR_1, W5500_COMMON_REGISTER, addr[1]);
writeReg(W5500_GATEWAY_ADDR_2, W5500_COMMON_REGISTER, addr[2]);
writeReg(W5500_GATEWAY_ADDR_3, W5500_COMMON_REGISTER, addr[3]);
return this;
}
// ***************************************************************************
// getGatewayAddr
// Returns: an array of four integers with the gateway IP address
// Parameters:
// none
// **************************************************************************
function getGatewayAddr() {
local addr = array(4);
// server.log((hardware.millis() - started) + ": DBG setGatewayAddr: " + pformat(addr));
addr[0] = readReg(W5500_GATEWAY_ADDR_0, W5500_COMMON_REGISTER);
addr[1] = readReg(W5500_GATEWAY_ADDR_1, W5500_COMMON_REGISTER);
addr[2] = readReg(W5500_GATEWAY_ADDR_2, W5500_COMMON_REGISTER);
addr[3] = readReg(W5500_GATEWAY_ADDR_3, W5500_COMMON_REGISTER);
return addr;
}
// ***************************************************************************
// setSubnetMask
// Returns: this
// Parameters:
// addr - an array of four integers with the subnet mask
// **************************************************************************
function setSubnetMask(addr) {
local addr = _addrToIP(addr);
// Check that the address is actually different
local old_addr = getSubnetMask();
if (_areObjectsEqual(addr, old_addr)) return;
writeReg(W5500_SUBNET_MASK_ADDR_0, W5500_COMMON_REGISTER, addr[0]);
writeReg(W5500_SUBNET_MASK_ADDR_1, W5500_COMMON_REGISTER, addr[1]);
writeReg(W5500_SUBNET_MASK_ADDR_2, W5500_COMMON_REGISTER, addr[2]);
writeReg(W5500_SUBNET_MASK_ADDR_3, W5500_COMMON_REGISTER, addr[3]);
return this;
}
// ***************************************************************************
// getSubnet
// Returns: an array of four integers with the subnet address
// Parameters:
// none
// **************************************************************************
function getSubnetMask() {
local addr = array(4);
// server.log((hardware.millis() - started) + ": DBG setSubnet: " + pformat(addr));
addr[0] = readReg(W5500_SUBNET_MASK_ADDR_0, W5500_COMMON_REGISTER);
addr[1] = readReg(W5500_SUBNET_MASK_ADDR_1, W5500_COMMON_REGISTER);
addr[2] = readReg(W5500_SUBNET_MASK_ADDR_2, W5500_COMMON_REGISTER);
addr[3] = readReg(W5500_SUBNET_MASK_ADDR_3, W5500_COMMON_REGISTER);
return addr;
}
// ***************************************************************************
// setSourceHWAddr
// Returns: this
// Parameters:
// addr - an array of 6 integers with the mac address for the
// source hardware
// **************************************************************************
function setSourceHWAddr(addr, flip_public_bit = false) {
if (typeof addr == "string") {
// Convert from a string
addr = _addrToMac(addr);
}