-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTimerNetworkService.cpp
439 lines (397 loc) · 13.4 KB
/
TimerNetworkService.cpp
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
/*
* Copyright (c) 2019 Stephen Williams ([email protected])
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
# include "TimerNetworkService.h"
# include "TimerControlBox.h"
# include "version_tag.h"
# include <QNetworkInterface>
# include <QTcpSocket>
# include <cstdio>
# include <cassert>
/*
* The TimerNetworkService object implements the network protocol for
* the timer control box. The server creates a port, and listens for a
* single connection. (Only one connection is allowed.) Once the
* connection is made, the client may send commands, and this service
* sends responses. The general format of the commands is:
*
* ** Commands: <command> <options>...\n
* Commands are a set of words, terminated by a newline
* character. Each token of the command line is separated by one or
* more space characters. Leading and trailing spaces are ignored, and
* empty lines are ignored. The first word of the command line is the
* command code. The remaining words are arguments to th command.
*
* ** Responses: OK:<code>:<text>\n
* ERROR:<code>:<text>\n
*
* The response to a command is an ERROR record, or an OK record. In
* both cases, the <code> is a signed decimal value, and the <text> is
* arbitrary tex. The meaning of the text is defined by the command
* being responded to. For ERROR records, the <text> is a human
* readable error message.
*
* ======
* The supported commands are:
*
*** version
* -> OK:0:<version string>
*
* Retrieve the Archery Timer application version string. This is
* mostly intended for display. Also, this can be used to check the
* connection.
*
*** close-detach
* -> (no response)
*
* This is the only command that returns no response. The service
* closes the port, which detaches from the client. New connections
* can be made.
*
*** makeup-end
* -> OK:0
* -> OK:-1
*
* Tell the timer to set up a makeup end. The end number does not
* advance, and only a single line is called up. That like is called
* "MAKEUP" to make clear this is a special line. Use the start-timer
* to actually start the end.
*
*** next-end
* -> OK:<N>
*
* Tell the timer to set up for the next end. The end counter is
* incremented, the starting line is queued up, and the timer is
* prepared for the call-up phase. The timer is not started yet. The
* <N> in the response is the number of the end that is set up to
* start.
*
*** start-timer
* -> OK:0
* -> OK:-1
*
* If the timer is not running, start the timer and return OK:0. If
* the timer is currently running, then return OK:-1 and do nothing.
*
*** pause-timer
* -> OK:0
* -> OK:-1
*
* Opposite of start-timer. If the timer is running, pause it and
* return OK:0. A later start-timer will resume the timer. If the
* timer is not running, return OK:-1 and do nothing else.
*
*** fast-forward
* -> OK:0
* -> OK:-1
*
* If the timer is running, then skip to the end of the current
* phase. For example, if the timer is counting down the end, skip to
* the end of the end, blow 3 whistles, and go to the next
* line. Return OK:0.
*
* If the timer is not running, return OK:-1 and do nothing.
*
*** toggle-fullscreen
* -> OK:0
* -> OK:1
*
* If the timer window is not in fullscreen mode, then put it into
* fullscreen mode and hide the control box. If the screen is aready
* in fullscreen mode, then remove from fullscreen mode and show the
* control box.
*
* Return OK:1 if the timer ends up in fullscreen mode, and OK:0 if
* the timer ends up NOT in fullscreen mode.
*
*** query-settings
* -> OK:0:<key-value-pairs>...
*
* Query the timer settings. The response is all the current settings
* of the timer, formatted as <key>=<value> pairs. The keys are
* described below.
*
*** set <key-value-pairs>...
* -> OK:0
*
* Set settings. Any number of <key>=<value> pairs may be in the
* command line. Other settings will be left unchanged.
*
* ======
* The set and query-settings commands operate on some key-value
* pairs. These are the settings supported so far:
*
*** callup-time=<N>
* This is is time (in seconds) to call up a line.
*
*** end-time=<N>
* This is the time (in seconds) for an end.
*
*** warn-time=<N>
* This is the time (in seconds) remaining in an end when the display
* shows a warning color. For example, if end-time=120 and
* warn-time=30, then for the last 30 seconds of the end, the timer
* will display the warning color while still counting down.
*/
using namespace std;
TimerNetworkService::TimerNetworkService(TimerControlBox*parent)
: QTcpServer(parent)
{
controls_ = parent;
connection_ = 0;
connect(this, SIGNAL(newConnection()), SLOT(new_connection_signal()));
connect(&zero_conf_, SIGNAL(serviceAdded(QZeroConfService)),
this, SLOT(service_added(QZeroConfService)));
connect(&zero_conf_, SIGNAL(serviceRemoved(QZeroConfService)),
this, SLOT(service_removed(QZeroConfService)));
connect(&zero_conf_, SIGNAL(serviceUpdated(QZeroConfService)),
this, SLOT(service_updated(QZeroConfService)));
listen();
fprintf(stdout, "XXXX TimerNetworkService: server port = %u\n", serverPort());
QString port_text;
port_text.setNum(serverPort());
controls_->network_service_port(port_text);
scan_for_networks_();
connect(&clock_, SIGNAL(timeout()), SLOT(clock_timeout()));
clock_.setSingleShot(false);
clock_.setInterval(2000);
clock_.start();
}
TimerNetworkService::~TimerNetworkService()
{
}
/*
* This method scans all the network addresses (that are up) and sees if any
* come alive or go away. If the set of available networks changes, restart
* the publish.
*/
void TimerNetworkService::scan_for_networks_()
{
QList<QHostAddress> tmp_addresses = QNetworkInterface::allAddresses();
QList<QHostAddress> addresses;
for (QList<QHostAddress>::const_iterator cur = tmp_addresses.begin()
; cur != tmp_addresses.end() ; ++ cur) {
// Skip loopback addresses.
if (cur->isLoopback()) continue;
addresses.append(*cur);
}
QStringList built_list;
for (QList<QHostAddress>::const_iterator cur = addresses.begin()
; cur != addresses.end() ; ++ cur) {
if (!cur->isGlobal())
continue;
if (cur->protocol() != QAbstractSocket::IPv4Protocol)
continue;
built_list.push_back(cur->toString());
}
// If the list is the same as it has been, then there is nothing to do.
if (built_list == if_list_)
return;
fprintf(stdout, "XXXX Got a network interfaces list. (%d)\n", built_list.size());
for (QString&cur : built_list) {
fprintf(stdout, "XXXX %s\n", cur.toLatin1().data());
}
if_list_ = built_list;
controls_->network_interfaces(if_list_);
fprintf(stdout, "XXXX Publish service.\n");
fflush(stdout);
zero_conf_.clearServiceTxtRecords();
zero_conf_.startServicePublish("Icarus Archery Timer", "_icarus_archery_timer._tcp", "local", serverPort());
}
void TimerNetworkService::clock_timeout()
{
if (connection_ == 0) {
// Connection tick.
scan_for_networks_();
}
}
void TimerNetworkService::new_connection_signal(void)
{
while (QTcpSocket*sock = nextPendingConnection()) {
if (connection_ != 0) {
fprintf(stdout, "XXXX TimerNetworkService: connection busy.\n");
fflush(stdout);
delete sock;
continue;
}
fprintf(stdout, "XXXX TimerNetworkService: Accepted a connection.\n");
fflush(stdout);
pauseAccepting();
connection_ = sock;
controls_->network_service_port("connected");
controls_->network_interfaces(QStringList());
connect(connection_, SIGNAL(readyRead()), SLOT(ready_read()));
connect(connection_, SIGNAL(disconnected()),SLOT(port_disconnected()));
// Stop publishing, if connected.
//zero_conf_.stopServicePublish();
}
}
/*
* This slot receives the signal that there is data to read. Read as
* much data as possible, processing lines when there are line breaks.
*/
void TimerNetworkService::ready_read(void)
{
assert(connection_);
char buf[1024];
qint64 rc;
while ( connection_ && ((rc = connection_->read(buf, sizeof buf)) > 0)) {
for (int idx = 0 ; idx < rc ; idx += 1) {
if (buf[idx] != '\n') {
line_buffer_.append(buf[idx]);
continue;
}
process_command_(line_buffer_);
line_buffer_ = "";
}
}
}
void TimerNetworkService::port_disconnected(void)
{
fprintf(stdout, "XXXX TimerNetworkService: dropped connection\n");
fflush(stdout);
QTcpSocket*port = connection_;
connection_ = 0;
resumeAccepting();
port->deleteLater();
// Show the port in the control panel.
QString port_text;
port_text.setNum(serverPort());
controls_->network_service_port(port_text);
controls_->network_interfaces(if_list_);
// Resume publishing.
//zero_conf_.clearServiceTxtRecords();
//zero_conf_.startServicePublish("Icarus Archery Timer", "_icarus_archery_timer._tcp", "local", serverPort());
}
void TimerNetworkService::service_added(QZeroConfService)
{
fprintf(stderr, "XXXX TimerNetworkService::service_added NOT IMPLEMENTED.\n");
}
void TimerNetworkService::service_removed(QZeroConfService)
{
fprintf(stderr, "XXXX TimerNetworkService::service_removed NOT IMPLEMENTED.\n");
}
void TimerNetworkService::service_updated(QZeroConfService)
{
fprintf(stderr, "XXXX TimerNetworkService::service_updated NOT IMPLEMENTED.\n");
}
static inline QString ok_with_error_code(int rc)
{
QString res = "OK:";
QString num;
num.setNum(rc, 10);
res.append(num);
res.append("\n");
return res;
}
static inline QString ok_with_error_code(int rc, const QString&text)
{
QString res = "OK:";
QString num;
num.setNum(rc, 10);
res.append(num);
res.append(":");
res.append(text);
res.append("\n");
return res;
}
void TimerNetworkService::process_command_(const QString&cmd)
{
QStringList args = cmd.simplified().split(' ', Qt::SkipEmptyParts);
if (args.size() == 0) return;
if (args[0] == "version") {
connection_->write(ok_with_error_code(0, VERSION_TAG).toLatin1().data());
return;
}
if (args[0] == "close-detach") {
disconnect(connection_, SIGNAL(readyRead()), this, SLOT(ready_read()));
QTcpSocket*tmp = connection_;
connection_ = 0;
resumeAccepting();
tmp->close();
return;
}
if (args[0] == "makeup-end") {
int rc = controls_->special_end_command("MAKEUP");
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "next-end") {
int rc = -1;
if (args.size() < 2) {
// Handle the old case, where we let the service
// do the end counting.
rc = controls_->next_end_command();
} else {
// Handle the general case that the next end
// number and practice flag are passed in.
int end_number = args[1].toInt();
bool practice_flag = false;
for (int idx = 2 ; idx < args.size() ; idx += 1) {
if (args[idx] == "practice") {
practice_flag = true;
} else if (args[idx] == "no-practice") {
practice_flag = false;
} else {
}
}
rc = controls_->next_end_command(end_number, practice_flag);
}
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "start-timer") {
int rc = controls_->start_timer_command();
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "fast-forward") {
int rc = controls_->fast_forward_command();
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "pause-timer") {
int rc = controls_->pause_timer_command();
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "emergency-stop") {
int rc = controls_->emergency_stop_command();
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "toggle-fullscreen") {
int rc = controls_->toggle_fullscreen_command();
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "set") {
int rc = 0;
for (int idx = 1 ; idx < args.size() ; idx += 1)
controls_->set_command(args[idx]);
connection_->write(ok_with_error_code(rc).toLatin1().data());
return;
}
if (args[0] == "query-settings") {
QString text;
int rc = controls_->query_settings_command(text);
connection_->write(ok_with_error_code(rc, text).toLatin1().data());
return;
}
connection_->write("ERROR:-1:No such command\n");
}