Welcome to mirror list, hosted at ThFree Co, Russian Federation.

W5500Socket.cpp « W5500Ethernet « Networking « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 46901f2e6fde0b52ba0076e2e58b95748373b8dd (plain)
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
/*
 * Socket.cpp
 *
 *  Created on: 25 Dec 2016
 *      Author: David
 */

#include "W5500Socket.h"
#include <Networking/Network.h>
#include <Networking/NetworkDefs.h>
#include <Networking/NetworkInterface.h>
#include "Wiznet/Ethernet/socketlib.h"
#include <Networking/NetworkBuffer.h>
#include <Platform/RepRap.h>

//***************************************************************************************************
// Socket class

const unsigned int MaxBuffersPerSocket = 4;

W5500Socket::W5500Socket(NetworkInterface *iface) noexcept
	: Socket(iface), receivedData(nullptr)
{
}

// Initialise a TCP socket
void W5500Socket::Init(SocketNumber skt, TcpPort serverPort, NetworkProtocol p) noexcept
{
	socketNum = skt;
	localPort = serverPort;
	protocol = p;
	ReInit();
}

void W5500Socket::TerminateAndDisable() noexcept
{
	if (state != SocketState::disabled)		// we must not call close() if the socket has never been initialised, because socketNum won't have been initialised
	{
		MutexLocker lock(interface->interfaceMutex);

		Terminate();
		close(socketNum);
		state = SocketState::disabled;
	}
}

void W5500Socket::ReInit() noexcept
{
	MutexLocker lock(interface->interfaceMutex);

	// Discard any received data
	while (receivedData != nullptr)
	{
		receivedData = receivedData->Release();
	}

	persistConnection = true;
	isTerminated = false;
	isSending = false;

	// Re-initialise the socket on the W5500
	if (protocol != MdnsProtocol)
	{
		state = SocketState::inactive;

		socket(socketNum, Sn_MR_TCP, localPort, 0x00);
	}
	else
	{
		state = SocketState::listening;

		uint8_t har[6];
		memcpy(har, MdnsMacAddress, sizeof(har));
		setSn_DHAR(socketNum, har);							// NB: Using a constexpr value directly does not work here!
		setSn_DIPR(socketNum, (IPAddress)MdnsIPAddress);
		setSn_DPORT(socketNum, MdnsPort);

		socket(socketNum, Sn_MR_UDP, MdnsPort, SF_MULTI_ENABLE);
	}
}

// Close a connection when the last packet has been sent
void W5500Socket::Close() noexcept
{
	MutexLocker lock(interface->interfaceMutex);

	if (state != SocketState::disabled && state != SocketState::inactive)
	{
		if (protocol != MdnsProtocol)
		{
			ExecCommand(socketNum, Sn_CR_DISCON);
		}
		state = SocketState::closing;
		DiscardReceivedData();
		if (protocol == FtpDataProtocol)
		{
			localPort = 0;					// don't re-listen automatically
		}
	}
}

// Terminate a connection immediately
void W5500Socket::Terminate() noexcept
{
	MutexLocker lock(interface->interfaceMutex);

	if (state != SocketState::disabled)
	{
		disconnectNoWait(socketNum);
		isTerminated = true;
		state = SocketState::inactive;
		DiscardReceivedData();
	}
}

// Return true if there is or may soon be more data to read
bool W5500Socket::CanRead() const noexcept
{
	return (state == SocketState::connected)
		|| (state == SocketState::listening && protocol == MdnsProtocol)
		|| (state == SocketState::clientDisconnecting && receivedData != nullptr && receivedData->TotalRemaining() != 0);
}

bool W5500Socket::CanSend() const noexcept
{
	return state == SocketState::connected || (state == SocketState::listening && protocol == MdnsProtocol);
}

// Read 1 character from the receive buffers, returning true if successful
bool W5500Socket::ReadChar(char& c) noexcept
{
	if (receivedData != nullptr)
	{
		MutexLocker lock(interface->interfaceMutex);

		const bool ret = receivedData->ReadChar(c);
		if (receivedData->IsEmpty())
		{
			receivedData = receivedData->Release();
		}
		return ret;
	}

	c = 0;
	return false;
}

// Return a pointer to data in a buffer and a length available
bool W5500Socket::ReadBuffer(const uint8_t *&buffer, size_t &len) noexcept
{
	if (receivedData != nullptr)
	{
		len = receivedData->Remaining();
		buffer = receivedData->UnreadData();
		return true;
	}

	return false;
}

// Flag some data as taken from the receive buffers. We never take data from more than one buffer at a time.
void W5500Socket::Taken(size_t len) noexcept
{
	if (receivedData != nullptr)
	{
		receivedData->Taken(len);
		if (receivedData->IsEmpty())
		{
			receivedData = receivedData->Release();		// discard empty buffer at head of chain
		}
	}
}

