diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..55199aa2 --- /dev/null +++ b/.clang-format @@ -0,0 +1,14 @@ +BasedOnStyle: Google +Language: Cpp +ColumnLimit: 0 +IndentWidth: 2 +TabWidth: 2 +UseTab: Never +IndentPPDirectives: AfterHash +ReflowComments: false +SpacesBeforeTrailingComments: 1 +AlignConsecutiveMacros: true +AlignTrailingComments: false +AccessModifierOffset: -2 +DerivePointerAlignment: false +PointerAlignment: Left diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..e01795cc --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = false +insert_final_newline = true diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..17eed9c4 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,22 @@ +name: Check Code Format + +on: [push, pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Check main format + uses: DoozyX/clang-format-lint-action@v0.6 + with: + source: "./main" + extensions: "h,ino" + clangFormatVersion: 9 + - name: Check test format + uses: DoozyX/clang-format-lint-action@v0.6 + with: + source: "./test" + extensions: "h,ino" + clangFormatVersion: 9 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b9f3806a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.pio +.vscode diff --git a/.travis.yml b/.travis.yml index 8005813c..6cad8691 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,22 +19,21 @@ # Travis CI documentation (see above). # - # # Template #1: General project. Test it using existing `platformio.ini`. # -matrix: +jobs: include: - - language: python + - name: "Build and deploy with PlatformIO" + language: python python: 2.7 - sudo: false cache: - directories: - - "~/.platformio" + directories: + - "~/.platformio" install: - pip install -U platformio - platformio update - script: + script: - sed -i 's/version_tag/'$TRAVIS_TAG'/g' main/User_config.h - platformio run - bash scripts/prepare_deploy.sh @@ -52,7 +51,8 @@ matrix: - toDeploy/* skip_cleanup: true - - language: node_js + - name: "Build and deploy docs" + language: node_js node_js: - lts/* install: @@ -63,10 +63,10 @@ matrix: before_deploy: echo "docs.openmqttgateway.com" >> docs/.vuepress/dist/CNAME deploy: provider: pages - skip-cleanup: true + skip_cleanup: true local_dir: docs/.vuepress/dist - github-token: $GITHUB_TOKEN # a token generated on github allowing travis to push code on you repository - keep-history: true + github_token: $GITHUB_TOKEN # a token generated on github allowing travis to push code on you repository + keep_history: true on: repo: 1technophile/OpenMQTTGateway all_branches: true diff --git a/main/User_config.h b/main/User_config.h index 9d2e0051..49457317 100644 --- a/main/User_config.h +++ b/main/User_config.h @@ -48,10 +48,10 @@ */ /*-------------DEFINE GATEWAY NAME BELOW IT CAN ALSO BE DEFINED IN platformio.ini----------------*/ #ifndef Gateway_Name - #define Gateway_Name "OpenMQTTGateway" +# define Gateway_Name "OpenMQTTGateway" #endif #ifndef Gateway_Short_Name - #define Gateway_Short_Name "OMG" +# define Gateway_Short_Name "OMG" #endif #define Base_Topic "home/" @@ -60,35 +60,35 @@ //#define NetworkAdvancedSetup true //uncomment if you want to set advanced network parameters for arduino boards, not uncommented you can set the IP and mac only #ifdef NetworkAdvancedSetup // for arduino boards advanced config - #if defined(ESP8266)||defined(ESP32) - const byte ip[] = { 192, 168, 1, 99 }; //ip adress of the gateway, already defined for arduino below - #endif - const byte gateway[] = { 0, 0, 0, 0 }; - const byte Dns[] = { 0, 0, 0, 0 }; - const byte subnet[] = { 255, 255, 255, 0 }; +# if defined(ESP8266) || defined(ESP32) +const byte ip[] = {192, 168, 1, 99}; //ip adress of the gateway, already defined for arduino below +# endif +const byte gateway[] = {0, 0, 0, 0}; +const byte Dns[] = {0, 0, 0, 0}; +const byte subnet[] = {255, 255, 255, 0}; #endif -#if defined(ESP8266)||defined(ESP32) // for nodemcu, weemos and esp8266 - //#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP +#if defined(ESP8266) || defined(ESP32) // for nodemcu, weemos and esp8266 +//#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP #else // for arduino boards - const byte ip[] = { 192, 168, 1, 99 }; - const byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95 }; //W5100 ethernet shield mac adress +const byte ip[] = {192, 168, 1, 99}; +const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield mac adress #endif #if defined(ESPWifiManualSetup) // for nodemcu, weemos and esp8266 - #define wifi_ssid "wifi ssid" - #define wifi_password "wifi password" +# define wifi_ssid "wifi ssid" +# define wifi_password "wifi password" #endif -#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point -#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point +#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point +#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point #define WifiManager_ConfigPortalTimeOut 120 -#define WifiManager_TimeOut 5 +#define WifiManager_TimeOut 5 /*-------------DEFINE YOUR ADVANCED NETWORK PARAMETERS BELOW----------------*/ //#define MDNS_SD //uncomment if you want to use mdns for discovering automatically your ip server, please note that MDNS with ESP32 can cause the BLE to not work -#define maxConnectionRetry 10 //maximum MQTT connection attempts before going to wifimanager setup if never connected once -#define maxConnectionRetryWifi 5 //maximum Wifi connection attempts with existing credential at start (used to bypass ESP32 issue on wifi connect) +#define maxConnectionRetry 10 //maximum MQTT connection attempts before going to wifimanager setup if never connected once +#define maxConnectionRetryWifi 5 //maximum Wifi connection attempts with existing credential at start (used to bypass ESP32 issue on wifi connect) //set minimum quality of signal so it ignores AP's under that quality #define MinimumWifiSignalQuality 8 @@ -97,11 +97,11 @@ //MQTT Parameters definition //#define mqtt_server_name "www.mqtt_broker.com" // instead of defining the server by its IP you can define it by its name, uncomment this line and set the correct MQTT server host name #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) - #define parameters_size 20 - #define mqtt_topic_max_size 100 +# define parameters_size 20 +# define mqtt_topic_max_size 100 #else - #define parameters_size 15 - #define mqtt_topic_max_size 50 +# define parameters_size 15 +# define mqtt_topic_max_size 50 #endif char mqtt_user[parameters_size] = "your_username"; // not compulsory only if your broker needs authentication char mqtt_pass[parameters_size] = "your_password"; // not compulsory only if your broker needs authentication @@ -110,9 +110,9 @@ char mqtt_port[6] = "1883"; char mqtt_topic[mqtt_topic_max_size] = Base_Topic; char gateway_name[parameters_size * 2] = Gateway_Name; -#if defined(ESP8266)||defined(ESP32) - #define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol - #define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol +#if defined(ESP8266) || defined(ESP32) +# define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol +# define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol #endif /*------------------DEEP SLEEP parameters ------------------*/ @@ -120,34 +120,34 @@ char gateway_name[parameters_size * 2] = Gateway_Name; //DEFAULT_LOW_POWER_MODE 1 to activate deep sleep with LCD ON when a function is processing, //DEFAULT_LOW_POWER_MODE 2 to activate deep sleep with LED ON when a function is processing (LCD is turned OFF) #ifdef ESP32 - #ifndef SLEEP_BUTTON - #define SLEEP_BUTTON 33 - #endif - #ifndef DEFAULT_LOW_POWER_MODE - #define DEFAULT_LOW_POWER_MODE 0 - #endif - #ifndef LOW_POWER_LED - #define LOW_POWER_LED 2 - #endif - #ifndef LOW_POWER_LED_OFF - #define LOW_POWER_LED_OFF 1 - #endif +# ifndef SLEEP_BUTTON +# define SLEEP_BUTTON 33 +# endif +# ifndef DEFAULT_LOW_POWER_MODE +# define DEFAULT_LOW_POWER_MODE 0 +# endif +# ifndef LOW_POWER_LED +# define LOW_POWER_LED 2 +# endif +# ifndef LOW_POWER_LED_OFF +# define LOW_POWER_LED_OFF 1 +# endif int low_power_mode = DEFAULT_LOW_POWER_MODE; #endif // WIFI mode, uncomment to force a wifi mode, if not uncommented the ESP will connect without a mode forced // if there is a reconnection issue it will try to connect with G mode and if not working with B mode #ifdef ESP32 - #include "esp_wifi.h" - uint8_t wifiProtocol = 0; // default mode, automatic selection - //uint8_t wifiProtocol = WIFI_PROTOCOL_11B; - //uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G; // can't have only one https://github.com/espressif/esp-idf/issues/702 - //uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N; // can't have only one https://github.com/espressif/esp-idf/issues/702 +# include "esp_wifi.h" +uint8_t wifiProtocol = 0; // default mode, automatic selection + //uint8_t wifiProtocol = WIFI_PROTOCOL_11B; + //uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G; // can't have only one https://github.com/espressif/esp-idf/issues/702 + //uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N; // can't have only one https://github.com/espressif/esp-idf/issues/702 #elif ESP8266 - uint8_t wifiProtocol = 0; // default mode, automatic selection - //uint8_t wifiProtocol = WIFI_PHY_MODE_11B; - //uint8_t wifiProtocol = WIFI_PHY_MODE_11G; - //uint8_t wifiProtocol = WIFI_PHY_MODE_11N; +uint8_t wifiProtocol = 0; // default mode, automatic selection + //uint8_t wifiProtocol = WIFI_PHY_MODE_11B; + //uint8_t wifiProtocol = WIFI_PHY_MODE_11G; + //uint8_t wifiProtocol = WIFI_PHY_MODE_11N; #endif /*-------------DEFINE THE MODULES YOU WANT BELOW----------------*/ @@ -183,11 +183,11 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE; //#define ZradioCC1101 "CC1101" //ESP8266, ESP32 /*-------------DEFINE YOUR MQTT ADVANCED PARAMETERS BELOW----------------*/ -#define version_Topic "/version" -#define will_Topic "/LWT" -#define will_QoS 0 -#define will_Retain true -#define will_Message "offline" +#define version_Topic "/version" +#define will_Topic "/LWT" +#define will_QoS 0 +#define will_Retain true +#define will_Message "offline" #define Gateway_AnnouncementMsg "online" #define jsonPublishing true //comment if you don't want to use Json publishing (one topic for all the parameters) @@ -195,7 +195,7 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE; #define jsonReceiving true //comment if you don't want to use Json reception analysis //#define simplePublishing true //comment if you don't want to use simple publishing (one topic for one parameter) -//example +//example // home/OpenMQTTGateway_ESP32_DEVKIT/BTtoMQTT/4XXXXXXXXXX4/rssi -63.0 // home/OpenMQTTGateway_ESP32_DEVKIT/BTtoMQTT/4XXXXXXXXXX4/servicedata fe0000000000000000000000000000000000000000 //#define simpleReceiving true //comment if you don't want to use old way reception analysis @@ -203,49 +203,49 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE; /*-------------DEFINE YOUR OTA PARAMETERS BELOW----------------*/ #define ota_hostname Gateway_Name #define ota_password "OTAPASSWORD" -#define ota_port 8266 +#define ota_port 8266 /*-------------DEFINE PINs FOR STATUS LEDs----------------*/ #ifndef led_receive - #ifdef ESP8266 - #define led_receive 40 - #elif ESP32 - #define led_receive 40 - #elif __AVR_ATmega2560__ //arduino mega - #define led_receive 40 - #else //arduino uno/nano - #define led_receive 40 - #endif +# ifdef ESP8266 +# define led_receive 40 +# elif ESP32 +# define led_receive 40 +# elif __AVR_ATmega2560__ //arduino mega +# define led_receive 40 +# else //arduino uno/nano +# define led_receive 40 +# endif #endif #ifndef led_send - #ifdef ESP8266 - #define led_send 42 - #elif ESP32 - #define led_send 42 - #elif __AVR_ATmega2560__ //arduino mega - #define led_send 42 - #else //arduino uno/nano - #define led_send 42 - #endif +# ifdef ESP8266 +# define led_send 42 +# elif ESP32 +# define led_send 42 +# elif __AVR_ATmega2560__ //arduino mega +# define led_send 42 +# else //arduino uno/nano +# define led_send 42 +# endif #endif #ifndef led_info - #ifdef ESP8266 - #define led_info 44 - #elif ESP32 - #define led_info 44 - #elif __AVR_ATmega2560__ //arduino mega - #define led_info 44 - #else //arduino uno/nano - #define led_info 44 - #endif +# ifdef ESP8266 +# define led_info 44 +# elif ESP32 +# define led_info 44 +# elif __AVR_ATmega2560__ //arduino mega +# define led_info 44 +# else //arduino uno/nano +# define led_info 44 +# endif #endif #ifndef TRIGGER_PIN - #ifdef ESP8266 - #define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s) - #elif ESP32 - #define TRIGGER_PIN 0 // boot button as full reset button (long press >10s) - #endif +# ifdef ESP8266 +# define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s) +# elif ESP32 +# define TRIGGER_PIN 0 // boot button as full reset button (long press >10s) +# endif #endif // VCC ------------D|-----------/\/\/\/\ ----------------- Arduino PIN @@ -255,19 +255,19 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE; /*-------------------CHANGING THEM IS NOT COMPULSORY-----------------------*/ /*----------------------------USER PARAMETERS-----------------------------*/ #ifdef ZgatewaySRFB - #define SERIAL_BAUD 19200 +# define SERIAL_BAUD 19200 #else - #define SERIAL_BAUD 115200 +# define SERIAL_BAUD 115200 #endif /*--------------MQTT general topics-----------------*/ // global MQTT subject listened by the gateway to execute commands (send RF, IR or others) -#define subjectMQTTtoX "/commands/#" -#define subjectMultiGTWKey "toMQTT" -#define subjectGTWSendKey "MQTTto" +#define subjectMQTTtoX "/commands/#" +#define subjectMultiGTWKey "toMQTT" +#define subjectGTWSendKey "MQTTto" // key used for launching commands to the gateway -#define restartCmd "restart" -#define eraseCmd "erase" +#define restartCmd "restart" +#define eraseCmd "erase" // uncomment the line below to integrate msg value into the subject when receiving //#define valueAsASubject true @@ -276,16 +276,16 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE; #define time_avoid_duplicate 3000 // if you want to avoid duplicate mqtt message received set this to > 0, the value is the time in milliseconds during which we don't publish duplicates #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) - #define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 - #define ARDUINOJSON_USE_LONG_LONG 1 +# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 +# define ARDUINOJSON_USE_LONG_LONG 1 #else // boards with smaller memory - #define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 +# define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 #endif #define TimeBetweenReadingSYS 120 // time between (s) system readings (like memory) -#define TimeBeforeMQTTconnect 10 // time estimated (s) before the board is connected to MQTT -#define subjectSYStoMQTT "/SYStoMQTT" -#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config" +#define TimeBeforeMQTTconnect 10 // time estimated (s) before the board is connected to MQTT +#define subjectSYStoMQTT "/SYStoMQTT" +#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config" /*-------------------DEFINE LOG LEVEL----------------------*/ #define LOG_LEVEL LOG_LEVEL_NOTICE diff --git a/main/ZactuatorFASTLED.ino b/main/ZactuatorFASTLED.ino index 8bd92d9d..6adaf4f4 100644 --- a/main/ZactuatorFASTLED.ino +++ b/main/ZactuatorFASTLED.ino @@ -24,10 +24,9 @@ #ifdef ZactuatorFASTLED -#include +# include -enum LEDState -{ +enum LEDState { OFF, FIRE, GENERAL @@ -42,8 +41,7 @@ const long blinkInterval = 300; const long fireUpdate = 10; CRGBPalette16 gPal; -void setupFASTLED() -{ +void setupFASTLED() { Log.notice(F("FASTLED_DATA_PIN: %d" CR), FASTLED_DATA_PIN); Log.notice(F("FASTLED_NUM_LEDS: %d" CR), FASTLED_NUM_LEDS); Log.trace(F("ZactuatorFASTLED setup done " CR)); @@ -51,15 +49,13 @@ void setupFASTLED() } //returns the current step of the animation -int animation_step(int duration, int steps) -{ +int animation_step(int duration, int steps) { int currentStep = ((currentUpdate % duration) / ((float)duration)) * steps; return currentStep; } //returns the number of steps since the last update -int animation_step_count(int duration, int steps) -{ +int animation_step_count(int duration, int steps) { long lastAnimationNumber = lastUpdate / duration; long currentAnimationNumber = currentUpdate / duration; int lastStep = ((lastUpdate % duration) / ((float)duration)) * steps; @@ -68,44 +64,29 @@ int animation_step_count(int duration, int steps) return currentStep - lastStep + (currentAnimationNumber - lastAnimationNumber) * steps; } -void FASTLEDLoop() -{ - +void FASTLEDLoop() { lastUpdate = currentUpdate; currentUpdate = millis(); - if (currentLEDState == GENERAL) - { - - for (int i = 0; i < FASTLED_NUM_LEDS; i++) - { - + if (currentLEDState == GENERAL) { + for (int i = 0; i < FASTLED_NUM_LEDS; i++) { int count = animation_step_count(blinkInterval, 2); int step = animation_step(blinkInterval, 2); - if (count > 0) - { - if (blinkLED[i]) - { - - if (step == 0) - { + if (count > 0) { + if (blinkLED[i]) { + if (step == 0) { leds[i] = ledColorBlink[i]; - } - else - { + } else { ledColorBlink[i] = leds[i]; leds[i] = CRGB::Black; } } } } - } - else if (currentLEDState == FIRE) - { + } else if (currentLEDState == FIRE) { int count = animation_step_count(fireUpdate, 1); - if (count > 0) - { + if (count > 0) { //random16_add_entropy( random(0)); //random() don't exists in ESP framework - workaround? Fire2012WithPalette(); } @@ -113,87 +94,69 @@ void FASTLEDLoop() FastLED.show(); } -boolean FASTLEDtoMQTT() -{ +boolean FASTLEDtoMQTT() { return false; } -#ifdef jsonReceiving -void MQTTtoFASTLED(char *topicOri, JsonObject &jsonData) -{ +# ifdef jsonReceiving +void MQTTtoFASTLED(char* topicOri, JsonObject& jsonData) { currentLEDState = GENERAL; //trc(topicOri); //number = (long)strtol(&datacallback[1], NULL, 16); - if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled)) - { + if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled)) { Log.trace(F("MQTTtoFASTLED JSON analysis" CR)); int ledNr = jsonData["led"]; Log.notice(F("Led numero: %d" CR), ledNr); - const char *color = jsonData["hex"]; + const char* color = jsonData["hex"]; Log.notice(F("Color hex: %s" CR), color); long number = (long)strtol(color, NULL, 16); bool blink = jsonData["blink"]; - if (ledNr <= FASTLED_NUM_LEDS) - { + if (ledNr <= FASTLED_NUM_LEDS) { Log.notice(F("Blink: %d" CR), blink); blinkLED[ledNr] = blink; leds[ledNr] = number; } } } -#endif +# endif -#ifdef simpleReceiving -void MQTTtoFASTLED(char *topicOri, char *datacallback) -{ +# ifdef simpleReceiving +void MQTTtoFASTLED(char* topicOri, char* datacallback) { Log.trace(F("MQTTtoFASTLED: " CR)); currentLEDState = GENERAL; long number = 0; - if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED)) - { + if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED)) { number = (long)strtol(&datacallback[1], NULL, 16); Log.notice(F("Number: %l" CR), number); - for (int i = 0; i < FASTLED_NUM_LEDS; i++) - { + for (int i = 0; i < FASTLED_NUM_LEDS; i++) { leds[i] = number; } FastLED.show(); - } - else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness)) - { + } else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness)) { number = (long)strtol(&datacallback[1], NULL, 16); Log.notice(F("Number: %l" CR), number); FastLED.setBrightness(number); FastLED.show(); - } - else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation)) - { + } else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation)) { String payload = datacallback; Log.notice(F("Datacallback: %s" CR), datacallback); - if (strstr(datacallback, "fire") != NULL) - { + if (strstr(datacallback, "fire") != NULL) { currentLEDState = FIRE; gPal = HeatColors_p; - } - else - { + } else { currentLEDState = OFF; } - } - else - { + } else { currentLEDState = OFF; } - if (currentLEDState == OFF) - { - for (int i = 0; i < FASTLED_NUM_LEDS; i++) - { + if (currentLEDState == OFF) { + for (int i = 0; i < FASTLED_NUM_LEDS; i++) { leds[i] = CRGB::Black; } } } -#endif +# endif // Fire2012 by Mark Kriegsman, July 2012 // as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY //// @@ -225,52 +188,44 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback) // COOLING: How much does the air cool as it rises? // Less cooling = taller flames. More cooling = shorter flames. // Default 55, suggested range 20-100 -#define COOLING 55 +# define COOLING 55 // SPARKING: What chance (out of 255) is there that a new spark will be lit? // Higher chance = more roaring fire. Lower chance = more flickery fire. // Default 120, suggested range 50-200. -#define SPARKING 120 +# define SPARKING 120 bool gReverseDirection = false; -void Fire2012WithPalette() -{ +void Fire2012WithPalette() { // Array of temperature readings at each simulation cell static byte heat[FASTLED_NUM_LEDS]; // Step 1. Cool down every cell a little - for (int i = 0; i < FASTLED_NUM_LEDS; i++) - { + for (int i = 0; i < FASTLED_NUM_LEDS; i++) { heat[i] = qsub8(heat[i], random8(0, ((COOLING * 10) / FASTLED_NUM_LEDS) + 2)); } // Step 2. Heat from each cell drifts 'up' and diffuses a little - for (int k = FASTLED_NUM_LEDS - 1; k >= 2; k--) - { + for (int k = FASTLED_NUM_LEDS - 1; k >= 2; k--) { heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3; } // Step 3. Randomly ignite new 'sparks' of heat near the bottom - if (random8() < SPARKING) - { + if (random8() < SPARKING) { int y = random8(7); heat[y] = qadd8(heat[y], random8(160, 255)); } // Step 4. Map from heat cells to LED colors - for (int j = 0; j < FASTLED_NUM_LEDS; j++) - { + for (int j = 0; j < FASTLED_NUM_LEDS; j++) { // Scale the heat value from 0-255 down to 0-240 // for best results with color palettes. byte colorindex = scale8(heat[j], 240); CRGB color = ColorFromPalette(gPal, colorindex); int pixelnumber; - if (gReverseDirection) - { + if (gReverseDirection) { pixelnumber = (FASTLED_NUM_LEDS - 1) - j; - } - else - { + } else { pixelnumber = j; } leds[pixelnumber] = color; diff --git a/main/ZactuatorONOFF.ino b/main/ZactuatorONOFF.ino index 9a2e5b42..b4115a91 100644 --- a/main/ZactuatorONOFF.ino +++ b/main/ZactuatorONOFF.ino @@ -30,37 +30,29 @@ #ifdef ZactuatorONOFF -#ifdef jsonReceiving -void MQTTtoONOFF(char *topicOri, JsonObject &ONOFFdata) -{ - if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF)) - { +# ifdef jsonReceiving +void MQTTtoONOFF(char* topicOri, JsonObject& ONOFFdata) { + if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF)) { Log.trace(F("MQTTtoONOFF json data analysis" CR)); int boolSWITCHTYPE = ONOFFdata["cmd"] | 99; int pin = ONOFFdata["pin"] | ACTUATOR_ONOFF_PIN; - if (boolSWITCHTYPE != 99) - { + if (boolSWITCHTYPE != 99) { Log.notice(F("MQTTtoONOFF boolSWITCHTYPE ok: %d" CR), boolSWITCHTYPE); Log.notice(F("Pin number: %d" CR), pin); pinMode(pin, OUTPUT); digitalWrite(pin, boolSWITCHTYPE); // we acknowledge the sending by publishing the value to an acknowledgement topic pub(subjectGTWONOFFtoMQTT, ONOFFdata); - } - else - { + } else { Log.error(F("MQTTtoONOFF failed json read" CR)); } } } -#endif - -#ifdef simpleReceiving -void MQTTtoONOFF(char *topicOri, char *datacallback) -{ - if ((cmpToMainTopic(topicOri, subjectMQTTtoONOFF))) - { +# endif +# ifdef simpleReceiving +void MQTTtoONOFF(char* topicOri, char* datacallback) { + if ((cmpToMainTopic(topicOri, subjectMQTTtoONOFF))) { Log.trace(F("MQTTtoONOFF" CR)); int pin = strtol(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 Log.notice(F("Pin number: %d" CR), pin); @@ -78,6 +70,6 @@ void MQTTtoONOFF(char *topicOri, char *datacallback) pub(subjectGTWONOFFtoMQTT, &b); } } -#endif +# endif #endif diff --git a/main/ZboardM5.ino b/main/ZboardM5.ino index fd3eee75..3618dcf4 100644 --- a/main/ZboardM5.ino +++ b/main/ZboardM5.ino @@ -29,224 +29,201 @@ #include "User_config.h" #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) -#ifdef ZboardM5STICKC -#include -#endif -#ifdef ZboardM5STACK -#include -#endif -void logToLCD(bool display) -{ - display ? Log.begin(LOG_LEVEL_LCD, &M5.Lcd) : Log.begin(LOG_LEVEL, &Serial); // Log on LCD following LOG_LEVEL_LCD +# ifdef ZboardM5STICKC +# include +# endif +# ifdef ZboardM5STACK +# include +# endif +void logToLCD(bool display) { + display ? Log.begin(LOG_LEVEL_LCD, &M5.Lcd) : Log.begin(LOG_LEVEL, &Serial); // Log on LCD following LOG_LEVEL_LCD } -void setBrightness(int brightness) -{ - #ifdef ZboardM5STACK - M5.Lcd.setBrightness(brightness * 2); - #endif - #ifdef ZboardM5STICKC - (!brightness) ? M5.Axp.ScreenBreath(0) : M5.Axp.ScreenBreath(7 + (int)brightness * 0.08); - #endif +void setBrightness(int brightness) { +# ifdef ZboardM5STACK + M5.Lcd.setBrightness(brightness * 2); +# endif +# ifdef ZboardM5STICKC + (!brightness) ? M5.Axp.ScreenBreath(0) : M5.Axp.ScreenBreath(7 + (int)brightness * 0.08); +# endif } -void setupM5() -{ - Log.notice(F("Setup M5" CR)); - pinMode(SLEEP_BUTTON, INPUT); - // M5 stack 320*240 - // M5StickC 160*80 - // M5Stick LCD not supported - Log.notice(F("Low power set to: %d" CR), low_power_mode); - switch (low_power_mode)// if LOW POWER the intro is bypassed and the brightness set to sleep brightness - { - case 0: - wakeScreen(NORMAL_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(WHITE); - displayIntro(M5.Lcd.width() * 0.25, (M5.Lcd.width() / 2) + M5.Lcd.width() * 0.12, (M5.Lcd.height()/2) + M5.Lcd.height() * 0.2); - #if LOG_TO_LCD - Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD - #endif - break; - case 1: - wakeScreen(SLEEP_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(WHITE); - #if LOG_TO_LCD - Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD - #endif - break; - case 2: - M5.begin(false,false,false); - break; - } - Log.notice(F("Setup M5 end" CR)); +void setupM5() { + Log.notice(F("Setup M5" CR)); + pinMode(SLEEP_BUTTON, INPUT); + // M5 stack 320*240 + // M5StickC 160*80 + // M5Stick LCD not supported + Log.notice(F("Low power set to: %d" CR), low_power_mode); + switch (low_power_mode) // if LOW POWER the intro is bypassed and the brightness set to sleep brightness + { + case 0: + wakeScreen(NORMAL_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(WHITE); + displayIntro(M5.Lcd.width() * 0.25, (M5.Lcd.width() / 2) + M5.Lcd.width() * 0.12, (M5.Lcd.height() / 2) + M5.Lcd.height() * 0.2); +# if LOG_TO_LCD + Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD +# endif + break; + case 1: + wakeScreen(SLEEP_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(WHITE); +# if LOG_TO_LCD + Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD +# endif + break; + case 2: + M5.begin(false, false, false); + break; + } + Log.notice(F("Setup M5 end" CR)); } -void sleepScreen() -{ - Log.trace(F("Screen going to sleep" CR)); - #ifdef ZboardM5STACK - M5.begin(false,false,false); // M5.lcd.sleep() provokes a reset of the ESP - #endif - #ifdef ZboardM5STICKC - M5.Axp.ScreenBreath(0); - M5.Axp.SetLDO2(false); - #endif +void sleepScreen() { + Log.trace(F("Screen going to sleep" CR)); +# ifdef ZboardM5STACK + M5.begin(false, false, false); // M5.lcd.sleep() provokes a reset of the ESP +# endif +# ifdef ZboardM5STICKC + M5.Axp.ScreenBreath(0); + M5.Axp.SetLDO2(false); +# endif } -void wakeScreen(int brightness) -{ - Log.trace(F("Screen wake up" CR)); - M5.begin(); - M5.Lcd.setCursor(0, 0, (M5.Lcd.height() > 200) ? 4:2); - M5.Lcd.setTextSize(1); - M5.Lcd.setRotation(1); - setBrightness(brightness); +void wakeScreen(int brightness) { + Log.trace(F("Screen wake up" CR)); + M5.begin(); + M5.Lcd.setCursor(0, 0, (M5.Lcd.height() > 200) ? 4 : 2); + M5.Lcd.setTextSize(1); + M5.Lcd.setRotation(1); + setBrightness(brightness); } -void loopM5() -{ - static int previousBtnState; - int currentBtnState = digitalRead(SLEEP_BUTTON); - if(currentBtnState != previousBtnState && currentBtnState == 0) - { - int newlow_power_mode = low_power_mode; - (low_power_mode == 2) ? newlow_power_mode = 0 : newlow_power_mode = newlow_power_mode + 1; - changelow_power_mode(newlow_power_mode); - } - previousBtnState = currentBtnState; - static int previousLogLevel; - switch (Log.getLastMsgLevel()) - { +void loopM5() { + static int previousBtnState; + int currentBtnState = digitalRead(SLEEP_BUTTON); + if (currentBtnState != previousBtnState && currentBtnState == 0) { + int newlow_power_mode = low_power_mode; + (low_power_mode == 2) ? newlow_power_mode = 0 : newlow_power_mode = newlow_power_mode + 1; + changelow_power_mode(newlow_power_mode); + } + previousBtnState = currentBtnState; + static int previousLogLevel; + switch (Log.getLastMsgLevel()) { case 1: case 2: - if (low_power_mode != 2) - { - wakeScreen(NORMAL_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(TFT_RED); // FATAL, ERROR - M5.Lcd.setTextColor(TFT_BLACK, TFT_RED); - } - break; + if (low_power_mode != 2) { + wakeScreen(NORMAL_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(TFT_RED); // FATAL, ERROR + M5.Lcd.setTextColor(TFT_BLACK, TFT_RED); + } + break; case 3: - if (low_power_mode != 2) - { - wakeScreen(NORMAL_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(TFT_ORANGE); // WARNING - M5.Lcd.setTextColor(TFT_BLACK, TFT_ORANGE); - } - break; + if (low_power_mode != 2) { + wakeScreen(NORMAL_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(TFT_ORANGE); // WARNING + M5.Lcd.setTextColor(TFT_BLACK, TFT_ORANGE); + } + break; default: - if (previousLogLevel != Log.getLastMsgLevel() && low_power_mode != 2) - { - wakeScreen(SLEEP_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(TFT_WHITE); - drawLogo(M5.Lcd.width() * 0.1875, (M5.Lcd.width()/2) - M5.Lcd.width() * 0.24, M5.Lcd.height() * 0.5, true, true, true, true, true, true); - } - break; - } - previousLogLevel = Log.getLastMsgLevel(); + if (previousLogLevel != Log.getLastMsgLevel() && low_power_mode != 2) { + wakeScreen(SLEEP_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(TFT_WHITE); + drawLogo(M5.Lcd.width() * 0.1875, (M5.Lcd.width() / 2) - M5.Lcd.width() * 0.24, M5.Lcd.height() * 0.5, true, true, true, true, true, true); + } + break; + } + previousLogLevel = Log.getLastMsgLevel(); } -void MQTTtoM5(char *topicOri, JsonObject &M5data) -{ // json object decoding - if (cmpToMainTopic(topicOri, subjectMQTTtoM5set)) - { - Log.trace(F("MQTTtoM5 json set" CR)); - // Log display set between M5 lcd (true) and serial monitor (false) - if (M5data.containsKey("log-lcd")) - { - bool displayOnLCD = M5data["log-lcd"]; - Log.notice(F("Set lcd log: %T" CR), displayOnLCD); - logToLCD(displayOnLCD); - } +void MQTTtoM5(char* topicOri, JsonObject& M5data) { // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoM5set)) { + Log.trace(F("MQTTtoM5 json set" CR)); + // Log display set between M5 lcd (true) and serial monitor (false) + if (M5data.containsKey("log-lcd")) { + bool displayOnLCD = M5data["log-lcd"]; + Log.notice(F("Set lcd log: %T" CR), displayOnLCD); + logToLCD(displayOnLCD); } + } } -void displayIntro(int i, int X, int Y) -{ - Log.trace(F("Intro display on screen" CR)); - drawLogo(i, X, Y, false, true, false, false, false, false); - delay(50); - drawLogo(i, X, Y, false, false, true, false, false, false); - delay(50); - drawLogo(i, X, Y, false, true, false, false, false, false); - delay(50); - drawLogo(i, X, Y, false, true, true, false, false, false); - delay(50); - drawLogo(i, X, Y, false, true, true, true, false, false); - delay(50); - drawLogo(i, X, Y, false, true, true, false, true, false); - delay(50); - drawLogo(i, X, Y, false, true, true, true, true, false); - delay(50); - drawLogo(i, X, Y, true, true, true, true, true, false); +void displayIntro(int i, int X, int Y) { + Log.trace(F("Intro display on screen" CR)); + drawLogo(i, X, Y, false, true, false, false, false, false); + delay(50); + drawLogo(i, X, Y, false, false, true, false, false, false); + delay(50); + drawLogo(i, X, Y, false, true, false, false, false, false); + delay(50); + drawLogo(i, X, Y, false, true, true, false, false, false); + delay(50); + drawLogo(i, X, Y, false, true, true, true, false, false); + delay(50); + drawLogo(i, X, Y, false, true, true, false, true, false); + delay(50); + drawLogo(i, X, Y, false, true, true, true, true, false); + delay(50); + drawLogo(i, X, Y, true, true, true, true, true, false); } -void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circle2, bool circle3, bool line1, bool line2, bool name) -{ - int circle1T = logoSize / 15; - int circle2T = logoSize / 25; - int circle3T = logoSize / 30; +void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circle2, bool circle3, bool line1, bool line2, bool name) { + int circle1T = logoSize / 15; + int circle2T = logoSize / 25; + int circle3T = logoSize / 30; - int circle3Y = circle1Y - (logoSize * 1.2); - int circle3X = circle1X - (logoSize * 0.13); - int circle2X = circle1X - (logoSize * 1.05); - int circle2Y = circle1Y - (logoSize * 0.8); + int circle3Y = circle1Y - (logoSize * 1.2); + int circle3X = circle1X - (logoSize * 0.13); + int circle2X = circle1X - (logoSize * 1.05); + int circle2Y = circle1Y - (logoSize * 0.8); - if (line1) - { - M5.Lcd.drawLine(circle1X - 2, circle1Y, circle2X - 2, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X - 1, circle1Y, circle2X - 1, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X, circle1Y, circle2X, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X + 1, circle1Y, circle2X + 1, circle2Y, BLUE); - M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, BLUE); - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE); - } - if (line2) - { - M5.Lcd.drawLine(circle1X - 2, circle1Y, circle3X - 2, circle3Y, BLUE); - M5.Lcd.drawLine(circle1X - 1, circle1Y, circle3X - 1, circle3Y, BLUE); - M5.Lcd.drawLine(circle1X, circle1Y, circle3X, circle3Y, BLUE); - M5.Lcd.drawLine(circle1X + 1, circle1Y, circle3X + 1, circle3Y, BLUE); - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE); - } + if (line1) { + M5.Lcd.drawLine(circle1X - 2, circle1Y, circle2X - 2, circle2Y, BLUE); + M5.Lcd.drawLine(circle1X - 1, circle1Y, circle2X - 1, circle2Y, BLUE); + M5.Lcd.drawLine(circle1X, circle1Y, circle2X, circle2Y, BLUE); + M5.Lcd.drawLine(circle1X + 1, circle1Y, circle2X + 1, circle2Y, BLUE); + M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, BLUE); + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE); + } + if (line2) { + M5.Lcd.drawLine(circle1X - 2, circle1Y, circle3X - 2, circle3Y, BLUE); + M5.Lcd.drawLine(circle1X - 1, circle1Y, circle3X - 1, circle3Y, BLUE); + M5.Lcd.drawLine(circle1X, circle1Y, circle3X, circle3Y, BLUE); + M5.Lcd.drawLine(circle1X + 1, circle1Y, circle3X + 1, circle3Y, BLUE); + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE); + } + M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE); + if (circle1) { + M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2, WHITE); + M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T, TFT_GREEN); M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE); - if (circle1) - { - M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2, WHITE); - M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T, TFT_GREEN); - M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE); - } - if (circle2) - { - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3, WHITE); - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T, TFT_ORANGE); - M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE); - } - if (circle3) - { - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4, WHITE); - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T, TFT_PINK); - M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE); - } - if (name) - { - M5.Lcd.setTextColor(BLUE); - M5.Lcd.drawString("penMQTTGateway", circle1X + (circle1X * 0.27), circle1Y, (M5.Lcd.height() > 200) ? 4:2); - } + } + if (circle2) { + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3, WHITE); + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T, TFT_ORANGE); + M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE); + } + if (circle3) { + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4, WHITE); + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T, TFT_PINK); + M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE); + } + if (name) { + M5.Lcd.setTextColor(BLUE); + M5.Lcd.drawString("penMQTTGateway", circle1X + (circle1X * 0.27), circle1Y, (M5.Lcd.height() > 200) ? 4 : 2); + } } -void M5Display(char * line1, char * line2, char * line3) -{ - if (low_power_mode == 2) digitalWrite(LOW_POWER_LED, 1 - LOW_POWER_LED_OFF); - wakeScreen(NORMAL_LCD_BRIGHTNESS); - M5.Lcd.fillScreen(TFT_WHITE); - drawLogo(M5.Lcd.width() * 0.1875, (M5.Lcd.width()/2) - M5.Lcd.width() * 0.24, M5.Lcd.height() * 0.5, true, true, true, true, true, true); - M5.Lcd.setTextColor(BLUE); - M5.Lcd.drawString(line1, 5, M5.Lcd.height() * 0.7, 1); - M5.Lcd.drawString(line2, 5, M5.Lcd.height() * 0.8, 1); - M5.Lcd.drawString(line3, 5, M5.Lcd.height() * 0.9, 1); - delay(2000); - digitalWrite(LOW_POWER_LED, LOW_POWER_LED_OFF); // to switch off no need of condition +void M5Display(char* line1, char* line2, char* line3) { + if (low_power_mode == 2) digitalWrite(LOW_POWER_LED, 1 - LOW_POWER_LED_OFF); + wakeScreen(NORMAL_LCD_BRIGHTNESS); + M5.Lcd.fillScreen(TFT_WHITE); + drawLogo(M5.Lcd.width() * 0.1875, (M5.Lcd.width() / 2) - M5.Lcd.width() * 0.24, M5.Lcd.height() * 0.5, true, true, true, true, true, true); + M5.Lcd.setTextColor(BLUE); + M5.Lcd.drawString(line1, 5, M5.Lcd.height() * 0.7, 1); + M5.Lcd.drawString(line2, 5, M5.Lcd.height() * 0.8, 1); + M5.Lcd.drawString(line3, 5, M5.Lcd.height() * 0.9, 1); + delay(2000); + digitalWrite(LOW_POWER_LED, LOW_POWER_LED_OFF); // to switch off no need of condition } #endif diff --git a/main/Zgateway2G.ino b/main/Zgateway2G.ino index aa4c8e50..a7417bfc 100644 --- a/main/Zgateway2G.ino +++ b/main/Zgateway2G.ino @@ -29,8 +29,8 @@ #ifdef Zgateway2G -#include -#include // library for controling A6 or A7 module +# include // library for controling A6 or A7 module +# include // Instantiate the library with TxPin, RxPin. A6lib A6l(_2G_TX_PIN, _2G_RX_PIN); //D6 to A6 RX, D7 to A6 TX @@ -39,16 +39,14 @@ int unreadSMSLocs[50] = {0}; int unreadSMSNum = 0; SMSmessage sms; -void setup2G() -{ +void setup2G() { Log.notice(F("_2G_TX_PIN: %d " CR), _2G_TX_PIN); Log.notice(F("_2G_RX_PIN: %d " CR), _2G_RX_PIN); setupGSM(false); Log.trace(F("Zgateway2G setup done " CR)); } -void setupGSM(bool deleteSMS) -{ +void setupGSM(bool deleteSMS) { Log.trace(F("Init 2G module: %d" CR), _2G_PWR_PIN); delay(1000); // Power-cycle the module to reset it. @@ -59,45 +57,37 @@ void setupGSM(bool deleteSMS) signalStrengthAnalysis(); delay(1000); // deleting all sms - if (deleteSMS) - { - if (A6l.deleteSMS(1, 4) == A6_OK) - { + if (deleteSMS) { + if (A6l.deleteSMS(1, 4) == A6_OK) { Log.notice(F("delete SMS OK" CR)); - } - else - { + } else { Log.error(F("delete SMS KO" CR)); } } } -void signalStrengthAnalysis() -{ +void signalStrengthAnalysis() { int signalStrength = 0; signalStrength = A6l.getSignalStrength(); Log.trace(F("Signal strength: %d" CR), signalStrength); - if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL) - { + if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL) { Log.trace(F("Signal too low restart the module" CR)); setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module } } -bool _2GtoMQTT() -{ +bool _2GtoMQTT() { // Get the memory locations of unread SMS messages. unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512); Log.trace(F("Creating SMS buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &SMSdata = jsonBuffer.createObject(); - for (int i = 0; i < unreadSMSNum; i++) - { + JsonObject& SMSdata = jsonBuffer.createObject(); + for (int i = 0; i < unreadSMSNum; i++) { Log.notice(F("New message at index: %d" CR), unreadSMSNum); sms = A6l.readSMS(unreadSMSLocs[i]); - SMSdata.set("message", (char *)sms.message.c_str()); - SMSdata.set("date", (char *)sms.date.c_str()); - SMSdata.set("phone", (char *)sms.number.c_str()); + SMSdata.set("message", (char*)sms.message.c_str()); + SMSdata.set("date", (char*)sms.date.c_str()); + SMSdata.set("phone", (char*)sms.number.c_str()); A6l.deleteSMS(unreadSMSLocs[i]); // we delete the SMS received Log.trace(F("Adv data 2GtoMQTT" CR)); pub(subject2GtoMQTT, SMSdata); @@ -105,76 +95,58 @@ bool _2GtoMQTT() } return false; } -#ifdef simpleReceiving -void MQTTto2G(char *topicOri, char *datacallback) -{ - +# ifdef simpleReceiving +void MQTTto2G(char* topicOri, char* datacallback) { String data = datacallback; String topic = topicOri; - if (cmpToMainTopic(topicOri, subjectMQTTto2G)) - { + if (cmpToMainTopic(topicOri, subjectMQTTto2G)) { Log.trace(F("MQTTto2G data analysis" CR)); // 2G DATA ANALYSIS String phone_number = ""; int pos0 = topic.lastIndexOf(_2GPhoneKey); - if (pos0 != -1) - { + if (pos0 != -1) { pos0 = pos0 + strlen(_2GPhoneKey); phone_number = topic.substring(pos0); - Log.notice(F("MQTTto2G phone: %s" CR),(char *)phone_number.c_str()); - Log.notice(F("MQTTto2G sms: %s" CR),(char *)data.c_str()); - if (A6l.sendSMS(phone_number, data) == A6_OK) - { + Log.notice(F("MQTTto2G phone: %s" CR), (char*)phone_number.c_str()); + Log.notice(F("MQTTto2G sms: %s" CR), (char*)data.c_str()); + if (A6l.sendSMS(phone_number, data) == A6_OK) { Log.notice(F("SMS OK" CR)); // Acknowledgement to the GTW2G topic pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } - else - { + } else { Log.error(F("SMS KO" CR)); // Acknowledgement to the GTW2G topic pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also } - } - else - { + } else { Log.error(F("MQTTto2G Fail reading phone number" CR)); } } } -#endif +# endif -#ifdef jsonReceiving -void MQTTto2G(char *topicOri, JsonObject &SMSdata) -{ - - if (cmpToMainTopic(topicOri, subjectMQTTto2G)) - { - const char *sms = SMSdata["message"]; - const char *phone = SMSdata["phone"]; +# ifdef jsonReceiving +void MQTTto2G(char* topicOri, JsonObject& SMSdata) { + if (cmpToMainTopic(topicOri, subjectMQTTto2G)) { + const char* sms = SMSdata["message"]; + const char* phone = SMSdata["phone"]; Log.trace(F("MQTTto2G json data analysis" CR)); - if (sms && phone) - { - Log.notice(F("MQTTto2G phone: %s" CR),phone); - Log.notice(F("MQTTto2G sms: %s" CR),sms); - if (A6l.sendSMS(String(phone), String(sms)) == A6_OK) - { + if (sms && phone) { + Log.notice(F("MQTTto2G phone: %s" CR), phone); + Log.notice(F("MQTTto2G sms: %s" CR), sms); + if (A6l.sendSMS(String(phone), String(sms)) == A6_OK) { Log.notice(F("SMS OK" CR)); // Acknowledgement to the GTW2G topic pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } - else - { + } else { Log.error(F("SMS KO" CR)); pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also } - } - else - { + } else { Log.error(F("MQTTto2G failed json read" CR)); } } } -#endif +# endif #endif diff --git a/main/ZgatewayBT.ino b/main/ZgatewayBT.ino index 1b4bdb8e..b28689fb 100644 --- a/main/ZgatewayBT.ino +++ b/main/ZgatewayBT.ino @@ -31,67 +31,61 @@ Thanks to wolass https://github.com/wolass for suggesting me HM 10 and dinosd ht #include "User_config.h" #ifdef ESP32 -#include "FreeRTOS.h" +# include "FreeRTOS.h" FreeRTOS::Semaphore semaphoreCreateOrUpdateDevice = FreeRTOS::Semaphore("createOrUpdateDevice"); - // Headers used for deep sleep functions - #include - #include - #include - #include +// Headers used for deep sleep functions +# include +# include +# include +# include #endif #ifdef ZgatewayBT -#include +# include using namespace std; vector devices; -static BLEdevice NO_DEVICE_FOUND = { {0,0,0,0,0,0,0,0,0,0,0,0}, false, false, false }; +static BLEdevice NO_DEVICE_FOUND = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false, false, false}; static bool oneWhite = false; +BLEdevice* getDeviceByMac(const char* mac); -BLEdevice * getDeviceByMac(const char *mac) -{ +BLEdevice* getDeviceByMac(const char* mac) { Log.trace(F("getDeviceByMac %s" CR), mac); - for (vector::iterator p = devices.begin(); p != devices.end(); ++p) - { - if ((strcmp(p->macAdr, mac) == 0)) - { + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) { + if ((strcmp(p->macAdr, mac) == 0)) { return &(*p); } } return &NO_DEVICE_FOUND; } -bool updateWorB(JsonObject &BTdata, bool isWhite) -{ +bool updateWorB(JsonObject& BTdata, bool isWhite) { Log.trace(F("update WorB" CR)); const char* jsonKey = isWhite ? "white-list" : "black-list"; int size = BTdata[jsonKey].size(); - if (size == 0) + if (size == 0) return false; - for (int i = 0; i < size; i++) - { - const char *mac = BTdata[jsonKey][i]; + for (int i = 0; i < size; i++) { + const char* mac = BTdata[jsonKey][i]; createOrUpdateDevice(mac, (isWhite ? device_flags_isWhiteL : device_flags_isBlackL)); } - + return true; } -void createOrUpdateDevice(const char *mac, uint8_t flags) -{ -#ifdef ESP32 +void createOrUpdateDevice(const char* mac, uint8_t flags) { +# ifdef ESP32 if (!semaphoreCreateOrUpdateDevice.take(30000, "createOrUpdateDevice")) return; -#endif +# endif - BLEdevice *device = getDeviceByMac(mac); - if(device == &NO_DEVICE_FOUND) - { + BLEdevice* device = getDeviceByMac(mac); + if (device == &NO_DEVICE_FOUND) { Log.trace(F("add %s" CR), mac); //new device device = new BLEdevice(); @@ -100,18 +94,14 @@ void createOrUpdateDevice(const char *mac, uint8_t flags) device->isWhtL = flags & device_flags_isWhiteL; device->isBlkL = flags & device_flags_isBlackL; devices.push_back(*device); - } - else - { + } else { Log.trace(F("update %s" CR), mac); - - if(flags & device_flags_isDisc) - { + + if (flags & device_flags_isDisc) { device->isDisc = true; } - if(flags & device_flags_isWhiteL || flags & device_flags_isBlackL) - { + if (flags & device_flags_isWhiteL || flags & device_flags_isBlackL) { device->isWhtL = flags & device_flags_isWhiteL; device->isBlkL = flags & device_flags_isBlackL; } @@ -120,38 +110,34 @@ void createOrUpdateDevice(const char *mac, uint8_t flags) // update oneWhite flag oneWhite = oneWhite || device->isWhtL; -#ifdef ESP32 +# ifdef ESP32 semaphoreCreateOrUpdateDevice.give(); -#endif +# endif } -#define isWhite(device) device->isWhtL -#define isBlack(device) device->isBlkL -#define isDiscovered(device) device->isDisc +# define isWhite(device) device->isWhtL +# define isBlack(device) device->isBlkL +# define isDiscovered(device) device->isDisc -void dumpDevices() -{ - for (vector::iterator p = devices.begin(); p != devices.end(); ++p) - { - Log.trace(F("macAdr %s" CR),p->macAdr); - Log.trace(F("isDisc %d" CR),p->isDisc); - Log.trace(F("isWhtL %d" CR),p->isWhtL); - Log.trace(F("isBlkL %d" CR),p->isBlkL); +void dumpDevices() { + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) { + Log.trace(F("macAdr %s" CR), p->macAdr); + Log.trace(F("isDisc %d" CR), p->isDisc); + Log.trace(F("isWhtL %d" CR), p->isWhtL); + Log.trace(F("isBlkL %d" CR), p->isBlkL); } } -void strupp(char *beg) -{ +void strupp(char* beg) { while (*beg = toupper(*beg)) ++beg; } -#ifdef ZmqttDiscovery -void MiFloraDiscovery(char *mac) -{ -#define MiFloraparametersCount 4 +# ifdef ZmqttDiscovery +void MiFloraDiscovery(char* mac) { +# define MiFloraparametersCount 4 Log.trace(F("MiFloraDiscovery" CR)); - char *MiFlorasensor[MiFloraparametersCount][8] = { + char* MiFlorasensor[MiFloraparametersCount][8] = { {"sensor", "MiFlora-lux", mac, "illuminance", jsonLux, "", "", "lu"}, {"sensor", "MiFlora-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "MiFlora-fer", mac, "", jsonFer, "", "", "µS/cm"}, @@ -163,42 +149,39 @@ void MiFloraDiscovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void VegTrugDiscovery(char *mac) -{ -#define VegTrugparametersCount 4 +void VegTrugDiscovery(char* mac) { +# define VegTrugparametersCount 4 Log.trace(F("VegTrugDiscovery" CR)); - char *VegTrugsensor[VegTrugparametersCount][8] = { + char* VegTrugsensor[VegTrugparametersCount][8] = { {"sensor", "VegTrug-lux", mac, "illuminance", jsonLux, "", "", "lu"}, {"sensor", "VegTrug-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "VegTrug-fer", mac, "", jsonFer, "", "", "µS/cm"}, {"sensor", "VegTrug-moi", mac, "", jsonMoi, "", "", "%"} //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - + createDiscoveryFromList(mac, VegTrugsensor, VegTrugparametersCount); createOrUpdateDevice(mac, device_flags_isDisc); } -void MiJiaDiscovery(char *mac) -{ -#define MiJiaparametersCount 3 +void MiJiaDiscovery(char* mac) { +# define MiJiaparametersCount 3 Log.trace(F("MiJiaDiscovery" CR)); - char *MiJiasensor[MiJiaparametersCount][8] = { + char* MiJiasensor[MiJiaparametersCount][8] = { {"sensor", "MiJia-batt", mac, "battery", jsonBatt, "", "", "%"}, {"sensor", "MiJia-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "MiJia-hum", mac, "humidity", jsonHum, "", "", "%"} //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - + createDiscoveryFromList(mac, MiJiasensor, MiJiaparametersCount); createOrUpdateDevice(mac, device_flags_isDisc); } -void LYWSD02Discovery(char *mac) -{ -#define LYWSD02parametersCount 3 +void LYWSD02Discovery(char* mac) { +# define LYWSD02parametersCount 3 Log.trace(F("LYWSD02Discovery" CR)); - char *LYWSD02sensor[LYWSD02parametersCount][8] = { + char* LYWSD02sensor[LYWSD02parametersCount][8] = { {"sensor", "LYWSD02-batt", mac, "battery", jsonBatt, "", "", "V"}, {"sensor", "LYWSD02-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "LYWSD02-hum", mac, "humidity", jsonHum, "", "", "%"} @@ -209,11 +192,10 @@ void LYWSD02Discovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void CLEARGRASSTRHDiscovery(char *mac) -{ -#define CLEARGRASSTRHparametersCount 3 +void CLEARGRASSTRHDiscovery(char* mac) { +# define CLEARGRASSTRHparametersCount 3 Log.trace(F("CLEARGRASSTRHDiscovery" CR)); - char *CLEARGRASSTRHsensor[CLEARGRASSTRHparametersCount][8] = { + char* CLEARGRASSTRHsensor[CLEARGRASSTRHparametersCount][8] = { {"sensor", "CLEARGRASSTRH-batt", mac, "battery", jsonBatt, "", "", "V"}, {"sensor", "CLEARGRASSTRH-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "CLEARGRASSTRH-hum", mac, "humidity", jsonHum, "", "", "%"} @@ -224,11 +206,10 @@ void CLEARGRASSTRHDiscovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void CLEARGRASSCGD1Discovery(char *mac) -{ -#define CLEARGRASSCGD1parametersCount 3 +void CLEARGRASSCGD1Discovery(char* mac) { +# define CLEARGRASSCGD1parametersCount 3 Log.trace(F("CLEARGRASSCGD1Discovery" CR)); - char *CLEARGRASSCGD1sensor[CLEARGRASSCGD1parametersCount][8] = { + char* CLEARGRASSCGD1sensor[CLEARGRASSCGD1parametersCount][8] = { {"sensor", "CLEARGRASSCGD1-batt", mac, "battery", jsonBatt, "", "", "V"}, {"sensor", "CLEARGRASSCGD1-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "CLEARGRASSCGD1-hum", mac, "humidity", jsonHum, "", "", "%"} @@ -239,11 +220,10 @@ void CLEARGRASSCGD1Discovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void CLEARGRASSTRHKPADiscovery(char *mac) -{ -#define CLEARGRASSTRHKPAparametersCount 3 +void CLEARGRASSTRHKPADiscovery(char* mac) { +# define CLEARGRASSTRHKPAparametersCount 3 Log.trace(F("CLEARGRASSTRHKPADiscovery" CR)); - char *CLEARGRASSTRHKPAsensor[CLEARGRASSTRHKPAparametersCount][8] = { + char* CLEARGRASSTRHKPAsensor[CLEARGRASSTRHKPAparametersCount][8] = { {"sensor", "CLEARGRASSTRHKPA-pres", mac, "pressure", jsonPres, "", "", "kPa"}, {"sensor", "CLEARGRASSTRHKPA-tem", mac, "temperature", jsonTemp, "", "", "°C"}, {"sensor", "CLEARGRASSTRHKPA-hum", mac, "humidity", jsonHum, "", "", "%"} @@ -254,11 +234,10 @@ void CLEARGRASSTRHKPADiscovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void MiScaleDiscovery(char *mac) -{ -#define MiScaleparametersCount 1 +void MiScaleDiscovery(char* mac) { +# define MiScaleparametersCount 1 Log.trace(F("MiScaleDiscovery" CR)); - char *MiScalesensor[MiScaleparametersCount][8] = { + char* MiScalesensor[MiScaleparametersCount][8] = { {"sensor", "MiScale-weight", mac, "", jsonWeight, "", "", "kg"}, //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; @@ -267,11 +246,10 @@ void MiScaleDiscovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void MiLampDiscovery(char *mac) -{ -#define MiLampparametersCount 1 +void MiLampDiscovery(char* mac) { +# define MiLampparametersCount 1 Log.trace(F("MiLampDiscovery" CR)); - char *MiLampsensor[MiLampparametersCount][8] = { + char* MiLampsensor[MiLampparametersCount][8] = { {"sensor", "MiLamp-presence", mac, "", jsonPresence, "", "", "d"}, //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; @@ -280,11 +258,10 @@ void MiLampDiscovery(char *mac) createOrUpdateDevice(mac, device_flags_isDisc); } -void MiBandDiscovery(char *mac) -{ -#define MiBandparametersCount 1 +void MiBandDiscovery(char* mac) { +# define MiBandparametersCount 1 Log.trace(F("MiBandDiscovery" CR)); - char *MiBandsensor[MiBandparametersCount][8] = { + char* MiBandsensor[MiBandparametersCount][8] = { {"sensor", "MiBand-steps", mac, "", jsonStep, "", "", "nb"}, //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; @@ -292,87 +269,80 @@ void MiBandDiscovery(char *mac) createDiscoveryFromList(mac, MiBandsensor, MiBandparametersCount); createOrUpdateDevice(mac, device_flags_isDisc); } -#else -void MiFloraDiscovery(char *mac){} -void VegTrugDiscovery(char *mac){} -void MiJiaDiscovery(char *mac){} -void LYWSD02Discovery(char *mac){} -void CLEARGRASSTRHDiscovery(char *mac){} -void CLEARGRASSCGD1Discovery(char *mac){} -void CLEARGRASSTRHKPADiscovery(char *mac){} -void MiScaleDiscovery(char *mac){} -void MiLampDiscovery(char *mac){} -void MiBandDiscovery(char *mac){} -#endif +# else +void MiFloraDiscovery(char* mac) {} +void VegTrugDiscovery(char* mac) {} +void MiJiaDiscovery(char* mac) {} +void LYWSD02Discovery(char* mac) {} +void CLEARGRASSTRHDiscovery(char* mac) {} +void CLEARGRASSCGD1Discovery(char* mac) {} +void CLEARGRASSTRHKPADiscovery(char* mac) {} +void MiScaleDiscovery(char* mac) {} +void MiLampDiscovery(char* mac) {} +void MiBandDiscovery(char* mac) {} +# endif -#ifdef ESP32 +# ifdef ESP32 /* Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp Ported to Arduino ESP32 by Evandro Copercini */ // core task implementation thanks to https://techtutorialsx.com/2017/05/09/esp32-running-code-on-a-specific-core/ -#include -#include -#include -#include -#include "soc/timer_group_struct.h" -#include "soc/timer_group_reg.h" +# include +# include +# include +# include + +# include "soc/timer_group_reg.h" +# include "soc/timer_group_struct.h" //core on which the BLE detection task will run static int taskCore = 0; -class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks -{ - void onResult(BLEAdvertisedDevice advertisedDevice) - { +class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks { + void onResult(BLEAdvertisedDevice advertisedDevice) { Log.trace(F("Creating BLE buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &BLEdata = jsonBuffer.createObject(); + JsonObject& BLEdata = jsonBuffer.createObject(); String mac_adress = advertisedDevice.getAddress().toString().c_str(); mac_adress.toUpperCase(); - BLEdata.set("id", (char *)mac_adress.c_str()); + BLEdata.set("id", (char*)mac_adress.c_str()); mac_adress.replace(":", ""); String mactopic = subjectBTtoMQTT + String("/") + mac_adress; char mac[mac_adress.length() + 1]; mac_adress.toCharArray(mac, mac_adress.length() + 1); Log.notice(F("Device detected: %s" CR), mac); - BLEdevice *device = getDeviceByMac(mac); + BLEdevice* device = getDeviceByMac(mac); - if ((!oneWhite || isWhite(device)) && !isBlack(device)) - { //if not black listed mac we go AND if we have no white mac or this mac is white we go out + if ((!oneWhite || isWhite(device)) && !isBlack(device)) { //if not black listed mac we go AND if we have no white mac or this mac is white we go out if (advertisedDevice.haveName()) - BLEdata.set("name", (char *)advertisedDevice.getName().c_str()); - #if pubBLEManufacturerData - if (advertisedDevice.haveManufacturerData()) - { + BLEdata.set("name", (char*)advertisedDevice.getName().c_str()); +# if pubBLEManufacturerData + if (advertisedDevice.haveManufacturerData()) { char* manufacturerdata = BLEUtils::buildHexData(NULL, (uint8_t*)advertisedDevice.getManufacturerData().data(), advertisedDevice.getManufacturerData().length()); Log.trace(F("Manufacturer Data: %s" CR), manufacturerdata); BLEdata.set("manufacturerdata", manufacturerdata); } - #endif +# endif if (advertisedDevice.haveRSSI()) BLEdata.set("rssi", (int)advertisedDevice.getRSSI()); if (advertisedDevice.haveTXPower()) BLEdata.set("txpower", (int8_t)advertisedDevice.getTXPower()); - #ifdef subjectHomePresence +# ifdef subjectHomePresence if (advertisedDevice.haveRSSI()) haRoomPresence(BLEdata); // this device has an rssi in consequence we can use it for home assistant room presence component - #endif - if (advertisedDevice.haveServiceData()) - { +# endif + if (advertisedDevice.haveServiceData()) { int serviceDataCount = advertisedDevice.getServiceDataCount(); Log.trace(F("Get services data number: %d" CR), serviceDataCount); - for (int j = 0; j < serviceDataCount; j++) - { + for (int j = 0; j < serviceDataCount; j++) { std::string serviceData = advertisedDevice.getServiceData(j); int serviceDataLength = serviceData.length(); String returnedString = ""; - for (int i = 0; i < serviceDataLength; i++) - { + for (int i = 0; i < serviceDataLength; i++) { int a = serviceData[i]; - if (a < 16) - { + if (a < 16) { returnedString = returnedString + "0"; } returnedString = returnedString + String(a, HEX); @@ -383,31 +353,26 @@ class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks Log.trace(F("Service data: %s" CR), service_data); BLEdata.set("servicedata", service_data); std::string serviceDatauuid = advertisedDevice.getServiceDataUUID(j).toString(); - Log.trace(F("Service data UUID: %s" CR), (char *)serviceDatauuid.c_str()); - BLEdata.set("servicedatauuid", (char *)serviceDatauuid.c_str()); + Log.trace(F("Service data UUID: %s" CR), (char*)serviceDatauuid.c_str()); + BLEdata.set("servicedatauuid", (char*)serviceDatauuid.c_str()); PublishDeviceData(BLEdata); } - } - else - { + } else { PublishDeviceData(BLEdata); // publish device even if there is no service data } - } - else - { + } else { Log.trace(F("Filtered mac device" CR)); } } }; -void BLEscan() -{ +void BLEscan() { TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_feed = 1; TIMERG0.wdt_wprotect = 0; Log.notice(F("Scan begin" CR)); BLEDevice::init(""); - BLEScan *pBLEScan = BLEDevice::getScan(); //create new scan + BLEScan* pBLEScan = BLEDevice::getScan(); //create new scan MyAdvertisedDeviceCallbacks myCallbacks; pBLEScan->setAdvertisedDeviceCallbacks(&myCallbacks); pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster @@ -416,27 +381,21 @@ void BLEscan() esp_bt_controller_deinit(); } -void coreTask(void *pvParameters) -{ - while (true) - { +void coreTask(void* pvParameters) { + while (true) { Log.trace(F("BT Task running on core: %d" CR), xPortGetCoreID()); if (!low_power_mode) delay(BLEinterval); int n = 0; - while (client.state() != 0 && n <= TimeBeforeMQTTconnect) - { + while (client.state() != 0 && n <= TimeBeforeMQTTconnect) { n++; Log.trace(F("Wait for MQTT on core: %d attempt: %d" CR), xPortGetCoreID(), n); delay(1000); } - if(client.state() != 0 ) - { + if (client.state() != 0) { Log.warning(F("MQTT client disconnected no BLE scan" CR)); delay(1000); - } - else - { + } else { pinMode(LOW_POWER_LED, OUTPUT); if (low_power_mode == 2) digitalWrite(LOW_POWER_LED, 1 - LOW_POWER_LED_OFF); @@ -445,7 +404,7 @@ void coreTask(void *pvParameters) if (low_power_mode) digitalWrite(LOW_POWER_LED, LOW_POWER_LED_OFF); } - if(low_power_mode) + if (low_power_mode) lowPowerESP32(); } } @@ -456,12 +415,11 @@ void lowPowerESP32() // low power mode deepSleep(BLEinterval * 1000); } -void deepSleep(uint64_t time_in_us) -{ - #if defined(ZboardM5STACK) || defined(ZboardM5STICKC) +void deepSleep(uint64_t time_in_us) { +# if defined(ZboardM5STACK) || defined(ZboardM5STICKC) sleepScreen(); esp_sleep_enable_ext0_wakeup((gpio_num_t)SLEEP_BUTTON, LOW); - #endif +# endif Log.trace(F("Deactivating ESP32 components" CR)); esp_wifi_stop(); @@ -475,56 +433,52 @@ void deepSleep(uint64_t time_in_us) esp_deep_sleep(time_in_us); } -void changelow_power_mode(int newLowPowerMode) -{ +void changelow_power_mode(int newLowPowerMode) { Log.notice(F("Changing LOW POWER mode to: %d" CR), newLowPowerMode); - #if defined(ZboardM5STACK) || defined(ZboardM5STICKC) - if (low_power_mode == 2) - { - #ifdef ZboardM5STACK +# if defined(ZboardM5STACK) || defined(ZboardM5STICKC) + if (low_power_mode == 2) { +# ifdef ZboardM5STACK M5.Lcd.wakeup(); - #endif - #ifdef ZboardM5STICKC +# endif +# ifdef ZboardM5STICKC M5.Axp.SetLDO2(true); M5.Lcd.begin(); - #endif +# endif } char lpm[2]; sprintf(lpm, "%d", newLowPowerMode); M5Display("Changing LOW POWER mode to:", lpm, ""); - #endif +# endif low_power_mode = newLowPowerMode; preferences.begin(Gateway_Short_Name, false); preferences.putUInt("low_power_mode", low_power_mode); preferences.end(); } -void setupBT() -{ +void setupBT() { Log.notice(F("BLEinterval: %d" CR), BLEinterval); Log.notice(F("Minrssi: %d" CR), Minrssi); Log.notice(F("Low Power Mode: %d" CR), low_power_mode); // we setup a task with priority one to avoid conflict with other gateways xTaskCreatePinnedToCore( - coreTask, /* Function to implement the task */ + coreTask, /* Function to implement the task */ "coreTask", /* Name of the task */ - 10000, /* Stack size in words */ - NULL, /* Task input parameter */ - 1, /* Priority of the task */ - NULL, /* Task handle. */ - taskCore); /* Core where the task should run */ + 10000, /* Stack size in words */ + NULL, /* Task input parameter */ + 1, /* Priority of the task */ + NULL, /* Task handle. */ + taskCore); /* Core where the task should run */ Log.trace(F("ZgatewayBT multicore ESP32 setup done " CR)); } -bool BTtoMQTT() -{ // for on demand BLE scans +bool BTtoMQTT() { // for on demand BLE scans BLEscan(); } -#else // arduino or ESP8266 working with HM10/11 +# else // arduino or ESP8266 working with HM10/11 -#include -#define QUESTION_MSG "AT+DISA?" +# include +# define QUESTION_MSG "AT+DISA?" SoftwareSerial softserial(BT_RX, BT_TX); @@ -534,8 +488,7 @@ unsigned long timebt = 0; // this struct define which parts of the hexadecimal chain we extract and what to do with these parts struct decompose d[6] = {{"mac", 16, 12, true}, {"typ", 28, 2, false}, {"rsi", 30, 2, false}, {"rdl", 32, 2, false}, {"sty", 44, 4, true}, {"rda", 56, 60, false}}; -void setupBT() -{ +void setupBT() { BLEinterval = TimeBtw_Read; Minrssi = MinimumRSSI; Log.notice(F("BLEinterval: %d" CR), BLEinterval); @@ -547,50 +500,42 @@ void setupBT() delay(100); softserial.print(F("AT+RESET" CR)); delay(100); - #ifdef HM_BLUE_LED_STOP +# ifdef HM_BLUE_LED_STOP softserial.print(F("AT+PIO11" CR)); // When not connected (as in BLE mode) the LED is off. When connected the LED is solid on. - #endif +# endif delay(100); Log.trace(F("ZgatewayBT HM1X setup done " CR)); } -bool BTtoMQTT() -{ +bool BTtoMQTT() { //extract serial data from module in hexa format - while (softserial.available() > 0) - { + while (softserial.available() > 0) { int a = softserial.read(); - if (a < 16) - { + if (a < 16) { returnedString = returnedString + "0"; } returnedString = returnedString + String(a, HEX); } - if (millis() > (timebt + BLEinterval)) - { //retrieving data + if (millis() > (timebt + BLEinterval)) { //retrieving data timebt = millis(); - #if defined(ESP8266) +# if defined(ESP8266) yield(); - #endif - if (returnedString != "") - { - Log.verbose(F("returnedString: %s" CR), (char *)returnedString.c_str()); +# endif + if (returnedString != "") { + Log.verbose(F("returnedString: %s" CR), (char*)returnedString.c_str()); size_t pos = 0; - while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1) - { - #if defined(ESP8266) + while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1) { +# if defined(ESP8266) yield(); - #endif +# endif String token = returnedString.substring(pos); returnedString.remove(pos, returnedString.length()); char token_char[token.length() + 1]; token.toCharArray(token_char, token.length() + 1); Log.trace(F("Token: %s" CR), token_char); - if (token.length() > 60) - { // we extract data only if we have infos (BLEdelimiter length + 4) - for (int i = 0; i < 6; i++) - { + if (token.length() > 60) { // we extract data only if we have infos (BLEdelimiter length + 4) + for (int i = 0; i < 6; i++) { extract_char(token_char, d[i].extract, d[i].start, d[i].len, d[i].reverse, false); if (i == 3) d[5].len = (int)strtol(d[i].extract, NULL, 16) * 2; // extracting the length of the rest data @@ -600,31 +545,30 @@ bool BTtoMQTT() { Log.trace(F("Creating BLE buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &BLEdata = jsonBuffer.createObject(); + JsonObject& BLEdata = jsonBuffer.createObject(); strupp(d[0].extract); - BLEdevice *device = getDeviceByMac(d[0].extract); + BLEdevice* device = getDeviceByMac(d[0].extract); if (isBlack(device)) return false; //if black listed mac we go out if (oneWhite && !isWhite(device)) return false; //if we have at least one white mac and this mac is not white we go out - #ifdef subjectHomePresence +# ifdef subjectHomePresence String HomePresenceId; - for (int i = 0; i < 12; i++) - { + for (int i = 0; i < 12; i++) { HomePresenceId += String(d[0].extract[i]); if (((i - 1) % 2 == 0) && (i != 11)) HomePresenceId += ":"; } - Log.trace(F("HomePresenceId %s" CR),(char *)HomePresenceId.c_str()); - BLEdata.set("id", (char *)HomePresenceId.c_str()); - #endif + Log.trace(F("HomePresenceId %s" CR), (char*)HomePresenceId.c_str()); + BLEdata.set("id", (char*)HomePresenceId.c_str()); +# endif int rssi = (int)strtol(d[2].extract, NULL, 16) - 256; BLEdata.set("rssi", (int)rssi); - #ifdef subjectHomePresence +# ifdef subjectHomePresence haRoomPresence(BLEdata); // this device has an rssi in consequence we can use it for home assistant room presence component - #endif +# endif Log.trace(F("Service data: %s" CR), d[5].extract); BLEdata.set("servicedata", d[5].extract); PublishDeviceData(BLEdata); @@ -636,24 +580,20 @@ bool BTtoMQTT() } softserial.print(F(QUESTION_MSG)); return false; - } - else - { + } else { return false; } } -#endif +# endif -void RemoveJsonPropertyIf(JsonObject &obj, char* key, bool condition) -{ - if(condition){ - Log.trace(F("Removing %s" CR), key); - obj.remove(key); +void RemoveJsonPropertyIf(JsonObject& obj, char* key, bool condition) { + if (condition) { + Log.trace(F("Removing %s" CR), key); + obj.remove(key); } } -double value_from_service_data(const char *service_data, int offset, int data_length) -{ +double value_from_service_data(const char* service_data, int offset, int data_length) { char rev_data[data_length + 1]; char data[data_length + 1]; memcpy(rev_data, &service_data[offset], data_length); @@ -664,214 +604,187 @@ double value_from_service_data(const char *service_data, int offset, int data_le double value = strtol(data, NULL, 16); if (value > 65000 && data_length <= 4) value = value - 65535; - Log.trace(F("value %D" CR),value); + Log.trace(F("value %D" CR), value); return value; } -boolean valid_service_data(const char * data) -{ +boolean valid_service_data(const char* data) { int size = strlen(data); for (int i = 0; i < size; ++i) { - if(data[i] != 48) // 48 correspond to 0 in ASCII table + if (data[i] != 48) // 48 correspond to 0 in ASCII table return true; } return false; } -void launch_discovery(JsonObject &BLEdata, char * mac){ - BLEdevice *device = getDeviceByMac(mac); - if (!isDiscovered(device) && BLEdata.containsKey("model")) - { +void launch_discovery(JsonObject& BLEdata, char* mac) { + BLEdevice* device = getDeviceByMac(mac); + if (!isDiscovered(device) && BLEdata.containsKey("model")) { Log.trace(F("Launching discovery of %s" CR), mac); - if(strcmp(BLEdata["model"].as(), "HHCCJCY01HHCC") == 0) MiFloraDiscovery(mac); - if(strcmp(BLEdata["model"].as(), "VegTrug") == 0) VegTrugDiscovery(mac); - if(strcmp(BLEdata["model"].as(), "LYWSDCGQ") == 0) MiJiaDiscovery(mac); - if(strcmp(BLEdata["model"].as(), "LYWSD02") == 0) LYWSD02Discovery(mac); - if(strcmp(BLEdata["model"].as(), "CGG1") == 0) CLEARGRASSTRHDiscovery(mac); - if(strcmp(BLEdata["model"].as(), "CGP1W") == 0) CLEARGRASSTRHKPADiscovery(mac); - if(strcmp(BLEdata["model"].as(), "MUE4094RT") == 0) MiLampDiscovery(mac); - if(strcmp(BLEdata["model"].as(), "CGD1") == 0) CLEARGRASSCGD1Discovery(mac); - if(strcmp(BLEdata["model"].as(), "MiBand") == 0) MiBandDiscovery(mac); - if(strcmp(BLEdata["model"].as(), "XMTZC04HM") == 0 || - strcmp(BLEdata["model"].as(), "XMTZC05HM") == 0) MiScaleDiscovery(mac); - } - else - { + if (strcmp(BLEdata["model"].as(), "HHCCJCY01HHCC") == 0) MiFloraDiscovery(mac); + if (strcmp(BLEdata["model"].as(), "VegTrug") == 0) VegTrugDiscovery(mac); + if (strcmp(BLEdata["model"].as(), "LYWSDCGQ") == 0) MiJiaDiscovery(mac); + if (strcmp(BLEdata["model"].as(), "LYWSD02") == 0) LYWSD02Discovery(mac); + if (strcmp(BLEdata["model"].as(), "CGG1") == 0) CLEARGRASSTRHDiscovery(mac); + if (strcmp(BLEdata["model"].as(), "CGP1W") == 0) CLEARGRASSTRHKPADiscovery(mac); + if (strcmp(BLEdata["model"].as(), "MUE4094RT") == 0) MiLampDiscovery(mac); + if (strcmp(BLEdata["model"].as(), "CGD1") == 0) CLEARGRASSCGD1Discovery(mac); + if (strcmp(BLEdata["model"].as(), "MiBand") == 0) MiBandDiscovery(mac); + if (strcmp(BLEdata["model"].as(), "XMTZC04HM") == 0 || + strcmp(BLEdata["model"].as(), "XMTZC05HM") == 0) MiScaleDiscovery(mac); + } else { Log.trace(F("Device already discovered or model not detected" CR)); } } -void PublishDeviceData(JsonObject &BLEdata) -{ - if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi)) - { // process only the devices close enough - JsonObject &BLEdataOut = process_bledata(BLEdata); +void PublishDeviceData(JsonObject& BLEdata) { + if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi)) { // process only the devices close enough + JsonObject& BLEdataOut = process_bledata(BLEdata); String mac_adress = BLEdataOut["id"].as(); mac_adress.replace(":", ""); char mac[mac_adress.length() + 1]; mac_adress.toCharArray(mac, mac_adress.length() + 1); - #ifdef ZmqttDiscovery - launch_discovery(BLEdataOut, mac); - #endif - #if !pubBLEServiceUUID - RemoveJsonPropertyIf(BLEdataOut, "servicedatauuid", BLEdataOut.containsKey("servicedatauuid")); - #endif - #if !pubKnownBLEServiceData - RemoveJsonPropertyIf(BLEdataOut, "servicedata", BLEdataOut.containsKey("model") && BLEdataOut.containsKey("servicedata")); - #endif +# ifdef ZmqttDiscovery + launch_discovery(BLEdataOut, mac); +# endif +# if !pubBLEServiceUUID + RemoveJsonPropertyIf(BLEdataOut, "servicedatauuid", BLEdataOut.containsKey("servicedatauuid")); +# endif +# if !pubKnownBLEServiceData + RemoveJsonPropertyIf(BLEdataOut, "servicedata", BLEdataOut.containsKey("model") && BLEdataOut.containsKey("servicedata")); +# endif String mactopic(mac); mactopic = subjectBTtoMQTT + String("/") + mactopic; - pub((char *)mactopic.c_str(), BLEdataOut); - } - else - { + pub((char*)mactopic.c_str(), BLEdataOut); + } else { Log.trace(F("Low rssi, device filtered" CR)); } } -JsonObject& process_bledata(JsonObject &BLEdata){ - if(BLEdata.containsKey("servicedata")) - { +JsonObject& process_bledata(JsonObject& BLEdata) { + if (BLEdata.containsKey("servicedata")) { Log.trace(F("Checking BLE service data validity" CR)); - const char * service_data = (const char *)(BLEdata["servicedata"]|""); - if(valid_service_data(service_data)) - { + const char* service_data = (const char*)(BLEdata["servicedata"] | ""); + if (valid_service_data(service_data)) { Log.trace(F("Searching BLE device data %s size %d" CR), service_data, strlen(service_data)); Log.trace(F("Is it a mi flora ?" CR)); - if (strstr(service_data, "209800") != NULL) - { + if (strstr(service_data, "209800") != NULL) { Log.trace(F("mi flora data reading" CR)); BLEdata.set("model", "HHCCJCY01HHCC"); return process_sensors(2, BLEdata); } Log.trace(F("Is it a vegtrug ?" CR)); - if (strstr(service_data, "20bc03") != NULL && strlen(service_data) > ServicedataMinLength) - { + if (strstr(service_data, "20bc03") != NULL && strlen(service_data) > ServicedataMinLength) { Log.trace(F("vegtrug data reading" CR)); BLEdata.set("model", "VegTrug"); return process_sensors(2, BLEdata); } Log.trace(F("Is it a LYWSDCGQ?" CR)); - if (strstr(service_data, "20aa01") != NULL && strlen(service_data) > ServicedataMinLength) - { + if (strstr(service_data, "20aa01") != NULL && strlen(service_data) > ServicedataMinLength) { Log.trace(F("LYWSDCGQ data reading" CR)); BLEdata.set("model", "LYWSDCGQ"); return process_sensors(0, BLEdata); } Log.trace(F("Is it a LYWSD02?" CR)); - if (strstr(service_data, "205b04") != NULL && strlen(service_data) > ServicedataMinLength) - { + if (strstr(service_data, "205b04") != NULL && strlen(service_data) > ServicedataMinLength) { Log.trace(F("LYWSD02 data reading" CR)); BLEdata.set("model", "LYWSD02"); return process_sensors(2, BLEdata); } Log.trace(F("Is it a CGG1?" CR)); - if (strstr(service_data, "304703") != NULL && strlen(service_data) > ServicedataMinLength) - { + if (strstr(service_data, "304703") != NULL && strlen(service_data) > ServicedataMinLength) { Log.trace(F("CGG1 data reading method 1" CR)); BLEdata.set("model", "CGG1"); return process_sensors(0, BLEdata); } Log.trace(F("Is it a MUE4094RT?" CR)); - if (strstr(service_data, "4030dd") != NULL) - { + if (strstr(service_data, "4030dd") != NULL) { Log.trace(F("MUE4094RT data reading" CR)); BLEdata.set("model", "MUE4094RT"); return process_milamp(BLEdata); } Log.trace(F("Is it a CGP1W?" CR)); - if (strstr(service_data, "08094c") != NULL && strlen(service_data) > ServicedataMinLength) - { + if (strstr(service_data, "08094c") != NULL && strlen(service_data) > ServicedataMinLength) { Log.trace(F("CGP1W data reading" CR)); BLEdata.set("model", "CGP1W"); return process_cleargrass(BLEdata, true); } Log.trace(F("Is it a CGG1" CR)); - if (strstr(service_data, "080774") != NULL) - { + if (strstr(service_data, "080774") != NULL) { Log.trace(F("CGG1 method 2" CR)); BLEdata.set("model", "CGG1"); // no discovery as it is already available with method 1 return process_cleargrass(BLEdata, false); } Log.trace(F("Is it a CGD1?" CR)); - if ((strstr(service_data, "080caf") != NULL || strstr(service_data, "080c09") != NULL) - && (strlen(service_data) > ServicedataMinLength)) - { + if ((strstr(service_data, "080caf") != NULL || strstr(service_data, "080c09") != NULL) && (strlen(service_data) > ServicedataMinLength)) { Log.trace(F("CGD1 data reading" CR)); BLEdata.set("model", "CGD1"); return process_cleargrass(BLEdata, false); } - if(BLEdata.containsKey("servicedatauuid")) - { - const char * service_datauuid = (const char *)(BLEdata["servicedatauuid"]|""); + if (BLEdata.containsKey("servicedatauuid")) { + const char* service_datauuid = (const char*)(BLEdata["servicedatauuid"] | ""); Log.trace(F("servicedatauuid %s" CR), service_datauuid); Log.trace(F("Is it a MiBand?" CR)); - if (strstr(service_datauuid, "fee0") != NULL) - { + if (strstr(service_datauuid, "fee0") != NULL) { Log.trace(F("Mi Band data reading" CR)); BLEdata.set("model", "MiBand"); return process_miband(BLEdata); } Log.trace(F("Is it a XMTZC04HM?" CR)); - if (strstr(service_datauuid, "181d") != NULL) - { + if (strstr(service_datauuid, "181d") != NULL) { Log.trace(F("XMTZC04HM data reading" CR)); BLEdata.set("model", "XMTZC04HM"); return process_scale_v1(BLEdata); } Log.trace(F("Is it a XMTZC05HM?" CR)); - if (strstr(service_datauuid, "181b") != NULL) - { + if (strstr(service_datauuid, "181b") != NULL) { Log.trace(F("XMTZC05HM data reading" CR)); - BLEdata.set("model", "XMTZC05HM");; + BLEdata.set("model", "XMTZC05HM"); + ; return process_scale_v2(BLEdata); } } - } - else - { + } else { Log.trace(F("Non valid service data, removing it" CR)); BLEdata.remove("servicedata"); } - #if !pubUnknownBLEServiceData - Log.trace(F("Unknown service data, removing it" CR)); - BLEdata.remove("servicedata"); - #endif +# if !pubUnknownBLEServiceData + Log.trace(F("Unknown service data, removing it" CR)); + BLEdata.remove("servicedata"); +# endif } return BLEdata; } -JsonObject& process_sensors(int offset, JsonObject &BLEdata) -{ - const char * servicedata = BLEdata["servicedata"].as(); +JsonObject& process_sensors(int offset, JsonObject& BLEdata) { + const char* servicedata = BLEdata["servicedata"].as(); int data_length = 0; - - switch (servicedata[27 + offset]) - { - case '1': - case '2': - case '3': - case '4': - data_length = ((servicedata[27 + offset] - '0') * 2); - Log.trace(F("Valid data_length: %d" CR), data_length); - break; - default: - Log.trace(F("Invalid data_length, not enriching the device data" CR)); - return BLEdata; + + switch (servicedata[27 + offset]) { + case '1': + case '2': + case '3': + case '4': + data_length = ((servicedata[27 + offset] - '0') * 2); + Log.trace(F("Valid data_length: %d" CR), data_length); + break; + default: + Log.trace(F("Invalid data_length, not enriching the device data" CR)); + return BLEdata; } double value = 9999; @@ -880,44 +793,42 @@ JsonObject& process_sensors(int offset, JsonObject &BLEdata) // Mi flora provides tem(perature), (earth) moi(sture), fer(tility) and lux (illuminance) // Mi Jia provides tem(perature), batt(erry) and hum(idity) // following the value of digit 23 + offset we determine the type of data we get from the sensor - switch (servicedata[23 + offset]) - { - case '9': - BLEdata.set("fer", (double)value); - break; - case '4': - BLEdata.set("tem", (double)value / 10); - break; - case '6': - BLEdata.set("hum", (double)value / 10); - break; - case '7': - BLEdata.set("lux", (double)value); - break; - case '8': - BLEdata.set("moi", (double)value); - break; - case 'a': - BLEdata.set("batt", (double)value); - break; - case 'd': - // humidity - value = value_from_service_data(servicedata, 28 + offset, 4); - BLEdata.set("tem", (double)value / 10); - // temperature - value = value_from_service_data(servicedata, 32 + offset, 4); - BLEdata.set("hum", (double)value / 10); - break; - default: - Log.trace(F("can't read values" CR)); + switch (servicedata[23 + offset]) { + case '9': + BLEdata.set("fer", (double)value); + break; + case '4': + BLEdata.set("tem", (double)value / 10); + break; + case '6': + BLEdata.set("hum", (double)value / 10); + break; + case '7': + BLEdata.set("lux", (double)value); + break; + case '8': + BLEdata.set("moi", (double)value); + break; + case 'a': + BLEdata.set("batt", (double)value); + break; + case 'd': + // humidity + value = value_from_service_data(servicedata, 28 + offset, 4); + BLEdata.set("tem", (double)value / 10); + // temperature + value = value_from_service_data(servicedata, 32 + offset, 4); + BLEdata.set("hum", (double)value / 10); + break; + default: + Log.trace(F("can't read values" CR)); } return BLEdata; } -JsonObject& process_scale_v1(JsonObject &BLEdata) -{ - const char * servicedata = BLEdata["servicedata"].as(); +JsonObject& process_scale_v1(JsonObject& BLEdata) { + const char* servicedata = BLEdata["servicedata"].as(); double weight = value_from_service_data(servicedata, 2, 4) / 200; @@ -927,9 +838,8 @@ JsonObject& process_scale_v1(JsonObject &BLEdata) return BLEdata; } -JsonObject& process_scale_v2(JsonObject &BLEdata) -{ - const char * servicedata = BLEdata["servicedata"].as(); +JsonObject& process_scale_v2(JsonObject& BLEdata) { + const char* servicedata = BLEdata["servicedata"].as(); double weight = value_from_service_data(servicedata, 22, 4) / 200; double impedance = value_from_service_data(servicedata, 18, 4); @@ -941,9 +851,8 @@ JsonObject& process_scale_v2(JsonObject &BLEdata) return BLEdata; } -JsonObject& process_miband(JsonObject &BLEdata) -{ - const char * servicedata = BLEdata["servicedata"].as(); +JsonObject& process_miband(JsonObject& BLEdata) { + const char* servicedata = BLEdata["servicedata"].as(); double steps = value_from_service_data(servicedata, 0, 4); @@ -953,9 +862,8 @@ JsonObject& process_miband(JsonObject &BLEdata) return BLEdata; } -JsonObject& process_milamp(JsonObject &BLEdata) -{ - const char * servicedata = BLEdata["servicedata"].as(); +JsonObject& process_milamp(JsonObject& BLEdata) { + const char* servicedata = BLEdata["servicedata"].as(); long darkness = value_from_service_data(servicedata, 8, 2); @@ -966,9 +874,8 @@ JsonObject& process_milamp(JsonObject &BLEdata) return BLEdata; } -JsonObject& process_cleargrass(JsonObject &BLEdata, boolean air) -{ - const char * servicedata = BLEdata["servicedata"].as(); +JsonObject& process_cleargrass(JsonObject& BLEdata, boolean air) { + const char* servicedata = BLEdata["servicedata"].as(); double value = 9999; // humidity @@ -977,8 +884,7 @@ JsonObject& process_cleargrass(JsonObject &BLEdata, boolean air) // temperature value = value_from_service_data(servicedata, 24, 4); BLEdata.set("hum", (double)value / 10); - if (air) - { + if (air) { // air pressure value = value_from_service_data(servicedata, 32, 4); BLEdata.set("pres", (double)value / 100); @@ -987,36 +893,30 @@ JsonObject& process_cleargrass(JsonObject &BLEdata, boolean air) return BLEdata; } -#ifdef subjectHomePresence -void haRoomPresence(JsonObject &HomePresence) -{ +# ifdef subjectHomePresence +void haRoomPresence(JsonObject& HomePresence) { int BLErssi = HomePresence["rssi"]; Log.trace(F("BLErssi %d" CR), BLErssi); int txPower = HomePresence["txpower"] | 0; if (txPower >= 0) txPower = -59; //if tx power is not found we set a default calibration value - Log.trace(F("TxPower: %d" CR),txPower); + Log.trace(F("TxPower: %d" CR), txPower); double ratio = BLErssi * 1.0 / txPower; double distance; - if (ratio < 1.0) - { + if (ratio < 1.0) { distance = pow(ratio, 10); - } - else - { + } else { distance = (0.89976) * pow(ratio, 7.7095) + 0.111; } HomePresence["distance"] = distance; - Log.trace(F("Ble distance %D" CR),distance); + Log.trace(F("Ble distance %D" CR), distance); String topic = String(Base_Topic) + "home_presence/" + String(gateway_name); - pub_custom_topic((char *)topic.c_str(), HomePresence, false); + pub_custom_topic((char*)topic.c_str(), HomePresence, false); } -#endif +# endif -void MQTTtoBT(char *topicOri, JsonObject &BTdata) -{ // json object decoding - if (cmpToMainTopic(topicOri, subjectMQTTtoBTset)) - { +void MQTTtoBT(char* topicOri, JsonObject& BTdata) { // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoBTset)) { Log.trace(F("MQTTtoBT json set" CR)); // Black list & white list set @@ -1028,8 +928,7 @@ void MQTTtoBT(char *topicOri, JsonObject &BTdata) dumpDevices(); // Scan interval set - if (BTdata.containsKey("interval")) - { + if (BTdata.containsKey("interval")) { Log.trace(F("BLE interval setup" CR)); // storing BLE interval for further use if needed unsigned int prevBLEinterval = BLEinterval; @@ -1037,28 +936,25 @@ void MQTTtoBT(char *topicOri, JsonObject &BTdata) // set BLE interval if present if not setting default value BLEinterval = (unsigned int)BTdata["interval"]; Log.notice(F("New interval: %d ms" CR), BLEinterval); - if (BLEinterval == 0) - { + if (BLEinterval == 0) { if (BTtoMQTT()) // as BLEinterval is = to 0 we can launch the loop and the scan will execute immediately Log.trace(F("Scan done" CR)); BLEinterval = prevBLEinterval; // as 0 was just used as a command we recover previous scan duration } } // MinRSSI set - if (BTdata.containsKey("minrssi")) - { + if (BTdata.containsKey("minrssi")) { // storing Min RSSI for further use if needed Log.trace(F("Previous Minrssi: %d" CR), Minrssi); // set Min RSSI if present if not setting default value Minrssi = (unsigned int)BTdata["minrssi"]; Log.notice(F("New Minrssi: %d" CR), Minrssi); } - #ifdef ESP32 - if (BTdata.containsKey("low_power_mode")) - { +# ifdef ESP32 + if (BTdata.containsKey("low_power_mode")) { changelow_power_mode((int)BTdata["low_power_mode"]); } - #endif +# endif } } -#endif \ No newline at end of file +#endif diff --git a/main/ZgatewayIR.ino b/main/ZgatewayIR.ino index ce82ebde..7bfa1cce 100644 --- a/main/ZgatewayIR.ino +++ b/main/ZgatewayIR.ino @@ -29,54 +29,54 @@ #ifdef ZgatewayIR -#if defined(ESP8266) || defined(ESP32) -#include -#include // Needed if you want to send IR commands. -#include // Needed if you want to receive IR commands. -#include -#ifdef DumpMode // in dump mode we increase the size of the buffer to catch big codes +# if defined(ESP8266) || defined(ESP32) +# include // Needed if you want to receive IR commands. +# include +# include // Needed if you want to send IR commands. +# include +# ifdef DumpMode // in dump mode we increase the size of the buffer to catch big codes IRrecv irrecv(IR_RECEIVER_PIN, 1024, 15U, true); -#else +# else IRrecv irrecv(IR_RECEIVER_PIN); -#endif +# endif IRsend irsend(IR_EMITTER_PIN); -#else -#include +# else +# include IRrecv irrecv(IR_RECEIVER_PIN); IRsend irsend; //connect IR emitter pin to D9 on arduino, you need to comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library IRremote.h so as to free pin D3 for RF RECEIVER PIN -#endif +# endif // IR protocol bits definition for Arduino (for ESP9266 they are defined in IRRemoteESP8266.h) -#ifndef NEC_BITS -#define NEC_BITS 32U -#endif -#ifndef SAMSUNG_BITS -#define SAMSUNG_BITS 32U -#endif -#ifndef SHARP_BITS -#define SHARP_ADDRESS_BITS 5U -#define SHARP_COMMAND_BITS 8U -#define SHARP_BITS (SHARP_ADDRESS_BITS + SHARP_COMMAND_BITS + 2) // 15U -#endif -#ifndef RC5_BITS -#define RC5_RAW_BITS 14U -#define RC5_BITS RC5_RAW_BITS - 2U -#endif -#ifndef DISH_BITS -#define DISH_BITS 16U -#endif -#ifndef SONY_12_BITS -#define SONY_12_BITS 12U -#endif -#ifndef LG_BITS -#define LG_BITS 28U -#endif -#ifndef WHYNTER_BITS -#define WHYNTER_BITS 32U -#endif +# ifndef NEC_BITS +# define NEC_BITS 32U +# endif +# ifndef SAMSUNG_BITS +# define SAMSUNG_BITS 32U +# endif +# ifndef SHARP_BITS +# define SHARP_ADDRESS_BITS 5U +# define SHARP_COMMAND_BITS 8U +# define SHARP_BITS (SHARP_ADDRESS_BITS + SHARP_COMMAND_BITS + 2) // 15U +# endif +# ifndef RC5_BITS +# define RC5_RAW_BITS 14U +# define RC5_BITS RC5_RAW_BITS - 2U +# endif +# ifndef DISH_BITS +# define DISH_BITS 16U +# endif +# ifndef SONY_12_BITS +# define SONY_12_BITS 12U +# endif +# ifndef LG_BITS +# define LG_BITS 28U +# endif +# ifndef WHYNTER_BITS +# define WHYNTER_BITS 32U +# endif // The function below comes from IRMQTTServer.INO on IRremoteESP8266 project from @crankyoldgit -uint64_t getUInt64fromHex(char const *str) { +uint64_t getUInt64fromHex(char const* str) { uint64_t result = 0; uint16_t offset = 0; // Skip any leading '0x' or '0X' prefix. @@ -85,21 +85,20 @@ uint64_t getUInt64fromHex(char const *str) { char c = str[offset]; result *= 16; if (isdigit(c)) - result += c - '0'; // '0' .. '9' + result += c - '0'; // '0' .. '9' else if (isupper(c)) - result += c - 'A' + 10; // 'A' .. 'F' + result += c - 'A' + 10; // 'A' .. 'F' else - result += c - 'a' + 10; // 'a' .. 'f' + result += c - 'a' + 10; // 'a' .. 'f' } return result; } -void setupIR() -{ +void setupIR() { //IR init parameters -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.begin(); -#endif +# endif irrecv.enableIRIn(); // Start the receiver @@ -108,79 +107,70 @@ void setupIR() Log.trace(F("ZgatewayIR setup done " CR)); } -void IRtoMQTT() -{ +void IRtoMQTT() { decode_results results; - if (irrecv.decode(&results)) - { + if (irrecv.decode(&results)) { Log.trace(F("Creating IR buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &IRdata = jsonBuffer.createObject(); + JsonObject& IRdata = jsonBuffer.createObject(); Log.trace(F("Rcv. IR" CR)); -#ifdef ESP32 +# ifdef ESP32 String taskMessage = "Task running on core "; taskMessage = taskMessage + xPortGetCoreID(); //trc(taskMessage); -#endif +# endif IRdata.set("value", (unsigned long long)(results.value)); IRdata.set("protocol", (int)(results.decode_type)); IRdata.set("bits", (int)(results.bits)); -#if defined(ESP8266) || defined(ESP32) //resultToHexidecimal is only available with IRremoteESP8266 +# if defined(ESP8266) || defined(ESP32) //resultToHexidecimal is only available with IRremoteESP8266 String hex = resultToHexidecimal(&results); - IRdata.set("hex", (char *)hex.c_str()); - IRdata.set("protocol_name", (char *)(typeToString(results.decode_type, false)).c_str()); -#endif + IRdata.set("hex", (char*)hex.c_str()); + IRdata.set("protocol_name", (char*)(typeToString(results.decode_type, false)).c_str()); +# endif String rawCode = ""; // Dump data - for (uint16_t i = 1; i < results.rawlen; i++) - { -#if defined(ESP8266) || defined(ESP32) + for (uint16_t i = 1; i < results.rawlen; i++) { +# if defined(ESP8266) || defined(ESP32) if (i % 100 == 0) yield(); // Preemptive yield every 100th entry to feed the WDT. rawCode = rawCode + (results.rawbuf[i] * RAWTICK); -#else +# else rawCode = rawCode + (results.rawbuf[i] * USECPERTICK); -#endif +# endif if (i < results.rawlen - 1) rawCode = rawCode + ","; // ',' not needed on last one } //trc(rawCode); IRdata.set("raw", rawCode); // if needed we directly resend the raw code -#ifdef RawDirectForward -#if defined(ESP8266) || defined(ESP32) +# ifdef RawDirectForward +# if defined(ESP8266) || defined(ESP32) uint16_t rawsend[results.rawlen]; - for (uint16_t i = 1; i < results.rawlen; i++) - { + for (uint16_t i = 1; i < results.rawlen; i++) { if (i % 100 == 0) yield(); // Preemptive yield every 100th entry to feed the WDT. -#else +# else unsigned int rawsend[results.rawlen]; - for (int i = 1; i < results.rawlen; i++) - { -#endif + for (int i = 1; i < results.rawlen; i++) { +# endif rawsend[i] = results.rawbuf[i]; } irsend.sendRaw(rawsend, results.rawlen, RawFrequency); Log.trace(F("raw redirected" CR)); -#endif +# endif irrecv.resume(); // Receive the next value unsigned long long MQTTvalue = IRdata.get("value"); //trc(MQTTvalue); - if ((pubIRunknownPrtcl == false && IRdata.get("protocol") == -1)) - { // don't publish unknown IR protocol + if ((pubIRunknownPrtcl == false && IRdata.get("protocol") == -1)) { // don't publish unknown IR protocol Log.notice(F("--no pub unknwn prt--" CR)); - } - else if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) - { // conditions to avoid duplications of IR -->MQTT + } else if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of IR -->MQTT Log.trace(F("Adv data IRtoMQTT" CR)); pub(subjectIRtoMQTT, IRdata); Log.trace(F("Store val: %D" CR), MQTTvalue); storeValue(MQTTvalue); - if (repeatIRwMQTT) - { + if (repeatIRwMQTT) { Log.trace(F("Pub. IR for rpt" CR)); pubMQTT(subjectMQTTtoIR, MQTTvalue); } @@ -188,57 +178,46 @@ void IRtoMQTT() } } -#ifdef jsonReceiving -void MQTTtoIR(char *topicOri, JsonObject &IRdata) -{ - - if (cmpToMainTopic(topicOri, subjectMQTTtoIR)) - { +# ifdef jsonReceiving +void MQTTtoIR(char* topicOri, JsonObject& IRdata) { + if (cmpToMainTopic(topicOri, subjectMQTTtoIR)) { Log.trace(F("MQTTtoIR json" CR)); uint64_t data = IRdata["value"]; - const char *raw = IRdata["raw"]; - const char *hex = IRdata["hex"]; - if (hex) {// we privilegiate the hex usage over the value one (less risk of error) + const char* raw = IRdata["raw"]; + const char* hex = IRdata["hex"]; + if (hex) { // we privilegiate the hex usage over the value one (less risk of error) Log.trace(F("hex: %s" CR), hex); data = getUInt64fromHex(hex); } - if (data != 0 || raw) - { + if (data != 0 || raw) { Log.trace(F("MQTTtoIR value || raw detected" CR)); bool signalSent = false; - const char *protocol_name = IRdata["protocol_name"]; + const char* protocol_name = IRdata["protocol_name"]; unsigned int valueBITS = IRdata["bits"] | 0; uint16_t valueRPT = IRdata["repeat"] | repeatIRwNumber; - if (raw) - { + if (raw) { Log.trace(F("Raw: %s" CR), raw); unsigned int s = strlen(raw); //number of "," value count int count = 0; - for (int i = 0; i < s; i++) - { - if (raw[i] == ',') - { + for (int i = 0; i < s; i++) { + if (raw[i] == ',') { count++; } } -#ifdef IR_GC - if (strcmp(protocol_name, "GC") == 1) - { // sending GC data from https://irdb.globalcache.com +# ifdef IR_GC + if (strcmp(protocol_name, "GC") == 1) { // sending GC data from https://irdb.globalcache.com Log.trace(F("GC" CR)); //buffer allocation from char datacallback uint16_t GC[count + 1]; String value = ""; int j = 0; - for (int i = 0; i < s; i++) - { - if (raw[i] != ',') - { + for (int i = 0; i < s; i++) { + if (raw[i] != ',') { value = value + String(raw[i]); } - if ((raw[i] == ',') || (i == s - 1)) - { + if ((raw[i] == ',') || (i == s - 1)) { GC[j] = value.toInt(); value = ""; j++; @@ -247,27 +226,23 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata) irsend.sendGC(GC, j); signalSent = true; } -#endif -#ifdef IR_RAW - if (strcmp(protocol_name, "Raw") == 1) - { // sending Raw data +# endif +# ifdef IR_RAW + if (strcmp(protocol_name, "Raw") == 1) { // sending Raw data Log.trace(F("Raw" CR)); //buffer allocation from char datacallback -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) uint16_t Raw[count + 1]; -#else +# else unsigned int Raw[count + 1]; -#endif +# endif String value = ""; int j = 0; - for (int i = 0; i < s; i++) - { - if (raw[i] != ',') - { + for (int i = 0; i < s; i++) { + if (raw[i] != ',') { value = value + String(raw[i]); } - if ((raw[i] == ',') || (i == s - 1)) - { + if ((raw[i] == ',') || (i == s - 1)) { Raw[j] = value.toInt(); value = ""; j++; @@ -276,213 +251,192 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata) irsend.sendRaw(Raw, j, RawFrequency); signalSent = true; } -#endif - } - else if (protocol_name && (strcmp(protocol_name, "NEC") != 1)) - { +# endif + } else if (protocol_name && (strcmp(protocol_name, "NEC") != 1)) { Log.trace(F("Using Identified Protocol: %s bits: %d repeat: %d" CR), protocol_name, valueBITS, valueRPT); signalSent = sendIdentifiedProtocol(protocol_name, data, hex, valueBITS, valueRPT); - } - else - { + } else { Log.trace(F("Using NEC protocol" CR)); Log.notice(F("Sending IR signal with %s"), protocol_name); - if (valueBITS == 0) + if (valueBITS == 0) valueBITS = NEC_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendNEC(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendNEC(data, valueBITS); -#endif +# endif signalSent = true; } - if (signalSent) - { // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also + if (signalSent) { // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also Log.notice(F("MQTTtoIR OK" CR)); pub(subjectGTWIRtoMQTT, IRdata); } irrecv.enableIRIn(); // ReStart the IR receiver (if not restarted it is not able to receive data) - } - else - { + } else { Log.error(F("MQTTtoIR failed json read" CR)); } } } -#endif +# endif - -bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, const char *hex, unsigned int valueBITS, uint16_t valueRPT) -{ +bool sendIdentifiedProtocol(const char* protocol_name, unsigned long long data, const char* hex, unsigned int valueBITS, uint16_t valueRPT) { uint8_t dataarray[valueBITS]; - if(hex) - { - const char *ptr = NULL; + if (hex) { + const char* ptr = NULL; (strstr(hex, "0x") != NULL) ? ptr = hex += 2 : ptr = hex; - for (int i = 0; i < sizeof dataarray/sizeof *dataarray; i++) { - sscanf(ptr, "%2hhx", &dataarray[i]); - ptr += 2; + for (int i = 0; i < sizeof dataarray / sizeof *dataarray; i++) { + sscanf(ptr, "%2hhx", &dataarray[i]); + ptr += 2; } for (int i = 0; i < valueBITS; i++) { - Log.trace(F("%x"), dataarray[i]); + Log.trace(F("%x"), dataarray[i]); } } -#ifdef IR_WHYNTER - if (strcmp(protocol_name, "WHYNTER") == 1) - { +# ifdef IR_WHYNTER + if (strcmp(protocol_name, "WHYNTER") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = WHYNTER_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendWhynter(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendWhynter(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_LG - if (strcmp(protocol_name, "LG") == 1) - { +# endif +# ifdef IR_LG + if (strcmp(protocol_name, "LG") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = LG_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendLG(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendLG(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_SONY - if (strcmp(protocol_name, "SONY") == 1) - { +# endif +# ifdef IR_SONY + if (strcmp(protocol_name, "SONY") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = SONY_12_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendSony(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendSony(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_DISH - if (strcmp(protocol_name, "DISH") == 1) - { +# endif +# ifdef IR_DISH + if (strcmp(protocol_name, "DISH") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = DISH_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendDISH(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendDISH(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_RC5 - if (strcmp(protocol_name, "RC5") == 1) - { +# endif +# ifdef IR_RC5 + if (strcmp(protocol_name, "RC5") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = RC5_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendRC5(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendRC5(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_RC6 - if (strcmp(protocol_name, "RC6") == 1) - { +# endif +# ifdef IR_RC6 + if (strcmp(protocol_name, "RC6") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = RC6_MODE0_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendRC6(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendRC6(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_SHARP - if (strcmp(protocol_name, "SHARP") == 1) - { +# endif +# ifdef IR_SHARP + if (strcmp(protocol_name, "SHARP") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = SHARP_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendSharpRaw(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendSharpRaw(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_SAMSUNG - if (strcmp(protocol_name, "SAMSUNG") == 1) - { +# endif +# ifdef IR_SAMSUNG + if (strcmp(protocol_name, "SAMSUNG") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = SAMSUNG_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendSAMSUNG(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendSAMSUNG(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_JVC - if (strcmp(protocol_name, "JVC") == 1) - { +# endif +# ifdef IR_JVC + if (strcmp(protocol_name, "JVC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = JVC_BITS; -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) irsend.sendJVC(data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendJVC(data, valueBITS); -#endif +# endif return true; } -#endif -#ifdef IR_PANASONIC - if (strcmp(protocol_name, "PANASONIC") == 1) - { -#if defined(ESP8266) || defined(ESP32) +# endif +# ifdef IR_PANASONIC + if (strcmp(protocol_name, "PANASONIC") == 1) { +# if defined(ESP8266) || defined(ESP32) Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = PANASONIC_BITS; irsend.sendPanasonic(PanasonicAddress, data, valueBITS, valueRPT); -#else +# else for (int i = 0; i <= valueRPT; i++) irsend.sendPanasonic(PanasonicAddress, data); -#endif +# endif return true; } -#endif +# endif -#if defined(ESP8266) || defined(ESP32) -#ifdef IR_COOLIX - if (strcmp(protocol_name, "COOLIX") == 1) - { +# if defined(ESP8266) || defined(ESP32) +# ifdef IR_COOLIX + if (strcmp(protocol_name, "COOLIX") == 1) { Log.trace(F("Sending %s:" CR), protocol_name); Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) @@ -492,10 +446,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendCOOLIX(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_RCMM - if (strcmp(protocol_name, "RCMM") == 1) - { +# endif +# ifdef IR_RCMM + if (strcmp(protocol_name, "RCMM") == 1) { Log.trace(F("Sending %s:" CR), protocol_name); Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) @@ -503,20 +456,18 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendRCMM(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DENON - if (strcmp(protocol_name, "DENON") == 1) - { +# endif +# ifdef IR_DENON + if (strcmp(protocol_name, "DENON") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = DENON_BITS; irsend.sendDenon(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_GICABLE - if (strcmp(protocol_name, "GICABLE") == 1) - { +# endif +# ifdef IR_GICABLE + if (strcmp(protocol_name, "GICABLE") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kGicableBits; @@ -525,10 +476,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendGICable(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_SHERWOOD - if (strcmp(protocol_name, "SHERWOOD") == 1) - { +# endif +# ifdef IR_SHERWOOD + if (strcmp(protocol_name, "SHERWOOD") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kSherwoodBits; @@ -537,10 +487,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendSherwood(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHI - if (strcmp(protocol_name, "MITSUBISHI") == 1) - { +# endif +# ifdef IR_MITSUBISHI + if (strcmp(protocol_name, "MITSUBISHI") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishiBits; @@ -549,20 +498,18 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishi(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_NIKAI - if (strcmp(protocol_name, "NIKAI") == 1) - { +# endif +# ifdef IR_NIKAI + if (strcmp(protocol_name, "NIKAI") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kNikaiBits; irsend.sendNikai(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MIDEA - if (strcmp(protocol_name, "MIDEA") == 1) - { +# endif +# ifdef IR_MIDEA + if (strcmp(protocol_name, "MIDEA") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMideaBits; @@ -571,20 +518,18 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMidea(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MAGIQUEST - if (strcmp(protocol_name, "MAGIQUEST") == 1) - { +# endif +# ifdef IR_MAGIQUEST + if (strcmp(protocol_name, "MAGIQUEST") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMagiquestBits; irsend.sendMagiQuest(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_LASERTAG - if (strcmp(protocol_name, "LASERTAG") == 1) - { +# endif +# ifdef IR_LASERTAG + if (strcmp(protocol_name, "LASERTAG") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kLasertagBits; @@ -593,10 +538,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendLasertag(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_CARRIER_AC - if (strcmp(protocol_name, "CARRIER_AC") == 1) - { +# endif +# ifdef IR_CARRIER_AC + if (strcmp(protocol_name, "CARRIER_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kCarrierAcBits; @@ -605,10 +549,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendCarrierAC(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHI2 - if (strcmp(protocol_name, "MITSUBISHI2") == 1) - { +# endif +# ifdef IR_MITSUBISHI2 + if (strcmp(protocol_name, "MITSUBISHI2") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishiBits; @@ -617,10 +560,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishi2(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_AIWA_RC_T501 - if (strcmp(protocol_name, "AIWA_RC_T501") == 1) - { +# endif +# ifdef IR_AIWA_RC_T501 + if (strcmp(protocol_name, "AIWA_RC_T501") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kAiwaRcT501Bits; @@ -629,10 +571,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendAiwaRCT501(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN - if (strcmp(protocol_name, "DAIKIN") == 1) - { +# endif +# ifdef IR_DAIKIN + if (strcmp(protocol_name, "DAIKIN") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikinStateLength; @@ -641,10 +582,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_KELVINATOR - if (strcmp(protocol_name, "KELVINATOR") == 1) - { +# endif +# ifdef IR_KELVINATOR + if (strcmp(protocol_name, "KELVINATOR") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kKelvinatorStateLength; @@ -653,10 +593,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendKelvinator(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHI_AC - if (strcmp(protocol_name, "MITSUBISHI_AC") == 1) - { +# endif +# ifdef IR_MITSUBISHI_AC + if (strcmp(protocol_name, "MITSUBISHI_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishiACStateLength; @@ -665,20 +604,18 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishiAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_SANYO - if (strcmp(protocol_name, "SANYOLC7461") == 1) - { +# endif +# ifdef IR_SANYO + if (strcmp(protocol_name, "SANYOLC7461") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kSanyoLC7461Bits; irsend.sendSanyoLC7461(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_GREE - if (strcmp(protocol_name, "GREE") == 1) - { +# endif +# ifdef IR_GREE + if (strcmp(protocol_name, "GREE") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kGreeStateLength; @@ -687,10 +624,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendGree(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_ARGO - if (strcmp(protocol_name, "ARGO") == 1) - { +# endif +# ifdef IR_ARGO + if (strcmp(protocol_name, "ARGO") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kArgoStateLength; @@ -699,10 +635,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendArgo(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_TROTEC - if (strcmp(protocol_name, "TROTEC") == 1) - { +# endif +# ifdef IR_TROTEC + if (strcmp(protocol_name, "TROTEC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kTrotecStateLength; @@ -711,10 +646,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendTrotec(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_TOSHIBA_AC - if (strcmp(protocol_name, "TOSHIBA_AC") == 1) - { +# endif +# ifdef IR_TOSHIBA_AC + if (strcmp(protocol_name, "TOSHIBA_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kToshibaACBits; @@ -723,19 +657,17 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendToshibaAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_FUJITSU_AC - if (strcmp(protocol_name, "FUJITSU_AC") == 1) - { +# endif +# ifdef IR_FUJITSU_AC + if (strcmp(protocol_name, "FUJITSU_AC") == 1) { if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kFujitsuAcMinRepeat); irsend.sendFujitsuAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_HAIER_AC - if (strcmp(protocol_name, "HAIER_AC") == 1) - { +# endif +# ifdef IR_HAIER_AC + if (strcmp(protocol_name, "HAIER_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kHaierACStateLength; @@ -744,10 +676,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendHaierAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_HITACHI_AC - if (strcmp(protocol_name, "HITACHI_AC") == 1) - { +# endif +# ifdef IR_HITACHI_AC + if (strcmp(protocol_name, "HITACHI_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kHitachiAcStateLength; @@ -756,10 +687,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendHitachiAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_HITACHI_AC1 - if (strcmp(protocol_name, "HITACHI_AC1") == 1) - { +# endif +# ifdef IR_HITACHI_AC1 + if (strcmp(protocol_name, "HITACHI_AC1") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kHitachiAc1StateLength; @@ -768,10 +698,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendHitachiAC1(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_HITACHI_AC2 - if (strcmp(protocol_name, "HITACHI_AC2") == 1) - { +# endif +# ifdef IR_HITACHI_AC2 + if (strcmp(protocol_name, "HITACHI_AC2") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kHitachiAc2StateLength; @@ -780,10 +709,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendHitachiAC2(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_HAIER_AC_YRW02 - if (strcmp(protocol_name, "HAIER_AC_YRW02") == 1) - { +# endif +# ifdef IR_HAIER_AC_YRW02 + if (strcmp(protocol_name, "HAIER_AC_YRW02") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kHaierACYRW02StateLength; @@ -792,10 +720,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendHaierACYRW02(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_WHIRLPOOL_AC - if (strcmp(protocol_name, "WHIRLPOOL_AC") == 1) - { +# endif +# ifdef IR_WHIRLPOOL_AC + if (strcmp(protocol_name, "WHIRLPOOL_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kWhirlpoolAcStateLength; @@ -804,10 +731,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendWhirlpoolAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_SAMSUNG_AC - if (strcmp(protocol_name, "SAMSUNG_AC") == 1) - { +# endif +# ifdef IR_SAMSUNG_AC + if (strcmp(protocol_name, "SAMSUNG_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kSamsungAcStateLength; @@ -816,30 +742,27 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendSamsungAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_LUTRON - if (strcmp(protocol_name, "LUTRON") == 1) - { +# endif +# ifdef IR_LUTRON + if (strcmp(protocol_name, "LUTRON") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kLutronBits; irsend.sendLutron(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_ELECTRA_AC - if (strcmp(protocol_name, "ELECTRA_AC") == 1) - { +# endif +# ifdef IR_ELECTRA_AC + if (strcmp(protocol_name, "ELECTRA_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kElectraAcStateLength; irsend.sendElectraAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_PANASONIC_AC - if (strcmp(protocol_name, "PANASONIC_AC") == 1) - { +# endif +# ifdef IR_PANASONIC_AC + if (strcmp(protocol_name, "PANASONIC_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kPanasonicAcStateLength; @@ -848,37 +771,33 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendPanasonicAC(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_PIONEER - if (strcmp(protocol_name, "PIONEER") == 1) - { +# endif +# ifdef IR_PIONEER + if (strcmp(protocol_name, "PIONEER") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kPioneerBits; irsend.sendPioneer(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_LG2 - if (strcmp(protocol_name, "LG2") == 1) - { +# endif +# ifdef IR_LG2 + if (strcmp(protocol_name, "LG2") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kLgBits; irsend.sendLG2(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MWM - if (strcmp(protocol_name, "MWM") == 1) - { +# endif +# ifdef IR_MWM + if (strcmp(protocol_name, "MWM") == 1) { irsend.sendMWM(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN2 - if (strcmp(protocol_name, "DAIKIN2") == 1) - { +# endif +# ifdef IR_DAIKIN2 + if (strcmp(protocol_name, "DAIKIN2") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikin2StateLength; @@ -887,30 +806,27 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin2(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_VESTEL_AC - if (strcmp(protocol_name, "VESTEL_AC") == 1) - { +# endif +# ifdef IR_VESTEL_AC + if (strcmp(protocol_name, "VESTEL_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kVestelAcBits; irsend.sendVestelAc(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_SAMSUNG36 - if (strcmp(protocol_name, "SAMSUNG36") == 1) - { +# endif +# ifdef IR_SAMSUNG36 + if (strcmp(protocol_name, "SAMSUNG36") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kSamsung36Bits; irsend.sendSamsung36(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_TCL112AC - if (strcmp(protocol_name, "TCL112AC") == 1) - { +# endif +# ifdef IR_TCL112AC + if (strcmp(protocol_name, "TCL112AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kTcl112AcStateLength; @@ -919,20 +835,18 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendTcl112Ac(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_TECO - if (strcmp(protocol_name, "TECO") == 1) - { +# endif +# ifdef IR_TECO + if (strcmp(protocol_name, "TECO") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kTecoBits; irsend.sendTeco(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_LEGOPF - if (strcmp(protocol_name, "LEGOPF") == 1) - { +# endif +# ifdef IR_LEGOPF + if (strcmp(protocol_name, "LEGOPF") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kLegoPfBits; @@ -941,10 +855,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendLegoPf(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHIHEAVY88 - if (strcmp(protocol_name, "MITSUBISHIHEAVY88") == 1) - { +# endif +# ifdef IR_MITSUBISHIHEAVY88 + if (strcmp(protocol_name, "MITSUBISHIHEAVY88") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishiHeavy88StateLength; @@ -953,10 +866,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishiHeavy88(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHIHEAVY152 - if (strcmp(protocol_name, "MITSUBISHIHEAVY152") == 1) - { +# endif +# ifdef IR_MITSUBISHIHEAVY152 + if (strcmp(protocol_name, "MITSUBISHIHEAVY152") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishiHeavy152StateLength; @@ -965,10 +877,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishiHeavy152(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN216 - if (strcmp(protocol_name, "DAIKIN216") == 1) - { +# endif +# ifdef IR_DAIKIN216 + if (strcmp(protocol_name, "DAIKIN216") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikin216StateLength; @@ -977,10 +888,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin216(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_SHARP_AC - if (strcmp(protocol_name, "SHARP_AC") == 1) - { +# endif +# ifdef IR_SHARP_AC + if (strcmp(protocol_name, "SHARP_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kSharpAcStateLength; @@ -989,10 +899,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendSharpAc(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_GOODWEATHER - if (strcmp(protocol_name, "GOODWEATHER_AC") == 1) - { +# endif +# ifdef IR_GOODWEATHER + if (strcmp(protocol_name, "GOODWEATHER_AC") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kGoodweatherBits; @@ -1001,10 +910,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendGoodweather(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_INAX - if (strcmp(protocol_name, "INAX") == 1) - { +# endif +# ifdef IR_INAX + if (strcmp(protocol_name, "INAX") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kInaxBits; @@ -1013,10 +921,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendInax(data, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN160 - if (strcmp(protocol_name, "DAIKIN160") == 1) - { +# endif +# ifdef IR_DAIKIN160 + if (strcmp(protocol_name, "DAIKIN160") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikin160StateLength; @@ -1025,10 +932,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin160(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_NEOCLIMA - if (strcmp(protocol_name, "NEOCLIMA") == 1) - { +# endif +# ifdef IR_NEOCLIMA + if (strcmp(protocol_name, "NEOCLIMA") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kNeoclimaStateLength; @@ -1037,10 +943,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendNeoclima(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN176 - if (strcmp(protocol_name, "DAIKIN176") == 1) - { +# endif +# ifdef IR_DAIKIN176 + if (strcmp(protocol_name, "DAIKIN176") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikin176StateLength; @@ -1049,10 +954,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin176(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN128 - if (strcmp(protocol_name, "DAIKIN128") == 1) - { +# endif +# ifdef IR_DAIKIN128 + if (strcmp(protocol_name, "DAIKIN128") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikin128StateLength; @@ -1061,10 +965,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin128(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_AMCOR - if (strcmp(protocol_name, "AMCOR") == 1) - { +# endif +# ifdef IR_AMCOR + if (strcmp(protocol_name, "AMCOR") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kAmcorStateLength; @@ -1073,10 +976,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendAmcor(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_DAIKIN152 - if (strcmp(protocol_name, "DAIKIN152") == 1) - { +# endif +# ifdef IR_DAIKIN152 + if (strcmp(protocol_name, "DAIKIN152") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kDaikin152StateLength; @@ -1085,10 +987,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendDaikin152(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHI136 - if (strcmp(protocol_name, "MITSUBISHI136") == 1) - { +# endif +# ifdef IR_MITSUBISHI136 + if (strcmp(protocol_name, "MITSUBISHI136") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishi136StateLength; @@ -1097,10 +998,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishi136(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_MITSUBISHI112 - if (strcmp(protocol_name, "MITSUBISHI112") == 1) - { +# endif +# ifdef IR_MITSUBISHI112 + if (strcmp(protocol_name, "MITSUBISHI112") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) valueBITS = kMitsubishi112StateLength; @@ -1109,10 +1009,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendMitsubishi112(dataarray, valueBITS, valueRPT); return true; } -#endif -#ifdef IR_HITACHI_AC424 - if (strcmp(protocol_name, "HITACHI_AC424") == 1) - { +# endif +# ifdef IR_HITACHI_AC424 + if (strcmp(protocol_name, "HITACHI_AC424") == 1) { Log.notice(F("Sending IR signal with %s"), protocol_name); Log.notice(F("Sending IR signal with %s"), protocol_name); if (valueBITS == 0) @@ -1122,9 +1021,9 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, irsend.sendHitachiAc424(dataarray, valueBITS, valueRPT); return true; } -#endif -Log.trace(F("At the end" CR)); +# endif + Log.trace(F("At the end" CR)); return false; -#endif +# endif } #endif diff --git a/main/ZgatewayLORA.ino b/main/ZgatewayLORA.ino index ea8869b4..ca38778e 100644 --- a/main/ZgatewayLORA.ino +++ b/main/ZgatewayLORA.ino @@ -29,17 +29,15 @@ #ifdef ZgatewayLORA -#include -#include -#include +# include +# include +# include -void setupLORA() -{ +void setupLORA() { SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_SS); LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0); - if (!LoRa.begin(LORA_BAND)) - { + if (!LoRa.begin(LORA_BAND)) { Log.error(F("ZgatewayLORA setup failed!" CR)); while (1) ; @@ -54,46 +52,40 @@ void setupLORA() Log.trace(F("ZgatewayLORA setup done" CR)); } -void LORAtoMQTT() -{ +void LORAtoMQTT() { int packetSize = LoRa.parsePacket(); - if (packetSize) - { + if (packetSize) { StaticJsonBuffer jsonBuffer; - JsonObject &LORAdata = jsonBuffer.createObject(); + JsonObject& LORAdata = jsonBuffer.createObject(); Log.trace(F("Rcv. LORA" CR)); -#ifdef ESP32 +# ifdef ESP32 String taskMessage = "LORA Task running on core "; taskMessage = taskMessage + xPortGetCoreID(); //trc(taskMessage); -#endif +# endif String packet; packet = ""; - for (int i = 0; i < packetSize; i++) - { + for (int i = 0; i < packetSize; i++) { packet += (char)LoRa.read(); } LORAdata.set("rssi", (int)LoRa.packetRssi()); LORAdata.set("snr", (float)LoRa.packetSnr()); LORAdata.set("pferror", (float)LoRa.packetFrequencyError()); LORAdata.set("packetSize", (int)packetSize); - LORAdata.set("message", (char *)packet.c_str()); + LORAdata.set("message", (char*)packet.c_str()); pub(subjectLORAtoMQTT, LORAdata); - if (repeatLORAwMQTT) - { + if (repeatLORAwMQTT) { Log.trace(F("Pub LORA for rpt" CR)); pub(subjectMQTTtoLORA, LORAdata); } } } -#ifdef jsonReceiving -void MQTTtoLORA(char *topicOri, JsonObject &LORAdata) -{ // json object decoding - if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) - { +# ifdef jsonReceiving +void MQTTtoLORA(char* topicOri, JsonObject& LORAdata) { // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) { Log.trace(F("MQTTtoLORA json" CR)); - const char *message = LORAdata["message"]; + const char* message = LORAdata["message"]; int txPower = LORAdata["txpower"] | LORA_TX_POWER; int spreadingFactor = LORAdata["spreadingfactor"] | LORA_SPREADING_FACTOR; long int frequency = LORAdata["frequency "] | LORA_BAND; @@ -102,8 +94,7 @@ void MQTTtoLORA(char *topicOri, JsonObject &LORAdata) int preambleLength = LORAdata["preamblelength"] | LORA_PREAMBLE_LENGTH; byte syncWord = LORAdata["syncword"] | LORA_SYNC_WORD; bool Crc = LORAdata["enablecrc"] | DEFAULT_CRC; - if (message) - { + if (message) { LoRa.setTxPower(txPower); LoRa.setFrequency(frequency); LoRa.setSpreadingFactor(spreadingFactor); @@ -118,19 +109,15 @@ void MQTTtoLORA(char *topicOri, JsonObject &LORAdata) LoRa.endPacket(); Log.trace(F("MQTTtoLORA OK" CR)); pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } - else - { + } else { Log.error(F("MQTTtoLORA Fail json" CR)); } } } -#endif -#ifdef simpleReceiving -void MQTTtoLORA(char *topicOri, char *LORAdata) -{ // json object decoding - if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) - { +# endif +# ifdef simpleReceiving +void MQTTtoLORA(char* topicOri, char* LORAdata) { // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) { LoRa.beginPacket(); LoRa.print(LORAdata); LoRa.endPacket(); @@ -138,5 +125,5 @@ void MQTTtoLORA(char *topicOri, char *LORAdata) pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also } } -#endif +# endif #endif diff --git a/main/ZgatewayPilight.ino b/main/ZgatewayPilight.ino index 85e51b98..f383d7e7 100644 --- a/main/ZgatewayPilight.ino +++ b/main/ZgatewayPilight.ino @@ -29,149 +29,129 @@ #ifdef ZgatewayPilight -#ifdef ZradioCC1101 - #include -#endif +# ifdef ZradioCC1101 +# include +# endif -#include +# include ESPiLight rf(RF_EMITTER_PIN); // use -1 to disable transmitter -void pilightCallback(const String &protocol, const String &message, int status, - size_t repeats, const String &deviceID) -{ - if (status == VALID) - { +void pilightCallback(const String& protocol, const String& message, int status, + size_t repeats, const String& deviceID) { + if (status == VALID) { Log.trace(F("Creating RF PiLight buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &RFPiLightdata = jsonBuffer.createObject(); + JsonObject& RFPiLightdata = jsonBuffer.createObject(); StaticJsonBuffer jsonBuffer2; - JsonObject &msg = jsonBuffer2.parseObject(message); + JsonObject& msg = jsonBuffer2.parseObject(message); RFPiLightdata.set("message", msg); - RFPiLightdata.set("protocol", (char *)protocol.c_str()); - RFPiLightdata.set("length", (char *)deviceID.c_str()); + RFPiLightdata.set("protocol", (char*)protocol.c_str()); + RFPiLightdata.set("length", (char*)deviceID.c_str()); RFPiLightdata.set("repeats", (int)repeats); RFPiLightdata.set("status", (int)status); pub(subjectPilighttoMQTT, RFPiLightdata); - if (repeatPilightwMQTT) - { + if (repeatPilightwMQTT) { Log.trace(F("Pub Pilight for rpt" CR)); pub(subjectMQTTtoPilight, RFPiLightdata); } } } -void setupPilight() -{ -#ifndef ZgatewayRF &&ZgatewayRF2 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell - #ifdef ZradioCC1101 //receiving with CC1101 - ELECHOUSE_cc1101.Init(); - ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY); - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); - rf.enableReceiver(); - #endif +void setupPilight() { +# ifndef ZgatewayRF&& ZgatewayRF2 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell +# ifdef ZradioCC1101 //receiving with CC1101 + ELECHOUSE_cc1101.Init(); + ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY); + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); + rf.enableReceiver(); +# endif rf.setCallback(pilightCallback); rf.initReceiver(RF_RECEIVER_PIN); pinMode(RF_EMITTER_PIN, OUTPUT); // Set this here, because if this is the RX pin it was reset to INPUT by Serial.end(); Log.notice(F("RF_EMITTER_PIN: %d " CR), RF_EMITTER_PIN); Log.notice(F("RF_RECEIVER_PIN: %d " CR), RF_RECEIVER_PIN); Log.trace(F("ZgatewayPilight setup done " CR)); -#else +# else Log.trace(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2" CR)); -#endif +# endif } -void PilighttoMQTT() -{ +void PilighttoMQTT() { rf.loop(); } -void MQTTtoPilight(char *topicOri, JsonObject &Pilightdata) -{ - #ifdef ZradioCC1101 - ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on - rf.disableReceiver(); - #endif +void MQTTtoPilight(char* topicOri, JsonObject& Pilightdata) { +# ifdef ZradioCC1101 + ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on + rf.disableReceiver(); +# endif int result = 0; - if (cmpToMainTopic(topicOri, subjectMQTTtoPilight)) - { + if (cmpToMainTopic(topicOri, subjectMQTTtoPilight)) { Log.trace(F("MQTTtoPilight json data analysis" CR)); - const char *message = Pilightdata["message"]; - const char *protocol = Pilightdata["protocol"]; - const char *raw = Pilightdata["raw"]; - if (raw) - { + const char* message = Pilightdata["message"]; + const char* protocol = Pilightdata["protocol"]; + const char* raw = Pilightdata["raw"]; + if (raw) { int msgLength = 0; uint16_t codes[MAXPULSESTREAMLENGTH]; msgLength = rf.stringToPulseTrain( raw, codes, MAXPULSESTREAMLENGTH); - if (msgLength > 0) - { + if (msgLength > 0) { rf.sendPulseTrain(codes, msgLength); Log.notice(F("MQTTtoPilight raw ok" CR)); result = msgLength; - } - else - { + } else { Log.trace(F("MQTTtoPilight raw KO" CR)); - switch (result) - { - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C: - Log.trace(F("'c' not found in string, or has no data" CR)); - break; - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P: - Log.trace(F("'p' not found in string, or has no data" CR)); - break; - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END: - Log.trace(F("';' or '@' not found in data string" CR)); - break; - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE: - Log.trace(F("pulse type not defined" CR)); - break; + switch (result) { + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C: + Log.trace(F("'c' not found in string, or has no data" CR)); + break; + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P: + Log.trace(F("'p' not found in string, or has no data" CR)); + break; + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END: + Log.trace(F("';' or '@' not found in data string" CR)); + break; + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE: + Log.trace(F("pulse type not defined" CR)); + break; } } - } - else if (message && protocol) - { + } else if (message && protocol) { Log.trace(F("MQTTtoPilight msg & protocol ok" CR)); result = rf.send(protocol, message); - } - else - { + } else { Log.error(F("MQTTtoPilight failed json read" CR)); } - if (result > 0) - { + if (result > 0) { Log.trace(F("Adv data MQTTtoPilight push state via PilighttoMQTT" CR)); pub(subjectGTWPilighttoMQTT, Pilightdata); - } - else - { - switch (result) - { - case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: - Log.error(F("protocol is not available" CR)); - break; - case ESPiLight::ERROR_INVALID_PILIGHT_MSG: - Log.error(F("message is invalid" CR)); - break; - case ESPiLight::ERROR_INVALID_JSON: - Log.error(F("message is not a proper json object" CR)); - break; - case ESPiLight::ERROR_NO_OUTPUT_PIN: - Log.error(F("no transmitter pin" CR)); - break; - default: - Log.error(F("invalid json data, can't read raw or message/protocol" CR)); - break; + } else { + switch (result) { + case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: + Log.error(F("protocol is not available" CR)); + break; + case ESPiLight::ERROR_INVALID_PILIGHT_MSG: + Log.error(F("message is invalid" CR)); + break; + case ESPiLight::ERROR_INVALID_JSON: + Log.error(F("message is not a proper json object" CR)); + break; + case ESPiLight::ERROR_NO_OUTPUT_PIN: + Log.error(F("no transmitter pin" CR)); + break; + default: + Log.error(F("invalid json data, can't read raw or message/protocol" CR)); + break; } } } - #ifdef ZradioCC1101 - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on - rf.enableReceiver(); - #endif +# ifdef ZradioCC1101 + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on + rf.enableReceiver(); +# endif } #endif diff --git a/main/ZgatewayRF.ino b/main/ZgatewayRF.ino index 4743db55..66cf75cf 100644 --- a/main/ZgatewayRF.ino +++ b/main/ZgatewayRF.ino @@ -29,61 +29,55 @@ #ifdef ZgatewayRF -#ifdef ZradioCC1101 - #include -#endif +# ifdef ZradioCC1101 +# include +# endif -#include // library for controling Radio frequency switch +# include // library for controling Radio frequency switch RCSwitch mySwitch = RCSwitch(); -#ifdef ZmqttDiscovery -void RFtoMQTTdiscovery(unsigned long MQTTvalue) -{ //on the fly switch creation from received RF values +# ifdef ZmqttDiscovery +void RFtoMQTTdiscovery(unsigned long MQTTvalue) { //on the fly switch creation from received RF values char val[11]; sprintf(val, "%lu", MQTTvalue); Log.trace(F("switchRFDiscovery" CR)); - char *switchRF[8] = {"switch", val, "", "", "", val, "", ""}; + char* switchRF[8] = {"switch", val, "", "", "", val, "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - Log.trace(F("CreateDiscoverySwitch: %s" CR),switchRF[1]); + Log.trace(F("CreateDiscoverySwitch: %s" CR), switchRF[1]); createDiscovery(switchRF[0], - subjectRFtoMQTT, switchRF[1], (char *)getUniqueId(switchRF[1], switchRF[2]).c_str(), + subjectRFtoMQTT, switchRF[1], (char*)getUniqueId(switchRF[1], switchRF[2]).c_str(), will_Topic, switchRF[3], switchRF[4], switchRF[5], switchRF[6], switchRF[7], 0, "", "", true, subjectMQTTtoRF); } -#endif - -void setupRF() -{ +# endif +void setupRF() { //RF init parameters Log.notice(F("RF_EMITTER_PIN: %d " CR), RF_EMITTER_PIN); Log.notice(F("RF_RECEIVER_PIN: %d " CR), RF_RECEIVER_PIN); - #ifdef ZradioCC1101 //receiving with CC1101 - ELECHOUSE_cc1101.Init(); - ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY); - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); - #endif +# ifdef ZradioCC1101 //receiving with CC1101 + ELECHOUSE_cc1101.Init(); + ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY); + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); +# endif mySwitch.enableTransmit(RF_EMITTER_PIN); mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); mySwitch.enableReceive(RF_RECEIVER_PIN); Log.trace(F("ZgatewayRF setup done" CR)); } -void RFtoMQTT() -{ - - if (mySwitch.available()) - { +void RFtoMQTT() { + if (mySwitch.available()) { const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4); StaticJsonBuffer jsonBuffer; - JsonObject &RFdata = jsonBuffer.createObject(); + JsonObject& RFdata = jsonBuffer.createObject(); Log.trace(F("Rcv. RF" CR)); -#ifdef ESP32 - Log.trace(F("RF Task running on core :%d" CR),xPortGetCoreID()); -#endif +# ifdef ESP32 + Log.trace(F("RF Task running on core :%d" CR), xPortGetCoreID()); +# endif RFdata.set("value", (unsigned long)mySwitch.getReceivedValue()); RFdata.set("protocol", (int)mySwitch.getReceivedProtocol()); RFdata.set("length", (int)mySwitch.getReceivedBitlength()); @@ -91,16 +85,14 @@ void RFtoMQTT() mySwitch.resetAvailable(); unsigned long MQTTvalue = RFdata.get("value"); - if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) - { // conditions to avoid duplications of RF -->MQTT -#ifdef ZmqttDiscovery //component creation for HA + if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of RF -->MQTT +# ifdef ZmqttDiscovery //component creation for HA RFtoMQTTdiscovery(MQTTvalue); -#endif +# endif pub(subjectRFtoMQTT, RFdata); Log.trace(F("Store val: %lu" CR), MQTTvalue); storeValue(MQTTvalue); - if (repeatRFwMQTT) - { + if (repeatRFwMQTT) { Log.trace(F("Pub RF for rpt" CR)); pub(subjectMQTTtoRF, RFdata); } @@ -108,15 +100,13 @@ void RFtoMQTT() } } -#ifdef simpleReceiving -void MQTTtoRF(char *topicOri, char *datacallback) -{ - - #ifdef ZradioCC1101 // set Receive off and Transmitt on - ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); - mySwitch.disableReceive(); - mySwitch.enableTransmit(RF_EMITTER_PIN); - #endif +# ifdef simpleReceiving +void MQTTtoRF(char* topicOri, char* datacallback) { +# ifdef ZradioCC1101 // set Receive off and Transmitt on + ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); + mySwitch.disableReceive(); + mySwitch.enableTransmit(RF_EMITTER_PIN); +# endif unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 // RF DATA ANALYSIS @@ -126,35 +116,29 @@ void MQTTtoRF(char *topicOri, char *datacallback) int valuePLSL = 0; int valueBITS = 0; int pos = topic.lastIndexOf(RFprotocolKey); - if (pos != -1) - { + if (pos != -1) { pos = pos + +strlen(RFprotocolKey); valuePRT = (topic.substring(pos, pos + 1)).toInt(); } //We look into the subject to see if a special RF pulselength is defined int pos2 = topic.lastIndexOf(RFpulselengthKey); - if (pos2 != -1) - { + if (pos2 != -1) { pos2 = pos2 + strlen(RFpulselengthKey); valuePLSL = (topic.substring(pos2, pos2 + 3)).toInt(); } int pos3 = topic.lastIndexOf(RFbitsKey); - if (pos3 != -1) - { + if (pos3 != -1) { pos3 = pos3 + strlen(RFbitsKey); valueBITS = (topic.substring(pos3, pos3 + 2)).toInt(); } - if ((cmpToMainTopic(topicOri, subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)) - { + if ((cmpToMainTopic(topicOri, subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)) { Log.trace(F("MQTTtoRF dflt" CR)); mySwitch.setProtocol(1, 350); mySwitch.send(data, 24); // Acknowledgement to the GTWRF topic pub(subjectGTWRFtoMQTT, datacallback); - } - else if ((valuePRT != 0) || (valuePLSL != 0) || (valueBITS != 0)) - { + } else if ((valuePRT != 0) || (valuePLSL != 0) || (valueBITS != 0)) { Log.trace(F("MQTTtoRF usr par." CR)); if (valuePRT == 0) valuePRT = 1; @@ -170,28 +154,25 @@ void MQTTtoRF(char *topicOri, char *datacallback) // Acknowledgement to the GTWRF topic pub(subjectGTWRFtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also } - #ifdef ZradioCC1101 // set Receive on and Transmitt off - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); - mySwitch.disableTransmit(); - mySwitch.enableReceive(RF_RECEIVER_PIN); - #endif +# ifdef ZradioCC1101 // set Receive on and Transmitt off + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); + mySwitch.disableTransmit(); + mySwitch.enableReceive(RF_RECEIVER_PIN); +# endif } -#endif +# endif -#ifdef jsonReceiving -void MQTTtoRF(char *topicOri, JsonObject &RFdata) -{ // json object decoding - #ifdef ZradioCC1101 // set Receive off and Transmitt on - ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); - mySwitch.disableReceive(); - mySwitch.enableTransmit(RF_EMITTER_PIN); - #endif - if (cmpToMainTopic(topicOri, subjectMQTTtoRF)) - { +# ifdef jsonReceiving +void MQTTtoRF(char* topicOri, JsonObject& RFdata) { // json object decoding +# ifdef ZradioCC1101 // set Receive off and Transmitt on + ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); + mySwitch.disableReceive(); + mySwitch.enableTransmit(RF_EMITTER_PIN); +# endif + if (cmpToMainTopic(topicOri, subjectMQTTtoRF)) { Log.trace(F("MQTTtoRF json" CR)); unsigned long data = RFdata["value"]; - if (data != 0) - { + if (data != 0) { int valuePRT = RFdata["protocol"] | 1; int valuePLSL = RFdata["delay"] | 350; int valueBITS = RFdata["length"] | 24; @@ -203,19 +184,17 @@ void MQTTtoRF(char *topicOri, JsonObject &RFdata) mySwitch.setProtocol(valuePRT, valuePLSL); mySwitch.send(data, valueBITS); Log.notice(F("MQTTtoRF OK" CR)); - pub(subjectGTWRFtoMQTT, RFdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also + pub(subjectGTWRFtoMQTT, RFdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); // Restore the default value - } - else - { + } else { Log.error(F("MQTTtoRF Fail json" CR)); } } - #ifdef ZradioCC1101 // set Receive on and Transmitt off - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); - mySwitch.disableTransmit(); - mySwitch.enableReceive(RF_RECEIVER_PIN); - #endif +# ifdef ZradioCC1101 // set Receive on and Transmitt off + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); + mySwitch.disableTransmit(); + mySwitch.enableReceive(RF_RECEIVER_PIN); +# endif } -#endif +# endif #endif diff --git a/main/ZgatewayRF2.ino b/main/ZgatewayRF2.ino index c9e153ae..7e4eb94b 100644 --- a/main/ZgatewayRF2.ino +++ b/main/ZgatewayRF2.ino @@ -37,15 +37,14 @@ sudo mosquitto_pub -t home/commands/MQTTtoRF2/CODE_8233372/UNIT_0/PERIOD_272 -m/ #ifdef ZgatewayRF2 -#ifdef ZradioCC1101 - #include -#endif +# ifdef ZradioCC1101 +# include +# endif -#include -#include +# include +# include -struct RF2rxd -{ +struct RF2rxd { unsigned int period; unsigned long address; unsigned long groupBit; @@ -56,32 +55,28 @@ struct RF2rxd RF2rxd rf2rd; -void setupRF2() -{ -#ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF - #ifdef ZradioCC1101 //receiving with CC1101 - ELECHOUSE_cc1101.Init(); - ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY); - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); - #endif +void setupRF2() { +# ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF +# ifdef ZradioCC1101 //receiving with CC1101 + ELECHOUSE_cc1101.Init(); + ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY); + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); +# endif NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback); Log.notice(F("RF_EMITTER_PIN: %d " CR), RF_EMITTER_PIN); Log.notice(F("RF_RECEIVER_PIN: %d " CR), RF_RECEIVER_PIN); Log.trace(F("ZgatewayRF2 setup done " CR)); -#endif +# endif pinMode(RF_EMITTER_PIN, OUTPUT); digitalWrite(RF_EMITTER_PIN, LOW); } -void RF2toMQTT() -{ - - if (rf2rd.hasNewData) - { +void RF2toMQTT() { + if (rf2rd.hasNewData) { Log.trace(F("Creating RF2 buffer" CR)); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5); StaticJsonBuffer jsonBuffer; - JsonObject &RF2data = jsonBuffer.createObject(); + JsonObject& RF2data = jsonBuffer.createObject(); rf2rd.hasNewData = false; @@ -96,9 +91,7 @@ void RF2toMQTT() } } -void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType) -{ - +void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType) { rf2rd.period = period; rf2rd.address = address; rf2rd.groupBit = groupBit; @@ -107,13 +100,12 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group rf2rd.hasNewData = true; } -#ifdef simpleReceiving -void MQTTtoRF2(char *topicOri, char *datacallback) -{ - #ifdef ZradioCC1101 - NewRemoteReceiver::disable(); - ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on - #endif +# ifdef simpleReceiving +void MQTTtoRF2(char* topicOri, char* datacallback) { +# ifdef ZradioCC1101 + NewRemoteReceiver::disable(); + ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on +# endif // RF DATA ANALYSIS //We look into the subject to see if a special RF protocol is defined @@ -129,43 +121,37 @@ void MQTTtoRF2(char *topicOri, char *datacallback) int valueDIM = -1; int pos = topic.lastIndexOf(RF2codeKey); - if (pos != -1) - { + if (pos != -1) { pos = pos + +strlen(RF2codeKey); valueCODE = (topic.substring(pos, pos + 8)).toInt(); Log.notice(F("RF2 code: %l" CR), valueCODE); } int pos2 = topic.lastIndexOf(RF2periodKey); - if (pos2 != -1) - { + if (pos2 != -1) { pos2 = pos2 + strlen(RF2periodKey); valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt(); Log.notice(F("RF2 Period: %d" CR), valuePERIOD); } int pos3 = topic.lastIndexOf(RF2unitKey); - if (pos3 != -1) - { + if (pos3 != -1) { pos3 = pos3 + strlen(RF2unitKey); valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt(); Log.notice(F("Unit: %d" CR), valueUNIT); } int pos4 = topic.lastIndexOf(RF2groupKey); - if (pos4 != -1) - { + if (pos4 != -1) { pos4 = pos4 + strlen(RF2groupKey); valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt(); - Log.notice(F("RF2 Group: %d" CR),valueGROUP); + Log.notice(F("RF2 Group: %d" CR), valueGROUP); } int pos5 = topic.lastIndexOf(RF2dimKey); - if (pos5 != -1) - { + if (pos5 != -1) { isDimCommand = true; valueDIM = atoi(datacallback); Log.notice(F("RF2 Dim: %d" CR), valueDIM); } - if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) - { + if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) { Log.trace(F("MQTTtoRF2" CR)); if (valueCODE == 0) valueCODE = 8233378; @@ -177,25 +163,16 @@ void MQTTtoRF2(char *topicOri, char *datacallback) Log.trace(F("Creating transmitter" CR)); NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); Log.trace(F("Sending data" CR)); - if (valueGROUP) - { - if (isDimCommand) - { + if (valueGROUP) { + if (isDimCommand) { transmitter.sendGroupDim(valueDIM); - } - else - { + } else { transmitter.sendGroup(boolSWITCHTYPE); } - } - else - { - if (isDimCommand) - { + } else { + if (isDimCommand) { transmitter.sendDim(valueUNIT, valueDIM); - } - else - { + } else { transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); } } @@ -218,38 +195,32 @@ void MQTTtoRF2(char *topicOri, char *datacallback) MQTTdimLevel = String(valueDIM); String MQTTRF2string; Log.trace(F("Adv data MQTTtoRF2 push state via RF2toMQTT" CR)); - if (isDimCommand) - { + if (isDimCommand) { MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2dimKey + String("/") + RF2periodKey + MQTTperiod; - pub((char *)MQTTRF2string.c_str(), (char *)MQTTdimLevel.c_str()); - } - else - { + pub((char*)MQTTRF2string.c_str(), (char*)MQTTdimLevel.c_str()); + } else { MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod; - pub((char *)MQTTRF2string.c_str(), (char *)MQTTswitchType.c_str()); + pub((char*)MQTTRF2string.c_str(), (char*)MQTTswitchType.c_str()); } } - #ifdef ZradioCC1101 - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on - NewRemoteReceiver::enable(); - #endif +# ifdef ZradioCC1101 + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on + NewRemoteReceiver::enable(); +# endif } -#endif +# endif -#ifdef jsonReceiving -void MQTTtoRF2(char *topicOri, JsonObject &RF2data) -{ // json object decoding - #ifdef ZradioCC1101 - NewRemoteReceiver::disable(); - ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on - #endif +# ifdef jsonReceiving +void MQTTtoRF2(char* topicOri, JsonObject& RF2data) { // json object decoding +# ifdef ZradioCC1101 + NewRemoteReceiver::disable(); + ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on +# endif - if (cmpToMainTopic(topicOri, subjectMQTTtoRF2)) - { + if (cmpToMainTopic(topicOri, subjectMQTTtoRF2)) { Log.trace(F("MQTTtoRF2 json" CR)); int boolSWITCHTYPE = RF2data["switchType"] | 99; - if (boolSWITCHTYPE != 99) - { + if (boolSWITCHTYPE != 99) { Log.trace(F("MQTTtoRF2 switch type ok" CR)); bool isDimCommand = boolSWITCHTYPE == 2; unsigned long valueCODE = RF2data["address"]; @@ -257,8 +228,7 @@ void MQTTtoRF2(char *topicOri, JsonObject &RF2data) int valuePERIOD = RF2data["period"]; int valueGROUP = RF2data["group"]; int valueDIM = RF2data["dim"] | -1; - if ((valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) - { + if ((valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) { Log.trace(F("MQTTtoRF2" CR)); if (valueCODE == 0) valueCODE = 8233378; @@ -269,25 +239,16 @@ void MQTTtoRF2(char *topicOri, JsonObject &RF2data) NewRemoteReceiver::disable(); NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); Log.trace(F("Sending" CR)); - if (valueGROUP) - { - if (isDimCommand) - { + if (valueGROUP) { + if (isDimCommand) { transmitter.sendGroupDim(valueDIM); - } - else - { + } else { transmitter.sendGroup(boolSWITCHTYPE); } - } - else - { - if (isDimCommand) - { + } else { + if (isDimCommand) { transmitter.sendDim(valueUNIT, valueDIM); - } - else - { + } else { transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); } } @@ -297,16 +258,14 @@ void MQTTtoRF2(char *topicOri, JsonObject &RF2data) // Publish state change back to MQTT pub(subjectGTWRF2toMQTT, RF2data); } - } - else - { + } else { Log.error(F("MQTTtoRF2 failed json read" CR)); } } - #ifdef ZradioCC1101 - ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on - NewRemoteReceiver::enable(); - #endif +# ifdef ZradioCC1101 + ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on + NewRemoteReceiver::enable(); +# endif } -#endif +# endif #endif diff --git a/main/ZgatewayRFM69.ino b/main/ZgatewayRFM69.ino index b016832d..eca5a09c 100644 --- a/main/ZgatewayRFM69.ino +++ b/main/ZgatewayRFM69.ino @@ -32,16 +32,15 @@ #ifdef ZgatewayRFM69 -#include //https://www.github.com/lowpowerlab/rfm69 -#include -#include +# include +# include //https://www.github.com/lowpowerlab/rfm69 +# include char RadioConfig[128]; // vvvvvvvvv Global Configuration vvvvvvvvvvv -struct _GLOBAL_CONFIG -{ +struct _GLOBAL_CONFIG { uint32_t checksum; char rfmapname[32]; char encryptkey[16 + 1]; @@ -51,33 +50,29 @@ struct _GLOBAL_CONFIG uint8_t rfmfrequency; }; -#define GC_POWER_LEVEL (pGC->powerlevel & 0x1F) -#define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0) -#define SELECTED_FREQ(f) ((pGC->rfmfrequency == f) ? "selected" : "") +# define GC_POWER_LEVEL (pGC->powerlevel & 0x1F) +# define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0) +# define SELECTED_FREQ(f) ((pGC->rfmfrequency == f) ? "selected" : "") -struct _GLOBAL_CONFIG *pGC; +struct _GLOBAL_CONFIG* pGC; // vvvvvvvvv Global Configuration vvvvvvvvvvv -uint32_t gc_checksum() -{ - uint8_t *p = (uint8_t *)pGC; +uint32_t gc_checksum() { + uint8_t* p = (uint8_t*)pGC; uint32_t checksum = 0; p += sizeof(pGC->checksum); - for (size_t i = 0; i < (sizeof(*pGC) - 4); i++) - { + for (size_t i = 0; i < (sizeof(*pGC) - 4); i++) { checksum += *p++; } return checksum; } -#if defined(ESP8266) || defined(ESP32) -void eeprom_setup() -{ +# if defined(ESP8266) || defined(ESP32) +void eeprom_setup() { EEPROM.begin(4096); - pGC = (struct _GLOBAL_CONFIG *)EEPROM.getDataPtr(); + pGC = (struct _GLOBAL_CONFIG*)EEPROM.getDataPtr(); // if checksum bad init GC else use GC values - if (gc_checksum() != pGC->checksum) - { + if (gc_checksum() != pGC->checksum) { Log.trace(F("Factory reset" CR)); memset(pGC, 0, sizeof(*pGC)); strcpy_P(pGC->encryptkey, ENCRYPTKEY); @@ -90,15 +85,14 @@ void eeprom_setup() EEPROM.commit(); } } -#endif +# endif RFM69 radio; -void setupRFM69(void) -{ -#if defined(ESP8266) || defined(ESP32) +void setupRFM69(void) { +# if defined(ESP8266) || defined(ESP32) eeprom_setup(); -#endif +# endif int freq; static const char PROGMEM JSONtemplate[] = R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})"; @@ -107,13 +101,11 @@ void setupRFM69(void) radio = RFM69(RFM69_CS, RFM69_IRQ, GC_IS_RFM69HCW, RFM69_IRQN); // Initialize radio - if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid)) - { + if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid)) { Log.error(F("ZgatewayRFM69 initialization failed" CR)); } - if (GC_IS_RFM69HCW) - { + if (GC_IS_RFM69HCW) { radio.setHighPower(); // Only for RFM69HCW & HW! } radio.setPowerLevel(GC_POWER_LEVEL); // power output ranges from 0 (5dBm) to 31 (20dBm) @@ -121,141 +113,118 @@ void setupRFM69(void) if (pGC->encryptkey[0] != '\0') radio.encrypt(pGC->encryptkey); - switch (pGC->rfmfrequency) - { - case RF69_433MHZ: - freq = 433; - break; - case RF69_868MHZ: - freq = 868; - break; - case RF69_915MHZ: - freq = 915; - break; - case RF69_315MHZ: - freq = 315; - break; - default: - freq = -1; - break; + switch (pGC->rfmfrequency) { + case RF69_433MHZ: + freq = 433; + break; + case RF69_868MHZ: + freq = 868; + break; + case RF69_915MHZ: + freq = 915; + break; + case RF69_315MHZ: + freq = 315; + break; + default: + freq = -1; + break; } Log.notice(F("ZgatewayRFM69 Listening and transmitting at: %d" CR), freq); size_t len = snprintf_P(RadioConfig, sizeof(RadioConfig), JSONtemplate, freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL); - if (len >= sizeof(RadioConfig)) - { + if (len >= sizeof(RadioConfig)) { Log.trace(F("\n\n*** RFM69 config truncated ***\n" CR)); } } -bool RFM69toMQTT(void) -{ +bool RFM69toMQTT(void) { //check if something was received (could be an interrupt from the radio) - if (radio.receiveDone()) - { + if (radio.receiveDone()) { Log.trace(F("Creating RFM69 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &RFM69data = jsonBuffer.createObject(); + JsonObject& RFM69data = jsonBuffer.createObject(); uint8_t data[RF69_MAX_DATA_LEN + 1]; // For the null character uint8_t SENDERID = radio.SENDERID; uint8_t DATALEN = radio.DATALEN; uint16_t RSSI = radio.RSSI; //save packet because it may be overwritten - memcpy(data, (void *)radio.DATA, DATALEN); + memcpy(data, (void*)radio.DATA, DATALEN); data[DATALEN] = '\0'; // Terminate the string // Ack as soon as possible //check if sender wanted an ACK - if (radio.ACKRequested()) - { + if (radio.ACKRequested()) { radio.sendACK(); } //updateClients(senderId, rssi, (const char *)data); - Log.trace(F("Data received: %s" CR), (const char *)data); + Log.trace(F("Data received: %s" CR), (const char*)data); char buff[sizeof(subjectRFM69toMQTT) + 4]; sprintf(buff, "%s/%d", subjectRFM69toMQTT, SENDERID); - RFM69data.set("data", (char *)data); + RFM69data.set("data", (char*)data); RFM69data.set("rssi", (int)radio.RSSI); RFM69data.set("senderid", (int)radio.SENDERID); pub(buff, RFM69data); return true; - } - else - { + } else { return false; } } -#ifdef simpleReceiving -void MQTTtoRFM69(char *topicOri, char *datacallback) -{ - - if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) - { +# ifdef simpleReceiving +void MQTTtoRFM69(char* topicOri, char* datacallback) { + if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) { Log.trace(F("MQTTtoRFM69 data analysis" CR)); char data[RF69_MAX_DATA_LEN + 1]; - memcpy(data, (void *)datacallback, RF69_MAX_DATA_LEN); + memcpy(data, (void*)datacallback, RF69_MAX_DATA_LEN); data[RF69_MAX_DATA_LEN] = '\0'; //We look into the subject to see if a special RF protocol is defined String topic = topicOri; int valueRCV = defaultRFM69ReceiverId; //default receiver id value int pos = topic.lastIndexOf(RFM69receiverKey); - if (pos != -1) - { + if (pos != -1) { pos = pos + +strlen(RFM69receiverKey); valueRCV = (topic.substring(pos, pos + 3)).toInt(); Log.notice(F("RFM69 receiver ID: %d" CR), valueRCV); } - if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) - { + if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) { Log.notice(F(" OK " CR)); // Acknowledgement to the GTWRF topic char buff[sizeof(subjectGTWRFM69toMQTT) + 4]; sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID); pub(buff, data); - } - else - { + } else { Log.error(F("RFM69 sending failed" CR)); } } } -#endif -#ifdef jsonReceiving -void MQTTtoRFM69(char *topicOri, JsonObject &RFM69data) -{ - - if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) - { - const char *data = RFM69data["data"]; +# endif +# ifdef jsonReceiving +void MQTTtoRFM69(char* topicOri, JsonObject& RFM69data) { + if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) { + const char* data = RFM69data["data"]; Log.trace(F("MQTTtoRFM69 json data analysis" CR)); - if (data) - { + if (data) { Log.trace(F("MQTTtoRFM69 data ok" CR)); int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value Log.notice(F("RFM69 receiver ID: %d" CR), valueRCV); - if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) - { + if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) { Log.notice(F(" OK " CR)); // Acknowledgement to the GTWRF topic pub(subjectGTWRFM69toMQTT, RFM69data); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } - else - { + } else { Log.error(F("MQTTtoRFM69 sending failed" CR)); } - } - else - { + } else { Log.error(F("MQTTtoRFM69 failed json read" CR)); } } } -#endif +# endif #endif diff --git a/main/ZgatewaySRFB.ino b/main/ZgatewaySRFB.ino index 50bf6e58..55e4035d 100644 --- a/main/ZgatewaySRFB.ino +++ b/main/ZgatewaySRFB.ino @@ -35,19 +35,16 @@ unsigned char _uartbuf[RF_MESSAGE_SIZE + 3] = {0}; unsigned char _uartpos = 0; -void setupSRFB() -{ +void setupSRFB() { Log.trace(F("ZgatewaySRFB setup done " CR)); - Log.trace(F("Serial Baud: %l" CR),SERIAL_BAUD); + Log.trace(F("Serial Baud: %l" CR), SERIAL_BAUD); } -void _rfbSend(byte *message) -{ +void _rfbSend(byte* message) { Serial.println(); Serial.write(RF_CODE_START); Serial.write(RF_CODE_RFOUT); - for (unsigned char j = 0; j < RF_MESSAGE_SIZE; j++) - { + for (unsigned char j = 0; j < RF_MESSAGE_SIZE; j++) { Serial.write(message[j]); } Serial.write(RF_CODE_STOP); @@ -55,17 +52,13 @@ void _rfbSend(byte *message) Serial.println(); } -void _rfbSend(byte *message, int times) -{ - +void _rfbSend(byte* message, int times) { char buffer[RF_MESSAGE_SIZE]; _rfbToChar(message, buffer); Log.notice(F("[RFBRIDGE] Sending MESSAGE" CR)); - for (int i = 0; i < times; i++) - { - if (i > 0) - { + for (int i = 0; i < times; i++) { + if (i > 0) { unsigned long start = millis(); while (millis() - start < RF_SEND_DELAY) delay(1); @@ -74,30 +67,21 @@ void _rfbSend(byte *message, int times) } } -bool SRFBtoMQTT() -{ - +bool SRFBtoMQTT() { static bool receiving = false; - while (Serial.available()) - { + while (Serial.available()) { yield(); byte c = Serial.read(); - if (receiving) - { - if (c == RF_CODE_STOP) - { + if (receiving) { + if (c == RF_CODE_STOP) { _rfbDecode(); receiving = false; - } - else - { + } else { _uartbuf[_uartpos++] = c; } - } - else if (c == RF_CODE_START) - { + } else if (c == RF_CODE_START) { _uartpos = 0; receiving = true; } @@ -105,9 +89,7 @@ bool SRFBtoMQTT() return receiving; } -void _rfbDecode() -{ - +void _rfbDecode() { static unsigned long last = 0; if (millis() - last < RF_RECEIVE_DELAY) return; @@ -116,14 +98,13 @@ void _rfbDecode() byte action = _uartbuf[0]; char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0}; - if (action == RF_CODE_RFIN) - { + if (action == RF_CODE_RFIN) { _rfbToChar(&_uartbuf[1], buffer); Log.trace(F("Creating SRFB buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &SRFBdata = jsonBuffer.createObject(); - SRFBdata.set("raw", (char *)buffer); + JsonObject& SRFBdata = jsonBuffer.createObject(); + SRFBdata.set("raw", (char*)buffer); char Tsyn[4] = {0}; extract_char(buffer, Tsyn, 0, 4, false, true); @@ -145,14 +126,12 @@ void _rfbDecode() unsigned long MQTTvalue = (unsigned long)strtoul(val, NULL, 10); SRFBdata.set("value", (unsigned long)MQTTvalue); - if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) - { // conditions to avoid duplications of RF -->MQTT + if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of RF -->MQTT Log.trace(F("Adv data SRFBtoMQTT" CR)); pub(subjectSRFBtoMQTT, SRFBdata); Log.trace(F("Store val: %lu" CR), MQTTvalue); storeValue(MQTTvalue); - if (repeatSRFBwMQTT) - { + if (repeatSRFBwMQTT) { Log.trace(F("Publish SRFB for rpt" CR)); pub(subjectMQTTtoSRFB, SRFBdata); } @@ -161,8 +140,7 @@ void _rfbDecode() } } -void _rfbAck() -{ +void _rfbAck() { Log.trace(F("[RFBRIDGE] Sending ACK\n" CR)); Serial.println(); Serial.write(RF_CODE_START); @@ -175,13 +153,11 @@ void _rfbAck() /* From an hexa char array ("A220EE...") to a byte array (half the size) */ -bool _rfbToArray(const char *in, byte *out) -{ +bool _rfbToArray(const char* in, byte* out) { if (strlen(in) != RF_MESSAGE_SIZE * 2) return false; char tmp[3] = {0}; - for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++) - { + for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++) { memcpy(tmp, &in[p * 2], 2); out[p] = strtol(tmp, NULL, 16); } @@ -191,57 +167,47 @@ bool _rfbToArray(const char *in, byte *out) /* From a byte array to an hexa char array ("A220EE...", double the size) */ -bool _rfbToChar(byte *in, char *out) -{ - for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++) - { +bool _rfbToChar(byte* in, char* out) { + for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++) { sprintf_P(&out[p * 2], PSTR("%02X" CR), in[p]); } return true; } -#ifdef simpleReceiving -void MQTTtoSRFB(char *topicOri, char *datacallback) -{ - +# ifdef simpleReceiving +void MQTTtoSRFB(char* topicOri, char* datacallback) { // RF DATA ANALYSIS String topic = topicOri; int valueRPT = 0; - if (topic == subjectMQTTtoSRFB) - { - + if (topic == subjectMQTTtoSRFB) { int valueMiniPLSL = 0; int valueMaxiPLSL = 0; int valueSYNC = 0; int pos = topic.lastIndexOf(SRFBRptKey); - if (pos != -1) - { + if (pos != -1) { pos = pos + +strlen(SRFBRptKey); valueRPT = (topic.substring(pos, pos + 1)).toInt(); - Log.notice(F("SRFB Repeat: %d" CR),valueRPT); + Log.notice(F("SRFB Repeat: %d" CR), valueRPT); } int pos2 = topic.lastIndexOf(SRFBminipulselengthKey); - if (pos2 != -1) - { + if (pos2 != -1) { pos2 = pos2 + strlen(SRFBminipulselengthKey); valueMiniPLSL = (topic.substring(pos2, pos2 + 3)).toInt(); - Log.notice(F("RF Mini Pulse Lgth: %d" CR),valueMiniPLSL); + Log.notice(F("RF Mini Pulse Lgth: %d" CR), valueMiniPLSL); } int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey); - if (pos3 != -1) - { + if (pos3 != -1) { pos3 = pos3 + strlen(SRFBmaxipulselengthKey); valueMaxiPLSL = (topic.substring(pos3, pos3 + 2)).toInt(); Log.notice(F("RF Maxi Pulse Lgth: %d" CR), valueMaxiPLSL); } int pos4 = topic.lastIndexOf(SRFBsyncKey); - if (pos4 != -1) - { + if (pos4 != -1) { pos4 = pos4 + strlen(SRFBsyncKey); valueSYNC = (topic.substring(pos4, pos4 + 2)).toInt(); Log.notice(F("RF sync: %d" CR), valueSYNC); @@ -286,12 +252,9 @@ void MQTTtoSRFB(char *topicOri, char *datacallback) // Acknowledgement to the GTWRF topic pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also } - if (topic == subjectMQTTtoSRFBRaw) - { - + if (topic == subjectMQTTtoSRFBRaw) { int pos = topic.lastIndexOf(SRFBRptKey); - if (pos != -1) - { + if (pos != -1) { pos = pos + +strlen(SRFBRptKey); valueRPT = (topic.substring(pos, pos + 1)).toInt(); Log.notice(F("SRFB Repeat: %d" CR), valueRPT); @@ -306,29 +269,22 @@ void MQTTtoSRFB(char *topicOri, char *datacallback) pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also } } -#endif -#ifdef jsonReceiving -void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata) -{ - +# endif +# ifdef jsonReceiving +void MQTTtoSRFB(char* topicOri, JsonObject& SRFBdata) { // RF DATA ANALYSIS - const char *raw = SRFBdata["raw"]; + const char* raw = SRFBdata["raw"]; int valueRPT = SRFBdata["repeat"] | 1; - if (cmpToMainTopic(topicOri, subjectMQTTtoSRFB)) - { + if (cmpToMainTopic(topicOri, subjectMQTTtoSRFB)) { Log.trace(F("MQTTtoSRFB json" CR)); - if (raw) - { // send raw in priority when defined in the json + if (raw) { // send raw in priority when defined in the json Log.trace(F("MQTTtoSRFB raw ok" CR)); byte message_b[RF_MESSAGE_SIZE]; _rfbToArray(raw, message_b); _rfbSend(message_b, valueRPT); - } - else - { + } else { unsigned long data = SRFBdata["value"]; - if (data != 0) - { + if (data != 0) { Log.notice(F("MQTTtoSRFB data ok" CR)); int valueMiniPLSL = SRFBdata["val_Tlow"]; int valueMaxiPLSL = SRFBdata["val_Thigh"]; @@ -343,8 +299,8 @@ void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata) if (valueSYNC == 0) valueSYNC = 9500; - Log.notice(F("SRFB Repeat: %d" CR),valueRPT); - Log.notice(F("RF Mini Pulse Lgth: %d" CR),valueMiniPLSL); + Log.notice(F("SRFB Repeat: %d" CR), valueRPT); + Log.notice(F("RF Mini Pulse Lgth: %d" CR), valueMiniPLSL); Log.notice(F("RF Maxi Pulse Lgth: %d" CR), valueMaxiPLSL); Log.notice(F("RF sync: %d" CR), valueSYNC); @@ -376,13 +332,11 @@ void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata) _rfbSend(message_b, valueRPT); // Acknowledgement to the GTWRF topic pub(subjectGTWSRFBtoMQTT, SRFBdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } - else - { + } else { Log.error(F("MQTTtoSRFB error decoding value" CR)); } } } } -#endif +# endif #endif diff --git a/main/ZgatewayWeatherStation.ino b/main/ZgatewayWeatherStation.ino index a2a19732..3e946023 100644 --- a/main/ZgatewayWeatherStation.ino +++ b/main/ZgatewayWeatherStation.ino @@ -26,42 +26,38 @@ #include "User_config.h" #ifdef ZgatewayWeatherStation -#include +# include WeatherStationDataRx wsdr(RF_WS_RECEIVER_PIN, true); -void PairedDeviceAdded(byte newID) -{ -#if defined(ESP8266) || defined(ESP32) - Serial.printf("ZgatewayWeatherStation: New device paired %d\r\n", newID); -#else - Serial.print("ZgatewayWeatherStation: New device paired "); - Serial.println(newID, DEC); -#endif - const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(2); - StaticJsonBuffer jsonBuffer; - JsonObject &RFdata = jsonBuffer.createObject(); - RFdata.set("sensor", newID); - RFdata.set("action", "paired"); - pub(subjectRFtoMQTT, RFdata); - wsdr.pair(NULL, PairedDeviceAdded); +void PairedDeviceAdded(byte newID) { +# if defined(ESP8266) || defined(ESP32) + Serial.printf("ZgatewayWeatherStation: New device paired %d\r\n", newID); +# else + Serial.print("ZgatewayWeatherStation: New device paired "); + Serial.println(newID, DEC); +# endif + const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(2); + StaticJsonBuffer jsonBuffer; + JsonObject& RFdata = jsonBuffer.createObject(); + RFdata.set("sensor", newID); + RFdata.set("action", "paired"); + pub(subjectRFtoMQTT, RFdata); + wsdr.pair(NULL, PairedDeviceAdded); } -void setupWeatherStation() -{ - Log.notice(F("RF_WS_RECEIVER_PIN %d" CR),RF_WS_RECEIVER_PIN); +void setupWeatherStation() { + Log.notice(F("RF_WS_RECEIVER_PIN %d" CR), RF_WS_RECEIVER_PIN); wsdr.begin(); wsdr.pair(NULL, PairedDeviceAdded); Log.trace(F("ZgatewayWeatherStation setup done " CR)); } -void sendWindSpeedData(byte id, float wind_speed, byte battery_status) -{ +void sendWindSpeedData(byte id, float wind_speed, byte battery_status) { unsigned long MQTTvalue = 10000 + round(wind_speed); - if (!isAduplicate(MQTTvalue)) - { // conditions to avoid duplications of RF -->MQTT + if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3); StaticJsonBuffer jsonBuffer; - JsonObject &RFdata = jsonBuffer.createObject(); + JsonObject& RFdata = jsonBuffer.createObject(); RFdata.set("sensor", id); RFdata.set("wind_speed", wind_speed); RFdata.set("battery", bitRead(battery_status, 0) == 0 ? "OK" : "Low"); @@ -71,14 +67,12 @@ void sendWindSpeedData(byte id, float wind_speed, byte battery_status) } } -void sendRainData(byte id, float rain_volume, byte battery_status) -{ +void sendRainData(byte id, float rain_volume, byte battery_status) { unsigned long MQTTvalue = 11000 + round(rain_volume * 10.0); - if (!isAduplicate(MQTTvalue)) - { // conditions to avoid duplications of RF -->MQTT + if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3); StaticJsonBuffer jsonBuffer; - JsonObject &RFdata = jsonBuffer.createObject(); + JsonObject& RFdata = jsonBuffer.createObject(); RFdata.set("sensor", id); RFdata.set("rain_volume", rain_volume); RFdata.set("battery", bitRead(battery_status, 1) == 0 ? "OK" : "Low"); @@ -88,14 +82,12 @@ void sendRainData(byte id, float rain_volume, byte battery_status) } } -void sendWindData(byte id, int wind_direction, float wind_gust, byte battery_status) -{ +void sendWindData(byte id, int wind_direction, float wind_gust, byte battery_status) { unsigned long MQTTvalue = 20000 + round(wind_gust * 10.0) + wind_direction; - if (!isAduplicate(MQTTvalue)) - { // conditions to avoid duplications of RF -->MQTT + if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4); StaticJsonBuffer jsonBuffer; - JsonObject &RFdata = jsonBuffer.createObject(); + JsonObject& RFdata = jsonBuffer.createObject(); RFdata.set("sensor", id); RFdata.set("wind_direction", wind_direction); RFdata.set("wind_gust", wind_gust); @@ -106,14 +98,12 @@ void sendWindData(byte id, int wind_direction, float wind_gust, byte battery_sta } } -void sendTemperatureData(byte id, float temperature, int humidity, byte battery_status) -{ +void sendTemperatureData(byte id, float temperature, int humidity, byte battery_status) { unsigned long MQTTvalue = 40000 + abs(round(temperature * 100.0)) + humidity; - if (!isAduplicate(MQTTvalue)) - { // conditions to avoid duplications of RF -->MQTT + if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4); StaticJsonBuffer jsonBuffer; - JsonObject &RFdata = jsonBuffer.createObject(); + JsonObject& RFdata = jsonBuffer.createObject(); RFdata.set("sensor", id); RFdata.set("temperature", temperature); RFdata.set("humidity", humidity); @@ -121,38 +111,35 @@ void sendTemperatureData(byte id, float temperature, int humidity, byte battery_ pub(subjectRFtoMQTT, RFdata); Log.trace(F("Store temp val: %lu" CR), MQTTvalue); storeValue(MQTTvalue); - } + } } -void ZgatewayWeatherStationtoMQTT() -{ +void ZgatewayWeatherStationtoMQTT() { char newData = wsdr.readData(); - switch (newData) - { - case 'T': - Log.trace(F("Temperature" CR)); - sendTemperatureData(wsdr.sensorID(), wsdr.readTemperature(), wsdr.readHumidity(), wsdr.batteryStatus()); - break; + switch (newData) { + case 'T': + Log.trace(F("Temperature" CR)); + sendTemperatureData(wsdr.sensorID(), wsdr.readTemperature(), wsdr.readHumidity(), wsdr.batteryStatus()); + break; - case 'S': - Log.trace(F("Wind speed" CR)); - sendWindSpeedData(wsdr.sensorID(), wsdr.readWindSpeed(), wsdr.batteryStatus()); - break; + case 'S': + Log.trace(F("Wind speed" CR)); + sendWindSpeedData(wsdr.sensorID(), wsdr.readWindSpeed(), wsdr.batteryStatus()); + break; - case 'G': - Log.trace(F("Wind direction" CR)); - sendWindData(wsdr.sensorID(), wsdr.readWindDirection(), wsdr.readWindGust(), wsdr.batteryStatus()); - break; + case 'G': + Log.trace(F("Wind direction" CR)); + sendWindData(wsdr.sensorID(), wsdr.readWindDirection(), wsdr.readWindGust(), wsdr.batteryStatus()); + break; - case 'R': - Log.trace(F("Rain volume" CR)); - sendRainData(wsdr.sensorID(), wsdr.readRainVolume(), wsdr.batteryStatus()); - break; + case 'R': + Log.trace(F("Rain volume" CR)); + sendRainData(wsdr.sensorID(), wsdr.readRainVolume(), wsdr.batteryStatus()); + break; - default: - break; + default: + break; } - } #endif diff --git a/main/ZmqttDiscovery.ino b/main/ZmqttDiscovery.ino index 7e9f4065..a7b5b22b 100644 --- a/main/ZmqttDiscovery.ino +++ b/main/ZmqttDiscovery.ino @@ -27,62 +27,57 @@ #ifdef ZmqttDiscovery -String getMacAddress() -{ +String getMacAddress() { uint8_t baseMac[6]; char baseMacChr[13] = {0}; -#if defined(ESP8266) +# if defined(ESP8266) WiFi.macAddress(baseMac); sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]); -#elif defined(ESP32) +# elif defined(ESP32) esp_read_mac(baseMac, ESP_MAC_WIFI_STA); sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]); -#else +# else sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); -#endif +# endif return String(baseMacChr); } -String getUniqueId(String name, String sufix) -{ +String getUniqueId(String name, String sufix) { String uniqueId = (String)getMacAddress() + name + sufix; return String(uniqueId); } -#ifdef ZgatewayBT -void createDiscoveryFromList(char *mac, char *sensorList[][8], int sensorCount) -{ - for (int i = 0; i < sensorCount; i++) - { - Log.trace(F("CreateDiscoverySensor %s" CR),sensorList[i][1]); +# ifdef ZgatewayBT +void createDiscoveryFromList(char* mac, char* sensorList[][8], int sensorCount) { + for (int i = 0; i < sensorCount; i++) { + Log.trace(F("CreateDiscoverySensor %s" CR), sensorList[i][1]); String discovery_topic = String(subjectBTtoMQTT) + "/" + String(mac); String unique_id = String(mac) + "-" + sensorList[i][1]; createDiscovery(sensorList[i][0], - (char *)discovery_topic.c_str(), sensorList[i][1], (char *)unique_id.c_str(), + (char*)discovery_topic.c_str(), sensorList[i][1], (char*)unique_id.c_str(), will_Topic, sensorList[i][3], sensorList[i][4], sensorList[i][5], sensorList[i][6], sensorList[i][7], 0, "", "", false, ""); } } -#endif +# endif -void createDiscovery(char *sensor_type, - char *st_topic, char *s_name, char *unique_id, - char *availability_topic, char *device_class, char *value_template, - char *payload_on, char *payload_off, char *unit_of_meas, +void createDiscovery(char* sensor_type, + char* st_topic, char* s_name, char* unique_id, + char* availability_topic, char* device_class, char* value_template, + char* payload_on, char* payload_off, char* unit_of_meas, int off_delay, - char *payload_available, char *payload_not_avalaible, bool child_device, char *cmd_topic) -{ + char* payload_available, char* payload_not_avalaible, bool child_device, char* cmd_topic) { const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(1); StaticJsonBuffer jsonBuffer; - JsonObject &sensor = jsonBuffer.createObject(); + JsonObject& sensor = jsonBuffer.createObject(); char state_topic[mqtt_topic_max_size]; strcpy(state_topic, mqtt_topic); strcat(state_topic, st_topic); sensor.set("stat_t", state_topic); //state_topic - sensor.set("name", s_name); //name + sensor.set("name", s_name); //name sensor.set("uniq_id", unique_id); //unique_id if (device_class[0]) sensor.set("dev_cla", device_class); //device_class @@ -101,58 +96,55 @@ void createDiscovery(char *sensor_type, if (payload_not_avalaible[0]) sensor.set("pl_not_avail", payload_not_avalaible); //payload_off - if (cmd_topic[0]) - { + if (cmd_topic[0]) { char command_topic[mqtt_topic_max_size]; strcpy(command_topic, mqtt_topic); strcat(command_topic, cmd_topic); sensor.set("cmd_t", command_topic); //command_topic } - if (child_device) - { + if (child_device) { StaticJsonBuffer jsonDeviceBuffer; - JsonObject &device = jsonDeviceBuffer.createObject(); + JsonObject& device = jsonDeviceBuffer.createObject(); device.set("name", gateway_name); device.set("manufacturer", DEVICEMANUFACTURER); device.set("sw_version", OMG_VERSION); - JsonArray &identifiers = device.createNestedArray("identifiers"); + JsonArray& identifiers = device.createNestedArray("identifiers"); identifiers.add(getMacAddress()); sensor.set("device", device); //device sensor is connected to } String topic = String(discovery_Topic) + "/" + String(sensor_type) + "/" + String(unique_id) + "/config"; - pub_custom_topic((char *)topic.c_str(), sensor, true); + pub_custom_topic((char*)topic.c_str(), sensor, true); } -void pubMqttDiscovery() -{ +void pubMqttDiscovery() { Log.trace(F("omgStatusDiscovery" CR)); - createDiscovery("binary_sensor", //set Type - will_Topic, Gateway_Name, (char *)getUniqueId("", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "connectivity", "", //set availability_topic,device_class,value_template, - Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, false, "" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic + createDiscovery("binary_sensor", //set Type + will_Topic, Gateway_Name, (char*)getUniqueId("", "").c_str(), //set state_topic,name,uniqueId + will_Topic, "connectivity", "", //set availability_topic,device_class,value_template, + Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas, + 0, //set off_delay + Gateway_AnnouncementMsg, will_Message, false, "" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic ); - createDiscovery("switch", //set Type - will_Topic, "restart OMG", (char *)getUniqueId("restart", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "", //set availability_topic,device_class,value_template, - "{\"cmd\":\"restart\"}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic + createDiscovery("switch", //set Type + will_Topic, "restart OMG", (char*)getUniqueId("restart", "").c_str(), //set state_topic,name,uniqueId + will_Topic, "", "", //set availability_topic,device_class,value_template, + "{\"cmd\":\"restart\"}", "", "", //set,payload_on,payload_off,unit_of_meas, + 0, //set off_delay + Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic ); - createDiscovery("switch", //set Type - will_Topic, "erase OMG", (char *)getUniqueId("erase", "").c_str(), //set state_topic,name,uniqueId - will_Topic, "", "", //set availability_topic,device_class,value_template, - "{\"cmd\":\"erase\"}", "", "", //set,payload_on,payload_off,unit_of_meas, - 0, //set off_delay - Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic + createDiscovery("switch", //set Type + will_Topic, "erase OMG", (char*)getUniqueId("erase", "").c_str(), //set state_topic,name,uniqueId + will_Topic, "", "", //set availability_topic,device_class,value_template, + "{\"cmd\":\"erase\"}", "", "", //set,payload_on,payload_off,unit_of_meas, + 0, //set off_delay + Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic ); -#ifdef ZsensorBME280 -#define BMEparametersCount 6 +# ifdef ZsensorBME280 +# define BMEparametersCount 6 Log.trace(F("bme280Discovery" CR)); - char *BMEsensor[BMEparametersCount][8] = { + char* BMEsensor[BMEparametersCount][8] = { {"sensor", "tempc", "bme", "temperature", jsonTemp, "", "", "°C"}, {"sensor", "tempf", "bme", "temperature", jsonTempf, "", "", "°F"}, {"sensor", "pa", "bme", "", jsonPa, "", "", "hPa"}, @@ -162,320 +154,314 @@ void pubMqttDiscovery() //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - for (int i = 0; i < BMEparametersCount; i++) - { + for (int i = 0; i < BMEparametersCount; i++) { Log.trace(F("CreateDiscoverySensor" CR)); //trc(BMEsensor[i][1]); createDiscovery(BMEsensor[i][0], - BMETOPIC, BMEsensor[i][1], (char *)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(), + BMETOPIC, BMEsensor[i][1], (char*)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(), will_Topic, BMEsensor[i][3], BMEsensor[i][4], BMEsensor[i][5], BMEsensor[i][6], BMEsensor[i][7], 0, "", "", true, ""); } -#endif +# endif -#ifdef ZsensorHTU21 -#define HTUparametersCount 3 +# ifdef ZsensorHTU21 +# define HTUparametersCount 3 Log.trace(F("htu21Discovery" CR)); - char *HTUsensor[HTUparametersCount][8] = { + char* HTUsensor[HTUparametersCount][8] = { {"sensor", "tempc", "htu", "temperature", jsonTemp, "", "", "°C"}, {"sensor", "tempf", "htu", "temperature", jsonTempf, "", "", "°F"}, {"sensor", "hum", "htu", "humidity", jsonHum, "", "", "%"} //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - for (int i = 0; i < HTUparametersCount; i++) - { + for (int i = 0; i < HTUparametersCount; i++) { Log.trace(F("CreateDiscoverySensor" CR)); //trc(HTUsensor[i][1]); createDiscovery(HTUsensor[i][0], - HTUTOPIC, HTUsensor[i][1], (char *)getUniqueId(HTUsensor[i][1], HTUsensor[i][2]).c_str(), + HTUTOPIC, HTUsensor[i][1], (char*)getUniqueId(HTUsensor[i][1], HTUsensor[i][2]).c_str(), will_Topic, HTUsensor[i][3], HTUsensor[i][4], HTUsensor[i][5], HTUsensor[i][6], HTUsensor[i][7], 0, "", "", true, ""); } -#endif +# endif -#ifdef ZsensorDHT -#define DHTparametersCount 2 +# ifdef ZsensorDHT +# define DHTparametersCount 2 Log.trace(F("DHTDiscovery" CR)); - char *DHTsensor[DHTparametersCount][8] = { + char* DHTsensor[DHTparametersCount][8] = { {"sensor", "tempc", "dht", "temperature", jsonTemp, "", "", "°C"}, {"sensor", "hum", "dht", "humidity", jsonHum, "", "", "%"}}; - for (int i = 0; i < DHTparametersCount; i++) - { + for (int i = 0; i < DHTparametersCount; i++) { Log.trace(F("CreateDiscoverySensor" CR)); //trc(DHTsensor[i][1]); createDiscovery(DHTsensor[i][0], - DHTTOPIC, DHTsensor[i][1], (char *)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(), + DHTTOPIC, DHTsensor[i][1], (char*)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(), will_Topic, DHTsensor[i][3], DHTsensor[i][4], DHTsensor[i][5], DHTsensor[i][6], DHTsensor[i][7], 0, "", "", true, ""); } -#endif +# endif -#ifdef ZsensorADC +# ifdef ZsensorADC Log.trace(F("ADCDiscovery" CR)); - char *ADCsensor[8] = {"sensor", "adc", "", "", jsonAdc, "", "", ""}; + char* ADCsensor[8] = {"sensor", "adc", "", "", jsonAdc, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(ADCsensor[1]); createDiscovery(ADCsensor[0], - ADCTOPIC, ADCsensor[1], (char *)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(), + ADCTOPIC, ADCsensor[1], (char*)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(), will_Topic, ADCsensor[3], ADCsensor[4], ADCsensor[5], ADCsensor[6], ADCsensor[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZsensorBH1750 -#define BH1750parametersCount 3 +# ifdef ZsensorBH1750 +# define BH1750parametersCount 3 Log.trace(F("BH1750Discovery" CR)); - char *BH1750sensor[BH1750parametersCount][8] = { + char* BH1750sensor[BH1750parametersCount][8] = { {"sensor", "lux", "BH1750", "illuminance", jsonLux, "", "", "lu"}, {"sensor", "ftCd", "BH1750", "", jsonFtcd, "", "", ""}, {"sensor", "wattsm2", "BH1750", "", jsonWm2, "", "", "wm²"} //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - for (int i = 0; i < BH1750parametersCount; i++) - { + for (int i = 0; i < BH1750parametersCount; i++) { Log.trace(F("CreateDiscoverySensor" CR)); //trc(BH1750sensor[i][1]); createDiscovery(BH1750sensor[i][0], - subjectBH1750toMQTT, BH1750sensor[i][1], (char *)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(), + subjectBH1750toMQTT, BH1750sensor[i][1], (char*)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(), will_Topic, BH1750sensor[i][3], BH1750sensor[i][4], BH1750sensor[i][5], BH1750sensor[i][6], BH1750sensor[i][7], 0, "", "", true, ""); } -#endif +# endif -#ifdef ZsensorTSL2561 -#define TSL2561parametersCount 3 +# ifdef ZsensorTSL2561 +# define TSL2561parametersCount 3 Log.trace(F("TSL2561Discovery" CR)); - char *TSL2561sensor[TSL2561parametersCount][8] = { + char* TSL2561sensor[TSL2561parametersCount][8] = { {"sensor", "lux", "TSL2561", "illuminance", jsonLux, "", "", "lu"}, {"sensor", "ftcd", "TSL2561", "", jsonFtcd, "", "", ""}, {"sensor", "wattsm2", "TSL2561", "", jsonWm2, "", "", "wm²"} //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - for (int i = 0; i < TSL2561parametersCount; i++) - { + for (int i = 0; i < TSL2561parametersCount; i++) { Log.trace(F("CreateDiscoverySensor" CR)); //trc(TSL2561sensor[i][1]); createDiscovery(TSL2561sensor[i][0], - subjectTSL12561toMQTT, TSL2561sensor[i][1], (char *)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(), + subjectTSL12561toMQTT, TSL2561sensor[i][1], (char*)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(), will_Topic, TSL2561sensor[i][3], TSL2561sensor[i][4], TSL2561sensor[i][5], TSL2561sensor[i][6], TSL2561sensor[i][7], 0, "", "", true, ""); } -#endif +# endif -#ifdef ZsensorHCSR501 +# ifdef ZsensorHCSR501 Log.trace(F("HCSR501Discovery" CR)); - char *HCSR501sensor[8] = {"binary_sensor", "hcsr501", "", "", jsonPresence, "true", "false", ""}; + char* HCSR501sensor[8] = {"binary_sensor", "hcsr501", "", "", jsonPresence, "true", "false", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(HCSR501sensor[1]); createDiscovery(HCSR501sensor[0], - subjectHCSR501toMQTT, HCSR501sensor[1], (char *)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(), + subjectHCSR501toMQTT, HCSR501sensor[1], (char*)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(), will_Topic, HCSR501sensor[3], HCSR501sensor[4], HCSR501sensor[5], HCSR501sensor[6], HCSR501sensor[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZsensorGPIOInput +# ifdef ZsensorGPIOInput Log.trace(F("GPIOInputDiscovery" CR)); - char *GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "", "", jsonGpio, "HIGH", "LOW", ""}; + char* GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "", "", jsonGpio, "HIGH", "LOW", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(GPIOInputsensor[1]); createDiscovery(GPIOInputsensor[0], - subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char *)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(), + subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char*)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(), will_Topic, GPIOInputsensor[3], GPIOInputsensor[4], GPIOInputsensor[5], GPIOInputsensor[6], GPIOInputsensor[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZsensorINA226 -#define INA226parametersCount 3 +# ifdef ZsensorINA226 +# define INA226parametersCount 3 Log.trace(F("INA226Discovery" CR)); - char *INA226sensor[INA226parametersCount][8] = { + char* INA226sensor[INA226parametersCount][8] = { {"sensor", "volt", "INA226", "", jsonVolt, "", "", "V"}, {"sensor", "current", "INA226", "", jsonCurrent, "", "", "A"}, {"sensor", "power", "INA226", "", jsonPower, "", "", "W"} //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - for (int i = 0; i < INA226parametersCount; i++) - { + for (int i = 0; i < INA226parametersCount; i++) { Log.trace(F("CreateDiscoverySensor" CR)); //trc(INA226sensor[i][1]); createDiscovery(INA226sensor[i][0], - subjectINA226toMQTT, INA226sensor[i][1], (char *)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(), + subjectINA226toMQTT, INA226sensor[i][1], (char*)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(), will_Topic, INA226sensor[i][3], INA226sensor[i][4], INA226sensor[i][5], INA226sensor[i][6], INA226sensor[i][7], 0, "", "", true, ""); } -#endif +# endif -#ifdef ZsensorDS1820 +# ifdef ZsensorDS1820 // Publish any DS1820 sensors found on the OneWire bus pubOneWire_HADiscovery(); -#endif +# endif -#ifdef ZactuatorONOFF +# ifdef ZactuatorONOFF Log.trace(F("actuatorONOFFDiscovery" CR)); - char *actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "", "", "{\"cmd\":1}", "{\"cmd\":0}", ""}; + char* actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "", "", "{\"cmd\":1}", "{\"cmd\":0}", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(actuatorONOFF[1]); createDiscovery(actuatorONOFF[0], - subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char *)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(), + subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char*)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(), will_Topic, actuatorONOFF[3], actuatorONOFF[4], actuatorONOFF[5], actuatorONOFF[6], actuatorONOFF[7], 0, "", "", true, subjectMQTTtoONOFF); -#endif +# endif -#ifdef ZgatewayRF +# ifdef ZgatewayRF // Sensor to display RF received value Log.trace(F("gatewayRFDiscovery" CR)); - char *gatewayRF[8] = {"sensor", "gatewayRF", "", "", jsonVal, "", "", ""}; + char* gatewayRF[8] = {"sensor", "gatewayRF", "", "", jsonVal, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayRF[1]); createDiscovery(gatewayRF[0], - subjectRFtoMQTT, gatewayRF[1], (char *)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(), + subjectRFtoMQTT, gatewayRF[1], (char*)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(), will_Topic, gatewayRF[3], gatewayRF[4], gatewayRF[5], gatewayRF[6], gatewayRF[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewayRF2 +# ifdef ZgatewayRF2 // Sensor to display RF received value Log.trace(F("gatewayRF2Discovery" CR)); - char *gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", jsonVal, "", "", ""}; + char* gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", jsonVal, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayRF2[1]); createDiscovery(gatewayRF2[0], - subjectRF2toMQTT, gatewayRF2[1], (char *)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(), + subjectRF2toMQTT, gatewayRF2[1], (char*)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(), will_Topic, gatewayRF2[3], gatewayRF2[4], gatewayRF2[5], gatewayRF2[6], gatewayRF2[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewayRFM69 +# ifdef ZgatewayRFM69 // Sensor to display RF received value Log.trace(F("gatewayRFM69Discovery" CR)); - char *gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", jsonVal, "", "", ""}; + char* gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", jsonVal, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayRFM69[1]); createDiscovery(gatewayRFM69[0], - subjectRFM69toMQTT, gatewayRFM69[1], (char *)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(), + subjectRFM69toMQTT, gatewayRFM69[1], (char*)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(), will_Topic, gatewayRFM69[3], gatewayRFM69[4], gatewayRFM69[5], gatewayRFM69[6], gatewayRFM69[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewayLORA +# ifdef ZgatewayLORA // Sensor to display RF received value Log.trace(F("gatewayLORADiscovery" CR)); - char *gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", jsonMsg, "", "", ""}; + char* gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", jsonMsg, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayLORA[1]); createDiscovery(gatewayLORA[0], - subjectLORAtoMQTT, gatewayLORA[1], (char *)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(), + subjectLORAtoMQTT, gatewayLORA[1], (char*)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(), will_Topic, gatewayLORA[3], gatewayLORA[4], gatewayLORA[5], gatewayLORA[6], gatewayLORA[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewaySRFB +# ifdef ZgatewaySRFB // Sensor to display RF received value Log.trace(F("gatewaySRFBDiscovery" CR)); - char *gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", jsonVal, "", "", ""}; + char* gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", jsonVal, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewaySRFB[1]); createDiscovery(gatewaySRFB[0], - subjectSRFBtoMQTT, gatewaySRFB[1], (char *)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(), + subjectSRFBtoMQTT, gatewaySRFB[1], (char*)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(), will_Topic, gatewaySRFB[3], gatewaySRFB[4], gatewaySRFB[5], gatewaySRFB[6], gatewaySRFB[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewayPilight +# ifdef ZgatewayPilight // Sensor to display RF received value Log.trace(F("gatewayPilightDiscovery" CR)); - char *gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", jsonMsg, "", "", ""}; + char* gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", jsonMsg, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayPilight[1]); createDiscovery(gatewayPilight[0], - subjectPilighttoMQTT, gatewayPilight[1], (char *)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(), + subjectPilighttoMQTT, gatewayPilight[1], (char*)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(), will_Topic, gatewayPilight[3], gatewayPilight[4], gatewayPilight[5], gatewayPilight[6], gatewayPilight[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewayIR +# ifdef ZgatewayIR // Sensor to display IR received value Log.trace(F("gatewayIRDiscovery" CR)); - char *gatewayIR[8] = {"sensor", "gatewayIR", "", "", jsonVal, "", "", ""}; + char* gatewayIR[8] = {"sensor", "gatewayIR", "", "", jsonVal, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayIR[1]); createDiscovery(gatewayIR[0], - subjectIRtoMQTT, gatewayIR[1], (char *)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(), + subjectIRtoMQTT, gatewayIR[1], (char*)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(), will_Topic, gatewayIR[3], gatewayIR[4], gatewayIR[5], gatewayIR[6], gatewayIR[7], 0, "", "", true, ""); -#endif +# endif -#ifdef Zgateway2G +# ifdef Zgateway2G // Sensor to display 2G received value Log.trace(F("gateway2GDiscovery" CR)); - char *gateway2G[8] = {"sensor", "gateway2G", "", "", jsonMsg, "", "", ""}; + char* gateway2G[8] = {"sensor", "gateway2G", "", "", jsonMsg, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gateway2G[1]); createDiscovery(gateway2G[0], - subject2GtoMQTT, gateway2G[1], (char *)getUniqueId(gateway2G[1], gateway2G[2]).c_str(), + subject2GtoMQTT, gateway2G[1], (char*)getUniqueId(gateway2G[1], gateway2G[2]).c_str(), will_Topic, gateway2G[3], gateway2G[4], gateway2G[5], gateway2G[6], gateway2G[7], 0, "", "", true, ""); -#endif +# endif -#ifdef ZgatewayBT +# ifdef ZgatewayBT // Sensor to display BT received value Log.trace(F("gatewayBTDiscovery" CR)); - char *gatewayBT[8] = {"sensor", "gatewayBT", "", "", jsonId, "", "", ""}; + char* gatewayBT[8] = {"sensor", "gatewayBT", "", "", jsonId, "", "", ""}; //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement Log.trace(F("CreateDiscoverySensor" CR)); //trc(gatewayBT[1]); createDiscovery(gatewayBT[0], - subjectBTtoMQTT, gatewayBT[1], (char *)getUniqueId(gatewayBT[1], gatewayBT[2]).c_str(), + subjectBTtoMQTT, gatewayBT[1], (char*)getUniqueId(gatewayBT[1], gatewayBT[2]).c_str(), will_Topic, gatewayBT[3], gatewayBT[4], gatewayBT[5], gatewayBT[6], gatewayBT[7], 0, "", "", true, ""); -#endif +# endif } #endif diff --git a/main/ZsensorADC.ino b/main/ZsensorADC.ino index 3be67a1a..49e5f583 100644 --- a/main/ZsensorADC.ino +++ b/main/ZsensorADC.ino @@ -30,40 +30,33 @@ #ifdef ZsensorADC -#if defined(ESP8266) +# if defined(ESP8266) ADC_MODE(ADC_TOUT); -#endif +# endif //Time used to wait for an interval before resending adc value unsigned long timeadc = 0; -void setupADC() -{ +void setupADC() { Log.notice(F("Reading ADC on pin: %d" CR), ADC_PIN); } -void MeasureADC() -{ - if (millis() > (timeadc + TimeBetweenReadingADC)) - { //retrieving value of temperature and humidity of the box from DHT every xUL -#if defined(ESP8266) +void MeasureADC() { + if (millis() > (timeadc + TimeBetweenReadingADC)) { //retrieving value of temperature and humidity of the box from DHT every xUL +# if defined(ESP8266) yield(); -#endif +# endif timeadc = millis(); static int persistedadc; int val = analogRead(ADC_PIN); - if (isnan(val)) - { + if (isnan(val)) { Log.error(F("Failed to read from ADC !" CR)); - } - else - { - if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC) - { + } else { + if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC) { Log.trace(F("Creating ADC buffer" CR)); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1); StaticJsonBuffer jsonBuffer; - JsonObject &ADCdata = jsonBuffer.createObject(); + JsonObject& ADCdata = jsonBuffer.createObject(); ADCdata.set("adc", (int)val); pub(ADCTOPIC, ADCdata); persistedadc = val; diff --git a/main/ZsensorBH1750.ino b/main/ZsensorBH1750.ino index ef9f7ede..9a723707 100644 --- a/main/ZsensorBH1750.ino +++ b/main/ZsensorBH1750.ino @@ -39,11 +39,10 @@ #include "User_config.h" #ifdef ZsensorBH1750 -#include "math.h" // Library for trig and exponential functions -#include "Wire.h" // Library for communication with I2C / TWI devices +# include "Wire.h" // Library for communication with I2C / TWI devices +# include "math.h" // Library for trig and exponential functions -void setupZsensorBH1750() -{ +void setupZsensorBH1750() { Log.notice(F("Setup BH1750 on adress: %H" CR), BH1750_i2c_addr); Wire.begin(); Wire.beginTransmission(BH1750_i2c_addr); @@ -52,14 +51,11 @@ void setupZsensorBH1750() delay(300); } -// void loop() -void MeasureLightIntensity() -{ - if (millis() > (timebh1750 + TimeBetweenReadingBH1750)) - { //retrieving value of Lux, FtCd and Wattsm2 from BH1750 +void MeasureLightIntensity() { + if (millis() > (timebh1750 + TimeBetweenReadingBH1750)) { //retrieving value of Lux, FtCd and Wattsm2 from BH1750 Log.trace(F("Creating BH1750 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &BH1750data = jsonBuffer.createObject(); + JsonObject& BH1750data = jsonBuffer.createObject(); timebh1750 = millis(); unsigned int i = 0; @@ -72,12 +68,9 @@ void MeasureLightIntensity() // Check if reads failed and exit early (to try again). Wire.requestFrom(BH1750_i2c_addr, 2); - if (Wire.available() != 2) - { + if (Wire.available() != 2) { Log.error(F("Failed to read from LightSensor BH1750!" CR)); - } - else - { + } else { i = Wire.read(); i <<= 8; i |= Wire.read(); @@ -88,32 +81,23 @@ void MeasureLightIntensity() Wattsm2 = Lux / 683.0; // Generate Lux - if (Lux != persistedll || bh1750_always) - { + if (Lux != persistedll || bh1750_always) { BH1750data.set("lux", (unsigned int)Lux); - } - else - { + } else { Log.trace(F("Same lux don't send it" CR)); } // Generate FtCd - if (ftcd != persistedlf || bh1750_always) - { + if (ftcd != persistedlf || bh1750_always) { BH1750data.set("ftcd", (unsigned int)ftcd); - } - else - { + } else { Log.trace(F("Same ftcd don't send it" CR)); } // Generate Watts/m2 - if (Wattsm2 != persistedlw || bh1750_always) - { + if (Wattsm2 != persistedlw || bh1750_always) { BH1750data.set("wattsm2", (unsigned int)Wattsm2); - } - else - { + } else { Log.trace(F("Same wattsm2 don't send it" CR)); } if (BH1750data.size() > 0) diff --git a/main/ZsensorBME280.ino b/main/ZsensorBME280.ino index 9dfcc595..800b2f60 100644 --- a/main/ZsensorBME280.ino +++ b/main/ZsensorBME280.ino @@ -40,17 +40,17 @@ #include "User_config.h" #ifdef ZsensorBME280 -#include "Wire.h" // Library for communication with I2C / TWI devices -#include -#include "SparkFunBME280.h" +# include + +# include "SparkFunBME280.h" +# include "Wire.h" // Library for communication with I2C / TWI devices //Global sensor object BME280 mySensor; -void setupZsensorBME280() -{ +void setupZsensorBME280() { mySensor.settings.commInterface = I2C_MODE; - mySensor.settings.I2CAddress = BME280_i2c_addr; + mySensor.settings.I2CAddress = BME280_i2c_addr; Log.notice(F("Setup BME280 on adress: %H" CR), BME280_i2c_addr); //***Operation settings*****************************// @@ -101,15 +101,11 @@ void setupZsensorBME280() mySensor.settings.humidOverSample = 1; delay(10); // Gives the Sensor enough time to turn on (The BME280 requires 2ms to start up) - Log.notice(F("Bosch BME280 Initialized - Result of .begin(): 0x %h" CR),mySensor.begin()); + Log.notice(F("Bosch BME280 Initialized - Result of .begin(): 0x %h" CR), mySensor.begin()); } -void MeasureTempHumAndPressure() -{ - - if (millis() > (timebme280 + TimeBetweenReadingbme280)) - { - +void MeasureTempHumAndPressure() { + if (millis() > (timebme280 + TimeBetweenReadingbme280)) { timebme280 = millis(); static float persisted_bme_tempc; static float persisted_bme_tempf; @@ -126,73 +122,52 @@ void MeasureTempHumAndPressure() float BmeAltiFt = mySensor.readFloatAltitudeFeet(); // Check if reads failed and exit early (to try again). - if (isnan(BmeTempC) || isnan(BmeTempF) || isnan(BmeHum) || isnan(BmePa) || isnan(BmeAltiM) || isnan(BmeAltiFt)) - { + if (isnan(BmeTempC) || isnan(BmeTempF) || isnan(BmeHum) || isnan(BmePa) || isnan(BmeAltiM) || isnan(BmeAltiFt)) { Log.error(F("Failed to read from BME280!" CR)); - } - else - { + } else { Log.trace(F("Creating BME280 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &BME280data = jsonBuffer.createObject(); + JsonObject& BME280data = jsonBuffer.createObject(); // Generate Temperature in degrees C - if (BmeTempC != persisted_bme_tempc || bme280_always) - { + if (BmeTempC != persisted_bme_tempc || bme280_always) { BME280data.set("tempc", (float)BmeTempC); - } - else - { + } else { Log.trace(F("Same Degrees C don't send it" CR)); } // Generate Temperature in degrees F - if (BmeTempF != persisted_bme_tempf || bme280_always) - { + if (BmeTempF != persisted_bme_tempf || bme280_always) { BME280data.set("tempf", (float)BmeTempF); - } - else - { + } else { Log.trace(F("Same Degrees F don't send it" CR)); } // Generate Humidity in percent - if (BmeHum != persisted_bme_hum || bme280_always) - { + if (BmeHum != persisted_bme_hum || bme280_always) { BME280data.set("hum", (float)BmeHum); - } - else - { + } else { Log.trace(F("Same Humidity don't send it" CR)); } // Generate Pressure in Pa - if (BmePa != persisted_bme_pa || bme280_always) - { + if (BmePa != persisted_bme_pa || bme280_always) { BME280data.set("pa", (float)BmePa); - } - else - { + } else { Log.trace(F("Same Pressure don't send it" CR)); } // Generate Altitude in Meter - if (BmeAltiM != persisted_bme_altim || bme280_always) - { + if (BmeAltiM != persisted_bme_altim || bme280_always) { Log.trace(F("Sending Altitude Meter to MQTT" CR)); BME280data.set("altim", (float)BmeAltiM); - } - else - { + } else { Log.trace(F("Same Altitude Meter don't send it" CR)); } // Generate Altitude in Feet - if (BmeAltiFt != persisted_bme_altift || bme280_always) - { + if (BmeAltiFt != persisted_bme_altift || bme280_always) { BME280data.set("altift", (float)BmeAltiFt); - } - else - { + } else { Log.trace(F("Same Altitude Feet don't send it" CR)); } if (BME280data.size() > 0) diff --git a/main/ZsensorDHT.ino b/main/ZsensorDHT.ino index 49225ab1..e18eb764 100644 --- a/main/ZsensorDHT.ino +++ b/main/ZsensorDHT.ino @@ -30,23 +30,20 @@ #include "User_config.h" #ifdef ZsensorDHT -#include -#include +# include +# include DHT dht(DHT_RECEIVER_PIN, DHT_SENSOR_TYPE); //Time used to wait for an interval before resending temp and hum unsigned long timedht = 0; -void setupDHT() -{ +void setupDHT() { Log.notice(F("Reading DHT on pin: %d" CR), DHT_RECEIVER_PIN); } -void MeasureTempAndHum() -{ - if (millis() > (timedht + TimeBetweenReadingDHT)) - { //retrieving value of temperature and humidity of the box from DHT every xUL +void MeasureTempAndHum() { + if (millis() > (timedht + TimeBetweenReadingDHT)) { //retrieving value of temperature and humidity of the box from DHT every xUL timedht = millis(); static float persistedh; static float persistedt; @@ -54,29 +51,20 @@ void MeasureTempAndHum() // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Check if any reads failed and exit early (to try again). - if (isnan(h) || isnan(t)) - { + if (isnan(h) || isnan(t)) { Log.error(F("Failed to read from DHT sensor!" CR)); - } - else - { + } else { Log.trace(F("Creating DHT buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &DHTdata = jsonBuffer.createObject(); - if (h != persistedh || dht_always) - { + JsonObject& DHTdata = jsonBuffer.createObject(); + if (h != persistedh || dht_always) { DHTdata.set("hum", (float)h); - } - else - { + } else { Log.trace(F("Same hum don't send it" CR)); } - if (t != persistedt || dht_always) - { + if (t != persistedt || dht_always) { DHTdata.set("temp", (float)t); - } - else - { + } else { Log.trace(F("Same temp don't send it" CR)); } if (DHTdata.size() > 0) diff --git a/main/ZsensorDS1820.ino b/main/ZsensorDS1820.ino index 3ebc66a9..60622313 100644 --- a/main/ZsensorDS1820.ino +++ b/main/ZsensorDS1820.ino @@ -26,8 +26,8 @@ #include "User_config.h" #ifdef ZsensorDS1820 -#include -#include +# include +# include OneWire owbus(DS1820_OWBUS_PIN); DallasTemperature ds1820(&owbus); @@ -38,10 +38,8 @@ static uint8_t ds1820_resolution[OW_MAX_SENSORS]; static String ds1820_type[OW_MAX_SENSORS]; static String ds1820_addr[OW_MAX_SENSORS]; - -void setupZsensorDS1820() -{ - Log.trace(F("DS1820: configured pin: %d for 1-wire bus" CR), DS1820_OWBUS_PIN ); +void setupZsensorDS1820() { + Log.trace(F("DS1820: configured pin: %d for 1-wire bus" CR), DS1820_OWBUS_PIN); ds1820.begin(); // Search the OneWire bus for all devices @@ -51,57 +49,46 @@ void setupZsensorDS1820() Log.notice(F("DS1820: Found %d devices" CR), numDevicesOnBus); // Cycle though all of the devices on the OneWire bus - for (int deviceIndex = 0; deviceIndex < numDevicesOnBus && ds1820_count < OW_MAX_SENSORS; deviceIndex++) - { + for (int deviceIndex = 0; deviceIndex < numDevicesOnBus && ds1820_count < OW_MAX_SENSORS; deviceIndex++) { // get the next device on the OneWire bus and confirm it is a sensor the library can handle (Dallas DS18X20 1-wire devices) - if ( ds1820.getAddress(ds1820_address, deviceIndex) && ds1820.validFamily(ds1820_address) ) - { + if (ds1820.getAddress(ds1820_address, deviceIndex) && ds1820.validFamily(ds1820_address)) { ds1820_addr[ds1820_count] = String("0x"); - for (uint8_t i = 0; i < 8; i++) - { + for (uint8_t i = 0; i < 8; i++) { if (ds1820_address[i] < 0x10) ds1820_addr[ds1820_count] += String("0"); ds1820_devices[ds1820_count][i] = ds1820_address[i]; ds1820_addr[ds1820_count] += String(ds1820_address[i], HEX); - } - + } + // set the resolution and thus conversion timing - if (ds1820_address[0] == 0x10) - { + if (ds1820_address[0] == 0x10) { // DS1820/DS18S20 have no resolution configuration register, - // both have a 9-bit temperature register. Resolutions greater - // than 9-bit can be calculated using the data from the temperature, + // both have a 9-bit temperature register. Resolutions greater + // than 9-bit can be calculated using the data from the temperature, // and COUNT REMAIN and COUNT PER °C registers in the scratchpad. // The resolution of the calculation depends on the model. - ds1820_type[ds1820_count] = String("DS1820/DS18S20"); - } - else if (ds1820_address[0] == 0x28) - { + ds1820_type[ds1820_count] = String("DS1820/DS18S20"); + } else if (ds1820_address[0] == 0x28) { // DS18B20 and 18B22 are capable of different resolutions (9-12 bit) ds1820_type[ds1820_count] = String("DS18B20"); ds1820.setResolution(ds1820_address, DS1820_RESOLUTION); - } - else if (ds1820_address[0] == 0x22) - { + } else if (ds1820_address[0] == 0x22) { ds1820_type[ds1820_count] = String("DS1822"); ds1820.setResolution(ds1820_address, DS1820_RESOLUTION); - } - else - { + } else { ds1820_type[ds1820_count] = String("DS1825"); ds1820.setResolution(ds1820_address, DS1820_RESOLUTION); - } + } ds1820_resolution[ds1820_count] = ds1820.getResolution(ds1820_address); Log.trace(F("DS1820: Device %d, Type: %s, Address: %s, Resolution: %d" CR), - ds1820_count, - (char *)ds1820_type[ds1820_count].c_str(), - (char *)ds1820_addr[ds1820_count].c_str(), - ds1820_resolution[ds1820_count]); + ds1820_count, + (char*)ds1820_type[ds1820_count].c_str(), + (char*)ds1820_addr[ds1820_count].c_str(), + ds1820_resolution[ds1820_count]); ds1820_count++; } } - - if (ds1820.getDS18Count() == 0) - { + + if (ds1820.getDS18Count() == 0) { Log.error(F("DS1820: Failed to enumerate sensors on 1-wire bus. Check your pin assignment!" CR)); } @@ -110,103 +97,88 @@ void setupZsensorDS1820() ds1820.setWaitForConversion(false); } -void pubOneWire_HADiscovery() -{ +void pubOneWire_HADiscovery() { // If zmqttDiscovery is enabled, create a sensor topic for each DS18b20 sensor found on the bus, using addr as uniqueID -#ifdef ZmqttDiscovery +# ifdef ZmqttDiscovery Log.notice(F("CreateDiscoverySensor - Found %d" CR), ds1820_count); - for (int index=0; index (timeDS1820 + (DS1820_INTERVAL_SEC*1000) - DS1820_CONV_TIME))) - { + if (!triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC * 1000) - DS1820_CONV_TIME))) { Log.trace(F("DS1820: Trigger temperature conversion..." CR)); ds1820.requestTemperatures(); triggeredConversion = true; - } - else if (triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC*1000)))) - { + } else if (triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC * 1000)))) { timeDS1820 = millis(); triggeredConversion = false; - - if (ds1820_count < 1) - { + + if (ds1820_count < 1) { Log.error(F("DS1820: Failed to identify any temperature sensors on 1-wire bus during setup!" CR)); - } - else - { + } else { Log.trace(F("DS1820: Reading temperature(s) from %d sensor(s)..." CR), ds1820_count); StaticJsonBuffer jsonBuffer; - JsonObject &DS1820data = jsonBuffer.createObject(); + JsonObject& DS1820data = jsonBuffer.createObject(); - for (uint8_t i=0; i < ds1820_count; i++) - { - current_temp[i] = round(ds1820.getTempC(ds1820_devices[i])*10)/10.0; - if (current_temp[i] == -127) - { - Log.error(F("DS1820: Device %s currently disconnected!" CR), (char *)ds1820_addr[i].c_str() ); - } - else if (DS1820_ALWAYS || current_temp[i] != persisted_temp[i]) - { + for (uint8_t i = 0; i < ds1820_count; i++) { + current_temp[i] = round(ds1820.getTempC(ds1820_devices[i]) * 10) / 10.0; + if (current_temp[i] == -127) { + Log.error(F("DS1820: Device %s currently disconnected!" CR), (char*)ds1820_addr[i].c_str()); + } else if (DS1820_ALWAYS || current_temp[i] != persisted_temp[i]) { if (DS1820_FAHRENHEIT) { - Log.notice(F("DS1820: Temperature %s %d F" CR), - (char *)ds1820_addr[i].c_str(), - DallasTemperature::toFahrenheit(current_temp[i])); + Log.notice(F("DS1820: Temperature %s %d F" CR), + (char*)ds1820_addr[i].c_str(), + DallasTemperature::toFahrenheit(current_temp[i])); DS1820data.set("temp", (float)DallasTemperature::toFahrenheit(current_temp[i])); DS1820data.set("unit", "F"); } else { - Log.notice(F("DS1820: Temperature %s %d C" CR), - (char *)ds1820_addr[i].c_str(), - current_temp[i]); + Log.notice(F("DS1820: Temperature %s %d C" CR), + (char*)ds1820_addr[i].c_str(), + current_temp[i]); DS1820data.set("temp", (float)DallasTemperature::toFahrenheit(current_temp[i])); DS1820data.set("unit", "F"); DS1820data.set("temp", (float)current_temp[i]); DS1820data.set("unit", "C"); } - if (DS1820_DETAILS) { + if (DS1820_DETAILS) { DS1820data.set("type", ds1820_type[i]); DS1820data.set("res", ds1820_resolution[i] + String("bit" CR)); DS1820data.set("addr", ds1820_addr[i]); } - pub((char *)(String(OW_TOPIC) + "/" + ds1820_addr[i]).c_str(), DS1820data); + pub((char*)(String(OW_TOPIC) + "/" + ds1820_addr[i]).c_str(), DS1820data); delay(10); - } - else - { - Log.trace(F("DS1820: Temperature for device %s didn't change, don't publish it." CR), (char *)ds1820_addr[i].c_str()); + } else { + Log.trace(F("DS1820: Temperature for device %s didn't change, don't publish it." CR), (char*)ds1820_addr[i].c_str()); } persisted_temp[i] = current_temp[i]; } diff --git a/main/ZsensorGPIOInput.ino b/main/ZsensorGPIOInput.ino index a6832e93..f8b9e4c0 100644 --- a/main/ZsensorGPIOInput.ino +++ b/main/ZsensorGPIOInput.ino @@ -34,14 +34,12 @@ unsigned long lastDebounceTime = 0; int InputState = 3; // Set to 3 so that it reads on startup int lastInputState = 3; -void setupGPIOInput() -{ +void setupGPIOInput() { Log.notice(F("Reading GPIO at pin: %d" CR), GPIOInput_PIN); pinMode(GPIOInput_PIN, INPUT_PULLUP); // declare GPIOInput pin as input_pullup to prevent floating. Pin will be high when not connected to ground } -void MeasureGPIOInput() -{ +void MeasureGPIOInput() { int reading = digitalRead(GPIOInput_PIN); // check to see if you just pressed the button @@ -49,33 +47,28 @@ void MeasureGPIOInput() // since the last press to ignore any noise: // If the switch changed, due to noise or pressing: - if (reading != lastInputState) - { + if (reading != lastInputState) { // reset the debouncing timer lastDebounceTime = millis(); } - if ((millis() - lastDebounceTime) > GPIOInputDebounceDelay) - { + if ((millis() - lastDebounceTime) > GPIOInputDebounceDelay) { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) yield(); -#endif +# endif // if the Input state has changed: - if (reading != InputState) - { + if (reading != InputState) { InputState = reading; Log.trace(F("Creating GPIOInput buffer" CR)); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1); StaticJsonBuffer jsonBuffer; - JsonObject &GPIOdata = jsonBuffer.createObject(); - if (InputState == HIGH) - { + JsonObject& GPIOdata = jsonBuffer.createObject(); + if (InputState == HIGH) { GPIOdata.set("gpio", "HIGH"); } - if (InputState == LOW) - { + if (InputState == LOW) { GPIOdata.set("gpio", "LOW"); } if (GPIOdata.size() > 0) diff --git a/main/ZsensorGPIOKeyCode.ino b/main/ZsensorGPIOKeyCode.ino index ba22f713..2a982b3d 100644 --- a/main/ZsensorGPIOKeyCode.ino +++ b/main/ZsensorGPIOKeyCode.ino @@ -31,18 +31,15 @@ int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on startup int lastInputStateGPIOKeyCode = 0x0f; int lastLatchStateGPIOKeyCode = 0; -void setupGPIOKeyCode() -{ +void setupGPIOKeyCode() { pinMode(GPIOKeyCode_LATCH_PIN, INPUT_PULLUP); // - pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); // - pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); // - pinMode(GPIOKeyCode_D2_PIN, INPUT_PULLUP); // + pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); // + pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); // + pinMode(GPIOKeyCode_D2_PIN, INPUT_PULLUP); // //pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); // } -void MeasureGPIOKeyCode() -{ - +void MeasureGPIOKeyCode() { int latch = digitalRead(GPIOKeyCode_LATCH_PIN); // check to see if you just pressed the button @@ -52,12 +49,11 @@ void MeasureGPIOKeyCode() { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: -#if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) yield(); -#endif +# endif // if the Input state has changed: - if (latch > 0 && lastLatchStateGPIOKeyCode != latch) - { + if (latch > 0 && lastLatchStateGPIOKeyCode != latch) { int reading = digitalRead(GPIOKeyCode_D0_PIN) | (digitalRead(GPIOKeyCode_D1_PIN) << 1) | (digitalRead(GPIOKeyCode_D2_PIN) << 2); //| digitalRead(GPIOKeyCode_D3_PIN) << 3; @@ -71,8 +67,7 @@ void MeasureGPIOKeyCode() lastLatchStateGPIOKeyCode = latch; } - if (latch != lastLatchStateGPIOKeyCode) - { + if (latch != lastLatchStateGPIOKeyCode) { lastLatchStateGPIOKeyCode = latch; Log.notice(F("GPIOKeyCode latch %d" CR), latch); if (latch == 0) diff --git a/main/ZsensorHCSR04.ino b/main/ZsensorHCSR04.ino index 7ea5e25c..229cdc0a 100644 --- a/main/ZsensorHCSR04.ino +++ b/main/ZsensorHCSR04.ino @@ -33,49 +33,38 @@ unsigned long timeHCSR04 = 0; -void setupHCSR04() -{ +void setupHCSR04() { Log.notice(F("HCSR04 trigger pin: %d" CR), HCSR04_TRI_PIN); Log.notice(F("HCSR04 echo pin: %d" CR), HCSR04_ECH_PIN); pinMode(HCSR04_TRI_PIN, OUTPUT); // declare HC SR-04 trigger pin as output - pinMode(HCSR04_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input + pinMode(HCSR04_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input } -void MeasureDistance() -{ - if (millis() > (timeHCSR04 + TimeBetweenReadingHCSR04)) - { +void MeasureDistance() { + if (millis() > (timeHCSR04 + TimeBetweenReadingHCSR04)) { timeHCSR04 = millis(); Log.trace(F("Creating HCSR04 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &HCSR04data = jsonBuffer.createObject(); + JsonObject& HCSR04data = jsonBuffer.createObject(); digitalWrite(HCSR04_TRI_PIN, LOW); delayMicroseconds(2); digitalWrite(HCSR04_TRI_PIN, HIGH); delayMicroseconds(10); digitalWrite(HCSR04_TRI_PIN, LOW); unsigned long duration = pulseIn(HCSR04_ECH_PIN, HIGH); - if (isnan(duration)) - { + if (isnan(duration)) { Log.error(F("Failed to read from HC SR04 sensor!" CR)); - } - else - { + } else { static unsigned int distance = 99999; unsigned int d = duration / 58.2; HCSR04data.set("distance", (int)d); - if (d > distance) - { + if (d > distance) { HCSR04data.set("direction", "away"); Log.trace(F("HC SR04 Distance changed" CR)); - } - else if (d < distance) - { + } else if (d < distance) { HCSR04data.set("direction", "towards"); Log.trace(F("HC SR04 Distance changed" CR)); - } - else if (HCSR04_always) - { + } else if (HCSR04_always) { HCSR04data.set("direction", "static"); Log.trace(F("HC SR04 Distance hasn't changed" CR)); } diff --git a/main/ZsensorHCSR501.ino b/main/ZsensorHCSR501.ino index 4cc10937..096ea23d 100644 --- a/main/ZsensorHCSR501.ino +++ b/main/ZsensorHCSR501.ino @@ -30,37 +30,29 @@ #ifdef ZsensorHCSR501 -void setupHCSR501() -{ +void setupHCSR501() { Log.notice(F("HCSR501 pin: %d" CR), HCSR501_PIN); pinMode(HCSR501_PIN, INPUT); // declare HC SR-501 pin as input } -void MeasureHCSR501() -{ - if (millis() > TimeBeforeStartHCSR501) - { //let time to init the PIR sensor +void MeasureHCSR501() { + if (millis() > TimeBeforeStartHCSR501) { //let time to init the PIR sensor const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1); StaticJsonBuffer jsonBuffer; - JsonObject &HCSR501data = jsonBuffer.createObject(); + JsonObject& HCSR501data = jsonBuffer.createObject(); static int pirState = LOW; int PresenceValue = digitalRead(HCSR501_PIN); - #if defined(ESP8266) || defined(ESP32) +# if defined(ESP8266) || defined(ESP32) yield(); - #endif - if (PresenceValue == HIGH) - { - if (pirState == LOW) - { +# endif + if (PresenceValue == HIGH) { + if (pirState == LOW) { //turned on HCSR501data.set("hcsr501", "true"); pirState = HIGH; } - } - else - { - if (pirState == HIGH) - { + } else { + if (pirState == HIGH) { // turned off HCSR501data.set("hcsr501", "false"); pirState = LOW; diff --git a/main/ZsensorHTU21.ino b/main/ZsensorHTU21.ino index 85918d24..2e18f1b4 100644 --- a/main/ZsensorHTU21.ino +++ b/main/ZsensorHTU21.ino @@ -38,10 +38,11 @@ #include "User_config.h" #ifdef ZsensorHTU21 -#include "Wire.h" // Library for communication with I2C / TWI devices -#include -#include "SparkFunHTU21D.h" -#include "config_HTU21.h" +# include + +# include "SparkFunHTU21D.h" +# include "Wire.h" // Library for communication with I2C / TWI devices +# include "config_HTU21.h" //Time used to wait for an interval before resending measured values unsigned long timehtu21 = 0; @@ -49,24 +50,20 @@ unsigned long timehtu21 = 0; //Global sensor object HTU21D htuSensor; -void setupZsensorHTU21() -{ +void setupZsensorHTU21() { delay(10); // Gives the Sensor enough time to turn on Log.notice(F("HTU21 Initialized - begin()" CR)); -#if defined(ESP32) +# if defined(ESP32) Wire.begin(I2C_SDA, I2C_SCL); htuSensor.begin(Wire); -#else +# else htuSensor.begin(); -#endif +# endif } -void MeasureTempHum() -{ - - if (millis() > (timehtu21 + TimeBetweenReadinghtu21)) - { +void MeasureTempHum() { + if (millis() > (timehtu21 + TimeBetweenReadinghtu21)) { Log.trace(F("Read HTU21 Sensor" CR)); timehtu21 = millis(); @@ -76,41 +73,31 @@ void MeasureTempHum() float HtuTempC = htuSensor.readTemperature(); float HtuHum = htuSensor.readHumidity(); - if (HtuTempC >= 998 || HtuHum >= 998 ) - { + if (HtuTempC >= 998 || HtuHum >= 998) { Log.error(F("Failed to read from sensor HTU21!" CR)); return; } // Check if reads failed and exit early (to try again). - if (isnan(HtuTempC) || isnan(HtuHum)) - { + if (isnan(HtuTempC) || isnan(HtuHum)) { Log.error(F("Failed to read from sensor HTU21!" CR)); - } - else - { + } else { Log.notice(F("Creating HTU21 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &HTU21data = jsonBuffer.createObject(); + JsonObject& HTU21data = jsonBuffer.createObject(); // Generate Temperature in degrees C - if (HtuTempC != persisted_htu_tempc || htu21_always) - { - float HtuTempF = (HtuTempC*1.8)+32; + if (HtuTempC != persisted_htu_tempc || htu21_always) { + float HtuTempF = (HtuTempC * 1.8) + 32; HTU21data.set("tempc", (float)HtuTempC); HTU21data.set("tempf", (float)HtuTempF); - } - else - { + } else { Log.notice(F("Same Temp. Don't send it" CR)); } // Generate Humidity in percent - if (HtuHum != persisted_htu_hum || htu21_always) - { + if (HtuHum != persisted_htu_hum || htu21_always) { HTU21data.set("hum", (float)HtuHum); - } - else - { + } else { Log.notice(F("Same Humidity. Don't send it" CR)); } diff --git a/main/ZsensorINA226.ino b/main/ZsensorINA226.ino index f9404bf7..a9523fa9 100644 --- a/main/ZsensorINA226.ino +++ b/main/ZsensorINA226.ino @@ -35,40 +35,36 @@ #include "User_config.h" #ifdef ZsensorINA226 -#include +# include -float rShunt = 0.1; // Shunt Widerstand festlegen, hier 0.1 Ohm +float rShunt = 0.1; // Shunt Widerstand festlegen, hier 0.1 Ohm const int INA226_ADDR = 0x40; // A0 und A1 auf GND > Adresse 40 Hex auf Seite 18 im Datenblatt //Time used to wait for an interval before resending temp and hum unsigned long timeINA226 = 0; -void setupINA226() -{ +void setupINA226() { Wire.begin(); // Configuration Register Standard Einstellung 0x4127, hier aber 16 Werte Mitteln > 0x4427 writeRegister(0x00, 0x4427); // 1.1ms Volt und Strom A/D-Wandlung, Shunt und VBus continous } -void MeasureINA226() -{ - if (millis() > (timeINA226 + TimeBetweenReadingINA226)) - { //retrieving value of temperature and humidity of the box from DHT every xUL +void MeasureINA226() { + if (millis() > (timeINA226 + TimeBetweenReadingINA226)) { //retrieving value of temperature and humidity of the box from DHT every xUL timeINA226 = millis(); Log.trace(F("Creating INA226 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &INA226data = jsonBuffer.createObject(); + JsonObject& INA226data = jsonBuffer.createObject(); // Topic on which we will send data Log.trace(F("Retrieving electrical data" CR)); // Bus Spannung, read-only, 16Bit, 0...40.96V max., LSB 1.25mV float volt = readRegister(0x02) * 0.00125; // Seite 24: Shunt Spannung +- 81,92mV mit 16 Bit, LSB 2,5uV int shuntvolt = readRegister(0x01); - if (shuntvolt && 0x8000) - { // eine negative Zahl? Dann 2er Komplement bilden + if (shuntvolt && 0x8000) { // eine negative Zahl? Dann 2er Komplement bilden shuntvolt = ~shuntvolt; // alle Bits invertieren - shuntvolt += 1; // 1 dazuzählen - shuntvolt *= -1; // negativ machen + shuntvolt += 1; // 1 dazuzählen + shuntvolt *= -1; // negativ machen } float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R float power = abs(volt * current); @@ -79,15 +75,14 @@ void MeasureINA226() dtostrf(volt, 6, 3, volt_c); dtostrf(current, 6, 3, current_c); dtostrf(power, 6, 3, power_c); - INA226data.set("volt", (char *)volt_c); - INA226data.set("current", (char *)current_c); - INA226data.set("power", (char *)power_c); + INA226data.set("volt", (char*)volt_c); + INA226data.set("current", (char*)current_c); + INA226data.set("power", (char*)power_c); pub(subjectINA226toMQTT, INA226data); } } -static void writeRegister(byte reg, word value) -{ +static void writeRegister(byte reg, word value) { Wire.beginTransmission(INA226_ADDR); Wire.write(reg); Wire.write((value >> 8) & 0xFF); @@ -95,15 +90,12 @@ static void writeRegister(byte reg, word value) Wire.endTransmission(); } -static word readRegister(byte reg) -{ +static word readRegister(byte reg) { word res = 0x0000; Wire.beginTransmission(INA226_ADDR); Wire.write(reg); - if (Wire.endTransmission() == 0) - { - if (Wire.requestFrom(INA226_ADDR, 2) >= 2) - { + if (Wire.endTransmission() == 0) { + if (Wire.requestFrom(INA226_ADDR, 2) >= 2) { res = Wire.read() * 256; res += Wire.read(); } diff --git a/main/ZsensorTSL2561.ino b/main/ZsensorTSL2561.ino index 8d4bccb5..6273d457 100644 --- a/main/ZsensorTSL2561.ino +++ b/main/ZsensorTSL2561.ino @@ -40,15 +40,15 @@ #include "User_config.h" #ifdef ZsensorTSL2561 -#include "math.h" -#include "Wire.h" -#include -#include +# include +# include + +# include "Wire.h" +# include "math.h" Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345); -void displaySensorDetails(void) -{ +void displaySensorDetails(void) { sensor_t sensor; tsl.getSensor(&sensor); Log.trace(F("------------------------------------" CR)); @@ -62,14 +62,12 @@ void displaySensorDetails(void) delay(500); } -void setupZsensorTSL2561() -{ +void setupZsensorTSL2561() { Log.notice(F("Setup TSL2561 on adress: %H" CR), TSL2561_ADDR_FLOAT); Wire.begin(); Wire.beginTransmission(TSL2561_ADDR_FLOAT); - if (!tsl.begin()) - { + if (!tsl.begin()) { Log.error(F("No TSL2561 detected" CR)); } @@ -86,24 +84,21 @@ void setupZsensorTSL2561() displaySensorDetails(); } -void MeasureLightIntensityTSL2561() -{ - if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) - { +void MeasureLightIntensityTSL2561() { + if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) { static uint32_t persisted_lux; timetsl2561 = millis(); Log.trace(F("Creating TSL2561 buffer" CR)); StaticJsonBuffer jsonBuffer; - JsonObject &TSL2561data = jsonBuffer.createObject(); + JsonObject& TSL2561data = jsonBuffer.createObject(); sensors_event_t event; tsl.getEvent(&event); if (event.light) // if event.light == 0 the sensor is clipping, do not send { - if (persisted_lux != event.light || tsl2561_always) - { + if (persisted_lux != event.light || tsl2561_always) { persisted_lux = event.light; TSL2561data.set("lux", (float)event.light); @@ -111,14 +106,10 @@ void MeasureLightIntensityTSL2561() TSL2561data.set("wattsm2", (float)(event.light) / 683.0); pub(subjectTSL12561toMQTT, TSL2561data); - } - else - { + } else { Log.trace(F("Same lux value, do not send" CR)); } - } - else - { + } else { Log.error(F("Failed to read from TSL2561" CR)); } } diff --git a/main/config_2G.h b/main/config_2G.h index 0865b1ef..0f85101f 100644 --- a/main/config_2G.h +++ b/main/config_2G.h @@ -28,34 +28,34 @@ extern void setup2G(); extern bool _2GtoMQTT(); -extern void MQTTto2G(char *topicOri, char *datacallback); -extern void MQTTto2G(char *topicOri, JsonObject &SMSdata); +extern void MQTTto2G(char* topicOri, char* datacallback); +extern void MQTTto2G(char* topicOri, JsonObject& SMSdata); /*-------------------2G topics & parameters----------------------*/ //433Mhz MQTT Subjects and keys -#define subjectMQTTto2G "/commands/MQTTto2G" -#define subject2GtoMQTT "/2GtoMQTT" +#define subjectMQTTto2G "/commands/MQTTto2G" +#define subject2GtoMQTT "/2GtoMQTT" #define subjectGTW2GtoMQTT "/2GtoMQTT" -#define _2GPhoneKey "PHO_" // phone number define the phone number to send the SMS MQTT->2G +#define _2GPhoneKey "PHO_" // phone number define the phone number to send the SMS MQTT->2G #define _2G_MODULE_BAUDRATE 9600 -#define _2G_MIN_SIGNAL 30 -#define _2G_MAX_SIGNAL 1000 +#define _2G_MIN_SIGNAL 30 +#define _2G_MAX_SIGNAL 1000 /*-------------------PIN DEFINITIONS----------------------*/ #if !defined(_2G_TX_PIN) || !defined(_2G_RX_PIN) || !defined(_2G_PWR_PIN) - #ifdef ESP8266 - #define _2G_TX_PIN D6 //D6 to A6 RX, - #define _2G_RX_PIN D7 //D7 to A6 TX - #define _2G_PWR_PIN D5 // connect a MOSFET to power on and off your A6/7 module - #elif defined(ESP32) - #define _2G_TX_PIN 16 //D16 to A6 RX, - #define _2G_RX_PIN 17 //D17 to A6 TX - #define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module - #else - #define _2G_TX_PIN 6 //D6 to A6 RX, - #define _2G_RX_PIN 7 //D7 to A6 TX - #define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module - #endif +# ifdef ESP8266 +# define _2G_TX_PIN D6 //D6 to A6 RX, +# define _2G_RX_PIN D7 //D7 to A6 TX +# define _2G_PWR_PIN D5 // connect a MOSFET to power on and off your A6/7 module +# elif defined(ESP32) +# define _2G_TX_PIN 16 //D16 to A6 RX, +# define _2G_RX_PIN 17 //D17 to A6 TX +# define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module +# else +# define _2G_TX_PIN 6 //D6 to A6 RX, +# define _2G_RX_PIN 7 //D7 to A6 TX +# define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module +# endif #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_ADC.h b/main/config_ADC.h index bd3bf77c..d1afcd67 100644 --- a/main/config_ADC.h +++ b/main/config_ADC.h @@ -30,19 +30,19 @@ extern void setupADC(); extern void ADCtoMQTT(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define ADCTOPIC "/ADCtoMQTT" +#define ADCTOPIC "/ADCtoMQTT" #if !defined(TimeBetweenReadingADC) || (TimeBetweenReadingADC < 200) - #define TimeBetweenReadingADC 500 // time between 2 ADC readings, minimum 200 to let the time of the ESP to keep the connection +# define TimeBetweenReadingADC 500 // time between 2 ADC readings, minimum 200 to let the time of the ESP to keep the connection #endif #ifndef ThresholdReadingADC - #define ThresholdReadingADC 50 // following the comparison between the previous value and the current one +- the threshold the value will be published or not +# define ThresholdReadingADC 50 // following the comparison between the previous value and the current one +- the threshold the value will be published or not #endif /*-------------------PIN DEFINITIONS----------------------*/ #if defined(ESP8266) || !defined(ADC_PIN) - #define ADC_PIN A0 //on nodeMCU this is D3 GPIO0 +# define ADC_PIN A0 //on nodeMCU this is D3 GPIO0 #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_BH1750.h b/main/config_BH1750.h index 8220b462..afb94da7 100644 --- a/main/config_BH1750.h +++ b/main/config_BH1750.h @@ -41,14 +41,14 @@ extern void setupBH1750(); extern void BH1750toMQTT(); -#define bh1750_always true // if false when the current value for light Level (Lux) is the same as previous one don't send it by MQTT +#define bh1750_always true // if false when the current value for light Level (Lux) is the same as previous one don't send it by MQTT #define TimeBetweenReadingBH1750 30000 /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectBH1750toMQTT "/BH1750toMQTT" +#define subjectBH1750toMQTT "/BH1750toMQTT" //Time used to wait for an interval before resending measured values unsigned long timebh1750 = 0; int BH1750_i2c_addr = 0x23; // Light Sensor I2C Address -#endif \ No newline at end of file +#endif diff --git a/main/config_BME280.h b/main/config_BME280.h index 6262bcbe..ce0cf282 100644 --- a/main/config_BME280.h +++ b/main/config_BME280.h @@ -41,12 +41,12 @@ extern void setupBME280(); extern void BME280toMQTT(); -#define bme280_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT +#define bme280_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT #define TimeBetweenReadingbme280 30000 /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define BMETOPIC "/CLIMAtoMQTT/bme" +#define BMETOPIC "/CLIMAtoMQTT/bme" //Time used to wait for an interval before resending measured values unsigned long timebme280 = 0; diff --git a/main/config_BT.h b/main/config_BT.h index 3a52f724..b8457f5b 100644 --- a/main/config_BT.h +++ b/main/config_BT.h @@ -27,38 +27,38 @@ #define config_BT_h extern void setupBT(); -extern bool BTtoMQTT(); -extern void MQTTtoBT(char * topicOri, JsonObject& RFdata); +extern bool BTtoMQTT(); +extern void MQTTtoBT(char* topicOri, JsonObject& RFdata); /*----------------------BT topics & parameters-------------------------*/ -#define subjectBTtoMQTT "/BTtoMQTT" -#define subjectMQTTtoBTset "/commands/MQTTtoBT/config" -#define MinimumRSSI -100 //default minimum rssi value, all the devices below -90 will not be reported -#define Scan_duration 10 //define the time for a scan --WARNING-- changing this value can lead to instability on ESP32 -#define HM-10 -#define HMSerialSpeed 9600 // Communication speed with the HM module, softwareserial doesn't support 115200 +#define subjectBTtoMQTT "/BTtoMQTT" +#define subjectMQTTtoBTset "/commands/MQTTtoBT/config" +#define MinimumRSSI -100 //default minimum rssi value, all the devices below -90 will not be reported +#define Scan_duration 10 //define the time for a scan --WARNING-- changing this value can lead to instability on ESP32 +#define HM -10 +#define HMSerialSpeed 9600 // Communication speed with the HM module, softwareserial doesn't support 115200 //#define HM-11 // uncomment this line if you use HM-11 and comment the line above //#define HM_BLUE_LED_STOP true //uncomment to stop the blue led light of HM1X -#define BLEdelimiter "4f4b2b444953413a" // OK+DISA: +#define BLEdelimiter "4f4b2b444953413a" // OK+DISA: #define ServicedataMinLength 30 #ifndef TimeBtw_Read - #define TimeBtw_Read 55555 //define default time between 2 scans +# define TimeBtw_Read 55555 //define default time between 2 scans #endif #ifndef pubKnownBLEServiceData - #define pubKnownBLEServiceData false // define true if you want to publish service data belonging to recognised sensors +# define pubKnownBLEServiceData false // define true if you want to publish service data belonging to recognised sensors #endif #ifndef pubUnknownBLEServiceData - #define pubUnknownBLEServiceData true // define false if you don't want to publish service data to unrecognised sensors (in case you are having too heavy service data) https://github.com/1technophile/OpenMQTTGateway/issues/318#issuecomment-446064707 +# define pubUnknownBLEServiceData true // define false if you don't want to publish service data to unrecognised sensors (in case you are having too heavy service data) https://github.com/1technophile/OpenMQTTGateway/issues/318#issuecomment-446064707 #endif #ifndef pubBLEManufacturerData - #define pubBLEManufacturerData false // define true if you want to publish the manufacturer's data (sometimes contains characters that aren't valid with receiving client) +# define pubBLEManufacturerData false // define true if you want to publish the manufacturer's data (sometimes contains characters that aren't valid with receiving client) #endif #ifndef pubBLEServiceUUID - #define pubBLEServiceUUID false // define true if you want to publish the service UUID data +# define pubBLEServiceUUID false // define true if you want to publish the service UUID data #endif /*-------------------HOME ASSISTANT ROOM PRESENCE ----------------------*/ @@ -68,37 +68,37 @@ extern void MQTTtoBT(char * topicOri, JsonObject& RFdata); unsigned int BLEinterval = TimeBtw_Read; //time between 2 scans int Minrssi = MinimumRSSI; //minimum rssi value -struct BLEdevice{ +struct BLEdevice { char macAdr[13]; bool isDisc; bool isWhtL; bool isBlkL; }; -#define device_flags_isDisc 1 << 0 +#define device_flags_isDisc 1 << 0 #define device_flags_isWhiteL 1 << 1 #define device_flags_isBlackL 1 << 2 -struct decompose{ +struct decompose { char subject[4]; int start; int len; bool reverse; char extract[60]; }; - + /*-------------------PIN DEFINITIONS----------------------*/ #if !defined(BT_RX) || !defined(BT_TX) - #ifdef ESP8266 - #define BT_RX 13 //D7 ESP8266 RX connect HM-10 or 11 TX - #define BT_TX 12 //D6 ESP8266 TX connect HM-10 or 11 RX - #elif defined(ESP32) - #define BT_RX 18 // not tested - #define BT_TX 19 // not tested - #else - #define BT_RX 5 //arduino RX connect HM-10 or 11 TX - #define BT_TX 6 //arduino TX connect HM-10 or 11 RX - #endif +# ifdef ESP8266 +# define BT_RX 13 //D7 ESP8266 RX connect HM-10 or 11 TX +# define BT_TX 12 //D6 ESP8266 TX connect HM-10 or 11 RX +# elif defined(ESP32) +# define BT_RX 18 // not tested +# define BT_TX 19 // not tested +# else +# define BT_RX 5 //arduino RX connect HM-10 or 11 TX +# define BT_TX 6 //arduino TX connect HM-10 or 11 RX +# endif #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_DHT.h b/main/config_DHT.h index 92b9905e..045e14a9 100644 --- a/main/config_DHT.h +++ b/main/config_DHT.h @@ -30,8 +30,8 @@ extern void setupDHT(); extern void DHTtoMQTT(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define DHTTOPIC "/DHTtoMQTT/dht1" -#define dht_always true // if false when the current value for temp or hum is the same as previous one don't send it by MQTT +#define DHTTOPIC "/DHTtoMQTT/dht1" +#define dht_always true // if false when the current value for temp or hum is the same as previous one don't send it by MQTT #define TimeBetweenReadingDHT 30000 // time between 2 DHT readings /*-------------DHT SENSOR TYPE-------------*/ //#define DHT_SENSOR_TYPE DHT11 //uncomment for DHT11 Sensor @@ -39,13 +39,13 @@ extern void DHTtoMQTT(); #define DHT_SENSOR_TYPE DHT22 //uncomment for DHT22 Sensor (default for backwards compatibility) /*-------------------PIN DEFINITIONS----------------------*/ #ifndef DHT_RECEIVER_PIN - #if defined(ESP8266) - #define DHT_RECEIVER_PIN 5 //5 = D1 you can put 14 = D5 if you don't use HCSR501 sensor and the RFM69 - #elif defined(ESP32) - #define DHT_RECEIVER_PIN 16 - #else - #define DHT_RECEIVER_PIN 8 - #endif +# if defined(ESP8266) +# define DHT_RECEIVER_PIN 5 //5 = D1 you can put 14 = D5 if you don't use HCSR501 sensor and the RFM69 +# elif defined(ESP32) +# define DHT_RECEIVER_PIN 16 +# else +# define DHT_RECEIVER_PIN 8 +# endif #endif #endif \ No newline at end of file diff --git a/main/config_DS1820.h b/main/config_DS1820.h index df19d799..f16276f2 100644 --- a/main/config_DS1820.h +++ b/main/config_DS1820.h @@ -31,26 +31,26 @@ extern void DS1820toMQTT(); extern void pubOneWire_HADiscovery(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define OW_TOPIC "/OneWiretoMQTT/ds1820" -#define OW_MAX_SENSORS 8 // query max. sensors on 1-wire bus -#define DS1820_ALWAYS true // if false only published current temperature if has changed from previous reading +#define OW_TOPIC "/OneWiretoMQTT/ds1820" +#define OW_MAX_SENSORS 8 // query max. sensors on 1-wire bus +#define DS1820_ALWAYS true // if false only published current temperature if has changed from previous reading #define DS1820_INTERVAL_SEC 60 // time between DS1820 readings (seconds) -#define DS1820_RESOLUTION 10 // conversion times: 9 bit (93.75 ms), 10 bit (187.5 ms), 11 bit (375 ms), 12 bit (750 ms) +#define DS1820_RESOLUTION 10 // conversion times: 9 bit (93.75 ms), 10 bit (187.5 ms), 11 bit (375 ms), 12 bit (750 ms) #ifndef DS1820_FAHRENHEIT - #define DS1820_FAHRENHEIT false // defaults to Celcius +# define DS1820_FAHRENHEIT false // defaults to Celcius #endif -#define DS1820_DETAILS true // publish extented info for each sensor (resolution, address, type) -#define DS1820_CONV_TIME 2000 // trigger conversion before requesting temperature readings (ms) +#define DS1820_DETAILS true // publish extented info for each sensor (resolution, address, type) +#define DS1820_CONV_TIME 2000 // trigger conversion before requesting temperature readings (ms) /*-------------------PIN DEFINITIONS----------------------*/ #ifndef DS1820_OWBUS_PIN - #if defined(ESP8266) - #define DS1820_OWBUS_PIN 2 - #elif defined(ESP32) - #define DS1820_OWBUS_PIN 2 - #else - #define DS1820_OWBUS_PIN 2 - #endif +# if defined(ESP8266) +# define DS1820_OWBUS_PIN 2 +# elif defined(ESP32) +# define DS1820_OWBUS_PIN 2 +# else +# define DS1820_OWBUS_PIN 2 +# endif #endif #endif diff --git a/main/config_FASTLED.h b/main/config_FASTLED.h index 56eec3bb..1860327f 100644 --- a/main/config_FASTLED.h +++ b/main/config_FASTLED.h @@ -26,11 +26,11 @@ /*-------------------FASTLED topics & parameters----------------------*/ //FASTLED MQTT Subjects -#define subjectMQTTtoFASTLED "/commands/MQTTtoFASTLED" -#define subjectMQTTtoFASTLEDsetled "/commands/MQTTtoFASTLED/setled" //set only one LED with JSON struct {"led":0-x,"hex":"#000000","blink":true/false} +#define subjectMQTTtoFASTLED "/commands/MQTTtoFASTLED" +#define subjectMQTTtoFASTLEDsetled "/commands/MQTTtoFASTLED/setled" //set only one LED with JSON struct {"led":0-x,"hex":"#000000","blink":true/false} #define subjectMQTTtoFASTLEDsetbrightness "/commands/MQTTtoFASTLED/setbrightness" //set the brightness 0-255 -#define subjectMQTTtoFASTLEDsetanimation "/commands/MQTTtoFASTLED/setanimation" //Animation Fire2012 by Mark Kriegsman -#define subjectGTWFASTLEDtoMQTT "/FASTLEDtoMQTT" //same color on all LEDs in #RRGGBB +#define subjectMQTTtoFASTLEDsetanimation "/commands/MQTTtoFASTLED/setanimation" //Animation Fire2012 by Mark Kriegsman +#define subjectGTWFASTLEDtoMQTT "/FASTLEDtoMQTT" //same color on all LEDs in #RRGGBB // How many leds in your strip? #define FASTLED_NUM_LEDS 16 @@ -72,15 +72,15 @@ #ifdef ESP8266 //#define FASTLED_ESP8266_RAW_PIN_ORDER //#define FASTLED_ESP8266_NODEMCU_PIN_ORDER -#define FASTLED_ESP8266_D1_PIN_ORDER -#define FASTLED_DATA_PIN D2 // only D2 works by me +# define FASTLED_ESP8266_D1_PIN_ORDER +# define FASTLED_DATA_PIN D2 // only D2 works by me //#define FASTLED_CLOCK_PIN 13 #elif ESP32 -#define FASTLED_DATA_PIN 16 -#define FASTLED_CLOCK_PIN 13 +# define FASTLED_DATA_PIN 16 +# define FASTLED_CLOCK_PIN 13 #else -#define FASTLED_DATA_PIN 10 -#define FASTLED_CLOCK_PIN 13 +# define FASTLED_DATA_PIN 10 +# define FASTLED_CLOCK_PIN 13 #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_GPIOInput.h b/main/config_GPIOInput.h index 11c00ff0..b67adf26 100644 --- a/main/config_GPIOInput.h +++ b/main/config_GPIOInput.h @@ -30,16 +30,16 @@ extern void setupGPIOInput(); extern void GPIOInputtoMQTT(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectGPIOInputtoMQTT "/GPIOInputtoMQTT" +#define subjectGPIOInputtoMQTT "/GPIOInputtoMQTT" #define GPIOInputDebounceDelay 60 //debounce time, increase if there are issues /*-------------------PIN DEFINITIONS----------------------*/ #ifndef GPIOInput_PIN - #if defined(ESP8266) || defined(ESP32) - #define GPIOInput_PIN 13 - #else - #define GPIOInput_PIN 7 - #endif +# if defined(ESP8266) || defined(ESP32) +# define GPIOInput_PIN 13 +# else +# define GPIOInput_PIN 7 +# endif #endif #endif diff --git a/main/config_GPIOKeyCode.h b/main/config_GPIOKeyCode.h index 1b09b44a..b7d71b1d 100644 --- a/main/config_GPIOKeyCode.h +++ b/main/config_GPIOKeyCode.h @@ -30,30 +30,30 @@ extern void setupGPIOKeyCode(); extern void GPIOKeyCodetoMQTT(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectGPIOKeyCodetoMQTT "/keycode" +#define subjectGPIOKeyCodetoMQTT "/keycode" #define subjectGPIOKeyCodeStatetoMQTT subjectGPIOKeyCodetoMQTT "/status" -#define GPIOKeyCodeDebounceDelay 60 //debounce time, increase if there are issues +#define GPIOKeyCodeDebounceDelay 60 //debounce time, increase if there are issues /*-------------------PIN DEFINITIONS----------------------*/ #if defined(ESP8266) || defined(ESP32) -#ifndef GPIOKeyCode_LATCH_PIN - #define GPIOKeyCode_LATCH_PIN 12 //D6 -#endif -#ifndef GPIOKeyCode_D0_PIN - #define GPIOKeyCode_D0_PIN 14 //D5 -#endif -#ifndef GPIOKeyCode_D1_PIN - #define GPIOKeyCode_D1_PIN 5 //D1 -#endif -#ifndef GPIOKeyCode_D2_PIN - #define GPIOKeyCode_D2_PIN 13 //D7 -#endif -#ifndef GPIOKeyCode_D3_PIN - #define GPIOKeyCode_D3_PIN XX //?? -#endif +# ifndef GPIOKeyCode_LATCH_PIN +# define GPIOKeyCode_LATCH_PIN 12 //D6 +# endif +# ifndef GPIOKeyCode_D0_PIN +# define GPIOKeyCode_D0_PIN 14 //D5 +# endif +# ifndef GPIOKeyCode_D1_PIN +# define GPIOKeyCode_D1_PIN 5 //D1 +# endif +# ifndef GPIOKeyCode_D2_PIN +# define GPIOKeyCode_D2_PIN 13 //D7 +# endif +# ifndef GPIOKeyCode_D3_PIN +# define GPIOKeyCode_D3_PIN XX //?? +# endif #else -// must define !!! +// must define !!! #endif #endif \ No newline at end of file diff --git a/main/config_HCSR04.h b/main/config_HCSR04.h index 5c84c9ed..46dfe2c4 100644 --- a/main/config_HCSR04.h +++ b/main/config_HCSR04.h @@ -40,23 +40,23 @@ extern void setupHCSR04(); extern void MeasureDistance(); -#define HCSR04_always true // If false, the current value of the parameter is the same as previous one don't send it by MQTT +#define HCSR04_always true // If false, the current value of the parameter is the same as previous one don't send it by MQTT #define TimeBetweenReadingHCSR04 5000 /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectHCSR04 "/DISTtoMQTT/sr04" +#define subjectHCSR04 "/DISTtoMQTT/sr04" /*-------------------PIN DEFINITIONS----------------------*/ #if defined(ESP8266) - #define HCSR04_TRI_PIN D6 - #define HCSR04_ECH_PIN D7 +# define HCSR04_TRI_PIN D6 +# define HCSR04_ECH_PIN D7 #elif defined(ESP32) - #define HCSR04_TRI_PIN 16 // NOT TESTED - #define HCSR04_ECH_PIN 17 // NOT TESTED +# define HCSR04_TRI_PIN 16 // NOT TESTED +# define HCSR04_ECH_PIN 17 // NOT TESTED #else - #define HCSR04_TRI_PIN 6 // NOT TESTED - #define HCSR04_ECH_PIN 5 // NOT TESTED +# define HCSR04_TRI_PIN 6 // NOT TESTED +# define HCSR04_ECH_PIN 5 // NOT TESTED #endif #endif \ No newline at end of file diff --git a/main/config_HCSR501.h b/main/config_HCSR501.h index 6803ba29..1b233d97 100644 --- a/main/config_HCSR501.h +++ b/main/config_HCSR501.h @@ -30,21 +30,21 @@ extern void setupHCSR501(); extern void HCSR501toMQTT(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectHCSR501toMQTT "/HCSR501toMQTT" +#define subjectHCSR501toMQTT "/HCSR501toMQTT" #ifndef TimeBeforeStartHCSR501 - #define TimeBeforeStartHCSR501 60000 //define the time necessary for HC SR501 init +# define TimeBeforeStartHCSR501 60000 //define the time necessary for HC SR501 init #endif /*-------------------PIN DEFINITIONS----------------------*/ #ifndef HCSR501_PIN - #if defined(ESP8266) - #define HCSR501_PIN D5 - #elif defined(ESP32) - #define HCSR501_PIN 5 - #else - #define HCSR501_PIN 7 - #endif +# if defined(ESP8266) +# define HCSR501_PIN D5 +# elif defined(ESP32) +# define HCSR501_PIN 5 +# else +# define HCSR501_PIN 7 +# endif #endif #endif \ No newline at end of file diff --git a/main/config_HTU21.h b/main/config_HTU21.h index 28b08deb..8d0a08aa 100644 --- a/main/config_HTU21.h +++ b/main/config_HTU21.h @@ -41,18 +41,18 @@ extern void setupHTU21(); extern void HTU21toMQTT(); -#define htu21_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT +#define htu21_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT #define TimeBetweenReadinghtu21 30000 /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define HTUTOPIC "/CLIMAtoMQTT/htu" +#define HTUTOPIC "/CLIMAtoMQTT/htu" #if defined(ESP32) - #if !defined(I2C_SDA) || !defined(I2C_SCL) - #define I2C_SDA 16 - #define I2C_SCL 0 - #endif +# if !defined(I2C_SDA) || !defined(I2C_SCL) +# define I2C_SDA 16 +# define I2C_SCL 0 +# endif #endif #endif \ No newline at end of file diff --git a/main/config_INA226.h b/main/config_INA226.h index 7e9c6715..66a8b90d 100644 --- a/main/config_INA226.h +++ b/main/config_INA226.h @@ -30,7 +30,7 @@ extern void setupINA226(); extern void INA226toMQTT(); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectINA226toMQTT "/INA226toMQTT" +#define subjectINA226toMQTT "/INA226toMQTT" #define TimeBetweenReadingINA226 30000 // time between 2 INA226 readings -#endif \ No newline at end of file +#endif diff --git a/main/config_IR.h b/main/config_IR.h index 307a3d2c..fec4ed19 100644 --- a/main/config_IR.h +++ b/main/config_IR.h @@ -27,146 +27,146 @@ #define config_IR_h extern void setupIR(); -extern void IRtoMQTT(); -extern void MQTTtoIR(char * topicOri, char * datacallback); -extern void MQTTtoIR(char * topicOri, JsonObject& RFdata); +extern void IRtoMQTT(); +extern void MQTTtoIR(char* topicOri, char* datacallback); +extern void MQTTtoIR(char* topicOri, JsonObject& RFdata); /*-------------------IR topics & parameters----------------------*/ //IR MQTT Subjects -#define subjectGTWIRtoMQTT "/IRtoMQTT" -#define subjectIRtoMQTT "/IRtoMQTT" -#define subjectMQTTtoIR "/commands/MQTTtoIR" +#define subjectGTWIRtoMQTT "/IRtoMQTT" +#define subjectIRtoMQTT "/IRtoMQTT" +#define subjectMQTTtoIR "/commands/MQTTtoIR" // subject monitored to listen traffic processed by other gateways to store data and avoid ntuple #define subjectMultiGTWIR "+/+/IRtoMQTT" -#define IRbitsKey "IRBITS_" // bits will be defined if a subject contains IRbitsKey followed by a value of 2 digits -#define IRRptKey "RPT_" // repeats will be defined if a subject contains IRRptKey followed by a value of 1 digit -#define repeatIRwMQTT false // do we repeat a received signal by using mqtt -#define repeatIRwNumber 0 // default repeat of the signal +#define IRbitsKey "IRBITS_" // bits will be defined if a subject contains IRbitsKey followed by a value of 2 digits +#define IRRptKey "RPT_" // repeats will be defined if a subject contains IRRptKey followed by a value of 1 digit +#define repeatIRwMQTT false // do we repeat a received signal by using mqtt +#define repeatIRwNumber 0 // default repeat of the signal //#define RawDirectForward false // direct repeat of IR signal with raw data #define RawFrequency 38 // raw frequency sending //#define DumpMode true // uncomment so as to see big dumps of IR codes #define pubIRunknownPrtcl false // key to avoid mqtt publication of unknown IR protocol (set to true if you want to publish unknown protocol) -#define PanasonicAddress 0x4004 // Panasonic address (Pre data) +#define PanasonicAddress 0x4004 // Panasonic address (Pre data) -#if defined(ESP8266) || defined(ESP32) //IR supported protocols on ESP8266, all supported per default - #define IR_GC - #define IR_RAW - #define IR_COOLIX - #define IR_WHYNTER - #define IR_LG - #define IR_SONY - #define IR_DISH - #define IR_RC5 - #define IR_RC6 - #define IR_SHARP - #define IR_SAMSUNG - #define IR_PANASONIC - #define IR_RCMM - #define IR_MITSUBISHI - #define IR_GICABLE - #define IR_MITSUBISHI2 - #define IR_LASERTAG - #define IR_CARRIER_AC - #define IR_MIDEA - #define IR_NIKAI - #define IR_SHERWOOD - #define IR_DENON - #define IR_AIWA_RC_T501 - #define IR_JVC - #define IR_SANYO - #define IR_DAIKIN - #define IR_KELVINATOR - #define IR_MITSUBISHI_AC - #define IR_SANYO_LC7461 - #define IR_GREE - #define IR_ARGO - #define IR_TROTEC - #define IR_TOSHIBA_AC - #define IR_FUJITSU_AC - #define IR_MAGIQUEST - #define IR_HAIER_AC - #define IR_HITACHI_AC - #define IR_HITACHI_AC1 - #define IR_HITACHI_AC2 - #define IR_GICABLE - #define IR_HAIER_AC_YRW02 - #define IR_WHIRLPOOL_AC - #define IR_SAMSUNG_AC - #define IR_LUTRON - #define IR_ELECTRA_AC - #define IR_PANASONIC_AC - #define IR_PIONEER - #define IR_LG2 - #define IR_MWM - #define IR_DAIKIN2 - #define IR_VESTEL_AC - #define IR_SAMSUNG36 - #define IR_TCL112AC - #define IR_TECO - #define IR_LEGOPF - #define IR_MITSUBISHI_HEAVY_88 - #define IR_MITSUBISHI_HEAVY_152 - #define IR_DAIKIN216 - #define IR_SHARP_AC - #define IR_GOODWEATHER - #define IR_INAX - #define IR_DAIKIN160 - #define IR_NEOCLIMA - #define IR_DAIKIN176 - #define IR_DAIKIN128 - #define IR_AMCOR - #define IR_DAIKIN152 - #define IR_MITSUBISHI136 - #define IR_MITSUBISHI112 - #define IR_HITACHI_AC424 +#if defined(ESP8266) || defined(ESP32) //IR supported protocols on ESP8266, all supported per default +# define IR_GC +# define IR_RAW +# define IR_COOLIX +# define IR_WHYNTER +# define IR_LG +# define IR_SONY +# define IR_DISH +# define IR_RC5 +# define IR_RC6 +# define IR_SHARP +# define IR_SAMSUNG +# define IR_PANASONIC +# define IR_RCMM +# define IR_MITSUBISHI +# define IR_GICABLE +# define IR_MITSUBISHI2 +# define IR_LASERTAG +# define IR_CARRIER_AC +# define IR_MIDEA +# define IR_NIKAI +# define IR_SHERWOOD +# define IR_DENON +# define IR_AIWA_RC_T501 +# define IR_JVC +# define IR_SANYO +# define IR_DAIKIN +# define IR_KELVINATOR +# define IR_MITSUBISHI_AC +# define IR_SANYO_LC7461 +# define IR_GREE +# define IR_ARGO +# define IR_TROTEC +# define IR_TOSHIBA_AC +# define IR_FUJITSU_AC +# define IR_MAGIQUEST +# define IR_HAIER_AC +# define IR_HITACHI_AC +# define IR_HITACHI_AC1 +# define IR_HITACHI_AC2 +# define IR_GICABLE +# define IR_HAIER_AC_YRW02 +# define IR_WHIRLPOOL_AC +# define IR_SAMSUNG_AC +# define IR_LUTRON +# define IR_ELECTRA_AC +# define IR_PANASONIC_AC +# define IR_PIONEER +# define IR_LG2 +# define IR_MWM +# define IR_DAIKIN2 +# define IR_VESTEL_AC +# define IR_SAMSUNG36 +# define IR_TCL112AC +# define IR_TECO +# define IR_LEGOPF +# define IR_MITSUBISHI_HEAVY_88 +# define IR_MITSUBISHI_HEAVY_152 +# define IR_DAIKIN216 +# define IR_SHARP_AC +# define IR_GOODWEATHER +# define IR_INAX +# define IR_DAIKIN160 +# define IR_NEOCLIMA +# define IR_DAIKIN176 +# define IR_DAIKIN128 +# define IR_AMCOR +# define IR_DAIKIN152 +# define IR_MITSUBISHI136 +# define IR_MITSUBISHI112 +# define IR_HITACHI_AC424 #elif __AVR_ATmega2560__ - #define IR_COOLIX - #define IR_Whynter - #define IR_LG - #define IR_Sony - #define IR_DISH - #define IR_RC5 - #define IR_Sharp - #define IR_SAMSUNG - #define IR_Raw - #define IR_PANASONIC +# define IR_COOLIX +# define IR_Whynter +# define IR_LG +# define IR_Sony +# define IR_DISH +# define IR_RC5 +# define IR_Sharp +# define IR_SAMSUNG +# define IR_Raw +# define IR_PANASONIC #else //IR supported protocols on arduino uncomment if you want to send with this protocol, NEC protocol is available per default - //#define IR_COOLIX - //#define IR_Whynter - //#define IR_LG - //#define IR_Sony - //#define IR_DISH - //#define IR_RC5 - //#define IR_Sharp - //#define IR_SAMSUNG - //#define IR_Raw - //#define IR_PANASONIC +//#define IR_COOLIX +//#define IR_Whynter +//#define IR_LG +//#define IR_Sony +//#define IR_DISH +//#define IR_RC5 +//#define IR_Sharp +//#define IR_SAMSUNG +//#define IR_Raw +//#define IR_PANASONIC #endif /*-------------------PIN DEFINITIONS----------------------*/ #ifndef IR_RECEIVER_PIN - #ifdef ESP8266 - #define IR_RECEIVER_PIN 2 //D4 /replace by 4 with sonoff rf bridge - #elif ESP32 - #define IR_RECEIVER_PIN 26 - #elif __AVR_ATmega2560__ - #define IR_RECEIVER_PIN 2 // 2 = D2 on arduino mega - #else - #define IR_RECEIVER_PIN 0 // 0 = D2 on arduino UNO - #endif +# ifdef ESP8266 +# define IR_RECEIVER_PIN 2 //D4 /replace by 4 with sonoff rf bridge +# elif ESP32 +# define IR_RECEIVER_PIN 26 +# elif __AVR_ATmega2560__ +# define IR_RECEIVER_PIN 2 // 2 = D2 on arduino mega +# else +# define IR_RECEIVER_PIN 0 // 0 = D2 on arduino UNO +# endif #endif #ifndef IR_EMITTER_PIN - #ifdef ESP8266 - #define IR_EMITTER_PIN 16 //D0/ replace by 0 (D3) if you use IR LOLIN controller shield /replace by 5 with sonoff rf bridge - #elif ESP32 - #define IR_EMITTER_PIN 14 - #elif __AVR_ATmega2560__ - #define IR_EMITTER_PIN 9 - #else - #define IR_EMITTER_PIN 9 - #endif +# ifdef ESP8266 +# define IR_EMITTER_PIN 16 //D0/ replace by 0 (D3) if you use IR LOLIN controller shield /replace by 5 with sonoff rf bridge +# elif ESP32 +# define IR_EMITTER_PIN 14 +# elif __AVR_ATmega2560__ +# define IR_EMITTER_PIN 9 +# else +# define IR_EMITTER_PIN 9 +# endif #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_LORA.h b/main/config_LORA.h index faf3ec04..26f0fbd9 100644 --- a/main/config_LORA.h +++ b/main/config_LORA.h @@ -27,13 +27,13 @@ #define config_LORA_h extern void setupLORA(); -extern void LORAtoMQTT(); -extern void MQTTtoLORA(char * topicOri, char * datacallback); -extern void MQTTtoLORA(char * topicOri, JsonObject& RFdata); +extern void LORAtoMQTT(); +extern void MQTTtoLORA(char* topicOri, char* datacallback); +extern void MQTTtoLORA(char* topicOri, JsonObject& RFdata); /*----------------------LORA topics & parameters-------------------------*/ -#define subjectLORAtoMQTT "/LORAtoMQTT" -#define subjectMQTTtoLORA "/commands/MQTTtoLORA" -#define subjectGTWLORAtoMQTT "/LORAtoMQTT" +#define subjectLORAtoMQTT "/LORAtoMQTT" +#define subjectMQTTtoLORA "/commands/MQTTtoLORA" +#define subjectGTWLORAtoMQTT "/LORAtoMQTT" //Default parameters used when the parameters are not set in the json data #define LORA_BAND 868E6 @@ -49,11 +49,11 @@ extern void MQTTtoLORA(char * topicOri, JsonObject& RFdata); /*-------------------PIN DEFINITIONS----------------------*/ //TTGO LORA BOARD ESP32 PIN DEFINITION -#define LORA_SCK 5 // GPIO5 -- SX1278's SCK -#define LORA_MISO 19 // GPIO19 -- SX1278's MISO -#define LORA_MOSI 27 // GPIO27 -- SX1278's MOSI -#define LORA_SS 18 // GPIO18 -- SX1278's CS -#define LORA_RST 14 // GPIO14 -- SX1278's RESET -#define LORA_DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request) +#define LORA_SCK 5 // GPIO5 -- SX1278's SCK +#define LORA_MISO 19 // GPIO19 -- SX1278's MISO +#define LORA_MOSI 27 // GPIO27 -- SX1278's MOSI +#define LORA_SS 18 // GPIO18 -- SX1278's CS +#define LORA_RST 14 // GPIO14 -- SX1278's RESET +#define LORA_DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request) #endif \ No newline at end of file diff --git a/main/config_M5.h b/main/config_M5.h index a19972eb..52424709 100644 --- a/main/config_M5.h +++ b/main/config_M5.h @@ -27,10 +27,10 @@ #define config_M5_h #ifdef ZboardM5STICKC -#include +# include #endif #ifdef ZboardM5STACK -#include +# include #endif extern void setupM5(); @@ -38,15 +38,15 @@ extern void loopM5(); /*----------------------------USER PARAMETERS-----------------------------*/ /*---------------DEFINE SCREEN BRIGHTNESS------------------*/ #ifndef SLEEP_LCD_BRIGHTNESS - #define SLEEP_LCD_BRIGHTNESS 2 // 0 to 100 +# define SLEEP_LCD_BRIGHTNESS 2 // 0 to 100 #endif #ifndef NORMAL_LCD_BRIGHTNESS - #define NORMAL_LCD_BRIGHTNESS 100 // 0 to 100 +# define NORMAL_LCD_BRIGHTNESS 100 // 0 to 100 #endif /*-------------------DEFINE LOG LEVEL----------------------*/ #define LOG_LEVEL_LCD LOG_LEVEL_WARNING // if we go down below warning the size of the text to display can make the M5 restarting -#define LOG_TO_LCD true //set to false if you want to use serial monitor for the log per default instead of the M5 screen +#define LOG_TO_LCD true //set to false if you want to use serial monitor for the log per default instead of the M5 screen /*-------------------DEFINE MQTT TOPIC FOR CONFIG----------------------*/ -#define subjectMQTTtoM5set "/commands/MQTTtoM5/config" +#define subjectMQTTtoM5set "/commands/MQTTtoM5/config" #endif \ No newline at end of file diff --git a/main/config_ONOFF.h b/main/config_ONOFF.h index cb2daab8..28c489f4 100644 --- a/main/config_ONOFF.h +++ b/main/config_ONOFF.h @@ -27,26 +27,26 @@ #define config_ONOFF_h extern void setupONOFF(); -extern void MQTTtoONOFF(char * topicOri, char * datacallback); -extern void MQTTtoONOFF(char * topicOri, JsonObject& RFdata); +extern void MQTTtoONOFF(char* topicOri, char* datacallback); +extern void MQTTtoONOFF(char* topicOri, JsonObject& RFdata); /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectMQTTtoONOFF "/commands/MQTTtoONOFF" -#define subjectGTWONOFFtoMQTT "/ONOFFtoMQTT" +#define subjectMQTTtoONOFF "/commands/MQTTtoONOFF" +#define subjectGTWONOFFtoMQTT "/ONOFFtoMQTT" -#define ONKey "setON" +#define ONKey "setON" #define OFFKey "setOFF" /*-------------------PIN DEFINITIONS----------------------*/ // default pin, if not set into the MQTT json #ifndef ACTUATOR_ONOFF_PIN - #ifdef ESP8266 - #define ACTUATOR_ONOFF_PIN 15 //12 for sonoff basic relay - #elif ESP32 - #define ACTUATOR_ONOFF_PIN 15 - #else - #define ACTUATOR_ONOFF_PIN 13 - #endif +# ifdef ESP8266 +# define ACTUATOR_ONOFF_PIN 15 //12 for sonoff basic relay +# elif ESP32 +# define ACTUATOR_ONOFF_PIN 15 +# else +# define ACTUATOR_ONOFF_PIN 13 +# endif #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_RF.h b/main/config_RF.h index 5cee740e..a1014c0c 100644 --- a/main/config_RF.h +++ b/main/config_RF.h @@ -32,29 +32,29 @@ #ifdef ZgatewayRF extern void setupRF(); extern void RFtoMQTT(); -extern void MQTTtoRF(char *topicOri, char *datacallback); -extern void MQTTtoRF(char *topicOri, JsonObject &RFdata); +extern void MQTTtoRF(char* topicOri, char* datacallback); +extern void MQTTtoRF(char* topicOri, JsonObject& RFdata); #endif #ifdef ZgatewayRF2 extern void setupRF2(); extern void RF2toMQTT(); -extern void MQTTtoRF2(char *topicOri, char *datacallback); -extern void MQTTtoRF2(char *topicOri, JsonObject &RFdata); +extern void MQTTtoRF2(char* topicOri, char* datacallback); +extern void MQTTtoRF2(char* topicOri, JsonObject& RFdata); #endif #ifdef ZgatewayPilight extern void setupPilight(); extern void PilighttoMQTT(); -extern void MQTTtoPilight(char *topicOri, char *datacallback); -extern void MQTTtoPilight(char *topicOri, JsonObject &RFdata); +extern void MQTTtoPilight(char* topicOri, char* datacallback); +extern void MQTTtoPilight(char* topicOri, JsonObject& RFdata); #endif /*-------------------RF topics & parameters----------------------*/ //433Mhz MQTT Subjects and keys -#define subjectMQTTtoRF "/commands/MQTTto433" -#define subjectRFtoMQTT "/433toMQTT" +#define subjectMQTTtoRF "/commands/MQTTto433" +#define subjectRFtoMQTT "/433toMQTT" #define subjectGTWRFtoMQTT "/433toMQTT" -#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit -#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits -#define repeatRFwMQTT false // do we repeat a received signal by using mqtt with RF gateway +#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit +#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits +#define repeatRFwMQTT false // do we repeat a received signal by using mqtt with RF gateway /* RF supported protocols @@ -73,52 +73,52 @@ RF supported protocols /*-------------------RF2 topics & parameters----------------------*/ //433Mhz newremoteswitch MQTT Subjects and keys -#define subjectMQTTtoRF2 "/commands/MQTTtoRF2" -#define subjectRF2toMQTT "/RF2toMQTT" +#define subjectMQTTtoRF2 "/commands/MQTTtoRF2" +#define subjectRF2toMQTT "/RF2toMQTT" #define subjectGTWRF2toMQTT "/433toMQTT" -#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits -#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits -#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits -#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit -#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits +#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits +#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits +#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits +#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit +#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits /*-------------------ESPPiLight topics & parameters----------------------*/ //433Mhz Pilight MQTT Subjects and keys -#define subjectMQTTtoPilight "/commands/MQTTtoPilight" -#define subjectPilighttoMQTT "/PilighttoMQTT" +#define subjectMQTTtoPilight "/commands/MQTTtoPilight" +#define subjectPilighttoMQTT "/PilighttoMQTT" #define subjectGTWPilighttoMQTT "/PilighttoMQTT" -#define PilightRAW "RAW" -#define repeatPilightwMQTT false // do we repeat a received signal by using mqtt with Pilight gateway +#define PilightRAW "RAW" +#define repeatPilightwMQTT false // do we repeat a received signal by using mqtt with Pilight gateway /*-------------------CC1101 frequency----------------------*/ -//Match frequency to the hardware version of the radio if ZradioCC1101 is used. -#define CC1101_FREQUENCY 433.92 +//Match frequency to the hardware version of the radio if ZradioCC1101 is used. +#define CC1101_FREQUENCY 433.92 /*-------------------PIN DEFINITIONS----------------------*/ #ifndef RF_RECEIVER_PIN - #ifdef ESP8266 - #define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod - #elif ESP32 - #define RF_RECEIVER_PIN 27 // D27 on DOIT ESP32 - #elif __AVR_ATmega2560__ - #define RF_RECEIVER_PIN 1 //1 = D3 on mega - #else - #define RF_RECEIVER_PIN 1 //1 = D3 on arduino - #endif +# ifdef ESP8266 +# define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod +# elif ESP32 +# define RF_RECEIVER_PIN 27 // D27 on DOIT ESP32 +# elif __AVR_ATmega2560__ +# define RF_RECEIVER_PIN 1 //1 = D3 on mega +# else +# define RF_RECEIVER_PIN 1 //1 = D3 on arduino +# endif #endif #ifndef RF_EMITTER_PIN - #ifdef ESP8266 - #define RF_EMITTER_PIN 3 // RX on nodemcu if it doesn't work with 3, try with 4 (D2) // put 5 with rf bridge direct mod - #elif ESP32 - #define RF_EMITTER_PIN 12 // D12 on DOIT ESP32 - #elif __AVR_ATmega2560__ - #define RF_EMITTER_PIN 4 - #else - //IMPORTANT NOTE: On arduino UNO connect IR emitter pin to D9 , comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library IRremote/boarddefs.h so as to free pin D3 for RF RECEIVER PIN - //RF PIN definition - #define RF_EMITTER_PIN 4 //4 = D4 on arduino - #endif +# ifdef ESP8266 +# define RF_EMITTER_PIN 3 // RX on nodemcu if it doesn't work with 3, try with 4 (D2) // put 5 with rf bridge direct mod +# elif ESP32 +# define RF_EMITTER_PIN 12 // D12 on DOIT ESP32 +# elif __AVR_ATmega2560__ +# define RF_EMITTER_PIN 4 +# else +//IMPORTANT NOTE: On arduino UNO connect IR emitter pin to D9 , comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library IRremote/boarddefs.h so as to free pin D3 for RF RECEIVER PIN +//RF PIN definition +# define RF_EMITTER_PIN 4 //4 = D4 on arduino +# endif #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_RFM69.h b/main/config_RFM69.h index 8e331c46..a8d70373 100644 --- a/main/config_RFM69.h +++ b/main/config_RFM69.h @@ -27,17 +27,17 @@ #define config_RFM69_h extern void setupRFM69(); -extern bool RFM69toMQTT(); -extern void MQTTtoRFM69(char * topicOri, char * datacallback); -extern void MQTTtoRFM69(char * topicOri, JsonObject& RFdata); +extern bool RFM69toMQTT(); +extern void MQTTtoRFM69(char* topicOri, char* datacallback); +extern void MQTTtoRFM69(char* topicOri, JsonObject& RFdata); /*----------------------RFM69 topics & parameters -------------------------*/ // Topic where the message from RFM69 will be published by the gateway, // appended with the nodeID of the sender -#define subjectRFM69toMQTT "/RFM69toMQTT" +#define subjectRFM69toMQTT "/RFM69toMQTT" // Topic subscribed by the gateway. Messages received will be sent to RFM69 -#define subjectMQTTtoRFM69 "/commands/MQTTtoRFM69" -#define RFM69receiverKey "RCV_" // receiver id will be defined if a subject contains RFM69receiverKey followed by a value of 3 digits +#define subjectMQTTtoRFM69 "/commands/MQTTtoRFM69" +#define RFM69receiverKey "RCV_" // receiver id will be defined if a subject contains RFM69receiverKey followed by a value of 3 digits // On reception of an ack from RFM69, the message that has been sent is published here #define subjectGTWRFM69toMQTT "/RFM69toMQTT/acked" #define defaultRFM69ReceiverId 99 @@ -47,33 +47,33 @@ const char PROGMEM ENCRYPTKEY[] = "sampleEncryptKey"; const char PROGMEM MDNS_NAME[] = "rfm69gw1"; const char PROGMEM MQTT_BROKER[] = "raspi2"; const char PROGMEM RFM69AP_NAME[] = "RFM69-AP"; -#define NETWORKID 200 //the same on all nodes that talk to each other -#define NODEID 10 +#define NETWORKID 200 //the same on all nodes that talk to each other +#define NODEID 10 //Match frequency to the hardware version of the radio -#define FREQUENCY RF69_433MHZ +#define FREQUENCY RF69_433MHZ //#define FREQUENCY RF69_868MHZ //#define FREQUENCY RF69_915MHZ -#define IS_RFM69HCW true // set to 'true' if you are using an RFM69HCW module -#define POWER_LEVEL 31 +#define IS_RFM69HCW true // set to 'true' if you are using an RFM69HCW module +#define POWER_LEVEL 31 /*-------------------PIN DEFINITIONS----------------------*/ #if defined(ESP8266) - #define RFM69_CS D1 - #define RFM69_IRQ D8 // GPIO15/D8 - #define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ) - #define RFM69_RST D4 // GPIO02/D4 +# define RFM69_CS D1 +# define RFM69_IRQ D8 // GPIO15/D8 +# define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ) +# define RFM69_RST D4 // GPIO02/D4 #elif defined(ESP32) - #define RFM69_CS 1 - #define RFM69_IRQ 8 // GPIO15/D8 - #define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ) - #define RFM69_RST 4 // GPIO02/D4 +# define RFM69_CS 1 +# define RFM69_IRQ 8 // GPIO15/D8 +# define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ) +# define RFM69_RST 4 // GPIO02/D4 #else - //RFM69 not tested with arduino - #define RFM69_CS 10 - #define RFM69_IRQ 0 - #define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ) - #define RFM69_RST 9 +//RFM69 not tested with arduino +# define RFM69_CS 10 +# define RFM69_IRQ 0 +# define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ) +# define RFM69_RST 9 #endif -#endif \ No newline at end of file +#endif diff --git a/main/config_SRFB.h b/main/config_SRFB.h index 4bb0c5de..a43217ad 100644 --- a/main/config_SRFB.h +++ b/main/config_SRFB.h @@ -28,19 +28,19 @@ #define config_SRFB_h extern void setupSRFB(); -extern bool SRFBtoMQTT(); -extern void MQTTtoSRFB(char * topicOri, char * datacallback); -extern void MQTTtoSRFB(char * topicOri, JsonObject& RFdata); +extern bool SRFBtoMQTT(); +extern void MQTTtoSRFB(char* topicOri, char* datacallback); +extern void MQTTtoSRFB(char* topicOri, JsonObject& RFdata); /*-------------------RF topics & parameters----------------------*/ //433Mhz MQTT Subjects and keys -#define subjectMQTTtoSRFB "/commands/MQTTtoSRFB" -#define subjectMQTTtoSRFBRaw "/commands/MQTTtoSRFB/Raw" -#define subjectSRFBtoMQTT "/SRFBtoMQTT" -#define subjectGTWSRFBtoMQTT "/SRFBtoMQTT" -#define SRFBRptKey "RPT_" +#define subjectMQTTtoSRFB "/commands/MQTTtoSRFB" +#define subjectMQTTtoSRFBRaw "/commands/MQTTtoSRFB/Raw" +#define subjectSRFBtoMQTT "/SRFBtoMQTT" +#define subjectGTWSRFBtoMQTT "/SRFBtoMQTT" +#define SRFBRptKey "RPT_" #define SRFBmaxipulselengthKey "Thigh_" #define SRFBminipulselengthKey "Tlow_" -#define SRFBsyncKey "Tsyn_" +#define SRFBsyncKey "Tsyn_" #define repeatSRFBwMQTT false // do we repeat a received signal by using mqtt with Sonoff RF Bridge @@ -48,19 +48,19 @@ extern void MQTTtoSRFB(char * topicOri, JsonObject& RFdata); // RFBRIDGE // ----------------------------------------------------------------------------- -#define RF_SEND_TIMES 4 // How many times to send the message -#define RF_SEND_DELAY 500 // Interval between sendings in ms -#define RF_RECEIVE_DELAY 500 // Interval between recieving in ms (avoid debouncing) +#define RF_SEND_TIMES 4 // How many times to send the message +#define RF_SEND_DELAY 500 // Interval between sendings in ms +#define RF_RECEIVE_DELAY 500 // Interval between recieving in ms (avoid debouncing) // ----------------------------------------------------------------------------- // DEFINITIONS // ----------------------------------------------------------------------------- -#define RF_MESSAGE_SIZE 9 -#define RF_CODE_START 0xAA -#define RF_CODE_ACK 0xA0 -#define RF_CODE_RFIN 0xA4 -#define RF_CODE_RFOUT 0xA5 -#define RF_CODE_STOP 0x55 +#define RF_MESSAGE_SIZE 9 +#define RF_CODE_START 0xAA +#define RF_CODE_ACK 0xA0 +#define RF_CODE_RFIN 0xA4 +#define RF_CODE_RFOUT 0xA5 +#define RF_CODE_STOP 0x55 -#endif \ No newline at end of file +#endif diff --git a/main/config_TSL2561.h b/main/config_TSL2561.h index c07cf16b..066abb56 100644 --- a/main/config_TSL2561.h +++ b/main/config_TSL2561.h @@ -42,11 +42,11 @@ extern void setupTSL2561(); extern void TSL2561toMQTT(); -#define tsl2561_always true // if false only send current value if it has changed -#define TimeBetweenReadingtsl2561 30000 +#define tsl2561_always true // if false only send current value if it has changed +#define TimeBetweenReadingtsl2561 30000 /*----------------------------USER PARAMETERS-----------------------------*/ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ -#define subjectTSL12561toMQTT "/LIGHTtoMQTT" +#define subjectTSL12561toMQTT "/LIGHTtoMQTT" //Time used to wait for an interval before resending measured values unsigned long timetsl2561 = 0; diff --git a/main/config_WeatherStation.h b/main/config_WeatherStation.h index 2b133f36..35128d45 100644 --- a/main/config_WeatherStation.h +++ b/main/config_WeatherStation.h @@ -35,18 +35,17 @@ extern void ZgatewayWeatherStationtoMQTT(); /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ #define subjectRFtoMQTT "/433toMQTT" - /*-------------------PIN DEFINITIONS----------------------*/ #ifndef RF_WS_RECEIVER_PIN - #ifdef ESP8266 - #define RF_WS_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod - #elif ESP32 - #define RF_WS_RECEIVER_PIN 27 // D27 on DOIT ESP32 - #elif __AVR_ATmega2560__ - #define RF_WS_RECEIVER_PIN 1 //1 = D3 on mega - #else - #define RF_WS_RECEIVER_PIN 1 //1 = D3 on arduino - #endif +# ifdef ESP8266 +# define RF_WS_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod +# elif ESP32 +# define RF_WS_RECEIVER_PIN 27 // D27 on DOIT ESP32 +# elif __AVR_ATmega2560__ +# define RF_WS_RECEIVER_PIN 1 //1 = D3 on mega +# else +# define RF_WS_RECEIVER_PIN 1 //1 = D3 on arduino +# endif #endif #endif \ No newline at end of file diff --git a/main/config_mqttDiscovery.h b/main/config_mqttDiscovery.h index d7406187..4e59bb67 100644 --- a/main/config_mqttDiscovery.h +++ b/main/config_mqttDiscovery.h @@ -29,72 +29,72 @@ extern String getUniqueId(String name, String sufix); extern void pubMqttDiscovery(); -extern void createDiscoveryFromList(char *mac, char *sensorList[][8], int sensorCount); -extern void createDiscovery(char * sensor_type, - char * state_topic, char * s_name, char * unique_id, - char * availability_topic, char * device_class, char * value_template, - char * payload_on, char * payload_off, char * unit_of_meas, - int off_delay, - char * payload_available, char * payload_not_avalaible, bool child_device , char * command_topic); +extern void createDiscoveryFromList(char* mac, char* sensorList[][8], int sensorCount); +extern void createDiscovery(char* sensor_type, + char* state_topic, char* s_name, char* unique_id, + char* availability_topic, char* device_class, char* value_template, + char* payload_on, char* payload_off, char* unit_of_meas, + int off_delay, + char* payload_available, char* payload_not_avalaible, bool child_device, char* command_topic); #define discovery_Topic "homeassistant" #define DEVICEMANUFACTURER "OMG_community" /*-------------- Auto discovery macros-----------------*/ -// Set the line below to true so as to have autodiscovery working with OpenHAB +// Set the line below to true so as to have autodiscovery working with OpenHAB #define OpenHABDiscovery false #if OpenHABDiscovery // OpenHAB autodiscovery value key definition (is defined command is not supported by OpenHAB) -#define jsonBatt "{{ value_json.batt }}" -#define jsonLux "{{ value_json.lux }}" -#define jsonPres "{{ value_json.pres }}" -#define jsonFer "{{ value_json.fer }}" -#define jsonMoi "{{ value_json.moi }}" -#define jsonHum "{{ value_json.hum }}" -#define jsonTemp "{{ value_json.tem }}" -#define jsonStep "{{ value_json.steps }}" -#define jsonWeight "{{ value_json.weight }}" -#define jsonPresence "{{ value_json.presence }}" -#define jsonAltim "{{ value_json.altim }}" -#define jsonAltif "{{ value_json.altift }}" -#define jsonTempf "{{ value_json.tempf }}" -#define jsonMsg "{{ value_json.message }}" -#define jsonVal "{{ value_json.value }}" -#define jsonVolt "{{ value_json.volt }}" -#define jsonCurrent "{{ value_json.current }}" -#define jsonPower "{{ value_json.power }}" -#define jsonGpio "{{ value_json.gpio }}" -#define jsonFtcd "{{ value_json.ftcd }}" -#define jsonWm2 "{{ value_json.wattsm2 }}" -#define jsonAdc "{{ value_json.adc }}" -#define jsonPa "{{ float(value_json.pa) * 0.01 }}" -#define jsonId "{{ value_json.id }}" +# define jsonBatt "{{ value_json.batt }}" +# define jsonLux "{{ value_json.lux }}" +# define jsonPres "{{ value_json.pres }}" +# define jsonFer "{{ value_json.fer }}" +# define jsonMoi "{{ value_json.moi }}" +# define jsonHum "{{ value_json.hum }}" +# define jsonTemp "{{ value_json.tem }}" +# define jsonStep "{{ value_json.steps }}" +# define jsonWeight "{{ value_json.weight }}" +# define jsonPresence "{{ value_json.presence }}" +# define jsonAltim "{{ value_json.altim }}" +# define jsonAltif "{{ value_json.altift }}" +# define jsonTempf "{{ value_json.tempf }}" +# define jsonMsg "{{ value_json.message }}" +# define jsonVal "{{ value_json.value }}" +# define jsonVolt "{{ value_json.volt }}" +# define jsonCurrent "{{ value_json.current }}" +# define jsonPower "{{ value_json.power }}" +# define jsonGpio "{{ value_json.gpio }}" +# define jsonFtcd "{{ value_json.ftcd }}" +# define jsonWm2 "{{ value_json.wattsm2 }}" +# define jsonAdc "{{ value_json.adc }}" +# define jsonPa "{{ float(value_json.pa) * 0.01 }}" +# define jsonId "{{ value_json.id }}" #else // Home assistant autodiscovery value key definition -#define jsonBatt "{{ value_json.batt | is_defined }}" -#define jsonLux "{{ value_json.lux | is_defined }}" -#define jsonPres "{{ value_json.pres | is_defined }}" -#define jsonFer "{{ value_json.fer | is_defined }}" -#define jsonMoi "{{ value_json.moi | is_defined }}" -#define jsonHum "{{ value_json.hum | is_defined }}" -#define jsonTemp "{{ value_json.tem | is_defined }}" -#define jsonStep "{{ value_json.steps | is_defined }}" -#define jsonWeight "{{ value_json.weight | is_defined }}" -#define jsonPresence "{{ value_json.presence | is_defined }}" -#define jsonAltim "{{ value_json.altim | is_defined }}" -#define jsonAltif "{{ value_json.altift | is_defined }}" -#define jsonTempf "{{ value_json.tempf | is_defined }}" -#define jsonMsg "{{ value_json.message | is_defined }}" -#define jsonVal "{{ value_json.value | is_defined }}" -#define jsonVolt "{{ value_json.volt | is_defined }}" -#define jsonCurrent "{{ value_json.current | is_defined }}" -#define jsonPower "{{ value_json.power | is_defined }}" -#define jsonGpio "{{ value_json.gpio | is_defined }}" -#define jsonFtcd "{{ value_json.ftcd | is_defined }}" -#define jsonWm2 "{{ value_json.wattsm2 | is_defined }}" -#define jsonAdc "{{ value_json.adc | is_defined }}" -#define jsonPa "{{ float(value_json.pa) * 0.01 | is_defined }}" -#define jsonId "{{ value_json.id | is_defined }}" +# define jsonBatt "{{ value_json.batt | is_defined }}" +# define jsonLux "{{ value_json.lux | is_defined }}" +# define jsonPres "{{ value_json.pres | is_defined }}" +# define jsonFer "{{ value_json.fer | is_defined }}" +# define jsonMoi "{{ value_json.moi | is_defined }}" +# define jsonHum "{{ value_json.hum | is_defined }}" +# define jsonTemp "{{ value_json.tem | is_defined }}" +# define jsonStep "{{ value_json.steps | is_defined }}" +# define jsonWeight "{{ value_json.weight | is_defined }}" +# define jsonPresence "{{ value_json.presence | is_defined }}" +# define jsonAltim "{{ value_json.altim | is_defined }}" +# define jsonAltif "{{ value_json.altift | is_defined }}" +# define jsonTempf "{{ value_json.tempf | is_defined }}" +# define jsonMsg "{{ value_json.message | is_defined }}" +# define jsonVal "{{ value_json.value | is_defined }}" +# define jsonVolt "{{ value_json.volt | is_defined }}" +# define jsonCurrent "{{ value_json.current | is_defined }}" +# define jsonPower "{{ value_json.power | is_defined }}" +# define jsonGpio "{{ value_json.gpio | is_defined }}" +# define jsonFtcd "{{ value_json.ftcd | is_defined }}" +# define jsonWm2 "{{ value_json.wattsm2 | is_defined }}" +# define jsonAdc "{{ value_json.adc | is_defined }}" +# define jsonPa "{{ float(value_json.pa) * 0.01 | is_defined }}" +# define jsonId "{{ value_json.id | is_defined }}" #endif -#endif \ No newline at end of file +#endif diff --git a/main/main.ino b/main/main.ino index c93feafe..92fe1a6a 100644 --- a/main/main.ino +++ b/main/main.ino @@ -29,129 +29,130 @@ // array to store previous received RFs, IRs codes and their timestamps #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) -#define array_size 12 +# define array_size 12 unsigned long ReceivedSignal[array_size][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}}; //Time used to wait for an interval before checking system measures unsigned long timer_sys_measures = 0; #else // boards with smaller memory -#define array_size 4 +# define array_size 4 unsigned long ReceivedSignal[array_size][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}}; #endif -#include #include #include +#include // Modules config inclusion #if defined(ZgatewayRF) || defined(ZgatewayRF2) || defined(ZgatewayPilight) -#include "config_RF.h" +# include "config_RF.h" #endif #ifdef ZgatewayWeatherStation -#include "config_WeatherStation.h" +# include "config_WeatherStation.h" #endif #ifdef ZgatewayLORA -#include "config_LORA.h" +# include "config_LORA.h" #endif #ifdef ZgatewaySRFB -#include "config_SRFB.h" +# include "config_SRFB.h" #endif #ifdef ZgatewayBT -#include "config_BT.h" +# include "config_BT.h" #endif #ifdef ZgatewayIR -#include "config_IR.h" +# include "config_IR.h" #endif #ifdef Zgateway2G -#include "config_2G.h" +# include "config_2G.h" #endif #ifdef ZactuatorONOFF -#include "config_ONOFF.h" +# include "config_ONOFF.h" #endif #ifdef ZsensorINA226 -#include "config_INA226.h" +# include "config_INA226.h" #endif #ifdef ZsensorHCSR501 -#include "config_HCSR501.h" +# include "config_HCSR501.h" #endif #ifdef ZsensorADC -#include "config_ADC.h" +# include "config_ADC.h" #endif #ifdef ZsensorBH1750 -#include "config_BH1750.h" +# include "config_BH1750.h" #endif #ifdef ZsensorTSL2561 -#include "config_TSL2561.h" +# include "config_TSL2561.h" #endif #ifdef ZsensorBME280 -#include "config_BME280.h" +# include "config_BME280.h" #endif #ifdef ZsensorHTU21 -#include "config_HTU21.h" +# include "config_HTU21.h" #endif #ifdef ZsensorHCSR04 -#include "config_HCSR04.h" +# include "config_HCSR04.h" #endif #ifdef ZsensorDHT -#include "config_DHT.h" +# include "config_DHT.h" #endif #ifdef ZsensorDS1820 -#include "config_DS1820.h" +# include "config_DS1820.h" #endif #ifdef ZgatewayRFM69 -#include "config_RFM69.h" +# include "config_RFM69.h" #endif #ifdef ZsensorGPIOInput -#include "config_GPIOInput.h" +# include "config_GPIOInput.h" #endif #ifdef ZsensorGPIOKeyCode -#include "config_GPIOKeyCode.h" +# include "config_GPIOKeyCode.h" #endif #ifdef ZmqttDiscovery -#include "config_mqttDiscovery.h" +# include "config_mqttDiscovery.h" #endif #ifdef ZactuatorFASTLED -#include "config_FASTLED.h" +# include "config_FASTLED.h" #endif #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) -#include "config_M5.h" +# include "config_M5.h" #endif /*------------------------------------------------------------------------*/ //adding this to bypass the problem of the arduino builder issue 50 -void callback(char *topic, byte *payload, unsigned int length); +void callback(char* topic, byte* payload, unsigned int length); bool connectedOnce = false; //indicate if we have been connected once to MQTT int failure_number_ntwk = 0; // number of failure connecting to network int failure_number_mqtt = 0; // number of failure connecting to MQTT #ifdef ESP32 - #include - #include "SPIFFS.h" - #include - #include - #include - #include "esp_wifi.h" - WiFiClient eClient; - #include - #include - Preferences preferences; -#ifdef MDNS_SD - #include -#endif +# include +# include +# include +# include + +# include "SPIFFS.h" +# include "esp_wifi.h" +WiFiClient eClient; +# include +# include +Preferences preferences; +# ifdef MDNS_SD +# include +# endif #elif defined(ESP8266) - #include - #include - #include - #include - #include - #include - WiFiClient eClient; -#ifdef MDNS_SD - #include -#endif +# include +# include +# include +# include +# include +# include +WiFiClient eClient; +# ifdef MDNS_SD +# include +# endif #else - #include - EthernetClient eClient; +# include +EthernetClient eClient; #endif // client link to pubsub mqtt @@ -160,12 +161,10 @@ PubSubClient client(eClient); //MQTT last attemps reconnection date unsigned long lastMQTTReconnectAttempt = 0; -void revert_hex_data(char *in, char *out, int l) -{ +void revert_hex_data(char* in, char* out, int l) { //reverting array 2 by 2 to get the data in good order int i = l - 2, j = 0; - while (i != -2) - { + while (i != -2) { if (i % 2 == 0) out[j] = in[i + 1]; else @@ -176,13 +175,11 @@ void revert_hex_data(char *in, char *out, int l) out[l - 1] = '\0'; } -void extract_char(char *token_char, char *subset, int start, int l, bool reverse, bool isNumber) -{ +void extract_char(char* token_char, char* subset, int start, int l, bool reverse, bool isNumber) { char tmp_subset[l + 1]; memcpy(tmp_subset, &token_char[start], l); tmp_subset[l] = '\0'; - if (isNumber) - { + if (isNumber) { char tmp_subset2[l + 1]; if (reverse) revert_hex_data(tmp_subset, tmp_subset2, l + 1); @@ -191,9 +188,7 @@ void extract_char(char *token_char, char *subset, int start, int l, bool reverse long long_value = strtoul(tmp_subset2, NULL, 16); sprintf(tmp_subset2, "%ld", long_value); strncpy(subset, tmp_subset2, l + 1); - } - else - { + } else { if (reverse) revert_hex_data(tmp_subset, subset, l + 1); else @@ -202,47 +197,41 @@ void extract_char(char *token_char, char *subset, int start, int l, bool reverse subset[l] = '\0'; } -char *ip2CharArray(IPAddress ip) -{ //from Nick Lee https://stackoverflow.com/questions/28119653/arduino-display-ethernet-localip +char* ip2CharArray(IPAddress ip) { //from Nick Lee https://stackoverflow.com/questions/28119653/arduino-display-ethernet-localip static char a[16]; sprintf(a, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); return a; } -bool to_bool(String const &s) -{ // thanks Chris Jester-Young from stackoverflow +bool to_bool(String const& s) { // thanks Chris Jester-Young from stackoverflow return s != "0"; } -void pub(char *topicori, char *payload, bool retainFlag) -{ +void pub(char* topicori, char* payload, bool retainFlag) { String topic = String(mqtt_topic) + String(topicori); - pubMQTT((char *)topic.c_str(), payload, retainFlag); + pubMQTT((char*)topic.c_str(), payload, retainFlag); } -void pub(char *topicori, JsonObject &data) -{ - Log.notice(F("Subject: %s" CR),topicori); +void pub(char* topicori, JsonObject& data) { + Log.notice(F("Subject: %s" CR), topicori); logJson(data); - if (client.connected()) - { + if (client.connected()) { digitalWrite(led_receive, HIGH); String topic = String(mqtt_topic) + String(topicori); #ifdef valueAsASubject unsigned long value = data["value"]; - if (value != 0) - { + if (value != 0) { topic = topic + "/" + String(value); } #endif #ifdef jsonPublishing Log.trace(F("jsonPublishing" CR)); - #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) +# if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) char JSONmessageBuffer[data.measureLength() + 1]; - #else +# else char JSONmessageBuffer[JSON_MSG_BUFFER]; - #endif +# endif data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); pubMQTT(topic, JSONmessageBuffer); #endif @@ -250,213 +239,173 @@ void pub(char *topicori, JsonObject &data) #ifdef simplePublishing Log.trace(F("simplePublishing" CR)); // Loop through all the key-value pairs in obj - for (JsonPair &p : data) - { - #if defined(ESP8266) + for (JsonPair& p : data) { +# if defined(ESP8266) yield(); - #endif - if (p.value.is() && strcmp(p.key, "rssi") != 0) - { //test rssi , bypass solution due to the fact that a int is considered as an unsigned long - if (strcmp(p.key, "value") == 0) - { // if data is a value we don't integrate the name into the topic +# endif + if (p.value.is() && strcmp(p.key, "rssi") != 0) { //test rssi , bypass solution due to the fact that a int is considered as an unsigned long + if (strcmp(p.key, "value") == 0) { // if data is a value we don't integrate the name into the topic pubMQTT(topic, p.value.as()); - } - else - { // if data is not a value we integrate the name into the topic + } else { // if data is not a value we integrate the name into the topic pubMQTT(topic + "/" + String(p.key), p.value.as()); } - } - else if (p.value.is()) - { + } else if (p.value.is()) { pubMQTT(topic + "/" + String(p.key), p.value.as()); - } - else if (p.value.is()) - { + } else if (p.value.is()) { pubMQTT(topic + "/" + String(p.key), p.value.as()); - } - else if (p.value.is()) - { - pubMQTT(topic + "/" + String(p.key), p.value.as()); + } else if (p.value.is()) { + pubMQTT(topic + "/" + String(p.key), p.value.as()); } } #endif - } - else - { + } else { Log.warning(F("client not connected can't pub" CR)); } } -void pub(char *topicori, char *payload) -{ - if (client.connected()) - { +void pub(char* topicori, char* payload) { + if (client.connected()) { String topic = String(mqtt_topic) + String(topicori); Log.trace(F("Pub ack %s into: %s" CR), payload, topic.c_str()); pubMQTT(topic, payload); - } - else - { + } else { Log.warning(F("client not connected can't pub" CR)); } } -void pub_custom_topic(char *topicori, JsonObject &data, boolean retain) -{ - if (client.connected()) - { - #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) +void pub_custom_topic(char* topicori, JsonObject& data, boolean retain) { + if (client.connected()) { +#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) char JSONmessageBuffer[data.measureLength() + 1]; - #else +#else char JSONmessageBuffer[JSON_MSG_BUFFER]; - #endif +#endif data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); Log.trace(F("Pub json :%s into custom topic: %s" CR), JSONmessageBuffer, topicori); pubMQTT(topicori, JSONmessageBuffer, retain); - } - else - { + } else { Log.warning(F("client not connected can't pub" CR)); } } -// Low level MQTT functions -void pubMQTT(char * topic, char * payload) -{ - client.publish(topic, payload); +// Low level MQTT functions +void pubMQTT(char* topic, char* payload) { + client.publish(topic, payload); } -void pubMQTT(char * topicori, char * payload, bool retainFlag) -{ +void pubMQTT(char* topicori, char* payload, bool retainFlag) { client.publish(topicori, payload, retainFlag); } -void pubMQTT(String topic, char * payload) -{ - client.publish((char *)topic.c_str(),payload); +void pubMQTT(String topic, char* payload) { + client.publish((char*)topic.c_str(), payload); } -void pubMQTT(char *topic, unsigned long payload) -{ +void pubMQTT(char* topic, unsigned long payload) { char val[11]; sprintf(val, "%lu", payload); client.publish(topic, val); } -void pubMQTT(char *topic, unsigned long long payload) -{ +void pubMQTT(char* topic, unsigned long long payload) { char val[21]; sprintf(val, "%llu", payload); client.publish(topic, val); } -void pubMQTT(char *topic, String payload) -{ - client.publish(topic, (char *)payload.c_str()); +void pubMQTT(char* topic, String payload) { + client.publish(topic, (char*)payload.c_str()); } -void pubMQTT(String topic, String payload) -{ - client.publish((char *)topic.c_str(), (char *)payload.c_str()); +void pubMQTT(String topic, String payload) { + client.publish((char*)topic.c_str(), (char*)payload.c_str()); } -void pubMQTT(String topic, int payload) -{ +void pubMQTT(String topic, int payload) { char val[12]; sprintf(val, "%d", payload); - client.publish((char *)topic.c_str(), val); + client.publish((char*)topic.c_str(), val); } -void pubMQTT(String topic, float payload) -{ +void pubMQTT(String topic, float payload) { char val[12]; dtostrf(payload, 3, 1, val); - client.publish((char *)topic.c_str(), val); + client.publish((char*)topic.c_str(), val); } -void pubMQTT(char *topic, float payload) -{ +void pubMQTT(char* topic, float payload) { char val[12]; dtostrf(payload, 3, 1, val); client.publish(topic, val); } -void pubMQTT(char *topic, int payload) -{ +void pubMQTT(char* topic, int payload) { char val[6]; sprintf(val, "%d", payload); client.publish(topic, val); } -void pubMQTT(char *topic, unsigned int payload) -{ +void pubMQTT(char* topic, unsigned int payload) { char val[6]; sprintf(val, "%u", payload); client.publish(topic, val); } -void pubMQTT(char *topic, long payload) -{ +void pubMQTT(char* topic, long payload) { char val[11]; sprintf(val, "%l", payload); client.publish(topic, val); } -void pubMQTT(char *topic, double payload) -{ +void pubMQTT(char* topic, double payload) { char val[16]; sprintf(val, "%d", payload); client.publish(topic, val); } -void pubMQTT(String topic, unsigned long payload) -{ +void pubMQTT(String topic, unsigned long payload) { char val[11]; sprintf(val, "%lu", payload); - client.publish((char *)topic.c_str(), val); + client.publish((char*)topic.c_str(), val); } -void logJson(JsonObject &jsondata) -{ - #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) +void logJson(JsonObject& jsondata) { +#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) char JSONmessageBuffer[jsondata.measureLength() + 1]; - #else +#else char JSONmessageBuffer[JSON_MSG_BUFFER]; - #endif +#endif jsondata.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); - Log.notice(F("Received json : %s" CR),JSONmessageBuffer); + Log.notice(F("Received json : %s" CR), JSONmessageBuffer); } -bool cmpToMainTopic(char * topicOri, char * toAdd){ +bool cmpToMainTopic(char* topicOri, char* toAdd) { char topic[mqtt_topic_max_size]; - strcpy(topic,mqtt_topic); - strcat(topic,toAdd); - if (strstr(topicOri,topic) != NULL){ + strcpy(topic, mqtt_topic); + strcat(topic, toAdd); + if (strstr(topicOri, topic) != NULL) { return true; - }else{ + } else { return false; } } -void connectMQTT() -{ - +void connectMQTT() { #ifndef ESPWifiManualSetup - #if defined(ESP8266) || defined(ESP32) - checkButton(); // check if a reset of wifi/mqtt settings is asked - #endif +# if defined(ESP8266) || defined(ESP32) + checkButton(); // check if a reset of wifi/mqtt settings is asked +# endif #endif Log.warning(F("MQTT connection..." CR)); char topic[mqtt_topic_max_size]; - strcpy(topic,mqtt_topic); - strcat(topic,will_Topic); - if (client.connect(gateway_name, mqtt_user, mqtt_pass, topic, will_QoS, will_Retain, will_Message)) - { - #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) - if (low_power_mode < 2) + strcpy(topic, mqtt_topic); + strcat(topic, will_Topic); + if (client.connect(gateway_name, mqtt_user, mqtt_pass, topic, will_QoS, will_Retain, will_Message)) { +#if defined(ZboardM5STICKC) || defined(ZboardM5STACK) + if (low_power_mode < 2) M5Display("MQTT connected", "", ""); - #endif +#endif Log.notice(F("Connected to broker" CR)); failure_number_mqtt = 0; // Once connected, publish an announcement... @@ -465,98 +414,92 @@ void connectMQTT() pub(version_Topic, OMG_VERSION, will_Retain); //Subscribing to topic char topic2[mqtt_topic_max_size]; - strcpy(topic2,mqtt_topic); - strcat(topic2,subjectMQTTtoX); - if (client.subscribe(topic2)) - { - #ifdef ZgatewayRF + strcpy(topic2, mqtt_topic); + strcat(topic2, subjectMQTTtoX); + if (client.subscribe(topic2)) { +#ifdef ZgatewayRF client.subscribe(subjectMultiGTWRF); // subject on which other OMG will publish, this OMG will store these msg and by the way don't republish them if they have been already published - #endif - #ifdef ZgatewayIR +#endif +#ifdef ZgatewayIR client.subscribe(subjectMultiGTWIR); // subject on which other OMG will publish, this OMG will store these msg and by the way don't republish them if they have been already published - #endif +#endif Log.trace(F("Subscription OK to the subjects" CR)); } - } - else - { + } else { failure_number_mqtt++; // we count the failure Log.warning(F("failure_number_mqtt: %d" CR), failure_number_mqtt); Log.warning(F("failed, rc=%d" CR), client.state()); delay(5000); - #if defined(ESP8266) || defined(ESP32) +#if defined(ESP8266) || defined(ESP32) disconnection_handling(failure_number_mqtt); - #endif +#endif } } // Callback function, when the gateway receive an MQTT value on the topics subscribed this function is called -void callback(char *topic, byte *payload, unsigned int length) -{ +void callback(char* topic, byte* payload, unsigned int length) { // In order to republish this payload, a copy must be made // as the orignal payload buffer will be overwritten whilst // constructing the PUBLISH packet. Log.trace(F("Hey I got a callback " CR)); // Allocate the correct amount of memory for the payload copy - byte *p = (byte *)malloc(length + 1); + byte* p = (byte*)malloc(length + 1); // Copy the payload to the new buffer memcpy(p, payload, length); // Conversion to a printable string p[length] = '\0'; //launch the function to treat received data if this data concern OpenMQTTGateway if ((strstr(topic, subjectMultiGTWKey) != NULL) || (strstr(topic, subjectGTWSendKey) != NULL)) - receivingMQTT(topic, (char *)p); + receivingMQTT(topic, (char*)p); // Free the memory free(p); } -void setup_parameters() -{ +void setup_parameters() { strcat(mqtt_topic, gateway_name); } -void setup() -{ +void setup() { //Launch serial for debugging purposes Serial.begin(SERIAL_BAUD); Log.begin(LOG_LEVEL, &Serial); Log.notice(F(CR "************* WELCOME TO OpenMQTTGateway **************" CR)); #if defined(ESP8266) || defined(ESP32) - #ifdef ESP8266 - #ifndef ZgatewaySRFB // if we are not in sonoff rf bridge case we apply the ESP8266 pin optimization - Serial.end(); - Serial.begin(SERIAL_BAUD, SERIAL_8N1, SERIAL_TX_ONLY); // enable on ESP8266 to free some pin - #endif - #elif ESP32 - preferences.begin(Gateway_Short_Name, false); - low_power_mode = preferences.getUInt("low_power_mode", DEFAULT_LOW_POWER_MODE); - preferences.end(); - #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) - setupM5(); - #endif - #endif +# ifdef ESP8266 +# ifndef ZgatewaySRFB // if we are not in sonoff rf bridge case we apply the ESP8266 pin optimization + Serial.end(); + Serial.begin(SERIAL_BAUD, SERIAL_8N1, SERIAL_TX_ONLY); // enable on ESP8266 to free some pin +# endif +# elif ESP32 + preferences.begin(Gateway_Short_Name, false); + low_power_mode = preferences.getUInt("low_power_mode", DEFAULT_LOW_POWER_MODE); + preferences.end(); +# if defined(ZboardM5STICKC) || defined(ZboardM5STACK) + setupM5(); +# endif +# endif Log.trace(F("OpenMQTTGateway Wifi protocol used: %d" CR), wifiProtocol); - #if defined(ESPWifiManualSetup) +# if defined(ESPWifiManualSetup) setup_wifi(); - #else +# else setup_wifimanager(false); - #endif +# endif - Log.trace(F("OpenMQTTGateway mac: %s" CR),WiFi.macAddress().c_str()); - Log.trace(F("OpenMQTTGateway ip: %s" CR),WiFi.localIP().toString().c_str()); + Log.trace(F("OpenMQTTGateway mac: %s" CR), WiFi.macAddress().c_str()); + Log.trace(F("OpenMQTTGateway ip: %s" CR), WiFi.localIP().toString().c_str()); setOTA(); - #else // In case of arduino platform +#else // In case of arduino platform //Launch serial for debugging purposes Serial.begin(SERIAL_BAUD); //Begining ethernet connection in case of Arduino + W5100 setup_ethernet(); - #endif +#endif //setup LED status pinMode(led_receive, OUTPUT); @@ -566,23 +509,23 @@ void setup() digitalWrite(led_send, LOW); digitalWrite(led_info, LOW); - #if defined(MDNS_SD) && defined(ESP8266) +#if defined(MDNS_SD) && defined(ESP8266) Log.trace(F("Connecting to MQTT by mDNS without mqtt hostname" CR)); connectMQTTmdns(); - #else +#else long port; port = strtol(mqtt_port, NULL, 10); - Log.trace(F("Port: %l" CR),port); - #ifdef mqtt_server_name // if name is defined we define the mqtt server by its name - IPAddress mqtt_server_ip; - WiFi.hostByName(mqtt_server_name, mqtt_server_ip); - client.setServer(mqtt_server_ip, port); - Log.trace(F("Mqtt server connection by host name: %s" CR),mqtt_server_ip.toString()); - #else // if not by its IP adress - client.setServer(mqtt_server, port); - Log.trace(F("Mqtt server connection by IP: %s" CR),mqtt_server); - #endif - #endif + Log.trace(F("Port: %l" CR), port); +# ifdef mqtt_server_name // if name is defined we define the mqtt server by its name + IPAddress mqtt_server_ip; + WiFi.hostByName(mqtt_server_name, mqtt_server_ip); + client.setServer(mqtt_server_ip, port); + Log.trace(F("Mqtt server connection by host name: %s" CR), mqtt_server_ip.toString()); +# else // if not by its IP adress + client.setServer(mqtt_server, port); + Log.trace(F("Mqtt server connection by IP: %s" CR), mqtt_server); +# endif +#endif setup_parameters(); @@ -592,99 +535,98 @@ void setup() lastMQTTReconnectAttempt = 0; - #ifdef ZsensorBME280 +#ifdef ZsensorBME280 setupZsensorBME280(); - #endif - #ifdef ZsensorHTU21 +#endif +#ifdef ZsensorHTU21 setupZsensorHTU21(); - #endif - #ifdef ZsensorBH1750 +#endif +#ifdef ZsensorBH1750 setupZsensorBH1750(); - #endif - #ifdef ZsensorTSL2561 +#endif +#ifdef ZsensorTSL2561 setupZsensorTSL2561(); - #endif - #ifdef Zgateway2G +#endif +#ifdef Zgateway2G setup2G(); - #endif - #ifdef ZgatewayIR +#endif +#ifdef ZgatewayIR setupIR(); - #endif - #ifdef ZgatewayLORA +#endif +#ifdef ZgatewayLORA setupLORA(); - #endif - #ifdef ZgatewayRF +#endif +#ifdef ZgatewayRF setupRF(); - #endif - #ifdef ZgatewayRF2 +#endif +#ifdef ZgatewayRF2 setupRF2(); - #endif - #ifdef ZgatewayPilight +#endif +#ifdef ZgatewayPilight setupPilight(); - #endif - #ifdef ZgatewayWeatherStation +#endif +#ifdef ZgatewayWeatherStation setupWeatherStation(); - #endif - #ifdef ZgatewaySRFB +#endif +#ifdef ZgatewaySRFB setupSRFB(); - #endif - #ifdef ZgatewayBT +#endif +#ifdef ZgatewayBT setupBT(); - #endif - #ifdef ZgatewayRFM69 +#endif +#ifdef ZgatewayRFM69 setupRFM69(); - #endif - #ifdef ZsensorINA226 +#endif +#ifdef ZsensorINA226 setupINA226(); - #endif - #ifdef ZsensorHCSR501 +#endif +#ifdef ZsensorHCSR501 setupHCSR501(); - #endif - #ifdef ZsensorHCSR04 +#endif +#ifdef ZsensorHCSR04 setupHCSR04(); - #endif - #ifdef ZsensorGPIOInput +#endif +#ifdef ZsensorGPIOInput setupGPIOInput(); - #endif - #ifdef ZsensorGPIOKeyCode +#endif +#ifdef ZsensorGPIOKeyCode setupGPIOKeyCode(); - #endif - #ifdef ZactuatorFASTLED +#endif +#ifdef ZactuatorFASTLED setupFASTLED(); - #endif - #ifdef ZsensorDS1820 +#endif +#ifdef ZsensorDS1820 setupZsensorDS1820(); - #endif - #ifdef ZsensorADC +#endif +#ifdef ZsensorADC setupADC(); - #endif - #ifdef ZsensorDHT +#endif +#ifdef ZsensorDHT setupDHT(); - #endif - Log.trace(F("MQTT_MAX_PACKET_SIZE: %d" CR),MQTT_MAX_PACKET_SIZE); - #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) +#endif + Log.trace(F("MQTT_MAX_PACKET_SIZE: %d" CR), MQTT_MAX_PACKET_SIZE); +#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) if (MQTT_MAX_PACKET_SIZE == 128) Log.error(F("WRONG PUBSUBCLIENT LIBRARY USED PLEASE INSTALL THE ONE FROM RELEASE PAGE" CR)); - #endif +#endif Log.notice(F("Setup OpenMQTTGateway end" CR)); } #if defined(ESP8266) || defined(ESP32) // Bypass for ESP not reconnecting automaticaly the second time https://github.com/espressif/arduino-esp32/issues/2501 -bool wifi_reconnect_bypass(){ - uint8_t wifi_autoreconnect_cnt = 0; - #ifdef ESP32 - while (WiFi.status() != WL_CONNECTED && wifi_autoreconnect_cnt < maxConnectionRetryWifi) { - #else - while (WiFi.waitForConnectResult() != WL_CONNECTED && wifi_autoreconnect_cnt < maxConnectionRetryWifi) { - #endif +bool wifi_reconnect_bypass() { + uint8_t wifi_autoreconnect_cnt = 0; +# ifdef ESP32 + while (WiFi.status() != WL_CONNECTED && wifi_autoreconnect_cnt < maxConnectionRetryWifi) { +# else + while (WiFi.waitForConnectResult() != WL_CONNECTED && wifi_autoreconnect_cnt < maxConnectionRetryWifi) { +# endif Log.notice(F("Attempting Wifi connection with saved AP: %d" CR), wifi_autoreconnect_cnt); WiFi.begin(); delay(500); wifi_autoreconnect_cnt++; - } - if(wifi_autoreconnect_cnt < maxConnectionRetryWifi) - { + } + if (wifi_autoreconnect_cnt < maxConnectionRetryWifi) { return true; } else { return false; @@ -692,71 +634,64 @@ bool wifi_reconnect_bypass(){ } // the 2 methods below are used to recover wifi connection by changing the protocols -void forceWifiProtocol(){ -#ifdef ESP32 +void forceWifiProtocol() { +# ifdef ESP32 Log.warning(F("ESP32: Forcing to wifi %d" CR), wifiProtocol); esp_wifi_set_protocol(WIFI_IF_STA, wifiProtocol); -#elif ESP8266 +# elif ESP8266 Log.warning(F("ESP8266: Forcing to wifi %d" CR), wifiProtocol); WiFi.setPhyMode((WiFiPhyMode_t)wifiProtocol); -#endif +# endif } -void reinit_wifi() -{ +void reinit_wifi() { delay(10); WiFi.mode(WIFI_STA); if (!wifiProtocol) forceWifiProtocol(); WiFi.begin(); } -void disconnection_handling( int failure_number){ +void disconnection_handling(int failure_number) { Log.warning(F("disconnection_handling, failed %d times" CR), failure_number); - if (failure_number > maxConnectionRetry && !connectedOnce) - { - #ifndef ESPWifiManualSetup + if (failure_number > maxConnectionRetry && !connectedOnce) { +# ifndef ESPWifiManualSetup Log.error(F("Failed connecting 1st time to mqtt, reset wifi manager & erase network credentials" CR)); setup_wifimanager(true); - #endif - } - else if (failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_BG && connectedOnce) - { +# endif + } else if (failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_BG && connectedOnce) { Log.warning(F("Attempt to reinit wifi: %d" CR), wifiProtocol); reinit_wifi(); - } - else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_BG && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B ) // After maxConnectionRetry + ATTEMPTS_BEFORE_BG try to connect with BG protocol + } else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_BG && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B) // After maxConnectionRetry + ATTEMPTS_BEFORE_BG try to connect with BG protocol { - #ifdef ESP32 +# ifdef ESP32 wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G; - #elif ESP8266 +# elif ESP8266 wifiProtocol = WIFI_PHY_MODE_11G; - #endif +# endif Log.warning(F("Wifi Protocol changed to WIFI_11G: %d" CR), wifiProtocol); reinit_wifi(); - } - else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG ) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol + } else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol { - #ifdef ESP32 +# ifdef ESP32 wifiProtocol = WIFI_PROTOCOL_11B; - #elif ESP8266 +# elif ESP8266 wifiProtocol = WIFI_PHY_MODE_11B; - #endif +# endif Log.warning(F("Wifi Protocol changed to WIFI_11B: %d" CR), wifiProtocol); reinit_wifi(); - } - else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG ) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol + } else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol { - #ifdef ESP32 +# ifdef ESP32 wifiProtocol = 0; - #elif ESP8266 +# elif ESP8266 wifiProtocol = 0; - #endif +# endif Log.warning(F("Wifi Protocol reverted to normal mode: %d" CR), wifiProtocol); reinit_wifi(); } } -void setOTA(){ +void setOTA() { // Port defaults to 8266 ArduinoOTA.setPort(ota_port); @@ -793,34 +728,31 @@ void setOTA(){ #endif #if defined(ESPWifiManualSetup) -void setup_wifi() -{ - +void setup_wifi() { delay(10); WiFi.mode(WIFI_STA); if (!wifiProtocol) forceWifiProtocol(); // We start by connecting to a WiFi network Log.trace(F("Connecting to %s" CR), wifi_ssid); - #ifdef ESPWifiAdvancedSetup +# ifdef ESPWifiAdvancedSetup IPAddress ip_adress(ip); IPAddress gateway_adress(gateway); IPAddress subnet_adress(subnet); IPAddress dns_adress(Dns); - if (!WiFi.config(ip_adress, gateway_adress, subnet_adress, dns_adress)) - { + if (!WiFi.config(ip_adress, gateway_adress, subnet_adress, dns_adress)) { Log.error(F("Wifi STA Failed to configure" CR)); } WiFi.begin(wifi_ssid, wifi_password); - #else +# else WiFi.begin(wifi_ssid, wifi_password); - #endif +# endif - if(wifi_reconnect_bypass()); - Log.notice(F("Connected with saved credentials" CR)); + if (wifi_reconnect_bypass()) + ; + Log.notice(F("Connected with saved credentials" CR)); - while (WiFi.status() != WL_CONNECTED) - { + while (WiFi.status() != WL_CONNECTED) { delay(500); Log.trace(F("." CR)); failure_number_ntwk++; @@ -838,26 +770,21 @@ bool shouldSaveConfig = true; //do we have been connected once to mqtt //callback notifying us of the need to save config -void saveConfigCallback() -{ +void saveConfigCallback() { Log.trace(F("Should save config" CR)); shouldSaveConfig = true; } -void checkButton() -{ // code from tzapu/wifimanager examples +void checkButton() { // code from tzapu/wifimanager examples // check for button press - if (digitalRead(TRIGGER_PIN) == LOW) - { + if (digitalRead(TRIGGER_PIN) == LOW) { // poor mans debounce/press-hold, code not ideal for production delay(50); - if (digitalRead(TRIGGER_PIN) == LOW) - { + if (digitalRead(TRIGGER_PIN) == LOW) { Log.trace(F("Trigger button Pressed" CR)); // still holding button for 3000 ms, reset settings, code not ideaa for production delay(3000); // reset delay hold - if (digitalRead(TRIGGER_PIN) == LOW) - { + if (digitalRead(TRIGGER_PIN) == LOW) { Log.trace(F("Button Held" CR)); Log.notice(F("Erasing ESP Config, restarting" CR)); setup_wifimanager(true); @@ -866,28 +793,25 @@ void checkButton() } } -void eraseAndRestart() -{ - #if defined(ESP8266) +void eraseAndRestart() { +# if defined(ESP8266) WiFi.disconnect(true); - #else +# else WiFi.disconnect(true, true); - #endif +# endif Log.trace(F("Formatting requested, result: %d" CR), SPIFFS.format()); - #if defined(ESP8266) +# if defined(ESP8266) ESP.eraseConfig(); delay(5000); ESP.reset(); - #else +# else ESP.restart(); - #endif +# endif } -void setup_wifimanager(bool reset_settings) -{ - +void setup_wifimanager(bool reset_settings) { pinMode(TRIGGER_PIN, INPUT_PULLUP); delay(10); @@ -900,34 +824,28 @@ void setup_wifimanager(bool reset_settings) //read configuration from FS json Log.trace(F("mounting FS..." CR)); - if (SPIFFS.begin()) - { + if (SPIFFS.begin()) { Log.trace(F("mounted file system" CR)); - } - else - { + } else { Log.warning(F("failed to mount FS -> formating" CR)); SPIFFS.format(); if (SPIFFS.begin()) Log.trace(F("mounted file system after formating" CR)); } - if (SPIFFS.exists("/config.json")) - { + if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Log.trace(F("reading config file" CR)); File configFile = SPIFFS.open("/config.json", "r"); - if (configFile) - { + if (configFile) { Log.trace(F("opened config file" CR)); size_t size = configFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; - JsonObject &json = jsonBuffer.parseObject(buf.get()); + JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); - if (json.success()) - { + if (json.success()) { Log.trace(F("\nparsed json" CR)); if (json.containsKey("mqtt_server")) strcpy(mqtt_server, json["mqtt_server"]); @@ -941,9 +859,7 @@ void setup_wifimanager(bool reset_settings) strcpy(mqtt_topic, json["mqtt_topic"]); if (json.containsKey("gateway_name")) strcpy(gateway_name, json["gateway_name"]); - } - else - { + } else { Log.warning(F("failed to load json config" CR)); } } @@ -969,14 +885,14 @@ void setup_wifimanager(bool reset_settings) //set config save notify callback wifiManager.setSaveConfigCallback(saveConfigCallback); - //set static ip - #ifdef NetworkAdvancedSetup +//set static ip +# ifdef NetworkAdvancedSetup Log.trace(F("Adv wifi cfg" CR)); IPAddress gateway_adress(gateway); IPAddress subnet_adress(subnet); IPAddress ip_adress(ip); - wifiManager.setSTAStaticIPConfig(ip_adress, gateway_adress,subnet_adress); - #endif + wifiManager.setSTAStaticIPConfig(ip_adress, gateway_adress, subnet_adress); +# endif //add all your parameters here wifiManager.addParameter(&custom_mqtt_server); @@ -989,43 +905,41 @@ void setup_wifimanager(bool reset_settings) //set minimum quality of signal so it ignores AP's under that quality wifiManager.setMinimumSignalQuality(MinimumWifiSignalQuality); - if(!wifi_reconnect_bypass())// if we didn't connect with saved credential we start Wifimanager web portal + if (!wifi_reconnect_bypass()) // if we didn't connect with saved credential we start Wifimanager web portal { - #ifdef ESP32 - if (low_power_mode < 2) - { - #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) +# ifdef ESP32 + if (low_power_mode < 2) { +# if defined(ZboardM5STICKC) || defined(ZboardM5STACK) M5Display("Connect your phone to WIFI AP:", WifiManager_ssid, WifiManager_password); - #endif +# endif } else { // in case of low power mode we put the ESP to sleep again if we didn't get connected (typical in case the wifi is down) - #ifdef ZgatewayBT +# ifdef ZgatewayBT lowPowerESP32(); - #endif +# endif } - #endif +# endif - Log.notice(F("Connect your phone to WIFI AP: %s with PWD: %s" CR), WifiManager_ssid, WifiManager_password ); + Log.notice(F("Connect your phone to WIFI AP: %s with PWD: %s" CR), WifiManager_ssid, WifiManager_password); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password)) - { + if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password)) { Log.warning(F("failed to connect and hit timeout" CR)); delay(3000); - //reset and try again - #if defined(ESP8266) +//reset and try again +# if defined(ESP8266) ESP.reset(); - #else +# else ESP.restart(); - #endif +# endif delay(5000); } } - #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) - if (low_power_mode < 2) +# if defined(ZboardM5STICKC) || defined(ZboardM5STACK) + if (low_power_mode < 2) M5Display("Wifi connected", "", ""); - #endif +# endif //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); @@ -1036,11 +950,10 @@ void setup_wifimanager(bool reset_settings) strcpy(gateway_name, custom_gateway_name.getValue()); //save the custom parameters to FS - if (shouldSaveConfig) - { + if (shouldSaveConfig) { Log.trace(F("saving config" CR)); DynamicJsonBuffer jsonBuffer; - JsonObject &json = jsonBuffer.createObject(); + JsonObject& json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; json["mqtt_port"] = mqtt_port; json["mqtt_user"] = mqtt_user; @@ -1049,8 +962,7 @@ void setup_wifimanager(bool reset_settings) json["gateway_name"] = gateway_name; File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) - { + if (!configFile) { Log.error(F("failed to open config file for writing" CR)); } @@ -1062,71 +974,56 @@ void setup_wifimanager(bool reset_settings) } #else // Arduino case -void setup_ethernet() -{ - #ifdef NetworkAdvancedSetup +void setup_ethernet() { +# ifdef NetworkAdvancedSetup Log.trace(F("Adv eth cfg" CR)); Ethernet.begin(mac, ip, Dns, gateway, subnet); - #else +# else Log.trace(F("Spl eth cfg" CR)); Ethernet.begin(mac, ip); - #endif - if (Ethernet.hardwareStatus() == EthernetNoHardware) - { +# endif + if (Ethernet.hardwareStatus() == EthernetNoHardware) { Log.error(F("Ethernet shield was not found." CR)); - } - else - { - Log.trace(F("ip: %s " CR),Ethernet.localIP()); + } else { + Log.trace(F("ip: %s " CR), Ethernet.localIP()); } } #endif #if defined(MDNS_SD) && defined(ESP8266) -void connectMQTTmdns() -{ - if (!MDNS.begin("ESP_MQTT")) - { +void connectMQTTmdns() { + if (!MDNS.begin("ESP_MQTT")) { Log.error(F("Error setting up MDNS responder!" CR)); - while (1) - { + while (1) { delay(1000); } } Log.trace(F("Browsing for MQTT service" CR)); int n = MDNS.queryService("mqtt", "tcp"); - if (n == 0) - { + if (n == 0) { Log.error(F("no services found" CR)); - } - else - { - Log.trace(F("%d service(s) found" CR),n); - for (int i = 0; i < n; ++i) - { - Log.trace(F("Service %d %s found" CR),i, MDNS.hostname(i).c_str()); - Log.trace(F("IP %s Port %d" CR),MDNS.IP(i).toString().c_str(), MDNS.port(i)); + } else { + Log.trace(F("%d service(s) found" CR), n); + for (int i = 0; i < n; ++i) { + Log.trace(F("Service %d %s found" CR), i, MDNS.hostname(i).c_str()); + Log.trace(F("IP %s Port %d" CR), MDNS.IP(i).toString().c_str(), MDNS.port(i)); } - if (n == 1) - { + if (n == 1) { Log.trace(F("One MQTT server found setting parameters" CR)); client.setServer(MDNS.IP(0), int(MDNS.port(0))); - } - else - { + } else { Log.error(F("Several MQTT servers found, please deactivate mDNS and set your default server" CR)); } } } #endif -void loop() -{ - #ifndef ESPWifiManualSetup - #if defined(ESP8266) || defined(ESP32) - checkButton(); // check if a reset of wifi/mqtt settings is asked - #endif - #endif +void loop() { +#ifndef ESPWifiManualSetup +# if defined(ESP8266) || defined(ESP32) + checkButton(); // check if a reset of wifi/mqtt settings is asked +# endif +#endif digitalWrite(led_receive, LOW); digitalWrite(led_info, LOW); @@ -1134,244 +1031,234 @@ void loop() unsigned long now = millis(); - #if defined(ESP8266) || defined(ESP32) - if (WiFi.status() == WL_CONNECTED) - { - #else - if ((Ethernet.hardwareStatus() != EthernetW5100 && Ethernet.linkStatus() == LinkON) || (Ethernet.hardwareStatus() == EthernetW5100)) - { //we are able to detect disconnection only on w5200 and w5500 - #endif +#if defined(ESP8266) || defined(ESP32) + if (WiFi.status() == WL_CONNECTED) { +#else + if ((Ethernet.hardwareStatus() != EthernetW5100 && Ethernet.linkStatus() == LinkON) || (Ethernet.hardwareStatus() == EthernetW5100)) { //we are able to detect disconnection only on w5200 and w5500 +#endif failure_number_ntwk = 0; - if (client.connected()) - { - - #ifdef ZmqttDiscovery - if(!connectedOnce) pubMqttDiscovery(); // at first connection we publish the discovery payloads - #endif + if (client.connected()) { +#ifdef ZmqttDiscovery + if (!connectedOnce) pubMqttDiscovery(); // at first connection we publish the discovery payloads +#endif connectedOnce = true; failure_number_ntwk = 0; client.loop(); - #if defined(ESP8266) || defined(ESP32) +#if defined(ESP8266) || defined(ESP32) ArduinoOTA.handle(); - #endif +#endif - #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) - if (now > (timer_sys_measures + (TimeBetweenReadingSYS * 1000)) || !timer_sys_measures) - { +#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) + if (now > (timer_sys_measures + (TimeBetweenReadingSYS * 1000)) || !timer_sys_measures) { timer_sys_measures = millis(); stateMeasures(); } - #endif - #ifdef ZsensorBME280 +#endif +#ifdef ZsensorBME280 MeasureTempHumAndPressure(); //Addon to measure Temperature, Humidity, Pressure and Altitude with a Bosch BME280 - #endif - #ifdef ZsensorHTU21 +#endif +#ifdef ZsensorHTU21 MeasureTempHum(); //Addon to measure Temperature, Humidity, of a HTU21 sensor - #endif - #ifdef ZsensorHCSR04 +#endif +#ifdef ZsensorHCSR04 MeasureDistance(); //Addon to measure distance with a HC-SR04 - #endif - #ifdef ZsensorBH1750 +#endif +#ifdef ZsensorBH1750 MeasureLightIntensity(); //Addon to measure Light Intensity with a BH1750 - #endif - #ifdef ZsensorTSL2561 +#endif +#ifdef ZsensorTSL2561 MeasureLightIntensityTSL2561(); - #endif - #ifdef ZsensorDHT +#endif +#ifdef ZsensorDHT MeasureTempAndHum(); //Addon to measure the temperature with a DHT - #endif - #ifdef ZsensorDS1820 - MeasureDS1820Temp(); //Addon to measure the temperature with DS1820 sensor(s) - #endif - #ifdef ZsensorINA226 +#endif +#ifdef ZsensorDS1820 + MeasureDS1820Temp(); //Addon to measure the temperature with DS1820 sensor(s) +#endif +#ifdef ZsensorINA226 MeasureINA226(); - #endif - #ifdef ZsensorHCSR501 +#endif +#ifdef ZsensorHCSR501 MeasureHCSR501(); - #endif - #ifdef ZsensorGPIOInput +#endif +#ifdef ZsensorGPIOInput MeasureGPIOInput(); - #endif - #ifdef ZsensorGPIOKeyCode +#endif +#ifdef ZsensorGPIOKeyCode MeasureGPIOKeyCode(); - #endif - #ifdef ZsensorADC +#endif +#ifdef ZsensorADC MeasureADC(); //Addon to measure the analog value of analog pin - #endif - #ifdef ZgatewayLORA +#endif +#ifdef ZgatewayLORA LORAtoMQTT(); - #endif - #ifdef ZgatewayRF +#endif +#ifdef ZgatewayRF RFtoMQTT(); - #endif - #ifdef ZgatewayRF2 +#endif +#ifdef ZgatewayRF2 RF2toMQTT(); - #endif - #ifdef ZgatewayWeatherStation +#endif +#ifdef ZgatewayWeatherStation ZgatewayWeatherStationtoMQTT(); - #endif - #ifdef ZgatewayPilight +#endif +#ifdef ZgatewayPilight PilighttoMQTT(); - #endif - #ifdef ZgatewayBT - #ifndef ESP32 - if (BTtoMQTT()) - Log.trace(F("BTtoMQTT OK" CR)); - #endif - #endif - #ifdef ZgatewaySRFB +#endif +#ifdef ZgatewayBT +# ifndef ESP32 + if (BTtoMQTT()) + Log.trace(F("BTtoMQTT OK" CR)); +# endif +#endif +#ifdef ZgatewaySRFB SRFBtoMQTT(); - #endif - #ifdef ZgatewayIR +#endif +#ifdef ZgatewayIR IRtoMQTT(); - #endif - #ifdef Zgateway2G +#endif +#ifdef Zgateway2G if (_2GtoMQTT()) Log.trace(F("2GtoMQTT OK" CR)); - #endif - #ifdef ZgatewayRFM69 +#endif +#ifdef ZgatewayRFM69 if (RFM69toMQTT()) Log.trace(F("RFM69toMQTT OK" CR)); - #endif - #ifdef ZactuatorFASTLED +#endif +#ifdef ZactuatorFASTLED FASTLEDLoop(); - #endif - } - else - { +#endif + } else { connectMQTT(); } - } - else - { // disconnected from network - #if defined(ESP8266) || defined(ESP32) + } else { // disconnected from network +#if defined(ESP8266) || defined(ESP32) Log.warning(F("wifi disconnected" CR)); delay(10000); // add a delay to avoid ESP32 crash and reset failure_number_ntwk++; disconnection_handling(failure_number_ntwk); - #else +#else Log.warning(F("eth disconnected" CR)); - #endif +#endif } - // Function that doesn't need an active connection - #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) +// Function that doesn't need an active connection +#if defined(ZboardM5STICKC) || defined(ZboardM5STACK) loopM5(); - #endif +#endif } #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) -void stateMeasures() -{ +void stateMeasures() { StaticJsonBuffer jsonBuffer; - JsonObject &SYSdata = jsonBuffer.createObject(); + JsonObject& SYSdata = jsonBuffer.createObject(); unsigned long uptime = millis() / 1000; SYSdata["uptime"] = uptime; SYSdata["version"] = OMG_VERSION; Log.trace(F("retrieving value of system characteristics Uptime (s):%u" CR), uptime); - #if defined(ESP8266) || defined(ESP32) - uint32_t freeMem; - freeMem = ESP.getFreeHeap(); - SYSdata["freemem"] = freeMem; - long rssi = WiFi.RSSI(); - SYSdata["rssi"] = rssi; - String SSID = WiFi.SSID(); - SYSdata["SSID"] = SSID; - SYSdata["ip"] = ip2CharArray(WiFi.localIP()); - String mac = WiFi.macAddress(); - SYSdata["mac"] = (char *)mac.c_str(); - SYSdata["wifiprt"] = (int)wifiProtocol; - #else - SYSdata["ip"] = ip2CharArray(Ethernet.localIP()); - #endif +# if defined(ESP8266) || defined(ESP32) + uint32_t freeMem; + freeMem = ESP.getFreeHeap(); + SYSdata["freemem"] = freeMem; + long rssi = WiFi.RSSI(); + SYSdata["rssi"] = rssi; + String SSID = WiFi.SSID(); + SYSdata["SSID"] = SSID; + SYSdata["ip"] = ip2CharArray(WiFi.localIP()); + String mac = WiFi.macAddress(); + SYSdata["mac"] = (char*)mac.c_str(); + SYSdata["wifiprt"] = (int)wifiProtocol; +# else + SYSdata["ip"] = ip2CharArray(Ethernet.localIP()); +# endif String modules = ""; - #ifdef ZgatewayRF +# ifdef ZgatewayRF modules = modules + ZgatewayRF; - #endif - #ifdef ZsensorBME280 +# endif +# ifdef ZsensorBME280 modules = modules + ZsensorBME280; - #endif - #ifdef ZsensorHTU21 +# endif +# ifdef ZsensorHTU21 modules = modules + ZsensorHTU21; - #endif - #ifdef ZsensorHCSR04 +# endif +# ifdef ZsensorHCSR04 modules = modules + ZsensorHCSR04; - #endif - #ifdef ZsensorBH1750 +# endif +# ifdef ZsensorBH1750 modules = modules + ZsensorBH1750; - #endif - #ifdef ZsensorTSL2561 +# endif +# ifdef ZsensorTSL2561 modules = modules + ZsensorTSL2561; - #endif - #ifdef ZsensorDHT +# endif +# ifdef ZsensorDHT modules = modules + ZsensorDHT; - #endif - #ifdef ZsensorDS1820 +# endif +# ifdef ZsensorDS1820 modules = modules + ZsensorDS1820; - #endif - #ifdef ZactuatorONOFF +# endif +# ifdef ZactuatorONOFF modules = modules + ZactuatorONOFF; - #endif - #ifdef Zgateway2G +# endif +# ifdef Zgateway2G modules = modules + Zgateway2G; - #endif - #ifdef ZgatewayIR +# endif +# ifdef ZgatewayIR modules = modules + ZgatewayIR; - #endif - #ifdef ZgatewayLORA +# endif +# ifdef ZgatewayLORA modules = modules + ZgatewayLORA; - #endif - #ifdef ZgatewayRF2 +# endif +# ifdef ZgatewayRF2 modules = modules + ZgatewayRF2; - #endif - #ifdef ZgatewayWeatherStation +# endif +# ifdef ZgatewayWeatherStation modules = modules + ZgatewayWeatherStation; - #endif - #ifdef ZgatewayPilight +# endif +# ifdef ZgatewayPilight modules = modules + ZgatewayPilight; - #endif - #ifdef ZgatewaySRFB +# endif +# ifdef ZgatewaySRFB modules = modules + ZgatewaySRFB; - #endif - #ifdef ZgatewayBT +# endif +# ifdef ZgatewayBT modules = modules + ZgatewayBT; - #ifdef ESP32 - SYSdata["lowpowermode"] = (int)low_power_mode; - #endif - #endif - #ifdef ZgatewayRFM69 +# ifdef ESP32 + SYSdata["lowpowermode"] = (int)low_power_mode; +# endif +# endif +# ifdef ZgatewayRFM69 modules = modules + ZgatewayRFM69; - #endif - #ifdef ZsensorINA226 +# endif +# ifdef ZsensorINA226 modules = modules + ZsensorINA226; - #endif - #ifdef ZsensorHCSR501 +# endif +# ifdef ZsensorHCSR501 modules = modules + ZsensorHCSR501; - #endif - #ifdef ZsensorGPIOInput +# endif +# ifdef ZsensorGPIOInput modules = modules + ZsensorGPIOInput; - #endif - #ifdef ZsensorGPIOKeyCode +# endif +# ifdef ZsensorGPIOKeyCode modules = modules + ZsensorGPIOKeyCode; - #endif - #ifdef ZsensorGPIOKeyCode +# endif +# ifdef ZsensorGPIOKeyCode modules = modules + ZsensorGPIOKeyCode; - #endif - #ifdef ZmqttDiscovery +# endif +# ifdef ZmqttDiscovery modules = modules + ZmqttDiscovery; - #endif - #ifdef ZactuatorFASTLED +# endif +# ifdef ZactuatorFASTLED modules = modules + ZactuatorFASTLED; - #endif - #ifdef ZboardM5STACK +# endif +# ifdef ZboardM5STACK M5.Power.begin(); SYSdata["m5-batt-level"] = (int8_t)M5.Power.getBatteryLevel(); SYSdata["m5-is-charging"] = (bool)M5.Power.isCharging(); SYSdata["m5-is-chargefull"] = (bool)M5.Power.isChargeFull(); - #endif - #ifdef ZboardM5STICKC +# endif +# ifdef ZboardM5STICKC M5.Axp.EnableCoulombcounter(); SYSdata["m5-bat-voltage"] = (float)M5.Axp.GetBatVoltage(); SYSdata["m5-bat-current"] = (float)M5.Axp.GetBatCurrent(); @@ -1383,37 +1270,32 @@ void stateMeasures() SYSdata["m5-bat-power"] = (float)M5.Axp.GetBatPower(); SYSdata["m5-bat-chargecurrent"] = (float)M5.Axp.GetBatChargeCurrent(); SYSdata["m5-aps-voltage"] = (float)M5.Axp.GetAPSVoltage(); - #endif +# endif SYSdata["modules"] = modules; pub(subjectSYStoMQTT, SYSdata); } #endif -void storeValue(unsigned long MQTTvalue) -{ +void storeValue(unsigned long MQTTvalue) { unsigned long now = millis(); // find oldest value of the buffer int o = getMin(); - Log.trace(F("Min ind: %d" CR),o); + Log.trace(F("Min ind: %d" CR), o); // replace it by the new one ReceivedSignal[o][0] = MQTTvalue; ReceivedSignal[o][1] = now; - Log.trace(F("store code : %u / %u" CR),ReceivedSignal[o][0],ReceivedSignal[o][1]); + Log.trace(F("store code : %u / %u" CR), ReceivedSignal[o][0], ReceivedSignal[o][1]); Log.trace(F("Col: val/timestamp" CR)); - for (int i = 0; i < array_size; i++) - { - Log.trace(F("mem code : %u / %u" CR),ReceivedSignal[i][0],ReceivedSignal[i][1]); + for (int i = 0; i < array_size; i++) { + Log.trace(F("mem code : %u / %u" CR), ReceivedSignal[i][0], ReceivedSignal[i][1]); } } -int getMin() -{ +int getMin() { unsigned int minimum = ReceivedSignal[0][1]; int minindex = 0; - for (int i = 0; i < array_size; i++) - { - if (ReceivedSignal[i][1] < minimum) - { + for (int i = 0; i < array_size; i++) { + if (ReceivedSignal[i][1] < minimum) { minimum = ReceivedSignal[i][1]; minindex = i; } @@ -1421,17 +1303,13 @@ int getMin() return minindex; } -bool isAduplicate(unsigned long value) -{ +bool isAduplicate(unsigned long value) { Log.trace(F("isAdupl?" CR)); // check if the value has been already sent during the last time_avoid_duplicate - for (int i = 0; i < array_size; i++) - { - if (ReceivedSignal[i][0] == value) - { + for (int i = 0; i < array_size; i++) { + if (ReceivedSignal[i][0] == value) { unsigned long now = millis(); - if (now - ReceivedSignal[i][1] < time_avoid_duplicate) - { // change + if (now - ReceivedSignal[i][1] < time_avoid_duplicate) { // change Log.notice(F("no pub. dupl" CR)); return true; } @@ -1440,108 +1318,102 @@ bool isAduplicate(unsigned long value) return false; } -void receivingMQTT(char *topicOri, char *datacallback) -{ - +void receivingMQTT(char* topicOri, char* datacallback) { StaticJsonBuffer jsonBuffer; - JsonObject &jsondata = jsonBuffer.parseObject(datacallback); + JsonObject& jsondata = jsonBuffer.parseObject(datacallback); if (strstr(topicOri, subjectMultiGTWKey) != NULL) // storing received value so as to avoid publishing this value if it has been already sent by this or another OpenMQTTGateway { unsigned long data = 0; - #ifdef jsonPublishing +#ifdef jsonPublishing if (jsondata.success()) data = jsondata["value"]; - #endif +#endif - #ifdef simplePublishing +#ifdef simplePublishing data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 - #endif +#endif - if (data != 0) - { + if (data != 0) { storeValue(data); } } - if (jsondata.success()) - { // json object ok -> json decoding + if (jsondata.success()) { // json object ok -> json decoding // log the received json logJson(jsondata); - #ifdef ZgatewayPilight // ZgatewayPilight is only defined with json publishing due to its numerous parameters +#ifdef ZgatewayPilight // ZgatewayPilight is only defined with json publishing due to its numerous parameters MQTTtoPilight(topicOri, jsondata); - #endif - #ifdef jsonReceiving - #ifdef ZgatewayLORA - MQTTtoLORA(topicOri, jsondata); - #endif - #ifdef ZgatewayRF - MQTTtoRF(topicOri, jsondata); - #endif - #ifdef ZgatewayRF2 - MQTTtoRF2(topicOri, jsondata); - #endif - #ifdef Zgateway2G - MQTTto2G(topicOri, jsondata); - #endif - #ifdef ZgatewaySRFB - MQTTtoSRFB(topicOri, jsondata); - #endif - #ifdef ZgatewayIR - MQTTtoIR(topicOri, jsondata); - #endif - #ifdef ZgatewayRFM69 - MQTTtoRFM69(topicOri, jsondata); - #endif - #ifdef ZgatewayBT - MQTTtoBT(topicOri, jsondata); - #endif - #ifdef ZactuatorFASTLED - MQTTtoFASTLED(topicOri, jsondata); - #endif - #if defined(ZboardM5STICKC) || defined(ZboardM5STACK) - MQTTtoM5(topicOri, jsondata); - #endif - #endif - #ifdef ZactuatorONOFF // outside the jsonpublishing macro due to the fact that we need to use simplepublishing with HA discovery +#endif +#ifdef jsonReceiving +# ifdef ZgatewayLORA + MQTTtoLORA(topicOri, jsondata); +# endif +# ifdef ZgatewayRF + MQTTtoRF(topicOri, jsondata); +# endif +# ifdef ZgatewayRF2 + MQTTtoRF2(topicOri, jsondata); +# endif +# ifdef Zgateway2G + MQTTto2G(topicOri, jsondata); +# endif +# ifdef ZgatewaySRFB + MQTTtoSRFB(topicOri, jsondata); +# endif +# ifdef ZgatewayIR + MQTTtoIR(topicOri, jsondata); +# endif +# ifdef ZgatewayRFM69 + MQTTtoRFM69(topicOri, jsondata); +# endif +# ifdef ZgatewayBT + MQTTtoBT(topicOri, jsondata); +# endif +# ifdef ZactuatorFASTLED + MQTTtoFASTLED(topicOri, jsondata); +# endif +# if defined(ZboardM5STICKC) || defined(ZboardM5STACK) + MQTTtoM5(topicOri, jsondata); +# endif +#endif +#ifdef ZactuatorONOFF // outside the jsonpublishing macro due to the fact that we need to use simplepublishing with HA discovery MQTTtoONOFF(topicOri, jsondata); - #endif +#endif digitalWrite(led_send, HIGH); MQTTtoSYS(topicOri, jsondata); - } - else - { // not a json object --> simple decoding - #ifdef simpleReceiving - #ifdef ZgatewayLORA - MQTTtoLORA(topicOri, datacallback); - #endif - #ifdef ZgatewayRF - MQTTtoRF(topicOri, datacallback); - #endif - #ifdef ZgatewayRF315 - MQTTtoRF315(topicOri, datacallback); - #endif - #ifdef ZgatewayRF2 - MQTTtoRF2(topicOri, datacallback); - #endif - #ifdef Zgateway2G - MQTTto2G(topicOri, datacallback); - #endif - #ifdef ZgatewaySRFB - MQTTtoSRFB(topicOri, datacallback); - #endif - #ifdef ZgatewayRFM69 - MQTTtoRFM69(topicOri, datacallback); - #endif - #ifdef ZactuatorFASTLED - MQTTtoFASTLED(topicOri, datacallback); - #endif - #endif - #ifdef ZactuatorONOFF + } else { // not a json object --> simple decoding +#ifdef simpleReceiving +# ifdef ZgatewayLORA + MQTTtoLORA(topicOri, datacallback); +# endif +# ifdef ZgatewayRF + MQTTtoRF(topicOri, datacallback); +# endif +# ifdef ZgatewayRF315 + MQTTtoRF315(topicOri, datacallback); +# endif +# ifdef ZgatewayRF2 + MQTTtoRF2(topicOri, datacallback); +# endif +# ifdef Zgateway2G + MQTTto2G(topicOri, datacallback); +# endif +# ifdef ZgatewaySRFB + MQTTtoSRFB(topicOri, datacallback); +# endif +# ifdef ZgatewayRFM69 + MQTTtoRFM69(topicOri, datacallback); +# endif +# ifdef ZactuatorFASTLED + MQTTtoFASTLED(topicOri, datacallback); +# endif +#endif +#ifdef ZactuatorONOFF MQTTtoONOFF(topicOri, datacallback); - #endif +#endif digitalWrite(led_send, HIGH); } @@ -1549,35 +1421,27 @@ void receivingMQTT(char *topicOri, char *datacallback) digitalWrite(led_send, HIGH); } -void MQTTtoSYS(char *topicOri, JsonObject &SYSdata) -{ // json object decoding -if (cmpToMainTopic(topicOri,subjectMQTTtoSYSset)) - { +void MQTTtoSYS(char* topicOri, JsonObject& SYSdata) { // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoSYSset)) { Log.trace(F("MQTTtoSYS json" CR)); - #if defined(ESP8266) || defined(ESP32) - if (SYSdata.containsKey("cmd")) - { - const char *cmd = SYSdata["cmd"]; - Log.notice(F("Command: %s" CR),cmd); - if (strstr(cmd, restartCmd) != NULL) - { //restart - #if defined(ESP8266) +#if defined(ESP8266) || defined(ESP32) + if (SYSdata.containsKey("cmd")) { + const char* cmd = SYSdata["cmd"]; + Log.notice(F("Command: %s" CR), cmd); + if (strstr(cmd, restartCmd) != NULL) { //restart +# if defined(ESP8266) ESP.reset(); - #else +# else ESP.restart(); - #endif - } - else if (strstr(cmd, eraseCmd) != NULL) - { //erase and restart - #ifndef ESPWifiManualSetup +# endif + } else if (strstr(cmd, eraseCmd) != NULL) { //erase and restart +# ifndef ESPWifiManualSetup setup_wifimanager(true); - #endif - } - else - { +# endif + } else { Log.warning(F("wrong command" CR)); } } - #endif +#endif } } diff --git a/package.json b/package.json index 7ada2353..97a90861 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { - "scripts": { - "docs:dev": "vuepress dev docs", - "docs:build": "vuepress build docs" - } - } \ No newline at end of file + "scripts": { + "docs:dev": "vuepress dev docs", + "docs:build": "vuepress build docs" + } +} diff --git a/test/Test_config.h b/test/Test_config.h index 0ef359dd..f24d9242 100644 --- a/test/Test_config.h +++ b/test/Test_config.h @@ -51,7 +51,7 @@ */ /*-------------DEFINE GATEWAY NAME BELOW IT CAN ALSO BE DEFINED IN platformio.ini----------------*/ #ifndef Gateway_Name - #define Gateway_Name "OpenMQTTGateway" +# define Gateway_Name "OpenMQTTGateway" #endif #define Base_Topic "home/" @@ -59,29 +59,29 @@ /*-------------DEFINE YOUR NETWORK PARAMETERS BELOW----------------*/ //#define NetworkAdvancedSetup true //uncomment if you want to set advanced network parameters for arduino boards, not uncommented you can set the IP and mac only #ifdef NetworkAdvancedSetup // for arduino boards advanced config - // these values are only used if no dhcp configuration is available - const byte ip[] = { 192, 168, 1, 99 }; //ip adress - const byte gateway[] = { 0, 0, 0, 0 }; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns - const byte Dns[] = { 0, 0, 0, 0 }; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns - const byte subnet[] = { 255, 255, 255, 0 }; //ip adress +// these values are only used if no dhcp configuration is available +const byte ip[] = {192, 168, 1, 99}; //ip adress +const byte gateway[] = {0, 0, 0, 0}; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns +const byte Dns[] = {0, 0, 0, 0}; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns +const byte subnet[] = {255, 255, 255, 0}; //ip adress #endif -#if defined(ESP8266)||defined(ESP32) // for nodemcu, weemos and esp8266 - //#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP +#if defined(ESP8266) || defined(ESP32) // for nodemcu, weemos and esp8266 + //#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP #else // for arduino boards - const byte ip[] = { 192, 168, 1, 99 }; //ip adress - const byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95 }; //W5100 ethernet shield mac adress +const byte ip[] = {192, 168, 1, 99}; //ip adress +const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield mac adress #endif #if defined(ESPWifiManualSetup) // for nodemcu, weemos and esp8266 - #define wifi_ssid "wifi ssid" - #define wifi_password "wifi password" +# define wifi_ssid "wifi ssid" +# define wifi_password "wifi password" #endif -#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point -#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point +#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point +#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point #define WifiManager_ConfigPortalTimeOut 120 -#define WifiManager_TimeOut 5 +#define WifiManager_TimeOut 5 //#define MDNS_SD //uncomment if you want to use mdns for discovering automatically your ip server, please note that MDNS with ESP32 can cause the BLE to not work @@ -91,7 +91,7 @@ /*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/ //MQTT Parameters definition //#define mqtt_server_name "www.mqtt_broker.com" // instead of defining the server by its IP you can define it by its name, uncomment this line and set the correct MQTT server host name -#define parameters_size 20 +#define parameters_size 20 #define mqtt_topic_max_size 100 char mqtt_user[parameters_size] = "your_username"; // not compulsory only if your broker needs authentication char mqtt_pass[parameters_size] = "your_password"; // not compulsory only if your broker needs authentication @@ -100,11 +100,11 @@ char mqtt_port[6] = "1883"; char mqtt_topic[mqtt_topic_max_size] = Base_Topic; char gateway_name[parameters_size * 2] = Gateway_Name; -#define version_Topic "/version" -#define will_Topic "/LWT" -#define will_QoS 0 -#define will_Retain true -#define will_Message "Offline" +#define version_Topic "/version" +#define will_Topic "/LWT" +#define will_QoS 0 +#define will_Retain true +#define will_Message "Offline" #define Gateway_AnnouncementMsg "Online" #define maxMQTTretry 4 //maximum MQTT connection attempts before going to wifi setup @@ -112,52 +112,52 @@ char gateway_name[parameters_size * 2] = Gateway_Name; /*-------------DEFINE YOUR OTA PARAMETERS BELOW----------------*/ #define ota_hostname "OTAHOSTNAME" #define ota_password "OTAPASSWORD" -#define ota_port 8266 +#define ota_port 8266 /*-------------DEFINE PINs FOR STATUS LEDs----------------*/ #ifdef ESP8266 - #define led_receive 40 - #define led_send 42 - #define led_info 44 +# define led_receive 40 +# define led_send 42 +# define led_info 44 #elif ESP32 - #define led_receive 40 - #define led_send 42 - #define led_info 44 +# define led_receive 40 +# define led_send 42 +# define led_info 44 #elif __AVR_ATmega2560__ //arduino mega - #define led_receive 40 - #define led_send 42 - #define led_info 44 +# define led_receive 40 +# define led_send 42 +# define led_info 44 #else //arduino uno/nano - #define led_receive 40 - #define led_send 42 - #define led_info 44 +# define led_receive 40 +# define led_send 42 +# define led_info 44 #endif // VCC ------------D|-----------/\/\/\/\ ----------------- Arduino PIN // LED Resistor 270-510R #ifndef TRIGGER_PIN - #ifdef ESP8266 - #define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s) - #elif ESP32 - #define TRIGGER_PIN 0 // boot button as full reset button (long press >10s) - #endif +# ifdef ESP8266 +# define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s) +# elif ESP32 +# define TRIGGER_PIN 0 // boot button as full reset button (long press >10s) +# endif #endif /*----------------------------OTHER PARAMETERS-----------------------------*/ #ifdef ZgatewaySRFB - #define SERIAL_BAUD 19200 +# define SERIAL_BAUD 19200 #else - #define SERIAL_BAUD 115200 +# define SERIAL_BAUD 115200 #endif /*-------------------CHANGING THEM IS NOT COMPULSORY-----------------------*/ /*--------------MQTT general topics-----------------*/ // global MQTT subject listened by the gateway to execute commands (send RF, IR or others) -#define subjectMQTTtoX "/commands/#" -#define subjectMultiGTWKey "toMQTT" -#define subjectGTWSendKey "MQTTto" +#define subjectMQTTtoX "/commands/#" +#define subjectMultiGTWKey "toMQTT" +#define subjectGTWSendKey "MQTTto" // key used for launching commands to the gateway -#define restartCmd "restart" -#define eraseCmd "erase" +#define restartCmd "restart" +#define eraseCmd "erase" // define if we concatenate the values into the topic //#define valueAsASubject true @@ -166,16 +166,16 @@ char gateway_name[parameters_size * 2] = Gateway_Name; #define time_avoid_duplicate 3000 // if you want to avoid duplicate mqtt message received set this to > 0, the value is the time in milliseconds during which we don't publish duplicates #ifdef ESP32 - //#define multiCore //uncomment to use multicore function of ESP32 for BLE +//#define multiCore //uncomment to use multicore function of ESP32 for BLE #endif #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) - #define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 - #define ARDUINOJSON_USE_LONG_LONG 1 +# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 +# define ARDUINOJSON_USE_LONG_LONG 1 #else // boards with smaller memory - #define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 +# define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266 #endif #define TimeBetweenReadingSYS 120000 // time between system readings (like memory) -#define subjectSYStoMQTT "/SYStoMQTT" -#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config" +#define subjectSYStoMQTT "/SYStoMQTT" +#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config" #endif