L14-Click 1.0
STM32WLE5CC LoRaWAN Sensor Platform
Loading...
Searching...
No Matches
mysensors_base.c
Go to the documentation of this file.
1/*
2 * mysensors_base.c
3 *
4 * Created on: 29. 1. 2026
5 * Author: Milan
6 */
7
8#include "mysensors_base.h"
9#include "mysensors.h"
10#include "main.h"
11#include "se-identity.h"
12#include "lora_app.h"
13#include "sys_app.h"
14#include "utils/mydefs.h"
15
16
17
18
19
21 .Sign = SYSTEMPARAMS_SIGN, // only sign check
22 .AppVersion = {SYSTEMPARAMS_APPVER00, SYSTEMPARAMS_APPVER01}, // application version, SYSTEMPARAMS_APPVER01 - validity
23#ifdef DEBUG
24 .SensTimeoutMeasure = SYSTEMPARAMS_MINSENSORTIME, // 30sec, sensorsSeq_Init
25#else
26 .SensTimeoutMeasure = SYSTEMPARAMS_DEFAULTSENSORTIME, // 10min, sensorsSeq_Init
27#endif
28 .SensAltitude = SYSTEMPARAMS_DEFAULTALTITUDE, // bar_bmp585_Read, bar_ils22qs_Read, scd41_Init
29 .SensSendInOnePacket = 0,
30 .SensAvailableSensors = (SYSPARAM_TEMP_HUM | SYSPARAM_BAR), // bit mask of sensors
31
32 .MemsStoreSensorData = 1, // myloraWan_MeasureFinish
33 .MemsMaxSensorData = 0, // mems_WriteToSystemParams, will be updated later, according to memory chip
34 .MemsCurrentCountSensorData = 0, // mems_WriteToSystemParams, will be updated later, according to memory chip
35
36
37 .LoRaPort = SYSTEMPARAMS_DEFAULTLORAWANPORT, // myLoraWan_LastDataSend
38 .LoRaRepeatTryConnect = 10, // OnLoRaWanConnected
39 .LoRaAdaptiveDataRate = LORAWAN_ADR_STATE, // systemParams_SetLoRaWanParams
40 .LoRaDataRate = LORAWAN_DEFAULT_DATA_RATE, // systemParams_SetLoRaWanParams
41 .LoRaTxPower = LORAWAN_DEFAULT_TX_POWER, // systemParams_SetLoRaWanParams
42 .LoRaClass = LORAWAN_DEFAULT_CLASS, // systemParams_SetLoRaWanParams
43 .LoRaRegion = ACTIVE_REGION, // systemParams_SetLoRaWanParams
44
45
46 .HWBatteryLevelStatus = 0, // mems_WriteToSystemParams, will be updated later
47 .HWBatteryMV = 0, // mems_WriteToSystemParams, will be updated later, according to memory chip
48 .HWDevEUI = {}, // default 0, will be updated in getAppDevEUI
49 .HWAppEUI = FORMAT32_KEY(SYSTEM_APP_EUI), // LoRaWAN_Init
50 .HWAppKEY = FORMAT_KEY(SYSTEM_APP_KEY), // LoRaWAN_Init, app KEY
51 .HWDevADDR = 0, // will be updated in getAppDevEUI
52
53 .DevRestart = 0, // not ready yet 13.3.2026 - has mean?
54 .DevReset = 0, // write to NFC wrong data to invoke restart and recreate data
55 .DevOnOff = 0, // in main()
56
57 .Dummy = {},//
58 .Crc = 0 //
59 };
60int8_t _tryInit = 1; // xxx_Is - try init for ensure....
61
62
63static UTIL_TIMER_Object_t _timerToOff = {}; // timer to activate of OFF Mode
64static uint32_t _timerTick = 0; // timer tick
65
66/**
67 * @brief - Dummy function - the timer need empty dummy, cannot be NULL
68 */
69static void OnTimerToOff(void*)
70{
71}
72
73///////////////////////////////////// public //////////////////////////////////
74
75/*
76 void boardGetUniqueId(uint8_t *id)
77 {
78 // Example for STM32L0/WL series
79 uint32_t ID_1 = *((uint32_t*) 0x1FFF7580);
80 uint32_t ID_2 = *((uint32_t*) 0x1FFF7584);
81 uint32_t ID_3 = *((uint32_t*) 0x1FFF7588);
82
83 // Mix the 96-bit UID into a 64-bit DevEUI
84 uint32_t idL = ID_1 ^ ID_3;
85 uint32_t idH = ID_2;
86
87 id[7] = (uint8_t) (idL >> 24);
88 id[6] = (uint8_t) (idL >> 16);
89 id[5] = (uint8_t) (idL >> 8);
90 id[4] = (uint8_t) (idL);
91 id[3] = (uint8_t) (idH >> 24);
92 id[2] = (uint8_t) (idH >> 16);
93 id[1] = (uint8_t) (idH >> 8);
94 id[0] = (uint8_t) (idH);
95 }
96
97
98void getDevEuiFromHardware(uint8_t *devEui)
99{
100 // The STM32WL has a 96-bit Unique ID
101 uint32_t uid0 = HAL_GetUIDw0();
102 uint32_t uid1 = HAL_GetUIDw1();
103 uint32_t uid2 = HAL_GetUIDw2();
104
105 // To match the RAK sticker logic (or create a unique 64-bit ID):
106 devEui[0] = (uint8_t) (uid0 >> 24);
107 devEui[1] = (uint8_t) (uid0 >> 16);
108 devEui[2] = (uint8_t) (uid0 >> 8);
109 devEui[3] = (uint8_t) (uid0);
110 devEui[4] = (uint8_t) (uid1 >> 24);
111 devEui[5] = (uint8_t) (uid1 >> 16);
112 devEui[6] = (uint8_t) (uid2 >> 8);
113 devEui[7] = (uint8_t) (uid2);
114}
115*/
116
117static void getDevEuiFromHardware(uint8_t *devEui)
118{
119 // --- Prefix: your HW/FW identity (3 bytes) ---
120 // Bit 1 of byte[0] set = locally administered (not IEEE-registered)
121 devEui[0] = SYSTEM_APP_DevEUI0; // 0x45; // 0x46 = locally-administered variant of 0x44, or use 0x45 for private network
122 devEui[1] = SYSTEM_APP_DevEUI1; // 0x87;
123 devEui[2] = SYSTEM_APP_DevEUI2; // 0xF2;
124
125 // --- Unique part: 4 bytes derived from STM32 96-bit UID ---
126 uint32_t uid0 = HAL_GetUIDw0();
127 uint32_t uid2 = HAL_GetUIDw2();
128 uint32_t unique = uid0 ^ uid2; // XOR for better mixing
129
130 devEui[3] = (uint8_t)(unique >> 24);
131 devEui[4] = (uint8_t)(unique >> 16);
132 devEui[5] = (uint8_t)(unique >> 8);
133 devEui[6] = (uint8_t)(unique);
134
135 // --- Checksum: CRC-8 over bytes [0..6] ---
136 devEui[7] = systemParams_CalculateCrc(devEui, 7);
137}
138
139
141{
142 const uint8_t def[8] =
143 { 0, 0, 0, 0, 0, 0, 0, 0 };
144
145 if (memcmp(_systemParams.HWDevEUI, def, MIN(sizeof(_systemParams.HWDevEUI), sizeof(def))) == 0)
147
148 if (_systemParams.HWDevADDR == 0)
149 GetDevAddr(&_systemParams.HWDevADDR);
150
151 return _systemParams.HWDevEUI;
152}
153
155{
156 return _systemParams.HWAppEUI;
157}
158
160{
161 return _systemParams.HWAppKEY;
162
163}
164
165
166// Internal Helper: CRC-8 Calculation
167uint8_t systemParams_CalculateCrc(uint8_t *data, uint8_t len)
168{
169 uint8_t crc = 0xFF;
170 for (uint8_t i = 0; i < len; i++)
171 {
172 crc ^= data[i];
173 for (uint8_t bit = 8; bit > 0; --bit)
174 {
175 if (crc & 0x80)
176 crc = (crc << 1) ^ 0x31;
177 else
178 crc = (crc << 1);
179 }
180 }
181 return crc;
182}
183
188
190{
191 uint8_t crc = systemParams_CalculateCrc((uint8_t*)par, sizeof(*par) - sizeof(par->Crc));
192 return crc == par->Crc;
193}
194
196{
197 if (SZ_SYSTEMPARAMS != sizeof(systemParams_t))
198 {
199 writeLog("The sizeof systemParams_t:%d, expected:%d", sizeof(systemParams_t), SZ_SYSTEMPARAMS);
201 }
203 systemParams_getAppDevEUI(); // set default setting
204}
205
207{
208 if (_timerToOff.ReloadValue == 0)
209 UTIL_TIMER_Create(&_timerToOff, SYSTEMPARAMS_MINTIME2OFF, UTIL_TIMER_ONESHOT, OnTimerToOff, NULL);
210 UTIL_TIMER_Start(&_timerToOff);
212}
213
215{
216 uint32_t curTick = HAL_GetTick() - _timerTick;
217 UTIL_TIMER_Stop(&_timerToOff);
218
219 if (curTick >= SYSTEMPARAMS_MINTIME2OFF)
220 {
223 }
224}
225
227{
228 _systemParams.SensTimeoutMeasure = CLAMP(_systemParams.SensTimeoutMeasure, SYSTEMPARAMS_MINSENSORTIME, SYSTEMPARAMS_MAXSENSORTIME); // max 1h
230 _systemParams.LoRaRepeatTryConnect = CLAMP(_systemParams.LoRaRepeatTryConnect, 0, 20);
231 _systemParams.LoRaDataRate = CLAMP(_systemParams.LoRaDataRate, DR_0, DR_5);
232 _systemParams.LoRaTxPower = CLAMP(_systemParams.LoRaTxPower, TX_POWER_0, TX_POWER_7);
233 _systemParams.LoRaClass = CLAMP(_systemParams.LoRaClass, (uint8_t)CLASS_A, (uint8_t)CLASS_C);
234 _systemParams.LoRaRegion = CLAMP(_systemParams.LoRaRegion, 0, 9);
235}
236
237
239{
240 return (_systemParams.SensAvailableSensors & sensorType) != 0;
241}
242
243#ifdef WRITELOG
244#define SYS_WR(inst, member) \
245 writeLog("%03u(%02X) " #member ":%d(%02X)", \
246 (unsigned)((uint8_t*)&((inst).member) - (uint8_t*)&(inst)), \
247 (unsigned)((uint8_t*)&((inst).member) - (uint8_t*)&(inst)), \
248 (int)((inst).member),(int)((inst).member))
249
250// Byte array as AA:BB:CC:... — length passed explicitly
251#define SYS_WR_ARR(inst, member, len) \
252 do { \
253 unsigned _off = (unsigned)((uint8_t*)&((inst).member) - (uint8_t*)&(inst)); \
254 char _buf[3*(len)]; \
255 for (unsigned _i = 0; _i < (unsigned)(len); _i++) { \
256 _buf[_i*3+0] = "0123456789ABCDEF"[((inst).member[_i] >> 4) & 0xF]; \
257 _buf[_i*3+1] = "0123456789ABCDEF"[ (inst).member[_i] & 0xF]; \
258 _buf[_i*3+2] = (_i < (unsigned)(len)-1) ? ':' : '\0'; \
259 } \
260 writeLog("%03u(%02X) " #member ":%s", _off, _off, _buf); \
261 } while(0)
262
263// String field (char array)
264#define SYS_WR_STR(inst, member) \
265 writeLog("%03u(%02X) " #member ":%s", \
266 (unsigned)((uint8_t*)&((inst).member) - (uint8_t*)&(inst)), \
267 (unsigned)((uint8_t*)&((inst).member) - (uint8_t*)&(inst)), \
268 (inst).member)
269
270
271void systemParams_Log(const char* info)
272{
273 writeLog("=========== systemParams_Log %s =============", info);
275 SYS_WR_ARR (_systemParams, AppVersion, 2);
276
277 SYS_WR (_systemParams, SensTimeoutMeasure);
278 SYS_WR (_systemParams, SensAltitude);
279 SYS_WR (_systemParams, SensSendInOnePacket);
280 SYS_WR (_systemParams, SensAvailableSensors);
281
282 SYS_WR (_systemParams, MemsStoreSensorData);
283 SYS_WR (_systemParams, MemsMaxSensorData);
284 SYS_WR (_systemParams, MemsCurrentCountSensorData);
285
286 SYS_WR (_systemParams, LoRaPort);
287 SYS_WR (_systemParams, LoRaRepeatTryConnect);
288 SYS_WR (_systemParams, LoRaAdaptiveDataRate);
289 SYS_WR (_systemParams, LoRaDataRate);
290 SYS_WR (_systemParams, LoRaTxPower);
291 SYS_WR (_systemParams, LoRaClass);
292 SYS_WR (_systemParams, LoRaRegion);
293
294
295 SYS_WR (_systemParams, HWBatteryLevelStatus);
296 SYS_WR (_systemParams, HWBatteryMV);
297 SYS_WR_ARR (_systemParams, HWDevEUI, 8);
298 SYS_WR_ARR (_systemParams, HWAppEUI, 8);
299 SYS_WR_ARR (_systemParams, HWAppKEY, 16);
300 SYS_WR (_systemParams, HWDevADDR);
301
302 SYS_WR (_systemParams, DevRestart);
303 SYS_WR (_systemParams, DevReset);
304 SYS_WR (_systemParams, DevOnOff);
305
306 SYS_WR (_systemParams, Crc);
307 writeLog("==========================================");
308}
309#endif
Header of application of the LRWAN Middleware.
#define LORAWAN_ADR_STATE
Definition lora_app.h:82
#define ACTIVE_REGION
Definition lora_app.h:42
#define LORAWAN_DEFAULT_DATA_RATE
Definition lora_app.h:88
#define LORAWAN_DEFAULT_CLASS
Definition lora_app.h:71
#define LORAWAN_DEFAULT_TX_POWER
Definition lora_app.h:95
: Header for main.c file. This file contains the common defines of the application.
void Error_Handler(void)
Default error handler called by HAL on unrecoverable errors. Disables interrupts and enters an infini...
Definition main.c:505
@ MODEDEVICE_OFF
Definition main.h:59
void writeLog(const char *format,...)
Format and send a log message over UART (printf-style). Available only when WRITELOG is defined; comp...
Definition main.c:97
void setModeDevice(modeDevice_t mod)
set new device mode
Definition main.c:159
#define CLAMP(val, minVal, maxVal)
Clamp val to the closed interval [minVal, maxVal]. All three arguments are evaluated exactly once via...
Definition mydefs.h:50
void sensors_Retiming()
the System goes to OFF mode - retiming of timer sensor reading
Definition mysensors.c:424
static void OnTimerToOff(void *)
Dummy function - the timer need empty dummy, cannot be NULL
void sensorsBase_StartTimerToOff()
start timer to off the function is called from PWR_EnterStopMode - timer is started
static void getDevEuiFromHardware(uint8_t *devEui)
uint8_t * systemParams_getAppKey()
Return a pointer to the AppKey stored in _systemParams. Used by the LoRaWAN stack to derive session k...
void systemParams_SetCRCSystemParams()
Recalculate and store the CRC in _systemParams.Crc. Call this after modifying any field of _systemPar...
static UTIL_TIMER_Object_t _timerToOff
uint8_t systemParams_CalculateCrc(uint8_t *data, uint8_t len)
Calculate a CRC-8 checksum (Sensirion polynomial) over a byte buffer. Used to validate sensor I2C res...
uint8_t * systemParams_getAppEUI()
Return a pointer to the AppEUI (JoinEUI) stored in _systemParams. Used by the LoRaWAN stack during th...
uint8_t * systemParams_getAppDevEUI()
Return a pointer to the DevEUI stored in _systemParams. The DevEUI is auto-generated from the chip UI...
void sensorsBase_StopTimerToOff()
stop timer to off the function is called from PWR_ExitStopMode - the timer value is checked and the P...
uint8_t systemParams_CheckCRC(const systemParams_t *par)
Verify the CRC field of a systemParams_t structure.
void systemParams_Log(const char *info)
Log the current _systemParams fields to the UART debug output.
#define SYS_WR_ARR(inst, member, len)
#define SYS_WR(inst, member)
void systemParams_Correction()
Clamp all RW fields of _systemParams to their valid ranges. Called after loading parameters from NFC ...
#define SYS_WR_STR(inst, member)
static uint32_t _timerTick
void sensorsBase_Init()
Initialization of base sensor data structure.
uint8_t systemParams_IsSensorAvaiable(systemParams_Sensors_t sensorType)
Check whether a particular sensor is enabled in _systemParams.AvailableSensors.
#define SYSTEMPARAMS_MAXLORAWANPORT
Maximum valid LoRaWAN application port number (ports 224–255 are reserved).
#define SYSTEMPARAMS_APPVER00
Application firmware minor version number (plain integer).
#define SYSTEMPARAMS_MINSENSORTIME
Minimum allowed sensor measurement interval in milliseconds (30 seconds).
systemParams_t _systemParams
#define SYSTEMPARAMS_DEFAULTALTITUDE
The default sensor altitue.
#define SZ_SYSTEMPARAMS
Total size in bytes of the systemParams_t structure stored on the NFC tag and send via LoRa - the siz...
#define SYSTEMPARAMS_DEFAULTLORAWANPORT
Default LoRaWAN application port used for sensor uplinks.
#define SYSTEMPARAMS_MINTIME2OFF
Minimum idle time in milliseconds before the device enters OFF (standby) mode. Values below ~10 s are...
#define SYSTEM_APP_KEY
Default LoRaWAN AppKey (16 bytes – overridden via NFC before deployment).
systemParams_Sensors_t
Bitmask of sensor modules that are enabled / available for data collection. Used in systemParams_t....
@ SYSPARAM_BAR
@ SYSPARAM_TEMP_HUM
#define SYSTEM_APP_EUI
Default LoRaWAN JoinEUI / AppEUI (8 bytes, all zeros – overridden via NFC).
#define SYSTEMPARAMS_MINLORAWANPORT
Minimum valid LoRaWAN application port number (port 0 is reserved by the stack).
#define SYSTEM_APP_DevEUI0
First byte of the 3-byte OUI prefix used in the auto-generated DevEUI.
#define SYSTEMPARAMS_DEFAULTSENSORTIME
Default sensor measurement interval in milliseconds (10 minutes).
int8_t _tryInit
#define SYSTEM_APP_DevEUI1
Second byte of the 3-byte OUI prefix used in the auto-generated DevEUI.
#define SYSTEMPARAMS_SIGN
4-byte ASCII signature stored at offset 0 of systemParams_t to validate data integrity.
#define SYSTEMPARAMS_APPVER01
Application firmware major version number (plain integer) - check of validity struct together with SY...
#define SYSTEM_APP_DevEUI2
Third byte of the 3-byte OUI prefix used in the auto-generated DevEUI.
#define SYSTEMPARAMS_MAXSENSORTIME
Maximum allowed sensor measurement interval in milliseconds (18 hour).
Secure Element identity and keys.
#define FORMAT_KEY(...)
#define FORMAT32_KEY(...)
System configuration parameters – persisted in NFC EEPROM at address 0. The structure contains all mo...
uint32_t HAL_GetTick(void)
Definition sys_app.c:337
Function prototypes for sys_app.c file.
void GetDevAddr(uint32_t *devAddr)
callback to get the board 32 bits unique ID (LSB)
Definition sys_app.c:239