-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrowatt2lorawan.ino
1449 lines (1241 loc) · 46.2 KB
/
growatt2lorawan.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
///////////////////////////////////////////////////////////////////////////////
// growatt2lorawan.ino
//
// LoRaWAN Node for Growatt PV-Inverter Data Interface
//
// https://github.com/mcci-catena/arduino-lorawan/tree/master/examples/arduino_lorawan_esp32_example
// - implements power saving by using the ESP32 deep sleep mode
// - implements fast re-joining after sleep by storing network session data
// in the ESP32 RTC RAM
// - LoRa_Serialization is used for encoding various data types into bytes
// - internal Real-Time Clock (RTC) set from LoRaWAN network time (optional)
//
//
// Based on:
// ---------
// 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)
//
//
// Library dependencies (tested versions):
// ---------------------------------------
// MCCI Arduino Development Kit ADK 0.2.2
// MCCI LoRaWAN LMIC library 4.1.1
// MCCI Arduino LoRaWAN Library 0.9.2
// LoRa_Serialization 3.2.1
// ESP32Time 2.0.0
//
//
// created: 03/2023
//
//
// 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:
//
// 20230315 Created
// 20230403 Implemented uplink messages with different ports and cycle times
// 20230408 Modified debug output handling
// Added Modbus interface option over USB serial
// 20230417 Added pin config for TTGO LoRa32 V2.1
// 20230420 Added pin config for
// DFRobot FireBeetle ESP32 + FireBeetle Cover LoRa
// 20231009 Renamed FIREBEETLE_COVER_LORA in FIREBEETLE_ESP32_COVER_LORA
//
// Notes:
// - After a successful transmission, the controller can go into deep sleep
// (option SLEEP_EN)
// - Sleep time is defined in SLEEP_INTERVAL
// - If joining the network or transmitting uplink data fails,
// the controller can go into deep sleep
// (option FORCE_SLEEP)
// - Timeout is defined in SLEEP_TIMEOUT_INITIAL and SLEEP_TIMEOUT_JOINED
// - The ESP32's RTC RAM is used to store information about the LoRaWAN
// network session; this speeds up the connection after a restart
// significantly
// - 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
//
///////////////////////////////////////////////////////////////////////////////
//--- Select LoRaWAN Network ---
// The Things Network
#define ARDUINO_LMIC_CFG_NETWORK_TTN 1
// Helium Network
// see mcci-cathena/arduino-lorawan issue #185 "Add Helium EU868 support"
// (https://github.com/mcci-catena/arduino-lorawan/issues/185)
#define ARDUINO_LMIC_CFG_NETWORK_GENERIC 0
// (Add other networks here)
#include <Arduino_LoRaWAN_network.h>
#include <Arduino_LoRaWAN_EventLog.h>
#include <arduino_lmic.h>
#include <Preferences.h>
#include "src/settings.h"
#include "src/payload.h"
// 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
//-----------------------------------------------------------------------------
//
// User Configuration
//
// Enable debug mode (debug messages via serial port)
#define _DEBUG_MODE_
// Enable sleep mode - sleep after successful transmission to TTN (recommended!)
//#define SLEEP_EN
// Enable setting RTC from LoRaWAN network time
#define GET_NETWORKTIME
#if defined(GET_NETWORKTIME)
// Enter your time zone (https://remotemonitoringsystems.ca/time-zone-abbreviations.php)
const char* TZ_INFO = "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00";
// RTC to network time sync interval (in minutes)
#define CLOCK_SYNC_INTERVAL 24 * 60
#endif
// Number of uplink ports
#define NUM_PORTS 2
// Uplink period multipliers
#define UPLINK_PERIOD_MULTIPLIERS {1, 5}
typedef struct {
int port;
int mult;
} Schedule;
const Schedule UplinkSchedule[NUM_PORTS] = {
// {port, mult}
{1, 1},
{2, 2}
};
// If SLEEP_EN is defined, MCU will sleep for SLEEP_INTERVAL seconds after succesful transmission
#define SLEEP_INTERVAL 360
// Long sleep interval, MCU will sleep for SLEEP_INTERVAL_LONG seconds if battery voltage is below BATTERY_WEAK
#define SLEEP_INTERVAL_LONG 900
// Force deep sleep after a certain time, even if transmission was not completed
//#define FORCE_SLEEP
// During initialization (not joined), force deep sleep after SLEEP_TIMEOUT_INITIAL (if enabled)
#define SLEEP_TIMEOUT_INITIAL 1800
// If already joined, force deep sleep after SLEEP_TIMEOUT_JOINED seconds (if enabled)
#define SLEEP_TIMEOUT_JOINED 600
// Additional timeout to be applied after joining if Network Time Request pending
#define SLEEP_TIMEOUT_EXTRA 300
//-----------------------------------------------------------------------------
#if defined(GET_NETWORKTIME)
#include <ESP32Time.h>
#endif
// LoRa_Serialization
#include <LoraMessage.h>
// Pin mappings for some common ESP32 LoRaWAN boards.
// The ARDUINO_* defines are set by selecting the appropriate board (and borad variant, if applicable) in the Arduino IDE.
// The default SPI port of the specific board will be used.
#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/tree/master/variants/heltec_wifi_lora_32_V2/pins_ardiono.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(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("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(LORAWAN_NODE)
// LoRaWAN_Node board
// https://github.com/matthias-bs/LoRaWAN_Node
#pragma message("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; please select one in the Arduino IDE or in settings.h or create your own!")
// definitions for generic CI target ESP32:ESP32:ESP32
#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
#define DEBUG_PORT Serial2
#define DEBUG_PRINTF(...) { log_d(__VA_ARGS__); }
#define DEBUG_PRINTF_TS(...) { log_d(__VA_ARGS__); }
// 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_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]
//
// CMD_GET_INVERTER_SETTINGS
// byte0: 0xC0
//
// Response uplink messages
// -------------------------
//
// CMD_GET_DATETIME -> FPort=3
// 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=4
// byte0: reserved[ 7: 0]
// byte1: sleep_interval[15: 8]
// byte2: sleep_interval[ 7:0]
// byte3: sleep_interval_long[15:8]
// byte4: sleep_interval_long[ 7:0]
//
// CMD_GET_INVERTER_SETTINGS -> FPort=5
// TBD
#define CMD_SET_SLEEP_INTERVAL 0xA8
#define CMD_SET_SLEEP_INTERVAL_LONG 0xA9
#define CMD_GET_CONFIG 0xB1
#define CMD_GET_DATETIME 0x86
#define CMD_SET_DATETIME 0x88
#define CMD_GET_INVERTER_SETTINGS 0xC0
#if defined(GET_NETWORKTIME)
void printDateTime(void);
#endif
/****************************************************************************\
|
| 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();
#if defined(GET_NETWORKTIME)
/*!
* \fn requestNetworkTime
*
* \brief Wrapper function for LMIC_requestNetworkTime()
*/
void requestNetworkTime(void);
#endif
/*
// Attempt to override GetPinmap_ThisBoard() from MCCI_LoRaWAN_LMIC_library
// to get rid of "#pragma message: Board not supported -- use an explicit pinmap"
private:
const Arduino_LMIC::HalPinmap_t* Arduino_LMIC::GetPinmap_ThisBoard(void) {
return nullptr;
};
*/
/*!
* \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 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() {};
// Sensor data function stubs
float getTemperature(void);
uint16_t getVoltageBattery(void);
uint16_t getVoltageSupply(void);
bool isUplinkPending(void) {
if (this->m_fBusy) {
log_d("Busy");
return true;
}
for (int idx=0; idx<NUM_PORTS; idx++) {
log_d("m_fUplinkRequest[%d]=%d", idx, m_fUplinkRequest[idx]);
if (m_fUplinkRequest[idx])
return true;
}
return false;
};
void uplinkRequest(void) {
m_fUplinkRequest[0] = 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;
}
// Example sensor status flags
bool data_ok; //<! sensor data validation
bool battery_ok; //<! sensor battery status
// Example sensor data
float temperature_deg_c; //<! outdoor air temperature in °C
uint16_t battery_voltage_v; //<! battery voltage
uint16_t supply_voltage_v; //<! supply voltage
private:
void doUplink(int port);
bool m_fUplinkRequest[NUM_PORTS]; //!< 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::uint8_t const m_uplinkPeriodMult[NUM_PORTS] = UPLINK_PERIOD_MULTIPLIERS; //!< uplink period multiplier per port
std::uint32_t m_tReference[NUM_PORTS]; //!< time of last uplink
};
/****************************************************************************\
|
| Globals
|
\****************************************************************************/
// the global LoRaWAN instance.
cMyLoRaWAN myLoRaWAN {};
// the global sensor instance
cSensor mySensor {};
class cMyEventLog: public Arduino_LoRaWAN::cEventLog {
public:
void printTx(uint32_t ts, std::uint8_t channel, std::uint8_t rps) const
{
if (CORE_DEBUG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG) {
char buf[64];
*buf = '\0';
sprintf(buf, "TX @%u ms: ch=%d rps=0x%02X (%s %s %s %s IH=%u)",
ts,
channel,
rps,
getSfName(rps),
getBwName(rps),
getCrName(rps),
getCrcName(rps),
unsigned(getIh(rps))
);
DEBUG_PRINTF_TS("%s", buf);
}
}
void printCh(HardwareSerial & serial, std::uint8_t channel) const
{
serial.print(" ch=");
serial.print(std::uint32_t(channel));
}
void printRps(HardwareSerial & serial, std::uint8_t rps) const
{
serial.print(F(" rps=0x")); printHex2(serial, rps);
serial.print(F(" (")); serial.print(getSfName(rps));
printSpace(serial); serial.print(getBwName(rps));
printSpace(serial); serial.print(getCrName(rps));
printSpace(serial); serial.print(getCrcName(rps));
serial.print(F(" IH=")); serial.print(unsigned(getIh(rps)));
serial.print(')');
}
void printHex2(HardwareSerial & serial, unsigned v) const
{
v &= 0xff;
if (v < 16)
serial.print('0');
serial.print(v, HEX);
}
void printSpace(HardwareSerial & serial) const
{
serial.print(' ');
}
};
// 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
};
// 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
RTC_DATA_ATTR bool runtimeExpired = false; //!< flag indicating if runtime has expired at least once
RTC_DATA_ATTR uint32_t tReference[NUM_PORTS] = { 0 }; //!< time of last uplink
RTC_DATA_ATTR bool longSleep; //!< last sleep interval; 0 - normal / 1 - long
#if defined(GET_NETWORKTIME)
RTC_DATA_ATTR time_t rtcLastClockSync = 0; //!< timestamp of last RTC synchonization to network time
#endif
/// Uplink payload buffer
static uint8_t loraData[PAYLOAD_SIZE];
/// ESP32 preferences (stored in flash memory)
Preferences preferences;
struct sPrefs {
uint16_t sleep_interval; //!< preferences: sleep interval
uint16_t sleep_interval_long; //!< preferences: sleep interval long
} prefs;
/// Force sleep mode after <sleepTimeout> has been reached (if FORCE_SLEEP is defined)
ostime_t sleepTimeout;
/// RTC sync request flag - set (if due) in setup() / cleared in UserRequestNetworkTimeCb()
bool rtcSyncReq = false;
/// Sleep request
bool sleepReq = false;
/// Uplink request - command received via downlink
uint8_t uplinkReq = 0;
#if defined(GET_NETWORKTIME)
/// Seconds since the UTC epoch
uint32_t userUTCTime;
/// Real time clock
ESP32Time rtc;
#endif
/// Modbus interface select: 0 - USB / 1 - RS485
bool modbusRS485;
/****************************************************************************\
|
| 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
/// deveui, 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() {
pinMode(INTERFACE_SEL, INPUT_PULLUP);
modbusRS485 = digitalRead(INTERFACE_SEL);
// set baud rate
if (modbusRS485) {
Serial.begin(115200);
log_d("Modbus interface: RS485");
} else {
Serial.setDebugOutput(false);
DEBUG_PORT.begin(115200, SERIAL_8N1, DEBUG_RX, DEBUG_TX);
DEBUG_PORT.setDebugOutput(true);
log_d("Modbus interface: USB");
}
// wait for DEBUG_PORT to be ready
//while (! DEBUG_PORT)
// yield();
delay(500);
preferences.begin("GROWATT2LORAWAN", false);
prefs.sleep_interval = preferences.getUShort("sleep_interval", SLEEP_INTERVAL);
log_d("Preferences: sleep_interval: %u s", prefs.sleep_interval);
prefs.sleep_interval_long = preferences.getUShort("sleep_interval_long", SLEEP_INTERVAL_LONG);
log_d("Preferences: sleep_interval_long: %u s", prefs.sleep_interval_long);
preferences.end();
sleepTimeout = sec2osticks(SLEEP_TIMEOUT_INITIAL);
DEBUG_PRINTF_TS("");
#if defined(GET_NETWORKTIME)
// 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))) {
DEBUG_PRINTF("RTC sync required");
rtcSyncReq = true;
}
#endif
// set up the log; do this first.
myEventLog.setup();
DEBUG_PRINTF("myEventlog.setup() - done");
// set up the sensors.
mySensor.setup();
DEBUG_PRINTF("mySensor.setup() - done");
// set up lorawan.
myLoRaWAN.setup();
DEBUG_PRINTF("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 FORCE_SLEEP
if ((os_getTime() > sleepTimeout) & !rtcSyncReq) {
DEBUG_PRINTF_TS("Sleep timer expired!");
DEBUG_PRINTF("Shutdown()");
runtimeExpired = true;
myLoRaWAN.Shutdown();
magicFlag1 = 0;
magicFlag2 = 0;
ESP.deepSleep(SLEEP_INTERVAL * 1000000);
}
#endif
}
/****************************************************************************\
|
| LoRaWAN methods
|
\****************************************************************************/
// Receive and process downlink messages
void ReceiveCb(
void *pCtx,
uint8_t uPort,
const uint8_t *pBuffer,
size_t nBuffer) {
uplinkReq = 0;
log_v("Port: %d", uPort);
char buf[255];
*buf = '\0';
if (uPort > 0) {
for (int 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_GET_INVERTER_SETTINGS) && (nBuffer == 1)) {
log_d("Get inverter settings");
uplinkReq = CMD_GET_INVERTER_SETTINGS;
}
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_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_interval", 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_interval", prefs.sleep_interval_long);
preferences.end();
}
}
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());
#endif
// see MCCI_Arduino_LoRaWAN_Library/src/lib/arduino_lorawan_cEventLog.cpp
log_i("TX @%u ms: ch=%d rps=0x%02x (%s %s %s %s IH=%d)",
tstamp,
std::uint8_t(pEvent->getData(0)),
rps,
myEventLog.getSfName(rps),
myEventLog.getBwName(rps),
myEventLog.getCrName(rps),
myEventLog.getCrcName(rps),
unsigned(getIh(rps)));
}
);
}
// else if (event == some other), record with print-out function
else {
// do nothing.
}
},
(void *) this // in case we need it.
);
}
// this method is called when the LMIC needs OTAA info.
// return false to indicate "no provisioning", otherwise
// fill in the data and return true.
bool
cMyLoRaWAN::GetOtaaProvisioningInfo(
OtaaProvisioningInfo *pInfo
) {
// these are the same constants used in the LMIC compliance test script; eases testing
// with the RedwoodComm RWC5020B/RWC5020M testers.
// initialize info
memcpy(pInfo->DevEUI, deveui, sizeof(pInfo->DevEUI));
memcpy(pInfo->AppEUI, appeui, sizeof(pInfo->AppEUI));
memcpy(pInfo->AppKey, appkey, sizeof(pInfo->AppKey));
return true;
}
// This method is called after the node has joined the network.
void
cMyLoRaWAN::NetJoin(
void) {
DEBUG_PRINTF_TS("");
sleepTimeout = os_getTime() + sec2osticks(SLEEP_TIMEOUT_JOINED);
if (rtcSyncReq) {
// Allow additional time for completing Network Time Request
sleepTimeout += os_getTime() + sec2osticks(SLEEP_TIMEOUT_EXTRA);
}
}
// This method is called after transmission has been completed.
// If enabled, the controller goes into deep sleep mode now.
void
cMyLoRaWAN::NetTxComplete(void) {
DEBUG_PRINTF_TS("");
}
// Print session info for debugging
void
cMyLoRaWAN::printSessionInfo(const SessionInfo &Info)
{
log_v("Tag:\t\t%d", Info.V1.Tag);
log_v("Size:\t\t%d", Info.V1.Size);
log_v("Rsv2:\t\t%d", Info.V1.Rsv2);
log_v("Rsv3:\t\t%d", Info.V1.Rsv3);
log_v("NetID:\t\t0x%08X", Info.V1.NetID);
log_v("DevAddr:\t\t0x%08X", Info.V1.DevAddr);
if (CORE_DEBUG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG) {
char buf[64];
*buf = '\0';
for (int i=0; i<15;i++) {
sprintf(&buf[strlen(buf)], "%02X ", Info.V1.NwkSKey[i]);
}
log_v("NwkSKey:\t\t%s", buf);
}
if (CORE_DEBUG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG) {
char buf[64];
*buf = '\0';
for (int i=0; i<15;i++) {
sprintf(&buf[strlen(buf)], "%02X ", Info.V1.AppSKey[i]);
}
log_v("AppSKey:\t\t%s", buf);
}
}
// Print session state for debugging
void
cMyLoRaWAN::printSessionState(const SessionState &State)