forked from ka9q/ka9q-radio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.c
1640 lines (1508 loc) · 52.7 KB
/
control.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
// Interactive program to send commands and display internal state of 'radiod'
// Why are user interfaces always the biggest, ugliest and buggiest part of any program?
// Written as one big polling loop because ncurses is **not** thread safe
// Copyright 2017-2024 Phil Karn, KA9Q
// Major revisions fall 2020, 2023 (really continuous revisions!)
#define _GNU_SOURCE 1
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <unistd.h>
#include <stdbool.h>
#include <limits.h>
#include <string.h>
#if defined(linux)
#include <bsd/string.h>
#include <bsd/stdlib.h> // for arc4random()
#endif
#include <math.h>
#include <complex.h>
#undef I
#include <poll.h>
#include <sys/time.h>
#include <sys/select.h>
#include <ncurses.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netdb.h>
#include <locale.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <iniparser/iniparser.h>
#include <sysexits.h>
#include <errno.h>
#include <fcntl.h>
#include "avahi.h"
#include "misc.h"
#include "filter.h"
#include "multicast.h"
#include "bandplan.h"
#include "status.h"
#include "radio.h"
#include "config.h"
static int const DEFAULT_IP_TOS = 48;
static int const DEFAULT_MCAST_TTL = 1; // LAN only, no routers
static float Refresh_rate = 0.25f;
static char Locale[256] = "en_US.UTF-8";
static char const *Presets_file = "presets.conf"; // make configurable!
static dictionary *Pdict;
struct frontend Frontend;
struct sockaddr_storage Metadata_source_socket; // Source of metadata
struct sockaddr_storage Metadata_dest_socket; // Dest of metadata (typically multicast)
int Mcast_ttl = DEFAULT_MCAST_TTL;
int IP_tos = DEFAULT_IP_TOS;
float Blocktime;
int Overlap;
int Output_fd,Status_fd;
const char *App_path;
int Verbose;
static struct control {
int item;
bool lock;
int step;
} Control;
static struct {
float noise_bandwidth;
float sig_power;
float sn0;
float snr;
int64_t pll_start_time;
double pll_start_phase;
} Local;
static int send_poll(int ssrc);
static int pprintw(WINDOW *w,int y, int x, char const *prefix, char const *fmt, ...);
static WINDOW *Tuning_win,*Sig_win,*Filtering_win,*Demodulator_win,
*Options_win,*Presets_win,*Debug_win,*Input_win,
*Output_win;
static void display_tuning(WINDOW *tuning,struct channel const *channel);
static void display_info(WINDOW *w,int row,int col,struct channel const *channel);
static void display_filtering(WINDOW *filtering,struct channel const *channel);
static void display_sig(WINDOW *sig,struct channel const *channel);
static void display_demodulator(WINDOW *demodulator,struct channel const *channel);
static void display_options(WINDOW *options,struct channel const *channel);
static void display_presets(WINDOW *modes,struct channel const *channel);
static void display_input(WINDOW *input,struct channel const *channel);
static void display_output(WINDOW *output,struct channel const *channel);
static int process_keyboard(struct channel *,uint8_t **bpp,int c);
static void process_mouse(struct channel *channel,uint8_t **bpp);
static bool for_us(struct channel *channel,uint8_t const *buffer,int length,uint32_t ssrc);
static int init_demod(struct channel *channel);
// Fill in set of locally generated variables from channel structure
static void gen_locals(struct frontend *frontend,struct channel *channel){
Local.noise_bandwidth = fabsf(channel->filter.max_IF - channel->filter.min_IF);
Local.sig_power = channel->sig.bb_power - Local.noise_bandwidth * channel->sig.n0;
if(Local.sig_power < 0)
Local.sig_power = 0; // Avoid log(-x) = nan
Local.sn0 = Local.sig_power/channel->sig.n0;
Local.snr = power2dB(Local.sn0/Local.noise_bandwidth);
}
// Pop up a temporary window with the contents of a file in the
// library directory (usually /usr/local/share/ka9q-radio/)
// then wait for a single keyboard character to clear it
static void popup(char const *filename){
char fname[PATH_MAX];
if (dist_path(fname,sizeof(fname),filename) == -1)
return;
FILE * const fp = fopen(fname,"r");
if(fp == NULL)
return;
// Determine size of box
int rows=0, cols=0;
char *line = NULL;
size_t maxcols = 0;
while(getline(&line,&maxcols,fp) > 0){
chomp(line);
rows++;
if(strlen(line) > cols)
cols = strlen(line); // Longest line
}
rewind(fp);
// Allow room for box
WINDOW * const pop = newwin(rows+2,cols+2,0,0);
box(pop,0,0);
int row = 1; // Start inside box
while(getline(&line,&maxcols,fp) > 0){
chomp(line);
mvwaddstr(pop,row++,1,line);
}
fclose(fp);
FREE(line);
wnoutrefresh(pop);
doupdate();
wtimeout(pop,-1); // blocking read - wait indefinitely
(void)wgetch(pop); // Read and discard one character
wtimeout(pop,0);
werase(pop);
wrefresh(pop);
delwin(pop);
}
// Pop up a dialog box, issue a prompt and get a response
static void getentry(char const *prompt,char *response,int len){
int boxwidth = strlen(prompt) + len;
WINDOW * const pwin = newwin(5,boxwidth+2,0,0);
box(pwin,0,0);
mvwaddstr(pwin,1,1,prompt);
wrefresh(pwin);
echo();
timeout(-1);
// Manpage for wgetnstr doesn't say whether a terminating
// null is stashed. Hard to believe it isn't, but this is to be sure
memset(response,0,len);
int r = wgetnstr(pwin,response,len);
if(r != OK)
memset(response,0,len); // Zero out the read buffer
chomp(response);
timeout(0);
noecho();
werase(pwin);
wrefresh(pwin);
delwin(pwin);
}
static FILE *Tty;
static SCREEN *Term;
static void display_cleanup(void){
echo();
nocbreak();
if(!isendwin()){
endwin();
refresh();
}
if(Term)
delscreen(Term);
Term = NULL;
if(Tty)
fclose(Tty);
Tty = NULL;
}
static bool Frequency_lock;
// Adjust the selected item up or down one step
static void adjust_item(struct channel *channel,uint8_t **bpp,int direction){
double tunestep = pow(10., (double)Control.step);
if(!direction)
tunestep = - tunestep;
switch(Control.item){
case 0: // Carrier frequency
if(!Frequency_lock){ // Ignore if locked
channel->tune.freq += tunestep;
encode_double(bpp,RADIO_FREQUENCY,channel->tune.freq);
}
break;
case 1: // First LO
if(Control.lock) // Tuner is locked, don't change it
break;
// Send via radiod
encode_float(bpp,FIRST_LO_FREQUENCY,Frontend.frequency+tunestep);
break;
case 2: // IF (not implemented)
break;
case 3: // Filter low edge (hertz rather than millihertz)
{
float const x = min(channel->filter.max_IF,channel->filter.min_IF + (float)tunestep * 1000);
channel->filter.min_IF = x;
encode_float(bpp,LOW_EDGE,x);
}
break;
case 4: // Filter high edge
{
float const x = max(channel->filter.min_IF,channel->filter.max_IF + (float)tunestep * 1000);
channel->filter.max_IF = x;
encode_float(bpp,HIGH_EDGE,x);
}
break;
case 5: // Post-detection audio frequency shift
channel->tune.shift += tunestep;
encode_double(bpp,SHIFT_FREQUENCY,channel->tune.shift);
break;
}
}
// It seems better to just use the Griffin application to turn knob events into keystrokes or mouse events
static void adjust_up(struct channel *channel,uint8_t **bpp){
adjust_item(channel,bpp,1);
}
static void adjust_down(struct channel *channel,uint8_t **bpp){
adjust_item(channel,bpp,0);
}
static void toggle_lock(void){
switch(Control.item){
case 0:
Frequency_lock = !Frequency_lock; // Toggle frequency tuning lock
break;
case 1:
Control.lock = !Control.lock;
break;
}
}
// List of status windows, in order they'll be created, with sizes
static struct windef {
WINDOW **w;
int rows;
int cols;
} Windefs[] = {
{&Tuning_win, 18, 30},
{&Options_win, 18, 12},
// {&Presets_win,Npresets+2,9}, // Npresets is not a static initializer
{&Presets_win,18,9},
{&Sig_win,18,25},
{&Demodulator_win,18,26},
{&Filtering_win,18,22},
{&Input_win,18,45},
{&Output_win,18,45},
};
#define NWINS (sizeof(Windefs) / sizeof(Windefs[0]))
static void setup_windows(void){
// First row
int row = 0;
int col = 0;
int maxrows = 0;
endwin();
refresh();
clear();
struct winsize w;
ioctl(fileno(Tty),TIOCGWINSZ,&w);
COLS = w.ws_col;
LINES = w.ws_row;
// Delete all previous windows
for(int i=0; i < NWINS; i++){
if(*Windefs[i].w)
delwin(*Windefs[i].w);
*Windefs[i].w = NULL;
}
// Create as many as will fit
for(int i=0; i < NWINS; i++){
if(COLS < col + Windefs[i].cols){
// No more room on this line, go to next
col = 0;
row += maxrows;
maxrows = 0;
}
if(LINES < row + Windefs[i].rows){
// No more room for anything
return;
}
// Room on this line
* Windefs[i].w = newwin(Windefs[i].rows,Windefs[i].cols,row,col);
col += Windefs[i].cols;
maxrows = max(maxrows,Windefs[i].rows);
}
// Specially set up debug window
// Minimum of 45 cols for debug window, otherwise go to next row
if(col + 45 > COLS){
row += maxrows;
col = 0;
}
if(row < LINES && col < COLS)
Debug_win = newwin(LINES - row,COLS-col,row,col); // Only if room is left
// A message from our sponsor...
scrollok(Debug_win,TRUE); // This one scrolls so it can be written to with wprintw(...\n)
wprintw(Debug_win,"KA9Q-radio %s last modified %s\n",__FILE__,__TIMESTAMP__);
wprintw(Debug_win,"Copyright 2024, Phil Karn, KA9Q. May be used under the terms of the GNU Public License\n");
}
// Comparison for sorting by SSRC
static int chan_compare(void const *a,void const *b){
struct channel const *da = *(struct channel **)a;
struct channel const *db = *(struct channel **)b;
if(da->output.rtp.ssrc < db->output.rtp.ssrc){
return -1;
}
if(da->output.rtp.ssrc > db->output.rtp.ssrc){
return +1;
}
return 0;
}
static uint32_t Ssrc = 0;
// Thread to display receiver state, updated at 10Hz by default
// Uses the ancient ncurses text windowing library
// Also services keyboard, mouse and tuning knob, if present
int main(int argc,char *argv[]){
App_path = argv[0];
{
int c;
while((c = getopt(argc,argv,"vVs:r:")) != -1){
switch(c){
case 'V':
VERSION();
exit(EX_OK);
case 'v':
Verbose++;
break;
case 's':
Ssrc = strtol(optarg,NULL,0); // Send to specific SSRC
break;
case 'r':
Refresh_rate = strtod(optarg,NULL);
break;
default:
fprintf(stdout,"Unknown option %c\n",c);
break;
}
}
}
{
// The display thread assumes en_US.UTF-8, or anything with a thousands grouping character
// Otherwise the cursor movements will be wrong
char const * const cp = getenv("LANG");
if(cp != NULL){
strlcpy(Locale,cp,sizeof(Locale));
}
}
setlocale(LC_ALL,Locale); // Set either the hardwired default or the value of $LANG if it exists
char const *target = argc > optind ? argv[optind] : NULL;
Output_fd = socket(AF_INET,SOCK_DGRAM,0); // Eventually intended for all output with sendto()
if(Output_fd < 0){
fprintf(stdout,"can't create output socket: %s\n",strerror(errno));
exit(EX_OSERR); // let systemd restart us
}
fcntl(Output_fd,F_SETFL,O_NONBLOCK); // Just drop instead of blocking real time
if(target == NULL){
// Use avahi browser to find a radiod instance to control
fprintf(stdout,"Scanning for radiod instances...\n");
int const table_size = 1000;
struct service_tab table[table_size];
int radiod_count = avahi_browse(table,table_size,"_ka9q-ctl._udp"); // Returns list in global when cache is emptied
if(radiod_count == 0){
fprintf(stdout,"No radiod instances or Avahi not running; specify control channel manually\n");
exit(EX_UNAVAILABLE);
}
int n = 0;
if(radiod_count == 1){
// Only one, use it
fprintf(stdout,"Using %s (%s)\n",table[n].name,table[n].dns_name);
} else {
for(int i=0; i < radiod_count; i++)
fprintf(stdout,"%d: %s (%s)\n",i,table[i].name,table[i].dns_name);
fprintf(stdout,"Select index: ");
fflush(stdout);
char *line = NULL;
size_t linesize = 0;
if(getline(&line,&linesize,stdin) <= 0){
fprintf(stdout,"EOF on input\n");
FREE(line);
exit(EX_USAGE);
}
n = strtol(line,NULL,0);
FREE(line);
if(n < 0 || n >= radiod_count){
fprintf(stdout,"Index %d out of range, try again\n",n);
exit(EX_USAGE);
}
}
struct addrinfo *results = NULL;
struct addrinfo hints;
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_INET; // IPv4 for now
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICHOST | AI_NUMERICSERV;
int const ecode = getaddrinfo(table[n].address,table[n].port,&hints,&results);
if(ecode != 0){
fprintf(stdout,"getaddrinfo: %s\n",gai_strerror(ecode));
exit(EX_IOERR);
}
// Use first entry on list -- much simpler
// I previously tried each entry in turn until one succeeded, but with UDP sockets and
// flags set to only return supported addresses, how could any of them fail?
memcpy(&Metadata_dest_socket,results->ai_addr,sizeof(Metadata_dest_socket));
freeaddrinfo(results); results = NULL;
Status_fd = listen_mcast(&Metadata_dest_socket,table[n].interface);
join_group(Output_fd,(struct sockaddr *)&Metadata_dest_socket,table[n].interface,Mcast_ttl,IP_tos);
} else {
// Use resolv_mcast to resolve a manually entered domain name, using default port and parsing possible interface
char iface[1024]; // Multicast interface
resolve_mcast(target,&Metadata_dest_socket,DEFAULT_STAT_PORT,iface,sizeof(iface),0);
Status_fd = listen_mcast(&Metadata_dest_socket,iface);
join_group(Output_fd,(struct sockaddr *)&Metadata_dest_socket,iface,Mcast_ttl,IP_tos);
}
if(Status_fd < 0){
fprintf(stderr,"Can't listen to mcast status channel: %s\n",strerror(errno));
exit(EX_IOERR);
}
{
// All reads from the status channel will have a timeout
// Should this be configurable?
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000; // 100k microsec = 100 millisec
if(setsockopt(Status_fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout)) == -1)
perror("setsock timeout");
}
char presetsfile_path[PATH_MAX];
if (dist_path(presetsfile_path,sizeof(presetsfile_path),Presets_file) == -1) {
fprintf(stderr,"Could not find mode file %s\n", Presets_file);
exit(EX_NOINPUT);
}
Pdict = iniparser_load(presetsfile_path);
if(Pdict == NULL){
fprintf(stdout,"Can't load mode file %s\n",presetsfile_path);
exit(EX_NOINPUT);
}
atexit(display_cleanup);
struct channel **channels = NULL;
int chan_count = 0;
while(Ssrc == 0){
// No channel specified; poll radiod for a list, sort and let user choose
// If responses are lost or delayed and the user gets an incomplete list, just hit return
// and we'll poll again. New entries will be added & existing entries will be updated
// though any that disappear from radiod will remain on the list (not a big deal here)
// The search exits after either a 100 ms timeout waiting for any incoming message OR 1 sec with no new channels seen
// The second test is important when monitoring a status channel busy with 'control' polls or ka9q-web spectrum data
send_poll(0xffffffff);
// Read responses
int const chan_max = 1024;
if(channels == NULL)
channels = (struct channel **)calloc(chan_max,sizeof(struct channel *));
int64_t last_new_entry = gps_time_ns();
while(chan_count < chan_max){
struct sockaddr_storage source_socket;
socklen_t ssize = sizeof(source_socket);
uint8_t buffer[PKTSIZE];
int length = recvfrom(Status_fd,buffer,sizeof(buffer),0,(struct sockaddr *)&source_socket,&ssize); // should not block
if(length == -1 && errno == EAGAIN)
break; // Timeout; we're done
// Ignore our own command packets
if(length < 2 || (enum pkt_type)buffer[0] != STATUS)
continue;
// What to do with the source addresses?
memcpy(&Metadata_source_socket,&source_socket,sizeof(Metadata_source_socket));
struct channel * const channel = calloc(1,sizeof(struct channel));
init_demod(channel);
decode_radio_status(&Frontend,channel,buffer+1,length-1);
// Do we already have it?
int i;
for(i=0; i < chan_count; i++)
if(channels[i]->output.rtp.ssrc == channel->output.rtp.ssrc)
break;
if(i < chan_count){
// Already in table, replace
assert(channels[i] != NULL);
FREE(channels[i]);
channels[i] = channel;
if(gps_time_ns() > last_new_entry + BILLION)
break; // Give up after 1 sec with no new channels
} else {
channels[chan_count++] = channel; // New one, add
last_new_entry = gps_time_ns();
}
}
qsort(channels,chan_count,sizeof(channels[0]),chan_compare);
fprintf(stdout,"%13s %9s %13s %5s %s\n","SSRC","preset","freq, Hz","SNR","output channel");
uint32_t last_ssrc = 0;
for(int i=0; i < chan_count;i++){
struct channel *channel = channels[i];
if(channel == NULL || channel->output.rtp.ssrc == last_ssrc) // Skip dupes
continue;
char const *ip_addr_string = formatsock(&channel->output.dest_socket);
gen_locals(&Frontend,channel);
fprintf(stdout,"%13u %9s %'13.f %5.1f %s\n",channel->output.rtp.ssrc,channel->preset,channel->tune.freq,Local.snr,ip_addr_string);
last_ssrc = channel->output.rtp.ssrc;
}
fprintf(stdout,"%d channels; choose SSRC, create new SSRC, or hit return to look for more: ",chan_count);
fflush(stdout);
char *line = NULL;
size_t length = 0;
if(getline(&line,&length,stdin) <= 0){
fprintf(stdout,"EOF on input, exiting\n");
FREE(line);
exit(EX_USAGE);
}
int const n = strtol(line,NULL,0);
FREE(line);
if(n > 0)
Ssrc = n; // Will cause a break from this loop
}
// Free channel structures and pointer array, if they were used
for(int i=0; i < chan_count; i++){
if(channels[i] != NULL)
FREE(channels[i]);
}
FREE(channels);
struct channel Channel;
struct channel *channel = &Channel;
init_demod(channel);
// Set up display subwindows
Tty = fopen("/dev/tty","r+");
Term = newterm(NULL,Tty,Tty);
set_term(Term);
// meta(stdscr,TRUE);
keypad(stdscr,TRUE);
timeout(0); // Don't block in getch()
cbreak();
noecho();
mmask_t const mask = ALL_MOUSE_EVENTS;
mousemask(mask,NULL);
setup_windows();
Frontend.frequency = Frontend.min_IF = Frontend.max_IF = NAN;
/* Main loop:
Send poll if we haven't received one in our refresh interval
See if anything has arrived (use short timeout)
If there's a response, update local status & repaint display windows
Poll keyboard and process user commands
Randomize polls over +/- 32 ms in case someone else is also polling
This avoids possible synchronized back-to-back polls
This is a common technique in multicast protocols (e.g., IGMP queries)
*/
int const random_interval = 64 << 20; // power of 2 makes it easier for arc4random_uniform()
int64_t now = gps_time_ns();
int64_t next_radio_poll = now; // Immediate first poll
bool screen_update_needed = false;
for(;;){
int64_t const radio_poll_interval = Refresh_rate * BILLION; // Can change from the keyboard
if(now >= next_radio_poll){
// Time to poll radio
send_poll(Ssrc);
#ifdef DEBUG_POLL
wprintw(Debug_win,"poll sent %lld\n",now);
#endif
// Retransmit after 1/10 sec if no response
next_radio_poll = now + radio_poll_interval + arc4random_uniform(random_interval) - random_interval/2;
}
// Poll the input socket
// This paces keyboard polling so wait no more than 100 ms, even for long refresh intervals
int const recv_timeout = BILLION/10;
int64_t start_of_recv_poll = now;
uint8_t buffer[PKTSIZE];
int length = 0;
do {
now = gps_time_ns();
// Message from the radio program (or some transcoders)
struct sockaddr_storage source_socket;
socklen_t ssize = sizeof(source_socket);
length = recvfrom(Status_fd,buffer,sizeof(buffer),0,(struct sockaddr *)&source_socket,&ssize); // should not block
// Ignore our own command packets and responses to other SSIDs
if(length < 2 || (enum pkt_type)buffer[0] != STATUS || !for_us(channel,buffer+1,length-1,Ssrc))
continue; // Can include a timeout
// Process only if it's a response to our SSRC
memcpy(&Metadata_source_socket,&source_socket,sizeof(Metadata_source_socket));
screen_update_needed = true;
#ifdef DEBUG_POLL
wprintw(Debug_win,"got response length %d\n",length);
#endif
decode_radio_status(&Frontend,channel,buffer+1,length-1);
gen_locals(&Frontend,channel);
// Postpone next poll to specified interval
next_radio_poll = now + radio_poll_interval + arc4random_uniform(random_interval) - random_interval/2;
if(Blocktime == 0 && Frontend.samprate != 0)
Blocktime = 1000.0f * Frontend.L / Frontend.samprate; // Set the firat time
} while(now < start_of_recv_poll + recv_timeout);
// Set up command buffer in case we want to change something
uint8_t cmdbuffer[PKTSIZE];
uint8_t *bp = cmdbuffer;
*bp++ = CMD; // Command
// Poll keyboard and mouse
int const c = getch();
if(c == KEY_MOUSE){
process_mouse(channel,&bp);
screen_update_needed = true;
} else if(c != ERR) {
screen_update_needed = true;
if(process_keyboard(channel,&bp,c) == -1)
goto quit;
}
// Any commands to send?
if(bp > cmdbuffer+1){
// Yes
assert(Ssrc != 0);
encode_int(&bp,OUTPUT_SSRC,Ssrc); // Specific SSRC
encode_int(&bp,COMMAND_TAG,arc4random()); // Append a command tag
encode_eol(&bp);
int const command_len = bp - cmdbuffer;
#ifdef DEBUG_POLL
wprintw(Debug_win,"sent command len %d\n",command_len);
screen_update_needed = true; // show local change right away
#endif
if(sendto(Output_fd, cmdbuffer, command_len, 0, (struct sockaddr *)&Metadata_dest_socket,sizeof(struct sockaddr)) != command_len){
wprintw(Debug_win,"command send error: %s\n",strerror(errno));
screen_update_needed = true; // show local change right away
}
// This will elicit an answer, defer the next poll
next_radio_poll = now + radio_poll_interval + arc4random_uniform(random_interval) - random_interval/2;
}
if(screen_update_needed){
// update display windows
display_tuning(Tuning_win,channel);
display_filtering(Filtering_win,channel);
display_sig(Sig_win,channel);
display_demodulator(Demodulator_win,channel);
display_options(Options_win,channel);
display_presets(Presets_win,channel);
display_input(Input_win,channel);
display_output(Output_win,channel);
if(Debug_win != NULL){
touchwin(Debug_win); // since we're not redrawing it every cycle
wnoutrefresh(Debug_win);
}
doupdate(); // Update the screen right before we pause
screen_update_needed = false;
}
}
quit:;
endwin();
set_term(NULL);
if(Term != NULL)
delscreen(Term);
#if 0 // double free error, not really needed anyway
if(Tty != NULL)
fclose(Tty);
#endif
exit(EX_OK);
}
int const Entry_width = 15;
static int process_keyboard(struct channel *channel,uint8_t **bpp,int c){
// Look for keyboard and mouse events
switch(c){
case ERR:
break;
case KEY_RESIZE:
setup_windows();
break;
case 0x3: // ^C
case 'q': // Exit entire radio program. Should this be removed? ^C also works.
return -1;
case 'h':
case '?':
popup("help.txt");
break;
case 'l': // Toggle RF or first LO lock; affects how adjustments to LO and IF behave
toggle_lock();
break;
case KEY_NPAGE: // Page Down/tab key
case '\t': // go to next tuning item
Control.item = (Control.item + 1) % 6;
break;
case KEY_BTAB: // Page Up/Backtab, i.e., shifted tab:
case KEY_PPAGE: // go to previous tuning item
Control.item = (6 + Control.item - 1) % 6;
break;
case KEY_HOME: // Go back to item 0
Control.item = 0;
Control.step = 0;
break;
case KEY_BACKSPACE: // Cursor left: increase tuning step 10x
case KEY_LEFT:
if(Control.step >= 9){
beep();
break;
}
Control.step++;
break;
case KEY_RIGHT: // Cursor right: decrease tuning step /10
if(Control.step <= -3){
beep();
break;
}
Control.step--;
break;
case KEY_UP: // Increase whatever digit we're tuning
adjust_up(channel,bpp);
break;
case KEY_DOWN: // Decrease whatever we're tuning
adjust_down(channel,bpp);
break;
case '\f': // Screen repaint (formfeed, aka control-L)
clearok(curscr,TRUE);
break;
case 'S':
{
char str[Entry_width];
getentry("Output sample rate, Hz: ",str,sizeof(str));
int samprate = parse_frequency(str,false);
channel->output.samprate = samprate;
encode_int(bpp,OUTPUT_SAMPRATE,channel->output.samprate);
}
break;
case 's': // Squelch threshold for current mode
{
char str[Entry_width],*ptr;
getentry("Squelch SNR: ",str,sizeof(str));
float const x = strtof(str,&ptr);
if(ptr != str && isfinite(x)){
encode_float(bpp,SQUELCH_OPEN,x);
encode_float(bpp,SQUELCH_CLOSE,x - 1); // Make this a separate command
}
}
break;
case 'T': // Hang time, s (always taken as positive)
{
char str[Entry_width],*ptr;
getentry("Hang time, s: ",str,sizeof(str));
float const x = fabsf(strtof(str,&ptr));
if(ptr != str && isfinite(x))
encode_float(bpp,AGC_HANGTIME,x);
}
break;
case 'P': // PLL loop bandwidth, always positive
{
char str[Entry_width],*ptr;
getentry("PLL loop bandwidth, Hz: ",str,sizeof(str));
float const x = fabsf(strtof(str,&ptr));
if(ptr != str && isfinite(x))
encode_float(bpp,PLL_BW,x);
}
break;
case 'L': // AGC threshold, dB relative to headroom
{
char str[Entry_width],*ptr;
getentry("AGC threshold, dB: ",str,sizeof(str));
float const x = strtof(str,&ptr);
if(ptr != str && isfinite(x))
encode_float(bpp,AGC_THRESHOLD,x);
}
break;
case 'R': // Recovery rate, dB/s (always taken as positive)
{
char str[Entry_width],*ptr;
getentry("Recovery rate, dB/s: ",str,sizeof(str));
float const x = fabsf(strtof(str,&ptr));
if(ptr != str && isfinite(x))
encode_float(bpp,AGC_RECOVERY_RATE,x);
}
break;
case 'H': // Target AGC output level (headroom), dB, taken as negative
{
char str[Entry_width],*ptr;
getentry("Headroom, dB: ",str,sizeof(str));
float const x = -fabsf(strtof(str,&ptr));
if(ptr != str && isfinite(x))
encode_float(bpp,HEADROOM,x);
}
break;
case 'G': // Manually set front end gain, dB (positive or negative)
{
char str[Entry_width],*ptr;
getentry("RF Gain, dB: ",str,sizeof(str));
float const x = strtof(str,&ptr);
if(ptr != str && isfinite(x)){
encode_float(bpp,RF_GAIN,x);
}
}
break;
case 'A': // Manually set front end attenuation, dB (positive or negative)
{
char str[Entry_width],*ptr;
getentry("RF Atten, dB: ",str,sizeof(str));
float const x = fabsf(strtof(str,&ptr));
if(ptr != str && isfinite(x)){
encode_float(bpp,RF_ATTEN,x);
}
}
break;
case 'b':
{
char str[Entry_width],*ptr;
getentry("Opus bitrate, bit/sec (0=auto): ",str,sizeof(str));
int const x = labs(strtol(str,&ptr,0));
if(ptr != str)
encode_int(bpp,OPUS_BIT_RATE,x);
}
break;
case 'g': // Manually set linear channel gain, dB (positive or negative)
{
char str[Entry_width],*ptr;
getentry("Gain, dB: ",str,sizeof(str));
float const x = strtof(str,&ptr);
if(ptr != str && isfinite(x)){
encode_float(bpp,GAIN,x);
encode_byte(bpp,AGC_ENABLE,0); // Also done implicitly in radiod
}
}
break;
case 'r': // Poll/refresh rate
{
char str[Entry_width],*ptr;
getentry("Refresh rate (s): ",str,sizeof(str));
float const x = fabsf(strtof(str,&ptr));
if(ptr != str && isfinite(x))
Refresh_rate = x;
}
break;
case 'p':
case 'm': // Manual mode preset
{
char str[Entry_width];
char prompt[1024];
snprintf(prompt,sizeof(prompt),"Mode/Preset [ ");
int const nsec = iniparser_getnsec(Pdict);
for(int i=0;i < nsec;i++){
strlcat(prompt,iniparser_getsecname(Pdict,i),sizeof(prompt));
strlcat(prompt," ",sizeof(prompt));
}
strlcat(prompt,"]: ",sizeof(prompt));
getentry(prompt,str,sizeof(str));
if(strlen(str) > 0)
encode_string(bpp,PRESET,str,strlen(str));
}
break;
case 'f': // Tune to new radio frequency
{
char str[Entry_width];
getentry("Carrier frequency: ",str,sizeof(str));
if(strlen(str) > 0){
double const x = fabs(parse_frequency(str,true)); // Handles funky forms like 147m435
if(isfinite(x)){
channel->tune.freq = x;
encode_double(bpp,RADIO_FREQUENCY,channel->tune.freq);
}
}
}
break;
case 'k': // Kaiser window parameter
{
char str[Entry_width],*ptr;
getentry("Kaiser window β: ",str,sizeof(str));
float const b = strtof(str,&ptr);
if(ptr != str && isfinite(b)){
if(b < 0 || b >= 100){
beep(); // beyond limits
} else {
encode_float(bpp,KAISER_BETA,b);
}
}
}
break;
case 'o': // Set/clear option flags, most apply only to linear detector
{
char str[Entry_width];
getentry("[isb pll square stereo mono agc], '!' prefix disables: ",str,sizeof(str));
bool enable = true;
if(strchr(str,'!') != NULL)
enable = false;
if(strcasestr(str,"mono") != NULL){
encode_int(bpp,OUTPUT_CHANNELS,enable ? 1 : 2);
} else if(strcasestr(str,"stereo") != NULL){
encode_int(bpp,OUTPUT_CHANNELS,enable ? 2 : 1);
} else if(strcasestr(str,"isb") != NULL){
encode_byte(bpp,INDEPENDENT_SIDEBAND,enable);
} else if(strcasestr(str,"pll") != NULL){
encode_byte(bpp,PLL_ENABLE,enable);
} else if(strcasestr(str,"square") != NULL){
encode_byte(bpp,PLL_SQUARE,enable);
if(enable)
encode_byte(bpp,PLL_ENABLE,enable);
} else if(strcasestr(str,"agc") != NULL){
encode_byte(bpp,AGC_ENABLE,enable);
}
}
break;
case 'O': // Set/clear aux option flags, mainly for testing
{
char str[Entry_width],*ptr;
getentry("enter aux option number [0-63], ! disables: ",str,sizeof(str));
bool enable = true;
char *cp = strchr(str,'!');
if(cp != NULL){
enable = false;
cp++;
} else
cp = str;
int n = strtol(cp,&ptr,0);
if(ptr != cp && n >= 0 && n < 64){
if(enable)
encode_int(bpp,SETOPTS,1LL<<n);
else
encode_int(bpp,CLEAROPTS,1LL<<n);
}
}
break;
case 'u':
{
char str[Entry_width],*ptr;
getentry("Data channel status rate ",str,sizeof(str));
int const b = strtol(str,&ptr,0);
if(ptr != str && b >= 0)
encode_int(bpp,STATUS_INTERVAL,b);
}
break;
case 'e':
{
char str[Entry_width];
getentry("Output encoding [s16le s16be f32le f16le opus]: ",str,sizeof(str));
enum encoding e = parse_encoding(str);
if(e != NO_ENCODING)
encode_byte(bpp,OUTPUT_ENCODING,e);
}
break;
default:
beep();
break;
} // switch
return 0;
}
static void process_mouse(struct channel *channel,uint8_t **bpp){
// Process mouse events
// Need to handle the wheel as equivalent to up/down arrows
MEVENT mouse_event;
getmouse(&mouse_event);
int mx,my;
mx = mouse_event.x;
my = mouse_event.y;
mouse_event.y = mouse_event.x = mouse_event.z = 0;
if(mx != 0 && my != 0){
#if 0
wprintw(debug," (%d %d)",mx,my);