-
Notifications
You must be signed in to change notification settings - Fork 11
/
TcpServer.ino
508 lines (442 loc) · 17.3 KB
/
TcpServer.ino
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
/*
tcpServer.ino
The TCP (position, velocity and time) server sits on top of the network layer
and sends position data to one or more computers or cell phones for display.
Satellite ... Satellite
| | |
| | |
| V |
| RTK |
'------> Base <------'
Station
|
| NTRIP Server sends correction data
V
NTRIP Caster
|
| NTRIP Client receives correction data
|
V
Bluetooth RTK Network: TCP Client
.---------------- Rover ----------------------------------.
| | |
| | Network: TCP Server |
| TCP data | Position, velocity & time data | TCP data
| V |
| Computer or |
'------------> Cell Phone <-------------------------------'
for display
*/
#ifdef COMPILE_NETWORK
//----------------------------------------
// Constants
//----------------------------------------
#define TCP_SERVER_MAX_CLIENTS 4
#define TCP_SERVER_CLIENT_DATA_TIMEOUT (15 * 1000)
// Define the TCP server states
enum tcpServerStates
{
TCP_SERVER_STATE_OFF = 0,
TCP_SERVER_STATE_NETWORK_STARTED,
TCP_SERVER_STATE_RUNNING,
// Insert new states here
TCP_SERVER_STATE_MAX // Last entry in the state list
};
const char *const tcpServerStateName[] = {
"TCP_SERVER_STATE_OFF",
"TCP_SERVER_STATE_NETWORK_STARTED",
"TCP_SERVER_STATE_RUNNING",
};
const int tcpServerStateNameEntries = sizeof(tcpServerStateName) / sizeof(tcpServerStateName[0]);
const RtkMode_t tcpServerMode = RTK_MODE_BASE_FIXED | RTK_MODE_BASE_SURVEY_IN | RTK_MODE_ROVER;
//----------------------------------------
// Locals
//----------------------------------------
// TCP server
static NetworkServer *tcpServer = nullptr;
static uint8_t tcpServerState;
static uint32_t tcpServerTimer;
// TCP server clients
static volatile uint8_t tcpServerClientConnected;
static volatile uint8_t tcpServerClientDataSent;
static volatile uint8_t tcpServerClientWriteError;
static NetworkClient *tcpServerClient[TCP_SERVER_MAX_CLIENTS];
static IPAddress tcpServerClientIpAddress[TCP_SERVER_MAX_CLIENTS];
static volatile RING_BUFFER_OFFSET tcpServerClientTails[TCP_SERVER_MAX_CLIENTS];
static NetPriority_t tcpServerPriority = NETWORK_OFFLINE;
//----------------------------------------
// TCP Server handleGnssDataTask Support Routines
//----------------------------------------
// Send data to the TCP clients
int32_t tcpServerClientSendData(int index, uint8_t *data, uint16_t length)
{
length = tcpServerClient[index]->write(data, length);
if (length > 0)
{
// Update the data sent flag when data successfully sent
if (length > 0)
tcpServerClientDataSent = tcpServerClientDataSent | (1 << index);
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_CLIENT_DATA)) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_CLIENT_DATA);
systemPrintf("TCP server wrote %d bytes to %s\r\n", length,
tcpServerClientIpAddress[index].toString().c_str());
}
}
// Failed to write the data
else
{
// Done with this client connection
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_CLIENT_DATA)) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_CLIENT_DATA);
systemPrintf("TCP server breaking connection %d with client %s\r\n", index,
tcpServerClientIpAddress[index].toString().c_str());
}
tcpServerClient[index]->stop();
tcpServerClientConnected = tcpServerClientConnected & (~(1 << index));
tcpServerClientWriteError = tcpServerClientWriteError | (1 << index);
length = 0;
}
return length;
}
// Send TCP data to the clients
int32_t tcpServerSendData(uint16_t dataHead)
{
int32_t usedSpace = 0;
int32_t bytesToSend;
int index;
uint16_t tail;
// Update each of the clients
for (index = 0; index < TCP_SERVER_MAX_CLIENTS; index++)
{
tail = tcpServerClientTails[index];
// Determine if the client is connected
if (!(tcpServerClientConnected & (1 << index)))
tail = dataHead;
else
{
// Determine the amount of TCP data in the buffer
bytesToSend = dataHead - tail;
if (bytesToSend < 0)
bytesToSend += settings.gnssHandlerBufferSize;
if (bytesToSend > 0)
{
// Reduce bytes to send if we have more to send then the end of the buffer
// We'll wrap next loop
if ((tail + bytesToSend) > settings.gnssHandlerBufferSize)
bytesToSend = settings.gnssHandlerBufferSize - tail;
// Send the data to the TCP server clients
bytesToSend = tcpServerClientSendData(index, &ringBuffer[tail], bytesToSend);
// Assume all data was sent, wrap the buffer pointer
tail += bytesToSend;
if (tail >= settings.gnssHandlerBufferSize)
tail -= settings.gnssHandlerBufferSize;
// Update space available for use in UART task
bytesToSend = dataHead - tail;
if (bytesToSend < 0)
bytesToSend += settings.gnssHandlerBufferSize;
if (usedSpace < bytesToSend)
usedSpace = bytesToSend;
}
}
tcpServerClientTails[index] = tail;
}
// Return the amount of space that TCP server client is using in the buffer
return usedSpace;
}
// Remove previous messages from the ring buffer
void discardTcpServerBytes(RING_BUFFER_OFFSET previousTail, RING_BUFFER_OFFSET newTail)
{
int index;
uint16_t tail;
// Update each of the clients
for (index = 0; index < TCP_SERVER_MAX_CLIENTS; index++)
{
tail = tcpServerClientTails[index];
if (previousTail < newTail)
{
// No buffer wrap occurred
if ((tail >= previousTail) && (tail < newTail))
tcpServerClientTails[index] = newTail;
}
else
{
// Buffer wrap occurred
if ((tail >= previousTail) || (tail < newTail))
tcpServerClientTails[index] = newTail;
}
}
}
//----------------------------------------
// TCP Server Routines
//----------------------------------------
// Update the state of the TCP server state machine
void tcpServerSetState(uint8_t newState)
{
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_STATE)) && (!inMainMenu))
{
if (tcpServerState == newState)
systemPrint("*");
else
systemPrintf("%s --> ", tcpServerStateName[tcpServerState]);
}
tcpServerState = newState;
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_STATE)) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_STATE);
if (newState >= TCP_SERVER_STATE_MAX)
{
systemPrintf("Unknown TCP Server state: %d\r\n", tcpServerState);
reportFatalError("Unknown TCP Server state");
}
else
systemPrintln(tcpServerStateName[tcpServerState]);
}
}
// Start the TCP server
bool tcpServerStart()
{
IPAddress localIp;
if (settings.debugTcpServer && (!inMainMenu))
systemPrintln("TCP server starting the server");
// Start the TCP server
tcpServer = new NetworkServer(settings.tcpServerPort, TCP_SERVER_MAX_CLIENTS);
if (!tcpServer)
return false;
tcpServer->begin();
online.tcpServer = true;
localIp = networkGetIpAddress();
systemPrintf("TCP server online, IP address %s:%d\r\n", localIp.toString().c_str(), settings.tcpServerPort);
return true;
}
// Stop the TCP server
void tcpServerStop()
{
int index;
// Notify the rest of the system that the TCP server is shutting down
if (online.tcpServer)
{
// Notify the GNSS UART tasks of the TCP server shutdown
online.tcpServer = false;
delay(5);
}
// Determine if TCP server clients are active
if (tcpServerClientConnected)
{
// Shutdown the TCP server client links
for (index = 0; index < TCP_SERVER_MAX_CLIENTS; index++)
tcpServerStopClient(index);
}
// Shutdown the TCP server
if (tcpServer != nullptr)
{
// Stop the TCP server
if (settings.debugTcpServer && (!inMainMenu))
systemPrintln("TCP server stopping");
tcpServer->stop();
delete tcpServer;
tcpServer = nullptr;
}
// Stop using the network
if (tcpServerState != TCP_SERVER_STATE_OFF)
{
// The TCP server is now off
tcpServerSetState(TCP_SERVER_STATE_OFF);
tcpServerTimer = millis();
}
}
// Stop the TCP server client
void tcpServerStopClient(int index)
{
bool connected;
bool dataSent;
// Done with this client connection
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_DATA)) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_DATA);
// Determine the shutdown reason
connected = tcpServerClient[index]->connected() && (!(tcpServerClientWriteError & (1 << index)));
dataSent =
((millis() - tcpServerTimer) < TCP_SERVER_CLIENT_DATA_TIMEOUT) || (tcpServerClientDataSent & (1 << index));
if (!dataSent)
systemPrintf("TCP Server: No data sent over %d seconds\r\n", TCP_SERVER_CLIENT_DATA_TIMEOUT / 1000);
if (!connected)
systemPrintf("TCP Server: Link to client broken\r\n");
systemPrintf("TCP server client %d disconnected from %s\r\n", index,
tcpServerClientIpAddress[index].toString().c_str());
}
// Shutdown the TCP server client link
tcpServerClient[index]->stop();
tcpServerClientConnected = tcpServerClientConnected & (~(1 << index));
tcpServerClientWriteError = tcpServerClientWriteError & (~(1 << index));
}
// Update the TCP server state
void tcpServerUpdate()
{
bool connected;
bool dataSent;
int index;
IPAddress ipAddress;
// Shutdown the TCP server when the mode or setting changes
DMW_st(tcpServerSetState, tcpServerState);
if (NEQ_RTK_MODE(tcpServerMode) || (!settings.enableTcpServer))
{
if (tcpServerState > TCP_SERVER_STATE_OFF)
tcpServerStop();
}
/*
TCP Server state machine
.---------------->TCP_SERVER_STATE_OFF
| |
| tcpServerStop | settings.enableTcpServer
| |
| V
+<----------TCP_SERVER_STATE_NETWORK_STARTED
^ |
| | networkUserConnected
| |
| V
+<--------------TCP_SERVER_STATE_RUNNING
^ |
| | network failure
| |
| V
'-----------TCP_SERVER_STATE_WAIT_NO_CLIENTS
*/
switch (tcpServerState)
{
default:
break;
// Wait until the TCP server is enabled
case TCP_SERVER_STATE_OFF:
// Determine if the TCP server should be running
if (EQ_RTK_MODE(tcpServerMode) && settings.enableTcpServer)
{
if (settings.debugTcpServer && (!inMainMenu))
systemPrintln("TCP server start");
tcpServerPriority = NETWORK_OFFLINE;
tcpServerSetState(TCP_SERVER_STATE_NETWORK_STARTED);
}
break;
// Wait until the network is connected
case TCP_SERVER_STATE_NETWORK_STARTED:
// Determine if the TCP server was turned off
if (NEQ_RTK_MODE(tcpServerMode) || !settings.enableTcpServer)
tcpServerStop();
// Wait until the network is connected to the media
else if (networkIsConnected(&tcpServerPriority))
{
// Delay before starting the TCP server
if ((millis() - tcpServerTimer) >= (1 * 1000))
{
// The network type and host provide a valid configuration
tcpServerTimer = millis();
// Start the TCP server
if (tcpServerStart())
tcpServerSetState(TCP_SERVER_STATE_RUNNING);
}
}
break;
// Handle client connections and link failures
case TCP_SERVER_STATE_RUNNING:
// Determine if the network has failed
if ((!settings.enableTcpServer) || (!networkIsConnected(&tcpServerPriority)))
{
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_DATA)) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_DATA);
systemPrintln("TCP server initiating shutdown");
}
// Network connection failed, attempt to restart the network
tcpServerStop();
break;
}
// Walk the list of TCP server clients
for (index = 0; index < TCP_SERVER_MAX_CLIENTS; index++)
{
// Determine if the client data structure is in use
if (tcpServerClientConnected & (1 << index))
{
// Data structure in use
// Check for a working TCP server client connection
connected = tcpServerClient[index]->connected();
dataSent = ((millis() - tcpServerTimer) < TCP_SERVER_CLIENT_DATA_TIMEOUT) ||
(tcpServerClientDataSent & (1 << index));
if (connected && dataSent)
{
// Display this client connection
if (PERIODIC_DISPLAY(PD_TCP_SERVER_DATA) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_DATA);
systemPrintf("TCP server client %d connected to %s\r\n", index,
tcpServerClientIpAddress[index].toString().c_str());
}
}
// Shutdown the TCP server client link
else
tcpServerStopClient(index);
}
}
// Walk the list of TCP server clients
for (index = 0; index < TCP_SERVER_MAX_CLIENTS; index++)
{
// Determine if the client data structure is in use
if (!(tcpServerClientConnected & (1 << index)))
{
NetworkClient client;
// Data structure not in use
// Check for another TCP server client
client = tcpServer->accept();
// Done if no TCP server client found
if (!client)
break;
// Start processing the new TCP server client connection
tcpServerClient[index] = new NetworkClient;
tcpServerClientIpAddress[index] = tcpServerClient[index]->remoteIP();
tcpServerClientConnected = tcpServerClientConnected | (1 << index);
tcpServerClientDataSent = tcpServerClientDataSent | (1 << index);
if ((settings.debugTcpServer || PERIODIC_DISPLAY(PD_TCP_SERVER_DATA)) && (!inMainMenu))
{
PERIODIC_CLEAR(PD_TCP_SERVER_DATA);
systemPrintf("TCP server client %d connected to %s\r\n", index,
tcpServerClientIpAddress[index].toString().c_str());
}
}
}
// Check for data moving across the connections
if ((millis() - tcpServerTimer) >= TCP_SERVER_CLIENT_DATA_TIMEOUT)
{
// Restart the data verification
tcpServerTimer = millis();
tcpServerClientDataSent = 0;
}
break;
}
// Periodically display the TCP state
if (PERIODIC_DISPLAY(PD_TCP_SERVER_STATE) && (!inMainMenu))
tcpServerSetState(tcpServerState);
}
// Verify the TCP server tables
void tcpServerValidateTables()
{
char line[128];
// Verify TCP_SERVER_MAX_CLIENTS
if ((sizeof(tcpServerClientConnected) * 8) < TCP_SERVER_MAX_CLIENTS)
{
snprintf(line, sizeof(line),
"Please set TCP_SERVER_MAX_CLIENTS <= %d or increase size of tcpServerClientConnected",
sizeof(tcpServerClientConnected) * 8);
reportFatalError(line);
}
if (tcpServerStateNameEntries != TCP_SERVER_STATE_MAX)
reportFatalError("Fix tcpServerStateNameEntries to match tcpServerStates");
}
// Zero the TCP server client tails
void tcpServerZeroTail()
{
int index;
for (index = 0; index < TCP_SERVER_MAX_CLIENTS; index++)
tcpServerClientTails[index] = 0;
}
#endif // COMPILE_NETWORK