This repository has been archived by the owner on Oct 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
BresserWeatherSensorTTN.ino
2120 lines (1884 loc) · 74.7 KB
/
BresserWeatherSensorTTN.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
///////////////////////////////////////////////////////////////////////////////
// BresserWeatherSensorTTN.ino
//
// Bresser 5-in-1/6-in-1 868 MHz Weather Sensor Radio Receiver
// based on ESP32 and RFM95W -
// sends data to a LoRaWAN network (e.g. The Things Network)
//
// The RFM95W radio transceiver is used
// in FSK mode to receive weather sensor data
// and
// in LoRaWAN mode to connect to a LoRaWAN network
//
// Based on:
// ---------
// Bresser5in1-CC1101 by Sean Siford (https://github.com/seaniefs/Bresser5in1-CC1101)
// https://github.com/merbanan/rtl_433/blob/master/src/devices/bresser_6in1.c
// RadioLib by Jan Gromeš (https://github.com/jgromes/RadioLib)
// MCCI LoRaWAN LMIC library by Thomas Telkamp and Matthijs Kooijman / Terry Moore, MCCI (https://github.com/mcci-catena/arduino-lmic)
// MCCI Arduino LoRaWAN Library by Terry Moore, MCCI (https://github.com/mcci-catena/arduino-lorawan)
// Lora-Serialization by Joscha Feth (https://github.com/thesolarnomad/lora-serialization)
// ESP32Time by Felix Biego (https://github.com/fbiego/ESP32Time)
// OneWireNg by Piotr Stolarz (https://github.com/pstolarz/OneWireNg)
// DallasTemperature / Arduino-Temperature-Control-Library by Miles Burton (https://github.com/milesburton/Arduino-Temperature-Control-Library)
//
// Library dependencies (tested versions):
// ---------------------------------------
// (install via normal Arduino Library installer:)
// MCCI Arduino Development Kit ADK 0.2.2
// MCCI LoRaWAN LMIC library 4.1.1
// MCCI Arduino LoRaWAN Library 0.10.0
// RadioLib 6.6.0
// LoRa_Serialization 3.2.1
// ESP32Time 2.0.6
// BresserWeatherSensorReceiver 0.28.5
// OneWireNg 0.13.3 (optional)
// DallasTemperature 3.9.0 (optional)
// NimBLE-Arduino 1.4.1 (optional)
// ATC MiThermometer 0.4.2 (optional)
// Theengs Decoder 1.5.7 (optional)
//
// (installed from ZIP file:)
// DistanceSensor_A02YYUW 1.0.2 (optional)
//
// created: 06/2022
//
//
// MIT License
//
// Copyright (c) 2022 Matthias Prinke
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
// History:
//
// 20220620 Created
// 20220816 Added support of multiple Bresser 868 MHz sensors;
// e.g. weather sensor and soil temperature/moisture sensor
// 20220825 Added time keeping with RTC and synchronization to network time
// 20220915 Added monthly/daily/hourly precipitation values
// 20221010 Changed cMyLoRaWAN to inherit from Arduino_LoRaWAN_network
// instead of Arduino_LoRaWAN_ttn
// Moved LoRaWAN network selection to BresserWeatherSensorTTNCfg.h
// Changed LoRaWAN message size to actual payload size
// 20221011 Replaced Timezone library by ESP32's internal TZ handling
// 20221109 Updated BresserWeatherSensorReceiver to v0.4.0
// 20221117 Implemented wake-up to fixed time scheme
// Added energy saving modes
// 20221228 Modified DEBUG_PRINTF/DEBUG_PRINTF_TS macros to use
// Arduino logging functions
// 20221230 Added compile time option to enter deep sleep mode
// if receiving weather sensor data was not successful
// 20221231 Added setting of RTC via downlink
// 20230101 Added remote configuration via LoRaWAN downlink
// 20230112 Fixed rain gauge update in case RTC was set by LoRaWAN downlink
// Added note regarding LMIC_ENABLE_DeviceTimeReq
// 20230121 Added configuration for TTGO LoRa32 V1
// 20230208 Added configurations for TTGO LoRa32 V2 and V2.1
// 20230209 Added configuration for Adafruit Feather ESP32-S2 with RFM95W FeatherWing
// Added configuration for Adafruit Huzzah ESP32 Feather with RFM95W FeatherWing
// 20230211 Added integration of Theengs Decoder (https://github.com/theengs/decoder)
// for support of additional BLE sensors
// 20230217 Added integration of A02YYUW (DFRobot SEN0311)
// ultrasonic distance sensor
// (https://wiki.dfrobot.com/_A02YYUW_Waterproof_Ultrasonic_Sensor_SKU_SEN0311)
// 20230304 Added configuration for Heltec Wireless Stick
// 20230614 Added configuration for Heltec WiFi LoRa 32
// 20230705 Updated library versions
// 20230714 Added integration of Bresser Lightning Sensor
// 20230717 Added sensor startup to rain gauge
// 20230821 Implemented downlink commands CMD_GET_DATETIME & CMD_GET_CONFIG,
// added CMD_RESET_RAINGAUGE <flags>
// 20230910 Added configuration for Firebeetle ESP32 with Firebeetle Cover LoRa
// (FIREBEETLE_COVER_LORA)
// 20230927 Added configuration for Adafruit Feather RP2040 with RFM95W FeatherWing
// (INCOMPLETE & NOT FULLY TESTED!)
// 20231004 Replaced DEBUG_PRINTF/DEBUG_PRINTF_TS by macros log_i/../log_d/log_v
// 20231005 [RP2040] Implemented storing of LoRaWAN session state using preferences
// (instead of ESP32's RTC RAM)
// 20231006 [RP2040] Added sleep mode and wake-up by RTC
// 20231008 [RP2040] Added configuration for distance sensor
// 20231009 Renamed FIREBEETLE_COVER_LORA in FIREBEETLE_ESP32_COVER_LORA
// 20231223 Updated to BresserWeatherSensorReceiver v0.20.1
// 20240116 Fixed rain counter overflow value for SENSOR_TYPE_WEATHER0
// (see https://github.com/matthias-bs/BresserWeatherSensorReceiver/releases/tag/v0.5.1)
// 20240222 Added weatherSensor.clearSlots() (part of fix for #82), added workaround for (#81)
// 20240303 Added evaluation of temp_ok/humidity_ok/rain_ok (#82)
// 20240325 Added configuration for M5Stack Core2 with M5Stack Module LoRa868
// 20240606 Replaced ESP32AnalogRead by analogReadMilliVolts()
// Updated board configurations after changes in
// Arduino ESP32 package v3.0.X
//
// ToDo:
// - Split this file
//
// Notes:
// - Pin mapping of radio transceiver module is done in two places:
// - MCCI Arduino LoRaWAN Library: this file (see below)
// - BresserWeatherSensorReceiver Library: WeatherSensorCfg.h
// - After a successful transmission, the controller can go into deep sleep
// - If joining the network or transmitting uplink data fails,
// the controller can go into deep sleep
// - Weather sensor data is only received at startup; this avoids
// reconfiguration of the RFM95W module and its SW drivers -
// i.e. to work as a weather data relay to TTN, enabling sleep mode
// is basically the only useful option
// - The ESP32's RTC RAM/the RP2040's Flash (via Preferences library) is used
// to store information about the LoRaWAN network session;
// this speeds up the connection after a restart significantly
// - The ESP32's Bluetooth LE interface is used to access sensor data (option)
// - To enable Network Time Requests:
// #define LMIC_ENABLE_DeviceTimeReq 1
// - settimeofday()/gettimeofday() must be used to access the ESP32's RTC time
// - Arduino ESP32 package has built-in time zone handling, see
// https://github.com/SensorsIot/NTP-time-for-ESP8266-and-ESP32/blob/master/NTP_Example/NTP_Example.ino
// - Apply fixes if using Arduino ESP32 board package v2.0.x
// - mcci-catena/arduino-lorawan#204
// (https://github.com/mcci-catena/arduino-lorawan/pull/204)
// --> fixed in mcci-catena/arduino-lorawan v0.10.0
// - mcci-catena/arduino-lmic#714
// (https://github.com/mcci-catena/arduino-lmic/issues/714#issuecomment-822051171)
//
///////////////////////////////////////////////////////////////////////////////
/*! \file BresserWeatherSensorTTN.ino */
#include "BresserWeatherSensorTTNCfg.h"
#include <Arduino_LoRaWAN_network.h>
#include <Arduino_LoRaWAN_EventLog.h>
#include <arduino_lmic.h>
#include <Preferences.h>
#include <ESP32Time.h>
#include "logging.h"
#ifdef ARDUINO_ARCH_RP2040
#include "src/pico_rtc/pico_rtc_utils.h"
#include <hardware/rtc.h>
#endif
#if defined(ARDUINO_M5STACK_CORE2)
#include <M5Unified.h>
#endif
#ifdef RAINDATA_EN
#include "RainGauge.h"
#endif
#ifdef LIGHTNINGSENSOR_EN
#include "Lightning.h"
#endif
// NOTE: Add #define LMIC_ENABLE_DeviceTimeReq 1
// in ~/Arduino/libraries/MCCI_LoRaWAN_LMIC_library/project_config/lmic_project_config.h
#if (not(LMIC_ENABLE_DeviceTimeReq))
#warning "LMIC_ENABLE_DeviceTimeReq is not set - will not be able to retrieve network time!"
#endif
#ifndef SLEEP_EN
#warning "SLEEP_EN is not defined, but the weather sensors are only read once during (re-)start! You have been warned!"
#endif
#ifdef ONEWIRE_EN
// Dallas/Maxim OneWire Temperature Sensor
#include <DallasTemperature.h>
#endif
#ifdef DISTANCESENSOR_EN
// A02YYUW / DFRobot SEN0311 Ultrasonic Distance Sensor
#include <DistanceSensor_A02YYUW.h>
#endif
// BresserWeatherSensorReceiver
#include "WeatherSensorCfg.h"
#include "WeatherSensor.h"
#if defined(MITHERMOMETER_EN)
// BLE Temperature/Humidity Sensor
#include <ATC_MiThermometer.h>
#endif
#if defined(THEENGSDECODER_EN)
#include "src/BleSensors/BleSensors.h"
#endif
// LoRa_Serialization
#include <LoraMessage.h>
// Pin mapping for ESP32 (MCCI Arduino LoRaWAN Library)
// Note: Pin mapping for BresserWeatherSensorReceiver is done in WeatherSensorCfg.h!
// SPI2 is used on ESP32 per default! (e.g. see https://github.com/espressif/arduino-esp32/tree/master/variants/doitESP32devkitV1)
#if defined(ARDUINO_TTGO_LoRa32_V1)
// https://github.com/espressif/arduino-esp32/blob/master/variants/ttgo-lora32-v1/pins_arduino.h
// http://www.lilygo.cn/prod_view.aspx?TypeId=50003&Id=1130&FId=t3:50003:3
// https://github.com/Xinyuan-LilyGo/TTGO-LoRa-Series
// https://github.com/LilyGO/TTGO-LORA32/blob/master/schematic1in6.pdf
#define PIN_LMIC_NSS LORA_CS
#define PIN_LMIC_RST LORA_RST
#define PIN_LMIC_DIO0 LORA_IRQ
#define PIN_LMIC_DIO1 33
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#elif defined(ARDUINO_TTGO_LoRa32_V2)
// https://github.com/espressif/arduino-esp32/blob/master/variants/ttgo-lora32-v2/pins_arduino.h
#define PIN_LMIC_NSS LORA_CS
#define PIN_LMIC_RST LORA_RST
#define PIN_LMIC_DIO0 LORA_IRQ
#define PIN_LMIC_DIO1 33
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#pragma message("LoRa DIO1 must be wired to GPIO33 manually!")
#elif defined(ARDUINO_TTGO_LoRa32_v21new)
// https://github.com/espressif/arduino-esp32/blob/master/variants/ttgo-lora32-v21new/pins_arduino.h
#define PIN_LMIC_NSS LORA_CS
#define PIN_LMIC_RST LORA_RST
#define PIN_LMIC_DIO0 LORA_IRQ
#define PIN_LMIC_DIO1 LORA_D1
#define PIN_LMIC_DIO2 LORA_D2
#elif defined(ARDUINO_HELTEC_WIRELESS_STICK) || defined(ARDUINO_HELTEC_WIFI_LORA_32_V2)
// https://github.com/espressif/arduino-esp32/blob/master/variants/heltec_wireless_stick/pins_arduino.h
// https://github.com/espressif/arduino-esp32/blob/master/variants/heltec_wifi_lora_32_V2/pins_arduino.h
#define PIN_LMIC_NSS SS
#define PIN_LMIC_RST RST_LoRa
#define PIN_LMIC_DIO0 DIO0
#define PIN_LMIC_DIO1 DIO1
#define PIN_LMIC_DIO2 DIO2
#elif defined(ARDUINO_ADAFRUIT_FEATHER_ESP32S2)
#define PIN_LMIC_NSS 6
#define PIN_LMIC_RST 9
#define PIN_LMIC_DIO0 5
#define PIN_LMIC_DIO1 11
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#pragma message("ARDUINO_ADAFRUIT_FEATHER_ESP32S2 defined; assuming RFM95W FeatherWing will be used")
#pragma message("Required wiring: E to IRQ, D to CS, C to RST, A to DI01")
#pragma message("BLE is not available!")
#elif defined(ARDUINO_FEATHER_ESP32)
#define PIN_LMIC_NSS 14
#define PIN_LMIC_RST 27
#define PIN_LMIC_DIO0 32
#define PIN_LMIC_DIO1 33
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#pragma message("NOT TESTED!!!")
#pragma message("ARDUINO_ADAFRUIT_FEATHER_ESP32 defined; assuming RFM95W FeatherWing will be used")
#pragma message("Required wiring: A to RST, B to DIO1, D to DIO0, E to CS")
#elif defined(ARDUINO_M5STACK_Core2) || defined(ARDUINO_M5STACK_CORE2)
// Note:
// Depending on the environment, selecting M5Stack Core2 defines
// either ARDUINO_M5STACK_Core2 or ARDUINO_M5STACK_CORE2
// so both variants have to be checked!!!
#define PIN_LMIC_NSS 33
#define PIN_LMIC_RST 26
#define PIN_LMIC_DIO0 36
#define PIN_LMIC_DIO1 35
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#pragma message("ARDUINO_M5STACK_CORE2 defined; assuming M5Stack Module LoRa868 will be used")
#pragma message("Required wiring: DIO1 to GPIO35")
#elif defined(ARDUINO_ADAFRUIT_FEATHER_RP2040)
// Use pinning for Adafruit Feather RP2040 with RFM95W "FeatherWing" ADA3232
// https://github.com/earlephilhower/arduino-pico/blob/master/variants/adafruit_feather/pins_arduino.h
#define PIN_LMIC_NSS 7
#define PIN_LMIC_RST 11
#define PIN_LMIC_DIO0 8
#define PIN_LMIC_DIO1 10
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#pragma message("ARDUINO_ADAFRUIT_FEATHER_RP2040 defined; assuming RFM95W FeatherWing will be used")
#pragma message("Required wiring: A to RST, B to DIO1, D to DIO0, E to CS")
#elif defined(ARDUINO_DFROBOT_FIREBEETLE_ESP32) && defined(FIREBEETLE_ESP32_COVER_LORA)
// https://wiki.dfrobot.com/FireBeetle_ESP32_IOT_Microcontroller(V3.0)__Supports_Wi-Fi_&_Bluetooth__SKU__DFR0478
// https://wiki.dfrobot.com/FireBeetle_Covers_LoRa_Radio_868MHz_SKU_TEL0125
#define PIN_LMIC_NSS 27 // D4
#define PIN_LMIC_RST 25 // D2
#define PIN_LMIC_DIO0 26 // D3
#define PIN_LMIC_DIO1 9 // D5
#define PIN_LMIC_DIO2 cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN
#pragma message("ARDUINO_DFROBOT_FIREBEETLE_ESP32 && FIREBEETLE_ESP32_COVER_LORA defined; assuming FireBeetle ESP32 with FireBeetle Cover LoRa will be used")
#pragma message("Required wiring: D2 to RESET, D3 to DIO0, D4 to CS, D5 to DIO1")
#elif defined(ARDUINO_DFROBOT_FIREBEETLE_ESP32) && defined(LORAWAN_NODE)
// LoRaWAN_Node board
// https://github.com/matthias-bs/LoRaWAN_Node
#pragma message("ARDUINO_DFROBOT_FIREBEETLE_ESP32 && LORAWAN_NODE defined; assuming LoRaWAN_Node board will be used")
#define PIN_LMIC_NSS 14
#define PIN_LMIC_RST 12
#define PIN_LMIC_DIO0 4
#define PIN_LMIC_DIO1 16
#define PIN_LMIC_DIO2 17
#else
#pragma message("Unknown board configuration!")
#define PIN_LMIC_NSS 14
#define PIN_LMIC_RST 12
#define PIN_LMIC_DIO0 4
#define PIN_LMIC_DIO1 16
#define PIN_LMIC_DIO2 17
#endif
// Uplink message payload size
// The maximum allowed for all data rates is 51 bytes.
const uint8_t PAYLOAD_SIZE = 51;
// RTC Memory Handling
#define MAGIC1 (('m' << 24) | ('g' < 16) | ('c' << 8) | '1')
#define MAGIC2 (('m' << 24) | ('g' < 16) | ('c' << 8) | '2')
#define EXTRA_INFO_MEM_SIZE 64
// Debug printing
// ---------------
// To enable debug mode (debug messages via serial port):
// Arduino IDE: Tools->Core Debug Level: "Debug|Verbose"
// or
// set CORE_DEBUG_LEVEL in BresserWeatherSensorTTNCfg.h
// Downlink messages
// ------------------
//
// CMD_SET_WEATHERSENSOR_TIMEOUT
// (seconds)
// byte0: 0xA0
// byte1: ws_timeout[ 7: 0]
//
// CMD_SET_SLEEP_INTERVAL
// (seconds)
// byte0: 0xA8
// byte1: sleep_interval[15:8]
// byte2: sleep_interval[ 7:0]
// CMD_SET_SLEEP_INTERVAL_LONG
// (seconds)
// byte0: 0xA9
// byte1: sleep_interval_long[15:8]
// byte2: sleep_interval_long[ 7:0]
//
// CMD_RESET_RAINGAUGE
// byte0: 0xB0
// byte1: flags[7:0] (optional)
//
// CMD_GET_CONFIG
// byte0: 0xB1
//
// CMD_GET_DATETIME
// byte0: 0x86
//
// CMD_SET_DATETIME
// byte0: 0x88
// byte1: unixtime[31:24]
// byte2: unixtime[23:16]
// byte3: unixtime[15: 8]
// byte4: unixtime[ 7: 0]
//
// Response uplink messages
// -------------------------
//
// CMD_GET_DATETIME -> FPort=2
// byte0: unixtime[31:24]
// byte1: unixtime[23:16]
// byte2: unixtime[15: 8]
// byte3: unixtime[ 7: 0]
// byte4: rtc_source[ 7: 0]
//
// CMD_GET_CONFIG -> FPort=3
// byte0: ws_timeout[ 7: 0]
// byte1: sleep_interval[15: 8]
// byte2: sleep_interval[ 7:0]
// byte3: sleep_interval_long[15:8]
// byte4: sleep_interval_long[ 7:0]
#define CMD_SET_WEATHERSENSOR_TIMEOUT 0xA0
#define CMD_SET_SLEEP_INTERVAL 0xA8
#define CMD_SET_SLEEP_INTERVAL_LONG 0xA9
#define CMD_RESET_RAINGAUGE 0xB0
#define CMD_GET_CONFIG 0xB1
#define CMD_GET_DATETIME 0x86
#define CMD_SET_DATETIME 0x88
void printDateTime(void);
/****************************************************************************\
|
| The LoRaWAN object
|
\****************************************************************************/
/*!
* \class cMyLoRaWAN
*
* \brief The LoRaWAN object - LoRaWAN protocol and session handling
*/
class cMyLoRaWAN : public Arduino_LoRaWAN_network {
public:
cMyLoRaWAN() {};
using Super = Arduino_LoRaWAN_network;
/*!
* \fn setup
*
* \brief Initialize cMyLoRaWAN object
*/
void setup();
/*!
* \fn requestNetworkTime
*
* \brief Wrapper function for LMIC_requestNetworkTime()
*/
void requestNetworkTime(void);
/*!
* \fn printSessionInfo
*
* \brief Print contents of session info data structure for debugging
*
* \param Info Session information data structure
*/
void printSessionInfo(const SessionInfo &Info);
/*!
* \fn printSessionState
*
* \brief Print contents of session state data structure for debugging
*
* \param State Session state data structure
*/
void printSessionState(const SessionState &State);
/*!
* \fn doCfgUplink
*
* \brief Uplink configuration/status
*/
void doCfgUplink(void);
bool isBusy(void) {
return m_fBusy;
}
private:
bool m_fBusy; // set true while sending an uplink
protected:
// you'll need to provide implementation for this.
virtual bool GetOtaaProvisioningInfo(Arduino_LoRaWAN::OtaaProvisioningInfo*) override;
// NetTxComplete() activates deep sleep mode (if enabled)
virtual void NetTxComplete(void) override;
// NetJoin() changes <sleepTimeout>
virtual void NetJoin(void) override;
// Used to store/load data to/from persistent (at least during deep sleep) memory
virtual void NetSaveSessionInfo(const SessionInfo &Info, const uint8_t *pExtraInfo, size_t nExtraInfo) override;
//virtual bool GetSavedSessionInfo(SessionInfo &Info, uint8_t*, size_t, size_t*) override;
virtual void NetSaveSessionState(const SessionState &State) override;
virtual bool NetGetSessionState(SessionState &State) override;
virtual bool GetAbpProvisioningInfo(AbpProvisioningInfo *pAbpInfo) override;
};
/****************************************************************************\
|
| The sensor object
|
\****************************************************************************/
/*!
* \class cSensor
*
* \brief The sensor object - collect sensor data and schedule uplink
*/
class cSensor {
public:
/// \brief the constructor. Deliberately does very little.
cSensor() {};
/*!
* \fn getTemperature
*
* \brief Get temperature from DS18B20 sensor via OneWire bus
*
* \returns Temperature [degC]
*/
float getTemperature(void);
#ifdef ADC_EN
/*
* \fn getVoltage
*
* \brief Get ADC voltage from specified pin with averaging and application of divider
*
* \param adc ADC pin
*
* \param samples No. of samples used in averaging
*
* \param divider Voltage divider
*
* \returns Voltage [mV]
*/
uint16_t getVoltage(uint8_t pin = PIN_ADC_IN, uint8_t samples = UBATT_SAMPLES, float divider = UBATT_DIV);
#endif
/*!
* \fn uplinkRequest
*
* \brief Request uplink to LoRaWAN
*/
void uplinkRequest(void) {
m_fUplinkRequest = true;
};
/*!
* \brief set up the sensor object
*
* \param uplinkPeriodMs optional uplink interval. If not specified,
* transmit every six minutes.
*/
void setup(std::uint32_t uplinkPeriodMs = 6 * 60 * 1000);
/*!
* \brief update sensor loop.
*
* \details
* This should be called from the global loop(); it periodically
* gathers and transmits sensor data.
*/
void loop();
bool isBusy(void) {
return m_fBusy;
}
private:
void doUplink();
bool m_fUplinkRequest; //!< set true when uplink is requested
bool m_fBusy; //!< set true while sending an uplink
std::uint32_t m_uplinkPeriodMs; //!< uplink period in milliseconds
std::uint32_t m_tReference; //!< time of last uplink
};
/****************************************************************************\
|
| Globals
|
\****************************************************************************/
// the global LoRaWAN instance.
cMyLoRaWAN myLoRaWAN {};
// the global sensor instance
cSensor mySensor {};
// the global event log instance
Arduino_LoRaWAN::cEventLog myEventLog;
// The pin map. This form is convenient if the LMIC library
// doesn't support your board and you don't want to add the
// configuration to the library (perhaps you're just testing).
// This pinmap matches the FeatherM0 LoRa. See the arduino-lmic
// docs for more info on how to set this up.
const cMyLoRaWAN::lmic_pinmap myPinMap = {
.nss = PIN_LMIC_NSS,
.rxtx = cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN,
.rst = PIN_LMIC_RST,
.dio = { PIN_LMIC_DIO0, PIN_LMIC_DIO1, PIN_LMIC_DIO2 },
.rxtx_rx_active = 0,
.rssi_cal = 0,
.spi_freq = 8000000,
.pConfig = NULL
};
#if !defined(SESSION_IN_PREFERENCES)
// The following variables are stored in the ESP32's RTC RAM -
// their value is retained after a Sleep Reset.
RTC_DATA_ATTR uint32_t magicFlag1; //!< flag for validating Session State in RTC RAM
RTC_DATA_ATTR Arduino_LoRaWAN::SessionState rtcSavedSessionState; //!< Session State saved in RTC RAM
RTC_DATA_ATTR uint32_t magicFlag2; //!< flag for validating Session Info in RTC RAM
RTC_DATA_ATTR Arduino_LoRaWAN::SessionInfo rtcSavedSessionInfo; //!< Session Info saved in RTC RAM
RTC_DATA_ATTR size_t rtcSavedNExtraInfo; //!< size of extra Session Info data
RTC_DATA_ATTR uint8_t rtcSavedExtraInfo[EXTRA_INFO_MEM_SIZE]; //!< extra Session Info data
#endif
// Variables which must retain their values after deep sleep
#if defined(ESP32)
// Stored in RTC RAM
RTC_DATA_ATTR bool runtimeExpired = false; //!< flag indicating if runtime has expired at least once
RTC_DATA_ATTR bool longSleep; //!< last sleep interval; 0 - normal / 1 - long
RTC_DATA_ATTR time_t rtcLastClockSync = 0; //!< timestamp of last RTC synchonization to network time
#else
// Save to/restored from Watchdog SCRATCH registers
bool runtimeExpired; //!< flag indicating if runtime has expired at least once
bool longSleep; //!< last sleep interval; 0 - normal / 1 - long
time_t rtcLastClockSync; //!< timestamp of last RTC synchonization to network time
#endif
/// Bresser Weather Sensor Receiver
WeatherSensor weatherSensor;
/// ESP32 preferences (stored in flash memory)
static Preferences preferences;
struct sPrefs {
uint8_t ws_timeout; //!< preferences: weather sensor timeout
uint16_t sleep_interval; //!< preferences: sleep interval
uint16_t sleep_interval_long; //!< preferences: sleep interval long
} prefs;
#ifdef RAINDATA_EN
/// Rain data statistics
RainGauge rainGauge;
#endif
#ifdef LIGHTNINGSENSOR_EN
/// Lightning sensor post-processing
Lightning lightningProc;
#endif
#ifdef ONEWIRE_EN
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(PIN_ONEWIRE_BUS); //!< OneWire bus
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature temp_sensors(&oneWire); //!< Dallas temperature sensors connected to OneWire bus
#endif
#if defined(MITHERMOMETER_EN) || defined(THEENGSDECODER_EN)
std::vector<std::string> knownBLEAddresses = KNOWN_BLE_ADDRESSES;
#endif
#ifdef DISTANCESENSOR_EN
#if defined(ESP32)
DistanceSensor_A02YYUW distanceSensor(&Serial2);
#else
DistanceSensor_A02YYUW distanceSensor(&Serial1);
#endif
#endif
#ifdef MITHERMOMETER_EN
// Setup BLE Temperature/Humidity Sensors
ATC_MiThermometer bleSensors(knownBLEAddresses); //!< Mijia Bluetooth Low Energy Thermo-/Hygrometer
#endif
#ifdef THEENGSDECODER_EN
BleSensors bleSensors(knownBLEAddresses);
#endif
/// LoRaWAN uplink payload buffer
static uint8_t loraData[PAYLOAD_SIZE]; //!< LoRaWAN uplink payload buffer
/// Sleep request
bool sleepReq = false;
/// Uplink request - command received via downlink
uint8_t uplinkReq = 0;
/// Force sleep mode after <code>sleepTimeout</code> has been reached (if FORCE_SLEEP is defined)
ostime_t sleepTimeout; //!
/// Seconds since the UTC epoch
uint32_t userUTCTime;
/// RTC sync request flag - set (if due) in setup() / cleared in UserRequestNetworkTimeCb()
bool rtcSyncReq = false;
/// Real time clock
ESP32Time rtc;
/****************************************************************************\
|
| Provisioning info for LoRaWAN OTAA
|
\****************************************************************************/
//
// For normal use, we require that you edit the sketch to replace FILLMEIN_x
// with values assigned by the your network. However, for regression tests,
// we want to be able to compile these scripts. The regression tests define
// COMPILE_REGRESSION_TEST, and in that case we define FILLMEIN_x to non-
// working but innocuous values.
//
// #define COMPILE_REGRESSION_TEST 1
#ifdef COMPILE_REGRESSION_TEST
# define FILLMEIN_8 1, 0, 0, 0, 0, 0, 0, 0
# define FILLMEIN_16 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2
#else
# warning "You must replace the values marked FILLMEIN with real values from the TTN control panel!"
# define FILLMEIN_8 (#dont edit this, edit the lines that use FILLMEIN_8)
# define FILLMEIN_16 (#dont edit this, edit the lines that use FILLMEIN_16)
#endif
// APPEUI, DEVEUI and APPKEY
#include "secrets.h"
#ifndef SECRETS
#define SECRETS
// The following constants should be copied to secrets.h and configured appropriately
// according to the settings from TTN Console
/// DeviceEUI, little-endian (lsb first)
static const std::uint8_t deveui[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
/// AppEUI, little-endian (lsb first)
static const std::uint8_t appeui[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
/// AppKey: just a string of bytes, sometimes referred to as "big endian".
static const std::uint8_t appkey[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
#endif
/****************************************************************************\
|
| setup()
|
\****************************************************************************/
/// Arduino setup
void setup() {
#if defined(ARDUINO_ARCH_RP2040)
// see pico-sdk/src/rp2_common/hardware_rtc/rtc.c
rtc_init();
// Restore variables and RTC after reset
time_t time_saved = watchdog_hw->scratch[0];
datetime_t dt;
epoch_to_datetime(&time_saved, &dt);
// Set HW clock (only used in sleep mode)
rtc_set_datetime(&dt);
// Set SW clock
rtc.setTime(time_saved);
runtimeExpired = ((watchdog_hw->scratch[1] & 1) == 1);
longSleep = ((watchdog_hw->scratch[1] & 2) == 2);
rtcLastClockSync = watchdog_hw->scratch[2];
#endif
#if defined(ARDUINO_M5STACK_CORE2)
auto cfg = M5.config();
cfg.clear_display = true; // default=true. clear the screen when begin.
cfg.output_power = true; // default=true. use external port 5V output.
cfg.internal_imu = false; // default=true. use internal IMU.
cfg.internal_rtc = true; // default=true. use internal RTC.
cfg.internal_spk = false; // default=true. use internal speaker.
cfg.internal_mic = false; // default=true. use internal microphone.
M5.begin(cfg);
#endif
// set baud rate
Serial.begin(115200);
delay(3000);
Serial.setDebugOutput(true);
// wait for serial to be ready - or timeout if USB is not connected
delay(500);
#if defined(ARDUINO_ARCH_RP2040)
log_i("Time saved: %llu", time_saved);
#endif
preferences.begin("BWS-TTN", false);
prefs.ws_timeout = preferences.getUChar("ws_timeout", WEATHERSENSOR_TIMEOUT);
log_d("Preferences: weathersensor_timeout: %u s", prefs.ws_timeout);
prefs.sleep_interval = preferences.getUShort("sleep_int", SLEEP_INTERVAL);
log_d("Preferences: sleep_interval: %u s", prefs.sleep_interval);
prefs.sleep_interval_long = preferences.getUShort("sleep_int_long", SLEEP_INTERVAL_LONG);
log_d("Preferences: sleep_interval_long: %u s", prefs.sleep_interval_long);
preferences.end();
sleepTimeout = sec2osticks(SLEEP_TIMEOUT_INITIAL);
log_v("-");
// Set time zone
setenv("TZ", TZ_INFO, 1);
printDateTime();
// Check if clock was never synchronized or sync interval has expired
if ((rtcLastClockSync == 0) || ((rtc.getLocalEpoch() - rtcLastClockSync) > (CLOCK_SYNC_INTERVAL * 60))) {
log_i("RTC sync required");
rtcSyncReq = true;
}
// set up the log; do this first.
myEventLog.setup();
log_v("myEventlog.setup() - done");
// set up the sensors.
mySensor.setup();
log_v("mySensor.setup() - done");
// set up lorawan.
myLoRaWAN.setup();
log_v("myLoRaWAN.setup() - done");
mySensor.uplinkRequest();
}
/****************************************************************************\
|
| loop()
|
\****************************************************************************/
/// Arduino execution loop
void loop() {
// the order of these is arbitrary, but you must poll them all.
myLoRaWAN.loop();
mySensor.loop();
myEventLog.loop();
if (uplinkReq != 0) {
myLoRaWAN.doCfgUplink();
}
#ifdef SLEEP_EN
if (sleepReq & !rtcSyncReq) {
myLoRaWAN.Shutdown();
prepareSleep();
}
#endif
#ifdef FORCE_SLEEP
if (os_getTime() > sleepTimeout) {
runtimeExpired = true;
myLoRaWAN.Shutdown();
#ifdef FORCE_JOIN_AFTER_SLEEP_TIMEOUT
// Force join (instead of re-join)
#if !defined(SESSION_IN_PREFERENCES)
magicFlag1 = 0;
magicFlag2 = 0;
#else
preferences.begin("BWS-TTN-S");
preferences.clear();
preferences.end();
#endif
#endif
log_i("Sleep timer expired!");
prepareSleep();
}
#endif
}
/****************************************************************************\
|
| LoRaWAN methods
|
\****************************************************************************/
// Receive and process downlink messages
void ReceiveCb(
void *pCtx,
uint8_t uPort,
const uint8_t *pBuffer,
size_t nBuffer) {
(void)pCtx;
uplinkReq = 0;
log_v("Port: %d", uPort);
char buf[255];
*buf = '\0';
if (uPort > 0) {
for (size_t i = 0; i < nBuffer; i++) {
sprintf(&buf[strlen(buf)], "%02X ", pBuffer[i]);
}
log_v("Data: %s", buf);
if ((pBuffer[0] == CMD_GET_DATETIME) && (nBuffer == 1)) {
log_d("Get date/time");
uplinkReq = CMD_GET_DATETIME;
}
if ((pBuffer[0] == CMD_GET_CONFIG) && (nBuffer == 1)) {
log_d("Get config");
uplinkReq = CMD_GET_CONFIG;
}
if ((pBuffer[0] == CMD_SET_DATETIME) && (nBuffer == 5)) {
time_t set_time = pBuffer[4] | (pBuffer[3] << 8) | (pBuffer[2] << 16) | (pBuffer[1] << 24);
rtc.setTime(set_time);
rtcLastClockSync = rtc.getLocalEpoch();
#if CORE_DEBUG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
char tbuf[25];
struct tm timeinfo;
localtime_r(&set_time, &timeinfo);
strftime(tbuf, 25, "%Y-%m-%d %H:%M:%S", &timeinfo);
log_d("Set date/time: %s", tbuf);
#endif
}
if ((pBuffer[0] == CMD_SET_WEATHERSENSOR_TIMEOUT) && (nBuffer == 2)) {
log_d("Set weathersensor_timeout: %u s", pBuffer[1]);
preferences.begin("BWS-TTN", false);
preferences.putUChar("ws_timeout", pBuffer[1]);
preferences.end();
}
if ((pBuffer[0] == CMD_SET_SLEEP_INTERVAL) && (nBuffer == 3)){
prefs.sleep_interval = pBuffer[2] | (pBuffer[1] << 8);
log_d("Set sleep_interval: %u s", prefs.sleep_interval);
preferences.begin("BWS-TTN", false);
preferences.putUShort("sleep_int", prefs.sleep_interval);
preferences.end();
}
if ((pBuffer[0] == CMD_SET_SLEEP_INTERVAL_LONG) && (nBuffer == 3)){
prefs.sleep_interval_long = pBuffer[2] | (pBuffer[1] << 8);
log_d("Set sleep_interval_long: %u s", prefs.sleep_interval_long);
preferences.begin("BWS-TTN", false);
preferences.putUShort("sleep_int_long", prefs.sleep_interval_long);
preferences.end();
}
#ifdef RAINDATA_EN
if (pBuffer[0] == CMD_RESET_RAINGAUGE) {
if (nBuffer == 1) {
log_d("Reset raingauge");
rainGauge.reset();
}
else if (nBuffer == 2) {
log_d("Reset raingauge - flags: 0x%X", pBuffer[1]);
rainGauge.reset(pBuffer[1] & 0xF);
}
}
#endif
}
if (uplinkReq == 0) {
sleepReq = true;
}
}
// our setup routine does the class setup and then registers an event handler so
// we can see some interesting things
void
cMyLoRaWAN::setup() {
// simply call begin() w/o parameters, and the LMIC's built-in
// configuration for this board will be used.
this->Super::begin(myPinMap);
// LMIC_selectSubBand(0);
LMIC_setClockError(MAX_CLOCK_ERROR * 1 / 100);
this->SetReceiveBufferBufferCb(ReceiveCb);
this->RegisterListener(
// use a lambda so we're "inside" the cMyLoRaWAN from public/private perspective
[](void *pClientInfo, uint32_t event) -> void {
auto const pThis = (cMyLoRaWAN *)pClientInfo;
// for tx start, we quickly capture the channel and the RPS
if (event == EV_TXSTART) {
// use another lambda to make log prints easy
myEventLog.logEvent(
(void *) pThis,
LMIC.txChnl,
LMIC.rps,
0,
// the print-out function
[](cEventLog::EventNode_t const *pEvent) -> void {
#if CORE_DEBUG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO
//rps_t _rps = rps_t(pEvent->getData(1));
//Serial.printf("rps (1): %02X\n", _rps);
uint8_t rps = pEvent->getData(1);
uint32_t tstamp = osticks2ms(pEvent->getTime());