diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..5667061 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include + +#define MAX_RESTART 1 +#define MAX_FATAL_RESTART 3 + +uint64_t joinEUI = 0x0000000000000000; +uint64_t devEUI = 0x0000000000000000; +uint8_t appKey[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +uint8_t nwkKey[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +RTC_DATA_ATTR uint8_t fatalRestartCount = 0; +RTC_DATA_ATTR uint8_t restartCount = 0; + +ITransmitter* transmitter = new LoRaTransmitter( + joinEUI, + devEUI, + nwkKey, + appKey +); + +void fatalError(const char* msg){ + Serial.printf("[FATAL] %s\n", msg); + Serial.flush(); + delay(100); + + if (fatalRestartCount < MAX_FATAL_RESTART) { + fatalRestartCount++; + Serial.printf("[FATAL] Redémarrage %d/3\n", fatalRestartCount); + Serial.flush(); + ESP.restart(); + } + + Serial.printf("[FATAL] %d redémarrages : l'appareil entre en sommeil profond permanent\n", MAX_FATAL_RESTART); + Serial.flush(); + esp_deep_sleep_start(); +} + +void nonCriticalError(const char* msg){ + Serial.printf("[Error] %s\n", msg); + Serial.flush(); + delay(100); + + if (restartCount < MAX_RESTART) { + restartCount++; + Serial.printf("[Error] Tentative de redémarrage\n", restartCount); + Serial.flush(); + ESP.restart(); + } + + Serial.printf("[Error] %d redémarrage : l'appareil continue en mode dégradé\n", MAX_RESTART); +} + +void generateDailyGasPayload(uint32_t pulses, uint8_t *payload){ + payload[0] = (pulses >> 24) & 0xFF; + payload[1] = (pulses >> 16) & 0xFF; + payload[2] = (pulses >> 8) & 0xFF; + payload[3] = (pulses ) & 0xFF; +} + +void setup() { + Serial.begin(115200); + delay(2000); + + if (displayInit() != DisplayError::OK){ + nonCriticalError("Initialisation du périphérique d'affichage échouée"); + } + + if (transmitter->init() != TransmitError::OK){ + fatalError("Initialisation du périphérique radio échouée"); + } + if (transmitter->join() != TransmitError::OK){ + fatalError("Connexion au concentrateur LoRaWAN échouée"); + } + restartCount = 0; +} + +void loop() { + uint8_t payload[4]; + uint32_t pulses = simulateGasPulses(60); + + displayGasIndex(pulses); + + generateDailyGasPayload(pulses, payload); + transmitter->send(payload, sizeof(payload)); + + Serial.flush(); + + esp_deep_sleep(60); +} \ No newline at end of file