forked from PiInTheSky/lora-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.c
2588 lines (2095 loc) · 74.3 KB
/
gateway.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
#include <features.h>
#define __USE_XOPEN
#include <stdio.h>
#include <stdio.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdint.h>
#include <stdarg.h>
#include <pthread.h>
#include <curses.h>
#include <math.h>
#include <dirent.h>
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <time.h>
#include "urlencode.h"
#include "base64.h"
#include "ssdv.h"
#include "ftp.h"
#include "habitat.h"
#include "network.h"
#include "global.h"
#include "server.h"
#include "gateway.h"
#include "config.h"
#include "gui.h"
#define VERSION "V1.8.12"
bool run = TRUE;
// RFM98
uint8_t currentMode = 0x81;
#define REG_FIFO 0x00
#define REG_FIFO_ADDR_PTR 0x0D
#define REG_FIFO_TX_BASE_AD 0x0E
#define REG_FIFO_RX_BASE_AD 0x0F
#define REG_RX_NB_BYTES 0x13
#define REG_OPMODE 0x01
#define REG_FIFO_RX_CURRENT_ADDR 0x10
#define REG_IRQ_FLAGS 0x12
#define REG_PACKET_SNR 0x19
#define REG_PACKET_RSSI 0x1A
#define REG_CURRENT_RSSI 0x1B
#define REG_DIO_MAPPING_1 0x40
#define REG_DIO_MAPPING_2 0x41
#define REG_MODEM_CONFIG 0x1D
#define REG_MODEM_CONFIG2 0x1E
#define REG_MODEM_CONFIG3 0x26
#define REG_PAYLOAD_LENGTH 0x22
#define REG_IRQ_FLAGS_MASK 0x11
#define REG_HOP_PERIOD 0x24
#define REG_FREQ_ERROR 0x28
#define REG_DETECT_OPT 0x31
#define REG_DETECTION_THRESHOLD 0x37
// MODES
#define RF98_MODE_RX_CONTINUOUS 0x85
#define RF98_MODE_TX 0x83
#define RF98_MODE_SLEEP 0x80
#define RF98_MODE_STANDBY 0x81
#define PAYLOAD_LENGTH 255
// Modem Config 1
#define EXPLICIT_MODE 0x00
#define IMPLICIT_MODE 0x01
#define ERROR_CODING_4_5 0x02
#define ERROR_CODING_4_6 0x04
#define ERROR_CODING_4_7 0x06
#define ERROR_CODING_4_8 0x08
#define BANDWIDTH_7K8 0x00
#define BANDWIDTH_10K4 0x10
#define BANDWIDTH_15K6 0x20
#define BANDWIDTH_20K8 0x30
#define BANDWIDTH_31K25 0x40
#define BANDWIDTH_41K7 0x50
#define BANDWIDTH_62K5 0x60
#define BANDWIDTH_125K 0x70
#define BANDWIDTH_250K 0x80
#define BANDWIDTH_500K 0x90
// Modem Config 2
#define SPREADING_6 0x60
#define SPREADING_7 0x70
#define SPREADING_8 0x80
#define SPREADING_9 0x90
#define SPREADING_10 0xA0
#define SPREADING_11 0xB0
#define SPREADING_12 0xC0
#define CRC_OFF 0x00
#define CRC_ON 0x04
// POWER AMPLIFIER CONFIG
#define REG_PA_CONFIG 0x09
#define PA_MAX_BOOST 0x8F
#define PA_LOW_BOOST 0x81
#define PA_MED_BOOST 0x8A
#define PA_MAX_UK 0x88
#define PA_OFF_BOOST 0x00
#define RFO_MIN 0x00
// LOW NOISE AMPLIFIER
#define REG_LNA 0x0C
#define LNA_MAX_GAIN 0x23 // 0010 0011
#define LNA_OFF_GAIN 0x00
#define LNA_LOW_GAIN 0xC0 // 1100 0000
struct TLoRaMode
{
int ImplicitOrExplicit;
int ErrorCoding;
int Bandwidth;
int SpreadingFactor;
int LowDataRateOptimize;
int BaudRate;
char *Description;
} LoRaModes[] =
{
{EXPLICIT_MODE, ERROR_CODING_4_8, BANDWIDTH_20K8, SPREADING_11, 1, 60, "Telemetry"}, // 0: Normal mode for telemetry
{IMPLICIT_MODE, ERROR_CODING_4_5, BANDWIDTH_20K8, SPREADING_6, 0, 1400, "SSDV"}, // 1: Normal mode for SSDV
{EXPLICIT_MODE, ERROR_CODING_4_8, BANDWIDTH_62K5, SPREADING_8, 0, 2000, "Repeater"}, // 2: Normal mode for repeater network
{EXPLICIT_MODE, ERROR_CODING_4_6, BANDWIDTH_250K, SPREADING_7, 0, 8000, "Turbo"}, // 3: Normal mode for high speed images in 868MHz band
{IMPLICIT_MODE, ERROR_CODING_4_5, BANDWIDTH_250K, SPREADING_6, 0, 16828, "TurboX"}, // 4: Fastest mode within IR2030 in 868MHz band
{EXPLICIT_MODE, ERROR_CODING_4_8, BANDWIDTH_41K7, SPREADING_11, 0, 200, "Calling"}, // 5: Calling mode
{IMPLICIT_MODE, ERROR_CODING_4_5, BANDWIDTH_41K7, SPREADING_6, 0, 2800, "Uplink"}, // 6: Uplink mode for 868
{EXPLICIT_MODE, ERROR_CODING_4_5, BANDWIDTH_20K8, SPREADING_7, 0, 2800, "Telnet"}, // 7: Telnet-style comms with HAB on 434
{IMPLICIT_MODE, ERROR_CODING_4_5, BANDWIDTH_62K5, SPREADING_6, 0, 4500, "SSDV Repeater"} // 8: Fast (SSDV) repeater network
};
struct TConfig Config;
struct TBandwidth
{
int LoRaValue;
double Bandwidth;
char *ConfigString;
} Bandwidths[] =
{
{BANDWIDTH_7K8, 7.8, "7K8"},
{BANDWIDTH_10K4, 10.4, "10K4"},
{BANDWIDTH_15K6, 15.6, "15K6"},
{BANDWIDTH_20K8, 20.8, "20K8"},
{BANDWIDTH_31K25, 31.25, "31K25"},
{BANDWIDTH_41K7, 41.7, "41K7"},
{BANDWIDTH_62K5, 62.5, "62K5"},
{BANDWIDTH_125K, 125.0, "125K"},
{BANDWIDTH_250K, 250.0, "250K"},
{BANDWIDTH_500K, 500.0, "500K"}
};
int LEDCounts[2];
int help_win_displayed = 0;
pthread_mutex_t var = PTHREAD_MUTEX_INITIALIZER;
#pragma pack(1)
struct TBinaryPacket {
uint8_t PayloadIDs;
uint16_t Counter;
uint16_t BiSeconds;
float Latitude;
float Longitude;
uint16_t Altitude;
};
// Create pipes for inter proces communication
// GLOBAL AS CALLED FROM INTERRRUPT
int telem_pipe_fd[2];
int ssdv_pipe_fd[2];
// Create a structure to share some variables with the habitat child process
// GLOBAL AS CALLED FROM INTERRRUPT
thread_shared_vars_t htsv;
// Create a structure to share some variables with the ssdv child process
// GLOBAL AS CALLED FROM INTERRRUPT
thread_shared_vars_t stsv;
int habitate_telem_packets = 0;
WINDOW *mainwin=NULL; // Curses window
void CloseDisplay( WINDOW * mainwin )
{
/* Clean up after ourselves */
delwin( mainwin );
endwin( );
refresh( );
}
void bye(void)
{
if (mainwin != NULL)
{
CloseDisplay( mainwin);
mainwin = NULL;
}
}
void exit_error(char *msg)
{
bye(); // Close ncurses window, plus any future tidy-ups
fprintf(stderr, msg);
exit(1);
}
void
hexdump_buffer( const char *title, const char *buffer, const int len_buffer )
{
int i, j = 0;
char message[200];
FILE *fp;
fp = fopen( "pkt.txt", "a" );
fprintf( fp, "Title = %s\n", title );
for ( i = 0; i < len_buffer; i++ )
{
sprintf( &message[3 * j], "%02x ", buffer[i] );
j++;
if ( i % 16 == 15 )
{
j = 0;
fprintf( fp, "%s\n", message );
message[0] = '\0';
}
}
fprintf( fp, "%s\n", message );
fclose( fp );
}
void
writeRegister( int Channel, uint8_t reg, uint8_t val )
{
unsigned char data[2];
data[0] = reg | 0x80;
data[1] = val;
wiringPiSPIDataRW( Channel, data, 2 );
}
uint8_t
readRegister( int Channel, uint8_t reg )
{
unsigned char data[2];
uint8_t val;
data[0] = reg & 0x7F;
data[1] = 0;
wiringPiSPIDataRW( Channel, data, 2 );
val = data[1];
return val;
}
void LogPacket( int Channel, int8_t SNR, int RSSI, double FreqError, int Bytes, unsigned char MessageType )
{
if ( Config.EnablePacketLogging )
{
FILE *fp;
if ( ( fp = fopen( "packets.txt", "at" ) ) != NULL )
{
time_t now;
struct tm *tm;
now = time( 0 );
tm = localtime( &now );
fprintf( fp,
"%02d:%02d:%02d - Ch %d, SNR %d, RSSI %d, FreqErr %.1lf, Bytes %d, Type %02Xh\n",
tm->tm_hour, tm->tm_min, tm->tm_sec, Channel, SNR, RSSI,
FreqError, Bytes, MessageType );
fclose( fp );
}
}
}
void LogTelemetryPacket(char *Telemetry)
{
// if (Config.EnableTelemetryLogging)
{
FILE *fp;
if ( ( fp = fopen( "telemetry.txt", "at" ) ) != NULL )
{
time_t now;
struct tm *tm;
now = time( 0 );
tm = localtime( &now );
fprintf( fp, "%02d:%02d:%02d - %s\n", tm->tm_hour, tm->tm_min,
tm->tm_sec, Telemetry );
fclose( fp );
}
}
}
void LogMessage( const char *format, ... )
{
static WINDOW *Window = NULL;
char Buffer[512];
pthread_mutex_lock( &var ); // lock the critical section
if ( Window == NULL )
{
// Window = newwin(25, 30, 0, 50);
Window = newwin( LINES - 16, COLS, 16, 0 );
scrollok( Window, TRUE );
}
va_list args;
va_start( args, format );
vsprintf( Buffer, format, args );
va_end( args );
if ( strlen( Buffer ) > COLS - 1 )
{
Buffer[COLS - 3] = '.';
Buffer[COLS - 2] = '.';
Buffer[COLS - 1] = '\n';
Buffer[COLS] = 0;
}
waddstr( Window, Buffer );
wrefresh( Window );
pthread_mutex_unlock( &var ); // unlock once you are done
}
void ChannelPrintf(int Channel, int row, int column, const char *format, ... )
{
char Buffer[80];
va_list args;
pthread_mutex_lock( &var ); // lock the critical section
va_start( args, format );
vsprintf( Buffer, format, args );
va_end( args );
mvwaddstr( Config.LoRaDevices[Channel].Window, row, column, Buffer );
if (! help_win_displayed)
{
wrefresh( Config.LoRaDevices[Channel].Window );
}
pthread_mutex_unlock( &var ); // unlock once you are done
}
void
setMode( int Channel, uint8_t newMode )
{
if ( newMode == currentMode )
return;
switch ( newMode )
{
case RF98_MODE_TX:
writeRegister( Channel, REG_LNA, LNA_OFF_GAIN ); // TURN LNA OFF FOR TRANSMITT
writeRegister( Channel, REG_PA_CONFIG, Config.LoRaDevices[Channel].Power ); // PA_MAX_UK
writeRegister( Channel, REG_OPMODE, newMode );
currentMode = newMode;
break;
case RF98_MODE_RX_CONTINUOUS:
writeRegister( Channel, REG_PA_CONFIG, PA_OFF_BOOST ); // TURN PA OFF FOR RECIEVE??
writeRegister( Channel, REG_LNA, LNA_MAX_GAIN ); // MAX GAIN FOR RECEIVE
writeRegister( Channel, REG_OPMODE, newMode );
currentMode = newMode;
// LogMessage("Changing to Receive Continuous Mode\n");
break;
case RF98_MODE_SLEEP:
writeRegister( Channel, REG_OPMODE, newMode );
currentMode = newMode;
// LogMessage("Changing to Sleep Mode\n");
break;
case RF98_MODE_STANDBY:
writeRegister( Channel, REG_OPMODE, newMode );
currentMode = newMode;
// LogMessage("Changing to Standby Mode\n");
break;
default:
return;
}
if ( newMode != RF98_MODE_SLEEP )
{
while ( digitalRead( Config.LoRaDevices[Channel].DIO5 ) == 0 )
{
}
// delay(1);
}
// LogMessage("Mode Change Done\n");
return;
}
void setFrequency( int Channel, double Frequency )
{
unsigned long FrequencyValue;
char FrequencyString[10];
// Format frequency as xxx.xxx.x Mhz
sprintf( FrequencyString, "%8.4lf ", Frequency );
FrequencyString[8] = FrequencyString[7];
FrequencyString[7] = '.';
FrequencyValue = ( unsigned long ) ( Frequency * 7110656 / 434 );
writeRegister( Channel, 0x06, ( FrequencyValue >> 16 ) & 0xFF ); // Set frequency
writeRegister( Channel, 0x07, ( FrequencyValue >> 8 ) & 0xFF );
writeRegister( Channel, 0x08, FrequencyValue & 0xFF );
Config.LoRaDevices[Channel].activeFreq = Frequency;
// LogMessage("Set Frequency to %lf\n", Frequency);
ChannelPrintf( Channel, 1, 1, "Channel %d %s MHz ", Channel, FrequencyString );
}
void displayFrequency ( int Channel, double Frequency )
{
char FrequencyString[10];
// Format frequency as xxx.xxx.x Mhz
sprintf( FrequencyString, "%8.4lf ", Frequency );
FrequencyString[8] = FrequencyString[7];
FrequencyString[7] = '.';
ChannelPrintf( Channel, 1, 1, "Channel %d %s MHz ", Channel, FrequencyString );
}
void setLoRaMode( int Channel )
{
// LogMessage("Setting LoRa Mode\n");
setMode( Channel, RF98_MODE_SLEEP );
writeRegister( Channel, REG_OPMODE, 0x80 );
setMode( Channel, RF98_MODE_SLEEP );
// LogMessage("Set Default Frequency\n");
setFrequency( Channel, Config.LoRaDevices[Channel].Frequency);
}
int IntToSF(int Value)
{
return Value << 4;
}
int SFToInt(int SpreadingFactor)
{
return SpreadingFactor >> 4;
}
int IntToEC(int Value)
{
return (Value - 4) << 1;
}
int ECToInt(int ErrorCoding)
{
return (ErrorCoding >> 1) + 4;
}
int DoubleToBandwidth(double Bandwidth)
{
int i;
for (i=0; i<10; i++)
{
if (abs(Bandwidth - Bandwidths[i].Bandwidth) < (Bandwidths[i].Bandwidth/10))
{
return Bandwidths[i].LoRaValue;
}
}
return BANDWIDTH_20K8;
}
double BandwidthToDouble(int LoRaValue)
{
int i;
for (i=0; i<10; i++)
{
if (LoRaValue == Bandwidths[i].LoRaValue)
{
return Bandwidths[i].Bandwidth;
}
}
return 20.8;
}
int IntToLowOpt(int Value)
{
return Value ? 0x08 : 0;
}
int LowOptToInt(int LowOpt)
{
return LowOpt ? 1 : 0;
}
void SetLoRaParameters( int Channel, int ImplicitOrExplicit, int ErrorCoding, double Bandwidth, int SpreadingFactor, int LowDataRateOptimize )
{
writeRegister( Channel, REG_MODEM_CONFIG, ImplicitOrExplicit | IntToEC(ErrorCoding) | DoubleToBandwidth(Bandwidth));
writeRegister( Channel, REG_MODEM_CONFIG2, IntToSF(SpreadingFactor) | CRC_ON );
writeRegister( Channel, REG_MODEM_CONFIG3, 0x04 | IntToLowOpt(LowDataRateOptimize)); // 0x04: AGC sets LNA gain
writeRegister( Channel, REG_DETECT_OPT, ( readRegister( Channel, REG_DETECT_OPT ) & 0xF8 ) | ( ( SpreadingFactor == 6 ) ? 0x05 : 0x03 ) ); // 0x05 For SF6; 0x03 otherwise
writeRegister( Channel, REG_DETECTION_THRESHOLD, ( SpreadingFactor == 6 ) ? 0x0C : 0x0A ); // 0x0C for SF6, 0x0A otherwise
Config.LoRaDevices[Channel].CurrentBandwidth = Bandwidth; // Used for AFC - current bandwidth may be different to that configured (i.e. because we're using calling mode)
ChannelPrintf( Channel, 2, 1, "%s, %.2lf, SF%d, EC4:%d %s",
ImplicitOrExplicit ? "Implicit" : "Explicit",
Bandwidth,
SpreadingFactor,
ErrorCoding,
LowDataRateOptimize ? "LDRO" : "" );
}
void displayLoRaParameters( int Channel, int ImplicitOrExplicit, int ErrorCoding, double Bandwidth, int SpreadingFactor, int LowDataRateOptimize )
{
ChannelPrintf( Channel, 2, 1, "%s, %.2lf, SF%d, EC4:%d %s",
ImplicitOrExplicit ? "Implicit" : "Explicit",
Bandwidth,
SpreadingFactor,
ErrorCoding,
LowDataRateOptimize ? "LDRO" : "" );
}
void SetDefaultLoRaParameters( int Channel )
{
// LogMessage("Set Default Parameters\n");
SetLoRaParameters( Channel,
Config.LoRaDevices[Channel].ImplicitOrExplicit,
Config.LoRaDevices[Channel].ErrorCoding,
Config.LoRaDevices[Channel].Bandwidth,
Config.LoRaDevices[Channel].SpreadingFactor,
Config.LoRaDevices[Channel].LowDataRateOptimize );
}
/////////////////////////////////////
// Method: Setup to receive continuously
//////////////////////////////////////
void
startReceiving( int Channel )
{
writeRegister( Channel, REG_DIO_MAPPING_1, 0x00 ); // 00 00 00 00 maps DIO0 to RxDone
writeRegister( Channel, REG_PAYLOAD_LENGTH, 255 );
writeRegister( Channel, REG_RX_NB_BYTES, 255 );
writeRegister( Channel, REG_FIFO_RX_BASE_AD, 0 );
writeRegister( Channel, REG_FIFO_ADDR_PTR, 0 );
// Setup Receive Continous Mode
setMode( Channel, RF98_MODE_RX_CONTINUOUS );
}
void ReTune( int Channel, double FreqShift )
{
setMode( Channel, RF98_MODE_SLEEP );
LogMessage( "Retune by %.1lfkHz\n", FreqShift * 1000 );
setFrequency( Channel, Config.LoRaDevices[Channel].activeFreq + FreqShift );
startReceiving( Channel );
}
void SendLoRaData(int Channel, char *buffer, int Length)
{
unsigned char data[257];
int i;
// Change frequency for the uplink ?
if (Config.LoRaDevices[Channel].UplinkFrequency > 0)
{
LogMessage("Change frequency to %.3lfMHz\n", Config.LoRaDevices[Channel].UplinkFrequency);
setFrequency(Channel, Config.LoRaDevices[Channel].UplinkFrequency);
}
// Change mode for the uplink ?
if (Config.LoRaDevices[Channel].UplinkMode >= 0)
{
int UplinkMode;
UplinkMode = Config.LoRaDevices[Channel].UplinkMode;
LogMessage("Change LoRa mode to %d\n", Config.LoRaDevices[Channel].UplinkMode);
SetLoRaParameters(Channel,
LoRaModes[UplinkMode].ImplicitOrExplicit,
ECToInt(LoRaModes[UplinkMode].ErrorCoding),
BandwidthToDouble(LoRaModes[UplinkMode].Bandwidth),
SFToInt(LoRaModes[UplinkMode].SpreadingFactor),
0);
}
LogMessage( "LoRa Channel %d Sending %d bytes\n", Channel, Length );
Config.LoRaDevices[Channel].Sending = 1;
setMode( Channel, RF98_MODE_STANDBY );
writeRegister( Channel, REG_DIO_MAPPING_1, 0x40 ); // 01 00 00 00 maps DIO0 to TxDone
writeRegister( Channel, REG_FIFO_TX_BASE_AD, 0x00 ); // Update the address ptr to the current tx base address
writeRegister( Channel, REG_FIFO_ADDR_PTR, 0x00 );
data[0] = REG_FIFO | 0x80;
for ( i = 0; i < Length; i++ )
{
data[i + 1] = buffer[i];
}
wiringPiSPIDataRW( Channel, data, Length + 1 );
// Set the length. For implicit mode, since the length needs to match what the receiver expects, we have to set a value which is 255 for an SSDV packet
writeRegister( Channel, REG_PAYLOAD_LENGTH, Length );
// go into transmit mode
setMode( Channel, RF98_MODE_TX );
}
void ShowPacketCounts(int Channel)
{
if (Config.LoRaDevices[Channel].InUse)
{
ChannelPrintf( Channel, 7, 1, "Telem Packets = %d (%us) ",
Config.LoRaDevices[Channel].TelemetryCount,
Config.LoRaDevices[Channel].LastTelemetryPacketAt ? (unsigned int) (time(NULL) - Config.LoRaDevices[Channel].LastTelemetryPacketAt) : 0);
ChannelPrintf( Channel, 8, 1, "Image Packets = %d (%us) ",
Config.LoRaDevices[Channel].SSDVCount,
Config.LoRaDevices[Channel].
LastSSDVPacketAt ? ( unsigned int ) ( time( NULL ) -
Config.
LoRaDevices
[Channel].
LastSSDVPacketAt )
: 0 );
ChannelPrintf( Channel, 9, 1, "Bad CRC = %d Bad Type = %d",
Config.LoRaDevices[Channel].BadCRCCount,
Config.LoRaDevices[Channel].UnknownCount );
}
}
void ProcessUploadMessage(int Channel, char *Message)
{
// LogMessage("Ch %d: Uploaded message %s\n", Channel, Message);
}
void ProcessCallingMessage(int Channel, char *Message)
{
char Payload[16];
double Frequency;
int ImplicitOrExplicit, ErrorCoding, Bandwidth, SpreadingFactor, LowDataRateOptimize;
ChannelPrintf( Channel, 3, 1, "Calling message %d bytes ",
strlen( Message ) );
if ( sscanf( Message + 2, "%15[^,],%lf,%d,%d,%d,%d,%d",
Payload,
&Frequency,
&ImplicitOrExplicit,
&ErrorCoding,
&Bandwidth, &SpreadingFactor, &LowDataRateOptimize ) == 7 )
{
if (Config.LoRaDevices[Channel].AFC)
{
Frequency += (Config.LoRaDevices[Channel].activeFreq - Config.LoRaDevices[Channel].Frequency);
}
LogMessage( "Ch %d: Calling message, new frequency %7.3lf\n", Channel,
Frequency );
// Decoded OK
setMode( Channel, RF98_MODE_SLEEP );
// setFrequency(Channel, Config.LoRaDevices[Channel].activeFreq + );
setFrequency( Channel, Frequency );
SetLoRaParameters( Channel, ImplicitOrExplicit, ECToInt(ErrorCoding), BandwidthToDouble(Bandwidth), SFToInt(SpreadingFactor), LowOptToInt(LowDataRateOptimize));
setMode( Channel, RF98_MODE_RX_CONTINUOUS );
Config.LoRaDevices[Channel].InCallingMode = 1;
// ChannelPrintf(Channel, 1, 1, "Channel %d %7.3lfMHz ", Channel, Frequency);
}
}
size_t write_data( void *buffer, size_t size, size_t nmemb, void *userp )
{
return size * nmemb;
}
void UploadListenerTelemetry( char *callsign, float gps_lat, float gps_lon, char *antenna )
{
int time_epoch = ( int ) time( NULL );
if ( Config.EnableHabitat )
{
CURL *curl;
CURLcode res;
char PostFields[300];
char JsonData[200];
/* In windows, this will init the winsock stuff */
/* get a curl handle */
curl = curl_easy_init( );
if ( curl )
{
// So that the response to the curl POST doesn;'t mess up my finely crafted display!
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_data );
// Set the URL that is about to receive our POST
curl_easy_setopt( curl, CURLOPT_URL,
"http://habitat.habhub.org/transition/listener_telemetry" );
// Now specify the POST data
sprintf( JsonData, "{\"latitude\": %f, \"longitude\": %f}",
gps_lat, gps_lon );
sprintf( PostFields, "callsign=%s&time=%d&data=%s", callsign,
time_epoch, JsonData );
curl_easy_setopt( curl, CURLOPT_POSTFIELDS, PostFields );
// Perform the request, res will get the return code
res = curl_easy_perform( curl );
// Check for errors
if ( res == CURLE_OK )
{
LogMessage( "Uploaded listener %s position %f,%f\n",
Config.Tracker, Config.latitude,
Config.longitude );
}
else
{
LogMessage( "curl_easy_perform() failed: %s\n",
curl_easy_strerror( res ) );
}
// always cleanup
curl_easy_cleanup( curl );
}
/* In windows, this will init the winsock stuff */
/* get a curl handle */
curl = curl_easy_init( );
if ( curl )
{
// So that the response to the curl POST doesn;'t mess up my finely crafted display!
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_data );
// Set the URL that is about to receive our POST
curl_easy_setopt( curl, CURLOPT_URL,
"http://habitat.habhub.org/transition/listener_information" );
// Now specify the POST data
sprintf( JsonData, "{\"radio\": \"%s\", \"antenna\": \"%s\"}",
"LoRa RFM98W", antenna );
sprintf( PostFields, "callsign=%s&time=%d&data=%s", Config.Tracker, time_epoch, JsonData );
curl_easy_setopt( curl, CURLOPT_POSTFIELDS, PostFields );
// Perform the request, res will get the return code
res = curl_easy_perform( curl );
// Check for errors
if ( res != CURLE_OK )
{
LogMessage( "curl_easy_perform() failed: %s\n",
curl_easy_strerror( res ) );
}
// always cleanup
curl_easy_cleanup( curl );
}
}
}
void RemoveOldPayloads(void)
{
int i;
for (i=0; i<MAX_PAYLOADS; i++)
{
if (Config.Payloads[i].InUse)
{
if ((time(NULL) - Config.Payloads[i].LastPacketAt) > 10800)
{
// More than 3 hours old, so remove it
}
Config.Payloads[i].InUse = 0;
}
}
}
int FindFreePayload(char *Payload)
{
int i, Oldest;
// First pass - find match for payload
for (i=0; i<MAX_PAYLOADS; i++)
{
if (Config.Payloads[i].InUse)
{
if (strcmp(Payload, Config.Payloads[i].Payload) == 0)
{
return i;
}
}
}
// Second pass - just find a free position
for (i=0; i<MAX_PAYLOADS; i++)
{
if (!Config.Payloads[i].InUse)
{
Config.Payloads[i].InUse = 1;
strcpy(Config.Payloads[i].Payload, Payload);
return i;
}
}
// Third pass - find oldest payload
Oldest = 0;
for (i=1; i<MAX_PAYLOADS; i++)
{
if (Config.Payloads[i].LastPositionAt < Config.Payloads[Oldest].LastPositionAt)
{
Oldest = i;
}
}
strcpy(Config.Payloads[Oldest].Payload, Payload);
return i;
}
void DoPositionCalcs(int PayloadIndex)
{
unsigned long Now;
struct tm tm;
float Climb, Period;
strptime(Config.Payloads[PayloadIndex].Time, "%H:%M:%S", &tm);
Now = tm.tm_hour * 3600 + tm.tm_min * 60 + tm.tm_sec;
if ((Config.Payloads[PayloadIndex].LastPositionAt > 0 )
&& ( Now > Config.Payloads[PayloadIndex].LastPositionAt ) )
{
Climb = (float)Config.Payloads[PayloadIndex].Altitude - (float)Config.Payloads[PayloadIndex].PreviousAltitude;
Period = (float)Now - (float)Config.Payloads[PayloadIndex].LastPositionAt;
Config.Payloads[PayloadIndex].AscentRate = Climb / Period;
}
else
{
Config.Payloads[PayloadIndex].AscentRate = 0;
}
Config.Payloads[PayloadIndex].LastPositionAt = Now;
Config.Payloads[PayloadIndex].PreviousAltitude = Config.Payloads[PayloadIndex].Altitude;
}
void ProcessLine(int Channel, char *Line)
{
int PayloadIndex;
char Payload[32];
// Find free position for this payload
sscanf(Line + 2, "%31[^,]", Payload);
PayloadIndex = FindFreePayload(Payload);
// Store sentence against this payload
strcpy(Config.Payloads[PayloadIndex].Telemetry, Line);
// Fill in source channel
Config.Payloads[PayloadIndex].Channel = Channel;
// Parse key fields from sentence
sscanf( Line + 2, "%15[^,],%u,%8[^,],%lf,%lf,%u",
(Config.Payloads[PayloadIndex].Payload),
&(Config.Payloads[PayloadIndex].Counter),
(Config.Payloads[PayloadIndex].Time),
&(Config.Payloads[PayloadIndex].Latitude),
&(Config.Payloads[PayloadIndex].Longitude),
&(Config.Payloads[PayloadIndex].Altitude));
// Mark when this was received, so we can time-out old payloads
Config.Payloads[PayloadIndex].LastPacketAt = time(NULL);
// Ascent rate
DoPositionCalcs(PayloadIndex);
// Update display
ChannelPrintf(Channel, 4, 1, "%8.5lf, %8.5lf, %05u ",
Config.Payloads[PayloadIndex].Latitude,
Config.Payloads[PayloadIndex].Longitude,
Config.Payloads[PayloadIndex].Altitude);
}
void ProcessTelemetryMessage(int Channel, char *Message)
{
if (strlen(Message + 1) < 250)
{
char *startmessage, *endmessage;
char telem[40];
char buffer[40];
sprintf(telem, "Telemetry %d bytes", strlen( Message + 1 ));
// Pad the string with spaces to the size of the window
sprintf(buffer,"%-37s", telem );
ChannelPrintf( Channel, 3, 1, buffer);
startmessage = Message + strspn(Message, "$%") - 2;
endmessage = strchr( startmessage, '\n' );
if (endmessage == NULL) endmessage = strchr(startmessage, 0);
while ( endmessage != NULL )
{
int Repeated;
habitate_telem_packets++;
time_t now;
struct tm *tm;
*endmessage = '\0';
LogTelemetryPacket(startmessage);
if ((Repeated = (*startmessage == '%')))
{
*startmessage = '$';
}
strcpy( Config.LoRaDevices[Channel].Telemetry, startmessage );
ProcessLine(Channel, startmessage);
now = time( 0 );
tm = localtime( &now );
if ( Config.EnableHabitat )
{
// Create a telemetry packet
telemetry_t t;
t.Channel = Channel;
t.Packet_Number = habitate_telem_packets;
memcpy( t.Telemetry, startmessage, strlen( startmessage ) + 1 );
// Add the telemetry packet to the pipe
int result = write( telem_pipe_fd[1], &t, sizeof( t ) );
if ( result == -1 )
{
exit_error("Error writing to the telemetry pipe\n");
}
if ( result == 0 )