-
Notifications
You must be signed in to change notification settings - Fork 10
/
catena4618m201_simple.ino
1217 lines (1021 loc) · 35.8 KB
/
catena4618m201_simple.ino
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
/*
Module: catena4618m201_simple.ino
Function:
Sensor program for Catena 4618m201.
Copyright notice:
This file copyright (C) 2019 - 2024 by
MCCI Corporation
3520 Krums Corners Road
Ithaca, NY 14850
See project LICENSE file for license information.
Author:
Terry Moore, MCCI Corporation June 2019
Revision history:
See https://github.com/mcci-catena/Catena-Sketches
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_TxBuffer.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Catena_Download.h>
#include <Catena_BootloaderApi.h>
#include <Wire.h>
#include <Arduino_LoRaWAN.h>
#include <Catena_Si1133.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <mcci_ltr_329als.h>
#include <Catena_FlashParam.h>
#include <Catena_Log.h>
#include <cmath>
#include <type_traits>
using namespace McciCatena;
using namespace Mcci_Ltr_329als;
#if defined(ARDUINO_MCCI_CATENA_4618)
# include <Catena-SHT3x.h>
using cTemperatureSensor = McciCatenaSht3x::cSHT3x;
using namespace McciCatenaSht3x;
#elif defined(ARDUINO_MCCI_CATENA_4617)
# include <Catena-HS300x.h>
using cTemperatureSensor = McciCatenaHs300x::cHS300x;
using namespace McciCatenaHs300x;
#else
# error Platform not supported
#endif
/****************************************************************************\
|
| MANIFEST CONSTANTS & TYPEDEFS
|
\****************************************************************************/
constexpr uint8_t kUplinkPortV1 = 3;
constexpr uint8_t kUplinkPortV2 = 6;
enum class FlagsSensorPort3 : uint8_t
{
FlagVbat = 1 << 0,
FlagVcc = 1 << 1,
FlagBoot = 1 << 2,
FlagTH = 1 << 3, // temperature, humidity
FlagLight = 1 << 4, // Si1133 "ir", "white", "uv"
FlagVbus = 1 << 5, // Vbus input
};
constexpr FlagsSensorPort3 operator| (const FlagsSensorPort3 lhs, const FlagsSensorPort3 rhs)
{
return FlagsSensorPort3(uint8_t(lhs) | uint8_t(rhs));
};
FlagsSensorPort3 operator|= (FlagsSensorPort3 &lhs, const FlagsSensorPort3 &rhs)
{
lhs = lhs | rhs;
return lhs;
};
/* adjustable timing parameters */
enum {
// set this to interval between transmissions, in seconds
// Actual time will be a little longer because have to
// add measurement and broadcast time, but we attempt
// to compensate for the gross effects below.
CATCFG_T_CYCLE = 6 * 60, // every 6 minutes
CATCFG_T_CYCLE_TEST = 30, // every 30 seconds
CATCFG_T_CYCLE_INITIAL = 30, // every 30 seconds initially
CATCFG_INTERVAL_COUNT_INITIAL = 10, // repeat for 5 minutes
CATCFG_T_REBOOT = 30 * 24 * 60 * 60, // reboot every 30 days
};
/* additional timing parameters; ususually you don't change these. */
enum {
CATCFG_T_WARMUP = 1,
CATCFG_T_SETTLE = 5,
CATCFG_T_OVERHEAD = (CATCFG_T_WARMUP + CATCFG_T_SETTLE + 4),
CATCFG_T_MIN = CATCFG_T_OVERHEAD,
CATCFG_T_MAX = CATCFG_T_CYCLE < 60 * 60 ? 60 * 60 : CATCFG_T_CYCLE, // normally one hour max.
CATCFG_INTERVAL_COUNT = 30,
};
constexpr uint32_t CATCFG_GetInterval(uint32_t tCycle)
{
return (tCycle < CATCFG_T_OVERHEAD + 1)
? 1
: tCycle - CATCFG_T_OVERHEAD
;
}
enum {
CATCFG_T_INTERVAL = CATCFG_GetInterval(CATCFG_T_CYCLE),
};
// forwards
static void settleDoneCb(osjob_t *pSendJob);
static void warmupDoneCb(osjob_t *pSendJob);
static void txNotProvisionedCb(osjob_t *pSendJob);
static void sleepDoneCb(osjob_t *pSendJob);
static Arduino_LoRaWAN::SendBufferCbFn sendBufferDoneCb;
static Arduino_LoRaWAN::ReceivePortBufferCbFn receiveMessage;
/****************************************************************************\
|
| Command table
|
\****************************************************************************/
// forward reference to the command function
static cCommandStream::CommandFn cmdUpdate;
// the individual commmands are put in this table
static const cCommandStream::cEntry sMyExtraCommmands[] =
{
{ "fallback", cmdUpdate },
{ "update", cmdUpdate },
// other commands go here....
};
/* a top-level structure wraps the above and connects to the system table */
/* it optionally includes a "first word" so you can for sure avoid name clashes */
static cCommandStream::cDispatch
sMyExtraCommands_top(
sMyExtraCommmands, /* this is the pointer to the table */
sizeof(sMyExtraCommmands), /* this is the size of the table */
"system" /* this is the "first word" for all the commands in this table*/
);
/****************************************************************************\
|
| handy constexpr to extract the base name of a file
|
\****************************************************************************/
// two-argument version: first arg is what to return if we don't find
// a directory separator in the second part.
static constexpr const char *filebasename(const char *s, const char *p)
{
return p[0] == '\0' ? s :
(p[0] == '/' || p[0] == '\\') ? filebasename(p + 1, p + 1) :
filebasename(s, p + 1) ;
}
static constexpr const char *filebasename(const char *s)
{
return filebasename(s, s);
}
/****************************************************************************\
|
| READ-ONLY DATA
|
\****************************************************************************/
static const char sVersion[] = "0.4.1";
/****************************************************************************\
|
| VARIABLES
|
\****************************************************************************/
// the primary object
Catena gCatena;
//
// the LoRaWAN backhaul. Note that we use the
// Catena version so it can provide hardware-specific
// information to the base class.
//
Catena::LoRaWAN gLoRaWAN;
//
// the LED
//
StatusLed gLed (Catena::PIN_STATUS_LED);
// concrete type for flash parameters
using Flash_t = McciCatena::FlashParamsStm32L0_t;
using ParamBoard_t = Flash_t::ParamBoard_t;
using PageEndSignature1_t = Flash_t::PageEndSignature1_t;
using ParamDescId = Flash_t::ParamDescId;
// flag to disable LED
bool fDisableLED;
// set flag if Network time set to RTC
bool fNwTimeSet;
// set start time when network time is being set
std::uint32_t startTime;
// get Rev number
std::uint8_t boardRev;
// fetch the signature
const PageEndSignature1_t * const pRomSig =
reinterpret_cast<const PageEndSignature1_t *>(Flash_t::kPageEndSignature1Address);
// get pointer to memory block */
uint32_t descAddr = pRomSig->getParamPointer();
// find the serial number (must be first)
const ParamBoard_t * const pBoard = reinterpret_cast<const ParamBoard_t *>(descAddr);
// The temperature/humidity sensor
cTemperatureSensor gTemperatureSensor {Wire};
bool fTemperatureSensor;
// The LUX sensor
Catena_Si1133 gSi1133;
bool fLight;
// LTR329 LUX sensor
Ltr_329als gLtr {Wire};
Mcci_Ltr_329als_Regs::AlsContr_t gAlsCtrl;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK
);
// The flash
Catena_Mx25v8035f gFlash;
bool gfFlash;
/* instantiate a serial object */
cSerial<decltype(Serial)> gSerial(Serial);
/* instantiate the bootloader API */
cBootloaderApi gBootloaderApi;
/* instantiate the downloader */
cDownload gDownload;
// USB power
bool fUsbPower;
// have we printed the sleep info?
bool g_fPrintedSleeping = false;
// the job that's used to synchronize us with the LMIC code
static osjob_t sensorJob;
void sensorJob_cb(osjob_t *pJob);
// the cycle time to use
unsigned gTxCycle;
// remaining before we reset to default
unsigned gTxCycleCount;
/*
Name: setup()
Function:
Arduino setup function.
Definition:
void setup(
void
);
Description:
This function is called by the Arduino framework after
basic framework has been initialized. We initialize the sensors
that are present on the platform, set up the LoRaWAN connection,
and (ultimately) return to the framework, which then calls loop()
forever.
Returns:
No explicit result.
*/
void setup(void)
{
gCatena.begin();
setup_platform();
setup_flash();
setup_rev();
if (!isVersion2())
{
setup_light();
}
else
{
setup_ltr329();
}
setup_temp_rh();
setup_download();
setup_uplink();
}
void setup_platform(void)
{
#ifdef USBCON
// if running unattended, don't wait for USB connect.
if (! (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)))
{
while (!Serial)
/* wait for USB attach */
yield();
}
#endif
gCatena.SafePrintf("\n");
gCatena.SafePrintf("-------------------------------------------------------------------------------\n");
gCatena.SafePrintf("This is %s V%s.\n", filebasename(__FILE__), sVersion);
{
char sRegion[16];
gCatena.SafePrintf("Target network: %s / %s\n",
gLoRaWAN.GetNetworkName(),
gLoRaWAN.GetRegionString(sRegion, sizeof(sRegion))
);
}
gCatena.SafePrintf("Enter 'help' for a list of commands.\n");
gCatena.SafePrintf("(remember to select 'Line Ending: Newline' at the bottom of the monitor window.)\n");
gCatena.SafePrintf("SYSCLK: %u MHz\n", unsigned(gCatena.GetSystemClockRate() / (1000 * 1000)));
#ifdef USBCON
gCatena.SafePrintf("USB enabled\n");
#else
gCatena.SafePrintf("USB disabled\n");
#endif
gLoRaWAN.SetReceiveBufferBufferCb(receiveMessage);
setTxCycleTime(CATCFG_T_CYCLE_INITIAL, CATCFG_INTERVAL_COUNT_INITIAL);
Catena::UniqueID_string_t CpuIDstring;
gCatena.SafePrintf(
"CPU Unique ID: %s\n",
gCatena.GetUniqueIDstring(&CpuIDstring)
);
gCatena.SafePrintf("--------------------------------------------------------------------------------\n");
gCatena.SafePrintf("\n");
// set up the LED
gLed.begin();
gCatena.registerObject(&gLed);
gLed.Set(LedPattern::FastFlash);
// set up LoRaWAN
gCatena.SafePrintf("LoRaWAN init: ");
if (!gLoRaWAN.begin(&gCatena))
{
gCatena.SafePrintf("failed\n");
}
else
{
gCatena.SafePrintf("succeeded\n");
}
gCatena.registerObject(&gLoRaWAN);
/* find the platform */
const Catena::EUI64_buffer_t *pSysEUI = gCatena.GetSysEUI();
uint32_t flags;
const CATENA_PLATFORM * const pPlatform = gCatena.GetPlatform();
if (pPlatform)
{
gCatena.SafePrintf("EUI64: ");
for (unsigned i = 0; i < sizeof(pSysEUI->b); ++i)
{
gCatena.SafePrintf("%s%02x", i == 0 ? "" : "-", pSysEUI->b[i]);
}
gCatena.SafePrintf("\n");
flags = gCatena.GetPlatformFlags();
gCatena.SafePrintf(
"Platform Flags: %#010x\n",
flags
);
gCatena.SafePrintf(
"Operating Flags: %#010x\n",
gCatena.GetOperatingFlags()
);
}
else
{
gCatena.SafePrintf("**** no platform, check provisioning ****\n");
flags = 0;
}
}
void setup_rev()
{
if (!flashParam())
{
gCatena.SafePrintf(
"**Unable to fetch flash parameters, assuming 4618 version 1 (rev A)!\n"
);
boardRev = 0;
}
else {
printBoardInfo();
}
}
void setup_light(void)
{
if (gSi1133.begin())
{
fLight = true;
gSi1133.configure(0, CATENA_SI1133_MODE_SmallIR);
gSi1133.configure(1, CATENA_SI1133_MODE_White);
gSi1133.configure(2, CATENA_SI1133_MODE_UV);
gCatena.SafePrintf("Light sensor found\n");
}
else
{
fLight = false;
gCatena.SafePrintf("No Light Sensor found: check hardware\n");
}
}
void setup_ltr329(void)
{
if (! gLtr.begin())
{
gCatena.SafePrintf("No Light sensor found: check hardware\n");
fLight = false;
}
else
{
gCatena.SafePrintf("Light sensor found\n");
fLight = true;
}
}
void setup_temp_rh(void)
{
if (gTemperatureSensor.begin())
{
fTemperatureSensor = true;
gCatena.SafePrintf("Temperature/Humidity sensor found\n");
}
else
{
fTemperatureSensor = false;
gCatena.SafePrintf("No temperature/humidity sensor found: check hardware\n");
}
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS))
{
gfFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else
{
gfFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
uint32_t gRebootMs;
void setup_uplink(void)
{
LMIC_setClockError(1*65536/100);
/* figure out when to reboot */
gRebootMs = (CATCFG_T_REBOOT + os_getRndU2() - 32768) * 1000;
/* trigger a join by sending the first packet */
if (!(gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest)))
{
if (! gLoRaWAN.IsProvisioned())
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
else
{
gLed.Set(LedPattern::Joining);
/* trigger a join by sending the first packet */
startSendingUplink();
}
}
}
void setup_download()
{
/* add our application-specific commands */
gCatena.addCommands(
/* name of app dispatch table, passed by reference */
sMyExtraCommands_top,
/*
|| optionally a context pointer using static_cast<void *>().
|| normally only libraries (needing to be reentrant) need
|| to use the context pointer.
*/
nullptr
);
gDownload.begin(gFlash, gBootloaderApi);
}
/* process "system" "update" / "system" "fallback" -- args are ignored */
// argv[0] is "update" or "fallback"
// argv[1..argc-1] are the (ignored) arguments
static cCommandStream::CommandStatus cmdUpdate(
cCommandStream *pThis,
void *pContext,
int argc,
char **argv
)
{
cCommandStream::CommandStatus result;
pThis->printf(
"Update firmware: echo off, timeout %d seconds\n",
(cDownload::kTransferTimeoutMs + 500) / 1000
);
if (! gfFlash)
{
pThis->printf(
"** flash not found at init time, can't update **\n"
);
return cCommandStream::CommandStatus::kIoError;
}
gSPI2.begin();
gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS);
struct context_t
{
cCommandStream *pThis;
bool fWorking;
cDownload::Status_t status;
cCommandStream::CommandStatus cmdStatus;
cDownload::Request_t request;
};
context_t context { pThis, true };
auto doneFn =
[](void *pUserData, cDownload::Status_t status) -> void
{
context_t * const pCtx = (context_t *)pUserData;
cCommandStream * const pThis = pCtx->pThis;
cCommandStream::CommandStatus cmdStatus;
cmdStatus = cCommandStream::CommandStatus::kSuccess;
if (status != cDownload::Status_t::kSuccessful)
{
pThis->printf(
"download error, status %u\n",
unsigned(status)
);
cmdStatus = cCommandStream::CommandStatus::kIoError;
}
pCtx->cmdStatus = cmdStatus;
pCtx->fWorking = false;
};
if (gDownload.evStartSerialDownload(
argv[0][0] == 'u' ? cDownload::DownloadRq_t::GetUpdate
: cDownload::DownloadRq_t::GetFallback,
gSerial,
context.request,
doneFn,
(void *) &context)
)
{
while (context.fWorking)
gCatena.poll();
result = context.cmdStatus;
}
else
{
pThis->printf(
"download launch failure\n"
);
result = cCommandStream::CommandStatus::kInternalError;
}
gFlash.powerDown();
gSPI2.end();
return result;
}
// The Arduino loop routine -- in our case, we just drive the other loops.
// If we try to do too much, we can break the LMIC radio. So the work is
// done by outcalls scheduled from the LMIC os loop.
void fillBuffer(TxBuffer_t &b);
void loop()
{
gCatena.poll();
/* for mfg test, don't tx, just fill -- this causes output to Serial */
if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fManufacturingTest))
{
TxBuffer_t b;
fillBuffer(b);
delay(1000);
// since the light sensor was stopped in fillbuffer, restart it.
}
}
void fillBuffer(TxBuffer_t &b)
{
if (fLight&& !isVersion2())
gSi1133.start(true);
b.begin();
FlagsSensorPort3 flag;
flag = FlagsSensorPort3(0);
// we have no format byte for this.
uint8_t * const pFlag = b.getp();
b.put(0x00); /* will be set to the flags */
// vBat is sent as 5000 * v
float vBat = gCatena.ReadVbat();
gCatena.SafePrintf("vBat: %d mV\n", (int) (vBat * 1000.0f));
b.putV(vBat);
flag |= FlagsSensorPort3::FlagVbat;
// vBus is sent as 5000 * v
float vBus = gCatena.ReadVbus();
gCatena.SafePrintf("vBus: %d mV\n", (int) (vBus * 1000.0f));
fUsbPower = (vBus > 3.0) ? true : false;
uint32_t bootCount;
if (gCatena.getBootCount(bootCount))
{
b.putBootCountLsb(bootCount);
flag |= FlagsSensorPort3::FlagBoot;
}
if (fTemperatureSensor)
{
cTemperatureSensor::Measurements m;
bool fResult = gTemperatureSensor.getTemperatureHumidity(m);
if (fResult)
{
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// humidity is 2 bytes, where 0 == 0/0xFFFF and 0xFFFFF == 1.
gCatena.SafePrintf(
"Env: T: %d RH: %d\n",
(int) (m.Temperature + 0.5f),
(int) m.Humidity
);
b.putT(m.Temperature);
// no method for 2-byte RH, direct encode it.
b.put2uf((m.Humidity / 100.0f) * 65535.0f);
flag |= FlagsSensorPort3::FlagTH;
}
else
{
gCatena.SafePrintf(
"Env sensor not found\n"
);
}
}
if (!isVersion2())
{
if (fLight)
{
/* Get a new sensor event */
uint16_t data[3];
while (! gSi1133.isOneTimeReady())
{
yield();
}
gSi1133.readMultiChannelData(data, 3);
gSi1133.stop();
gCatena.SafePrintf(
"Si1133: %u IR, %u White, %u UV\n",
data[0],
data[1],
data[2]
);
b.putLux(data[0]);
b.putLux(data[1]);
b.putLux(data[2]);
flag |= FlagsSensorPort3::FlagLight;
}
}
else
{
if (fLight)
{
bool fError;
static constexpr float kMax_Gain_96 = 640.0f;
static constexpr float kMax_Gain_48 = 1280.0f;
static constexpr float kMax_Gain_8 = 7936.0f;
static constexpr float kMax_Gain_4 = 16128.0f;
static constexpr float kMax_Gain_2 = 32512.0f;
static constexpr float kMax_Gain_1 = 65535.0f;
// start a measurement
if (! gLtr.startSingleMeasurement())
gCatena.SafePrintf("gLtr.startSingleMeasurement() failed\n");
// wait for measurement to complete.
while (! gLtr.queryReady(fError))
{
if (fError)
break;
}
if (fError)
{
gCatena.SafePrintf("queryReady() failed\n");
}
else
{
float currentLux = gLtr.getLux();
gCatena.SafePrintf(
"LTR329: %d Lux\n",
(int)currentLux
);
b.put3f(currentLux);
if (currentLux <= kMax_Gain_96)
gAlsCtrl.setGain(96);
else if (currentLux <= kMax_Gain_48)
gAlsCtrl.setGain(48);
else if (currentLux <= kMax_Gain_8)
gAlsCtrl.setGain(8);
else if (currentLux <= kMax_Gain_4)
gAlsCtrl.setGain(4);
else if (currentLux <= kMax_Gain_2)
gAlsCtrl.setGain(2);
else
gAlsCtrl.setGain(1);
flag |= FlagsSensorPort3::FlagLight;
}
}
}
b.putV(vBus);
flag |= FlagsSensorPort3::FlagVbus;
*pFlag = uint8_t(flag);
}
void startSendingUplink(void)
{
TxBuffer_t b;
LedPattern savedLed = gLed.Set(LedPattern::Measuring);
fillBuffer(b);
if (savedLed != LedPattern::Joining)
gLed.Set(LedPattern::Sending);
else
gLed.Set(LedPattern::Joining);
bool fConfirmed = false;
uint8_t kUplinkPort;
if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fConfirmedUplink))
{
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
if (!isVersion2())
kUplinkPort = kUplinkPortV1;
else
kUplinkPort = kUplinkPortV2;
gLoRaWAN.SendBuffer(b.getbase(), b.getn(), sendBufferDoneCb, NULL, fConfirmed, kUplinkPort);
}
static void sendBufferDoneCb(
void *pContext,
bool fStatus
)
{
osjobcb_t pFn;
gLed.Set(LedPattern::Settling);
pFn = settleDoneCb;
if (! fStatus)
{
if (!gLoRaWAN.IsProvisioned())
{
// we'll talk about it at the callback.
pFn = txNotProvisionedCb;
// but prevent join attempts now.
gLoRaWAN.Shutdown();
}
else
gCatena.SafePrintf("send buffer failed\n");
}
os_setTimedCallback(
&sensorJob,
os_getTime()+sec2osticks(CATCFG_T_SETTLE),
pFn
);
}
static void txNotProvisionedCb(
osjob_t *pSendJob
)
{
gCatena.SafePrintf("LoRaWAN not provisioned yet. Use the commands to set it up.\n");
gLoRaWAN.Shutdown();
gLed.Set(LedPattern::NotProvisioned);
}
static void settleDoneCb(
osjob_t *pSendJob
)
{
const bool fDeepSleep = checkDeepSleep();
if (uint32_t(millis()) > gRebootMs)
{
// time to reboot
NVIC_SystemReset();
}
if (! g_fPrintedSleeping)
doSleepAlert(fDeepSleep);
/* count what we're up to */
updateSleepCounters();
if (fDeepSleep)
doDeepSleep(pSendJob);
else
doLightSleep(pSendJob);
}
bool checkDeepSleep(void)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDeepSleepTest);
bool fDeepSleep;
if (fDeepSleepTest)
{
fDeepSleep = true;
}
#ifdef USBCON
else if (Serial.dtr())
{
fDeepSleep = false;
}
#endif
else if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDisableDeepSleep))
{
fDeepSleep = false;
}
else if ((gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fUnattended)) != 0)
{
fDeepSleep = true;
}
else
{
fDeepSleep = false;
}
return fDeepSleep;
}
void doSleepAlert(const bool fDeepSleep)
{
g_fPrintedSleeping = true;
if (fDeepSleep)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDeepSleepTest);
const uint32_t deepSleepDelay = fDeepSleepTest ? 10 : 30;
gCatena.SafePrintf("using deep sleep in %u secs"
#ifdef USBCON
" (USB will disconnect while asleep)"
#endif
": ",
deepSleepDelay
);
// sleep and print
gLed.Set(LedPattern::TwoShort);
for (auto n = deepSleepDelay; n > 0; --n)
{
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 1000)
{
gCatena.poll();
yield();
}
gCatena.SafePrintf(".");
}
gCatena.SafePrintf("\nStarting deep sleep.\n");
uint32_t tNow = millis();
while (uint32_t(millis() - tNow) < 100)
{
gCatena.poll();
yield();
}
}
else
gCatena.SafePrintf("using light sleep\n");
}
void updateSleepCounters(void)
{
// update the sleep parameters
if (gTxCycleCount > 1)
{
// values greater than one are decremented and ultimately reset to default.
--gTxCycleCount;
}
else if (gTxCycleCount == 1)
{
// it's now one (otherwise we couldn't be here.)
gCatena.SafePrintf("resetting tx cycle to default: %u\n", CATCFG_T_CYCLE);
gTxCycleCount = 0;
gTxCycle = CATCFG_T_CYCLE;
}
else
{
// it's zero. Leave it alone.
}
}
void doDeepSleep(osjob_t *pJob)
{
bool const fDeepSleepTest = gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fDeepSleepTest);