forked from brianwiddas/gpiodcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
srcp.c
758 lines (576 loc) · 13.7 KB
/
srcp.c
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
/* SRCP for the Raspberry Pi
*
* THIS IS NOT A PROPER IMPLEMENTATION OF SRCP
*
* It is missing quite of a few things, and, more imporantly, skips out
* some important bits in order to work properly with JMRI. JMRI appears
* to have implemented its own protocol which is almost, but not quite,
* entirely unlike SRCP
*
* SRCP purists, look away now...
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
/* Socket stuff */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
/* getnameinfo() */
#include <netdb.h>
/* inet_ntop */
#include <arpa/inet.h>
/* strlen */
#include <string.h>
/* gettimeofday */
#include <sys/time.h>
/* Threads */
#include <pthread.h>
/* Time */
#include <time.h>
/* Signal handling */
#include <signal.h>
/* EX_OSERR */
//#include <sysexits.h>
/* errno variable & error numbers */
#include <errno.h>
/* Scheduler */
//#include <sched.h>
#include "srcp.h"
#include "dcc.h"
/* Structure for passing data to newly-created threads */
struct newthreaddata
{
int socket;
};
/* Linked list of all the trains we know about */
static struct genericloco *trainlist = NULL;
void debug_printtrainlist(void)
{
struct genericloco *list = trainlist;
printf("Train list:\n");
while(list)
{
printf("Address %u (p.v. %u)\n SS %u funcs %u = 0x%x\n DM %u (%s) V %d/%d\n",
list->address, list->protocolversion, list->speedsteps,
list->numfuncs, list->funcs, list->drivemode,
(list->drivemode?(list->drivemode==1?"F":"R"):"E"),
list->v, list->vmax);
list = list->next;
}
printf("List ends\n");
}
/* Set up the listening socket for the server */
int setup_network(void)
{
int listensock, optval;
struct sockaddr_storage bind_storage;
struct sockaddr_in *bind4;
struct sockaddr_in6 *bind6;
struct sockaddr *bindaddr;
bindaddr = (struct sockaddr *) &bind_storage;
bind6 = (struct sockaddr_in6 *) bindaddr;
bind6->sin6_family = AF_INET6;
bind6->sin6_port = htons(LISTENPORT);
bind6->sin6_addr = in6addr_any;
bind6->sin6_flowinfo = 0;
listensock = socket(AF_INET6, SOCK_STREAM, 0);
if(listensock<0)
{
if(errno == EAFNOSUPPORT)
{
/* No support for IPv6. Boo */
bind4 = (struct sockaddr_in *) bindaddr;
bind4->sin_family = AF_INET;
bind4->sin_port = htons(LISTENPORT);
bind4->sin_addr.s_addr = INADDR_ANY;
listensock = socket(AF_INET, SOCK_STREAM, 0);
if(listensock<0)
{
perror("(IPv4) socket");
exit(1);
}
}
else
{
perror("(IPv6) socket");
exit(1);
}
}
optval = 1;
if(setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0)
{
perror("setsockopt");
exit(1);
}
if(bind(listensock, bindaddr, sizeof(bind_storage)) < 0)
{
perror("bind");
exit(1);
}
if(listen(listensock, 10) < 0)
{
perror("listen");
exit(1);
}
/* DEBUG */
printf("Listening on port %u\n", LISTENPORT);
return listensock;
}
/* Send a string to a socket, adding the required timestamp */
static void writeto(unsigned int fd, char *string)
{
unsigned int writelen;
/* SRCP standard says a timestamp should preceed every message, but JMRI
* doesn't work if it does.
*/
#ifdef INCLUDETIME
struct timeval time;
char buffer[4];
char longbuf[2048];
gettimeofday(&time, NULL);
snprintf(buffer, 4, "%06i", (int)time.tv_usec);
snprintf(longbuf, 2048, "%lu.%s %s",
time.tv_sec, buffer, string);
string = longbuf;
#endif
writelen = write(fd, string, strlen(string));
if(writelen < 0)
{
perror("write");
exit(1);
}
printf("Sent: %s", string);
}
static size_t readfrom(int sock, char *buffer, size_t buffersize)
{
size_t readlen;
char *lineend;
readlen = read(sock, buffer, buffersize - 1);
if(readlen < 0)
{
perror("read");
exit(1);
}
/* Null terminate the string in the buffer */
buffer[readlen] = 0;
/* Remove CR/LF from the end of the line */
lineend = strpbrk(buffer, "\r\n");
if(lineend)
{
*lineend = 0;
}
printf("Received: %s\n", buffer);
return readlen;
}
/* Returns string number if one of the strings matches, or -1 otherwise
*
* eg tokenmatch("LIST", saveptr, "TEST", "LIST", "OF", "THINGS") = 1
*/
#define tokenmatch(...) __tokenmatch(__VA_ARGS__, NULL)
static int __tokenmatch(char *buffer, char **saveptr, ...)
{
char *token, *matchstr;
unsigned int stringnumber;
va_list ap;
token = strtok_r(buffer, " \r\n", saveptr);
if(!token)
return -1;
stringnumber = 0;
va_start(ap, saveptr);
while((matchstr = va_arg(ap, char *)))
{
/* strcmp returns 0 if the strings match */
if(!strcmp(token, matchstr))
return stringnumber;
stringnumber++;
}
return -1;
}
/* Returns next token as an integer, ignore failure */
static int tokeninteger(char *buffer, char **saveptr)
{
char *token;
token = strtok_r(buffer, " \r\n", saveptr);
if(token)
return atoi(token);
else
return -1;
}
static void badcommand(int sock, char **unused)
{
writeto(sock, "410 ERROR unknown command\r\n");
}
static struct genericloco *findloco(unsigned int address)
{
struct genericloco *loco;
loco = trainlist;
while(loco)
{
if(loco->address == address)
break;
loco = loco->next;
}
return loco;
}
static struct genericloco *newloco(void)
{
struct genericloco **loco;
loco = &trainlist;
while(*loco)
{
loco = &((*loco)->next);
}
*loco = malloc(sizeof(struct genericloco));
printf("New loco\n\n");
return *loco;
}
static void removeloco(unsigned int address)
{
struct genericloco **loco;
struct genericloco *ptr;
loco = &trainlist;
while(*loco)
{
if((*loco)->address == address)
{
ptr = *loco;
*loco = (*loco)->next;
free(ptr);
printf("Deleted loco\n\n");
return;
}
loco = &((*loco)->next);
}
}
static void locoinfo(int sock, struct genericloco *loco)
{
const unsigned int bus = 1;
char buffer[1024];
char *ptr;
int charcount;
unsigned int i;
charcount = sprintf(buffer, "100 INFO %u GL %u %u %d %d", bus,
loco->address, loco->drivemode, loco->v, loco->vmax);
ptr = &buffer[charcount];
for(i = 0; i < loco->numfuncs; i++)
{
charcount = sprintf(ptr, " %u", (loco->funcs&(1<<i))?1:0);
ptr = &ptr[charcount];
}
charcount = sprintf(ptr, "\r\n");
writeto(sock, buffer);
}
static void initloco(int sock, char **saveptr)
{
int address, protocol, speedsteps, numfuncs;
struct genericloco *newtrain;
const unsigned int bus = 1;
address = tokeninteger(NULL, saveptr);
if(tokenmatch(NULL, saveptr, "N"))
{
writeto(sock, "412 ERROR wrong value\r\n");
return;
}
protocol = tokeninteger(NULL, saveptr);
if(protocol != 1 && protocol != 2)
{
writeto(sock, "412 ERROR wrong value\r\n");
}
speedsteps = tokeninteger(NULL, saveptr);
if(speedsteps != 14 && speedsteps != 28 && speedsteps != 128)
{
writeto(sock, "412 ERROR wrong value. "
"Only speedsteps of 14/28/128 supported\r\n");
return;
}
numfuncs = tokeninteger(NULL, saveptr);
if(numfuncs < 0 || numfuncs > 32)
{
writeto(sock, "412 ERROR wrong value. "
"0-32 functions only\r\n");
return;
}
newtrain = newloco();
newtrain->address = address;
newtrain->protocolversion = protocol;
newtrain->speedsteps = speedsteps;
newtrain->numfuncs = numfuncs;
newtrain->funcs = 0;
newtrain->drivemode = 1 ;//2;
newtrain->v = 0;
newtrain->vmax = 100;
newtrain->dccspeed = NULL;
newtrain->dccfunc0to4 = NULL;
newtrain->next = NULL;
writeto(sock, "200 OK\r\n");
}
static void setloco(int sock, char **saveptr)
{
int address, drivemode, v, vmax, funcs;
int value;
struct genericloco *train;
const unsigned int bus = 1;
unsigned int i;
unsigned int calc;
address = tokeninteger(NULL, saveptr);
train = findloco(address);
if(!train)
{
writeto(sock, "412 ERROR wrong value\r\n");
return;
}
drivemode = tokeninteger(NULL, saveptr);
if(drivemode < 0 || drivemode > 2)
{
writeto(sock, "412 ERROR wrong value\r\n");
return;
}
v = tokeninteger(NULL, saveptr);
vmax = tokeninteger(NULL, saveptr);
if(vmax < 1 || v > vmax)
{
/* v can be less than 0; JMRI uses it for emergency stop */
writeto(sock, "412 ERROR wrong value.\r\n");
return;
}
funcs = 0;
for(i=0; i < train->numfuncs; i++)
{
value = tokeninteger(NULL, saveptr);
funcs |= (value?1:0)<<i;
}
train->funcs = funcs;
train->drivemode = drivemode;
train->v = v;
train->vmax = vmax;
/* TODO: 14/28 speed steps, long addresses */
calc = (126 * v)/vmax;
if(calc>0)
calc++; /* 1 is emergency stop, 2-127 are speed steps */
if(v<0 || drivemode==2)
calc=1; /* Emergency stop */
train->dccspeed =
add_update(train->dccspeed, 3, address, 0x3f,
calc | (drivemode?128:0));
/* 5-12 not currently supported. Not sure I have a suitable
* decoder for testing
*/
train->dccfunc0to4 =
add_update(train->dccfunc0to4, 2, address,
0x80 | ((funcs & 1)<<4) | ((funcs & 0x1e)>>1));
writeto(sock, "200 OK\r\n");
}
static void getloco(int sock, char **saveptr)
{
int address;
struct genericloco *train;
const unsigned int bus = 1;
address = tokeninteger(NULL, saveptr);
train = findloco(address);
if(!train)
{
writeto(sock, "416 ERROR no data\r\n");
return;
}
locoinfo(sock, train);
}
static void termloco(int sock, char **saveptr)
{
int address;
struct genericloco *train;
const unsigned int bus = 1;
address = tokeninteger(NULL, saveptr);
train = findloco(address);
if(!train)
{
writeto(sock, "412 ERROR wrong value\r\n");
return;
}
removeloco(address);
writeto(sock, "200 OK\r\n");
}
static void initpower(int sock, char **saveptr)
{
const unsigned int bus = 1;
/* Do something here? */
writeto(sock, "200 OK\r\n");
}
static void termpower(int sock, char **saveptr)
{
const unsigned int bus = 1;
/* And here */
writeto(sock, "200 OK\r\n");
}
static void setpower(int sock, char **saveptr)
{
const unsigned int bus = 1;
int on;
on = tokenmatch(NULL, saveptr, "OFF", "ON");
if(on < 0)
{
writeto(sock, "412 ERROR wrong value\r\n");
return;
}
/* Do something with the power setting */
writeto(sock, "200 OK\r\n");
}
static void getpower(int sock, char **saveptr)
{
const unsigned int bus = 1;
char buffer[512];
int on = 1;
/* Here too */
sprintf(buffer, "100 INFO %u POWER %s\r\n", bus, (on?"ON":"OFF"));
writeto(sock, buffer);
}
#define COMMANDS "GET", "SET", "CHECK", "WAIT", "INIT", "TERM", "RESET", "VERIFY"
#define FACILITIES "GL", "POWER"
static void (*srcpfunction[8][2])(int, char **) =
{
{ getloco, getpower },
{ setloco, setpower },
{ badcommand, badcommand },
{ badcommand, badcommand },
{ initloco, initpower },
{ termloco, termpower },
{ badcommand, badcommand },
{ badcommand, badcommand }
};
static void *communicationthread(struct newthreaddata *ntd)
{
int sock;
ssize_t readlen;
char *saveptr;
char buffer[1024];
enum { NONE = -1, INFO = 0, COMMAND = 1 } connectionmode;
int command, bus, facility;
char *send;
sock = ntd->socket;
/* Finished with this now */
free(ntd);
/* The welcome message doesn't have a timestamp */
send = "SRCP 0.8.3\r\n";
if(write(sock, send, strlen(send)) < 0)
{
perror("write");
exit(1);
}
while(1)
{
readlen = readfrom(sock, buffer, sizeof(buffer));
/* Handshake */
if(tokenmatch(buffer, &saveptr, "SET") ||
tokenmatch(NULL, &saveptr, "PROTOCOL") ||
tokenmatch(NULL, &saveptr, "SRCP"))
{
writeto(sock, "410 ERROR unknown command\r\n");
continue;
}
/* 0.8.3 = JMRI
* 0.82 = Android SRCP client
*/
if(tokenmatch(NULL, &saveptr, "0.8.3", "0.82") >= 0)
break;
writeto(sock, "400 ERROR unsupported protocol\r\n");
}
writeto(sock, "201 OK PROTOCOL SRCP\r\n");
connectionmode = NONE;
while(connectionmode == NONE)
{
readlen = readfrom(sock, buffer, sizeof(buffer));
if(tokenmatch(buffer, &saveptr, "SET") ||
tokenmatch(NULL, &saveptr, "CONNECTIONMODE") ||
tokenmatch(NULL, &saveptr, "SRCP"))
{
writeto(sock, "410 ERROR unknown command\r\n");
continue;
}
connectionmode = tokenmatch(NULL, &saveptr, "INFO", "COMMAND");
switch(connectionmode)
{
case INFO:
writeto(sock, "401 ERROR unsupported connection mode\r\n");
break;
case COMMAND:
writeto(sock, "202 OK CONNECTIONMODEOK\r\n");
break;
default:
writeto(sock, "401 ERROR unsupported connection mode\r\n");
}
}
while(1)
{
readlen = readfrom(sock, buffer, sizeof(buffer));
if(!tokenmatch(buffer, &saveptr, "GO"))
break;
writeto(sock, "410 ERROR unknown command\r\n");
}
sprintf(buffer, "200 OK %u\r\n", (unsigned int)pthread_self());
writeto(sock, buffer);
/* Handshake completed */
while ((readlen = readfrom(sock, buffer, sizeof(buffer))) > 0)
{
command = tokenmatch(buffer, &saveptr, COMMANDS);
if(command<0)
{
writeto(sock, "410 ERROR unknown command\r\n");
continue;
}
bus = tokeninteger(NULL, &saveptr);
facility = tokenmatch(NULL, &saveptr, FACILITIES);
if(facility<0)
{
writeto(sock, "410 ERROR unknown command\r\n");
continue;
}
srcpfunction[command][facility](sock, &saveptr);
}
return NULL;
}
int main(void)
{
int listensock, acceptsock, result;
struct sockaddr_storage remoteaddr;
char buffer[1024];
socklen_t addrlen;
pthread_t threadid;
struct newthreaddata *ntd;
setup_dcc();
listensock = setup_network();
addrlen = sizeof(remoteaddr);
while(1)
{
acceptsock = accept(listensock, (struct sockaddr *)&remoteaddr,
&addrlen);
if(acceptsock < 0)
{
perror("accept");
exit(1);
}
result = getnameinfo((struct sockaddr *)&remoteaddr,
sizeof(remoteaddr), buffer, sizeof(buffer),
NULL, 0, NI_NUMERICHOST);
if(result < 0)
{
fprintf(stderr, "getnameinfo: %s\n",
gai_strerror(result));
exit(1);
}
printf("Connection from: %s\n", buffer);
ntd = malloc(sizeof(struct newthreaddata));
if(!ntd)
{
perror("malloc");
exit(1);
}
ntd->socket = acceptsock;
if(pthread_create(&threadid, NULL, (void * (*)(void *)) communicationthread, ntd))
{
/* Failed to create thread */
perror("pthread_create");
exit(1);
}
}
}