// Poll a socket to see if it needs to be serviced
void W5500Socket::Poll() noexcept
{
	if (state != SocketState::disabled)
	{
		MutexLocker lock(interface->interfaceMutex);

		switch(getSn_SR(socketNum))
		{
		case SOCK_INIT:					// Socket has been initialised but is not listening yet
			if (localPort != 0)			// localPort for the FTP data socket is 0 until we have decided what port number to use
			{
				ExecCommand(socketNum, Sn_CR_LISTEN);
				state = SocketState::listening;
			}
			break;

		case SOCK_UDP:					// Socket is ready to receive UDP data
			ReceiveData();
			break;

		case SOCK_LISTEN:				// Socket is listening but no client has connected to it yet
			break;

		case SOCK_ESTABLISHED:			// A client is connected to this socket
			if (getSn_IR(socketNum) & Sn_IR_CON)
			{
				// New connection, so retrieve the sending IP address and port, and clear the interrupt
				getSn_DIPR(socketNum, remoteIPAddress);
				remotePort = getSn_DPORT(socketNum);
				setSn_IR(socketNum, Sn_IR_CON);
				whenConnected = millis();
			}

			if (state == SocketState::listening)		// if it is a new connection
			{
				if (reprap.GetNetwork().FindResponder(this, protocol))
				{
					state = SocketState::connected;
					sendOutstanding = false;
				}
				else if (millis() - whenConnected >= FindResponderTimeout)
				{
					if (reprap.Debug(moduleNetwork))
					{
						debugPrintf("Timed out waiting for resonder for port %u\n", localPort);
					}
					Terminate();
				}
			}

			if (state == SocketState::connected)
			{
				// See if the socket has received any data
				ReceiveData();
			}
			break;

		case SOCK_CLOSE_WAIT:			// A client has asked to disconnect
			// Check for further incoming packets before this socket is finally closed.
			// This must be done to ensure that FTP uploads are not cut off.
			ReceiveData();

			state = SocketState::clientDisconnecting;
			break;

		case SOCK_CLOSED:
			ReInit();
			break;

		default:
			break;
		}
	}
}

// Try to receive more incoming data from the socket. The mutex is already owned.
void W5500Socket::ReceiveData() noexcept
{
	const uint16_t len = getSn_RX_RSR(socketNum);
	if (len != 0 && len <= NetworkBuffer::bufferSize)
	{
//		debugPrintf("%u available\n", len);
		NetworkBuffer * const lastBuffer = NetworkBuffer::FindLast(receivedData);
		// NOTE: reading only part of the received data doesn't work because the wizchip doesn't track the buffer pointer properly.
		// We could probably make it work by tracking the buffer pointer ourselves, just as we do when sending data, and using wiz_recv_data_at.
		if (lastBuffer != nullptr && lastBuffer->SpaceLeft() >= len)
		{
			wiz_recv_data(socketNum, lastBuffer->UnwrittenData(), len);
			ExecCommand(socketNum, Sn_CR_RECV);
			lastBuffer->dataLength += len;
			if (reprap.Debug(moduleNetwork))
			{
				debugPrintf("Appended %u bytes\n", (unsigned int)len);
			}
		}
		else if (NetworkBuffer::Count(receivedData) < MaxBuffersPerSocket)
		{
			NetworkBuffer * const buf = NetworkBuffer::Allocate();
			if (buf != nullptr)
			{
				wiz_recv_data(socketNum, buf->Data(), len);
				ExecCommand(socketNum, Sn_CR_RECV);
				buf->dataLength = (size_t)len;
				NetworkBuffer::AppendToList(&receivedData, buf);
				if (reprap.Debug(moduleNetwork))
				{
					debugPrintf("Received %u bytes\n", (unsigned int)len);
				}
			}
		}
//		else debugPrintf("no buffer\n");
	}
}

// Discard any received data for this transaction. The mutex is already owned.
void W5500Socket::DiscardReceivedData() noexcept
{
	while (receivedData != nullptr)
	{
		receivedData = receivedData->Release();
	}
}

// Send the data, returning the length buffered
size_t W5500Socket::Send(const uint8_t *data, size_t length) noexcept
{
	MutexLocker lock(interface->interfaceMutex);

	const uint8_t status = getSn_SR(socketNum);
	if (CanSend() && length != 0 && (status == SOCK_ESTABLISHED || status == SOCK_UDP))
	{
		// Check for previous send complete
		if (isSending)									// are we already sending?
		{
			const uint8_t tmp = getSn_IR(socketNum);
			if (tmp & Sn_IR_SENDOK)						// did the previous send complete?
			{
				setSn_IR(socketNum, Sn_IR_SENDOK);		// if yes
				isSending = false;
			}
			else if (tmp & Sn_IR_TIMEOUT)				// did it time out?
			{
				isSending = false;
				disconnectNoWait(socketNum);			// if so, close the socket
				state = SocketState::aborted;
				return 0;								// and release buffers etc.
			}
			else
			{
				return 0;								// last send is still in progress
			}
		}

		if (!sendOutstanding)
		{
			wizTxBufferLeft = getSn_TX_FSR(socketNum);	// get free buffer space
			if (wizTxBufferLeft == 0)
			{
				return 0;
			}
			wizTxBufferPtr = getSn_TX_WR(socketNum);
		}

		if (length > wizTxBufferLeft)
		{
			length = wizTxBufferLeft;
		}
		wiz_send_data_at(socketNum, data, length, wizTxBufferPtr);
		wizTxBufferLeft -= length;
		wizTxBufferPtr += length;
		sendOutstanding = true;
		if (wizTxBufferLeft == 0)
		{
			Send();
		}
		return length;
	}
	return 0;
}

// Tell the interface to send the outstanding data
void W5500Socket::Send() noexcept
{
	MutexLocker lock(interface->interfaceMutex);

	if (CanSend() && sendOutstanding)
	{
		setSn_TX_WR(socketNum, wizTxBufferPtr);
		ExecCommand(socketNum, (protocol != MdnsProtocol) ? Sn_CR_SEND : Sn_CR_SEND_MAC);
		isSending = true;
		sendOutstanding = false;
	}
}

// End