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
|
/*
* EthernetInterface.cpp
*
* Created on: 24 Nov 2017
* Authors: David and Christian
*/
// Define this to keep the ASF status codes from being included. Without it ERR_TIMEOUT is defined twice
#define NO_STATUS_CODES
#include "LwipEthernetInterface.h"
#include "Networking/NetworkBuffer.h"
#include "LwipSocket.h"
#include "Platform.h"
#include "RepRap.h"
#include "Networking/HttpResponder.h"
#include "Networking/FtpResponder.h"
#include "Networking/TelnetResponder.h"
#include "General/IP4String.h"
#include "Version.h"
#include "GMAC/ethernet_sam.h"
extern "C"
{
#ifdef LWIP_STATS
#include "lwip/stats.h"
#endif
#include "lwip/dhcp.h"
#include "lwip/tcp.h"
#include "lwip/apps/netbiosns.h"
#include "lwip/apps/mdns.h"
extern struct netif gs_net_if;
}
const char * const MdnsServiceStrings[NumProtocols] = { "_http", "_ftp", "_telnet" };
const char * const MdnsTxtRecords[2] = { "product=" FIRMWARE_NAME, "version=" VERSION };
const unsigned int MdnsTtl = 10 * 60; // same value as on the Duet 0.6/0.8.5
/*-----------------------------------------------------------------------------------*/
static LwipEthernetInterface *ethernetInterface;
# include <RTOSIface/RTOSIface.h>
Mutex lwipMutex;
extern "C"
{
// Task function to keep the GMAC and LwIP running
void DoEthernetTask()
{
ethernet_task();
}
// Callback functions for LWIP (may be called from ISR)
static err_t conn_accept(void *arg, tcp_pcb *pcb, err_t err)
{
LWIP_UNUSED_ARG(arg);
LWIP_UNUSED_ARG(err);
if (ethernetInterface->ConnectionEstablished(pcb))
{
// A socket has accepted this connection and will deal with it
return ERR_OK;
}
tcp_abort(pcb);
return ERR_ABRT;
}
} // end extern "C"
/*-----------------------------------------------------------------------------------*/
LwipEthernetInterface::LwipEthernetInterface(Platform& p) noexcept : platform(p), closeDataPort(false), state(NetworkState::disabled),
activated(false), initialised(false), usingDhcp(false)
{
ethernetInterface = this;
// Create the sockets
for (size_t i : ARRAY_INDICES(sockets))
{
sockets[i] = new LwipSocket(this);
}
// Initialise default ports
for (size_t i = 0; i < NumProtocols; ++i)
{
portNumbers[i] = DefaultPortNumbers[i];
protocolEnabled[i] = (i == HttpProtocol);
}
}
#if SUPPORT_OBJECT_MODEL
// Object model table and functions
// Note: if using GCC version 7.3.1 20180622 and lambda functions are used in this table, you must compile this file with option -std=gnu++17.
// Otherwise the table will be allocated in RAM instead of flash, which wastes too much RAM.
// Macro to build a standard lambda function that includes the necessary type conversions
#define OBJECT_MODEL_FUNC(...) OBJECT_MODEL_FUNC_BODY(LwipEthernetInterface, __VA_ARGS__)
constexpr ObjectModelTableEntry LwipEthernetInterface::objectModelTable[] =
{
// These entries must be in alphabetical order
{ "actualIP", OBJECT_MODEL_FUNC(self->ipAddress), ObjectModelEntryFlags::none },
{ "gateway", OBJECT_MODEL_FUNC(self->gateway), ObjectModelEntryFlags::none },
{ "mac", OBJECT_MODEL_FUNC(self->macAddress), ObjectModelEntryFlags::none },
{ "subnet", OBJECT_MODEL_FUNC(self->netmask), ObjectModelEntryFlags::none },
{ "type", OBJECT_MODEL_FUNC_NOSELF("ethernet"), ObjectModelEntryFlags::none },
};
constexpr uint8_t LwipEthernetInterface::objectModelTableDescriptor[] = { 1, 5 };
DEFINE_GET_OBJECT_MODEL_TABLE(LwipEthernetInterface)
#endif
void LwipEthernetInterface::Init() noexcept
{
interfaceMutex.Create("LwipIface");
//TODO we don't yet use this mutex anywhere!
lwipMutex.Create("LwipCore");
// Clear the PCBs
for (size_t i = 0; i < NumTcpPorts; ++i)
{
listeningPcbs[i] = nullptr;
}
macAddress = platform.GetDefaultMacAddress();
}
GCodeResult LwipEthernetInterface::EnableProtocol(NetworkProtocol protocol, int port, int secure, const StringRef& reply) noexcept
{
if (secure != 0 && secure != -1)
{
reply.copy("this firmware does not support TLS");
return GCodeResult::error;
}
if (protocol < NumProtocols)
{
const Port portToUse = (port < 0) ? DefaultPortNumbers[protocol] : port;
if (portToUse != portNumbers[protocol] && state == NetworkState::active)
{
// We need to shut down and restart the protocol if it is active because the port number has changed
ShutdownProtocol(protocol);
protocolEnabled[protocol] = false;
}
portNumbers[protocol] = portToUse;
if (!protocolEnabled[protocol])
{
// Enable the corresponding socket
protocolEnabled[protocol] = true;
if (state == NetworkState::active)
{
StartProtocol(protocol);
RebuildMdnsServices();
}
}
ReportOneProtocol(protocol, reply);
return GCodeResult::ok;
}
reply.copy("Invalid protocol parameter");
return GCodeResult::error;
}
GCodeResult LwipEthernetInterface::DisableProtocol(NetworkProtocol protocol, const StringRef& reply) noexcept
{
if (protocol < NumProtocols)
{
if (state == NetworkState::active)
{
ShutdownProtocol(protocol);
}
protocolEnabled[protocol] = false;
ReportOneProtocol(protocol, reply);
return GCodeResult::ok;
}
reply.copy("Invalid protocol parameter");
return GCodeResult::error;
}
void LwipEthernetInterface::StartProtocol(NetworkProtocol protocol) noexcept
{
if (listeningPcbs[protocol] == nullptr)
{
tcp_pcb *pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, portNumbers[protocol]);
listeningPcbs[protocol] = tcp_listen(pcb);
tcp_accept(listeningPcbs[protocol], conn_accept);
}
switch(protocol)
{
case HttpProtocol:
for (SocketNumber skt = 0; skt < NumHttpSockets; ++skt)
{
sockets[skt]->Init(skt, portNumbers[protocol], protocol);
}
break;
case FtpProtocol:
sockets[FtpSocketNumber]->Init(FtpSocketNumber, portNumbers[protocol], protocol);
break;
case TelnetProtocol:
sockets[TelnetSocketNumber]->Init(TelnetSocketNumber, portNumbers[protocol], protocol);
break;
default:
break;
}
}
void LwipEthernetInterface::ShutdownProtocol(NetworkProtocol protocol) noexcept
{
#if 0 // chrishamm: Also see Network::Stop
for (NetworkResponder* r = responders; r != nullptr; r = r->GetNext())
{
r->Terminate(protocol);
}
#endif
switch(protocol)
{
case HttpProtocol:
for (SocketNumber skt = 0; skt < NumHttpSockets; ++skt)
{
sockets[skt]->TerminateAndDisable();
}
break;
case FtpProtocol:
sockets[FtpSocketNumber]->TerminateAndDisable();
sockets[FtpDataSocketNumber]->TerminateAndDisable();
break;
case TelnetProtocol:
sockets[TelnetSocketNumber]->TerminateAndDisable();
break;
default:
break;
}
if (listeningPcbs[protocol] != nullptr)
{
tcp_close(listeningPcbs[protocol]);
listeningPcbs[protocol] = nullptr;
}
}
// Report the protocols and ports in use
GCodeResult LwipEthernetInterface::ReportProtocols(const StringRef& reply) const noexcept
{
reply.Clear();
for (size_t i = 0; i < NumProtocols; ++i)
{
ReportOneProtocol(i, reply);
}
return GCodeResult::ok;
}
void LwipEthernetInterface::ReportOneProtocol(NetworkProtocol protocol, const StringRef& reply) const noexcept
{
if (protocolEnabled[protocol])
{
reply.lcatf("%s is enabled on port %u", ProtocolNames[protocol], portNumbers[protocol]);
}
else
{
reply.lcatf("%s is disabled", ProtocolNames[protocol]);
}
}
// This is called at the end of config.g processing.
// Start the network if it was enabled
void LwipEthernetInterface::Activate() noexcept
{
if (!activated)
{
activated = true;
if (state == NetworkState::enabled)
{
Start();
}
else
{
platform.Message(NetworkInfoMessage, "Ethernet is disabled.\n");
}
}
}
void LwipEthernetInterface::Exit() noexcept
{
Stop();
ethernet_terminate();
}
// Get the network state into the reply buffer, returning true if there is some sort of error
GCodeResult LwipEthernetInterface::GetNetworkState(const StringRef& reply) noexcept
{
ethernet_get_ipaddress(ipAddress, netmask, gateway);
const int enableState = EnableState();
reply.printf("Ethernet is %s, configured IP address: %s, actual IP address: %s",
(enableState == 0) ? "disabled" : "enabled",
IP4String(platform.GetIPAddress()).c_str(), IP4String(ipAddress).c_str());
return GCodeResult::ok;
}
// Start up the network
void LwipEthernetInterface::Start() noexcept
{
#if defined(DUET3)
digitalWrite(PhyResetPin, true); // bring the Ethernet Phy out of reset
#endif
if (initialised)
{
// Bring the netif up again
netif_set_up(&gs_net_if);
}
else
{
const char *hostname = reprap.GetNetwork().GetHostname();
// Allow the MAC address to be set only before LwIP is started...
ethernet_configure_interface(platform.GetDefaultMacAddress().bytes, hostname);
init_ethernet(DefaultIpAddress, DefaultNetMask, DefaultGateway);
// Initialise mDNS subsystem
mdns_resp_init();
mdns_resp_add_netif(&gs_net_if, hostname, MdnsTtl);
// Initialise NetBIOS responder
netbiosns_init();
netbiosns_set_name(hostname);
initialised = true;
}
state = NetworkState::establishingLink;
}
// Stop the network
void LwipEthernetInterface::Stop() noexcept
{
if (state != NetworkState::disabled)
{
netif_set_down(&gs_net_if);
#if defined(DUET3)
pinMode(PhyResetPin, OUTPUT_LOW); // hold the Ethernet Phy chip in reset
#endif
state = NetworkState::disabled;
}
}
// Main spin loop. If 'full' is true then we are being called from the main spin loop. If false then we are being called during HSMCI idle time.
void LwipEthernetInterface::Spin() noexcept
{
MutexLocker lock(lwipMutex);
switch(state)
{
case NetworkState::enabled:
case NetworkState::disabled:
default:
// Nothing to do
break;
case NetworkState::establishingLink:
if (ethernet_establish_link())
{
usingDhcp = platform.GetIPAddress().IsNull();
if (usingDhcp)
{
// IP address is all zeros, so use DHCP
state = NetworkState::obtainingIP;
// debugPrintf("Link established, getting IP address\n");
IPAddress nullAddress;
ethernet_set_configuration(nullAddress, nullAddress, nullAddress);
dhcp_start(&gs_net_if);
}
else
{
// Using static IP address
state = NetworkState::connected;
// debugPrintf("Link established, network running\n");
ethernet_set_configuration(platform.GetIPAddress(), platform.NetMask(), platform.GateWay());
}
}
break;
case NetworkState::obtainingIP:
if (ethernet_link_established())
{
// Check for incoming packets
DoEthernetTask();
// Have we obtained an IP address yet?
ethernet_get_ipaddress(ipAddress, netmask, gateway);
if (!ipAddress.IsNull())
{
// Notify the mDNS responder about this
state = NetworkState::connected;
// debugPrintf("IP address obtained, network running\n");
}
}
else
{
// debugPrintf("Lost phy link\n");
TerminateSockets();
state = NetworkState::establishingLink;
}
break;
case NetworkState::connected:
if (usingDhcp)
{
dhcp_stop(&gs_net_if);
}
InitSockets();
RebuildMdnsServices();
ethernet_get_ipaddress(ipAddress, netmask, gateway);
platform.MessageF(NetworkInfoMessage, "Ethernet running, IP address = %s\n", IP4String(ipAddress).c_str());
state = NetworkState::active;
break;
case NetworkState::active:
// Check that the link is still up
if (ethernet_link_established())
{
// Check for incoming packets
DoEthernetTask();
// Poll the next TCP socket
sockets[nextSocketToPoll]->Poll();
// Move on to the next TCP socket for next time
++nextSocketToPoll;
if (nextSocketToPoll == NumEthernetSockets)
{
nextSocketToPoll = 0;
}
// Check if the data port needs to be closed
if (closeDataPort && !sockets[FtpDataSocketNumber]->IsClosing())
{
TerminateDataPort();
}
}
else
{
// debugPrintf("Lost phy link\n");
TerminateSockets();
state = NetworkState::establishingLink;
}
break;
}
}
void LwipEthernetInterface::Diagnostics(MessageType mtype) noexcept
{
platform.Message(mtype, "- Ethernet -\n");
platform.MessageF(mtype, "State: %d\n", (int)state);
platform.MessageF(mtype, "Error counts: %u %u %u %u %u\n", rxErrorCount, rxBuffersNotFullyPopulatedCount, txErrorCount, txBufferNotFreeCount, txBufferTooShortCount);
platform.Message(mtype, "Socket states:");
for (LwipSocket *s : sockets)
{
platform.MessageF(mtype, " %d", s->GetState());
}
platform.Message(mtype, "\n");
#if LWIP_STATS
if (reprap.Debug(moduleNetwork))
{
// This prints LwIP diagnostics data to the USB port - blocking!
stats_display();
}
#endif
}
// Enable or disable the network. For Ethernet the ssid parameter is not used.
GCodeResult LwipEthernetInterface::EnableInterface(int mode, const StringRef& ssid, const StringRef& reply) noexcept
{
if (!activated)
{
state = (mode == 0) ? NetworkState::disabled : NetworkState::enabled;
}
else if (mode == 0)
{
if (state != NetworkState::disabled)
{
Stop();
platform.Message(NetworkInfoMessage, "Network stopped\n");
}
}
else if (state == NetworkState::disabled)
{
state = NetworkState::enabled;
Start();
}
return GCodeResult::ok;
}
int LwipEthernetInterface::EnableState() const noexcept
{
return (state == NetworkState::disabled) ? 0 : 1;
}
bool LwipEthernetInterface::ConnectionEstablished(tcp_pcb *pcb) noexcept
{
for (LwipSocket *s : sockets)
{
if (s->AcceptConnection(pcb))
{
// Socket has accepted the incoming connection
return true;
}
}
// No more free socket for this connection, terminate it
return false;
}
IPAddress LwipEthernetInterface::GetIPAddress() const noexcept
{
return ipAddress;
}
void LwipEthernetInterface::SetIPAddress(IPAddress p_ipAddress, IPAddress p_netmask, IPAddress p_gateway) noexcept
{
if (state == NetworkState::obtainingIP || state == NetworkState::active)
{
const bool wantDhcp = p_ipAddress.IsNull();
if (wantDhcp)
{
// Acquire dynamic IP address
if (!usingDhcp)
{
state = NetworkState::obtainingIP;
IPAddress nullAddress;
ethernet_set_configuration(nullAddress, nullAddress, nullAddress);
dhcp_start(&gs_net_if);
usingDhcp = true;
}
}
else
{
// Set static IP address
if (usingDhcp)
{
if (state == NetworkState::obtainingIP)
{
dhcp_stop(&gs_net_if);
}
state = NetworkState::active;
usingDhcp = false;
}
ethernet_set_configuration(p_ipAddress, p_netmask, p_gateway);
mdns_resp_netif_settings_changed(&gs_net_if);
}
}
}
void LwipEthernetInterface::UpdateHostname(const char *hostname) noexcept
{
if (initialised)
{
netbiosns_set_name(hostname);
RebuildMdnsServices(); // This updates the mDNS hostname too
}
}
GCodeResult LwipEthernetInterface::SetMacAddress(const MacAddress& mac, const StringRef& reply) noexcept
{
macAddress = mac;
return GCodeResult::ok;
}
void LwipEthernetInterface::OpenDataPort(Port port) noexcept
{
if (listeningPcbs[NumProtocols] != nullptr)
{
closeDataPort = true;
TerminateDataPort();
}
tcp_pcb *pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, port);
listeningPcbs[NumProtocols] = tcp_listen(pcb);
tcp_accept(listeningPcbs[NumProtocols], conn_accept);
sockets[FtpDataSocketNumber]->Init(FtpDataSocketNumber, port, FtpDataProtocol);
}
// Close FTP data port and purge associated resources
void LwipEthernetInterface::TerminateDataPort() noexcept
{
if (closeDataPort || !sockets[FtpDataSocketNumber]->IsClosing())
{
closeDataPort = false;
sockets[FtpDataSocketNumber]->TerminateAndDisable();
if (listeningPcbs[NumProtocols] != nullptr)
{
tcp_close(listeningPcbs[NumProtocols]);
listeningPcbs[NumProtocols] = nullptr;
}
}
else
{
// The socket may be waiting for a ACKs and a graceful disconnect.
// Give it some more time
closeDataPort = true;
}
}
void LwipEthernetInterface::InitSockets() noexcept
{
for (size_t i = 0; i < NumProtocols; ++i)
{
if (protocolEnabled[i])
{
StartProtocol(i);
}
}
nextSocketToPoll = 0;
}
void LwipEthernetInterface::TerminateSockets() noexcept
{
for (LwipSocket *socket : sockets)
{
socket->Terminate();
}
}
void GetServiceTxtEntries(struct mdns_service *service, void *txt_userdata)
{
for (size_t i = 0; i < ARRAY_SIZE(MdnsTxtRecords); i++)
{
mdns_resp_add_service_txtitem(service, MdnsTxtRecords[i], strlen(MdnsTxtRecords[i]));
}
}
void LwipEthernetInterface::RebuildMdnsServices() noexcept
{
mdns_resp_remove_netif(&gs_net_if);
mdns_resp_add_netif(&gs_net_if, reprap.GetNetwork().GetHostname(), MdnsTtl);
mdns_resp_add_service(&gs_net_if, "echo", "_echo", DNSSD_PROTO_TCP, 0, 0, nullptr, nullptr);
for (size_t protocol = 0; protocol < NumProtocols; protocol++)
{
if (protocolEnabled[protocol])
{
service_get_txt_fn_t txtFunc = (protocol == HttpProtocol) ? GetServiceTxtEntries : nullptr;
mdns_resp_add_service(&gs_net_if, ProtocolNames[protocol], MdnsServiceStrings[protocol], DNSSD_PROTO_TCP, portNumbers[protocol], MdnsTtl, txtFunc, nullptr);
}
}
mdns_resp_netif_settings_changed(&gs_net_if);
}
// End
|