feat: add nonces persistence across reboot

This commit is contained in:
Alexis Fourmaux 2026-05-03 17:11:25 +02:00
parent 01289ec357
commit d569a07655
2 changed files with 66 additions and 11 deletions

View file

@ -2,11 +2,16 @@
#include <SPI.h>
#include <RadioLib.h>
#include <Preferences.h>
Preferences prefs;
SX1276 radio = new Module(LORA_NSS, LORA_DIO0, LORA_RST, LORA_DIO1);
LoRaWANNode node(&radio, &EU868);
void loraReset() {
uint8_t noncesBuffer[RADIOLIB_LORAWAN_NONCES_BUF_SIZE];
void loraReset()
{
pinMode(LORA_RST, OUTPUT);
digitalWrite(LORA_RST, LOW);
delay(10);
@ -14,36 +19,84 @@ void loraReset() {
delay(10);
}
void loraInit() {
void loraInit()
{
loraReset();
SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_NSS);
Serial.print("[LoRa] Init... ");
int state = radio.begin();
if (state != RADIOLIB_ERR_NONE) {
if (state != RADIOLIB_ERR_NONE)
{
Serial.printf("ERREUR %d\n", state);
while (true) { delay(1000); }
while (true)
{
delay(1000);
}
}
Serial.println("OK");
}
void loraJoin(){
void loraRestoreDevNonce()
{
prefs.begin("lorawan");
size_t len = prefs.getBytesLength("nonces");
if (len == RADIOLIB_LORAWAN_NONCES_BUF_SIZE)
{
prefs.getBytes("nonces", noncesBuffer, RADIOLIB_LORAWAN_NONCES_BUF_SIZE);
}
else
{
Serial.println("[NVS] Aucune donnée trouvée, buffer initialisé à zéro");
memset(noncesBuffer, 0, RADIOLIB_LORAWAN_NONCES_BUF_SIZE);
}
prefs.end();
node.setBufferNonces(noncesBuffer);
}
void loraPersistDevNonce()
{
prefs.begin("lorawan");
uint8_t buffer[RADIOLIB_LORAWAN_NONCES_BUF_SIZE];
uint8_t *persist = node.getBufferNonces();
memcpy(buffer, persist, RADIOLIB_LORAWAN_NONCES_BUF_SIZE);
size_t result = prefs.putBytes("nonces", buffer, RADIOLIB_LORAWAN_NONCES_BUF_SIZE);
prefs.end();
}
void loraJoin()
{
node.beginOTAA(joinEUI, devEUI, nwkKey, appKey);
loraRestoreDevNonce();
Serial.print("[LoRaWAN] Join... ");
int state = node.activateOTAA();
if (state != RADIOLIB_LORAWAN_NEW_SESSION) {
loraPersistDevNonce();
if (state != RADIOLIB_LORAWAN_NEW_SESSION)
{
Serial.printf("Echec : %d\n", state);
while (true) { delay(1000); }
while (true)
{
delay(1000);
}
}
Serial.println("Join OK !");
}
void loraSend(uint8_t payload[], size_t size){
void loraSend(uint8_t payload[], size_t size)
{
int state = node.sendReceive(payload, size, 1);
if (state == RADIOLIB_ERR_NONE || state == RADIOLIB_LORAWAN_NO_DOWNLINK) {
if (state == RADIOLIB_ERR_NONE || state == RADIOLIB_LORAWAN_NO_DOWNLINK)
{
Serial.println("[TX] OK");
} else {
}
else
{
Serial.printf("[TX] Erreur : %d\n", state);
}
}

View file

@ -7,5 +7,7 @@ void loraReset();
void loraInit();
void loraJoin();
void loraSend(uint8_t payload[], size_t size);
void loraPersistDevNonce();
void loraSaveDevNonce();
#endif