-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
reflect.zig
2660 lines (2477 loc) · 91.8 KB
/
reflect.zig
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
//! LoRaWAN Zig App for NuttX. We call the LoRaWAN Library
//! to Join a LoRaWAN Network and send a Data Packet. Ported from:
//! https://github.com/lupyuen/lorawan_test/blob/main/lorawan_test_main.c
/// Import the Zig Standard Library
const std = @import("std");
/// Import the LoRaWAN Library from C
const c = @cImport({
// NuttX Defines
@cDefine("__NuttX__", "");
@cDefine("NDEBUG", "");
@cDefine("ARCH_RISCV", "");
// Workaround for "Unable to translate macro: undefined identifier `LL`"
@cDefine("LL", "");
@cDefine("__int_c_join(a, b)", "a"); // Bypass zig/lib/include/stdint.h
// NuttX Header Files
@cInclude("arch/types.h");
@cInclude("../../nuttx/include/limits.h");
@cInclude("stdio.h");
// LoRaWAN Header Files
@cInclude("firmwareVersion.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/githubVersion.h");
@cInclude("../libs/liblorawan/src/boards/utilities.h");
@cInclude("../libs/liblorawan/src/mac/region/RegionCommon.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/Commissioning.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/LmHandler/LmHandler.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/LmHandler/packages/LmhpCompliance.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/LmHandler/packages/LmhpClockSync.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/LmHandler/packages/LmhpRemoteMcastSetup.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/LmHandler/packages/LmhpFragmentation.h");
@cInclude("../libs/liblorawan/src/apps/LoRaMac/common/LmHandlerMsgDisplay.h");
// Fix for missing Radio Function Declarations in radio.h
@cInclude("radio-sx1262.h");
// TODO: BL602 Internal Temperature Sensor for seeding Entropy Pool
// #ifdef CONFIG_LIBBL602_ADC
// @cInclude("../libs/libbl602_adc/bl602_adc.h");
// @cInclude("../libs/libbl602_adc/bl602_glb.h");
// #endif // CONFIG_LIBBL602_ADC
});
///////////////////////////////////////////////////////////////////////////////
// Constants
/// LoRaWAN Region
const ACTIVE_REGION = c.LORAMAC_REGION_AS923;
/// LoRaWAN default end-device class
const LORAWAN_DEFAULT_CLASS = c.CLASS_A;
/// Defines the application data transmission duty cycle. 40s, value in [ms].
const APP_TX_DUTYCYCLE: c_int = 40000;
/// Defines a random delay for application data transmission duty cycle. 5s,
/// value in [ms].
const APP_TX_DUTYCYCLE_RND: c_int = 5000;
/// LoRaWAN Adaptive Data Rate
/// \remark Please note that when ADR is enabled the end-device should be static
const LORAWAN_ADR_STATE = false; // Previously: c.LORAMAC_HANDLER_ADR_OFF;
/// Default datarate
/// \remark Please note that LORAWAN_DEFAULT_DATARATE is used only when ADR is disabled
const LORAWAN_DEFAULT_DATARATE = c.DR_3;
/// LoRaWAN confirmed messages (unconfirmed)
const LORAWAN_DEFAULT_CONFIRMED_MSG_STATE = c.LORAMAC_HANDLER_UNCONFIRMED_MSG;
/// User application data buffer size
const LORAWAN_APP_DATA_BUFFER_MAX_SIZE = 242;
/// LoRaWAN ETSI duty cycle control enable/disable
/// \remark Please note that ETSI mandates duty cycled transmissions. Use only for test purposes
const LORAWAN_DUTYCYCLE_ON = true;
/// Defines the maximum size for the buffer receiving the fragmentation result.
/// \remark By default FragDecoder.h defines:
/// \ref FRAG_MAX_NB 21
/// \ref FRAG_MAX_SIZE 50
/// FileSize = FRAG_MAX_NB * FRAG_MAX_SIZE
/// If bigger file size is to be received or is fragmented differently
/// one must update those parameters.
const UNFRAGMENTED_DATA_SIZE = 21 * 50;
///////////////////////////////////////////////////////////////////////////////
// Main Function
/// Main Function that will be called by NuttX. We call the LoRaWAN Library
/// to Join a LoRaWAN Network and send a Data Packet.
pub export fn lorawan_test_main(
_argc: c_int,
_argv: [*]const [*]const u8
) c_int {
// Do Type Reflection
reflect();
// Unused parameters
_ = _argc;
_ = _argv;
// Init the Timer Struct at startup
TxTimer = std.mem.zeroes(c.TimerEvent_t);
// If we are using Entropy Pool and the BL602 ADC is available,
// add the Internal Temperature Sensor data to the Entropy Pool
// TODO: init_entropy_pool();
// Compute the interval between transmissions based on Duty Cycle
TxPeriodicity = @intCast(u32, // Cast to u32 because randr() can be negative
APP_TX_DUTYCYCLE +
c.randr(
-APP_TX_DUTYCYCLE_RND,
APP_TX_DUTYCYCLE_RND
)
);
// Show the Firmware and GitHub Versions
const appVersion = c.Version_t {
.Value = c.FIRMWARE_VERSION,
};
const gitHubVersion = c.Version_t {
.Value = c.GITHUB_VERSION,
};
c.DisplayAppInfo("Zig LoRaWAN Test", &appVersion, &gitHubVersion);
// Init LoRaWAN
if (LmHandlerInit(&LmHandlerCallbacks, &LmHandlerParams)
!= c.LORAMAC_HANDLER_SUCCESS) {
std.log.err("LoRaMac wasn't properly initialized", .{});
// Fatal error, endless loop.
while (true) {}
}
_ = &LmHandlerParams; // For debugging
_ = &LmhpComplianceParams; // For debugging
_ = &LmHandlerCallbacks; // For debugging
// Set system maximum tolerated rx error in milliseconds
_ = c.LmHandlerSetSystemMaxRxError(20);
// The LoRa-Alliance Compliance protocol package should always be initialized and activated.
_ = c.LmHandlerPackageRegister(c.PACKAGE_ID_COMPLIANCE, &LmhpComplianceParams);
_ = c.LmHandlerPackageRegister(c.PACKAGE_ID_CLOCK_SYNC, null);
_ = c.LmHandlerPackageRegister(c.PACKAGE_ID_REMOTE_MCAST_SETUP, null);
_ = c.LmHandlerPackageRegister(c.PACKAGE_ID_FRAGMENTATION, &FragmentationParams);
// Init the Clock Sync and File Transfer status
IsClockSynched = false;
IsFileTransferDone = false;
// Join the LoRaWAN Network
c.LmHandlerJoin();
// Set the Transmit Timer
StartTxProcess(LmHandlerTxEvents_t.LORAMAC_HANDLER_TX_ON_TIMER);
// Handle LoRaWAN Events
handle_event_queue(); // Never returns
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Transmit Data
/// Prepare the payload of a Data Packet and transmit it
fn PrepareTxFrame() void {
// If we haven't joined the LoRaWAN Network, try again later
if (c.LmHandlerIsBusy()) {
debug("PrepareTxFrame: Busy", .{});
return;
}
// Message to be sent to LoRaWAN
const msg: []const u8 = "Hi NuttX\x00"; // 9 bytes including null
debug("PrepareTxFrame: Transmit to LoRaWAN ({} bytes): {s}", .{
msg.len, msg
});
// Copy message into LoRaWAN buffer
std.mem.copy(
u8, // Type
&AppDataBuffer, // Destination
msg // Source
);
// Compose the transmit request
var appData = c.LmHandlerAppData_t {
.Buffer = &AppDataBuffer,
.BufferSize = msg.len,
.Port = 1,
};
// Validate the message size and check if it can be transmitted
var txInfo: c.LoRaMacTxInfo_t = undefined;
const status = c.LoRaMacQueryTxPossible(appData.BufferSize, &txInfo);
debug("PrepareTxFrame: status={}, maxSize={}, currentSize={}", .{
status,
txInfo.MaxPossibleApplicationDataSize,
txInfo.CurrentPossiblePayloadSize
});
assert(status == c.LORAMAC_STATUS_OK);
// Transmit the message
const sendStatus = c.LmHandlerSend(&appData, LmHandlerParams.IsTxConfirmed);
assert(sendStatus == c.LORAMAC_HANDLER_SUCCESS);
debug("PrepareTxFrame: Transmit OK", .{});
}
fn StartTxProcess(txEvent: LmHandlerTxEvents_t) void {
debug("StartTxProcess", .{});
switch (txEvent) {
LmHandlerTxEvents_t.LORAMAC_HANDLER_TX_ON_TIMER => {
// Schedule 1st packet transmission
c.TimerInit(&TxTimer, OnTxTimerEvent);
c.TimerSetValue(&TxTimer, TxPeriodicity);
OnTxTimerEvent(null);
},
LmHandlerTxEvents_t.LORAMAC_HANDLER_TX_ON_EVENT => {
// Do nothing
},
}
}
fn UplinkProcess() void {
debug("UplinkProcess", .{});
var isPending: u8 = 0;
// TODO: CRITICAL_SECTION_BEGIN();
isPending = IsTxFramePending;
IsTxFramePending = 0;
// TODO: CRITICAL_SECTION_END();
if (isPending == 1) {
PrepareTxFrame();
}
}
///////////////////////////////////////////////////////////////////////////////
// Event Handlers
/// Function executed on TxTimer event
export fn OnTxTimerEvent(event: [*c]c.struct_ble_npl_event) void {
debug("OnTxTimerEvent: timeout in {} ms, event=0x{x}", .{
TxPeriodicity, @ptrToInt(event)
});
c.TimerStop(&TxTimer);
IsTxFramePending = 1;
// Schedule next transmission
c.TimerSetValue(&TxTimer, TxPeriodicity);
c.TimerStart(&TxTimer);
}
export fn OnMacProcessNotify() void {
IsMacProcessPending = 1;
}
export fn OnNvmDataChange(state: c.LmHandlerNvmContextStates_t, size: u16) void {
c.DisplayNvmDataChange(state, size);
}
export fn OnNetworkParametersChange(params: [*c]c.CommissioningParams_t) void {
c.DisplayNetworkParametersUpdate(params);
}
export fn OnMacMcpsRequest(
status: c.LoRaMacStatus_t,
mcpsReq: [*c]c.McpsReq_t,
nextTxIn: c.TimerTime_t
) void {
c.DisplayMacMcpsRequestUpdate(status, mcpsReq, nextTxIn);
}
export fn OnMacMlmeRequest(
status: c.LoRaMacStatus_t,
mlmeReq: *MlmeReq_t,
nextTxIn: c.TimerTime_t
) void {
DisplayMacMlmeRequestUpdate(status, mlmeReq, nextTxIn);
}
export fn OnJoinRequest(params: [*c]c.LmHandlerJoinParams_t) void {
debug("OnJoinRequest", .{});
c.DisplayJoinRequestUpdate(params);
if (params.*.Status == c.LORAMAC_HANDLER_ERROR) {
c.LmHandlerJoin();
} else {
_ = c.LmHandlerRequestClass(LORAWAN_DEFAULT_CLASS);
}
}
export fn OnTxData(params: [*c]c.LmHandlerTxParams_t) void {
debug("OnTxData", .{});
c.DisplayTxUpdate(params);
}
export fn OnRxData(appData: [*c]c.LmHandlerAppData_t, params: [*c]c.LmHandlerRxParams_t) void {
debug("OnRxData", .{});
c.DisplayRxUpdate(appData, params);
}
export fn OnClassChange(deviceClass: c.DeviceClass_t) void {
debug("OnClassChange", .{});
c.DisplayClassUpdate(deviceClass);
switch (deviceClass) {
c.CLASS_A => {
IsMcSessionStarted = false;
},
c.CLASS_B => {
// Inform the server as soon as possible that the end-device has switched to ClassB
var appData = c.LmHandlerAppData_t {
.Buffer = null,
.BufferSize = 0,
.Port = 0,
};
_ = c.LmHandlerSend(
&appData,
c.LORAMAC_HANDLER_UNCONFIRMED_MSG
);
IsMcSessionStarted = true;
},
c.CLASS_C => {
IsMcSessionStarted = true;
},
else => {
unreachable;
}
}
}
export fn OnBeaconStatusChange(params: [*c]c.LoRaMacHandlerBeaconParams_t) void {
switch (params.*.State) {
c.LORAMAC_HANDLER_BEACON_RX => {
debug("OnBeaconStatusChange: LORAMAC_HANDLER_BEACON_RX", .{});
},
c.LORAMAC_HANDLER_BEACON_LOST => {
debug("OnBeaconStatusChange: LORAMAC_HANDLER_BEACON_LOST", .{});
},
c.LORAMAC_HANDLER_BEACON_NRX => {
debug("OnBeaconStatusChange: LORAMAC_HANDLER_BEACON_NRX", .{});
},
else => {
unreachable;
}
}
c.DisplayBeaconUpdate(params);
}
export fn OnSysTimeUpdate(isSynchronized: bool, _timeCorrection: i32) void {
_ = _timeCorrection;
IsClockSynched = isSynchronized;
}
///////////////////////////////////////////////////////////////////////////////
// Board Handlers
/// TODO: Get Battery Level
export fn BoardGetBatteryLevel() u8 {
return 0;
}
/// TODO: Get Temperature
export fn BoardGetTemperature() f32 {
return 22.0;
}
/// TODO: Get Random Seed
export fn BoardGetRandomSeed() u32 {
return 22;
}
///////////////////////////////////////////////////////////////////////////////
// Compliance Handlers
export fn OnTxPeriodicityChanged(periodicity: u32) void {
TxPeriodicity = periodicity;
if (TxPeriodicity == 0) {
// Revert to application default periodicity
TxPeriodicity = @intCast(u32, // Cast to u32 because randr() can be negative
APP_TX_DUTYCYCLE +
c.randr(
-APP_TX_DUTYCYCLE_RND,
APP_TX_DUTYCYCLE_RND
)
);
}
// Update timer periodicity
c.TimerStop( &TxTimer );
c.TimerSetValue( &TxTimer, TxPeriodicity );
c.TimerStart( &TxTimer );
}
export fn OnTxFrameCtrlChanged(isTxConfirmed: c.LmHandlerMsgTypes_t) void {
LmHandlerParams.IsTxConfirmed = isTxConfirmed;
}
export fn OnPingSlotPeriodicityChanged(pingSlotPeriodicity: u8) void {
LmHandlerParams.PingSlotPeriodicity = pingSlotPeriodicity;
}
///////////////////////////////////////////////////////////////////////////////
// Fragment Handlers
export fn FragDecoderWrite(addr: u32, data: [*c]u8, size: u32) i8 {
if (size >= UNFRAGMENTED_DATA_SIZE) {
return -1; // Fail
}
var i: u32 = 0;
while (i < size) : (i += 1) {
UnfragmentedData[addr + i] = data[i];
}
return 0; // Success
}
export fn FragDecoderRead(addr: u32, data: [*c]u8, size: u32) i8 {
if (size >= UNFRAGMENTED_DATA_SIZE) {
return -1; // Fail
}
var i: u32 = 0;
while (i < size) : (i += 1) {
data[i] = UnfragmentedData[addr + i];
}
return 0; // Success
}
export fn OnFragProgress(fragCounter: u16, fragNb: u16, fragSize: u8, fragNbLost: u16) void {
debug("###### =========== FRAG_DECODER ============ ######", .{});
debug("###### PROGRESS ######", .{});
debug("###### ===================================== ######", .{});
debug("RECEIVED : {} / {} Fragments", .{ fragCounter, fragNb });
debug(" {} / {} Bytes", .{ fragCounter * fragSize, fragNb * fragSize });
debug("LOST : {} Fragments", .{ fragNbLost });
}
export fn OnFragDone(status: i32, size: u32) void {
FileRxCrc = c.Crc32(
&UnfragmentedData,
@intCast(u16, size)
);
IsFileTransferDone = true;
debug("###### =========== FRAG_DECODER ============ ######", .{});
debug("###### FINISHED ######", .{});
debug("###### ===================================== ######", .{});
debug("STATUS : {}", .{ status });
debug("CRC : {x}", .{ FileRxCrc});
}
///////////////////////////////////////////////////////////////////////////////
// Event Queue
/// LoRaWAN Event Loop that dequeues Events from the Event Queue and processes the Events
fn handle_event_queue() void {
debug("handle_event_queue", .{});
// Loop forever handling Events from the Event Queue
while (true) {
// Get the next Event from the Event Queue
var ev: [*c]c.ble_npl_event = c.ble_npl_eventq_get(
&event_queue, // Event Queue
c.BLE_NPL_TIME_FOREVER // No Timeout (Wait forever for event)
);
// If no Event due to timeout, wait for next Event.
// Should never happen since we wait forever for an Event.
if (ev == null) { debug("handle_event_queue: timeout", .{}); continue; }
debug("handle_event_queue: ev=0x{x}", .{ @ptrToInt(ev) });
// Remove the Event from the Event Queue
c.ble_npl_eventq_remove(&event_queue, ev);
// Trigger the Event Handler Function
c.ble_npl_event_run(ev);
// Process the LoRaMac events
c.LmHandlerProcess();
// If we have joined the network, do the uplink
if (!c.LmHandlerIsBusy()) {
UplinkProcess();
}
// TODO: CRITICAL_SECTION_BEGIN();
if (IsMacProcessPending == 1) {
// Clear flag and prevent MCU to go into low power mode
IsMacProcessPending = 0;
} else {
// The MCU wakes up through events
// TODO: BoardLowPowerHandler();
}
// TODO: CRITICAL_SECTION_END();
}
}
///////////////////////////////////////////////////////////////////////////////
// Panic Handler
/// Called by Zig when it hits a Panic. We print the Panic Message, Stack Trace and halt. See
/// https://andrewkelley.me/post/zig-stack-traces-kernel-panic-bare-bones-os.html
/// https://github.com/ziglang/zig/blob/master/lib/std/builtin.zig#L763-L847
pub fn panic(
message: []const u8,
_stack_trace: ?*std.builtin.StackTrace
) noreturn {
// Print the Panic Message
_ = _stack_trace;
_ = puts("\n!ZIG PANIC!");
_ = puts(@ptrCast([*c]const u8, message));
// Print the Stack Trace
_ = puts("Stack Trace:");
var it = std.debug.StackIterator.init(@returnAddress(), null);
while (it.next()) |return_address| {
_ = printf("%p\n", return_address);
}
// Halt
while(true) {}
}
///////////////////////////////////////////////////////////////////////////////
// Logging
/// Called by Zig for `std.log.debug`, `std.log.info`, `std.log.err`, ...
/// https://gist.github.com/leecannon/d6f5d7e5af5881c466161270347ce84d
pub fn log(
comptime _message_level: std.log.Level,
comptime _scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
_ = _message_level;
_ = _scope;
// Format the message
var buf: [100]u8 = undefined; // Limit to 100 chars
var slice = std.fmt.bufPrint(&buf, format, args)
catch { _ = puts("*** log error: buf too small"); return; };
// Terminate the formatted message with a null
var buf2: [buf.len + 1 : 0]u8 = undefined;
std.mem.copy(
u8,
buf2[0..slice.len],
slice[0..slice.len]
);
buf2[slice.len] = 0;
// Print the formatted message
_ = puts(&buf2);
}
///////////////////////////////////////////////////////////////////////////////
// Entropy Pool and Internal Temperature Sensor
// #if defined(CONFIG_CRYPTO_RANDOM_POOL) && defined(CONFIG_LIBBL602_ADC)
/// Read the Internal Temperature Sensor as Float. Returns 0 if successful.
/// Based on bl_tsen_adc_get in https://github.com/lupyuen/bl_iot_sdk/blob/tsen/components/hal_drv/bl602_hal/bl_adc.c#L224-L282
// static int get_tsen_adc(
// float *temp, // Pointer to float to store the temperature
// uint8_t log_flag // 0 to disable logging, 1 to enable logging
// ) {
// assert(temp != NULL);
// static uint16_t tsen_offset = 0xFFFF;
// float val = 0.0;
// // If the offset has not been fetched...
// if (0xFFFF == tsen_offset) {
// // Define the ADC configuration
// tsen_offset = 0;
// ADC_CFG_Type adcCfg = {
// .v18Sel=ADC_V18_SEL_1P82V, /*!< ADC 1.8V select */
// .v11Sel=ADC_V11_SEL_1P1V, /*!< ADC 1.1V select */
// .clkDiv=ADC_CLK_DIV_32, /*!< Clock divider */
// .gain1=ADC_PGA_GAIN_1, /*!< PGA gain 1 */
// .gain2=ADC_PGA_GAIN_1, /*!< PGA gain 2 */
// .chopMode=ADC_CHOP_MOD_AZ_PGA_ON, /*!< ADC chop mode select */
// .biasSel=ADC_BIAS_SEL_MAIN_BANDGAP, /*!< ADC current form main bandgap or aon bandgap */
// .vcm=ADC_PGA_VCM_1V, /*!< ADC VCM value */
// .vref=ADC_VREF_2V, /*!< ADC voltage reference */
// .inputMode=ADC_INPUT_SINGLE_END, /*!< ADC input signal type */
// .resWidth=ADC_DATA_WIDTH_16_WITH_256_AVERAGE, /*!< ADC resolution and oversample rate */
// .offsetCalibEn=0, /*!< Offset calibration enable */
// .offsetCalibVal=0, /*!< Offset calibration value */
// };
// ADC_FIFO_Cfg_Type adcFifoCfg = {
// .fifoThreshold = ADC_FIFO_THRESHOLD_1,
// .dmaEn = DISABLE,
// };
// // Enable and reset the ADC
// GLB_Set_ADC_CLK(ENABLE,GLB_ADC_CLK_96M, 7);
// ADC_Disable();
// ADC_Enable();
// ADC_Reset();
// // Configure the ADC and Internal Temperature Sensor
// ADC_Init(&adcCfg);
// ADC_Channel_Config(ADC_CHAN_TSEN_P, ADC_CHAN_GND, 0);
// ADC_Tsen_Init(ADC_TSEN_MOD_INTERNAL_DIODE);
// ADC_FIFO_Cfg(&adcFifoCfg);
// // Fetch the offset
// BL_Err_Type rc = ADC_Trim_TSEN(&tsen_offset);
// assert(rc != BL_ERROR); // Read efuse data failed
// // Must wait 100 milliseconds or returned temperature will be negative
// usleep(100 * 1000);
// }
// // Read the temperature based on the offset
// val = TSEN_Get_Temp(tsen_offset);
// if (log_flag) {
// printf("offset = %d\n", tsen_offset);
// printf("temperature = %f Celsius\n", val);
// }
// // Return the temperature
// *temp = val;
// return 0;
// }
// #endif // CONFIG_CRYPTO_RANDOM_POOL && CONFIG_LIBBL602_ADC
/// If we are using Entropy Pool and the BL602 ADC is available,
/// add the Internal Temperature Sensor data to the Entropy Pool.
/// This prevents duplicate Join Nonce during BL602 Auto Flash and Test.
// static void init_entropy_pool(void) {
// #if defined(CONFIG_CRYPTO_RANDOM_POOL) && defined(CONFIG_LIBBL602_ADC)
// puts("init_entropy_pool");
// // Repeat 4 times to get good entropy (16 bytes)
// for (int i = 0; i < 4; i++) {
// // Read the Internal Temperature Sensor
// float temp = 0.0;
// get_tsen_adc(&temp, 1);
// // Add Sensor Data (4 bytes) to Entropy Pool
// up_rngaddentropy( // Add integers to Entropy Pool...
// RND_SRC_SENSOR, // Source is Sensor Data
// (FAR const uint32_t *) &temp, // Integers to be added
// sizeof(temp) / sizeof(uint32_t) // How many integers (1)
// );
// }
// // Force reseeding random number generator from entropy pool
// up_rngreseed();
// #endif // CONFIG_CRYPTO_RANDOM_POOL && CONFIG_LIBBL602_ADC
// }
///////////////////////////////////////////////////////////////////////////////
// Variables
/// Handler Callbacks. Changed `c.LmHandlerCallbacks_t` to `LmHandlerCallbacks_t`
/// (Aligned to 32 bits because it's passed to C)
var LmHandlerCallbacks align(4) = LmHandlerCallbacks_t {
.GetBatteryLevel = BoardGetBatteryLevel,
.GetTemperature = BoardGetTemperature,
.GetRandomSeed = BoardGetRandomSeed,
.OnMacProcess = OnMacProcessNotify,
.OnNvmDataChange = OnNvmDataChange,
.OnNetworkParametersChange = OnNetworkParametersChange,
.OnMacMcpsRequest = OnMacMcpsRequest,
.OnMacMlmeRequest = OnMacMlmeRequest,
.OnJoinRequest = OnJoinRequest,
.OnTxData = OnTxData,
.OnRxData = OnRxData,
.OnClassChange = OnClassChange,
.OnBeaconStatusChange = OnBeaconStatusChange,
.OnSysTimeUpdate = OnSysTimeUpdate,
};
//// Handler Parameters
/// (Aligned to 32 bits because it's passed to C)
var LmHandlerParams align(4) = c.LmHandlerParams_t {
.Region = ACTIVE_REGION,
.AdrEnable = LORAWAN_ADR_STATE,
.IsTxConfirmed = LORAWAN_DEFAULT_CONFIRMED_MSG_STATE,
.TxDatarate = LORAWAN_DEFAULT_DATARATE,
.PublicNetworkEnable = true, // Previously: c.LORAWAN_PUBLIC_NETWORK,
.DutyCycleEnabled = LORAWAN_DUTYCYCLE_ON,
.DataBufferMaxSize = LORAWAN_APP_DATA_BUFFER_MAX_SIZE,
.DataBuffer = &AppDataBuffer,
.PingSlotPeriodicity = c.REGION_COMMON_DEFAULT_PING_SLOT_PERIODICITY,
};
/// Compliance Parameters
/// (Aligned to 32 bits because it's passed to C)
var LmhpComplianceParams align(4) = c.LmhpComplianceParams_t {
.FwVersion = c.Version_t {
.Value = c.FIRMWARE_VERSION,
},
.OnTxPeriodicityChanged = OnTxPeriodicityChanged,
.OnTxFrameCtrlChanged = OnTxFrameCtrlChanged,
.OnPingSlotPeriodicityChanged = OnPingSlotPeriodicityChanged,
};
/// Fragmentation Parameters (Unused)
/// (Aligned to 32 bits because it's passed to C)
var FragmentationParams align(4) = c.LmhpFragmentationParams_t {
// TODO: #if( FRAG_DECODER_FILE_HANDLING_NEW_API == 1 )
.DecoderCallbacks = c.FragDecoderCallbacks_t {
.FragDecoderWrite = FragDecoderWrite,
.FragDecoderRead = FragDecoderRead,
},
// #else
// .Buffer = UnfragmentedData,
// .BufferSize = UNFRAGMENTED_DATA_SIZE,
// #endif
.OnProgress = OnFragProgress,
.OnDone = OnFragDone,
};
/// Indicates if LoRaMacProcess call is pending.
/// If variable is equal to 0 then the MCU can be set in low power mode
var IsMacProcessPending: u8 = 0;
/// Set to 1 if a transmit is pending
var IsTxFramePending: u8 = 0;
/// Random interval between transmissions (milliseconds)
var TxPeriodicity: u32 = 0;
/// Indicates if the system time has been synchronized
var IsClockSynched: bool = false;
/// MC Session Started
var IsMcSessionStarted: bool = false;
/// Indicates if the file transfer is done
var IsFileTransferDone: bool = false;
/// Received file computed CRC32
var FileRxCrc: u32 = 0;
/// User application data
/// (Aligned to 32 bits because it's passed to C)
var AppDataBuffer align(4) =
std.mem.zeroes([LORAWAN_APP_DATA_BUFFER_MAX_SIZE]u8);
/// Un-fragmented data storage (Unused)
/// (Aligned to 32 bits because it's passed to C)
var UnfragmentedData align(4) =
std.mem.zeroes([UNFRAGMENTED_DATA_SIZE]u8);
/// Timer to handle the application data transmission duty cycle.
/// We Init the timer in Main Function.
/// (Aligned to 32 bits because it's passed to C)
var TxTimer: c.TimerEvent_t align(4) =
undefined;
// If we init TxTimer...
// var TxTimer: c.TimerEvent_t align(4) =
// std.mem.zeroes(c.TimerEvent_t);
// Zig Compiler crashes with...
// TODO buf_write_value_bytes maybe typethread 11512 panic:
// Unable to dump stack trace: debug info stripped
///////////////////////////////////////////////////////////////////////////////
// Types
/// Handler Callbacks. Adapted from
/// https://github.com/lupyuen/zig-bl602-nuttx/blob/main/translated/lorawan_test_main.zig#L2818-L2833
pub const LmHandlerCallbacks_t = extern struct {
GetBatteryLevel: ?fn () callconv(.C) u8,
GetTemperature: ?fn () callconv(.C) f32,
GetRandomSeed: ?fn () callconv(.C) u32,
OnMacProcess: ?fn () callconv(.C) void,
OnNvmDataChange: ?fn (c.LmHandlerNvmContextStates_t, u16) callconv(.C) void,
OnNetworkParametersChange: ?fn ([*c]c.CommissioningParams_t) callconv(.C) void,
OnMacMcpsRequest: ?fn (c.LoRaMacStatus_t, [*c]c.McpsReq_t, c.TimerTime_t) callconv(.C) void,
/// Changed `[*c]c.MlmeReq_t` to `*MlmeReq_t`
OnMacMlmeRequest: ?fn (c.LoRaMacStatus_t, *MlmeReq_t, c.TimerTime_t) callconv(.C) void,
OnJoinRequest: ?fn ([*c]c.LmHandlerJoinParams_t) callconv(.C) void,
OnTxData: ?fn ([*c]c.LmHandlerTxParams_t) callconv(.C) void,
OnRxData: ?fn ([*c]c.LmHandlerAppData_t, [*c]c.LmHandlerRxParams_t) callconv(.C) void,
OnClassChange: ?fn (c.DeviceClass_t) callconv(.C) void,
OnBeaconStatusChange: ?fn ([*c]c.LoRaMacHandlerBeaconParams_t) callconv(.C) void,
OnSysTimeUpdate: ?fn (bool, i32) callconv(.C) void,
};
/// We use an Opaque Type to represent MLME Request, because it contains Bit Fields that can't be converted by Zig
const MlmeReq_t = opaque {};
/// Transmit Events
const LmHandlerTxEvents_t = enum {
LORAMAC_HANDLER_TX_ON_TIMER,
LORAMAC_HANDLER_TX_ON_EVENT,
};
///////////////////////////////////////////////////////////////////////////////
// Imported Functions and Variables
/// Changed `[*c]c.MlmeReq_t` to `*MlmeReq_t`. Adapted from
/// https://github.com/lupyuen/zig-bl602-nuttx/blob/main/translated/lorawan_test_main.zig#L2905
extern fn DisplayMacMlmeRequestUpdate(
status: c.LoRaMacStatus_t,
mlmeReq: *MlmeReq_t,
nextTxIn: c.TimerTime_t
) void;
/// Changed `[*c]c.LmHandlerCallbacks_t` to `*LmHandlerCallbacks_t`. Adapted from
/// https://github.com/lupyuen/zig-bl602-nuttx/blob/main/translated/lorawan_test_main.zig#L2835
extern fn LmHandlerInit(
callbacks: *LmHandlerCallbacks_t,
handlerParams: [*c]c.LmHandlerParams_t
) c.LmHandlerErrorStatus_t;
/// For safety, we import these functions ourselves to enforce Null-Terminated Strings.
/// We changed `[*c]const u8` to `[*:0]const u8`
extern fn printf(format: [*:0]const u8, ...) c_int;
extern fn puts(str: [*:0]const u8) c_int;
/// LoRaWAN Event Queue
extern var event_queue: c.struct_ble_npl_eventq;
/// Aliases for Zig Standard Library
const assert = std.debug.assert;
const debug = std.log.debug;
///////////////////////////////////////////////////////////////////////////////
// Reflection
// Do Type Reflection on the imported C functions
fn reflect() void {
// We run this at Compile-Time (instead of Runtime)...
comptime {
// Allow Zig Compiler to loop up to 100,000,000 times (Default is 1,000)
@setEvalBranchQuota(100_000_000);
// Test Zig Reflection
test_reflection();
// Define the Modules and the First / Last Functions in each Module.
// We order the Modules from High-Level to Low-Level.
var all_modules = [_]Module {
// LoRaMAC Handler is the Top Level Module that drives the LoRaWAN Stack
Module {
.name = "LMHandler",
.first_function = "LmHandlerInit",
.last_function = "DisplayAppInfo",
.first_index = undefined,
.last_index = undefined,
},
// LoRaMAC Module is the implementation of the LoRaWAN Driver
Module {
.name = "LoRaMAC",
.first_function = "LoRaMacInitialization",
.last_function = "LoRaMacDeInitialization",
.first_index = undefined,
.last_index = undefined,
},
// Radio Module is the abstract interface for LoRa Radio Transceivers
Module {
.name = "Radio",
.first_function = "RadioInit",
.last_function = "RadioAddRegisterToRetentionList",
.first_index = undefined,
.last_index = undefined,
},
// SX1262 Module is the LoRa Driver for Semtech SX1262 Radio Transceiver
Module {
.name = "SX1262",
.first_function = "SX126xInit",
.last_function = "SX126xSetOperatingMode",
.first_index = undefined,
.last_index = undefined,
},
// NimBLE is the Bottom Level Module that contains Multithreading Functions like Timers and Event Queues
Module {
.name = "NimBLE",
.first_function = "TimerInit",
.last_function = "TimerGetElapsedTime",
.first_index = undefined,
.last_index = undefined,
},
};
// Set the C Declaration Index for every Module
for (all_modules) |map, m| {
// Find the C Declaration Index for the Module's First Function
if (get_decl_by_name(map.first_function)) |decl_index| {
// Set the index
all_modules[m].first_index = decl_index;
@compileLog("Found module function: ", all_modules[m].first_function, map.name, decl_index);
} else {
// Missing Declaration
@compileLog("C Declaration not found for module: ", map.name, map.first_function);
}
// Find the C Declaration Index for the Module's Last Function
if (get_decl_by_name(map.last_function)) |decl_index| {
// Set the index
all_modules[m].last_index = decl_index;
@compileLog("Found module function: ", all_modules[m].last_function, map.name, decl_index);
} else {
// Missing Declaration
@compileLog("C Declaration not found for module: ", map.name, map.first_function);
}
} // End of Module
// Start Top-Down Flowchart
@compileLog("flowchart TD;");
// Render all Modules and their Functions as Subgraphs
render_modules(&all_modules);
// Render the Call Graph for all functions in the Call Log
render_call_graph(&all_modules);
} // End of Compile-Time Code
}
/// Render all Modules and their Functions as Subgraphs
fn render_modules(all_modules: []Module) void {
comptime {
// Render every Module
for (all_modules) |module, m| {
@compileLog(" subgraph ", module.name, ";");
// For every line in the Call Log...
var call_log_split = std.mem.split(u8, call_log, "\n");
while (call_log_split.next()) |line| {
var T = @typeInfo(c);
// If the Call Log matches a C Declaration...
if (get_decl_by_name_filtered(all_modules, line)) |decl_index| {
// Get the Module Index for the C Declaration
if (get_module_by_decl(all_modules, decl_index)) |m2| {
// If the C Declaration matches our Module Index...
if (m == m2) {
// Print the Function Name
var name = T.Struct.decls[decl_index].name;
@compileLog(" ", name, ";");
}
} else {
// Missing Declaration
var name = T.Struct.decls[decl_index].name;
@compileLog("Missing Decl:", name);
}
}
} // End of Call Log
@compileLog(" end;");
} // End of Module
}
}
/// Render the Call Graph for all functions in the Call Log
fn render_call_graph(all_modules: []Module) void {
comptime {
_ = all_modules;
var prev_index: usize = 0;
// For every line in the Call Log...
var call_log_split = std.mem.split(u8, call_log, "\n");
while (call_log_split.next()) |line| {
var T2 = @typeInfo(c);
// If the the Call Log matches a C Declaration...
if (get_decl_by_name_filtered(all_modules, line)) |decl_index| {
// Skip calls to self
if (decl_index == prev_index) { continue; }
// Get the C Function Name
var name = T2.Struct.decls[decl_index].name;
var prev_name =
if (prev_index == 0) "Start"
else T2.Struct.decls[prev_index].name;
// Draw the graph: [previous function]-->[current function]
@compileLog(" ", prev_name, "-->", name, ";");
prev_index = decl_index;
}
} // End of Call Log
var T2 = @typeInfo(c);
var prev_name = T2.Struct.decls[prev_index].name;
@compileLog(" ", prev_name, "-->", "End", ";");
}
}
/// Get the index of the Module that contains the C Declaration Index
fn get_module_by_decl(all_modules: []Module, decl_index: usize) ?usize {
comptime {
var m: ?usize = null;
var diff: usize = undefined;
// Find the Module that best matches the C Declaration Index
for (all_modules) |module, m2| {
// Overshot the C Declaration Index, skip it