-
Notifications
You must be signed in to change notification settings - Fork 183
/
s2e.c
1504 lines (1408 loc) · 53 KB
/
s2e.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
/*
* --- Revised 3-Clause BSD License ---
* Copyright (C) 2016-2019, SEMTECH (International) AG.
* 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.
* * Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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 SEMTECH 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 <stdio.h>
#include "s2conf.h"
#include "uj.h"
#include "ral.h"
#include "s2e.h"
#include "kwcrc.h"
#include "timesync.h"
u1_t s2e_dcDisabled; // no duty cycle limits - override for test/dev
u1_t s2e_ccaDisabled; // no LBT etc - ditto
u1_t s2e_dwellDisabled; // no dwell time limits - ditto
extern inline int rps_sf (rps_t params);
extern inline int rps_bw (rps_t params);
extern inline rps_t rps_make (int sf, int bw);
// Fwd decl.
static void s2e_txtimeout (tmr_t* tmr);
static void setDC (s2ctx_t* s2ctx, ustime_t t) {
for( u1_t u=0; u<MAX_TXUNITS; u++ ) {
for( u1_t i=0; i<DC_NUM_BANDS; i++ )
s2ctx->txunits[u].dc_eu863bands[i] = t;
for( u1_t i=0; i<MAX_DNCHNLS; i++ )
s2ctx->txunits[u].dc_perChnl[i] = t;
}
}
static void resetDC (s2ctx_t* s2ctx, u2_t dc_chnlRate) {
setDC(s2ctx, rt_getTime());
s2ctx->dc_chnlRate = dc_chnlRate;
}
static int s2e_canTxOK (s2ctx_t* s2ctx, txjob_t* txjob, int* ccaDisabled) {
return 1;
}
void s2e_ini (s2ctx_t* s2ctx) {
if( s2e_joineuiFilter == NULL )
s2e_joineuiFilter = rt_mallocN(uL_t, 2*MAX_JOINEUI_RANGES+2); // need min one trailing 0 entry
memset(s2ctx, 0, sizeof(*s2ctx));
txq_ini(&s2ctx->txq);
rxq_ini(&s2ctx->rxq);
s2ctx->canTx = s2e_canTxOK;
for( u1_t i=0; i<DR_CNT; i++ )
s2ctx->dr_defs[i] = RPS_ILLEGAL;
setDC(s2ctx, USTIME_MIN); // disable until we have a region that needs it
for( int u=0; u < MAX_TXUNITS; u++ ) {
rt_iniTimer(&s2ctx->txunits[u].timer, s2e_txtimeout);
s2ctx->txunits[u].timer.ctx = s2ctx;
s2ctx->txunits[u].head = TXIDX_END;
}
}
void s2e_free (s2ctx_t* s2ctx) {
for( int u=0; u < MAX_TXUNITS; u++ )
rt_clrTimer(&s2ctx->txunits[u].timer);
memset(s2ctx, 0, sizeof(*s2ctx));
ts_iniTimesync();
ral_stop();
}
// --------------------------------------------------------------------------------
//
// RX PART
//
// --------------------------------------------------------------------------------
//
// Check if we can fill the RXQ by retrieving frames from the radio layer.
// Then try to send as many as possible.
//
rxjob_t* s2e_nextRxjob (s2ctx_t* s2ctx) {
return rxq_nextJob(&s2ctx->rxq);
}
void s2e_addRxjob (s2ctx_t* s2ctx, rxjob_t* rxjob) {
// Add newly received frame to rxq
// Check for mirror frame (reflection on a neighboring frequency)
for( rxjob_t* p = &s2ctx->rxq.rxjobs[s2ctx->rxq.first]; p < rxjob; p++ ) {
if( p->dr == rxjob->dr &&
p->len == rxjob->len &&
memcmp(&s2ctx->rxq.rxdata[p->off], &s2ctx->rxq.rxdata[rxjob->off], rxjob->len) == 0 ) {
// Duplicate detected - drop the mirror
if( (8*rxjob->snr - rxjob->rssi) > (8*p->snr - p->rssi) ) {
// Drop previous frame p
LOG(MOD_S2E|DEBUG, "Dropped mirror frame freq=%F snr=%5.1f rssi=%d (vs. freq=%F snr=%5.1f rssi=%d) - DR%d mic=%d (%d byes)",
p->freq, p->snr/8.0, -p->rssi, rxjob->freq, rxjob->snr/8.0, -rxjob->rssi,
p->dr, (s4_t)rt_rlsbf4(&s2ctx->rxq.rxdata[p->off]+rxjob->len-4), p->len);
rxq_commitJob(&s2ctx->rxq, rxjob);
rxjob = rxq_dropJob(&s2ctx->rxq, p);
} else {
// else: Drop newly retrieved frame - aka don't commit it
LOG(MOD_S2E|DEBUG, "Dropped mirror frame freq=%F snr=%5.1f rssi=%d (vs. freq=%F snr=%5.1f rssi=%d) - DR%d mic=%d (%d byes)",
rxjob-> freq, rxjob->snr/8.0, -rxjob->rssi, p->freq, p->snr/8.0, -p->rssi,
rxjob->dr, (s4_t)rt_rlsbf4(&s2ctx->rxq.rxdata[rxjob->off]+rxjob->len-4), rxjob->len);
}
return;
}
}
// No mirror frame found
rxq_commitJob(&s2ctx->rxq, rxjob);
}
void s2e_flushRxjobs (s2ctx_t* s2ctx) {
while( s2ctx->rxq.first < s2ctx->rxq.next ) {
// Get a send buffer - parse frame / check filter
ujbuf_t sendbuf = (*s2ctx->getSendbuf)(s2ctx, MIN_UPJSON_SIZE);
if( sendbuf.buf == NULL ) {
// Websocket has no space - WS will call again
return;
}
rxjob_t* j = &s2ctx->rxq.rxjobs[s2ctx->rxq.first++];
dbuf_t lbuf = { .buf = NULL };
if( log_special(MOD_S2E|VERBOSE, &lbuf) )
xprintf(&lbuf, "RX %F DR%d %R snr=%.1f rssi=%d xtime=0x%lX - ",
j->freq, j->dr, s2e_dr2rps(s2ctx, j->dr), j->snr/8.0, -j->rssi, j->xtime);
uj_encOpen(&sendbuf, '{');
if( !s2e_parse_lora_frame(&sendbuf, &s2ctx->rxq.rxdata[j->off], j->len, lbuf.buf ? &lbuf : NULL) ) {
// Frame failed sanity checks or stopped by filters
sendbuf.pos = 0;
continue;
}
if( lbuf.buf )
log_specialFlush(lbuf.pos);
double reftime = 0.0;
if( s2ctx->muxtime ) {
reftime = s2ctx->muxtime +
ts_normalizeTimespanMCU(rt_getTime()-s2ctx->reftime) / 1e6;
}
uj_encKVn(&sendbuf,
"RefTime", 'T', reftime,
"DR", 'i', j->dr,
"Freq", 'i', j->freq,
"upinfo", '{',
/**/ "rctx", 'I', j->rctx,
/**/ "xtime", 'I', j->xtime,
/**/ "gpstime", 'I', ts_xtime2gpstime(j->xtime),
/**/ "rssi", 'i', -(s4_t)j->rssi,
/**/ "snr", 'g', j->snr/8.0,
/**/ "rxtime", 'T', rt_getUTC()/1e6,
"}",
NULL);
uj_encClose(&sendbuf, '}');
if( !xeos(&sendbuf) ) {
LOG(MOD_S2E|ERROR, "JSON encoding exceeds available buffer space: %d", sendbuf.bufsize);
} else {
(*s2ctx->sendText)(s2ctx, &sendbuf);
assert(sendbuf.buf==NULL);
}
}
}
// --------------------------------------------------------------------------------
//
// TX PART
//
// --------------------------------------------------------------------------------
static const u2_t DC_EU863BAND_RATE[] = {
[DC_DECI ]= 10,
[DC_CENTI]= 100,
[DC_MILLI]= 1000,
};
static ustime_t _calcAirTime (rps_t rps, u1_t plen, u1_t nocrc) {
if( rps == RPS_ILLEGAL )
return 0;
// The impl has been taken from lmic.c and adapted
u1_t bw = rps_bw(rps); // 0,1,2 = 125,250,500kHz
u1_t sf = rps_sf(rps); // 0=FSK, 1..6 = SF7..12
if( sf == FSK ) {
return (plen+/*preamble*/5+/*syncword*/3+/*len*/1+/*crc*/2) * /*bits/byte*/8
* rt_seconds(1) / /*kbit/s*/50000;
}
sf = 7 + (sf - SF7)*(SF8-SF7); // map enums SF7..SF12 to 7..12
u1_t sfx = 4*sf;
u1_t q = sfx - (sf >= 11 && bw == 0 ? 8 : 0);
u1_t ih = 0; // station never sends with implicit header
u1_t cr = 0; // CR_4_5=0, CR_4_6, CR_4_7, CR_4_8
int tmp = 8*plen - sfx + 28 + (nocrc?0:16) - (ih?20:0);
if( tmp > 0 ) {
tmp = (tmp + q - 1) / q;
tmp *= cr+5;
tmp += 8;
} else {
tmp = 8;
}
tmp = (tmp<<2) + /*preamble*/49 /* 4 * (8 + 4.25) */;
// bw = 125000 = 15625 * 2^3
// 250000 = 15625 * 2^4
// 500000 = 15625 * 2^5
// sf = 7..12
//
// osticks = tmp * OSTICKS_PER_SEC * 1<<sf / bw
//
// 3 => counter reduced divisor 125000/8 => 15625
// 2 => counter 2 shift on tmp
sfx = sf - (3+2) - bw;
int div = 15625;
if( sfx > 4 ) {
// prevent 32bit signed int overflow in last step
div >>= sfx-4;
sfx = 4;
}
return (((ustime_t)tmp << sfx) * rt_seconds(1) + div/2) / div;
}
ustime_t s2e_calcDnAirTime (rps_t rps, u1_t plen) {
return _calcAirTime(rps, plen, 1);
}
ustime_t s2e_calcUpAirTime (rps_t rps, u1_t plen) {
return _calcAirTime(rps, plen, 0);
}
static void send_dntxed (s2ctx_t* s2ctx, txjob_t* txjob) {
if( txjob->deveui ) {
// Note: dnsched does not have deveui field set - don't report dntxed
ujbuf_t sendbuf = (*s2ctx->getSendbuf)(s2ctx, MIN_UPJSON_SIZE/2);
if( sendbuf.buf == NULL ) {
LOG(MOD_S2E|ERROR, "%J - failed to send dntxed, no buffer space", txjob);
return;
}
uj_encOpen(&sendbuf, '{');
uj_encKVn(&sendbuf,
"msgtype", 's', "dntxed",
"seqno", 'I', txjob->diid, // for older servers (remove if obsoleted)
"diid", 'I', txjob->diid, // newer servers
"DevEui", 'E', txjob->deveui,
"rctx", 'i', txjob->txunit, // antenna that sent this frame
"xtime", 'I', txjob->xtime,
"txtime", 'T', txjob->txtime/1e6,
"gpstime", 'I', txjob->gpstime,
NULL);
uj_encClose(&sendbuf, '}');
(*s2ctx->sendText)(s2ctx, &sendbuf);
}
LOG(MOD_S2E|INFO, "TX %J - dntxed: %F %.1fdBm ant#%d(%d) DR%d %R frame=%12.4H",
txjob, txjob->freq, (double)txjob->txpow/TXPOW_SCALE,
txjob->txunit, ral_rctx2txunit(txjob->rctx), // sending/receiving antenna
txjob->dr, s2e_dr2rps(s2ctx, txjob->dr),
txjob->len, &s2ctx->txq.txdata[txjob->off]);
}
ustime_t s2e_updateMuxtime(s2ctx_t* s2ctx, double muxstime, ustime_t now) {
if( now == 0 )
now = rt_getTime();
s2ctx->muxtime = muxstime;
s2ctx->reftime = now;
return now;
}
rps_t s2e_dr2rps (s2ctx_t* s2ctx, u1_t dr) {
return dr < 16 ? s2ctx->dr_defs[dr] : RPS_ILLEGAL;
}
// This is called only for received frame (maps only to correct *up* DRs)
u1_t s2e_rps2dr (s2ctx_t* s2ctx, rps_t rps) {
for( u1_t dr=0; dr<DR_CNT; dr++ ) {
if( s2ctx->dr_defs[dr] == rps )
return dr;
}
return DR_ILLEGAL;
}
static void check_dnfreq (s2ctx_t* s2ctx, ujdec_t* ujd, u4_t* pfreq, u1_t* pchnl) {
sL_t freq = uj_int(ujd);
if( freq < s2ctx->min_freq || freq > s2ctx->max_freq )
uj_error(ujd, "Illegal frequency value: %ld - not in range %d..%d", freq, s2ctx->min_freq, s2ctx->max_freq);
*pfreq = freq;
// Find and assign a DN channel to this freq.
// This channel index is only used locally to tracking duty cycle
int ch;
for( ch=0; ch<MAX_DNCHNLS; ch++ ) {
if( s2ctx->dn_chnls[ch] == 0 )
break;
if( freq == s2ctx->dn_chnls[ch] ) {
*pchnl = ch;
return;
}
}
// New DN frequency detected
if( ch == MAX_DNCHNLS ) {
// Never occupy last slot - facilitates graceful operation under overflow
// Airtime of all excess channels is booked into this last slot
LOG(MOD_S2E|WARNING, "Out of space for DN channel frequencies");
} else {
s2ctx->dn_chnls[ch] = freq;
}
*pchnl = ch;
}
static void check_dr (s2ctx_t* s2ctx, ujdec_t* ujd, u1_t* pdr) {
sL_t dr = uj_int(ujd);
if( dr < 0 || dr >= DR_CNT || s2ctx->dr_defs[dr] == RPS_ILLEGAL )
uj_error(ujd, "Illegal datarate value: %d for region %s", dr, s2ctx->region_s);
*pdr = dr;
}
static int freq2band (u4_t freq) {
if( freq >= 869400000 && freq <= 869650000 )
return DC_DECI;
if( (freq >= 868000000 && freq <= 868600000) || (freq >= 869700000 && freq <= 870000000) )
return DC_CENTI;
return DC_MILLI;
}
static void update_DC (s2ctx_t* s2ctx, txjob_t* txj) {
if( s2ctx->region == J_EU863 ) {
u1_t band = freq2band(txj->freq);
ustime_t* dcbands = s2ctx->txunits[txj->txunit].dc_eu863bands;
ustime_t t = dcbands[band];
// Update unless disabled or blocked
if( t != USTIME_MIN && t != USTIME_MAX ) {
dcbands[band] = t = txj->txtime + txj->airtime * DC_EU863BAND_RATE[band];
LOG(XDEBUG, "DC EU band %d blocked until %>.3T (txtime=%>.3T airtime=%~T)",
DC_EU863BAND_RATE[band], t, txj->txtime, (ustime_t)txj->airtime);
}
}
int dnchnl = txj->dnchnl;
ustime_t* dclist = s2ctx->txunits[txj->txunit].dc_perChnl;
ustime_t t = dclist[dnchnl];
// Update unless disabled or blocked
if( t != USTIME_MIN && t != USTIME_MAX ) {
dclist[dnchnl] = t = txj->txtime + txj->airtime * s2ctx->dc_chnlRate;
LOG(XDEBUG, "DC dnchnl %d blocked until %>.3T (txtime=%>.3T airtime=%~T)",
dnchnl, t, txj->txtime, (ustime_t)txj->airtime);
}
}
static s2_t calcTxpow (s2ctx_t* s2ctx, txjob_t* txjob) {
s2_t txpow = s2ctx->txpow; // default TX power
// Check upper bound first - will be false for all tx freq if 0 - no range
if( txjob->freq <= s2ctx->txpow2_freq[1] && txjob->freq >= s2ctx->txpow2_freq[0] ) {
txpow = s2ctx->txpow2;
}
// in case of more complicated regulation: switch( s2ctx->region ) { .. }
return txpow;
}
static void updateAirtimeTxpow (s2ctx_t* s2ctx, txjob_t* txjob) {
txjob->airtime = s2e_calcDnAirTime(s2e_dr2rps(s2ctx, txjob->dr), txjob->len);
txjob->txpow = calcTxpow(s2ctx, txjob);
}
static int calcPriority (txjob_t* txjob) {
int prio = txjob->prio;
if( txjob->rx2freq || ((txjob->txflags & TXFLAG_CLSC) && txjob->retries < CLASS_C_BACKOFF_MAX) )
prio -= PRIO_PENALTY_ALTTXTIME;
if( txjob->altAnts )
prio -= PRIO_PENALTY_ALTANTENNA;
return prio;
}
// Switch to alternative (later) TX time - if any available
// This also updates airtime/txpow if parameters change.
static int altTxTime (s2ctx_t* s2ctx, txjob_t* txjob, ustime_t earliest) {
if( (txjob->txflags & TXFLAG_CLSC) ) {
again:
if( txjob->rx2freq ) {
// Switch over from RX1 to RX2 - we can sent anytime, since we move forward
// something it's unlikely to conflict with RX1 spot.
txjob->txtime = earliest - CLASS_C_BACKOFF_BY; // earliest possible time
txjob->xtime = ts_ustime2xtime(txjob->txunit, txjob->txtime);
txjob->retries = 0;
txjob->freq = txjob->rx2freq;
txjob->dr = txjob->rx2dr;
txjob->dnchnl = txjob->dnchnl2;
txjob->rx2freq = 0; // invalidate RX2
updateAirtimeTxpow(s2ctx, txjob);
if( txjob->xtime == 0 ) {
LOG(MOD_S2E|VERBOSE, "%J - class C dropped - no time sync to SX1301 yet", txjob);
return 0;
}
}
if( txjob->retries > CLASS_C_BACKOFF_MAX ) {
LOG(MOD_S2E|VERBOSE, "%J - class C out of TX tries (%d in %~T)",
txjob, txjob->retries, txjob->retries*CLASS_C_BACKOFF_BY);
return 0; // no alternative TX
}
// Push TX time back by backoff and check again
// - we don't need high precision here because class C listens always
txjob->retries += 1;
txjob->xtime += CLASS_C_BACKOFF_BY;
txjob->txtime += CLASS_C_BACKOFF_BY;
if( txjob->txtime < earliest )
goto again;
return 1;
}
if( (txjob->txflags & TXFLAG_PING) ) {
// Class B ping slot - server currently supplies only one time slot
LOG(MOD_S2E|VERBOSE, "%J - class B ping has no alternate TX time", txjob);
return 0;
}
// Class A
if( txjob->rx2freq == 0 ) {
LOG(MOD_S2E|VERBOSE, "%J - class A has no more alternate TX time", txjob);
return 0; // no alternative TX
}
txjob->freq = txjob->rx2freq;
txjob->dr = txjob->rx2dr;
txjob->dnchnl = txjob->dnchnl2;
txjob->txtime += rt_seconds(1);
txjob->xtime += rt_seconds(1);
txjob->rx2freq = 0; // invalidate RX2
updateAirtimeTxpow(s2ctx, txjob);
if( txjob->txtime < earliest ) {
LOG(MOD_S2E|VERBOSE, "%J - too late for RX2 by %~T", txjob, earliest - txjob->txtime);
return 0;
}
LOG(MOD_S2E|VERBOSE, "%J - trying RX2 %F DR%d", txjob, txjob->freq, txjob->dr);
return 1;
}
static int s2e_canTxEU863 (s2ctx_t* s2ctx, txjob_t* txjob, int* ccaDisabled) {
ustime_t txtime = txjob->txtime;
ustime_t band_exp = s2ctx->txunits[txjob->txunit].dc_eu863bands[freq2band(txjob->freq)];
if( txtime >= band_exp ) {
return 1; // clear channel analysis not required
}
// No DC in band
LOG(MOD_S2E|VERBOSE, "%J %F - no DC in band: txtime=%>.3T free=%>.3T",
txjob, txjob->freq, rt_ustime2utc(txtime), rt_ustime2utc(band_exp));
return 0;
}
static int s2e_canTxPerChnlDC (s2ctx_t* s2ctx, txjob_t* txjob, int* ccaDisabled) {
ustime_t txtime = txjob->txtime;
ustime_t chfree = s2ctx->txunits[txjob->txunit].dc_perChnl[txjob->dnchnl];
if( txtime >= chfree )
return 2; // can send if channel clear
LOG(MOD_S2E|VERBOSE, "%J %F - no DC in channel: txtime=%>.3T until=%>.3T",
txjob, txjob->freq, rt_ustime2utc(txtime), rt_ustime2utc(chfree));
return 0;
ustime_t band_exp = s2ctx->txunits[txjob->txunit].dc_eu863bands[freq2band(txjob->freq)];
if( txtime >= band_exp )
return 1; // clear channel analysis not required
// No DC in band
LOG(MOD_S2E|VERBOSE, "%J %F - no DC in band: txtime=%>.3T free=%>.3T",
txjob, txjob->freq, rt_ustime2utc(txtime), rt_ustime2utc(band_exp));
return 0;
}
// Add a txjob to the TX queue and insert ordered by txtime.
// Only basic exclusion constraints are checked for newly arriving txjobs:
// Independent on antenna choice:
// - if too late, try alternative TX times, if out of alternatives drop it
// Per antenna, start with preferred antenna and then try alternative antennas:
// - definitely no duty cycle, thus the frame can't be sent for sure. If it could be sent under CCA enter it
// - collision with ongoing TX on current antenna (never stop a running TX)
// If not excluded enter based on txtime. If txtime is head of txunit queue reset processing timer
// to kick start s2e_nextTxAction
//
int s2e_addTxjob (s2ctx_t* s2ctx, txjob_t* txjob, int relocate, ustime_t now) {
ustime_t earliest = now + TX_AIM_GAP;
u1_t txunit;
if( !relocate ) {
// txjob is fresh entry from LNS and not one that got reschduled due to TX conflicts
ustime_t txtime = txjob->txtime; //
txunit = txjob->txunit = ral_rctx2txunit(txjob->rctx);
txjob->altAnts = ral_altAntennas(txunit);
updateAirtimeTxpow(s2ctx, txjob);
if( txtime < earliest && !altTxTime(s2ctx, txjob, earliest) )
return 0;
goto start;
}
check_alt: {
u1_t alts = txjob->altAnts;
if( alts==0 ) {
// No more alternative antennas - try later TX time
if( !altTxTime(s2ctx, txjob, earliest) ) {
LOG(MOD_S2E|WARNING, "%J - unable to place frame", txjob);
return 0;
}
// and reset antenna options
txunit = txjob->txunit = ral_rctx2txunit(txjob->rctx);
txjob->altAnts = ral_altAntennas(txunit);
} else {
// Try to find alternative antenna
txunit = 0;
while( (alts & (1<<txunit)) == 0 )
txunit += 1;
txjob->txunit = txunit;
txjob->altAnts &= ~(1<<txunit);
}
}
start: {
int ccaDisabled = 0;
if( !s2e_dcDisabled && !(*s2ctx->canTx)(s2ctx, txjob, &ccaDisabled) )
goto check_alt;
ustime_t txtime = txjob->txtime;
txidx_t* pidx = &s2ctx->txunits[txunit].head;
txidx_t idx = pidx[0];
txjob_t* curr = txq_idx2job(&s2ctx->txq, idx);
if( curr && (curr->txflags & TXFLAG_TXING) && txtime < curr->txtime + curr->airtime + TX_MIN_GAP ) {
// Would interfer with currently ongoing TX
LOG(MOD_S2E|DEBUG, "%J - frame colliding with ongoing TX on ant#%d", txjob, txunit);
goto check_alt;
}
// Insert into Q by ascending txtime
do {
if( idx == TXIDX_END || txtime < curr->txtime ) {
// Found my place - insert/append
assert(txjob->next == TXIDX_NIL);
txjob->next = idx;
pidx[0] = txq_job2idx(&s2ctx->txq, txjob);
if( pidx == &s2ctx->txunits[txunit].head ) // new txjob is head of q?
rt_yieldTo(&s2ctx->txunits[txunit].timer, s2e_txtimeout);
return 1;
}
idx = (pidx = &curr->next)[0];
curr = txq_idx2job(&s2ctx->txq, idx);
} while(1);
}
}
// Analyze TX queue and decide on next action.
// Return the time when the next action is due if the queue head is not changed.
// This can be called any time to reevaluate actions.
// State engine:
// - A TXing job is pushed trhu its states before it is dequeued and the next txjob is even considered
// - entering and goining thru TXing states:
// - recalc xtime from latest timesync data
// - check clear channel
// - submit to radio
// - check that frame is being emitted (protects against radio failures, xticks rollovers)
// - at txend consider next txjob
// - If head txjob too far out, wait until it is TXable
//
// The return value makes a suggestion as to when the next call should be done.
//
ustime_t s2e_nextTxAction (s2ctx_t* s2ctx, u1_t txunit) {
ustime_t now = rt_getTime();
txidx_t *phead = &s2ctx->txunits[txunit].head;
again:
if( phead[0] == TXIDX_END )
return USTIME_MAX;
txjob_t* curr = txq_idx2job(&s2ctx->txq, phead[0]);
ustime_t txdelta = curr->txtime - now;
if( (curr->txflags & TXFLAG_TXING) ) {
// Head job in mode TXING
ustime_t txend = curr->txtime + curr->airtime;
if( now >= txend ) {
// TX is over - drop job
LOG(MOD_S2E|DEBUG, "Tx done diid=%ld", curr->diid);
txq_unqJob(&s2ctx->txq, phead);
txq_freeJob(&s2ctx->txq, curr);
goto again;
}
// Frame is still being transmitted - come back at end of TX
if( !(curr->txflags & TXFLAG_TXCHECKED) ) {
if( txdelta > -TXCHECK_FUDGE )
return curr->txtime + TXCHECK_FUDGE;
int txs = ral_txstatus(txunit);
if( txs != TXSTATUS_EMITTING ) {
// Something went wrong - should be emitting
LOG(MOD_S2E|ERROR, "%J - radio is not emitting frame - abandoning TX, trying alternative", curr);
ral_txabort(txunit);
goto check_alt;
}
// Looks like it's on air
update_DC(s2ctx, curr);
curr->txflags |= TXFLAG_TXCHECKED;
// sending dntxed here instead @txend gives nwks more time to update/inform muxs (join)
send_dntxed(s2ctx, curr);
}
return txend;
}
if( txdelta < TX_MIN_GAP ) {
// Missed TX start time - try alternative or drop frame
LOG(MOD_S2E|ERROR, "%J - missed TX time: txdelta=%ld min=%d", curr, txdelta, TX_MIN_GAP);
check_alt:
txq_unqJob(&s2ctx->txq, phead);
if( !s2e_addTxjob(s2ctx, curr, /*relocate*/1, now) ) // note: might change queue head! (reload @ again)
txq_freeJob(&s2ctx->txq, curr);
goto again;
}
// Txtime time too far out Head is TXable - is it time to feed the radio?
if( txdelta > TX_AIM_GAP ) {
LOG(MOD_S2E|DEBUG, "%J - next TX start ahead by %~T", curr, txdelta);
return curr->txtime - TX_AIM_GAP;
}
// Re-calc exact xtime based on latest timesync data
if( curr->gpstime ) {
// Recalc xtime against latest time sync data
curr->xtime = ts_gpstime2xtime(txunit, curr->gpstime);
curr->txtime = ts_xtime2ustime(curr->xtime);
txdelta = curr->txtime - now;
}
else if( ral_xtime2txunit(curr->xtime) != txunit ) {
curr->xtime = ts_xtime2xtime(curr->xtime, txunit);
}
if( curr->xtime == 0 ) {
LOG(MOD_S2E|ERROR, "%J - time sync problems - trying alternative", curr);
goto check_alt;
}
// Txtime close enough to make a decision
// Check channel access
int ccaDisabled = s2e_ccaDisabled;
if( !s2e_dcDisabled && !(*s2ctx->canTx)(s2ctx, curr, &ccaDisabled) )
goto check_alt;
// Check collision with subsequent frames and weigh priorities
// Assuming a txjob with later txstart time is not blocked by duty cycle
// if the earlier current txjob isn't
ustime_t txend = curr->txtime + curr->airtime;
txjob_t* other_txjob = curr;
int prio = calcPriority(curr);
do {
other_txjob = txq_idx2job(&s2ctx->txq, other_txjob->next);
if( other_txjob == NULL )
break;
if( txend < other_txjob->txtime - TX_MIN_GAP )
break; // no overlap
int oprio = calcPriority(other_txjob);
if( prio < oprio ) {
LOG(MOD_S2E|ERROR, "%J - Hindered by %J %~T later: prio %d<%d - trying alternative",
curr, other_txjob, other_txjob->txtime - curr->txtime, prio, oprio);
goto check_alt;
}
} while(1);
int txerr = ral_tx(curr, s2ctx, ccaDisabled);
if( txerr != RAL_TX_OK ) {
if( txerr == RAL_TX_NOCA ) {
LOG(MOD_S2E|ERROR, "%J - channel busy - trying alternative", curr);
} else {
LOG(MOD_S2E|ERROR, "%J - radio layer failed to TX - trying alternative", curr);
}
goto check_alt;
}
curr->txflags |= TXFLAG_TXING;
LOG(MOD_S2E|VERBOSE, "%J - starting TX in %~T", curr, txdelta);
// Unqueue all overlapping subsequent txjobs and find alternatives (antenna/txtime)
// If no alternatives drop txjob.
while(1) {
txjob_t* next_txjob = txq_idx2job(&s2ctx->txq, curr->next);
if( next_txjob == NULL || txend < next_txjob->txtime - TX_MIN_GAP )
break; // no next or no overlap
txq_unqJob(&s2ctx->txq, &curr->next);
if( !s2e_addTxjob(s2ctx, next_txjob, /*relocate*/1, now) ) // note: might change next!
txq_freeJob(&s2ctx->txq, next_txjob);
}
return curr->txtime + TXCHECK_FUDGE;
}
void s2e_txtimeout (tmr_t* tmr) {
s2ctx_t* s2ctx = tmr->ctx;
u1_t txunit = (s2txunit_t*)((u1_t*)tmr - offsetof(s2txunit_t, timer)) - s2ctx->txunits;
ustime_t t = s2e_nextTxAction(s2ctx, txunit);
if( t == USTIME_MAX )
return;
rt_setTimer(tmr, t);
}
static int handle_router_config (s2ctx_t* s2ctx, ujdec_t* D) {
char hwspec[MAX_HWSPEC_SIZE] = { 0 };
ujbuf_t sx1301conf = { .buf=NULL };
ujcrc_t field;
u1_t ccaDisabled=0, dcDisabled=0, dwellDisabled=0; // fields not present
s2_t default_txpow = 14 * TXPOW_SCALE; // builtin default
int jlistlen = 0;
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_freq_range: {
uj_enterArray(D);
s2ctx->min_freq = (uj_nextSlot(D), uj_uint(D));
s2ctx->max_freq = (uj_nextSlot(D), uj_uint(D));
uj_exitArray(D);
break;
}
case J_DRs: {
int dr = 0;
uj_enterArray(D);
while( uj_nextSlot(D) >= 0 ) {
uj_enterArray(D);
int sfin = (uj_nextSlot(D), uj_int(D));
int bwin = (uj_nextSlot(D), uj_int(D));
int dnonly = (uj_nextSlot(D), uj_int(D));
uj_exitArray(D);
if( sfin < 0 ) {
s2ctx->dr_defs[dr] = RPS_ILLEGAL;
} else {
// We're not tracking/checking dnonly right now
int bw = bwin==125 ? BW125 : bwin==250 ? BW250 : BW500;
int sf = 12-sfin;
rps_t rps = (sfin==0 ? FSK : rps_make(sf,bw)) | (dnonly ? RPS_DNONLY : 0);
s2ctx->dr_defs[dr] = rps;
}
dr = min(DR_CNT-1, dr+1);
}
uj_exitArray(D);
break;
}
case J_NetID: {
if( !uj_null(D) ) {
for( int i=0; i<4; i++ )
s2e_netidFilter[i] = 0;
uj_enterArray(D);
while( uj_nextSlot(D) >= 0 ) {
u4_t netid = uj_uint(D);
s2e_netidFilter[(netid >> 5) & 3] |= 1 << (netid & 0x1F);
}
uj_exitArray(D);
} else {
for( int i=0; i<4; i++ )
s2e_netidFilter[i] = 0xffFFffFF;
}
break;
}
case J_JoinEui: {
for( int i=0; i<2*MAX_JOINEUI_RANGES; i++ )
s2e_joineuiFilter[i] = 0;
if( !uj_null(D) ) {
uj_enterArray(D);
int off;
while( (off = uj_nextSlot(D)) >= 0 ) {
uj_enterArray(D);
if( off < MAX_JOINEUI_RANGES ) {
s2e_joineuiFilter[2*off+0] = (uj_nextSlot(D), uj_int(D));
s2e_joineuiFilter[2*off+1] = (uj_nextSlot(D), uj_int(D));
} else {
LOG(MOD_S2E|ERROR, "Too many Join EUI filter ranges - max %d supported", MAX_JOINEUI_RANGES);
}
uj_exitArray(D);
}
uj_exitArray(D);
jlistlen = min(off, MAX_JOINEUI_RANGES);
s2e_joineuiFilter[2*jlistlen] = 0; // terminate list
}
break;
}
case J_region: {
const char* s = uj_str(D);
snprintf(s2ctx->region_s, sizeof(s2ctx->region_s), "%s", s);
s2ctx->region = D->str.crc;
switch( s2ctx->region ) {
case J_EU863: {
s2ctx->canTx = s2e_canTxEU863;
s2ctx->txpow = 16 * TXPOW_SCALE;
s2ctx->txpow2 = 27 * TXPOW_SCALE;
s2ctx->txpow2_freq[0] = 869400000;
s2ctx->txpow2_freq[1] = 869650000;
resetDC(s2ctx, 3600/100); // 100s / 1h cummulative on time under PSA = ~2.78%
break;
}
case J_IL915: {
s2ctx->txpow = 14 * TXPOW_SCALE;
s2ctx->txpow2 = 20 * TXPOW_SCALE;
s2ctx->txpow2_freq[0] = 916200000;
s2ctx->txpow2_freq[1] = 916400000;
resetDC(s2ctx, 100); // 1%
break;
}
case J_KR920: {
s2ctx->ccaEnabled = 1;
s2ctx->canTx = s2e_canTxPerChnlDC;
s2ctx->txpow = 23 * TXPOW_SCALE;
resetDC(s2ctx, 50); // 2%
break;
}
case J_AS923JP: {
s2ctx->ccaEnabled = 1;
s2ctx->canTx = s2e_canTxPerChnlDC;
s2ctx->txpow = 13 * TXPOW_SCALE;
resetDC(s2ctx, 10); // 10%
break;
}
case J_US902: {
s2ctx->txpow = 30 * TXPOW_SCALE;
break;
}
}
break;
}
case J_max_eirp: {
// Generic device level max TX power - in general lower then what the GW can do
// Unless we get more specific limits we stick with that
default_txpow = (s2_t)(uj_num(D) * TXPOW_SCALE);
break;
}
case J_MuxTime: {
s2e_updateMuxtime(s2ctx, uj_num(D), 0);
rt_utcOffset = s2ctx->muxtime*1e6 - s2ctx->reftime;
break;
}
case J_hwspec: {
str_t s = uj_str(D);
if( D->str.len > sizeof(hwspec)-1 )
uj_error(D, "Hardware specifier is too long");
strcpy(hwspec, s);
break;
}
#if defined(CFG_prod)
case J_nocca:
case J_nodc:
case J_nodwell:
case J_device_mode: {
LOG(MOD_S2E|WARNING, "Feature not supported in production level code (router_config) - ignored: %s", D->field.name);
uj_skipValue(D);
break;
}
#else // !defined(CFG_prod)
case J_nocca: {
ccaDisabled = uj_bool(D) ? 2 : 1;
break;
}
case J_nodc: {
dcDisabled = uj_bool(D) ? 2 : 1;
break;
}
case J_nodwell: {
dwellDisabled = uj_bool(D) ? 2 : 1;
break;
}
case J_device_mode: {
sys_deviceMode = uj_bool(D) ? 1 : 0;
break;
}
#endif // !defined(CFG_prod)
case J_sx1301_conf: {
// Processed in ral layer
sx1301conf = uj_skipValue(D);
break;
}
case J_msgtype: {
// Silently ignored fields
uj_skipValue(D);
break;
}
default: {
LOG(MOD_S2E|WARNING, "Unknown field in router_config - ignored: %s (0x%X)", D->field.name, D->field.crc);
uj_skipValue(D);
break;
}
}
}
if( !hwspec[0] ) {
LOG(ERROR, "No 'hwspec' in 'router_config' message");
return 0;
}
if( sx1301conf.buf == NULL ) {
LOG(ERROR, "No 'sx1301_conf' in 'router_config' message");
return 0;
}
ts_iniTimesync();
if( !ral_config(hwspec,
s2ctx->ccaEnabled ? s2ctx->region : 0,
sx1301conf.buf, sx1301conf.bufsize) )
return 0;
// Override local settings with server settings if provided
if( ccaDisabled ) s2e_ccaDisabled = ccaDisabled & 2;
if( dcDisabled ) s2e_dcDisabled = dcDisabled & 2;
if( dwellDisabled ) s2e_dwellDisabled = dwellDisabled & 2;
if( s2ctx->txpow == 0 ) {
// No region specific settings, go with device/builtin default
s2ctx->txpow = default_txpow;
}
LOG(MOD_S2E|INFO, "Configuring for region: %s%s -- %F..%F",
s2ctx->region_s, s2ctx->ccaEnabled ? " (CCA)":"", s2ctx->min_freq, s2ctx->max_freq);
if( log_shallLog(MOD_S2E|VERBOSE) ) {
for( int dr=0; dr<16; dr++ ) {
int rps = s2ctx->dr_defs[dr];
if( rps == RPS_ILLEGAL ) {
LOG(MOD_S2E|VERBOSE, " DR%-2d undefined", dr);
} else {
LOG(MOD_S2E|VERBOSE, " DR%-2d %R %s", dr, rps, rps & RPS_DNONLY ? "(DN only)" : "");
}
}
LOG(MOD_S2E|VERBOSE,
" TX power: %.1f dBm EIRP",
s2ctx->txpow/(double)TXPOW_SCALE);
if( s2ctx->txpow2 ) {
LOG(MOD_S2E|VERBOSE, " %.1f dBm EIRP for %F..%F",
s2ctx->txpow2/(double)TXPOW_SCALE, s2ctx->txpow2_freq[0], s2ctx->txpow2_freq[1]);
}
LOG(MOD_S2E|VERBOSE, " JoinEui list: %d entries", jlistlen);
LOG(MOD_S2E|VERBOSE, " NetID filter: %08X-%08X-%08X-%08X",
s2e_netidFilter[0], s2e_netidFilter[0], s2e_netidFilter[0], s2e_netidFilter[0]);
LOG(MOD_S2E|VERBOSE, " Dev/test settings: nocca=%d nodc=%d nodwell=%d",
(s2e_ccaDisabled!=0), (s2e_dcDisabled!=0), (s2e_dwellDisabled!=0));
}
return 1;
}
// Obsolete message format - newer servers use dnmsg which carries more context!
void handle_dnframe (s2ctx_t* s2ctx, ujdec_t* D) {
ustime_t now = rt_getTime();
txjob_t* txjob = txq_reserveJob(&s2ctx->txq);
if( txjob == NULL ) {
LOG(MOD_S2E|ERROR, "Out of TX jobs - dropping incomming message");
return;
}
int flags = 0;
ujcrc_t field;
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_msgtype: {
uj_skipValue(D);
break;
}
case J_DR: {
check_dr(s2ctx, D, &txjob->dr);
flags |= 0x01;
break;
}
case J_Freq: {
check_dnfreq(s2ctx, D, &txjob->freq, &txjob->dnchnl);
flags |= 0x02;
break;
}
case J_DevEui: {
txjob->deveui = uj_eui(D);
flags |= 0x04;
break;
}
case J_xtime: {
txjob->xtime = uj_int(D);
flags |= 0x08;
break;
}
case J_asap: {
if( uj_bool(D) )
txjob->txflags |= TXFLAG_CLSC;
break;
}
case J_seqno: // older server (remove if obsoleted)
case J_diid: { // newer servers use this field name
txjob->diid = uj_int(D);
flags |= 0x10;
break;