-
Notifications
You must be signed in to change notification settings - Fork 4
/
catena4610_simple.ino
1093 lines (922 loc) · 32.4 KB
/
catena4610_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: catena4610_simple.ino
Function:
Sensor program for Catena 4610.
Copyright notice:
This file copyright (C) 2019 - 2023 by
MCCI Corporation
3520 Krums Corners Road
Ithaca, NY 14850
See project LICENSE file for license information.
Author:
Terry Moore, MCCI Corporation June 2019
*/
#include <Catena.h>
#include <Catena_Led.h>
#include <Catena_TxBuffer.h>
#include <Catena_CommandStream.h>
#include <Catena_Mx25v8035f.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Arduino_LoRaWAN.h>
#include <Catena_Si1133.h>
#include <Catena-SHT3x.h>
#include <mcci_ltr_329als.h>
#include <lmic.h>
#include <hal/hal.h>
#include <mcciadk_baselib.h>
#include <Catena_FlashParam.h>
#include <Catena_Log.h>
#include <cmath>
#include <type_traits>
using namespace McciCatena;
using namespace Mcci_Ltr_329als;
/****************************************************************************\
|
| Manifest Constants & Typedefs
|
\****************************************************************************/
static constexpr uint8_t kMessageFormatV2 = 0x1A;
enum class Flags : uint8_t
{
Vbat = 1 << 0, // Battery voltage
Vcc = 1 << 1, // system voltage
Boot = 1 << 2, // boot count
Env = 1 << 3, // temperature, humidity
Light = 1 << 4, // light (lux))
};
constexpr Flags operator| (const Flags lhs, const Flags rhs)
{
return Flags(uint8_t(lhs) | uint8_t(rhs));
};
inline Flags operator|= (Flags &lhs, const Flags &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;
/****************************************************************************\
|
| 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.3.0";
/****************************************************************************\
|
| 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;
// 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
Adafruit_BME280 gBme; // The default initalizer creates an I2C connection
// The LUX sensor
Catena_Si1133 gSi1133;
// SHT temperature sensor/humidity Sensor
using cTemperatureSensor = McciCatenaSht3x::cSHT3x;
cTemperatureSensor gTemperatureSensor {Wire};
// LTR329 LUX sensor
Ltr_329als gLtr {Wire};
Mcci_Ltr_329als_Regs::AlsContr_t gAlsCtrl;
bool fTemperature;
bool fLight;
SPIClass gSPI2(
Catena::PIN_SPI2_MOSI,
Catena::PIN_SPI2_MISO,
Catena::PIN_SPI2_SCK
);
// The flash
Catena_Mx25v8035f gFlash;
bool fFlash;
// 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_bme280();
setup_light();
}
else
{
setup_ltr329();
setup_sht3x();
}
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 4610 version 1 (rev C or earlier)!\n"
);
boardRev = 2;
}
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_bme280(void)
{
if (gBme.begin(BME280_ADDRESS, Adafruit_BME280::OPERATING_MODE::Sleep))
{
fTemperature = true;
gCatena.SafePrintf("Temperature/Humidity sensor found\n");
}
else
{
fTemperature = false;
gCatena.SafePrintf("No Temperature/Humidity sensor found: check hardware\n");
}
}
void setup_flash(void)
{
if (gFlash.begin(&gSPI2, Catena::PIN_SPI2_FLASH_SS))
{
fFlash = true;
gFlash.powerDown();
gCatena.SafePrintf("FLASH found, put power down\n");
}
else
{
fFlash = false;
gFlash.end();
gSPI2.end();
gCatena.SafePrintf("No FLASH found: check hardware\n");
}
}
void setup_sht3x(void)
{
if (gTemperatureSensor.begin())
{
fTemperature = true;
gCatena.SafePrintf("Temperature/Humidity sensor found\n");
}
else
{
fTemperature = false;
gCatena.SafePrintf("No Temperature/Humidity 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;
}
}
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();
}
}
}
// 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)
{
bool fVersion2 = false;
if (!isVersion2())
fVersion2 = false;
else
fVersion2 = true;
if (fLight && !fVersion2)
{
gSi1133.start(true);
}
b.begin();
Flags flag;
flag = Flags(0);
if (!fVersion2)
{
b.put(FormatSensor2); /* the flag for this record format */
}
else
{
b.put(kMessageFormatV2); /* the flag for this record format */
}
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 |= Flags::Vbat;
// 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 |= Flags::Boot;
}
if (!fVersion2)
{
if (fTemperature)
{
Adafruit_BME280::Measurements m = gBme.readTemperaturePressureHumidity();
// temperature is 2 bytes from -0x80.00 to +0x7F.FF degrees C
// pressure is 2 bytes, hPa * 10.
// humidity is one byte, where 0 == 0/256 and 0xFF == 255/256.
gCatena.SafePrintf(
"BME280: T: %d P: %d RH: %d\n",
(int) m.Temperature,
(int) m.Pressure,
(int) m.Humidity
);
b.putT(m.Temperature);
b.putP(m.Pressure);
b.putRH(m.Humidity);
flag |= Flags::Env;
}
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(LMIC_f2uflt16(data[1] / pow(2.0, 24)));
flag |= Flags::Light;
}
}
else
{
if (fTemperature)
{
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, directly encode it.
b.put2uf((m.Humidity / 100.0f) * 65535.0f);
flag |= Flags::Env;
}
}
else
{
gCatena.SafePrintf(
"Env sensor not found\n"
);
}
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 |= Flags::Light;
}
}
}
*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;
if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fConfirmedUplink))
{
gCatena.SafePrintf("requesting confirmed tx\n");
fConfirmed = true;
}
constexpr unsigned kUplinkPort = 1;
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);
uint32_t const sleepInterval = CATCFG_GetInterval(
fDeepSleepTest ? CATCFG_T_CYCLE_TEST : gTxCycle
);
/* ok... now it's time for a deep sleep */
gLed.Set(LedPattern::Off);
deepSleepPrepare();
/* sleep */
gCatena.Sleep(sleepInterval);
/* recover from sleep */
deepSleepRecovery();
/* and now... we're awake again. trigger another measurement */
sleepDoneCb(pJob);
}
void deepSleepPrepare(void)
{
Serial.end();
Wire.end();
SPI.end();
if (fFlash)
gSPI2.end();
}
void deepSleepRecovery(void)
{
Serial.begin();
Wire.begin();
SPI.begin();
if (fFlash)
gSPI2.begin();
}
void doLightSleep(osjob_t *pJob)
{
uint32_t interval = sec2osticks(CATCFG_GetInterval(gTxCycle));
gLed.Set(LedPattern::Sleeping);
if (gCatena.GetOperatingFlags() &
static_cast<uint32_t>(gCatena.OPERATING_FLAGS::fQuickLightSleep))
{
interval = 1;
}
gLed.Set(LedPattern::Sleeping);
os_setTimedCallback(
&sensorJob,
os_getTime() + interval,
sleepDoneCb
);
}
static void sleepDoneCb(
osjob_t *pJob
)
{
gLed.Set(LedPattern::WarmingUp);
os_setTimedCallback(
&sensorJob,
os_getTime() + sec2osticks(CATCFG_T_WARMUP),
warmupDoneCb
);
}
static void warmupDoneCb(
osjob_t *pJob
)
{
startSendingUplink();
}
static void receiveMessage(
void *pContext,
uint8_t port,
const uint8_t *pMessage,
size_t nMessage
)
{
unsigned txCycle;
unsigned txCount;
if (port == 0)
{
gCatena.SafePrintf("MAC message:");
for (unsigned i = 0; i < LMIC.dataBeg; ++i)
{
gCatena.SafePrintf(" %02x", LMIC.frame[i]);
}
gCatena.SafePrintf("\n");
return;
}
else if (! (port == 1 && 2 <= nMessage && nMessage <= 3))
{
gCatena.SafePrintf("invalid message port(%02x)/length(%x)\n",
port, nMessage
);
return;
}
txCycle = (pMessage[0] << 8) | pMessage[1];
if (txCycle < CATCFG_T_MIN || txCycle > CATCFG_T_MAX)
{
gCatena.SafePrintf("tx cycle time out of range: %u\n", txCycle);
return;
}
// byte [2], if present, is the repeat count.
// explicitly sending zero causes it to stick.
txCount = CATCFG_INTERVAL_COUNT;
if (nMessage >= 3)
{
txCount = pMessage[2];
}
setTxCycleTime(txCycle, txCount);
}