forked from flightaware/dump1090
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_io.c
2951 lines (2534 loc) · 101 KB
/
net_io.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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Part of dump1090, a Mode S message decoder for RTLSDR devices.
//
// net_io.c: network handling.
//
// Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
//
// This file is free software: you may copy, redistribute and/or modify it
// 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 file 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, see <https://www.gnu.org/licenses/>.
// This file incorporates work covered by the following copyright and
// permission notice:
//
// Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "dump1090.h"
/* for PRIX64 */
#include <inttypes.h>
#include <assert.h>
#include <stdarg.h>
//
// ============================= Networking =============================
//
// Note: here we disregard any kind of good coding practice in favor of
// extreme simplicity, that is:
//
// 1) We only rely on the kernel buffers for our I/O without any kind of
// user space buffering.
// 2) We don't register any kind of event handler, from time to time a
// function gets called and we accept new connections. All the rest is
// handled via non-blocking I/O and manually polling clients to see if
// they have something new to share with us when reading is needed.
static int handleBeastCommand(struct client *c, char *p);
static int decodeBinMessage(struct client *c, char *p);
static int decodeHexMessage(struct client *c, char *hex);
static int handleFaupCommand(struct client *c, char *hex);
static void moveNetClient(struct client *c, struct net_service *new_service);
static void send_raw_heartbeat(struct net_service *service);
static void send_beast_heartbeat(struct net_service *service);
static void send_sbs_heartbeat(struct net_service *service);
static void send_stratux_heartbeat(struct net_service *service);
static void writeBeastMessage(struct net_writer *writer, uint64_t timestamp, double signalLevel, unsigned char *msg, int msgLen);
static void writeFATSVEvent(struct modesMessage *mm, struct aircraft *a);
static void writeFATSVPositionUpdate(float lat, float lon, float alt);
static void autoset_modeac();
__attribute__ ((format (printf,3,0))) static char *safe_vsnprintf(char *p, char *end, const char *format, va_list ap);
__attribute__ ((format (printf,3,4))) static char *safe_snprintf(char *p, char *end, const char *format, ...);
static const char *jsonEscapeString(const char *str);
//
//=========================================================================
//
// Networking "stack" initialization
//
// Init a service with the given read/write characteristics, return the new service.
// Doesn't arrange for the service to listen or connect
struct net_service *serviceInit(const char *descr, struct net_writer *writer, heartbeat_fn hb, read_mode_t mode, const char *sep, read_fn handler)
{
struct net_service *service;
if (!(service = calloc(sizeof(*service), 1))) {
fprintf(stderr, "Out of memory allocating service %s\n", descr);
exit(1);
}
service->next = Modes.services;
Modes.services = service;
service->descr = descr;
service->listener_count = 0;
service->connections = 0;
service->writer = writer;
service->read_sep = sep;
service->read_mode = mode;
service->read_handler = handler;
if (service->writer) {
if (! (service->writer->data = malloc(MODES_OUT_BUF_SIZE)) ) {
fprintf(stderr, "Out of memory allocating output buffer for service %s\n", descr);
exit(1);
}
service->writer->service = service;
service->writer->dataUsed = 0;
service->writer->lastWrite = mstime();
service->writer->send_heartbeat = hb;
}
return service;
}
// Create a client attached to the given service using the provided socket FD
struct client *createSocketClient(struct net_service *service, int fd)
{
anetSetSendBuffer(Modes.aneterr, fd, (MODES_NET_SNDBUF_SIZE << Modes.net_sndbuf_size));
return createGenericClient(service, fd);
}
// Create a client attached to the given service using the provided FD (might not be a socket!)
struct client *createGenericClient(struct net_service *service, int fd)
{
struct client *c;
anetNonBlock(Modes.aneterr, fd);
if (!(c = (struct client *) malloc(sizeof(*c)))) {
fprintf(stderr, "Out of memory allocating a new %s network client\n", service->descr);
exit(1);
}
c->service = NULL;
c->next = Modes.clients;
c->fd = fd;
c->buflen = 0;
c->modeac_requested = 0;
c->verbatim_requested = (service == Modes.beast_verbatim_service || service == Modes.beast_verbatim_local_service);
c->local_requested = (service == Modes.beast_verbatim_local_service);
Modes.clients = c;
moveNetClient(c, service);
return c;
}
// Initiate an outgoing connection which will use the given service.
// Return the new client or NULL if the connection failed
struct client *serviceConnect(struct net_service *service, char *addr, int port)
{
int s;
char buf[20];
// Bleh.
snprintf(buf, 20, "%d", port);
s = anetTcpConnect(Modes.aneterr, addr, buf);
if (s == ANET_ERR)
return NULL;
return createSocketClient(service, s);
}
// Set up the given service to listen on an address/port.
// _exits_ on failure!
void serviceListen(struct net_service *service, char *bind_addr, char *bind_ports)
{
int *fds = NULL;
int n = 0;
char *p, *end;
char buf[128];
if (service->listener_count > 0) {
fprintf(stderr, "Tried to set up the service %s twice!\n", service->descr);
exit(1);
}
if (!bind_ports || !strcmp(bind_ports, "") || !strcmp(bind_ports, "0"))
return;
p = bind_ports;
while (p && *p) {
int newfds[16];
int nfds, i;
end = strpbrk(p, ", ");
if (!end) {
strncpy(buf, p, sizeof(buf));
buf[sizeof(buf)-1] = 0;
p = NULL;
} else {
size_t len = end - p;
if (len >= sizeof(buf))
len = sizeof(buf) - 1;
memcpy(buf, p, len);
buf[len] = 0;
p = end + 1;
}
nfds = anetTcpServer(Modes.aneterr, buf, bind_addr, newfds, sizeof(newfds));
if (nfds == ANET_ERR) {
fprintf(stderr, "Error opening the listening port %s (%s): %s\n",
buf, service->descr, Modes.aneterr);
exit(1);
}
fds = realloc(fds, (n+nfds) * sizeof(int));
if (!fds) {
fprintf(stderr, "out of memory\n");
exit(1);
}
for (i = 0; i < nfds; ++i) {
anetNonBlock(Modes.aneterr, newfds[i]);
fds[n++] = newfds[i];
}
}
service->listener_count = n;
service->listener_fds = fds;
}
struct net_service *makeBeastInputService(void)
{
return serviceInit("Beast TCP input", NULL, NULL, READ_MODE_BEAST, NULL, decodeBinMessage);
}
struct net_service *makeFatsvOutputService(void)
{
return serviceInit("FATSV TCP output", &Modes.fatsv_out, NULL, READ_MODE_IGNORE, NULL, NULL);
}
struct net_service *makeFaCmdInputService(void)
{
return serviceInit("faup Command input", NULL, NULL, READ_MODE_ASCII, "\n", handleFaupCommand);
}
void modesInitNet(void) {
struct net_service *s;
signal(SIGPIPE, SIG_IGN);
Modes.clients = NULL;
Modes.services = NULL;
// set up listeners
s = serviceInit("Raw TCP output", &Modes.raw_out, send_raw_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(s, Modes.net_bind_address, Modes.net_output_raw_ports);
// we maintain three output services for the different option setting combinations we support
// and switch clients between them if they request a change in mode
Modes.beast_cooked_service = serviceInit("Beast TCP output (cooked mode)", &Modes.beast_cooked_out, send_beast_heartbeat, READ_MODE_BEAST_COMMAND, NULL, handleBeastCommand);
Modes.beast_verbatim_service = serviceInit("Beast TCP output (verbatim mode)", &Modes.beast_verbatim_out, send_beast_heartbeat, READ_MODE_BEAST_COMMAND, NULL, handleBeastCommand);
Modes.beast_verbatim_local_service = serviceInit("Beast TCP output (verbatim+local mode)", &Modes.beast_verbatim_local_out, send_beast_heartbeat, READ_MODE_BEAST_COMMAND, NULL, handleBeastCommand);
if (Modes.net_verbatim)
serviceListen(Modes.beast_verbatim_service, Modes.net_bind_address, Modes.net_output_beast_ports);
else
serviceListen(Modes.beast_cooked_service, Modes.net_bind_address, Modes.net_output_beast_ports);
s = serviceInit("Basestation TCP output", &Modes.sbs_out, send_sbs_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(s, Modes.net_bind_address, Modes.net_output_sbs_ports);
s = serviceInit("Stratux TCP output", &Modes.stratux_out, send_stratux_heartbeat, READ_MODE_IGNORE, NULL, NULL);
serviceListen(s, Modes.net_bind_address, Modes.net_output_stratux_ports);
s = serviceInit("Raw TCP input", NULL, NULL, READ_MODE_ASCII, "\n", decodeHexMessage);
serviceListen(s, Modes.net_bind_address, Modes.net_input_raw_ports);
s = makeBeastInputService();
serviceListen(s, Modes.net_bind_address, Modes.net_input_beast_ports);
}
//
//=========================================================================
//
// This function gets called from time to time when the decoding thread is
// awakened by new data arriving. This usually happens a few times every second
//
static struct client * modesAcceptClients(void) {
int fd;
struct net_service *s;
for (s = Modes.services; s; s = s->next) {
int i;
for (i = 0; i < s->listener_count; ++i) {
while ((fd = anetTcpAccept(Modes.aneterr, s->listener_fds[i])) >= 0) {
createSocketClient(s, fd);
}
}
}
return Modes.clients;
}
//
//=========================================================================
//
// On error free the client, collect the structure, adjust maxfd if needed.
//
static void modesCloseClient(struct client *c) {
if (!c->service) {
fprintf(stderr, "warning: double close of net client\n");
return;
}
// Clean up, but defer removing from the list until modesNetCleanup().
// This is because there may be stackframes still pointing at this
// client (unpredictably: reading from client A may cause client B to
// be freed)
close(c->fd);
c->service->connections--;
// mark it as inactive and ready to be freed
c->fd = -1;
c->service = NULL;
c->modeac_requested = 0;
autoset_modeac();
}
//
//=========================================================================
//
// Send the write buffer for the specified writer to all connected clients
//
static void flushWrites(struct net_writer *writer) {
struct client *c;
for (c = Modes.clients; c; c = c->next) {
if (!c->service)
continue;
if (c->service == writer->service) {
#ifndef _WIN32
int nwritten = write(c->fd, writer->data, writer->dataUsed);
#else
int nwritten = send(c->fd, writer->data, writer->dataUsed, 0 );
#endif
if (nwritten != writer->dataUsed) {
modesCloseClient(c);
}
}
}
writer->dataUsed = 0;
writer->lastWrite = mstime();
}
// Prepare to write up to 'len' bytes to the given net_writer.
// Returns a pointer to write to, or NULL to skip this write.
static void *prepareWrite(struct net_writer *writer, int len) {
if (!writer ||
!writer->service ||
!writer->service->connections ||
!writer->data)
return NULL;
if (len > MODES_OUT_BUF_SIZE)
return NULL;
if (writer->dataUsed + len >= MODES_OUT_BUF_SIZE) {
// Flush now to free some space
flushWrites(writer);
}
return writer->data + writer->dataUsed;
}
// Complete a write previously begun by prepareWrite.
// endptr should point one byte past the last byte written
// to the buffer returned from prepareWrite.
static void completeWrite(struct net_writer *writer, void *endptr) {
writer->dataUsed = endptr - writer->data;
if (writer->dataUsed >= Modes.net_output_flush_size) {
flushWrites(writer);
}
}
//
//=========================================================================
//
// Write raw output in Beast Binary format with Timestamp to TCP clients
//
static void modesSendBeastVerbatimOutput(struct modesMessage *mm) {
// Don't forward mlat messages, unless --forward-mlat is set
if (mm->source == SOURCE_MLAT && !Modes.forward_mlat)
return;
// Do verbatim output for all messages
writeBeastMessage(&Modes.beast_verbatim_out, mm->timestampMsg, mm->signalLevel, mm->verbatim, mm->msgbits / 8);
}
static void modesSendBeastVerbatimLocalOutput(struct modesMessage *mm) {
// Never forward remote messages
if (mm->remote)
return;
// Do verbatim output for all messages
writeBeastMessage(&Modes.beast_verbatim_local_out, mm->timestampMsg, mm->signalLevel, mm->verbatim, mm->msgbits / 8);
}
static void modesSendBeastCookedOutput(struct modesMessage *mm, struct aircraft *a) {
// Don't forward mlat messages, unless --forward-mlat is set
if (mm->source == SOURCE_MLAT && !Modes.forward_mlat)
return;
// Filter some messages from cooked output
// Don't forward 2-bit-corrected messages
if (mm->correctedbits >= 2)
return;
// Don't forward unreliable messages
if ((a && !a->reliable) && !mm->reliable)
return;
writeBeastMessage(&Modes.beast_cooked_out, mm->timestampMsg, mm->signalLevel, mm->msg, mm->msgbits / 8);
}
static void writeBeastMessage(struct net_writer *writer, uint64_t timestamp, double signalLevel, unsigned char *msg, int msgLen) {
char ch;
int j;
int sig;
char *p = prepareWrite(writer, 2 + 2 * (7 + msgLen));
if (!p)
return;
*p++ = 0x1a;
if (msgLen == MODES_SHORT_MSG_BYTES)
{*p++ = '2';}
else if (msgLen == MODES_LONG_MSG_BYTES)
{*p++ = '3';}
else if (msgLen == MODEAC_MSG_BYTES)
{*p++ = '1';}
else
{return;}
/* timestamp, big-endian */
*p++ = (ch = (timestamp >> 40));
if (0x1A == ch) {*p++ = ch; }
*p++ = (ch = (timestamp >> 32));
if (0x1A == ch) {*p++ = ch; }
*p++ = (ch = (timestamp >> 24));
if (0x1A == ch) {*p++ = ch; }
*p++ = (ch = (timestamp >> 16));
if (0x1A == ch) {*p++ = ch; }
*p++ = (ch = (timestamp >> 8));
if (0x1A == ch) {*p++ = ch; }
*p++ = (ch = (timestamp));
if (0x1A == ch) {*p++ = ch; }
sig = round(sqrt(signalLevel) * 255);
if (signalLevel > 0 && sig < 1)
sig = 1;
if (sig > 255)
sig = 255;
*p++ = ch = (char)sig;
if (0x1A == ch) {*p++ = ch; }
for (j = 0; j < msgLen; j++) {
*p++ = (ch = msg[j]);
if (0x1A == ch) {*p++ = ch; }
}
completeWrite(writer, p);
}
static void send_beast_heartbeat(struct net_service *service)
{
static char heartbeat_message[] = { 0x1a, '1', 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char *data;
if (!service->writer)
return;
data = prepareWrite(service->writer, sizeof(heartbeat_message));
if (!data)
return;
memcpy(data, heartbeat_message, sizeof(heartbeat_message));
completeWrite(service->writer, data + sizeof(heartbeat_message));
}
//
//=========================================================================
//
// Write raw output to TCP clients
//
static void modesSendRawOutput(struct modesMessage *mm, struct aircraft *a) {
// Don't ever forward mlat messages via raw output.
if (mm->source == SOURCE_MLAT)
return;
// Filter some messages
// Don't forward 2-bit-corrected messages
if (mm->correctedbits >= 2)
return;
// Don't forward unreliable messages
if ((a && !a->reliable) && !mm->reliable)
return;
int msgLen = mm->msgbits / 8;
char *p = prepareWrite(&Modes.raw_out, msgLen*2 + 15);
if (!p)
return;
if (Modes.mlat && mm->timestampMsg) {
/* timestamp, big-endian */
sprintf(p, "@%012" PRIX64,
mm->timestampMsg);
p += 13;
} else
*p++ = '*';
unsigned char *msg = mm->msg;
for (int j = 0; j < msgLen; j++) {
sprintf(p, "%02X", msg[j]);
p += 2;
}
*p++ = ';';
*p++ = '\n';
completeWrite(&Modes.raw_out, p);
}
static void send_raw_heartbeat(struct net_service *service)
{
static char *heartbeat_message = "*0000;\n";
char *data;
int len = strlen(heartbeat_message);
if (!service->writer)
return;
data = prepareWrite(service->writer, len);
if (!data)
return;
memcpy(data, heartbeat_message, len);
completeWrite(service->writer, data + len);
}
//
//=========================================================================
//
// Write SBS output to TCP clients
//
static void modesSendSBSOutput(struct modesMessage *mm, struct aircraft *a) {
char *p;
struct timespec now;
struct tm stTime_receive, stTime_now;
int msgType;
// We require a tracked aircraft for SBS output
if (!a)
return;
// Don't ever forward 2-bit-corrected messages via SBS output.
if (mm->correctedbits >= 2)
return;
// Don't ever forward mlat messages via SBS output.
if (mm->source == SOURCE_MLAT)
return;
// Don't ever send unreliable messages via SBS output
if (!mm->reliable && !a->reliable)
return;
// For now, suppress non-ICAO addresses
if (mm->addr & MODES_NON_ICAO_ADDRESS)
return;
p = prepareWrite(&Modes.sbs_out, 200);
if (!p)
return;
//
// SBS BS style output checked against the following reference
// https://www.homepages.mcb.net/bones/SBS/Article/Barebones42_Socket_Data.htm - seems comprehensive
//
// Decide on the basic SBS Message Type
switch (mm->msgtype) {
case 4:
case 20:
msgType = 5;
break;
break;
case 5:
case 21:
msgType = 6;
break;
case 0:
case 16:
msgType = 7;
break;
case 11:
msgType = 8;
break;
case 17:
case 18:
if (mm->metype >= 1 && mm->metype <= 4) {
msgType = 1;
} else if (mm->metype >= 5 && mm->metype <= 8) {
msgType = 2;
} else if (mm->metype >= 9 && mm->metype <= 18) {
msgType = 3;
} else if (mm->metype == 19) {
msgType = 4;
} else {
return;
}
break;
default:
return;
}
// Fields 1 to 6 : SBS message type and ICAO address of the aircraft and some other stuff
p += sprintf(p, "MSG,%d,1,1,%06X,1,", msgType, mm->addr);
// Find current system time
clock_gettime(CLOCK_REALTIME, &now);
localtime_r(&now.tv_sec, &stTime_now);
// Find message reception time
time_t received = (time_t) (mm->sysTimestampMsg / 1000);
localtime_r(&received, &stTime_receive);
// Fields 7 & 8 are the message reception time and date
p += sprintf(p, "%04d/%02d/%02d,", (stTime_receive.tm_year+1900),(stTime_receive.tm_mon+1), stTime_receive.tm_mday);
p += sprintf(p, "%02d:%02d:%02d.%03u,", stTime_receive.tm_hour, stTime_receive.tm_min, stTime_receive.tm_sec, (unsigned) (mm->sysTimestampMsg % 1000));
// Fields 9 & 10 are the current time and date
p += sprintf(p, "%04d/%02d/%02d,", (stTime_now.tm_year+1900),(stTime_now.tm_mon+1), stTime_now.tm_mday);
p += sprintf(p, "%02d:%02d:%02d.%03u", stTime_now.tm_hour, stTime_now.tm_min, stTime_now.tm_sec, (unsigned) (now.tv_nsec / 1000000U));
// Field 11 is the callsign (if we have it)
if (mm->callsign_valid) {p += sprintf(p, ",%s", mm->callsign);}
else {p += sprintf(p, ",");}
// Field 12 is the altitude (if we have it)
if (Modes.use_gnss) {
if (mm->altitude_geom_valid) {
p += sprintf(p, ",%dH", mm->altitude_geom);
} else if (mm->altitude_baro_valid && trackDataValid(&a->geom_delta_valid)) {
p += sprintf(p, ",%dH", mm->altitude_baro + a->geom_delta);
} else if (mm->altitude_baro_valid) {
p += sprintf(p, ",%d", mm->altitude_baro);
} else {
p += sprintf(p, ",");
}
} else {
if (mm->altitude_baro_valid) {
p += sprintf(p, ",%d", mm->altitude_baro);
} else if (mm->altitude_geom_valid && trackDataValid(&a->geom_delta_valid)) {
p += sprintf(p, ",%d", mm->altitude_geom - a->geom_delta);
} else {
p += sprintf(p, ",");
}
}
// Field 13 is the ground Speed (if we have it)
if (mm->gs_valid) {
p += sprintf(p, ",%.0f", mm->gs.selected);
} else {
p += sprintf(p, ",");
}
// Field 14 is the ground Heading (if we have it)
if (mm->heading_valid && mm->heading_type == HEADING_GROUND_TRACK) {
p += sprintf(p, ",%.0f", mm->heading);
} else {
p += sprintf(p, ",");
}
// Fields 15 and 16 are the Lat/Lon (if we have it)
if (mm->cpr_decoded) {
p += sprintf(p, ",%1.5f,%1.5f", mm->decoded_lat, mm->decoded_lon);
} else {
p += sprintf(p, ",,");
}
// Field 17 is the VerticalRate (if we have it)
if (Modes.use_gnss) {
if (mm->geom_rate_valid) {
p += sprintf(p, ",%dH", mm->geom_rate);
} else if (mm->baro_rate_valid) {
p += sprintf(p, ",%d", mm->baro_rate);
} else {
p += sprintf(p, ",");
}
} else {
if (mm->baro_rate_valid) {
p += sprintf(p, ",%d", mm->baro_rate);
} else if (mm->geom_rate_valid) {
p += sprintf(p, ",%d", mm->geom_rate);
} else {
p += sprintf(p, ",");
}
}
// Field 18 is the Squawk (if we have it)
if (mm->squawk_valid) {
p += sprintf(p, ",%04x", mm->squawk);
} else {
p += sprintf(p, ",");
}
// Field 19 is the Squawk Changing Alert flag (if we have it)
if (mm->alert_valid) {
if (mm->alert) {
p += sprintf(p, ",-1");
} else {
p += sprintf(p, ",0");
}
} else {
p += sprintf(p, ",");
}
// Field 20 is the Squawk Emergency flag (if we have it)
if (mm->squawk_valid) {
if ((mm->squawk == 0x7500) || (mm->squawk == 0x7600) || (mm->squawk == 0x7700)) {
p += sprintf(p, ",-1");
} else {
p += sprintf(p, ",0");
}
} else {
p += sprintf(p, ",");
}
// Field 21 is the Squawk Ident flag (if we have it)
if (mm->spi_valid) {
if (mm->spi) {
p += sprintf(p, ",-1");
} else {
p += sprintf(p, ",0");
}
} else {
p += sprintf(p, ",");
}
// Field 22 is the OnTheGround flag (if we have it)
switch (mm->airground) {
case AG_GROUND:
p += sprintf(p, ",-1");
break;
case AG_AIRBORNE:
p += sprintf(p, ",0");
break;
default:
p += sprintf(p, ",");
break;
}
p += sprintf(p, "\r\n");
completeWrite(&Modes.sbs_out, p);
}
static void send_sbs_heartbeat(struct net_service *service)
{
static char *heartbeat_message = "\r\n"; // is there a better one?
char *data;
int len = strlen(heartbeat_message);
if (!service->writer)
return;
data = prepareWrite(service->writer, len);
if (!data)
return;
memcpy(data, heartbeat_message, len);
completeWrite(service->writer, data + len);
}
//
//=========================================================================
//
// Write Stratux output to TCP clients
//
#define STRATUX_MAX_PACKET_SIZE 1000
static void modesSendStratuxOutput(struct modesMessage *mm, struct aircraft *a) {
char *p;
// We require a tracked aircraft for Stratux output
if (!a)
return;
// Don't ever forward 2-bit-corrected messages via Stratux output.
if (mm->correctedbits >= 2)
return;
// Don't ever send unreliable messages via Stratux output
if (!mm->reliable && !a->reliable)
return;
p = prepareWrite(&Modes.stratux_out, STRATUX_MAX_PACKET_SIZE); // larger buffer size needed vs SBS
if (!p)
return;
char *end = p + STRATUX_MAX_PACKET_SIZE;
// Begin populating the traffic.go fields.
// ICAO address, Mode S message types, and signal level
int cacf = 0; // overload the JSON "CA" field to report CA (DF11 or DF17), CF (DF18), or zero (all other DF types)
if ((mm->msgtype == 11) || (mm->msgtype == 17)) {
cacf = mm->CA;
} else if (mm->msgtype == 18) {
cacf = mm->CF;
}
const char* is_mlat_str = "false";
if (mm->source == SOURCE_MLAT)
is_mlat_str = "true";
p = safe_snprintf(p, end,
"{\"Icao_addr\":%d,"
"\"DF\":%d,\"CA\":%d,"
"\"TypeCode\":%d,"
"\"SubtypeCode\":%d,"
"\"SignalLevel\":%f,"
"\"Gain\":%f,"
"\"IsMlat\":%s,",
mm->addr,
mm->msgtype, cacf,
mm->metype,
mm->mesub,
mm->signalLevel, // what precision and range is needed for RSSI?
sdrGetGainDb(sdrGetGain()),
is_mlat_str);
//// callsign
if (mm->callsign_valid)
p = safe_snprintf(p, end, "\"Tail\":\"%s\",", jsonEscapeString(mm->callsign));
else
p = safe_snprintf(p, end, "\"Tail\":null,");
//// altitude & gnss
bool alt_is_geom;
if (mm->altitude_baro_valid) {
p = safe_snprintf(p, end, "\"Alt\":%d,",mm->altitude_baro);
alt_is_geom = false;
} else if (mm->altitude_geom_valid) {
p = safe_snprintf(p, end, "\"Alt\":%d,",mm->altitude_geom);
alt_is_geom = true;
} else {
p = safe_snprintf(p, end, "\"Alt\":null,");
alt_is_geom = false;
}
// altitude source
if (alt_is_geom)
p = safe_snprintf(p, end, "\"AltIsGNSS\":true,");
else
p = safe_snprintf(p, end, "\"AltIsGNSS\":false,");
// GNSS alt. delta From baro alt.
if (trackDataValid(&a->geom_delta_valid))
p = safe_snprintf(p, end, "\"GnssDiffFromBaroAlt\":%d,",a->geom_delta);
else
p = safe_snprintf(p, end, "\"GnssDiffFromBaroAlt\":null,");
////
//// ground speed and track
if (mm->gs_valid)
p = safe_snprintf(p, end, "\"Speed_valid\":true,\"Speed\":%.0f,", mm->gs.selected);
else
p = safe_snprintf(p, end, "\"Speed_valid\":false,\"Speed\":null,");
//// ground heading
if (mm->heading_valid && mm->heading_type == HEADING_GROUND_TRACK)
p = safe_snprintf(p, end, "\"Track\":%.0f,", mm->heading);
else
p = safe_snprintf(p, end, "\"Track\":null,");
//// position
if (mm->cpr_decoded)
p = safe_snprintf(p, end, "\"Lat\":%.6f,\"Lng\":%.6f,\"Position_valid\":true,",
mm->decoded_lat, mm->decoded_lon);
else
p = safe_snprintf(p, end, "\"Lat\":null,\"Lng\":null,\"Position_valid\":false,");
//// vrate (use barometric if possible)
if (mm->baro_rate_valid)
p = safe_snprintf(p, end, "\"Vvel\":%d,", mm->baro_rate);
else if (mm->geom_rate_valid)
p = safe_snprintf(p, end, "\"Vvel\":%d,", mm->geom_rate);
else
p = safe_snprintf(p, end, "\"Vvel\":null,");
//// squawk
if (mm->squawk_valid)
p = safe_snprintf(p, end, "\"Squawk\":%x,", mm->squawk);
else
p = safe_snprintf(p, end, "\"Squawk\":null,");
// TODO: squawk changing alert support in stratux?
// TODO: squawk emergency flag?
// TODO: squawk ident flag?
// airground
switch (mm->airground) {
case AG_GROUND:
p = safe_snprintf(p, end, "\"OnGround\":true,");
break;
case AG_AIRBORNE:
p = safe_snprintf(p, end, "\"OnGround\":false,");
break;
default:
p = safe_snprintf(p, end, "\"OnGround\":null,");
}
// navigation accuracy category - position
if (mm->accuracy.nac_p_valid) {
p = safe_snprintf(p, end, "\"NACp\":%d,", mm->accuracy.nac_p);
} else {
p = safe_snprintf(p, end, "\"NACp\":null,");
}
// emitter type
int emitter = -1;
if ((mm->msgtype == 17) || (mm->msgtype == 18)) {
switch (mm->metype) {
case 1:
emitter = ((mm->mesub) | 0x18);
break;
case 2:
emitter = ((mm->mesub) | 0x10);
break;
case 3:
emitter = ((mm->mesub) | 0x08);
break;
case 4:
emitter = (mm->mesub);
break;
}
}
if (emitter >= 0)
p = safe_snprintf(p, end, "\"Emitter_category\":%d,", emitter);
else
p = safe_snprintf(p, end, "\"Emitter_category\":null,");
// Time message received (based on system clock). Format is 2016-02-20T06:35:43.155Z
struct tm stTime_receive;
time_t received = (time_t) (mm->sysTimestampMsg / 1000);
gmtime_r(&received, &stTime_receive);
p = safe_snprintf(p, end, "\"Timestamp\":\"%04d-%02d-%02dT%02d:%02d:%02d.%03dZ\"",
(stTime_receive.tm_year+1900),(stTime_receive.tm_mon+1),
stTime_receive.tm_mday, stTime_receive.tm_hour,
stTime_receive.tm_min, stTime_receive.tm_sec,
(unsigned)(mm->sysTimestampMsg % 1000));
p = safe_snprintf(p, end, "}\r\n");
if (p < end)
completeWrite(&Modes.stratux_out, p);
else
fprintf(stderr, "stratux: output too large (max %d, overran by %d)\n", STRATUX_MAX_PACKET_SIZE, (int) (p - end));
}
static void send_stratux_heartbeat(struct net_service *service)
{
static char *heartbeat_message = "{\"Icao_addr\":134217727}\r\n"; // 0x07FFFFFF. Overflows 24-bit ICAO to signal invalic #, need to validate that this won't cause problems with traffic.go
char *data;
int len = strlen(heartbeat_message);
if (!service->writer)