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

WiFiSocket.cpp « ESP8266WiFi « Networking « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 62160b73002ed54ac6814c29e327e6f20a3fba05 (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
/*
 * WiFiSocket.cpp
 *
 *  Created on: 22 Apr 2017
 *      Author: David
 */

#include "WiFiSocket.h"

#if HAS_WIFI_NETWORKING

#include <Networking/NetworkBuffer.h>
#include <Platform/RepRap.h>
#include <Platform/TaskPriorities.h>
#include "WiFiInterface.h"

const unsigned int MaxBuffersPerSocket = 4;

WiFiSocket::WiFiSocket(NetworkInterface *iface) noexcept : Socket(iface), receivedData(nullptr), hasMoreDataPending(false), state(SocketState::inactive), needsPolling(false)
{
}

void WiFiSocket::Init(SocketNumber n) noexcept
{
	socketNum = n;
	state = SocketState::inactive;
	txBufferSpace = 0;
}

// Close a connection when the last packet has been sent
void WiFiSocket::Close() noexcept
{
	if (state == SocketState::connected || state == SocketState::clientDisconnecting)
	{
		const int32_t reply = GetInterface()->SendCommand(NetworkCommand::connClose, socketNum, 0, 0, nullptr, 0, nullptr, 0);
		if (reply == ResponseEmpty)
		{
			state = (state == SocketState::connected) ? SocketState::closing : SocketState::inactive;
			DiscardReceivedData();
			return;
		}
	}

	if (reprap.Debug(moduleNetwork))
	{
		debugPrintf("close failed, in wrong state\n");
	}
	Terminate();							// something is not right, so terminate the socket for safety
}

// Terminate a connection immediately
// We can call this after any sort of error on a socket as long as it is in use.
void WiFiSocket::Terminate() noexcept
{
	if (state != SocketState::inactive)
	{
		const int32_t reply = GetInterface()->SendCommand(NetworkCommand::connAbort, socketNum, 0, 0, nullptr, 0, nullptr, 0);
		state = (reply != 0) ? SocketState::broken : SocketState::inactive;
	}
	DiscardReceivedData();
	txBufferSpace = 0;
}

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

// Return true if we can send data to this socket
bool WiFiSocket::CanSend() const noexcept
{
	return state == SocketState::connected;
}

// Read 1 character from the receive buffers, returning true if successful
bool WiFiSocket::ReadChar(char& c) noexcept
{
	if (receivedData != nullptr)
	{
		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, and mark the data as taken
bool WiFiSocket::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 WiFiSocket::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 WiFiSocket::Poll() noexcept
{
	// Get the socket status
	Receiver<ConnStatusResponse> resp;
	const int32_t ret = GetInterface()->SendCommand(NetworkCommand::connGetStatus, socketNum, 0, nullptr, 0, resp);
	if (ret != (int32_t)resp.Size())
	{
		// We can't do much here other than disable and restart wifi, or hope the next status call succeeds
		if (reprap.Debug(moduleNetwork))
		{
			debugPrintf("Bad recv status size\n");
		}
		return;
	}

	// As well as getting the status for the socket we asked about, we also received bitmaps of connected sockets.
	// Pass these to the Network module so that it can avoid polling idle sockets.
	GetInterface()->UpdateSocketStatus(resp.Value().connectedSockets, resp.Value().otherEndClosedSockets);

	switch (resp.Value().state)
	{
	case ConnState::otherEndClosed:
		// 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(resp.Value().bytesAvailable);

		if (state == SocketState::clientDisconnecting)
		{
			if (!CanRead())
			{
				// We already got here before, so close the connection once and for all
				Close();
			}
			break;
		}
		else if (state != SocketState::inactive)
		{
			state = SocketState::clientDisconnecting;
			if (reprap.Debug(moduleNetwork))
			{
				debugPrintf("Client disconnected on socket %u\n", socketNum);
			}
			break;
		}
		// We can get here if a client has sent very little data and then instantly closed
		// the connection, e.g. when an FTP client transferred very small files over the
		// data port. In such cases we must notify the responder about this transmission!
		// no break

	case ConnState::connected:
		if (state != SocketState::connected)
		{
			// It's a new connection
			if (reprap.Debug(moduleNetwork))
			{
				debugPrintf("New conn on socket %u for local port %u\n", socketNum, localPort);
			}
			localPort = resp.Value().localPort;
			remotePort = resp.Value().remotePort;
			remoteIPAddress.SetV4LittleEndian(resp.Value().remoteIp);
			if (state != SocketState::waitingForResponder)
			{
				WiFiInterface *iface = static_cast<WiFiInterface *>(interface);
				protocol = iface->GetProtocolByLocalPort(localPort);

				whenConnected = millis();
				state = SocketState::waitingForResponder;
			}
			if (reprap.GetNetwork().FindResponder(this, protocol))
			{
				state = (resp.Value().state == ConnState::connected) ? SocketState::connected : SocketState::clientDisconnecting;
				if (reprap.Debug(moduleNetwork))
				{
					debugPrintf("Found responder\n");
				}
			}
			else if (millis() - whenConnected >= FindResponderTimeout)
			{
				Terminate();
				if (reprap.Debug(moduleNetwork))
				{
					debugPrintf("No responder, new conn %u terminated\n", socketNum);
				}
			}
		}

		if (state == SocketState::connected)
		{
			txBufferSpace = resp.Value().writeBufferSpace;
			ReceiveData(resp.Value().bytesAvailable);
		}
		break;

	case ConnState::aborted:
		if (reprap.Debug(moduleNetwork))
		{
			debugPrintf("Socket %u aborted\n", socketNum);
		}
		state = SocketState::broken;			// make sure that the Terminate call send a command to the WiFi module
		Terminate();
		break;

	default:
		if (state == SocketState::connected || state == SocketState::waitingForResponder)
		{
			// Unexpected change of state
			if (reprap.Debug(moduleNetwork))
			{
				debugPrintf("Unexpected state change on socket %u\n", socketNum);
			}
			state = SocketState::broken;
		}
		else if (state == SocketState::closing)
		{
			// Socket closed
			state = SocketState::inactive;
		}
		break;
	}

	needsPolling = false;
}

WiFiInterface *WiFiSocket::GetInterface() const noexcept
{
	return static_cast<WiFiInterface *>(interface);
}

// Try to receive more incoming data from the socket.
void WiFiSocket::ReceiveData(uint16_t bytesAvailable) noexcept
{
	if (bytesAvailable != 0)
	{
//		debugPrintf("%u available\n", bytesAvailable);
		// First see if we already have a buffer with enough room
		NetworkBuffer *const lastBuffer = NetworkBuffer::FindLast(receivedData);
		if (lastBuffer != nullptr && (bytesAvailable <= lastBuffer->SpaceLeft() || (lastBuffer->SpaceLeft() != 0 && NetworkBuffer::Count(receivedData) >= MaxBuffersPerSocket)))
		{
			// Read data into the existing buffer
			const size_t maxToRead = min<size_t>(lastBuffer->SpaceLeft(), MaxDataLength);
			TaskBase::SetCurrentTaskPriority(TaskPriority::SpinPriority + 1);		// temporarily increase our priority so we get woken up when the transfer is complete
			const int32_t ret = GetInterface()->SendCommand(NetworkCommand::connRead, socketNum, 0, 0, nullptr, 0, lastBuffer->UnwrittenData(), maxToRead);
			if (ret > 0 && (size_t)ret <= maxToRead)
			{
				bytesAvailable -= ret;
				lastBuffer->dataLength += (size_t)ret;
				if (reprap.Debug(moduleNetwork))
				{
					debugPrintf("Received %u bytes\n", (unsigned int)ret);
				}
			}
		}
		else if (NetworkBuffer::Count(receivedData) < MaxBuffersPerSocket)
		{
			NetworkBuffer * const buf = NetworkBuffer::Allocate();
			if (buf != nullptr)
			{
				const size_t maxToRead = min<size_t>(NetworkBuffer::bufferSize, MaxDataLength);
				TaskBase::SetCurrentTaskPriority(TaskPriority::SpinPriority + 1);		// temporarily increase our priority so we get woken up when the transfer is complete
				const int32_t ret = GetInterface()->SendCommand(NetworkCommand::connRead, socketNum, 0, 0, nullptr, 0, buf->Data(), maxToRead);
				if (ret > 0 && (size_t)ret <= maxToRead)
				{
					bytesAvailable -= ret;
					buf->dataLength = (size_t)ret;
					NetworkBuffer::AppendToList(&receivedData, buf);
					if (reprap.Debug(moduleNetwork))
					{
						debugPrintf("Received %u bytes\n", (unsigned int)ret);
					}
				}
				else
				{
					buf->Release();
				}
			}
//			else debugPrintf("no buffer\n");
		}
	}
	hasMoreDataPending = (bytesAvailable != 0);
}

// Discard any received data for this transaction
void WiFiSocket::DiscardReceivedData() noexcept
{
	while (receivedData != nullptr)
	{
		receivedData = receivedData->Release();
	}
	hasMoreDataPending = false;
}

// Send the data, returning the length buffered
size_t WiFiSocket::Send(const uint8_t *data, size_t length) noexcept
{
	if (state == SocketState::connected && txBufferSpace != 0)
	{
		const size_t lengthToSend = min<size_t>(length, min<size_t>(txBufferSpace, MaxDataLength));
		const int32_t reply = GetInterface()->SendCommand(NetworkCommand::connWrite, socketNum, 0, 0, data, lengthToSend, nullptr, 0);
		if (reply >= 0 && (size_t)reply <= lengthToSend)
		{
			txBufferSpace -= (size_t)reply;
			return (size_t)reply;
		}
		if (reprap.Debug(moduleNetwork))
		{
			debugPrintf("Send failed, terminating\n");
		}
		state = SocketState::broken;							// something is not right, terminate the socket soon
	}
	return 0;
}

// Tell the interface to send the outstanding data
void WiFiSocket::Send() noexcept
{
	if (state == SocketState::connected)
	{
		const int32_t reply = GetInterface()->SendCommand(NetworkCommand::connWrite, socketNum, MessageHeaderSamToEsp::FlagPush, 0, nullptr, 0, nullptr, 0);
		if (reply < 0)
		{
			if (reprap.Debug(moduleNetwork))
			{
				debugPrintf("Send failed, terminating\n");
			}
			state = SocketState::broken;						// something is not right, terminate the socket soon
		}
	}
}

// Return true if we need to poll this socket
bool WiFiSocket::NeedsPolling() const noexcept
{
	return state != SocketState::inactive || needsPolling;
}

#endif	// HAS_WIFI_NETWORKING

// End