diff --git a/README.md b/README.md index ab61cac134e11142d2bc6edc73d7dd467864c6ba..263f5c4b59a7f3ad3e0930a4f299e4057d4a1cd8 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,17 @@ -# neOCampus-arduino library -neOCampus IoT support library for Arduino. This library will provides support for the following neOCampus boards: - * neOSensor boards based on ESP8266 (rev. >= V2) +# neOCampus-arduino | home of the neOSensor end-devices # +________________________________________________________________ + +This repository provides support for the following neOCampus boards: * neOSensor boards based on ESP32 * neOSensor-AirQuality board (ESP32) from CNRS' LCC lab. + * neOSensor boards based on ESP8266 (rev. >= V2) + +All this work was undertaken at Université Toulouse 3 / IRIT laboratory in the context of the [neOCampus](https://neocampus.org "neOCampus corporate") operation. ## NEWS ## - * **[Dec.20]** added PCB from ESP8266 version 4 (KiCad) :)\ - * **[Aug.20]** new definition board for neOSensor-AirQuality board :)\ + * **[Feb.21]** added KiCad PCB for neOSensor v5 (ESP32 based) :)\ + * **[Dec.20]** added PCB from ESP8266 version 4 (KiCad)\ + * **[Aug.20]** new definition board for neOSensor-AirQuality board\ added definition board for (future) neOSensor esp32 based board\ added suppport for boards configuration via sensOCampus JSON config\ added Arduino IDE support for our various neOSensor boards\ @@ -21,10 +26,13 @@ This board comes from CNRS LCC lab, it's a PhD work undertaken by Aymen Sendi (a The board features four specific sensors able to measure NO2, CO, CH20, NO2 alternate. ## Getting started ## -First of all, you ought to install esp32 or esp8266 support in your Arduino IDE. +First of all, you ought to install esp32, esp8266 or CubeCell support in your Arduino IDE. - - esp8266 https://arduino.esp8266.com/stable/package_esp8266com_index.json - - esp32 https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json +| Device | Arduino Board Manager json file | +|----------|---------------------------------------------------------------------------------------------| +| esp8266 | https://arduino.esp8266.com/stable/package_esp8266com_index.json | +| esp32 | https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json | +| CubeCell | https://resource.heltec.cn/download/package_CubeCell_index.json | Then, run script './deploy.sh' and boards will get added to your Arduino boards list :) @@ -45,7 +53,9 @@ Once you've launched the Arduino IDE, before compiling and uploading sketches to - debug serial link speed 115200 ### WiFi setup ### -Once started the board will provides a WiFi Access Point (AP) named: `neOSensor_xxxx` where xxxx are the MAC address last bytes. +Only for ESP based boards. + +Once started, the board will provides a WiFi Access Point (AP) named: `neOSensor_xxxx` where xxxx are the MAC address last bytes. **First time setup**\ In this case, AP will get available for 5mn for you to configure SSID along with WPA2 key. diff --git a/library.json b/old/library.json similarity index 100% rename from library.json rename to old/library.json diff --git a/library.properties b/old/library.properties similarity index 100% rename from library.properties rename to old/library.properties diff --git a/tools/EspExceptionDecoder/tool/EspExceptionDecoder.jar b/tools/EspExceptionDecoder/tool/EspExceptionDecoder.jar deleted file mode 100644 index 0c4e69bd2027ce567a705d66f90a581fdcc91267..0000000000000000000000000000000000000000 Binary files a/tools/EspExceptionDecoder/tool/EspExceptionDecoder.jar and /dev/null differ diff --git a/work/.gitkeep b/work/.gitkeep deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/work/README.md b/work/README.md deleted file mode 100644 index 68146458b6b9d737b3a442aaff5678848437e57d..0000000000000000000000000000000000000000 --- a/work/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Work area: temporary space to hold orig files'n dirs # - -## TODO ## -**library** - - mainly from sensocapus files, create the neOCampus lib - - take care of logging facility (maybe to integrate it with our lib) - - OTA, I2C, EEPROM ?? part of the library ??? - - continuous integration - -**examples** - - simple app that connect to sensocampus to retrieve and store both credentials and config - - sample app featuring a SSL connexion to the neOCampus MQTT broket - - ... - diff --git a/work/neocampus_libs.orig/log_levels.h b/work/neocampus_libs.orig/log_levels.h deleted file mode 100644 index 482abd2dc961bc3fbad127f9d5298afea1d44bf8..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/log_levels.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * neOCampus operation - * - * Debug levels definitions - * - * Thiebolt F. July 17 - * - */ - - -#ifndef _LOG_LEVELS_H_ -#define _LOG_LEVELS_H_ - -/* - * Includes - */ - - - -/* - * Definitions - */ -/* - * Logging levels: - * 1: ERROR errors - * 3: WARN errors and warnings - * 5: INFO errors, warnings and informational (default) - * 4: DEBUG errors, warnings, informational and debug - */ -#define LOG_LVL_ERROR 1 -#define LOG_LVL_WARNING 3 -#define LOG_LVL_INFO 5 -#define LOG_LVL_DEBUG 10 - -#define DEFL_LOG_LVL LOG_LVL_INFO - - -#endif /* _LOG_LEVELS_H_ */ - - diff --git a/work/neocampus_libs.orig/neocampus.h b/work/neocampus_libs.orig/neocampus.h deleted file mode 100644 index 8d304d92f4a2b5094d929221a5756ce39fba5834..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * neOCampus operation - * - * neOCampus *all-in-one* base definitions - * - * F.Thiebolt Nov.19 add MQTT socket timeout definition - * add WIFI_AP_MODE_CREDENTIALS - * F.Thiebolt Jun.18 start to merge boards types - * manage sensocampus sandbox through wifi parameters options - * Thiebolt F. July 17 initial release - * - */ - - -#ifndef _NEOCAMPUS_H_ -#define _NEOCAMPUS_H_ - -/* - * Includes - */ - -#include <Arduino.h> - -#include "log_levels.h" - - -/* - * Generic types definitions - */ -typedef void (*voidFuncPtr)(void); -typedef uint32_t firmwareRev_t; - - -/* - * Simultaneous TCP connexions - */ -#ifndef MAX_TCP_CONNECTIONS -#define MAX_TCP_CONNECTIONS 8 // maximum number of simultaneous TCP connexions (5 as default) -#endif - - - -/* - * >>> <<< - * >>> BOARD SELECTION <<< - * >>> <<< - * - * Select proper board definition to include - * - neOSensor.h all ESP8266 based hardware :) - */ -#include "neOSensor.h" - - - -/* - * LOGS definitions - */ -// set neOCampus logging level (min. is 1) -#ifndef LOG_LEVEL -#define LOG_LEVEL LOG_LVL_DEBUG -#endif /* LOG_LEVEL */ - -/* I2C low-level msg debug - * WARNING: display a lot of information about I2C messages! */ -//#define DEBUG_I2C - -// WiFi Manager debug mode on/off (default is on) -#define DEBUG_WIFI_MANAGER - -/* MQTT low-level msg debug - * WARNING: display a lot of information about MQTT messages! */ -#define MQTT_LOWLEVEL_DEBUG - - - - -/* - * SensOCampus - */ -/* - * WARNING: TESTING PURPOSES ONLY - * Activating definition below means that sensOCampus - * won't get contacted thus using defaults (i.e neOCampus sandbox) - * - * [Jun.18] removed in favour of customizable WiFiManager option :) - * - * #define DISABLE_SENSOCAMPUS // comment out to activate sensOCampus (normal mode) - * - */ -// sensOCampus credentials & config related definitions -#define MQTT_SERVER_NAME_LENGTH 64 // max length of MQTT server name -#define MQTT_BASE_TOPIC_LENGTH 64 // max length of MQTT base topic (i.e building/room) -#define SENSO_MQTT_LOGIN_LENGTH 32 // max length of sensOCampus MQTT login -#define SENSO_MQTT_PASSWD_LENGTH 64 // max length of sensOCampus MQTT password - -// defaults values for testing purposes -#define DEFL_MQTT_SERVER "neocampus.univ-tlse3.fr" -#define DEFL_MQTT_STD_PORT 1883 -#define DEFL_MQTT_ABROAD_PORT 10883 // for abroad access -#define DEFL_MQTT_LOGIN "test" // for SANDBOX mode -#define DEFL_MQTT_PASSWD "test" // for SANDBOX mode -#define DEFL_MQTT_TOPIC "TestTopic" // for SANDBOX mode - - -/* - * PubSub MQTT client (re)definitions - * Note: this file OUGHT to get included within PubSubClient.h - */ -#define MQTT_KEEPALIVE 60 -#define MQTT_SOCKET_TIMEOUT 60 -#define MQTT_MAX_PACKET_SIZE 256 - - -/* - * WiFi (and loosely related to) definitions - */ -// type for mac address in raw format -typedef uint8_t mac_addr_t[6]; - -/* --- SPIFFS WiFi related definitions - * Note: remember there's no directory support @ SPIFFS level! - */ -#define WIFI_CONFIG_FILE "/wifi.json" // (optional) WiFi configuration file for large-scale deployment in well-known env - -/* -typedef struct { - uint8_t bytes[6]; -} mac_addr_t; -*/ - -// type for mac address in string format -typedef char mac_str_t[18]; - -/* WiFi AP mode credentials: - * Password required to get connected to the WiFi settings mode. - */ -#define WIFI_AP_CREDENTIALS "neOSensor" - - -/* - * Modules related definitions - */ -/* a module's config file will be something like - * "/module_luminosity.json" - */ -#define MCFG_FILE_PREFIX "/module_" -#define MCFG_FILE_SUFFIX ".json" - - -#endif /* _NEOCAMPUS_H */ diff --git a/work/neocampus_libs.orig/neocampus_OTA.cpp b/work/neocampus_libs.orig/neocampus_OTA.cpp deleted file mode 100644 index cced73a7f06ddf83e2b304b9b728e3e942491319..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_OTA.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/* - * neOCampus operation - * - * Over The Air (OTA) firmware upgrade utilities - * - * Thiebolt F. Nov.19 upgrade to Arduino JSON6 - * Thiebolt F. August 17 - * - */ - - - -/* ---------------------------------------------------------------------------- - * --- Includes --------------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -#include <Arduino.h> -#include <EEPROM.h> -#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson -#include <ESP8266httpUpdate.h> - - -#include "neocampus.h" -#include "neocampus_debug.h" - -#include "neocampus_OTA.h" -#include "neocampus_utils.h" - - - -/* ---------------------------------------------------------------------------- - * --- Global shared variables/functions -------------------------------------- - * ---------------------------------------------------------------------------- - */ -extern bool _need2reboot; - - - -/* ---------------------------------------------------------------------------- - * --- Definitions ------------------------------------------------------------ - * ---------------------------------------------------------------------------- - */ -#define OTA_JSON_SIZE (JSON_OBJECT_SIZE(10)) // no more than 10 fields in JSON structure - - - -/* ---------------------------------------------------------------------------- - * --- Functions -------------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ - -/* - * Main firmware update function - */ -bool neOCampusOTA( void ) { - - if( _need2reboot ) return false; - - log_info(F("\n[OTA] start checking for firmware update ...")); - - // build url to json file - char ota_url[OTA_URL_LENGTH]; - unsigned int _wlen; - _wlen=snprintf(ota_url, sizeof(ota_url), - "%s/%s/%s/%s", OTA_BASE_URL,getHardware(),getBoardName(),OTA_JSON_FILE); - if( _wlen >= sizeof(ota_url) ) { - log_error(F("\n[OTA] error OTA_URL buffer undersized!")); log_flush(); - return false; - } - - // get url's ArduinoJson file content - char ota_json[OTA_JSON_LENGTH]; - if( http_get( ota_url, ota_json, sizeof(ota_json) ) != true ) { - return false; - } - - // get firmware revision from json and compare to current - StaticJsonDocument<OTA_JSON_SIZE> root; - auto err = deserializeJson( root, ota_json ); - if( err ) { - log_error(F("\n[OTA] ERROR parsing JSON file!")); - log_error(F("\n[OTA] ERROR msg: ")); log_error(err.c_str()); log_flush(); - return false; - } - - // check for revision field - if( (root.containsKey(F("revision"))==false) ) { - log_error(F("\n[OTA] ERROR no 'revision' field' in JSON file ?!?!")); - return false; - } - // ok, let's acquire this revision field - firmwareRev_t remoteFWver = (firmwareRev_t)(root[F("revision")].as<unsigned int>()); - - if( remoteFWver <= getFirmwareRev() ) { - // nothing todo, we're already with the latest version - log_info(F("\n[OTA] current firmware version ")); - log_info(getFirmwareRev(),DEC); log_info(F(" is equal or higher than remote ")); log_info(remoteFWver,DEC); - log_flush(); - return false; - } - - // check for image field - if( (root.containsKey(F("image"))==false) ) { - log_error(F("\n[OTA] ERROR no 'image' field' in JSON file ?!?!")); - return false; - } - - log_info(F("\n[OTA] on way to Firmware upgrade from ")); - log_info(getFirmwareRev(),DEC); log_info(F(" revision to new version ")); log_info(remoteFWver,DEC); - log_flush(); - - yield(); - /* - * WARNING: root["image"] is a pointer to ArduinoJson inner buffer - */ - return neOCampusOTA_url(root[F("image")]); -} - - -// upgrade from image's url -bool neOCampusOTA_url( const char *img_url ) { - - bool status = false; - - log_debug(F("\n[OTA] choosen firmware: "));log_debug(img_url);log_flush(); - // disable reboot on update - ESPhttpUpdate.rebootOnUpdate(false); - - t_httpUpdate_return ret = ESPhttpUpdate.update(img_url); - switch(ret) { - case HTTP_UPDATE_FAILED: - log_error(F("[OTA] ERROR update failed (!!): ")); log_error(ESPhttpUpdate.getLastErrorString()); - log_error(F(" ... continuing ...")); log_flush(); - break; - case HTTP_UPDATE_NO_UPDATES: - log_error(F("[OTA] no update ?!?!: ")); log_error(ESPhttpUpdate.getLastErrorString()); - log_error(F("... continuing ...")); log_flush(); - break; - case HTTP_UPDATE_OK: - log_info(F("\n[OTA] Update ok :)")); log_flush(); - status = true; - break; - } - - // check status - if( ! status ) { - return status; - } - - // closing things before restart - log_info(F("\n[OTA] prepare things before restarting with new firmware ...")); - _need2reboot = true; - - return status; -} - - -// get current firmwre revision -firmwareRev_t getFirmwareRev() { - return BOARD_FWREV; -} - -// get hardware (e.g ESP8266, ESP32, unknown ...) -const char *getHardware( void ) { -#ifdef ESP8266 - static const char hardware[] = "esp8266"; -#elif ESP32 - static const char hardware[] = "esp32"; -#else - static const char hardware[] = "unknown"; -#endif - return hardware; -} - -// get board name (e.g neOSensor) -const char *getBoardName( void ) { - return BOARD_NAME; -} - -// get board revision -uint8_t getBoarRev( void ) { - return (uint8_t)(BOARD_REVISION); -} - - diff --git a/work/neocampus_libs.orig/neocampus_OTA.h b/work/neocampus_libs.orig/neocampus_OTA.h deleted file mode 100644 index 1bb32254e3eee2d090b8273220c14e5aba614690..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_OTA.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * neOCampus operation - * - * Over The Air (OTA) firmware upgrade utilities - * - * Thiebolt F. August 17 - * - */ - - - -#ifndef _NEOCAMPUS_OTA_H_ -#define _NEOCAMPUS_OTA_H_ - - - -/* ---------------------------------------------------------------------------- - * --- Includes --------------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -#include <Arduino.h> - - - -/* ---------------------------------------------------------------------------- - * --- Definitions ------------------------------------------------------------ - * ---------------------------------------------------------------------------- - */ -/* - * OTA URL is something like - * http://neocampus.univ-tlse3.fr/images/${hardware}/${board_name}/default.json - */ -#define OTA_BASE_URL "http://neocampus.univ-tlse3.fr/images" -#define OTA_JSON_FILE "default.json" // name of file to look after @ neocampus server -#define OTA_URL_LENGTH 128 // maximum length of OTA's url -#define OTA_JSON_LENGTH 512 // maximum size of json file retrieved from server - - -/* ---------------------------------------------------------------------------- - * --- Functions prototypes --------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -/* - * Main firmware update function - */ -bool neOCampusOTA( void ); - -// upgrade from image's url -bool neOCampusOTA_url( const char * ); - -// get current revision firmware -firmwareRev_t getFirmwareRev(); - -// get hardware (e.g ESP8266, ESP32, unknown ...) -const char *getHardware( void ); - -// get board name (e.g neOSensor) -const char *getBoardName( void ); - -// get board revision -uint8_t getBoarRev( void ); - -#endif /* _NEOCAMPUS_OTA_H */ - diff --git a/work/neocampus_libs.orig/neocampus_debug.h b/work/neocampus_libs.orig/neocampus_debug.h deleted file mode 100644 index 146f6e4b470c3df0d1f63b67bbe21aed9db26b62..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_debug.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * neOCampus operation - * - * Debug definitions - * - * Thiebolt F. June 17 - * - */ - - -#ifndef _NEOCAMPUS_DEBUG_H_ -#define _NEOCAMPUS_DEBUG_H_ - -/* - * Includes - */ -#include <Arduino.h> - -#include "log_levels.h" - - - -/* - * Definitions - */ - -// define minimum messages -#if !defined(LOG_LEVEL) - #define LOG_LEVEL DEFL_LOG_LVL -#endif - - -// define macros related to various log levels -#define log_flush() { Serial.flush(); } - - -#if (LOG_LEVEL >= LOG_LVL_DEBUG) - #define log_debug(X, ...) { Serial.print(X, ## __VA_ARGS__); } -#else - #define log_debug(X, ...) {} -#endif - -#if (LOG_LEVEL >= LOG_LVL_INFO) - #define log_info(X, ...) { Serial.print(X, ## __VA_ARGS__); } -#else - #define log_info(X, ...) {} -#endif - -#if (LOG_LEVEL >= LOG_LVL_ERROR) - #define log_error(X, ...) { Serial.print(X, ## __VA_ARGS__); } -#else - #define log_error(X, ...) {} -#endif - -#if (LOG_LEVEL >= LOG_LVL_WARNING) - #define log_warning(X, ...) { Serial.print(X, ## __VA_ARGS__); } -#else - #define log_warning(X, ...) {} -#endif - - -#endif /* _NEOCAMPUS_DEBUG_H */ - - diff --git a/work/neocampus_libs.orig/neocampus_eeprom.cpp b/work/neocampus_libs.orig/neocampus_eeprom.cpp deleted file mode 100644 index 63eb7daa591e864e4c198a601fd2d4df74e1b189..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_eeprom.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * neOCampus operation - * - * EEPROM operations to store / retrieve keys - * - * THiebolt F. May.18 replace min() with _min() due to esp8266 arduino release >= 2.4.0 - * Thiebolt F. July 17 initial release - * - */ - - - -/* - * Includes - */ -#include <EEPROM.h> - -// neOCampus specific includes -#include "neocampus_eeprom.h" - - - - -/* - * Functions - */ -// HEX DUMP of EEPROM content -void hexdumpEEPROM( void ) { - log_debug(F("\n### EEPROM HEX DUMP (only first 20bytes) ###")); log_flush(); - for(uint8_t i=0; i < 20; i++ ){ - char _line[30]; - snprintf(_line,sizeof(_line),"\nEEPROM[%u] = 0x%02x '%c'", i, EEPROM.read(i), EEPROM.read(i)); - log_debug(_line); delay(20); log_flush(); - } -} - - -// EEPROM setup for sensOCampus purpose -bool setupEEPROM( void ) { - log_info(F("\n[EEPROM] starting setup with size = ")); log_info(NEOCAMPUS_EEPROM_SIZE,DEC); log_flush(); - - // declare EEPROM size - EEPROM.begin( NEOCAMPUS_EEPROM_SIZE ); - - // check if already initialized ? - if( checkEEPROMvalidity() ) { - log_debug(F("\n[EEPROM] already initialized :) ")); - return true; - } - - // format EEPROM - formatEEPROM(); - - // set validity flag - setEEPROMvalidity(); - - return true; -} - -// check EEPROM is valid -inline bool checkEEPROMvalidity( void ) { - if( EEPROM.read(EEPROM_ADDR_CHECK) != (uint8_t)EEPROM_VALIDITY_CHECK ) return false; - if( EEPROM.read(EEPROM_ADDR_SIZE) != (uint8_t)EEPROM_ADDR_LAST ) return false; - return true; -} - -// invalidate EEPROM content -void clearEEPROMvalidity( void ) { - EEPROM.write(EEPROM_ADDR_CHECK, (uint8_t)0x00); - delay(20); - EEPROM.commit(); -} - -// format EEPROM for neOCampus use -bool formatEEPROM( void ) { - log_debug(F("\n[EEPROM] nb bytes cleared is "));log_debug(EEPROM_ADDR_LAST,DEC); log_flush(); - for( uint16_t i=0; i<EEPROM_ADDR_LAST; i++ ) { - EEPROM.write(i, 0); - } - delay(20); - return EEPROM.commit(); -} - -// set EEPROM validity flag -inline void setEEPROMvalidity( void ) { - EEPROM.write(EEPROM_ADDR_CHECK, (uint8_t)EEPROM_VALIDITY_CHECK); - EEPROM.write(EEPROM_ADDR_SIZE, (uint8_t)EEPROM_ADDR_LAST); - delay(20); - EEPROM.commit(); -} - - -/* - * low-level write EEPROM function - */ -void _writeEEPROM( uint16_t start, uint16_t maxsize, const char *buf ) { - //log_debug(F("\n[EEPROM] from addr : "));log_debug(start,DEC); log_flush(); - //log_debug(F("\n[EEPROM] writing string : ")); log_debug(buf); log_flush(); - for( uint16_t i=start; i<(uint16_t)(start+maxsize); i++ ) { - EEPROM.write(i, buf[i-start]); - if( buf[i-start] == '\0' ) break; - } - delay(20); - EEPROM.commit(); -} - -// store 'login' within EEPROM -void setEEPROMlogin( const char *buf ) { - // call to low-level write EEPROM function - _writeEEPROM( (uint16_t)EEPROM_ADDR_MQTT_LOGIN, (uint16_t)SENSO_MQTT_LOGIN_LENGTH, buf ); -} - -// store 'passwd' within EEPROM -void setEEPROMpasswd( const char *buf ) { - // call to low-level write EEPROM function - _writeEEPROM( (uint16_t)EEPROM_ADDR_MQTT_PASSWD, (uint16_t)SENSO_MQTT_PASSWD_LENGTH, buf ); -} - - -/* - * low-level read EEPROM function - */ -bool _readEEPROM( uint16_t start, uint16_t maxsize, char *buf ) { - uint16_t i; - for( i=(uint16_t)start; i<(uint16_t)(start+maxsize); i++ ) { - buf[i-start] = EEPROM.read(i); - if( buf[i-start] == '\0' ) break; - } - // check for zero sized strings - if( i == start ) return false; - return true; -} - -// retrieve 'login' from EEPROM -bool getEEPROMlogin( char *buf, size_t bufsize ) { - if( !buf or bufsize==0 ) return false; - // call to low-level read EEPROM function - return _readEEPROM( (uint16_t)EEPROM_ADDR_MQTT_LOGIN, (uint16_t)(_min(SENSO_MQTT_LOGIN_LENGTH,bufsize)), buf ); -} - -// retrieve 'passwd' from EEPROM -bool getEEPROMpasswd( char *buf, size_t bufsize ) { - if( !buf or bufsize==0 ) return false; - // call to low-level read EEPROM function - return _readEEPROM( (uint16_t)EEPROM_ADDR_MQTT_PASSWD, (uint16_t)(_min(SENSO_MQTT_PASSWD_LENGTH,bufsize)), buf ); -} - - diff --git a/work/neocampus_libs.orig/neocampus_eeprom.h b/work/neocampus_libs.orig/neocampus_eeprom.h deleted file mode 100644 index fcab5833c78196a666a073254e126bb5b30aab10..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_eeprom.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * neOCampus operation - * - * EEPROM operations to store / retrieve keys - * - * Thiebolt F. July 17 - * - */ - - -#ifndef _NEOCAMPUS_EEPROM_H_ -#define _NEOCAMPUS_EEPROM_H_ - -/* - * Includes - */ - -#include <Arduino.h> - - -#include "neocampus.h" -#include "neocampus_debug.h" - - - -/* - * Definitions - */ -#define NEOCAMPUS_EEPROM_SIZE 256 - -#define EEPROM_ADDR_CHECK 0 // ought to contain value EEPROM_CHECK_VAL -#define EEPROM_ADDR_SIZE (EEPROM_ADDR_CHECK + 1) // ought to get equal to EEPROM_ADDR_LAST (in case EEPROM structure change, we reset everything) -#define EEPROM_ADDR_MQTT_LOGIN (EEPROM_ADDR_SIZE + 1) -#define EEPROM_ADDR_MQTT_PASSWD (EEPROM_ADDR_MQTT_LOGIN + SENSO_MQTT_LOGIN_LENGTH) -#define EEPROM_ADDR_LAST (EEPROM_ADDR_MQTT_PASSWD + SENSO_MQTT_PASSWD_LENGTH) - -#define EEPROM_VALIDITY_CHECK 42 - -/* - * Functions - */ -// initialize EEPROM -bool setupEEPROM( void ); - -// verify EEPROM content validity -inline bool checkEEPROMvalidity( void ); - -// clear EEPROM validity (invalidation) -void clearEEPROMvalidity( void ); - -// format EEPROM for neOCampus use -bool formatEEPROM( void ); - -// set EEPROM validity flag -inline void setEEPROMvalidity( void ); - -// store 'login' within EEPROM -void setEEPROMlogin( const char * ); - -// store 'passwd' within EEPROM -void setEEPROMpasswd( const char * ); - -// retrieve 'login' from EEPROM -bool getEEPROMlogin( char *, size_t ); - -// retrieve 'passwd' from EEPROM -bool getEEPROMpasswd( char *, size_t ); - -// HEX DUMP of EEPROM content -void hexdumpEEPROM( void ); - -#endif /* _NEOCAMPUS_EEPROM_H_ */ - diff --git a/work/neocampus_libs.orig/neocampus_i2c.cpp b/work/neocampus_libs.orig/neocampus_i2c.cpp deleted file mode 100644 index 7dc6bc30d74edc63bf4c495a2eb7201e6dbcd2cf..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_i2c.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/* - * neOCampus library - * - * - I2C synchronous functions read/write 8 and 16bits - */ - - -/* - * Includes - */ -#include <Wire.h> - -// neOCampus specific includes -#include "neocampus.h" -#include "neocampus_debug.h" - -#include "neocampus_i2c.h" - - - -/* I2C scanner: it starts to scan I2C bus according to specified start parameter - * Scan stops whenever a device respond and we send back it address. You can continue scanning - * giving previous answered addr+1 - */ -uint8_t i2c_scan(uint8_t start) { - - // check that i2c addr is within range ... - if( (start < I2C_ADDR_START) || (start > I2C_ADDR_STOP) ) { - log_debug("\n###ERROR I2C scan start addr is wrong!"); log_flush(); - return -1; - } - - // ... then let's start to scan i2c bus :) - int res; - for( uint8_t _addr=start; _addr <= I2C_ADDR_STOP; _addr++ ) { - - // i2c quick_write :) - res = i2c_quick_write( _addr ); - delay(20); // usefull ? - - if( res==0 ) return _addr; - else if( res==4 ) { - log_debug("\n###ERROR I2C scan err="); log_debug(DEC,res);log_flush(); - return -1; - } - } - - // nothing detected - return -1; -} - -/**************************************************************************/ -/*! - @brief Low level I2C read and write functions! -*/ -/**************************************************************************/ -int i2c_quick_write( uint8_t adr ) { - int res; - Wire.beginTransmission( adr ); - res = Wire.endTransmission(); - -#ifdef DEBUG_I2C - if( res==0 ) { - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-Qwrite] adr=0x%02x device detected ...", adr); - log_debug(_msg);log_flush(); - } -#endif - return res; -} - -void write8(uint8_t adr, uint8_t value) { -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-write8] adr=0x%02x (no reg) val=0x%02x", adr, value); - log_debug(_msg);log_flush(); -#endif - Wire.beginTransmission(adr); - Wire.write(value); - Wire.endTransmission(); -} - -void write8(uint8_t adr, uint8_t reg, uint8_t value) { -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-write8] adr=0x%02x reg=%d val=0x%02x", adr, reg, value); - log_debug(_msg);log_flush(); -#endif - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.write(value); - Wire.endTransmission(); -} - -uint8_t read8(uint8_t adr, uint8_t reg) { - uint8_t val; - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.endTransmission(); - - Wire.requestFrom(adr, (uint8_t)1); - val= Wire.read(); - -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-read8] adr=0x%02x reg=%d val=0x%02x", adr, reg, val); - log_debug(_msg);log_flush(); -#endif - - return val; -} - -void write16(uint8_t adr, uint8_t reg, uint16_t value) { -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-write16] adr=0x%02x reg=%d val=0x%04x", adr, reg, value); - log_debug(_msg);log_flush(); -#endif - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.write(value >> 8); - Wire.write(value & 0xFF); - Wire.endTransmission(); -} - -uint16_t read16(uint8_t adr, uint8_t reg) { - uint16_t val; - - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.endTransmission(); - - Wire.requestFrom(adr, (uint8_t)2); - val = Wire.read(); - val <<= 8; - val |= Wire.read(); - -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-read16] adr=0x%02x reg=%d val=0x%04x", adr, reg, val); - log_debug(_msg);log_flush(); -#endif - - return val; -} - - - -/* - * I2C write16 little-endian - */ -void write16le(uint8_t adr, uint8_t reg, uint16_t value) { -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-write16le] adr=0x%02x reg=%d val=0x%04x", adr, reg, value); - log_debug(_msg);log_flush(); -#endif - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.write(value & 0xFF); - Wire.write(value >> 8); - Wire.endTransmission(); -} - -/* - * I2C read16 little-endian - */ -uint16_t read16le(uint8_t adr, uint8_t reg) { - uint16_t val; - - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.endTransmission(); - - Wire.requestFrom(adr, (uint8_t)2); - uint8_t lsb = Wire.read(); - uint8_t msb = Wire.read(); - val = msb << 8; - val |= lsb; - -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-read16le] adr=0x%02x reg=%d val=0x%04x", adr, reg, val); - log_debug(_msg);log_flush(); -#endif - - return val; -} - - - -/* - * I2C bulk transfers - * involving the 'i2c repeated start bit' - * return number of bytes read - */ -uint8_t readList( uint8_t adr, uint8_t reg, uint8_t tab[], uint8_t tabsize ) { - - Wire.beginTransmission(adr); - Wire.write((uint8_t)reg); - Wire.endTransmission( false ); // enables the 'repeated start bit' - - Wire.requestFrom(adr, tabsize); - uint8_t i=0; - while( Wire.available() and ( i < tabsize) ) { - tab[i++] = Wire.read(); - } - Wire.endTransmission(); - -#ifdef DEBUG_I2C - char _msg[255]; - snprintf(_msg, sizeof(_msg), "\n[I2C-readList] adr=0x%02x reg=%d val=[0x%02x 0x%02x 0x%02x 0x%02x ... ]", adr, reg, tab[0], tab[1], tab[2], tab[3]); - log_debug(_msg);log_flush(); -#endif - - return i; -} - -uint8_t writeList( uint8_t adr, uint8_t reg, uint8_t *tab, uint8_t tabsize ){ - log_debug("\nNOT YET AVAILABLE :|"); - return 0; -} - - - diff --git a/work/neocampus_libs.orig/neocampus_i2c.h b/work/neocampus_libs.orig/neocampus_i2c.h deleted file mode 100644 index 3e3571c2f3c7a2b3006af5cc101c2cfeb404b13f..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_i2c.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * neOCampus operation - * - * I2C functions - * - * Thiebolt F. June 17 - * - */ - - -#ifndef _NEOCAMPUS_I2C_H_ -#define _NEOCAMPUS_I2C_H_ - -/* - * Includes - */ -#include <Arduino.h> - - - -/* - * Definitions - */ - -// i2c bus related definition -//#define DEBUG_I2C // low-level I2C debug messages (verbose option!!) -#define I2C_ADDR_START 0x01 -#define I2C_ADDR_STOP 0x7F - - - -/* - * Common functions - */ -// I2C bus scanner -uint8_t i2c_scan(uint8_t start); - -// I2C synchronous functions -int i2c_quick_write( uint8_t adr ); - -uint8_t read8(uint8_t adr, uint8_t reg); -void write8(uint8_t adr, uint8_t val); -void write8(uint8_t adr, uint8_t reg, uint8_t val); - -uint16_t read16(uint8_t adr, uint8_t reg); // big endian (default) -void write16(uint8_t adr, uint8_t reg, uint16_t val); // big endian (default) - -uint16_t read16le(uint8_t adr, uint8_t reg); // little-endian -void write16le(uint8_t adr, uint8_t reg, uint16_t val); // little-endian - -uint8_t readList( uint8_t adr, uint8_t reg, uint8_t *tab, uint8_t tabsize ); -uint8_t writeList( uint8_t adr, uint8_t reg, uint8_t *tab, uint8_t tabsize ); - - -#endif /* _NEOCAMPUS_I2C_H */ - - diff --git a/work/neocampus_libs.orig/neocampus_utils.cpp b/work/neocampus_libs.orig/neocampus_utils.cpp deleted file mode 100644 index a0247996c40e5f9ba12fbb61c4a049160204e5b9..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_utils.cpp +++ /dev/null @@ -1,572 +0,0 @@ -/* - * neOCampus operation - * - * Utilities functions like - * - WiFi setup - * - OTA updates - * - SPIFFS related - * - JSON encoding / decoding functions - * - ... - * - * F.Thiebolt Nov.19 set 30s WiFi connexion timeout with previous credentials - * Thiebolt F. July 17 - * - */ - - -/* ---------------------------------------------------------------------------- - * --- Includes --------------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -#include <FS.h> //this needs to be first, or it all crashes and burns ... still nowdays ?? - -#include <Arduino.h> -#include <EEPROM.h> -#include <ESP8266WiFi.h> -#include <ESP8266HTTPClient.h> // HTTP GET -#include <Esp.h> // ESP specific API for watchdog and others functionnalities - -//needed for WiFiManager library -#include <DNSServer.h> // for captive portal -#include <ESP8266WebServer.h> -#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager -#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson - -#include <Dns.h> // getHostByName -#include <time.h> // time() ctime() - -#include "neocampus.h" - -#include "neocampus_debug.h" -#include "neocampus_utils.h" - - - -/* ---------------------------------------------------------------------------- - * --- Global variables ------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -bool _WMsaveAddonConfigFlag = false; - - - -/* ---------------------------------------------------------------------------- - * --- Functions -------------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ - -// --- CLEAR switch management ------------------------------------------------ - -/* check clear switch for CLEAR procedure - * if pin == -1 --> check disabled - */ -bool checkCLEARswitch( uint8_t sw_pin ) { - if (sw_pin == INVALID_GPIO) return false; - - // set pin as input - pinMode( sw_pin, INPUT ); - - log_debug(F("\n[CLEAR] check for clear_switch activation ...")); log_flush(); - - bool _res = true; - // ... then read input for a specific time - for( uint8_t cpt=10; cpt > 0; cpt-- ) { - if ( digitalRead( sw_pin ) != HIGH ) { - // at least read as LOW one time --> cancel clear operation - _res = false; - break; - } - delay(50); // sleep for 50ms (allowing ESP to manage internals) - } - - /* okay, delay for clear switch acquisition is now over. - * If we need to clear things, we want to wait for sw_pin - * LOW (i.e user stopped to press switch) - */ - if( _res==true ) { - log_info(F("\n[CLEAR] activate CLEAR procedure ...")); - log_debug(F("\n[CLEAR] release SWITCH for clear to start ...")); - log_flush(); - } - while( digitalRead( sw_pin )==HIGH ) { - delay(250); - } - - return _res; -} - - - -// ---------------------------------------------------------------------------- -// --- WiFi setup ------------------------------------------------------------- - -/* - * compute WiFi Access Point Name - */ -const char *getAPname( void ) { - static char _apName[16] = ""; - - if( !strlen(_apName) ) { - const char *mac=getMacAddress(); - uint8_t mac_len=strlen(mac); -// snprintf(_apName,sizeof(_apName),"neOSensor_%c%c%c%c",mac[mac_len-5],mac[mac_len-4],mac[mac_len-2],mac[mac_len-1]); - snprintf(_apName,sizeof(_apName),"%s_%c%c%c%c",BOARD_NAME,mac[mac_len-5],mac[mac_len-4],mac[mac_len-2],mac[mac_len-1]); - } - - return (const char*)_apName; -} - -/* - * WiFiManager : callback upon exit of AP mode (i.e success) - * - callback notifying us of the need to save additional parameters - */ -void cb_exitConfigMode( void ) { - log_debug(F("\n[WiFiManager] exit config mode --> save addon parameters flag is set ...")); - _WMsaveAddonConfigFlag = true; -} - -/* - * WiFiManager : callback upon entering AP mode (will start to configure network) - */ -void cb_enterConfigMode( WiFiManager *myWiFiManager ) { - log_debug(F("\n[WiFiManager] entering WiFi AP config mode")); - log_debug(F("\n\tIP ")); log_debug(WiFi.softAPIP()); - log_debug(F("\n\tSSID ")); log_debug(myWiFiManager->getConfigPortalSSID()); - log_flush(); -} - -/* - * WiFi setup - */ -bool setupWiFi( wifiParametersMgt *wp ) { - - if( _need2reboot ) return false; - - log_info(F("\n[WiFi] start WiFiManager ...")); - - // reload config file - if( wp ) { - // load WiFi parameters and options - wp->loadConfigFile(); - } - - // Disable WiFi sleep mode ... - log_debug("\n[WiFi] disable WiFi sleep mode ..."); - WiFi.setSleepMode( WIFI_NONE_SLEEP ); - - // WiFi parameters availables ? - if( strlen(wp->getWIFIssid()) ) { - - log_debug(F("\n[WiFi] found ssid = ")); log_debug(wp->getWIFIssid()); - log_debug(F("\n[WiFi] found pass = ")); log_debug(wp->getWIFIpass()); - - // destroy saved parameters - WiFi.mode(WIFI_STA); - WiFi.disconnect(true); // or WiFiManager.resetSettings(); - delay(1000); - log_debug(F("\n[WiFi] start to reconnect using those credentials ..."));log_flush(); - WiFi.begin( wp->getWIFIssid(), wp->getWIFIpass() ); - - // retry for xx seconds using previously retrieved credentials - uint8_t _retry=WM_CONNECTION_ATTEMPT_TIMEOUT; - while( WiFi.status() != WL_CONNECTED and _retry-- ) { - delay(1000); - log_debug(F("+"));log_flush(); - } - } - - // WiFiManager local instance ... no need to keep once business is done - WiFiManager wifiManager; - - // debug messages - wifiManager.setDebugOutput( true ); - - // set enter config mode callback - wifiManager.setAPCallback( cb_enterConfigMode ); - - // set config save notify callback: only usefull for additional parameters - wifiManager.setSaveConfigCallback( cb_exitConfigMode ); - - // set minimum signal level - wifiManager.setMinimumSignalQuality(); // min. default is 8% - - // set custom ip for AP portal - wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - // set to exit portal after config - wifiManager.setBreakAfterConfig( true ); - - - - /* - * Declare WiFiManager additional parameters - * - * [Jun.18] WARNING --> use Ken Taylor WiFiManager verion: - * https://github.com/kentaylor/WiFiManager - * - * - hint reminder - * - TM1637 7 segment display with optional pins - * - * Note: HACK related below is because i don't want to allocate memory on the heap - * ... because you ought to free it at the end and it is much more secure to allocate - * on the stack ;) - */ - // Just a quick hint - WiFiManagerParameter p_hint("<small>*Hint: if you want to reuse the currently active WiFi credentials, leave SSID and Password fields empty</small>"); - - // kinds of custom HTML - const char _customHtml_checkbox[] = "type=\"checkbox\""; - const char _customHtml_checkbox_checked[] = "type=\"checkbox\" checked"; - - // enable / disable sensOCampus sandbox - WiFiManagerParameter p_sandbox("sandbox", "neOCampus sandbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); - if( wp->isEnabledSandbox() ) { - // [Jun.18] HACK that requires modification in WiFiManager - p_sandbox._customHTML = _customHtml_checkbox_checked; - } - - // TM1637 7 segment display parameters - WiFiManagerParameter p_sevenSegTM1637("sevenSegTM1637", "TM1637 7-seg (DIO=2,CLK=SCL)", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); - if( wp->isEnabled7segTM1637() ) { - // [Jun.18] HACK that requires modification in WiFiManager - p_sevenSegTM1637._customHTML = _customHtml_checkbox_checked; - } - -/* - // I2C SCL and SDA parameters are integers so we need to convert them to char array but - // no other special considerations - char convertedValue[3]; - sprintf(convertedValue, "%d", NEOCLOCK_TM1637_DIO); - WiFiManagerParameter p_pinTM1637dio("pinTM1637dio", "TM1637 DIO pin", convertedValue, 3); - sprintf(convertedValue, "%d", NEOCLOCK_TM1637_CLK); - WiFiManagerParameter p_pinTM1637clk("pinTM1637clk", "TM1637 CLK pin", convertedValue, 3); -*/ - - // PIR sensor - WiFiManagerParameter p_PIRsensor("PIRsensor", "PIR sensor (pin=5)", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); - if( wp->isEnabledPIR() ) { - // [Jun.18] HACK that requires modification in WiFiManager - p_PIRsensor._customHTML = _customHtml_checkbox_checked; - } - - - /* - *WARNING: Clear sensor ALL CONFIG (wifi, eeprom, spiffs) option - */ - WiFiManagerParameter p_eraseALL("eraseALL", "ERASE ALL", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); - - - /* - * add all parameters to wifiManager - */ - wifiManager.addParameter(&p_hint); - wifiManager.addParameter(&p_sandbox); - wifiManager.addParameter(&p_sevenSegTM1637); -/* - wifiManager.addParameter(&p_pinTM1637dio); - wifiManager.addParameter(&p_pinTM1637clk); -*/ - wifiManager.addParameter(&p_PIRsensor); - wifiManager.addParameter(&p_eraseALL); - - - // - // set timeouts - if( WiFi.status() != WL_CONNECTED ) { - log_debug(F("\n[WiFi] AP will get open for "));log_debug(WM_CONFIG_PORTAL_TIMEOUT,DEC);log_debug(F(" seconds")); - wifiManager.setConfigPortalTimeout(WM_CONFIG_PORTAL_TIMEOUT); - } - else { - log_debug(F("\n[WiFi] AP opened in CONFIG MODE for ")); log_debug(WM_CONFIG_PORTAL_TIMEOUT/6,DEC);log_debug(F(" seconds")); - wifiManager.setConfigPortalTimeout(WM_CONFIG_PORTAL_TIMEOUT/6); - } - // set a timeout trying to connect to a specified AP - log_debug(F("\n[WiFi] will try a connexion for maximum "));log_debug(WM_CONNECTION_ATTEMPT_TIMEOUT,DEC);log_debug(F(" seconds")); - wifiManager.setConnectTimeout(WM_CONNECTION_ATTEMPT_TIMEOUT); - - - /* - * if it does not connect it starts an access point with the specified name - * and goes into a blocking loop awaiting configuration - */ - log_debug(F("\n")); - wifiManager.startConfigPortal( getAPname(), WIFI_AP_CREDENTIALS ); // blocking call - delay(500); - - // whatever the result of the connection ... we save all parameters :) - // Getting posted form values and overriding local variables parameters - // Config file is written regardless the connection state - // TODO: find a way to parse ALL parameters added in wifi manager - if( _WMsaveAddonConfigFlag ) { - - // save wifi settings to wifi parameters object - wp->_getWIFIsettings(); - - // save OPTIONS to parameters object - wp->_setopt_sandboxMode( strncmp(p_sandbox.getValue(),"T",1)==0 ? true : false ); - wp->_setopt_7segTM1637( strncmp(p_sevenSegTM1637.getValue(),"T",1)==0 ? true : false ); - wp->_setopt_PIRsensor( strncmp(p_PIRsensor.getValue(),"T",1)==0 ? true : false ); - - /* - strcpy(thingspeakApiKey, p_thingspeakApiKey.getValue()); - sensorDht22 = (strncmp(p_sensorDht22.getValue(), "T", 1) == 0); - pinSda = atoi(p_pinSda.getValue()); - pinScl = atoi(p_pinScl.getValue()); - */ - - // Dangerous option !! - wp->_setopt_eraseALL( strncmp(p_eraseALL.getValue(),"T",1)==0 ? true : false ); - - // Writing JSON config file to flash for next boot - wp->saveConfigFile(); - } - - if( WiFi.status() != WL_CONNECTED ) { - log_error(F("\n[WiFi] failed to connect and hit timeout ... restart")); - // reboot our sensor - _need2reboot=true; - delay(1000); - return false; - } - - //if you get here you have connected to the WiFi - log_info(F("\n[WiFi] connected :)")); - log_debug(F("\n\tSSID ")); log_debug(WiFi.SSID()); - log_debug(F("\n\tIP ")); log_debug(WiFi.localIP()); - log_debug(F("\n\tRSSI ")); log_debug(WiFi.RSSI()); - - // Disable WiFi sleep mode ... - log_debug("\n[WiFi] disable WiFi sleep mode ..."); - WiFi.setSleepMode(WIFI_NONE_SLEEP); - - // well done :) - return true; -} - - -/* - * setup SPIFFS - */ -bool setupSPIFFS( void ) { - log_info(F("\n[SPIFFS] start ... ")); - if( !SPIFFS.begin() ) { - log_info(F("\n[SPIFFS] uninitialized file system ... format :|")); - delay(1000); - return formatSPIFFS(); - } - else { - log_info(F("\n[SPIFFS] mounted file system :)")); - } - return true; -} - - - -// --- utilities functions ---------------------------------------------------- -// hex dump of a buffer -void hex_dump( const char *buf, size_t bufsize ) { - log_debug(F("\n### HEX DUMP "));log_debug(bufsize,DEC);log_debug(F(" bytes ###")); log_flush(); - for(uint8_t i=0; i < (uint8_t)bufsize; i++ ){ - char _line[30]; - snprintf(_line,sizeof(_line),"\nbuf[%u] = 0x%02x '%c'", i, buf[i], buf[i]); - log_debug(_line); delay(20); log_flush(); - } -} - - -/* --- - * --- Format SPIFFS filesystem - */ -bool formatSPIFFS( void ) { - log_info(F("\n[SPIFFS] start formatting ... ")); - bool _res = SPIFFS.format(); - if( _res==true ) { - log_debug(F("success :)")); - } else log_error(F("[FAILURE] !!")); - log_flush(); - return _res; -} - - -// retrieve mac address -const char *getMacAddress( void ) { - static bool _initialized = false; - // mac address array format - static mac_addr_t _mac; - // mac address string format - static mac_str_t _mac_sta; - - if( _initialized == false ) { - //WiFi.softAPmacAddress( _mac ); // beware that AP mac addr is different from STA mac addr! - WiFi.macAddress( _mac ); - snprintf(_mac_sta, sizeof(_mac_sta), "%02x:%02x:%02x:%02x:%02x:%02x", _mac[0], _mac[1], _mac[2], _mac[3], _mac[4], _mac[5]); - _initialized = true; - } - return (const char *)_mac_sta; -} - - - -// retrieve current domain name -const char *getDomainName( void ) { - //static char _domainName[32] = ""; - - if( ! WiFi.isConnected() ) return NULL; - - // esp8266 affects a default hostname if not set by DHCP server - const char *_esp_defl_hostname = PSTR("ESP_"); - - /* is hostname one of the defaults esp8266 hostname ? - * i.e it starts with ESP_XXXXXX */ - if( not strncmp_P( WiFi.hostname().c_str(), _esp_defl_hostname, strlen_P(_esp_defl_hostname) ) ) { - log_debug(F("\n[getDomainName] hostname is a default one: ")); log_debug( WiFi.hostname().c_str() ); log_flush(); - - /* - * [Jun.18] DHCP_OPTION_HOSTNAME does not exist in dhcp.c (client) - * neither DHCP_OPTION_IDX_HOSTNAME - * TODO!! - */ - - return nullptr; - } - - /* Does hostname contains domain name too ? - * e.g esp8266-bu-hall.neocampus.univ-tlse3.fr */ - // lets find first dot - const char *cur_domain = strchr( WiFi.hostname().c_str(), '.' ); - if( cur_domain == NULL ) return nullptr; - // ... and at least a second dot ? - if( strchr( cur_domain+1, '.' ) == NULL ) return nullptr; - - // ok we finally found a hostname with AT LEAST 2 dots ==> FQDN - return cur_domain+1; -} - - -/* - * Get current time - * WARNING: static variable inside (i.e single thread) - */ -const char *getCurTime( const char *fmt ) { - - // STATIC variable ! - static char _tmpbuf[64]; - - // default format - const char defl_fmt[] = "%Y-%m-%d %H:%M:%S %z"; - - if( !fmt ) fmt=defl_fmt; - - struct tm *_tm; - time_t _curTime; - - time( &_curTime ); - _tm = localtime( &_curTime ); // Weird part ... localtime function *corrects* time to match timezone ... :s - strftime( _tmpbuf, sizeof(_tmpbuf), fmt, _tm); - - return (const char *)_tmpbuf; -} - - -/* - * low-level HTTP GET - */ -bool _http_get( const char *url, char *buf, size_t bufsize, const char *login, const char *passwd ) { - - HTTPClient http; - - http.begin(url); - log_debug(F("\n[HTTP] GET url : ")); log_debug(url); log_flush(); - - // authentication ? - if( login!=NULL and passwd!=NULL ) { - http.setAuthorization( login, passwd); - } - - // perform GET - int httpCode = http.GET(); - - // connexion failed to server ? - if( httpCode < 0 ) { - log_error(F("\n[HTTP] connexion error code : ")); log_debug(httpCode,DEC); log_flush(); - _need2reboot = true; - return false; - } - - // check for code 200 - if( httpCode == HTTP_CODE_OK ) { - String payload = http.getString(); - snprintf( buf, bufsize, "%s", payload.c_str() ); - } - else { - log_error(F("\n[HTTP] GET retcode : ")); log_debug(httpCode,DEC); log_flush(); - } - - // close connexion established with server - http.end(); - - yield(); - - return ( httpCode == HTTP_CODE_OK ); -} - -// --- -// HTTP get -bool http_get( const char *url, char buf[], size_t bufsize ) { - return _http_get( url, buf, bufsize, NULL, NULL ); -} - -// --- -// HTTP get with credentials -bool http_get( const char *url, char *buf, size_t bufsize, const char *login, const char *passwd ) { - return _http_get( url, buf, bufsize, login, passwd ); -} - -// --- -// Reset configuration and restart (delete module's config files and reboot) -bool neOSensor_reset( void ) { - - log_info(F("\n[reboot] neOSensor is about to reboot in a few seconds ...")); - - /* - * Delete ALL modules JSON config files - * - * Note: it works because modules' config files are ONLY WRITTEN - * upon config change ... not at the end of the module's life ;) - */ - const char *_prefix = PSTR(MCFG_FILE_PREFIX); // TBC: useful ? - const char *_suffix = PSTR(MCFG_FILE_SUFFIX); // TBC: useful ? - Dir dir = SPIFFS.openDir("/"); - while( dir.next() ) { - if( strncmp_P( dir.fileName().c_str(), _prefix, strlen_P(_prefix))!=0 ) continue; - if( strncmp_P( dir.fileName().c_str(), _suffix, strlen_P(_suffix))!=0 ) continue; - // delete matching file - log_debug(F("\n[reboot] deleting file : "));log_debug(dir.fileName());log_flush(); - } - - // reboot - neOSensor_reboot(); - - // unreachable zone - return true; -} - -// --- -// proper restart -void neOSensor_reboot( void ) { - - log_info(F("\n[reboot] neOSensor is about to reboot in a few seconds ...")); - - // properly close stuffs - EEPROM.commit(); - EEPROM.end(); - - // SPIFFS close - SPIFFS.end(); - - // call to restart - delay( 2000 + int(random(10000)) ); // random reboot delay - ESP.restart(); - delay(5000); -} - diff --git a/work/neocampus_libs.orig/neocampus_utils.h b/work/neocampus_libs.orig/neocampus_utils.h deleted file mode 100644 index 9c436df64a783c149e552d208ce86a5ede2c643e..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/neocampus_utils.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * neOCampus operation - * - * Utilities functions like - * - WiFi setup - * - OTA updates - * - SPIFFS related - * - JSON encoding / decoding functions - * - ... - * - * Thiebolt F. July 17 - * - */ - - - -#ifndef _NEOCAMPUS_UTILS_H_ -#define _NEOCAMPUS_UTILS_H_ - - - -/* ---------------------------------------------------------------------------- - * --- Includes --------------------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -#include <Arduino.h> - -#include "wifiParametersMgt.h" - - - -/* - * Global shared variables/functions - */ -// reboot flag -extern bool _need2reboot; - - - -/* ---------------------------------------------------------------------------- - * --- Definitions ------------------------------------------------------------ - * ---------------------------------------------------------------------------- - */ -// --- WiFi definitions ------------------------------------------------------- -#define WM_CONFIG_PORTAL_TIMEOUT 300 // seconds config portail will stay active -#define WM_CONNECTION_ATTEMPT_TIMEOUT 90 // will wait up to xxs for connecting to the specified SSID - - - -/* ---------------------------------------------------------------------------- - * --- Functions prototypes --------------------------------------------------- - * ---------------------------------------------------------------------------- - */ -// check clear switch for CLEAR procedure -bool checkCLEARswitch( uint8_t ); - -// whole neocampus WiFi connexion setup -bool setupWiFi( wifiParametersMgt *wp=nullptr ); - -// compute WiFi Access Point Name -const char *getAPname( void ); - -// obtain MAC address (e.g "18:fc:b3:de:c6:02") -const char *getMacAddress( void ); - -// retrieve current domain name -const char *getDomainName( void ); - -// retrieve current time -const char *getCurTime( const char *fmt=nullptr ); - -// HTTP get & get with credentials -bool http_get( const char *url, char *buf, size_t bufsize ); -bool http_get( const char *url, char *buf, size_t bufsize, const char *login, const char *passwd ); - -// setup SPIFFS -bool setupSPIFFS( void ); - -// Format SPI FileSystem -bool formatSPIFFS( void ); - -// Reset configuration and restart (delete module's config files and reboot) -bool neOSensor_reset( void ); - -// proper restart -void neOSensor_reboot( void ); - -// --- utilities functions ---------------------------------------------------- - -// hex dump of a buffer -void hex_dump( const char *, size_t ); - -#endif /* _NEOCAMPUS_UTILS_H */ diff --git a/work/neocampus_libs.orig/sensocampus.cpp b/work/neocampus_libs.orig/sensocampus.cpp deleted file mode 100644 index d13bdc349623e9b7d11ab45f7677a974527626c4..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/sensocampus.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/* - * neOCampus operation - * - * sensOCampus client class for interactions with sensOCampus server - * - * Thiebolt F. Nov.19 migrate to Arduino Json 6 - * Thiebolt F. July 17 - * - */ - - - -/* - * Includes - */ -#include <Arduino.h> -#include <ArduinoJson.h> - -#include "sensocampus.h" - -#include "neocampus_eeprom.h" -#include "neocampus_utils.h" - - - -/* - * Class constructor - */ -senso::senso( void ) { - _initialized = false; - // set default values - _applyDefaults(); -} - -senso::senso( wifiParametersMgt *p ) { - _initialized = false; - // set default values - _applyDefaults(); - // register link to global wifi parameters & options - _wifiParams = p; -} - - -/* - * Begin ... means populate everything from HTTP server sensocampus - * till the EEPROM - */ -boolean senso::begin( const char *mac ) { - log_info(F("\n[sensOCampus] start with provided mac addr ")); log_info( mac); log_flush(); - - // check global parameters - if( _wifiParams and _wifiParams->isValid() and _wifiParams->isEnabledSandbox()== true ) { - /* - * sensOCampus is NOT enabled - * ==> using SANDBOX mode - */ - log_debug(F("\n[senso] >>> DISABLED: using sensOCampus SANDBOX mode <<<")); log_flush(); - _mqtt_port = DEFL_MQTT_ABROAD_PORT; // probably because disabled mode means abroad ;) - delay(1000); - } - else { - /* - * sensOCampus normal operation - */ - // get device CREDENTIALS - if( http_getCredentials( mac ) != true ) { - log_error(F("\n[senso] error getting CREDENTIALS from sensOCampus server ?!")); log_flush(); - _applyDefaults(); - return false; - } - - // get device CONFIG - if( http_getConfig( ) != true ) { - log_error(F("\n[senso] error getting CONFIG from sensOCampus server ?!")); log_flush(); - _applyDefaults(); - return false; - } - } - - // both CREDENTIALS & CONFIG done :) - _initialized = true; - - return true; -} - - - -// obtain CREDENTIALS from sensOCampus server -bool senso::http_getCredentials( const char *mac ) { - log_debug(F("\n[sensOCampus] start http getCredentials ... ")); log_flush(); - - // get JSON response to url credentials http get - char url[SENSO_HTTP_URL_MAXSIZE]; - char buf[SENSO_HTTP_MAX_RESPONSE_SIZE]; - snprintf(url, sizeof(url),"%s%s", SENSO_GET_CREDENTIALS_URL, mac ); - if( !http_get( url, buf, sizeof(buf) ) ) { - return false; - } - log_debug(F("\n[senso] GET response <"));log_debug(buf);log_debug(F(">"));log_flush(); - - // [JSON] deserialize credentials - if( !_parseCredentials(buf) ) - return false; - - return true; -} - - -// obtain CONFIG from sensOCampus server -bool senso::http_getConfig( void ) { - log_debug(F("\n[sensOCampus] start http getConfig ... ")); log_flush(); - - // get JSON response to url config http get - char url[SENSO_HTTP_URL_MAXSIZE]; - char buf[SENSO_HTTP_MAX_RESPONSE_SIZE]; - snprintf(url, sizeof(url),"%s", SENSO_GET_CONFIG_URL ); - if( !http_get( url, buf, sizeof(buf), _mqtt_login, _mqtt_passwd ) ) { - return false; - } - log_debug(F("\n[senso] GET response <"));log_debug(buf);log_debug(F(">"));log_flush(); - - // [JSON] deserialize config - if( !_parseConfig(buf) ) - return false; - - return true; -} - - - -/* - * --- Private methods ----------------------------------------------------------------------- - */ - -// apply defaults to sensOCampus parameters -void senso::_applyDefaults( void ) { - _wifiParams = nullptr; - - // Note: snprintf automatically add NULL terminaison - snprintf(_mqtt_server, sizeof(_mqtt_server), DEFL_MQTT_SERVER); - _mqtt_port = DEFL_MQTT_STD_PORT; - snprintf(_mqtt_login, sizeof(_mqtt_login), DEFL_MQTT_LOGIN); - snprintf(_mqtt_passwd, sizeof(_mqtt_passwd), DEFL_MQTT_PASSWD); - snprintf(_mqtt_base_topic, sizeof(_mqtt_base_topic), "%s/%s", DEFL_MQTT_TOPIC, getAPname()); -} - -// parse JSON buffer that contains credentials -bool senso::_parseCredentials( char *json ) { - log_debug(F("\n[senso] start parsing JSON credentials ...")); - - StaticJsonDocument<SENSO_JSON_SIZE> root; - - auto err = deserializeJson( root, json ); - if( err ) { - log_error(F("\n[senso] ERROR parsing JSON credentials :"));log_error(err.c_str()); log_flush(); - return false; - } - - // check for "server" (i.e MQTT broker) in JSON buffer - if( (root.containsKey(F("server"))==true) ) { - snprintf(_mqtt_server, sizeof(_mqtt_server),"%s", (const char *)(root[F("server")]) ); - log_info(F("\n[senso] found 'server' = "));log_info(_mqtt_server); log_flush(); - } - - // check for "port" (i.e MQTT broker port) in JSON buffer - if( (root.containsKey(F("port"))==true) ) { - _mqtt_port = (uint16_t)root[F("port")]; - log_info(F("\n[senso] found 'port' = "));log_info(_mqtt_port,DEC); log_flush(); - } - - // check for "login" in JSON buffer - if( (root.containsKey(F("login"))==false) ) { - log_error(F("\n[senso] JSON credentials without 'login' ?!?!")); - return false; - } - /* ok, we have a 'login' field ... - * ... if we have a password field we apply both to senso & EEPROM - */ - // check for password in JSON - if( (root.containsKey(F("password"))==true) ) { - snprintf(_mqtt_login,sizeof(_mqtt_login),"%s", (const char *)(root[F("login")]) ); - setEEPROMlogin( _mqtt_login ); - snprintf(_mqtt_passwd,sizeof(_mqtt_passwd),"%s", (const char *)(root[F("password")]) ); - setEEPROMpasswd( _mqtt_passwd ); - log_info(F("\n[senso] eeprom stored login & password :)")); - return true; - } - - /* - * So far, we have a login field but without a password field ... - * ... thus it means that this later ought to get stored within - * EEPROM along with corresponding login in EEPROM too - */ - // retrieve login from EEPROM - if( !getEEPROMlogin( _mqtt_login, sizeof(_mqtt_login) ) ) { - log_error(F("\n[senso] login not found in EEPROM ?!?!")); log_flush(); - return false; - } - size_t len1=strlen(_mqtt_login); - size_t len2=strlen(root[F("login")]); - if( (len1!=len2) or strncmp(_mqtt_login, root[F("login")], max(len1,len2)) ) { - log_error(F("\n[senso] error login does not match the one stored in EEPROM ?!")); log_flush(); - return false; - } - - /* - * ok, JSON credentials provided login is the same as the one within EEPROM ... - * ... now retrieve saved password from EEPROM - */ - if( !getEEPROMpasswd( _mqtt_passwd, sizeof(_mqtt_passwd) ) ) { - log_error(F("\n[senso] error passwd not found in EEPROM !!")); log_flush(); - return false; - } - - // success :) - return true; -} - - -// parse JSON buffer that contains config -bool senso::_parseConfig( char *json ) { - log_debug(F("\n[senso] start parsing JSON config ...")); - - StaticJsonDocument<SENSO_JSON_SIZE> root; - - auto err = deserializeJson( root, json ); - if( err ) { - log_error(F("\n[senso] ERROR parsing JSON config: "));log_error(err.c_str()); log_flush(); - return false; - } - - // check for "topic" in JSON buffer - if( (root.containsKey(F("topics"))==false) ) { - log_error(F("\n[senso] JSON config without base 'topic' ?!?!")); - return false; - } - log_info(F("\n[senso] WARNING: only 1st topic taken into account!")); - //strcpy(_mqtt_base_topic,root[F("topics")][0]); - snprintf( _mqtt_base_topic, sizeof(_mqtt_base_topic), "%s", (const char *)(root[F("topics")][0]) ); - log_info(F("\n[senso] base TOPIC = ")); log_debug(_mqtt_base_topic); log_flush(); - - // check for server (MQTT) - if( (root.containsKey(F("server"))==true) ) { - snprintf( _mqtt_server, sizeof(_mqtt_server), "%s", (const char *)root[F("server")] ); - log_info(F("\n[senso] set MQTT server to ")); log_debug(_mqtt_server); log_flush(); - } - - // check for server (MQTT) - if( (root.containsKey(F("server"))==true) ) { - snprintf( _mqtt_server, sizeof(_mqtt_server), "%s", (const char *)root[F("server")] ); - log_info(F("\n[senso] set MQTT server to ")); log_debug(_mqtt_server); log_flush(); - } - - // check for server port (MQTT) - if( (root.containsKey(F("port"))==true) ) { - _mqtt_port = (uint16_t)root[F("port")]; - log_info(F("\n[senso] set MQTT port to ")); log_debug(_mqtt_port,DEC); log_flush(); - } - - // parse additional parameters here :) - - return true; -} - - -// Send back server name -const char * senso::getServer( void ) const { - return _mqtt_server; -} - -// Send back port number -uint16_t senso::getServerPort( void ) const { - return _mqtt_port; -} - -// Send back BaseTopic -const char *senso::getBaseTopic( void ) const { - return _mqtt_base_topic; -} - -// Send back MQTT username -const char *senso::getUser( void ) const { - return _mqtt_login; -} - -// Send back MQTT password -const char *senso::getPassword( void ) const { - return _mqtt_passwd; -} - diff --git a/work/neocampus_libs.orig/sensocampus.h b/work/neocampus_libs.orig/sensocampus.h deleted file mode 100644 index 10fe9102c0bd4cf977dcdf7e1fe5d80a1c96b42d..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/sensocampus.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * neOCampus operation - * - * sensOCampus client class for interactions with sensOCampus server - * - * Thiebolt F. July 17 - * - */ - - -#ifndef _SENSOCAMPUS_H_ -#define _SENSOCAMPUS_H_ - -/* - * Includes - */ - -#include <Arduino.h> -//#include <ArduinoJson.h> - -#include "neocampus.h" -#include "neocampus_debug.h" - -#include "wifiParametersMgt.h" - - - -/* - * Definitions - */ -#define SENSO_GET_CREDENTIALS_URL "http://sensocampus.univ-tlse3.fr/device/credentials?mac=" -#define SENSO_GET_CONFIG_URL "http://sensocampus.univ-tlse3.fr/device/config" -#define SENSO_HTTP_URL_MAXSIZE 128 // maximum size of a URL sent to sensOCampus -#define SENSO_HTTP_MAX_RESPONSE_SIZE 1024 // maximum size of a response from from an url sent to sensOCampus -#define SENSO_JSON_SIZE (JSON_OBJECT_SIZE(128)) // no more than 128 objects in any sensOCampus JSON response -#define SENSO_UNITID_SIZE 18 // unitID field maxsize (mac addr is 17 bytes) - - -/* - * Class - */ -class senso { - public: - senso( void ); - senso( wifiParametersMgt * ); - - boolean begin( const char * ); - bool http_getCredentials( const char * ); - bool http_getConfig( void ); - - const char *getServer( void ) const; - uint16_t getServerPort( void ) const; - const char *getBaseTopic( void ) const; - const char *getUser( void ) const; - const char *getPassword( void ) const; - -private: - /* - * private methods - */ - void _applyDefaults( void ); - bool _parseCredentials( char * ); - bool _parseConfig( char * ); - - /* - * private attributes - */ - // check if structure is valid - bool _initialized; - - // global wifiParametersMgt - wifiParametersMgt *_wifiParams; - - // grabbed from sensocampus sever - char _mqtt_server[MQTT_SERVER_NAME_LENGTH]; - uint16_t _mqtt_port; - char _mqtt_login[SENSO_MQTT_LOGIN_LENGTH]; - char _mqtt_passwd[SENSO_MQTT_PASSWD_LENGTH]; - char _mqtt_base_topic[MQTT_BASE_TOPIC_LENGTH]; -}; - -#endif /* _SENSOCAMPUS_H */ diff --git a/work/neocampus_libs.orig/wifiParametersMgt.cpp b/work/neocampus_libs.orig/wifiParametersMgt.cpp deleted file mode 100644 index 56a7ef0125a170ebe919981a1823781c53a5e4d8..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/wifiParametersMgt.cpp +++ /dev/null @@ -1,478 +0,0 @@ -/* - * neOCampus operation - * - * User's high-level parameters management class. - * Most of those parameters come from WiFiManager parameters - * - * Thiebolt F. Jun.18 initial release - * - */ - - -/* - * Includes - */ -#include <FS.h> - -/* - * ESP8266 advanced ops - */ -extern "C" { - #include "user_interface.h" // wifi_station_dhcpc_start, ... -} - -#include "neocampus.h" - -#include "neocampus_debug.h" -#include "neocampus_utils.h" - -#include "wifiParametersMgt.h" - - -/* - * Global shared variables/functions - */ -extern bool _need2reboot; - - -/* - * Definitions - */ -#define CONFIG_JSON_SIZE (JSON_OBJECT_SIZE(20)) // config file contains: frequency - - -// constructor -wifiParametersMgt::wifiParametersMgt( void ) { - _initialized = false; - - // apply default values - _applyDefaults(); -} - -// destructor -wifiParametersMgt::~wifiParametersMgt( void ) { - // free dynamically allocated memory -} - - - -/* - * check parameters validity - * i.e they have been initialized at least once - */ -bool wifiParametersMgt::isValid( void ) { - if( ! _initialized ) { - log_debug(F("\n[wifiParams] someone queried the parameters status that is NOT yet initialized ..."));log_flush(); - } - - return _initialized; -} - - - -/* - * load parameters file - */ -bool wifiParametersMgt::loadConfigFile( void ) { - - if( ! SPIFFS.exists(WIFI_CONFIG_FILE) ) { - log_info(F("\n[wifiParams] WiFi config file ")); log_info(WIFI_CONFIG_FILE); log_info(F(" does not exists")); - log_info(F("\n[wifiParams] applying DEFAULTS ...")); - log_flush(); - _applyDefaults(); - return false; - } - - // open wifi config file - File configFile = SPIFFS.open(WIFI_CONFIG_FILE, "r"); - if( ! configFile ) { - log_error(F("\n[wifiParams] error opening WiFi config file ")); log_error(WIFI_CONFIG_FILE); - log_error(F("\n[wifiParams] removing file and applying DEFAULTS ...")); - log_flush(); - SPIFFS.remove(WIFI_CONFIG_FILE); - _applyDefaults(); - return false; - } - - // grab file content in JSON buffer - log_debug(F("\n[wifiParams] start reading WiFi config file ...")); log_debug(WIFI_CONFIG_FILE); log_flush(); - size_t size = configFile.size(); - // Allocate a buffer to store contents of the file. - std::unique_ptr<char[]> buf(new char[size]); - log_debug(F("\n\treading ")); log_debug(size,DEC); log_debug(F(" bytes from config file ")); log_flush(); - configFile.readBytes(buf.get(), size); - - // JSON buffer allocation - if( size > (CONFIG_JSON_SIZE) ) { - log_error(F("\n[wifiParams] config file to read is too large for JsonBuffer to handle: ")); log_error(size,DEC); log_error(F(" bytes!")); log_flush(); - return false; - } - - StaticJsonDocument<CONFIG_JSON_SIZE> root; - - auto err = deserializeJson( root, buf.get() ); - if( err ) { - log_error(F("\n[wifiParams] JSON format error in WiFi config file ")); log_error(WIFI_CONFIG_FILE); - log_error(F("\n[wifiParams] ERROR msg: ")); log_error(err.c_str()); - log_error(F("\n[wifiParams] removing file and applying DEFAULTS ...")); - log_flush(); - SPIFFS.remove(WIFI_CONFIG_FILE); - _applyDefaults(); - return false; - } -#if (LOG_LEVEL >= LOG_LVL_DEBUG) - serializeJsonPretty( root, Serial ); -#endif - - // ready to parse JSON objects and to extract values - return _loadConfig( root.as<JsonObject>() ); -} - - - -/* - * save updated parameters to the config file - */ -bool wifiParametersMgt::saveConfigFile( void ) { - if( !isValid() ) return false; - - if( !_updated ) { - log_debug(F("\n[wifiParams] saved options from WEB portal didn't modified any of the default values for options ... thus nothing to save!")); log_flush(); - return false; - } - - log_info(F("\n[wifiParams] start to SAVE wifi parameters in config file ...")); log_flush(); - - // create JSON structure - StaticJsonDocument<CONFIG_JSON_SIZE> _doc; - JsonObject root = _doc.to<JsonObject>(); - - - // fill-in JSON structure - _saveConfig( root ); - - - /* - * save JSON to config file - */ - if( root.size()==0 ) { - // nothing to save ... thus we delete the config file (if any) - log_debug(F("\n[wifiParams] empty JSON structure ... thus remove config file: "));log_debug(WIFI_CONFIG_FILE);log_flush(); - return SPIFFS.remove(WIFI_CONFIG_FILE); - } - - // ok, there's something to save at least - File configFile = SPIFFS.open( WIFI_CONFIG_FILE, "w"); // truncate if exists or create otherwise - if( !configFile ) { - log_error(F("\n[wifiParams] error creating file: "));log_debug(WIFI_CONFIG_FILE);log_flush(); - return false; - } - - // save JSON to file - - if( serializeJson( root, configFile )==0 ) { - configFile.close(); - log_error(F("\n[wifiParams] error unable to write data to file: "));log_debug(WIFI_CONFIG_FILE);log_flush(); - return false; - } - - // close file - configFile.close(); - - log_info(F("\n[wifiParams] successfully saved JSON config file: "));log_debug(WIFI_CONFIG_FILE);log_flush(); - - return true; -} - - - -/* - * Grab WIFI settings from struct station_config - */ -bool wifiParametersMgt::_getWIFIsettings( void ) { - // grab WIFI station connexion parameters from current connexion ... - struct station_config _conf; - - if( wifi_station_get_config(&_conf) and strlen(reinterpret_cast<const char*>(_conf.ssid)) ) { - - log_debug(F("\n[wifiParams] retrieved current ssid = ")); log_debug(reinterpret_cast<const char*>(_conf.ssid)); - log_debug(F("\n[wifiParams] retrieved current pass = ")); log_debug(reinterpret_cast<const char*>(_conf.password)); - log_flush(); - - if( strcmp(_ssid, reinterpret_cast<const char*>(_conf.ssid)) or - !strcmp(_pass, reinterpret_cast<const char*>(_conf.password)) ) { - - log_debug(F("\n[wifiParams] new credentials detected ... update!")); log_flush(); - strncpy( _ssid, reinterpret_cast<const char*>(_conf.ssid), sizeof(_ssid) ); - strncpy( _pass, reinterpret_cast<const char*>(_conf.password), sizeof(_pass) ); - _updated = true; - } - } - else { - log_debug(F("\n[wifiParams] no SSID / PASS found neither in config file nor struct station ... probably first time connect ...")); log_flush(); - return false; - } - - return true; -} - - - -/* - * get WiFi SSID - */ -const char *wifiParametersMgt::getWIFIssid( void ) { - if( !_initialized ) return nullptr; - return _ssid; -} - - - -/* - * get WiFi PASSWORD - */ -const char *wifiParametersMgt::getWIFIpass( void ) { - if( !_initialized ) return nullptr; - return _pass; -} - - - -/* - * sensOCampus SANDBOX option - */ -bool wifiParametersMgt::_setopt_sandboxMode( bool value ) { - if( value != _opt_sandboxMode ) { - _opt_sandboxMode = value; - _updated = true; - } - return _opt_sandboxMode; -} - - - -/* - * neOClock TM1637 7 segment display driver - */ -bool wifiParametersMgt::_setopt_7segTM1637( bool value ) { - if( value != _opt_7segTM1637 ) { - _opt_7segTM1637 = value; - _updated = true; - } - return _opt_7segTM1637; -} - - - -/* - * PIR sensor option - */ -bool wifiParametersMgt::_setopt_PIRsensor( bool value ) { - if( value != _opt_PIRsensor ) { - _opt_PIRsensor = value; - _updated = true; - } - return _opt_PIRsensor; -} - - - -/* - * Dangerous: Erase ALL option - */ -bool wifiParametersMgt::_setopt_eraseALL( bool value ) { - _opt_eraseALL = value; - return _opt_eraseALL; -} - - - -/* ------------------------------------------------------------------------------ - * Private methods - */ - - - -/* - * apply DEFAULTS values - * Note: options ought to get false as defaults - */ -void wifiParametersMgt::_applyDefaults( void ) { - - // will get set to true once we'll have options set though our captive WEB portal - _updated = false; - - // WiFi settings - _ssid[0] = '\0'; - _pass[0] = '\0'; - - // as default, senSOcampus sandbox mode is DISABLED - _opt_sandboxMode = false; - - // TM1637 7segment based clock - _opt_7segTM1637 = false; - - // PIR sensor set as an option because it can't get detected - _opt_PIRsensor = false; - - - - - // Whole destruction option - _opt_eraseALL = false; - - /* - * finally structure is initialized - */ - _initialized = true; -} - - - -/* - * fill JSON structure with things to save - */ -bool wifiParametersMgt::_saveConfig( JsonObject root ) { - - // save WiFi parameters - if( strlen(_ssid) ) { - root["ssid"] = _ssid; - root["pass"] = _pass; - } - else { - log_debug(F("\n[wifiParams] no WIFI credentials to save ..."));log_flush(); - } - - // save options ? - if( _updated ) { - - root["opt_sandboxMode"] = _opt_sandboxMode; - root["opt_7segTM1637"] = _opt_7segTM1637; - root["opt_PIRsensor"] = _opt_PIRsensor; - - /* - * add additional options here - */ - } - else { - log_debug(F("\n[wifiParams] no change in options to save ..."));log_flush(); - } - - return true; -} - - - -/* - * parse JSON objects that contain config - */ -bool wifiParametersMgt::_loadConfig( JsonObject root ) { - log_debug(F("\n[wifiParams] start parsing JSON config ...")); - - bool _wifiSet = false; - -/* -// using C++98 syntax (for older compilers): -for (JsonObject::iterator it=root.begin(); it!=root.end(); ++it) { - Serial.println(it->key().c_str()); - Serial.println(it->value().as<char*>()); -} -*/ - - // iterate over all [key,values] pairs - for (JsonObject::iterator it=root.begin(); it!=root.end(); ++it) { - - { - const char *_key = PSTR("ssid"); - if( strncmp_P(it->key().c_str(), _key, strlen_P(_key))==0 ) { - // SSID is present :) - if( it->value().is<const char*>() ) { - _wifiSet = true; - strncpy( _ssid, it->value(), sizeof(_ssid) ); - log_debug(F("\n[wifiParams][config_file] ssid = ")); log_debug(_ssid); log_flush(); - } - else { - log_error(F("\n[wifiParams] wifi_ssid is not of const char* type ?!?!")); log_flush(); - } - continue; - } - } - - { - const char *_key = PSTR("pass"); - if( strncmp_P(it->key().c_str(), _key, strlen_P(_key))==0 ) { - // PASS is present :) - if( it->value().is<const char*>() ){ - _wifiSet = true; - strncpy( _pass, it->value(), sizeof(_pass) ); - log_debug(F("\n[wifiParams][config_file] pass = ")); log_debug(_pass); log_flush(); - } - else { - log_error(F("\n[wifiParams] wifi_pass is not of const char* type ?!?!")); log_flush(); - } - continue; - } - } - - { - const char *_key = PSTR("opt_sandboxMode"); - if( strncmp_P(it->key().c_str(), _key, strlen_P(_key))==0 ) { - // sensOCampus sandbox mode - if( it->value().is<bool>() ) { - _opt_sandboxMode = it->value(); - log_debug(F("\n[wifiParams][config_file] sandboxMode = ")); log_debug(_opt_sandboxMode,DEC); log_flush(); - } - else { - log_error(F("\n[wifiParams] opt_sandboxMode is not a bool ?!?!")); log_flush(); - } - continue; - } - } - - { - const char *_key = PSTR("opt_7segTM1637"); - if( strncmp_P(it->key().c_str(), _key, strlen_P(_key))==0 ) { - // TM1737 based 7 segment display - if( it->value().is<bool>() ) { - _opt_7segTM1637 = it->value(); - log_debug(F("\n[wifiParams][config_file] 7segTM1637 = ")); log_debug(_opt_7segTM1637,DEC); log_flush(); - } - else { - log_error(F("\n[wifiParams] opt_7segTM1637 is not a bool ?!?!")); log_flush(); - } - continue; - } - } - - { - const char *_key = PSTR("opt_PIRsensor"); - if( strncmp_P(it->key().c_str(), _key, strlen_P(_key))==0 ) { - // PIR sensor - if( it->value().is<bool>() ) { - _opt_PIRsensor = it->value(); - log_debug(F("\n[wifiParams][config_file] PIR sensor = ")); log_debug(_opt_PIRsensor,DEC); log_flush(); - } - else { - log_error(F("\n[wifiParams] opt_PIRsensor is not a bool ?!?!")); log_flush(); - } - continue; - } - } - - // unknown key ?!?! - log_error(F("\n[wifiParams] unknown key: "));log_debug((const char*)(it->key().c_str())); log_flush(); - } - - /* - * check if wifi connexion parameters have been read ... - * ... otherwise we'll extract them from struct station - */ - if( _wifiSet ) return true; - - // grab from previous settings ... - _getWIFIsettings(); - - // over :) - return true; -} - diff --git a/work/neocampus_libs.orig/wifiParametersMgt.h b/work/neocampus_libs.orig/wifiParametersMgt.h deleted file mode 100644 index 98a5e8a4595406c3138dde357183eab840b00103..0000000000000000000000000000000000000000 --- a/work/neocampus_libs.orig/wifiParametersMgt.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * neOCampus operation - * - * User's high-level parameters management class. - * Most of those parameters come from WiFiManager parameters - * - * Thiebolt F. Jun.18 initial release - * - */ - - -#ifndef _WIFI_PARAMETERS_MGT_H_ -#define _WIFI_PARAMETERS_MGT_H_ - -/* - * Includes - */ -#include <Arduino.h> -#include <ArduinoJson.h> - -#include "neocampus.h" - - - - -/* - * Definitions - */ - - - -/* - * Class - */ -class wifiParametersMgt { - public: - wifiParametersMgt( void ); - ~wifiParametersMgt( void ); - - // methods - bool isValid( void ); // tell parameters have been initialized at least once - bool loadConfigFile( void ); - bool saveConfigFile( void ); - - const char * getWIFIssid( void ); - const char * getWIFIpass( void ); - bool _getWIFIsettings( void ); // read struct station to extract WIFI parameters - - // wrapper for options querries - bool isEnabledSandbox( void ) { return _opt_sandboxMode; }; // tell if neOCampus sandbox apply or if sensocampus is enabled (default) - bool _setopt_sandboxMode( bool ); // TODO: find a better way :| - - bool isEnabled7segTM1637( void ) { return _opt_7segTM1637; }; // tell if 7-segments TM1637 driver has been activated (neOClock) - bool _setopt_7segTM1637( bool ); // TODO: find a better way :| - - bool isEnabledPIR( void ) { return _opt_PIRsensor; }; // tell if infrared detector has been activated - bool _setopt_PIRsensor( bool ); // TODO: find a better way :| - - - - bool isEnabledEraseALL( void ) { return _opt_eraseALL; }; // tell sensor to clear everything (wifi, eeprom and spiffs) - bool _setopt_eraseALL( bool ); // TODO: find a better way :| - - private: - - bool _initialized; - bool _updated; // did WEB options have been saved ? - - char _ssid[32]; - char _pass[64]; // for WEP keys ?? (yes ?) - - bool _opt_sandboxMode; // sensOCampus NORMAL / SANDBOX mode - bool _opt_7segTM1637; // TM1737 7segment display available - bool _opt_PIRsensor; // PIR sensor available - - bool _opt_eraseALL; // flag for whole destruction of WiFi credentials, eeprom, spiffs - - /* - * private member functions - */ - void _applyDefaults( void ); - bool _loadConfig( JsonObject ); // interprets JSON buffer from config file - bool _saveConfig( JsonObject ); // fill JSON buffer with things to save to config file -}; - - -#endif /* _WIFI_PARAMETERS_MGT_H_ */ - -