diff --git a/docs/participate/development.md b/docs/participate/development.md index 1d1e7eb..775ca39 100644 --- a/docs/participate/development.md +++ b/docs/participate/development.md @@ -5,6 +5,8 @@ agree to follow the code of conduct below [code of conduct]: https://github.com/1technophile/OpenMQTTGateway/blob/master/CODE_OF_CONDUCT.md +[code style guide](https://google.github.io/styleguide/cppguide.html#Formatting) + Fork the [development branch](https://github.com/1technophile/OpenMQTTGateway/tree/development), then clone the repo Make your modification, diff --git a/main/ZactuatorFASTLED.ino b/main/ZactuatorFASTLED.ino index 2380b9b..89801d8 100644 --- a/main/ZactuatorFASTLED.ino +++ b/main/ZactuatorFASTLED.ino @@ -24,12 +24,8 @@ #ifdef ZactuatorFASTLED -#ifdef ESP8266 #include -#else -#include -#endif -#include + enum LEDState { OFF, @@ -123,35 +119,32 @@ boolean FASTLEDtoMQTT() { return false; } -void MQTTtoFASTLEDJSON(char *topicOri, JsonObject& jsonData) +void MQTTtoFASTLEDJSON(char *topicOri, JsonObject &jsonData) { trc(F("MQTTtoFASTLEDJSON: ")); currentLEDState = GENERAL; trc(topicOri); //number = (long)strtol(&datacallback[1], NULL, 16); - - - if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLEDsetled)) + if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled)) { - trc(F("JSON parsed")); - int ledNr = jsonData["led"]; - trc(F("led")); - trc(ledNr); - const char *color = jsonData["hex"]; - trc(F("hex")); - - long number = (long)strtol(color, NULL, 16); - trc(number); - bool blink = jsonData["blink"]; - if (ledNr <= FASTLED_NUM_LEDS) - { - trc(F("blink")); - trc(blink); - blinkLED[ledNr] = blink; - leds[ledNr] = number; - } - + trc(F("JSON parsed")); + int ledNr = jsonData["led"]; + trc(F("led")); + trc(ledNr); + const char *color = jsonData["hex"]; + trc(F("hex")); + + long number = (long)strtol(color, NULL, 16); + trc(number); + bool blink = jsonData["blink"]; + if (ledNr <= FASTLED_NUM_LEDS) + { + trc(F("blink")); + trc(blink); + blinkLED[ledNr] = blink; + leds[ledNr] = number; + } } } void MQTTtoFASTLED(char *topicOri, char *datacallback) @@ -160,7 +153,7 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback) currentLEDState = GENERAL; long number = 0; trc(topicOri); - if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLED)) + if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED)) { number = (long)strtol(&datacallback[1], NULL, 16); trc(number); @@ -170,18 +163,18 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback) } FastLED.show(); } - else if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLEDsetbrightness)) + else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness)) { number = (long)strtol(&datacallback[1], NULL, 16); trc(number); FastLED.setBrightness(number); FastLED.show(); } - else if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLEDsetanimation)) + else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation)) { String payload = datacallback; trc(payload); - if ( strstr(datacallback,"fire") != NULL) + if (strstr(datacallback, "fire") != NULL) { currentLEDState = FIRE; gPal = HeatColors_p; @@ -195,7 +188,7 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback) { currentLEDState = OFF; } - if (currentLEDState==OFF) + if (currentLEDState == OFF) { for (int i = 0; i < FASTLED_NUM_LEDS; i++) { diff --git a/main/ZactuatorONOFF.ino b/main/ZactuatorONOFF.ino index cf180d1..9fca327 100644 --- a/main/ZactuatorONOFF.ino +++ b/main/ZactuatorONOFF.ino @@ -31,13 +31,15 @@ #ifdef ZactuatorONOFF #ifdef jsonReceiving -void MQTTtoONOFF(char * topicOri, JsonObject& ONOFFdata){ - - if (cmpToMainTopic(topicOri,subjectMQTTtoONOFF)){ +void MQTTtoONOFF(char *topicOri, JsonObject &ONOFFdata) +{ + if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF)) + { trc(F("MQTTtoONOFF json data analysis")); int boolSWITCHTYPE = ONOFFdata["state"] | 99; int pin = ONOFFdata["pin"] | ACTUATOR_ONOFF_PIN; - if (boolSWITCHTYPE != 99) { + if (boolSWITCHTYPE != 99) + { trc(F("MQTTtoONOFF boolSWITCHTYPE ok")); trc(boolSWITCHTYPE); trc(F("pin number")); @@ -46,7 +48,9 @@ void MQTTtoONOFF(char * topicOri, JsonObject& ONOFFdata){ digitalWrite(pin, boolSWITCHTYPE); // we acknowledge the sending by publishing the value to an acknowledgement topic pub(subjectGTWONOFFtoMQTT, ONOFFdata); - }else{ + } + else + { trc(F("MQTTtoONOFF failed json read")); } } @@ -54,8 +58,10 @@ void MQTTtoONOFF(char * topicOri, JsonObject& ONOFFdata){ #endif #ifdef simpleReceiving -void MQTTtoONOFF(char * topicOri, char * datacallback) { - if ((cmpToMainTopic(topicOri,subjectMQTTtoONOFF)) ){ +void MQTTtoONOFF(char *topicOri, char *datacallback) +{ + if ((cmpToMainTopic(topicOri, subjectMQTTtoONOFF))) + { trc(F("MQTTtoONOFF")); int pin = strtol(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 @@ -64,16 +70,17 @@ void MQTTtoONOFF(char * topicOri, char * datacallback) { pinMode(pin, OUTPUT); bool ON = false; - if (strstr(topicOri,ONKey) != NULL) ON = true; - if (strstr(topicOri,OFFKey) != NULL) ON = false; + if (strstr(topicOri, ONKey) != NULL) + ON = true; + if (strstr(topicOri, OFFKey) != NULL) + ON = false; digitalWrite(pin, ON); // we acknowledge the sending by publishing the value to an acknowledgement topic char b = ON; pub(subjectGTWONOFFtoMQTT, &b); - } + } } #endif - #endif diff --git a/main/Zgateway2G.ino b/main/Zgateway2G.ino index 9f65d3f..3fa58a4 100644 --- a/main/Zgateway2G.ino +++ b/main/Zgateway2G.ino @@ -33,13 +33,14 @@ #include // library for controling A6 or A7 module // Instantiate the library with TxPin, RxPin. -A6lib A6l(_2G_TX_PIN, _2G_RX_PIN); //D6 to A6 RX, D7 to A6 TX - +A6lib A6l(_2G_TX_PIN, _2G_RX_PIN); //D6 to A6 RX, D7 to A6 TX + int unreadSMSLocs[50] = {0}; int unreadSMSNum = 0; SMSmessage sms; -void setup2G(){ +void setup2G() +{ trc(F("_2G_TX_PIN ")); trc(_2G_TX_PIN); @@ -49,115 +50,139 @@ void setup2G(){ trc(F("Zgateway2G setup done ")); } -void setupGSM(bool deleteSMS){ - trc(F("Init 2G module: ")); - trc(_2G_PWR_PIN); - delay(1000); - // Power-cycle the module to reset it. - A6l.powerCycle(_2G_PWR_PIN); - trc(F("waiting for network connection")); - A6l.blockUntilReady(_2G_MODULE_BAUDRATE); - trc(F("A6/A7 gsm ready")); - signalStrengthAnalysis(); - delay(1000); - // deleting all sms - if (deleteSMS){ - if (A6l.deleteSMS(1,4) == A6_OK ) { - trc(F("delete SMS OK")); - }else{ - trc(F("delete SMS KO")); - } +void setupGSM(bool deleteSMS) +{ + trc(F("Init 2G module: ")); + trc(_2G_PWR_PIN); + delay(1000); + // Power-cycle the module to reset it. + A6l.powerCycle(_2G_PWR_PIN); + trc(F("waiting for network connection")); + A6l.blockUntilReady(_2G_MODULE_BAUDRATE); + trc(F("A6/A7 gsm ready")); + signalStrengthAnalysis(); + delay(1000); + // deleting all sms + if (deleteSMS) + { + if (A6l.deleteSMS(1, 4) == A6_OK) + { + trc(F("delete SMS OK")); } -} - -void signalStrengthAnalysis(){ - int signalStrength = 0; - signalStrength = A6l.getSignalStrength(); - trc(F("Signal strength: ")); - trc(signalStrength); - if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL ) { - trc(F("Signal too low restart the module")); - setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module - } -} - -bool _2GtoMQTT(){ - // Get the memory locations of unread SMS messages. - unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512); - trc(F("Creating SMS buffer")); - StaticJsonBuffer jsonBuffer; - JsonObject& SMSdata = jsonBuffer.createObject(); - for (int i = 0; i < unreadSMSNum; i++) { - trc(F("New message at index: ")); - trc(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()); - A6l.deleteSMS(unreadSMSLocs[i]); // we delete the SMS received - trc(F("Adv data 2GtoMQTT")); - pub(subject2GtoMQTT,SMSdata); - return true; - } - return false; -} -#ifdef simpleReceiving - void MQTTto2G(char * topicOri, char * datacallback) { - - String data = datacallback; - String topic = topicOri; - - if (cmpToMainTopic(topicOri,subjectMQTTto2G)) { - trc(F("MQTTto2G data analysis")); - // 2G DATA ANALYSIS - String phone_number = ""; - int pos0 = topic.lastIndexOf(_2GPhoneKey); - if (pos0 != -1) { - pos0 = pos0 + strlen(_2GPhoneKey); - phone_number = topic.substring(pos0); - trc(F("MQTTto2G phone ok")); - trc(phone_number); - trc(F("MQTTto2G sms")); - trc(data); - if (A6l.sendSMS(phone_number,data) == A6_OK ) { - trc(F("SMS OK")); - // 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{ - trc(F("SMS KO")); - // 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{ - trc(F("MQTTto2G Fail reading phone number")); - } + else + { + trc(F("delete SMS KO")); } } +} + +void signalStrengthAnalysis() +{ + int signalStrength = 0; + signalStrength = A6l.getSignalStrength(); + trc(F("Signal strength: ")); + trc(signalStrength); + if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL) + { + trc(F("Signal too low restart the module")); + setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module + } +} + +bool _2GtoMQTT() +{ + // Get the memory locations of unread SMS messages. + unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512); + trc(F("Creating SMS buffer")); + StaticJsonBuffer jsonBuffer; + JsonObject &SMSdata = jsonBuffer.createObject(); + for (int i = 0; i < unreadSMSNum; i++) + { + trc(F("New message at index: ")); + trc(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()); + A6l.deleteSMS(unreadSMSLocs[i]); // we delete the SMS received + trc(F("Adv data 2GtoMQTT")); + pub(subject2GtoMQTT, SMSdata); + return true; + } + return false; +} +#ifdef simpleReceiving +void MQTTto2G(char *topicOri, char *datacallback) +{ + + String data = datacallback; + String topic = topicOri; + + if (cmpToMainTopic(topicOri, subjectMQTTto2G)) + { + trc(F("MQTTto2G data analysis")); + // 2G DATA ANALYSIS + String phone_number = ""; + int pos0 = topic.lastIndexOf(_2GPhoneKey); + if (pos0 != -1) + { + pos0 = pos0 + strlen(_2GPhoneKey); + phone_number = topic.substring(pos0); + trc(F("MQTTto2G phone ok")); + trc(phone_number); + trc(F("MQTTto2G sms")); + trc(data); + if (A6l.sendSMS(phone_number, data) == A6_OK) + { + trc(F("SMS OK")); + // 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 + { + trc(F("SMS KO")); + // 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 + { + trc(F("MQTTto2G Fail reading phone number")); + } + } +} #endif #ifdef jsonReceiving - void MQTTto2G(char * topicOri, JsonObject& SMSdata) { - - if (cmpToMainTopic(topicOri,subjectMQTTto2G)){ - const char * sms = SMSdata["message"]; - const char * phone = SMSdata["phone"]; - trc(F("MQTTto2G json data analysis")); - if (sms && phone) { - trc(F("MQTTto2G sms & phone ok")); - trc(sms); - if (A6l.sendSMS(String(phone),String(sms)) == A6_OK ) { - trc(F("SMS OK")); - // 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{ - trc(F("SMS KO")); - 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{ - trc(F("MQTTto2G failed json read")); +void MQTTto2G(char *topicOri, JsonObject &SMSdata) +{ + + if (cmpToMainTopic(topicOri, subjectMQTTto2G)) + { + const char *sms = SMSdata["message"]; + const char *phone = SMSdata["phone"]; + trc(F("MQTTto2G json data analysis")); + if (sms && phone) + { + trc(F("MQTTto2G sms & phone ok")); + trc(sms); + if (A6l.sendSMS(String(phone), String(sms)) == A6_OK) + { + trc(F("SMS OK")); + // 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 + { + trc(F("SMS KO")); + 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 + { + trc(F("MQTTto2G failed json read")); + } } +} #endif #endif diff --git a/main/ZgatewayBT.ino b/main/ZgatewayBT.ino index db4fc6e..c01f024 100644 --- a/main/ZgatewayBT.ino +++ b/main/ZgatewayBT.ino @@ -36,18 +36,22 @@ Thanks to wolass https://github.com/wolass for suggesting me HM 10 and dinosd ht using namespace std; vector devices; -void setWorBMac(char * mac , bool isWhite){ +void setWorBMac(char *mac, bool isWhite) +{ bool foundMac = false; - for(vector::iterator p = devices.begin(); p != devices.end(); ++p){ - if((strcmp(p->macAdr,mac) == 0)){ - p->isWhtL = isWhite; - p->isBlkL = !isWhite; - foundMac = true; + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) + { + if ((strcmp(p->macAdr, mac) == 0)) + { + p->isWhtL = isWhite; + p->isBlkL = !isWhite; + foundMac = true; } } - if (!foundMac) { + if (!foundMac) + { BLEdevice device; - strcpy( device.macAdr,mac ); + strcpy(device.macAdr, mac); device.isDisc = false; device.isWhtL = isWhite; device.isBlkL = !isWhite; @@ -55,42 +59,56 @@ void setWorBMac(char * mac , bool isWhite){ } } -bool oneWhite(){ - for(vector::iterator p = devices.begin(); p != devices.end(); ++p){ - if(p->isWhtL) return true; +bool oneWhite() +{ + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) + { + if (p->isWhtL) + return true; } return false; } -bool isWhite(char * mac){ - for(vector::iterator p = devices.begin(); p != devices.end(); ++p){ - if((strcmp(p->macAdr,mac) == 0)){ - return p->isWhtL; +bool isWhite(char *mac) +{ + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) + { + if ((strcmp(p->macAdr, mac) == 0)) + { + return p->isWhtL; } } return false; } -bool isBlack(char * mac){ - for(vector::iterator p = devices.begin(); p != devices.end(); ++p){ - if((strcmp(p->macAdr,mac) == 0)){ - return p->isBlkL; +bool isBlack(char *mac) +{ + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) + { + if ((strcmp(p->macAdr, mac) == 0)) + { + return p->isBlkL; } } return false; } -bool isDiscovered(char * mac){ - for(vector::iterator p = devices.begin(); p != devices.end(); ++p){ - if((strcmp(p->macAdr,mac) == 0)){ - return p->isDisc; +bool isDiscovered(char *mac) +{ + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) + { + if ((strcmp(p->macAdr, mac) == 0)) + { + return p->isDisc; } } return false; } -void dumpDevices(){ - for(vector::iterator p = devices.begin(); p != devices.end(); ++p){ +void dumpDevices() +{ + for (vector::iterator p = devices.begin(); p != devices.end(); ++p) + { trc(p->macAdr); trc(p->isDisc); trc(p->isWhtL); @@ -98,265 +116,282 @@ void dumpDevices(){ } } -void strupp(char* beg) +void strupp(char *beg) { - while (*beg = toupper(*beg)) - ++beg; + while (*beg = toupper(*beg)) + ++beg; } #ifdef ZmqttDiscovery -void MiFloraDiscovery(char * mac){ - #define MiFloraparametersCount 4 +void MiFloraDiscovery(char *mac) +{ +#define MiFloraparametersCount 4 trc(F("MiFloraDiscovery")); - char * MiFlorasensor[MiFloraparametersCount][8] = { - {"sensor", "MiFlora-lux", mac, "illuminance","{{ value_json.lux | is_defined }}","", "", "lu"} , - {"sensor", "MiFlora-tem", mac,"temperature","{{ value_json.tem | is_defined }}","", "", "°C"} , - {"sensor", "MiFlora-fer", mac,"","{{ value_json.fer | is_defined }}","", "", "µS/cm"} , - {"sensor", "MiFlora-moi", mac,"","{{ value_json.moi | is_defined }}","", "", "%"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement + char *MiFlorasensor[MiFloraparametersCount][8] = { + {"sensor", "MiFlora-lux", mac, "illuminance", "{{ value_json.lux | is_defined }}", "", "", "lu"}, + {"sensor", "MiFlora-tem", mac, "temperature", "{{ value_json.tem | is_defined }}", "", "", "°C"}, + {"sensor", "MiFlora-fer", mac, "", "{{ value_json.fer | is_defined }}", "", "", "µS/cm"}, + {"sensor", "MiFlora-moi", mac, "", "{{ value_json.moi | is_defined }}", "", "", "%"} + //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - - for (int i=0;i - #include - #include - #include - #include "soc/timer_group_struct.h" - #include "soc/timer_group_reg.h" - - //core on which the BLE detection task will run - static int taskCore = 0; - - class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { - void onResult(BLEAdvertisedDevice advertisedDevice) { - trc(F("Creating BLE buffer")); - StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); - String mac_adress = advertisedDevice.getAddress().toString().c_str(); - BLEdata.set("id", (char *)mac_adress.c_str()); - mac_adress.replace(":",""); - mac_adress.toUpperCase(); - String mactopic = subjectBTtoMQTT + mac_adress; - char mac[mac_adress.length()+1]; - mac_adress.toCharArray(mac,mac_adress.length()+1); - trc("device detected"); - trc(mac); - if((!oneWhite() || isWhite(mac)) && !isBlack(mac)){ //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 (advertisedDevice.haveManufacturerData()) BLEdata.set("manufacturerdata", (char *)advertisedDevice.getManufacturerData().c_str()); - if (advertisedDevice.haveRSSI()) BLEdata.set("rssi", (int) advertisedDevice.getRSSI()); - if (advertisedDevice.haveTXPower()) BLEdata.set("txpower", (int8_t) advertisedDevice.getTXPower()); - #ifdef subjectHomePresence - if (advertisedDevice.haveRSSI()) haRoomPresence(BLEdata);// this device has an rssi in consequence we can use it for home assistant room presence component +// 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" + +//core on which the BLE detection task will run +static int taskCore = 0; + +class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks +{ + void onResult(BLEAdvertisedDevice advertisedDevice) + { + trc(F("Creating BLE buffer")); + StaticJsonBuffer jsonBuffer; + JsonObject &BLEdata = jsonBuffer.createObject(); + String mac_adress = advertisedDevice.getAddress().toString().c_str(); + BLEdata.set("id", (char *)mac_adress.c_str()); + mac_adress.replace(":", ""); + mac_adress.toUpperCase(); + String mactopic = subjectBTtoMQTT + mac_adress; + char mac[mac_adress.length() + 1]; + mac_adress.toCharArray(mac, mac_adress.length() + 1); + trc("device detected"); + trc(mac); + if ((!oneWhite() || isWhite(mac)) && !isBlack(mac)) + { //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 (advertisedDevice.haveManufacturerData()) + BLEdata.set("manufacturerdata", (char *)advertisedDevice.getManufacturerData().c_str()); + if (advertisedDevice.haveRSSI()) + BLEdata.set("rssi", (int)advertisedDevice.getRSSI()); + if (advertisedDevice.haveTXPower()) + BLEdata.set("txpower", (int8_t)advertisedDevice.getTXPower()); + #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()) + { + trc(F("Get services data :")); + int serviceDataCount = advertisedDevice.getServiceDataCount(); + trc(serviceDataCount); + 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++) + { + int a = serviceData[i]; + if (a < 16) + { + returnedString = returnedString + "0"; + } + returnedString = returnedString + String(a, HEX); + } + char service_data[returnedString.length() + 1]; + returnedString.toCharArray(service_data, returnedString.length() + 1); + service_data[returnedString.length()] = '\0'; + #ifdef pubBLEServiceData + BLEdata.set("servicedata", service_data); #endif - if (advertisedDevice.haveServiceData()){ - trc(F("Get services data :")); - int serviceDataCount = advertisedDevice.getServiceDataCount(); - trc(serviceDataCount); - for (int j = 0; j < serviceDataCount;j++){ - std::string serviceData = advertisedDevice.getServiceData(j); - int serviceDataLength = serviceData.length(); - String returnedString = ""; - for (int i=0; i(), "fe95") != NULL) + { //Mi FLora, Mi jia, Cleargrass Method 1, LYWDS02, VegTrug + trc("Processing BLE device data"); + int pos = -1; + pos = strpos(service_data, "209800"); + if (pos != -1) + { + trc(F("mi flora data reading")); + //example "servicedata":"71209800bc63b6658d7cc40d0910023200" + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + MiFloraDiscovery(mac); #endif - BLEdata.set("servicedatauuid", (char *)advertisedDevice.getServiceDataUUID(j).toString().c_str()); - if(abs((int)BLEdata["rssi"]|0) < abs(Minrssi)) { // publish only the devices close enough - pub((char *)mactopic.c_str(),BLEdata); - if (strstr(BLEdata["servicedatauuid"].as(),"fe95") != NULL ){ //Mi FLora, Mi jia, Cleargrass Method 1, LYWDS02, VegTrug - trc("Processing BLE device data"); - int pos = -1; - pos = strpos(service_data,"209800"); - if (pos != -1){ - trc(F("mi flora data reading")); - //example "servicedata":"71209800bc63b6658d7cc40d0910023200" - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) MiFloraDiscovery(mac); - #endif - process_sensors(pos - 24,service_data,mac); - } - pos = -1; - pos = strpos(service_data,"20bc03"); - if (pos != -1){ - trc(F("vegtrug data reading")); - //example "servicedata":"7120bc0399c309688d7cc40d0910020000" - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) VegTrugDiscovery(mac); - #endif - process_sensors(pos - 24,service_data,mac); - } - pos = -1; - pos = strpos(service_data,"20aa01"); - if (pos != -1){ - trc(F("mi jia data reading")); - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) MiJiaDiscovery(mac); - #endif - process_sensors(pos - 26,service_data,mac); - } - pos = -1; - pos = strpos(service_data,"205b04"); - if (pos != -1){ - trc(F("LYWSD02 data reading")); - //example "servicedata":"70205b04b96ab883c8593f09041002e000" - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) LYWSD02Discovery(mac); - #endif - process_sensors(pos - 24,service_data,mac); - } - pos = -1; - pos = strpos(service_data,"304703"); - if (pos != -1){ - trc(F("ClearGrass T RH data reading method 1")); - //example "servicedata":"5030470340743e10342d58041002d6000a100164" - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) CLEARGRASSTRHDiscovery(mac); - #endif - process_sensors(pos - 26,service_data,mac); - } - pos = -1; - pos = strpos(service_data,"4030dd"); - if (pos != -1){ - trc(F("Mi Lamp data reading")); - //example "servicedata":4030DD031D0300010100 - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) MiLampDiscovery(mac); - #endif - process_milamp(service_data,mac); - } - } - if (strstr(BLEdata["servicedatauuid"].as(),"181d") != NULL){ // Mi Scale V1 - trc(F("Mi Scale V1 data reading")); - //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) MiScaleDiscovery(mac); - #endif - process_scale_v1(service_data,mac); - } - if (strstr(BLEdata["servicedatauuid"].as(),"181b") != NULL){ // Mi Scale V2 - trc(F("Mi Scale V2 data reading")); - //example "servicedata":02c4e1070b1e13050c00002607 / 02a6e20705150a251df401443e /02a6e20705180c0d04d701943e - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) MiScaleDiscovery(mac); - #endif - process_scale_v2(service_data,mac); - } - if (strstr(BLEdata["servicedatauuid"].as(),"fee0") != NULL){ // Mi Band //0000fee0-0000-1000-8000-00805f9b34fb // ESP32 only - trc(F("Mi Band data reading")); - //example "servicedata":a21e0000 - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) MiBandDiscovery(mac); - #endif - process_miband(service_data,mac); - } - if (strstr(BLEdata["servicedata"].as(),"08094c") != NULL){ // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a - trc(F("Clear grass data with air pressure reading")); - //example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a - #ifdef ZmqttDiscovery - if(!isDiscovered(mac)) CLEARGRASSTRHKPADiscovery(mac); - #endif - process_cleargrass_air(service_data,mac); - } - if (strstr(BLEdata["servicedata"].as(),"080774") != NULL){ // Clear grass standard method 2/0807743e10342d580104c3002c0202012a - trc(F("Clear grass data reading method 2")); - //example "servicedata":0807743e10342d580104 c300 2c02 02012a - // no discovery as it is already available with method 1 - process_cleargrass(service_data,mac); - } - }else{ - trc("Low rssi, device filtered"); - } + process_sensors(pos - 24, service_data, mac); } - }else{ - if(abs((int)BLEdata["rssi"]|0) < abs(Minrssi)) { // publish only the devices close enough - pub((char *)mactopic.c_str(),BLEdata); // publish device even if there is no service data - }else{ + pos = -1; + pos = strpos(service_data, "20bc03"); + if (pos != -1) + { + trc(F("vegtrug data reading")); + //example "servicedata":"7120bc0399c309688d7cc40d0910020000" + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + VegTrugDiscovery(mac); + #endif + process_sensors(pos - 24, service_data, mac); + } + pos = -1; + pos = strpos(service_data, "20aa01"); + if (pos != -1) + { + trc(F("mi jia data reading")); + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + MiJiaDiscovery(mac); + #endif + process_sensors(pos - 26, service_data, mac); + } + pos = -1; + pos = strpos(service_data, "205b04"); + if (pos != -1) + { + trc(F("LYWSD02 data reading")); + //example "servicedata":"70205b04b96ab883c8593f09041002e000" + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + LYWSD02Discovery(mac); + #endif + process_sensors(pos - 24, service_data, mac); + } + pos = -1; + pos = strpos(service_data, "304703"); + if (pos != -1) + { + trc(F("ClearGrass T RH data reading method 1")); + //example "servicedata":"5030470340743e10342d58041002d6000a100164" + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + CLEARGRASSTRHDiscovery(mac); + #endif + process_sensors(pos - 26, service_data, mac); + } + pos = -1; + pos = strpos(service_data, "4030dd"); + if (pos != -1) + { + trc(F("Mi Lamp data reading")); + //example "servicedata":4030DD031D0300010100 + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + MiLampDiscovery(mac); + #endif + process_milamp(service_data, mac); + } + } + if (strstr(BLEdata["servicedatauuid"].as(), "181d") != NULL) + { // Mi Scale V1 + trc(F("Mi Scale V1 data reading")); + //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + MiScaleDiscovery(mac); + #endif + process_scale_v1(service_data, mac); + } + if (strstr(BLEdata["servicedatauuid"].as(), "181b") != NULL) + { // Mi Scale V2 + trc(F("Mi Scale V2 data reading")); + //example "servicedata":02c4e1070b1e13050c00002607 / 02a6e20705150a251df401443e /02a6e20705180c0d04d701943e + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + MiScaleDiscovery(mac); + #endif + process_scale_v2(service_data, mac); + } + if (strstr(BLEdata["servicedatauuid"].as(), "fee0") != NULL) + { // Mi Band //0000fee0-0000-1000-8000-00805f9b34fb // ESP32 only + trc(F("Mi Band data reading")); + //example "servicedata":a21e0000 + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + MiBandDiscovery(mac); + #endif + process_miband(service_data, mac); + } + if (strstr(BLEdata["servicedata"].as(), "08094c") != NULL) + { // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a + trc(F("Clear grass data with air pressure reading")); + //example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a + #ifdef ZmqttDiscovery + if (!isDiscovered(mac)) + CLEARGRASSTRHKPADiscovery(mac); + #endif + process_cleargrass_air(service_data, mac); + } + if (strstr(BLEdata["servicedata"].as(), "080774") != NULL) + { // Clear grass standard method 2/0807743e10342d580104c3002c0202012a + trc(F("Clear grass data reading method 2")); + //example "servicedata":0807743e10342d580104 c300 2c02 02012a + // no discovery as it is already available with method 1 + process_cleargrass(service_data, mac); + } + } + else + { + trc("Low rssi, device filtered"); + } + } + } + else + { + if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi)) + { // publish only the devices close enough + pub((char *)mactopic.c_str(), BLEdata); // publish device even if there is no service data + } + else + { + trc("Low rssi, device filtered"); + } + } + } + else + { + trc(F("Filtered mac device")); + } + } +}; + +void BLEscan() +{ + + TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE; + TIMERG0.wdt_feed = 1; + TIMERG0.wdt_wprotect = 0; + trc(F("Scan begin")); + BLEDevice::init(""); + BLEScan *pBLEScan = BLEDevice::getScan(); //create new scan + MyAdvertisedDeviceCallbacks myCallbacks; + pBLEScan->setAdvertisedDeviceCallbacks(&myCallbacks); + pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster + BLEScanResults foundDevices = pBLEScan->start(Scan_duration); + trc(F("Scan end, deinit controller")); + esp_bt_controller_deinit(); +} + +void coreTask(void *pvParameters) +{ + + String taskMessage = "BT Task running on core "; + taskMessage = taskMessage + xPortGetCoreID(); + + while (true) + { + trc(taskMessage); + delay(BLEinterval); + if (client.state() == 0) + { + BLEscan(); + } + else + { + trc("MQTT client disconnected no BLE scan"); + delay(1000); + } + } +} + +void setupBT() +{ + BLEinterval = TimeBtw_Read; + Minrssi = MinimumRSSI; + trc(F("BLEinterval btw scans")); + trc(BLEinterval); + trc(F("Minrssi")); + trc(Minrssi); + // we setup a task with priority one to avoid conflict with other gateways + xTaskCreatePinnedToCore( + 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 */ + trc(F("ZgatewayBT multicore ESP32 setup done ")); +} + +bool BTtoMQTT() +{ // for on demand BLE scans + BLEscan(); +} +#else // arduino or ESP8266 working with HM10/11 + +#include + +#define STRING_MSG "OK+DISC:" +#define QUESTION_MSG "AT+DISA?" +#define RESPONSE_MSG "OK+DISIS" +#define RESP_END_MSG "OK+DISCE" +#define SETUP_MSG "OK+RESET" + +SoftwareSerial softserial(BT_RX, BT_TX); + +String returnedString = ""; +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", 34, 60, false}}; + +void setupBT() +{ + BLEinterval = TimeBtw_Read; + Minrssi = MinimumRSSI; + trc(F("BLEinterval btw scans")); + trc(BLEinterval); + trc(F("Minrssi")); + trc(Minrssi); + softserial.begin(9600); + softserial.print(F("AT+ROLE1")); + delay(100); + softserial.print(F("AT+IMME1")); + delay(100); + softserial.print(F("AT+RESET")); + delay(100); + #ifdef HM_BLUE_LED_STOP + softserial.print(F("AT+PIO11")); // When not connected (as in BLE mode) the LED is off. When connected the LED is solid on. + #endif + delay(100); + trc(F("ZgatewayBT HM1X setup done ")); +} + +bool BTtoMQTT() +{ + + //extract serial data from module in hexa format + while (softserial.available() > 0) + { + int a = softserial.read(); + if (a < 16) + { + returnedString = returnedString + "0"; + } + returnedString = returnedString + String(a, HEX); + } + + if (millis() > (timebt + BLEinterval)) + { //retriving data + timebt = millis(); + #if defined(ESP8266) + yield(); + #endif + if (returnedString != "") + { + size_t pos = 0; + while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1) + { + #if defined(ESP8266) + yield(); + #endif + String token = returnedString.substring(pos); + returnedString.remove(pos, returnedString.length()); + char token_char[token.length() + 1]; + token.toCharArray(token_char, token.length() + 1); + trc(token); + if (token.length() > 60) + { // we extract data only if we have detailled infos + 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 + } + + if ((strlen(d[0].extract)) == 12) // if a mac adress is detected we publish it + { + trc(F("Creating BLE buffer")); + StaticJsonBuffer jsonBuffer; + JsonObject &BLEdata = jsonBuffer.createObject(); + strupp(d[0].extract); + if (isBlack(d[0].extract)) + return false; //if black listed mac we go out + if (oneWhite() && !isWhite(d[0].extract)) + return false; //if we have at least one white mac and this mac is not white we go out + #ifdef subjectHomePresence + String HomePresenceId; + for (int i = 0; i < 12; i++) + { + HomePresenceId += String(d[0].extract[i]); + if (((i - 1) % 2 == 0) && (i != 11)) + HomePresenceId += ":"; + } + trc(F("HomePresenceId")); + trc(HomePresenceId); + BLEdata.set("id", (char *)HomePresenceId.c_str()); + #endif + String topic = subjectBTtoMQTT + String(d[0].extract); + int rssi = (int)strtol(d[2].extract, NULL, 16) - 256; + BLEdata.set("rssi", (int)rssi); + #ifdef subjectHomePresence + haRoomPresence(BLEdata); // this device has an rssi in consequence we can use it for home assistant room presence component + #endif + String service_data(d[5].extract); + service_data = service_data.substring(14); + #ifdef pubBLEServiceData + BLEdata.set("servicedata", (char *)service_data.c_str()); + #endif + if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi)) + { // publish only the devices close enough + pub((char *)topic.c_str(), BLEdata); + int pos = -1; + pos = strpos(d[5].extract, "209800"); + if (pos != -1) + { + trc("mi flora data reading"); + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + MiFloraDiscovery(d[0].extract); + #endif + bool result = process_sensors(pos - 38, (char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "20aa01"); + //example "servicedata":"5020aa0194dfaa33342d580d1004e3002c02" + if (pos != -1) + { + trc("mi jia data reading"); + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + MiJiaDiscovery(d[0].extract); + #endif + bool result = process_sensors(pos - 40, (char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "205b04"); + //example "servicedata":"141695fe70205b0461298882c8593f09061002d002" + if (pos != -1) + { + trc("LYWSD02 data reading"); + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + LYWSD02Discovery(d[0].extract); + #endif + bool result = process_sensors(pos - 38, (char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "304703"); + if (pos != -1) + { + trc("CLEARGRASSTRH data reading method 1"); + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + CLEARGRASSTRHDiscovery(d[0].extract); + #endif + bool result = process_sensors(pos - 40, (char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "e30706"); + if (pos != -1) + { + trc("Mi Scale data reading"); + //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + MiScaleDiscovery(d[0].extract); + #endif + bool result = process_scale_v1((char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "4030dd"); + if (pos != -1) + { + trc(F("Mi Lamp data reading")); + //example "servicedata":4030dd31d0300010100 + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + MiLampDiscovery(d[0].extract); + #endif + process_milamp((char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "08094c"); // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a + if (pos != -1) + { + trc(F("Clear grass data with air pressure reading")); + //example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a + #ifdef ZmqttDiscovery + if (!isDiscovered(d[0].extract)) + CLEARGRASSTRHKPADiscovery(d[0].extract); + #endif + process_cleargrass_air((char *)service_data.c_str(), d[0].extract); + } + pos = -1; + pos = strpos(d[5].extract, "080774"); // Clear grass standard method 2/0807743e10342d580104c3002c0202012a + if (pos != -1) + { + trc(F("Clear grass data reading method 2")); + //example "servicedata":0807743e10342d580104 c300 2c02 02012a + // no discovery as it is already available with method 1 + process_cleargrass((char *)service_data.c_str(), d[0].extract); + } + return true; + } + else + { trc("Low rssi, device filtered"); } } - }else{ - trc(F("Filtered mac device")); } } - }; - - void BLEscan(){ - - TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE; - TIMERG0.wdt_feed=1; - TIMERG0.wdt_wprotect=0; - trc(F("Scan begin")); - BLEDevice::init(""); - BLEScan* pBLEScan = BLEDevice::getScan(); //create new scan - MyAdvertisedDeviceCallbacks myCallbacks; - pBLEScan->setAdvertisedDeviceCallbacks(&myCallbacks); - pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster - BLEScanResults foundDevices = pBLEScan->start(Scan_duration); - trc(F("Scan end, deinit controller")); - esp_bt_controller_deinit(); - } - - void coreTask( void * pvParameters ){ - - String taskMessage = "BT Task running on core "; - taskMessage = taskMessage + xPortGetCoreID(); - - while(true){ - trc(taskMessage); - delay(BLEinterval); - if (client.state() == 0) { - BLEscan(); - }else{ - trc("MQTT client disconnected no BLE scan"); - delay(1000); - } - } - } - - void setupBT(){ - BLEinterval = TimeBtw_Read; - Minrssi = MinimumRSSI; - trc(F("BLEinterval btw scans")); - trc(BLEinterval); - trc(F("Minrssi")); - trc(Minrssi); - // we setup a task with priority one to avoid conflict with other gateways - xTaskCreatePinnedToCore( - 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 */ - trc(F("ZgatewayBT multicore ESP32 setup done ")); - } - - bool BTtoMQTT(){ // for on demand BLE scans - BLEscan(); - } - #else // arduino or ESP8266 working with HM10/11 - - #include - - #define STRING_MSG "OK+DISC:" - #define QUESTION_MSG "AT+DISA?" - #define RESPONSE_MSG "OK+DISIS" - #define RESP_END_MSG "OK+DISCE" - #define SETUP_MSG "OK+RESET" - - SoftwareSerial softserial(BT_RX, BT_TX); - - String returnedString = ""; - 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",34,60,false}}; - - void setupBT() { - BLEinterval = TimeBtw_Read; - Minrssi = MinimumRSSI; - trc(F("BLEinterval btw scans")); - trc(BLEinterval); - trc(F("Minrssi")); - trc(Minrssi); - softserial.begin(9600); - softserial.print(F("AT+ROLE1")); - delay(100); - softserial.print(F("AT+IMME1")); - delay(100); - softserial.print(F("AT+RESET")); - delay(100); - #ifdef HM_BLUE_LED_STOP - softserial.print(F("AT+PIO11")); // When not connected (as in BLE mode) the LED is off. When connected the LED is solid on. - #endif - delay(100); - trc(F("ZgatewayBT HM1X setup done ")); - } - - bool BTtoMQTT() { - - //extract serial data from module in hexa format - while (softserial.available() > 0) { - int a = softserial.read(); - if (a < 16) { - returnedString = returnedString + "0"; - } - returnedString = returnedString + String(a,HEX); - } - - if (millis() > (timebt + BLEinterval)) {//retriving data - timebt = millis(); - #if defined(ESP8266) - yield(); - #endif - if (returnedString != "") { - size_t pos = 0; - while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1) { - #if defined(ESP8266) - yield(); - #endif - String token = returnedString.substring(pos); - returnedString.remove(pos,returnedString.length() ); - char token_char[token.length()+1]; - token.toCharArray(token_char, token.length()+1); - trc(token); - if ( token.length() > 60){// we extract data only if we have detailled infos - 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 - } - - if((strlen(d[0].extract)) == 12) // if a mac adress is detected we publish it - { - trc(F("Creating BLE buffer")); - StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); - strupp(d[0].extract); - if(isBlack(d[0].extract)) return false; //if black listed mac we go out - if(oneWhite() && !isWhite(d[0].extract)) return false; //if we have at least one white mac and this mac is not white we go out - #ifdef subjectHomePresence - String HomePresenceId; - for (int i = 0; i<12; i++){ - HomePresenceId += String(d[0].extract[i]); - if(((i-1) % 2 == 0) && (i!=11)) HomePresenceId += ":"; - } - trc(F("HomePresenceId")); - trc(HomePresenceId); - BLEdata.set("id", (char *)HomePresenceId.c_str()); - #endif - String topic = subjectBTtoMQTT + String(d[0].extract); - int rssi = (int)strtol(d[2].extract, NULL, 16) - 256; - BLEdata.set("rssi", (int)rssi); - #ifdef subjectHomePresence - haRoomPresence(BLEdata);// this device has an rssi in consequence we can use it for home assistant room presence component - #endif - String service_data(d[5].extract); - service_data = service_data.substring(14); - #ifdef pubBLEServiceData - BLEdata.set("servicedata", (char *)service_data.c_str()); - #endif - if(abs((int)BLEdata["rssi"]|0) < abs(Minrssi)) { // publish only the devices close enough - pub((char *)topic.c_str(),BLEdata); - int pos = -1; - pos = strpos(d[5].extract,"209800"); - if (pos != -1) { - trc("mi flora data reading"); - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) MiFloraDiscovery(d[0].extract); - #endif - bool result = process_sensors(pos - 38,(char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"20aa01"); - //example "servicedata":"5020aa0194dfaa33342d580d1004e3002c02" - if (pos != -1){ - trc("mi jia data reading"); - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) MiJiaDiscovery(d[0].extract); - #endif - bool result = process_sensors(pos - 40,(char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"205b04"); - //example "servicedata":"141695fe70205b0461298882c8593f09061002d002" - if (pos != -1){ - trc("LYWSD02 data reading"); - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) LYWSD02Discovery(d[0].extract); - #endif - bool result = process_sensors(pos - 38,(char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"304703"); - if (pos != -1){ - trc("CLEARGRASSTRH data reading method 1"); - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) CLEARGRASSTRHDiscovery(d[0].extract); - #endif - bool result = process_sensors(pos - 40,(char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"e30706"); - if (pos != -1){ - trc("Mi Scale data reading"); - //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) MiScaleDiscovery(d[0].extract); - #endif - bool result = process_scale_v1((char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"4030dd"); - if (pos != -1){ - trc(F("Mi Lamp data reading")); - //example "servicedata":4030dd31d0300010100 - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) MiLampDiscovery(d[0].extract); - #endif - process_milamp((char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"08094c"); // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a - if (pos != -1){ - trc(F("Clear grass data with air pressure reading")); - //example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a - #ifdef ZmqttDiscovery - if(!isDiscovered(d[0].extract)) CLEARGRASSTRHKPADiscovery(d[0].extract); - #endif - process_cleargrass_air((char *)service_data.c_str(),d[0].extract); - } - pos = -1; - pos = strpos(d[5].extract,"080774"); // Clear grass standard method 2/0807743e10342d580104c3002c0202012a - if (pos != -1){ - trc(F("Clear grass data reading method 2")); - //example "servicedata":0807743e10342d580104 c300 2c02 02012a - // no discovery as it is already available with method 1 - process_cleargrass((char *)service_data.c_str(),d[0].extract); - } - return true; - }else{ - trc("Low rssi, device filtered"); - } - } - } - } - returnedString = ""; //init data string - return false; - } - softserial.print(F(QUESTION_MSG)); - return false; - }else{ - return false; - } + returnedString = ""; //init data string + return false; } + softserial.print(F(QUESTION_MSG)); + return false; + } + else + { + return false; + } +} #endif -double value_from_service_data(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 ); +double value_from_service_data(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); rev_data[data_length] = '\0'; - + // reverse data order - revert_hex_data(rev_data, data, data_length+1); + revert_hex_data(rev_data, data, data_length + 1); double value = strtol(data, NULL, 16); - if (value > 65000 && data_length <= 4) value = value - 65535; + if (value > 65000 && data_length <= 4) + value = value - 65535; trc(value); return value; } -bool process_sensors(int offset, char * rest_data, char * mac_adress){ - +bool process_sensors(int offset, char *rest_data, char *mac_adress) +{ + trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); trc("rest_data"); trc(rest_data); int data_length = 0; trc("data_length"); trc(rest_data[51 + offset]); - switch (rest_data[51 + offset]) { - case '1' : - case '2' : - case '3' : - case '4' : - data_length = ((rest_data[51 + offset] - '0') * 2); - trc("valid data_length"); + switch (rest_data[51 + offset]) + { + case '1': + case '2': + case '3': + case '4': + data_length = ((rest_data[51 + offset] - '0') * 2); + trc("valid data_length"); break; - default: - trc("invalid data_length"); + default: + trc("invalid data_length"); return false; - } - + } + double value = 9999; value = value_from_service_data(rest_data, 52 + offset, data_length); // 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 47 we determine the type of data we get from the sensor - switch (rest_data[47 + offset]) { - case '9' : - BLEdata.set("fer", (double)value); + switch (rest_data[47 + offset]) + { + case '9': + BLEdata.set("fer", (double)value); break; - case '4' : - BLEdata.set("tem", (double)value/10); + case '4': + BLEdata.set("tem", (double)value / 10); break; - case '6' : - BLEdata.set("hum", (double)value/10); + 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 '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(rest_data, 52 + offset, 4); - BLEdata.set("tem", (double)value/10); - // temperature - value = value_from_service_data(rest_data, 56 + offset, 4); - BLEdata.set("hum", (double)value/10); - break; - default: + case 'a': + BLEdata.set("batt", (double)value); + break; + + case 'd': + // humidity + value = value_from_service_data(rest_data, 52 + offset, 4); + BLEdata.set("tem", (double)value / 10); + // temperature + value = value_from_service_data(rest_data, 56 + offset, 4); + BLEdata.set("hum", (double)value / 10); + break; + default: trc("can't read values"); return false; - } - String mactopic(mac_adress); - mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); - return true; + } + String mactopic(mac_adress); + mactopic = subjectBTtoMQTT + mactopic; + pub((char *)mactopic.c_str(), BLEdata); + return true; } -bool process_scale_v1(char * rest_data, char * mac_adress){ +bool process_scale_v1(char *rest_data, char *mac_adress) +{ //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" trc("rest_data"); trc(rest_data); trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); - double weight = value_from_service_data(rest_data, 2, 4)/200; + double weight = value_from_service_data(rest_data, 2, 4) / 200; //Set Json value BLEdata.set("weight", (double)weight); @@ -898,20 +1023,21 @@ bool process_scale_v1(char * rest_data, char * mac_adress){ // Publish weight String mactopic(mac_adress); mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); + pub((char *)mactopic.c_str(), BLEdata); return true; } -bool process_scale_v2(char * rest_data, char * mac_adress){ +bool process_scale_v2(char *rest_data, char *mac_adress) +{ //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" trc("rest_data"); trc(rest_data); trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); - double weight = value_from_service_data(rest_data, 22, 4)/200; + double weight = value_from_service_data(rest_data, 22, 4) / 200; double impedance = value_from_service_data(rest_data, 18, 4); //Set Json values @@ -921,18 +1047,19 @@ bool process_scale_v2(char * rest_data, char * mac_adress){ // Publish weight String mactopic(mac_adress); mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); + pub((char *)mactopic.c_str(), BLEdata); return true; } -bool process_miband(char * rest_data, char * mac_adress){ +bool process_miband(char *rest_data, char *mac_adress) +{ //example "servicedata":"a21e0000" trc("rest_data"); trc(rest_data); trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); double steps = value_from_service_data(rest_data, 0, 4); @@ -942,18 +1069,19 @@ bool process_miband(char * rest_data, char * mac_adress){ // Publish weight String mactopic(mac_adress); mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); + pub((char *)mactopic.c_str(), BLEdata); return true; } -bool process_milamp(char * rest_data, char * mac_adress){ +bool process_milamp(char *rest_data, char *mac_adress) +{ //example "servicedata":"4030dd31d0300010100" trc("rest_data"); trc(rest_data); trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); long darkness = value_from_service_data(rest_data, 8, 2); @@ -964,11 +1092,12 @@ bool process_milamp(char * rest_data, char * mac_adress){ // Publish String mactopic(mac_adress); mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); + pub((char *)mactopic.c_str(), BLEdata); return true; } -bool process_cleargrass_air(char * rest_data, char * mac_adress){ +bool process_cleargrass_air(char *rest_data, char *mac_adress) +{ //example "servicedata":"08094c0140342d580104c400240207025d2702015a" //decoding "08094c0140342d580104 temp:c400 hum:2402 0702 pressure:5d27 02015a" trc("rest_data"); @@ -976,119 +1105,134 @@ bool process_cleargrass_air(char * rest_data, char * mac_adress){ trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); double value = 9999; // humidity value = value_from_service_data(rest_data, 20, 4); - BLEdata.set("tem", (double)value/10); + BLEdata.set("tem", (double)value / 10); // temperature value = value_from_service_data(rest_data, 24, 4); - BLEdata.set("hum", (double)value/10); + BLEdata.set("hum", (double)value / 10); // air pressure value = value_from_service_data(rest_data, 32, 4); - BLEdata.set("pres", (double)value/100); + BLEdata.set("pres", (double)value / 100); String mactopic(mac_adress); mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); + pub((char *)mactopic.c_str(), BLEdata); return true; } - -bool process_cleargrass(char * rest_data, char * mac_adress){ +bool process_cleargrass(char *rest_data, char *mac_adress) +{ //example "servicedata":0807743e10342d580104 c300 2c02 02012a trc("rest_data"); trc(rest_data); trc(F("Creating BLE buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BLEdata = jsonBuffer.createObject(); + JsonObject &BLEdata = jsonBuffer.createObject(); double value = 9999; // humidity value = value_from_service_data(rest_data, 20, 4); - BLEdata.set("tem", (double)value/10); + BLEdata.set("tem", (double)value / 10); // temperature value = value_from_service_data(rest_data, 24, 4); - BLEdata.set("hum", (double)value/10); + BLEdata.set("hum", (double)value / 10); String mactopic(mac_adress); mactopic = subjectBTtoMQTT + mactopic; - pub((char *)mactopic.c_str(),BLEdata); + pub((char *)mactopic.c_str(), BLEdata); return true; } #ifdef subjectHomePresence -void haRoomPresence(JsonObject& HomePresence){ +void haRoomPresence(JsonObject &HomePresence) +{ int BLErssi = HomePresence["rssi"]; trc(F("BLErssi")); trc(BLErssi); - int txPower = HomePresence["txpower"]|0; - if (txPower >= 0) txPower = -59; //if tx power is not found we set a default calibration value + int txPower = HomePresence["txpower"] | 0; + if (txPower >= 0) + txPower = -59; //if tx power is not found we set a default calibration value trc(F("txPower")); trc(txPower); - double ratio = BLErssi*1.0/txPower; + double ratio = BLErssi * 1.0 / txPower; double distance; - if (ratio < 1.0) { - distance = pow(ratio,10); - }else{ - distance = (0.89976)* pow(ratio,7.7095) + 0.111; + if (ratio < 1.0) + { + distance = pow(ratio, 10); + } + else + { + distance = (0.89976) * pow(ratio, 7.7095) + 0.111; } HomePresence["distance"] = distance; trc(F("BLE DISTANCE :")); trc(distance); String topic = String(Base_Topic) + "home_presence/" + String(gateway_name); - pub_custom_topic((char *)topic.c_str(),HomePresence); + pub_custom_topic((char *)topic.c_str(), HomePresence); } #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)) + { trc(F("MQTTtoBT json set")); // Black list & white list set - int WLsize = BTdata["white-list"].size(); - if(WLsize > 0){ + int WLsize = BTdata["white-list"].size(); + if (WLsize > 0) + { trc(F("WL set")); - for (int i = 0; i < WLsize; i++){ - const char * whiteMac = BTdata["white-list"][i]; + for (int i = 0; i < WLsize; i++) + { + const char *whiteMac = BTdata["white-list"][i]; setWorBMac((char *)whiteMac, true); } } - int BLsize = BTdata["black-list"].size(); - if(BLsize > 0){ + int BLsize = BTdata["black-list"].size(); + if (BLsize > 0) + { trc(F("BL set")); - for (int i = 0; i < BLsize; i++){ - const char * blackMac = BTdata["black-list"][i]; - setWorBMac((char *)blackMac,false); + for (int i = 0; i < BLsize; i++) + { + const char *blackMac = BTdata["black-list"][i]; + setWorBMac((char *)blackMac, false); } } - if (BLsize > 0 || WLsize > 0) dumpDevices(); + if (BLsize > 0 || WLsize > 0) + dumpDevices(); // Scan interval set - if (BTdata.containsKey("interval")){ + if (BTdata.containsKey("interval")) + { trc(F("BLE interval")); // storing BLE interval for further use if needed unsigned int prevBLEinterval = BLEinterval; trc("previous interval"); - trc(BLEinterval); + trc(BLEinterval); // set BLE interval if present if not setting default value BLEinterval = (unsigned int)BTdata["interval"]; trc("new interval"); trc(BLEinterval); - if (BLEinterval == 0) { - if(BTtoMQTT())// as BLEinterval is = to 0 we can launch the loop and the scan will execute immediately - trc(F("Scan done")); + if (BLEinterval == 0) + { + if (BTtoMQTT()) // as BLEinterval is = to 0 we can launch the loop and the scan will execute immediately + trc(F("Scan done")); 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")) + { trc(F("Min RSSI")); // storing Min RSSI for further use if needed trc("previous Minrssi"); - trc(Minrssi); + trc(Minrssi); // set Min RSSI if present if not setting default value Minrssi = (unsigned int)BTdata["minrssi"]; trc("new Minrssi"); diff --git a/main/ZgatewayIR.ino b/main/ZgatewayIR.ino index a4b7011..798930b 100644 --- a/main/ZgatewayIR.ino +++ b/main/ZgatewayIR.ino @@ -30,59 +30,60 @@ #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 - IRrecv irrecv(IR_RECEIVER_PIN, 1024, 15U, true); - #else - IRrecv irrecv(IR_RECEIVER_PIN); - #endif - IRsend irsend(IR_EMITTER_PIN); +#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 +IRrecv irrecv(IR_RECEIVER_PIN, 1024, 15U, true); #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 +IRrecv irrecv(IR_RECEIVER_PIN); +#endif +IRsend irsend(IR_EMITTER_PIN); +#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 // IR protocol bits definition for Arduino (for ESP9266 they are defined in IRRemoteESP8266.h) #ifndef NEC_BITS - #define NEC_BITS 32U +#define NEC_BITS 32U #endif #ifndef SAMSUNG_BITS - #define SAMSUNG_BITS 32U +#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 +#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 +#define RC5_RAW_BITS 14U +#define RC5_BITS RC5_RAW_BITS - 2U #endif #ifndef DISH_BITS - #define DISH_BITS 16U +#define DISH_BITS 16U #endif #ifndef SONY_12_BITS - #define SONY_12_BITS 12U +#define SONY_12_BITS 12U #endif #ifndef LG_BITS - #define LG_BITS 28U +#define LG_BITS 28U #endif #ifndef WHYNTER_BITS - #define WHYNTER_BITS 32U +#define WHYNTER_BITS 32U #endif -void setupIR(){ - //IR init parameters - #if defined(ESP8266) || defined(ESP32) - irsend.begin(); - #endif +void setupIR() +{ +//IR init parameters +#if defined(ESP8266) || defined(ESP32) + irsend.begin(); +#endif irrecv.enableIRIn(); // Start the receiver - + trc(F("IR_EMITTER_PIN ")); trc(IR_EMITTER_PIN); trc(F("IR_RECEIVER_PIN ")); @@ -90,855 +91,1089 @@ void setupIR(){ trc(F("ZgatewayIR setup done ")); } -void IRtoMQTT(){ +void IRtoMQTT() +{ decode_results results; - if (irrecv.decode(&results)){ + if (irrecv.decode(&results)) + { trc(F("Creating IR buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& IRdata = jsonBuffer.createObject(); + JsonObject &IRdata = jsonBuffer.createObject(); trc(F("Rcv. IR")); - #ifdef ESP32 - String taskMessage = "Task running on core "; - taskMessage = taskMessage + xPortGetCoreID(); - trc(taskMessage); - #endif +#ifdef ESP32 + String taskMessage = "Task running on core "; + taskMessage = taskMessage + xPortGetCoreID(); + trc(taskMessage); +#endif IRdata.set("value", (unsigned 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 - 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("bits", (int)(results.bits)); +#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 String rawCode = ""; // Dump data - 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 - rawCode = rawCode + (results.rawbuf[i] * USECPERTICK); - #endif - if ( i < results.rawlen-1 ) rawCode = rawCode + ","; // ',' not needed on last one + 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 + rawCode = rawCode + (results.rawbuf[i] * USECPERTICK); +#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) - uint16_t rawsend[results.rawlen]; - for (uint16_t i = 1; i < results.rawlen; i++) { - if (i % 100 == 0) yield(); // Preemptive yield every 100th entry to feed the WDT. - #else - unsigned int rawsend[results.rawlen]; - for (int i = 1; i < results.rawlen; i++) { - #endif - rawsend[i] = results.rawbuf[i]; - } - irsend.sendRaw(rawsend, results.rawlen, RawFrequency); - trc(F("raw redirected")); - #endif +// if needed we directly resend the raw code +#ifdef RawDirectForward +#if defined(ESP8266) || defined(ESP32) + uint16_t rawsend[results.rawlen]; + for (uint16_t i = 1; i < results.rawlen; i++) + { + if (i % 100 == 0) + yield(); // Preemptive yield every 100th entry to feed the WDT. +#else + unsigned int rawsend[results.rawlen]; + for (int i = 1; i < results.rawlen; i++) + { +#endif + rawsend[i] = results.rawbuf[i]; + } + irsend.sendRaw(rawsend, results.rawlen, RawFrequency); + trc(F("raw redirected")); +#endif irrecv.resume(); // Receive the next value unsigned long MQTTvalue = IRdata.get("value"); trc(MQTTvalue); - if ((pubIRunknownPrtcl == false && IRdata.get("protocol") == -1 )/*|| MQTTvalue == ULONG_MAX*/){ // don't publish unknown IR protocol or data to high + if ((pubIRunknownPrtcl == false && IRdata.get("protocol") == -1) /*|| MQTTvalue == ULONG_MAX*/) + { // don't publish unknown IR protocol or data to high trc(F("--no pub unknwn prt or data to high--")); - } else if (!isAduplicate(MQTTvalue) && MQTTvalue!=0) {// conditions to avoid duplications of IR -->MQTT - trc(F("Adv data IRtoMQTT")); - pub(subjectIRtoMQTT,IRdata); - trc(F("Store val")); - storeValue(MQTTvalue); - if (repeatIRwMQTT){ - trc(F("Pub. IR for rpt")); - pubMQTT(subjectMQTTtoIR,MQTTvalue); - } } + else if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) + { // conditions to avoid duplications of IR -->MQTT + trc(F("Adv data IRtoMQTT")); + pub(subjectIRtoMQTT, IRdata); + trc(F("Store val")); + storeValue(MQTTvalue); + if (repeatIRwMQTT) + { + trc(F("Pub. IR for rpt")); + pubMQTT(subjectMQTTtoIR, MQTTvalue); + } } + } } #ifdef simpleReceiving - void MQTTtoIR(char * topicOri, char * datacallback) { - - // IR DATA ANALYSIS - //send received MQTT value by IR signal - bool signalSent = false; - uint64_t data = 0; - String strcallback = String(datacallback); - trc(datacallback); - unsigned int s = strcallback.length(); - //number of "," value count - int count = 0; - for(int i = 0; i < s; i++) +void MQTTtoIR(char *topicOri, char *datacallback) +{ + + // IR DATA ANALYSIS + //send received MQTT value by IR signal + bool signalSent = false; + uint64_t data = 0; + String strcallback = String(datacallback); + trc(datacallback); + unsigned int s = strcallback.length(); + //number of "," value count + int count = 0; + for (int i = 0; i < s; i++) + { + if (datacallback[i] == ',') { - if (datacallback[i] == ',') { count++; - } } - if(count == 0){ - data = strtoul(datacallback, NULL, 10); // standard sending with unsigned long, we will not be able to pass values > 4294967295 - } - #ifdef IR_GC - else if(strstr(topicOri, "GC") != NULL){ // sending GC data from https://irdb.globalcache.com - trc(F("GC")); - //buffer allocation from char datacallback - uint16_t GC[count+1]; - String value = ""; - int j = 0; - for(int i = 0; i < s; i++) + } + if (count == 0) + { + data = strtoul(datacallback, NULL, 10); // standard sending with unsigned long, we will not be able to pass values > 4294967295 + } +#ifdef IR_GC + else if (strstr(topicOri, "GC") != NULL) + { // sending GC data from https://irdb.globalcache.com + trc(F("GC")); + //buffer allocation from char datacallback + uint16_t GC[count + 1]; + String value = ""; + int j = 0; + for (int i = 0; i < s; i++) + { + if (datacallback[i] != ',') { - if (datacallback[i] != ',') { - value = value + String(datacallback[i]); - } - if ((datacallback[i] == ',') || (i == s - 1)) - { - GC[j]= value.toInt(); - value = ""; - j++; - } + value = value + String(datacallback[i]); } - irsend.sendGC(GC, j); - signalSent = true; - } - #endif - #ifdef IR_RAW - else if(strstr(topicOri, "Raw") != NULL){ // sending Raw data - trc(F("Raw")); - //buffer allocation from char datacallback - #if defined(ESP8266) || defined(ESP32) - uint16_t Raw[count+1]; - #else - unsigned int Raw[count+1]; - #endif - String value = ""; - int j = 0; - for(int i = 0; i < s; i++) + if ((datacallback[i] == ',') || (i == s - 1)) { - if (datacallback[i] != ',') { - value = value + String(datacallback[i]); - } - if ((datacallback[i] == ',') || (i == s - 1)) - { - Raw[j]= value.toInt(); - value = ""; - j++; - } + GC[j] = value.toInt(); + value = ""; + j++; } - irsend.sendRaw(Raw, j, RawFrequency); - signalSent = true; } - #endif - - //We look into the subject to see if a special Bits number is defined - String topic = topicOri; - unsigned int valueBITS = 0; - int pos = topic.lastIndexOf(IRbitsKey); - if (pos != -1){ - pos = pos + +strlen(IRbitsKey); - valueBITS = (topic.substring(pos,pos + 2)).toInt(); - trc(F("Bits nb:")); - trc(valueBITS); + irsend.sendGC(GC, j); + signalSent = true; + } +#endif +#ifdef IR_RAW + else if (strstr(topicOri, "Raw") != NULL) + { // sending Raw data + trc(F("Raw")); +//buffer allocation from char datacallback +#if defined(ESP8266) || defined(ESP32) + uint16_t Raw[count + 1]; +#else + unsigned int Raw[count + 1]; +#endif + String value = ""; + int j = 0; + for (int i = 0; i < s; i++) + { + if (datacallback[i] != ',') + { + value = value + String(datacallback[i]); + } + if ((datacallback[i] == ',') || (i == s - 1)) + { + Raw[j] = value.toInt(); + value = ""; + j++; + } } - //We look into the subject to see if a special repeat number is defined - uint16_t valueRPT = 0; - int pos2 = topic.lastIndexOf(IRRptKey); - if (pos2 != -1) { - pos2 = pos2 + strlen(IRRptKey); - valueRPT = (topic.substring(pos2,pos2 + 1)).toInt(); - trc(F("IR repeat:")); - trc(valueRPT); - } - - if(topicOri && (strstr(topicOri, "NEC") == NULL)){ - trc("SendId prt"); - signalSent = sendIdentifiedProtocol(topicOri, data, datacallback, valueBITS, valueRPT); - }else{ - trc(F("Not identified prt using NEC")); - if (valueBITS == 0) valueBITS = NEC_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendNEC(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendNEC(data, valueBITS); - #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 - pub(subjectGTWIRtoMQTT, datacallback); - } - irrecv.enableIRIn(); // ReStart the IR receiver (if not restarted it is not able to receive data) + irsend.sendRaw(Raw, j, RawFrequency); + signalSent = true; } #endif + //We look into the subject to see if a special Bits number is defined + String topic = topicOri; + unsigned int valueBITS = 0; + int pos = topic.lastIndexOf(IRbitsKey); + if (pos != -1) + { + pos = pos + +strlen(IRbitsKey); + valueBITS = (topic.substring(pos, pos + 2)).toInt(); + trc(F("Bits nb:")); + trc(valueBITS); + } + //We look into the subject to see if a special repeat number is defined + uint16_t valueRPT = 0; + int pos2 = topic.lastIndexOf(IRRptKey); + if (pos2 != -1) + { + pos2 = pos2 + strlen(IRRptKey); + valueRPT = (topic.substring(pos2, pos2 + 1)).toInt(); + trc(F("IR repeat:")); + trc(valueRPT); + } + + if (topicOri && (strstr(topicOri, "NEC") == NULL)) + { + trc("SendId prt"); + signalSent = sendIdentifiedProtocol(topicOri, data, datacallback, valueBITS, valueRPT); + } + else + { + trc(F("Not identified prt using NEC")); + if (valueBITS == 0) + valueBITS = NEC_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendNEC(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendNEC(data, valueBITS); +#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 + pub(subjectGTWIRtoMQTT, datacallback); + } + irrecv.enableIRIn(); // ReStart the IR receiver (if not restarted it is not able to receive data) +} +#endif + #ifdef jsonReceiving - void MQTTtoIR(char * topicOri, JsonObject& IRdata) { +void MQTTtoIR(char *topicOri, JsonObject &IRdata) +{ - if (cmpToMainTopic(topicOri,subjectMQTTtoIR)){ - trc(F("MQTTtoIR json")); - uint64_t data = IRdata["value"]; - const char * raw = IRdata["raw"]; - const char * datastring = IRdata["datastring"]; - if (data != 0 || raw || datastring) { - trc(F("MQTTtoIR value || raw || datasring ok")); - bool signalSent = false; - if(datastring){ - trc(F("datastring")); - trc(datastring); - }else{ - datastring =""; - } - const char * protocol_name = IRdata["protocol_name"]; - unsigned int valueBITS = IRdata["bits"]|0; - uint16_t valueRPT = IRdata["repeat"]|repeatIRwNumber; + if (cmpToMainTopic(topicOri, subjectMQTTtoIR)) + { + trc(F("MQTTtoIR json")); + uint64_t data = IRdata["value"]; + const char *raw = IRdata["raw"]; + const char *datastring = IRdata["datastring"]; + if (data != 0 || raw || datastring) + { + trc(F("MQTTtoIR value || raw || datasring ok")); + bool signalSent = false; + if (datastring) + { + trc(F("datastring")); + trc(datastring); + } + else + { + datastring = ""; + } + const char *protocol_name = IRdata["protocol_name"]; + unsigned int valueBITS = IRdata["bits"] | 0; + uint16_t valueRPT = IRdata["repeat"] | repeatIRwNumber; - if(raw){ - trc(F("raw")); - trc(raw); - unsigned int s = strlen(raw); - //number of "," value count - int count = 0; - for(int i = 0; i < s; i++) + if (raw) + { + trc(F("raw")); + trc(raw); + unsigned int s = strlen(raw); + //number of "," value count + int count = 0; + for (int i = 0; i < s; i++) + { + if (raw[i] == ',') { - if (raw[i] == ',') { count++; - } } - #ifdef IR_GC - if(strstr(protocol_name, "GC") != NULL){ // sending GC data from https://irdb.globalcache.com - trc(F("GC")); - //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] != ',') { - value = value + String(raw[i]); - } - if ((raw[i] == ',') || (i == s - 1)) - { - GC[j]= value.toInt(); - value = ""; - j++; - } - } - irsend.sendGC(GC, j); - signalSent = true; - } - #endif - #ifdef IR_RAW - if(strstr(protocol_name, "Raw") != NULL){ // sending Raw data - trc(F("Raw")); - //buffer allocation from char datacallback - #if defined(ESP8266) || defined(ESP32) - uint16_t Raw[count+1]; - #else - unsigned int Raw[count+1]; - #endif + } +#ifdef IR_GC + if (strstr(protocol_name, "GC") != NULL) + { // sending GC data from https://irdb.globalcache.com + trc(F("GC")); + //buffer allocation from char datacallback + uint16_t GC[count + 1]; String value = ""; int j = 0; - for(int i = 0; i < s; i++) + for (int i = 0; i < s; i++) { - if (raw[i] != ',') { + if (raw[i] != ',') + { value = value + String(raw[i]); } if ((raw[i] == ',') || (i == s - 1)) { - Raw[j]= value.toInt(); + GC[j] = value.toInt(); value = ""; j++; } } - irsend.sendRaw(Raw, j, RawFrequency); - signalSent = true; - } - #endif - }else if(protocol_name && (strstr(protocol_name, "NEC") == NULL)){ - signalSent = sendIdentifiedProtocol(protocol_name, data, datastring, valueBITS, valueRPT); - }else{ - trc(F("Using NEC protocol")); - if (valueBITS == 0) valueBITS = NEC_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendNEC(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendNEC(data, valueBITS); - #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 - trc(F("MQTTtoIR OK")); - pub(subjectGTWIRtoMQTT, IRdata); - } - irrecv.enableIRIn(); // ReStart the IR receiver (if not restarted it is not able to receive data) - }else{ - trc(F("MQTTtoIR failed json read")); + irsend.sendGC(GC, j); + signalSent = true; } - } +#endif +#ifdef IR_RAW + if (strstr(protocol_name, "Raw") != NULL) + { // sending Raw data + trc(F("Raw")); +//buffer allocation from char datacallback +#if defined(ESP8266) || defined(ESP32) + uint16_t Raw[count + 1]; +#else + unsigned int Raw[count + 1]; +#endif + String value = ""; + int j = 0; + for (int i = 0; i < s; i++) + { + if (raw[i] != ',') + { + value = value + String(raw[i]); + } + if ((raw[i] == ',') || (i == s - 1)) + { + Raw[j] = value.toInt(); + value = ""; + j++; + } + } + irsend.sendRaw(Raw, j, RawFrequency); + signalSent = true; + } +#endif + } + else if (protocol_name && (strstr(protocol_name, "NEC") == NULL)) + { + signalSent = sendIdentifiedProtocol(protocol_name, data, datastring, valueBITS, valueRPT); + } + else + { + trc(F("Using NEC protocol")); + if (valueBITS == 0) + valueBITS = NEC_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendNEC(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendNEC(data, valueBITS); +#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 + trc(F("MQTTtoIR OK")); + pub(subjectGTWIRtoMQTT, IRdata); + } + irrecv.enableIRIn(); // ReStart the IR receiver (if not restarted it is not able to receive data) + } + else + { + trc(F("MQTTtoIR failed json read")); + } + } +} +#endif + +bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, const char *datastring, unsigned int valueBITS, uint16_t valueRPT) +{ + unsigned char dataarray[valueBITS]; + const char *pointer = datastring; + int i = 0; + while (strlen(pointer) > 0 && i < valueBITS) + { + if (pointer[0] == ',') + { + pointer++; + } + else + { + dataarray[i] = strtol(pointer, (char **)&pointer, 16); + i++; + } + } + +#ifdef IR_WHYNTER + if (strstr(protocol_name, "WHYNTER") != NULL) + { + if (valueBITS == 0) + valueBITS = WHYNTER_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendWhynter(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendWhynter(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_LG + if (strstr(protocol_name, "LG") != NULL) + { + if (valueBITS == 0) + valueBITS = LG_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendLG(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendLG(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_SONY + if (strstr(protocol_name, "SONY") != NULL) + { + if (valueBITS == 0) + valueBITS = SONY_12_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendSony(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendSony(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_DISH + if (strstr(protocol_name, "DISH") != NULL) + { + if (valueBITS == 0) + valueBITS = DISH_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendDISH(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendDISH(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_RC5 + if (strstr(protocol_name, "RC5") != NULL) + { + if (valueBITS == 0) + valueBITS = RC5_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendRC5(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendRC5(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_RC6 + if (strstr(protocol_name, "RC6") != NULL) + { + if (valueBITS == 0) + valueBITS = RC6_MODE0_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendRC6(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendRC6(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_SHARP + if (strstr(protocol_name, "SHARP") != NULL) + { + if (valueBITS == 0) + valueBITS = SHARP_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendSharpRaw(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendSharpRaw(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_SAMSUNG + if (strstr(protocol_name, "SAMSUNG") != NULL) + { + if (valueBITS == 0) + valueBITS = SAMSUNG_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendSAMSUNG(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendSAMSUNG(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_JVC + if (strstr(protocol_name, "JVC") != NULL) + { + if (valueBITS == 0) + valueBITS = JVC_BITS; +#if defined(ESP8266) || defined(ESP32) + irsend.sendJVC(data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendJVC(data, valueBITS); +#endif + return true; + } +#endif +#ifdef IR_PANASONIC + if (strstr(protocol_name, "PANASONIC") != NULL) + { +#if defined(ESP8266) || defined(ESP32) + if (valueBITS == 0) + valueBITS = PANASONIC_BITS; + irsend.sendPanasonic(PanasonicAddress, data, valueBITS, valueRPT); +#else + for (int i = 0; i <= valueRPT; i++) + irsend.sendPanasonic(PanasonicAddress, data); +#endif + return true; } #endif -bool sendIdentifiedProtocol(const char * protocol_name, unsigned long long data, const char * datastring, unsigned int valueBITS, uint16_t valueRPT){ - unsigned char dataarray[valueBITS]; - const char* pointer = datastring; - int i = 0; - while (strlen(pointer) > 0 && i < valueBITS) { - if (pointer[0] == ',') { - pointer++; - } - else - { - dataarray[i] = strtol(pointer, (char**)& pointer, 16); - i++; - } - } - - #ifdef IR_WHYNTER - if (strstr(protocol_name, "WHYNTER") != NULL){ - if (valueBITS == 0) valueBITS = WHYNTER_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendWhynter(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendWhynter(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_LG - if (strstr(protocol_name, "LG") != NULL){ - if (valueBITS == 0) valueBITS = LG_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendLG(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendLG(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_SONY - if (strstr(protocol_name, "SONY") != NULL){ - if (valueBITS == 0) valueBITS = SONY_12_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendSony(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendSony(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_DISH - if (strstr(protocol_name, "DISH") != NULL){ - if (valueBITS == 0) valueBITS = DISH_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendDISH(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendDISH(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_RC5 - if (strstr(protocol_name, "RC5") != NULL){ - if (valueBITS == 0) valueBITS = RC5_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendRC5(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendRC5(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_RC6 - if (strstr(protocol_name, "RC6") != NULL){ - if (valueBITS == 0) valueBITS = RC6_MODE0_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendRC6(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendRC6(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_SHARP - if (strstr(protocol_name, "SHARP") != NULL){ - if (valueBITS == 0) valueBITS = SHARP_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendSharpRaw(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendSharpRaw(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_SAMSUNG - if (strstr(protocol_name, "SAMSUNG") != NULL){ - if (valueBITS == 0) valueBITS = SAMSUNG_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendSAMSUNG(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendSAMSUNG(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_JVC - if (strstr(protocol_name, "JVC") != NULL){ - if (valueBITS == 0) valueBITS = JVC_BITS; - #if defined(ESP8266) || defined(ESP32) - irsend.sendJVC(data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendJVC(data, valueBITS); - #endif - return true; - } - #endif - #ifdef IR_PANASONIC - if (strstr(protocol_name, "PANASONIC") != NULL){ - #if defined(ESP8266) || defined(ESP32) - if (valueBITS == 0) valueBITS = PANASONIC_BITS; - irsend.sendPanasonic(PanasonicAddress, data, valueBITS, valueRPT); - #else - for (int i=0; i <= valueRPT; i++) irsend.sendPanasonic(PanasonicAddress, data); - #endif +#if defined(ESP8266) || defined(ESP32) // sendings not available on arduino +#ifdef IR_COOLIX + if (strstr(protocol_name, "COOLIX") != NULL) + { + if (valueBITS == 0) + valueBITS = kCoolixBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kCoolixDefaultRepeat); + irsend.sendCOOLIX(data, valueBITS, valueRPT); return true; - } - #endif - - #if defined(ESP8266) || defined(ESP32) // sendings not available on arduino - #ifdef IR_COOLIX - if (strstr(protocol_name, "COOLIX") != NULL){ - if (valueBITS == 0) valueBITS = kCoolixBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kCoolixDefaultRepeat); - irsend.sendCOOLIX(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_RCMM - if (strstr(protocol_name, "RCMM") != NULL){ - if (valueBITS == 0) valueBITS = kRCMMBits; - irsend.sendRCMM(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DENON - if (strstr(protocol_name, "DENON") != NULL){ - if (valueBITS == 0) valueBITS = DENON_BITS; - irsend.sendDenon(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_GICABLE - if (strstr(protocol_name, "GICABLE") != NULL){ - if (valueBITS == 0) valueBITS = kGicableBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kGicableMinRepeat); - irsend.sendGICable(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_SHERWOOD - if (strstr(protocol_name, "SHERWOOD") != NULL){ - if (valueBITS == 0) valueBITS = kSherwoodBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kSherwoodMinRepeat); - irsend.sendSherwood(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHI - if (strstr(protocol_name, "MITSUBISHI") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishiBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishiMinRepeat); - irsend.sendMitsubishi(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_NIKAI - if (strstr(protocol_name, "NIKAI") != NULL){ - if (valueBITS == 0) valueBITS = kNikaiBits; - irsend.sendNikai(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MIDEA - if (strstr(protocol_name, "MIDEA") != NULL){ - if (valueBITS == 0) valueBITS = kMideaBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMideaMinRepeat); - irsend.sendMidea(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MAGIQUEST - if (strstr(protocol_name, "MAGIQUEST") != NULL){ - if (valueBITS == 0) valueBITS = kMagiquestBits; - irsend.sendMagiQuest(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_LASERTAG - if (strstr(protocol_name, "LASERTAG") != NULL){ - if (valueBITS == 0) valueBITS = kLasertagBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kLasertagMinRepeat); - irsend.sendLasertag(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_CARRIER_AC - if (strstr(protocol_name, "CARRIER_AC") != NULL){ - if (valueBITS == 0) valueBITS = kCarrierAcBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kCarrierAcMinRepeat); - irsend.sendCarrierAC(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHI2 - if (strstr(protocol_name, "MITSUBISHI2") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishiBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishiMinRepeat); - irsend.sendMitsubishi2(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_AIWA_RC_T501 - if (strstr(protocol_name, "AIWA_RC_T501") != NULL){ - if (valueBITS == 0) valueBITS = kAiwaRcT501Bits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kAiwaRcT501MinRepeats); - irsend.sendAiwaRCT501(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN - if (strstr(protocol_name, "DAIKIN") != NULL){ - if (valueBITS == 0) valueBITS = kDaikinStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikinDefaultRepeat); - irsend.sendDaikin(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_KELVINATOR - if (strstr(protocol_name, "KELVINATOR") != NULL){ - if (valueBITS == 0) valueBITS = kKelvinatorStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kKelvinatorDefaultRepeat); - irsend.sendKelvinator(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHI_AC - if (strstr(protocol_name, "MITSUBISHI_AC") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishiACStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishiACMinRepeat); - irsend.sendMitsubishiAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_SANYO - if (strstr(protocol_name, "SANYOLC7461") != NULL){ - if (valueBITS == 0) valueBITS = kSanyoLC7461Bits; - irsend.sendSanyoLC7461(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_GREE - if (strstr(protocol_name, "GREE") != NULL){ - if (valueBITS == 0) valueBITS = kGreeStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kGreeDefaultRepeat); - irsend.sendGree(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_ARGO - if (strstr(protocol_name, "ARGO") != NULL){ - if (valueBITS == 0) valueBITS = kArgoStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kArgoDefaultRepeat); - irsend.sendArgo(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_TROTEC - if (strstr(protocol_name, "TROTEC") != NULL){ - if (valueBITS == 0) valueBITS = kTrotecStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kTrotecDefaultRepeat); - irsend.sendTrotec(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_TOSHIBA_AC - if (strstr(protocol_name, "TOSHIBA_AC") != NULL){ - if (valueBITS == 0) valueBITS = kToshibaACBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kToshibaACMinRepeat); - irsend.sendToshibaAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_FUJITSU_AC - if (strstr(protocol_name, "FUJITSU_AC") != NULL){ - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kFujitsuAcMinRepeat); - irsend.sendFujitsuAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_HAIER_AC - if (strstr(protocol_name, "HAIER_AC") != NULL){ - if (valueBITS == 0) valueBITS = kHaierACStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kHaierAcDefaultRepeat); - irsend.sendHaierAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_HITACHI_AC - if (strstr(protocol_name, "HITACHI_AC") != NULL){ - if (valueBITS == 0) valueBITS = kHitachiAcStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); - irsend.sendHitachiAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_HITACHI_AC1 - if (strstr(protocol_name, "HITACHI_AC1") != NULL){ - if (valueBITS == 0) valueBITS = kHitachiAc1StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); - irsend.sendHitachiAC1(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_HITACHI_AC2 - if (strstr(protocol_name, "HITACHI_AC2") != NULL){ - if (valueBITS == 0) valueBITS = kHitachiAc2StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); - irsend.sendHitachiAC2(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_HAIER_AC_YRW02 - if (strstr(protocol_name, "HAIER_AC_YRW02") != NULL){ - if (valueBITS == 0) valueBITS = kHaierACYRW02StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kHaierAcYrw02DefaultRepeat); - irsend.sendHaierACYRW02(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_WHIRLPOOL_AC - if (strstr(protocol_name, "WHIRLPOOL_AC") != NULL){ - if (valueBITS == 0) valueBITS = kWhirlpoolAcStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kWhirlpoolAcDefaultRepeat); - irsend.sendWhirlpoolAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_SAMSUNG_AC - if (strstr(protocol_name, "SAMSUNG_AC") != NULL){ - if (valueBITS == 0) valueBITS = kSamsungAcStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kSamsungAcDefaultRepeat); - irsend.sendSamsungAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_LUTRON - if (strstr(protocol_name, "LUTRON") != NULL){ - if (valueBITS == 0) valueBITS = kLutronBits; - irsend.sendLutron(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_ELECTRA_AC - if (strstr(protocol_name, "ELECTRA_AC") != NULL){ - if (valueBITS == 0) valueBITS = kElectraAcStateLength; - irsend.sendElectraAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_PANASONIC_AC - if (strstr(protocol_name, "PANASONIC_AC") != NULL){ - if (valueBITS == 0) valueBITS = kPanasonicAcStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kPanasonicAcDefaultRepeat); - irsend.sendPanasonicAC(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_PIONEER - if (strstr(protocol_name, "PIONEER") != NULL){ - if (valueBITS == 0) valueBITS = kPioneerBits; - irsend.sendPioneer(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_LG2 - if (strstr(protocol_name, "LG2") != NULL){ - if (valueBITS == 0) valueBITS = kLgBits; - irsend.sendLG2(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MWM - if (strstr(protocol_name, "MWM") != NULL){ - irsend.sendMWM(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN2 - if (strstr(protocol_name, "DAIKIN2") != NULL){ - if (valueBITS == 0) valueBITS = kDaikin2StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikin2DefaultRepeat); - irsend.sendDaikin2(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_VESTEL_AC - if (strstr(protocol_name, "VESTEL_AC") != NULL){ - if (valueBITS == 0) valueBITS = kVestelAcBits; - irsend.sendVestelAc(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_SAMSUNG36 - if (strstr(protocol_name, "SAMSUNG36") != NULL){ - if (valueBITS == 0) valueBITS = kSamsung36Bits; - irsend.sendSamsung36(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_TCL112AC - if (strstr(protocol_name, "TCL112AC") != NULL){ - if (valueBITS == 0) valueBITS = kTcl112AcStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kTcl112AcDefaultRepeat); - irsend.sendTcl112Ac(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_TECO - if (strstr(protocol_name, "TECO") != NULL){ - if (valueBITS == 0) valueBITS = kTecoBits; - irsend.sendTeco(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_LEGOPF - if (strstr(protocol_name, "LEGOPF") != NULL){ - if (valueBITS == 0) valueBITS = kLegoPfBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kLegoPfMinRepeat); - irsend.sendLegoPf(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHIHEAVY88 - if (strstr(protocol_name, "MITSUBISHIHEAVY88") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishiHeavy88StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishiHeavy88MinRepeat); - irsend.sendMitsubishiHeavy88(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHIHEAVY152 - if (strstr(protocol_name, "MITSUBISHIHEAVY152") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishiHeavy152StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishiHeavy152MinRepeat); - irsend.sendMitsubishiHeavy152(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN216 - if (strstr(protocol_name, "DAIKIN216") != NULL){ - if (valueBITS == 0) valueBITS = kDaikin216StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikin216DefaultRepeat); - irsend.sendDaikin216(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_SHARP_AC - if (strstr(protocol_name, "SHARP_AC") != NULL){ - if (valueBITS == 0) valueBITS = kSharpAcStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kSharpAcDefaultRepeat); - irsend.sendSharpAc(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_GOODWEATHER - if (strstr(protocol_name, "GOODWEATHER_AC") != NULL){ - if (valueBITS == 0) valueBITS = kGoodweatherBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kGoodweatherMinRepeat); - irsend.sendGoodweather(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_INAX - if (strstr(protocol_name, "INAX") != NULL){ - if (valueBITS == 0) valueBITS = kInaxBits; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kInaxMinRepeat); - irsend.sendInax(data, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN160 - if (strstr(protocol_name, "DAIKIN160") != NULL){ - if (valueBITS == 0) valueBITS = kDaikin160StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikin160DefaultRepeat); - irsend.sendDaikin160(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_NEOCLIMA - if (strstr(protocol_name, "NEOCLIMA") != NULL){ - if (valueBITS == 0) valueBITS = kNeoclimaStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kNeoclimaMinRepeat); - irsend.sendNeoclima(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN176 - if (strstr(protocol_name, "DAIKIN176") != NULL){ - if (valueBITS == 0) valueBITS = kDaikin176StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikin176DefaultRepeat); - irsend.sendDaikin176(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN128 - if (strstr(protocol_name, "DAIKIN128") != NULL){ - if (valueBITS == 0) valueBITS = kDaikin128StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikin128DefaultRepeat); - irsend.sendDaikin128(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_AMCOR - if (strstr(protocol_name, "AMCOR") != NULL){ - if (valueBITS == 0) valueBITS = kAmcorStateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kAmcorDefaultRepeat); - irsend.sendAmcor(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_DAIKIN152 - if (strstr(protocol_name, "DAIKIN152") != NULL){ - if (valueBITS == 0) valueBITS = kDaikin152StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kDaikin152DefaultRepeat); - irsend.sendDaikin152(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHI136 - if (strstr(protocol_name, "MITSUBISHI136") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishi136StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishi136MinRepeat); - irsend.sendMitsubishi136(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_MITSUBISHI112 - if (strstr(protocol_name, "MITSUBISHI112") != NULL){ - if (valueBITS == 0) valueBITS = kMitsubishi112StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kMitsubishi112MinRepeat); - irsend.sendMitsubishi112(dataarray, valueBITS, valueRPT); - return true; - } - #endif - #ifdef IR_HITACHI_AC424 - if (strstr(protocol_name, "HITACHI_AC424") != NULL){ - if (valueBITS == 0) valueBITS = kHitachiAc424StateLength; - if (valueRPT == repeatIRwNumber) valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); - irsend.sendHitachiAc424(dataarray, valueBITS, valueRPT); - return true; - } - #endif - return false; - #endif + } +#endif +#ifdef IR_RCMM + if (strstr(protocol_name, "RCMM") != NULL) + { + if (valueBITS == 0) + valueBITS = kRCMMBits; + irsend.sendRCMM(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DENON + if (strstr(protocol_name, "DENON") != NULL) + { + if (valueBITS == 0) + valueBITS = DENON_BITS; + irsend.sendDenon(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_GICABLE + if (strstr(protocol_name, "GICABLE") != NULL) + { + if (valueBITS == 0) + valueBITS = kGicableBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kGicableMinRepeat); + irsend.sendGICable(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_SHERWOOD + if (strstr(protocol_name, "SHERWOOD") != NULL) + { + if (valueBITS == 0) + valueBITS = kSherwoodBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kSherwoodMinRepeat); + irsend.sendSherwood(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHI + if (strstr(protocol_name, "MITSUBISHI") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishiBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishiMinRepeat); + irsend.sendMitsubishi(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_NIKAI + if (strstr(protocol_name, "NIKAI") != NULL) + { + if (valueBITS == 0) + valueBITS = kNikaiBits; + irsend.sendNikai(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MIDEA + if (strstr(protocol_name, "MIDEA") != NULL) + { + if (valueBITS == 0) + valueBITS = kMideaBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMideaMinRepeat); + irsend.sendMidea(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MAGIQUEST + if (strstr(protocol_name, "MAGIQUEST") != NULL) + { + if (valueBITS == 0) + valueBITS = kMagiquestBits; + irsend.sendMagiQuest(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_LASERTAG + if (strstr(protocol_name, "LASERTAG") != NULL) + { + if (valueBITS == 0) + valueBITS = kLasertagBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kLasertagMinRepeat); + irsend.sendLasertag(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_CARRIER_AC + if (strstr(protocol_name, "CARRIER_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kCarrierAcBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kCarrierAcMinRepeat); + irsend.sendCarrierAC(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHI2 + if (strstr(protocol_name, "MITSUBISHI2") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishiBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishiMinRepeat); + irsend.sendMitsubishi2(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_AIWA_RC_T501 + if (strstr(protocol_name, "AIWA_RC_T501") != NULL) + { + if (valueBITS == 0) + valueBITS = kAiwaRcT501Bits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kAiwaRcT501MinRepeats); + irsend.sendAiwaRCT501(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN + if (strstr(protocol_name, "DAIKIN") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikinStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikinDefaultRepeat); + irsend.sendDaikin(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_KELVINATOR + if (strstr(protocol_name, "KELVINATOR") != NULL) + { + if (valueBITS == 0) + valueBITS = kKelvinatorStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kKelvinatorDefaultRepeat); + irsend.sendKelvinator(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHI_AC + if (strstr(protocol_name, "MITSUBISHI_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishiACStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishiACMinRepeat); + irsend.sendMitsubishiAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_SANYO + if (strstr(protocol_name, "SANYOLC7461") != NULL) + { + if (valueBITS == 0) + valueBITS = kSanyoLC7461Bits; + irsend.sendSanyoLC7461(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_GREE + if (strstr(protocol_name, "GREE") != NULL) + { + if (valueBITS == 0) + valueBITS = kGreeStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kGreeDefaultRepeat); + irsend.sendGree(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_ARGO + if (strstr(protocol_name, "ARGO") != NULL) + { + if (valueBITS == 0) + valueBITS = kArgoStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kArgoDefaultRepeat); + irsend.sendArgo(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_TROTEC + if (strstr(protocol_name, "TROTEC") != NULL) + { + if (valueBITS == 0) + valueBITS = kTrotecStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kTrotecDefaultRepeat); + irsend.sendTrotec(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_TOSHIBA_AC + if (strstr(protocol_name, "TOSHIBA_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kToshibaACBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kToshibaACMinRepeat); + irsend.sendToshibaAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_FUJITSU_AC + if (strstr(protocol_name, "FUJITSU_AC") != NULL) + { + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kFujitsuAcMinRepeat); + irsend.sendFujitsuAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_HAIER_AC + if (strstr(protocol_name, "HAIER_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kHaierACStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kHaierAcDefaultRepeat); + irsend.sendHaierAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_HITACHI_AC + if (strstr(protocol_name, "HITACHI_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kHitachiAcStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); + irsend.sendHitachiAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_HITACHI_AC1 + if (strstr(protocol_name, "HITACHI_AC1") != NULL) + { + if (valueBITS == 0) + valueBITS = kHitachiAc1StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); + irsend.sendHitachiAC1(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_HITACHI_AC2 + if (strstr(protocol_name, "HITACHI_AC2") != NULL) + { + if (valueBITS == 0) + valueBITS = kHitachiAc2StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); + irsend.sendHitachiAC2(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_HAIER_AC_YRW02 + if (strstr(protocol_name, "HAIER_AC_YRW02") != NULL) + { + if (valueBITS == 0) + valueBITS = kHaierACYRW02StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kHaierAcYrw02DefaultRepeat); + irsend.sendHaierACYRW02(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_WHIRLPOOL_AC + if (strstr(protocol_name, "WHIRLPOOL_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kWhirlpoolAcStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kWhirlpoolAcDefaultRepeat); + irsend.sendWhirlpoolAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_SAMSUNG_AC + if (strstr(protocol_name, "SAMSUNG_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kSamsungAcStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kSamsungAcDefaultRepeat); + irsend.sendSamsungAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_LUTRON + if (strstr(protocol_name, "LUTRON") != NULL) + { + if (valueBITS == 0) + valueBITS = kLutronBits; + irsend.sendLutron(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_ELECTRA_AC + if (strstr(protocol_name, "ELECTRA_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kElectraAcStateLength; + irsend.sendElectraAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_PANASONIC_AC + if (strstr(protocol_name, "PANASONIC_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kPanasonicAcStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kPanasonicAcDefaultRepeat); + irsend.sendPanasonicAC(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_PIONEER + if (strstr(protocol_name, "PIONEER") != NULL) + { + if (valueBITS == 0) + valueBITS = kPioneerBits; + irsend.sendPioneer(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_LG2 + if (strstr(protocol_name, "LG2") != NULL) + { + if (valueBITS == 0) + valueBITS = kLgBits; + irsend.sendLG2(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MWM + if (strstr(protocol_name, "MWM") != NULL) + { + irsend.sendMWM(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN2 + if (strstr(protocol_name, "DAIKIN2") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikin2StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikin2DefaultRepeat); + irsend.sendDaikin2(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_VESTEL_AC + if (strstr(protocol_name, "VESTEL_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kVestelAcBits; + irsend.sendVestelAc(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_SAMSUNG36 + if (strstr(protocol_name, "SAMSUNG36") != NULL) + { + if (valueBITS == 0) + valueBITS = kSamsung36Bits; + irsend.sendSamsung36(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_TCL112AC + if (strstr(protocol_name, "TCL112AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kTcl112AcStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kTcl112AcDefaultRepeat); + irsend.sendTcl112Ac(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_TECO + if (strstr(protocol_name, "TECO") != NULL) + { + if (valueBITS == 0) + valueBITS = kTecoBits; + irsend.sendTeco(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_LEGOPF + if (strstr(protocol_name, "LEGOPF") != NULL) + { + if (valueBITS == 0) + valueBITS = kLegoPfBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kLegoPfMinRepeat); + irsend.sendLegoPf(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHIHEAVY88 + if (strstr(protocol_name, "MITSUBISHIHEAVY88") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishiHeavy88StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishiHeavy88MinRepeat); + irsend.sendMitsubishiHeavy88(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHIHEAVY152 + if (strstr(protocol_name, "MITSUBISHIHEAVY152") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishiHeavy152StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishiHeavy152MinRepeat); + irsend.sendMitsubishiHeavy152(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN216 + if (strstr(protocol_name, "DAIKIN216") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikin216StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikin216DefaultRepeat); + irsend.sendDaikin216(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_SHARP_AC + if (strstr(protocol_name, "SHARP_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kSharpAcStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kSharpAcDefaultRepeat); + irsend.sendSharpAc(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_GOODWEATHER + if (strstr(protocol_name, "GOODWEATHER_AC") != NULL) + { + if (valueBITS == 0) + valueBITS = kGoodweatherBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kGoodweatherMinRepeat); + irsend.sendGoodweather(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_INAX + if (strstr(protocol_name, "INAX") != NULL) + { + if (valueBITS == 0) + valueBITS = kInaxBits; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kInaxMinRepeat); + irsend.sendInax(data, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN160 + if (strstr(protocol_name, "DAIKIN160") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikin160StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikin160DefaultRepeat); + irsend.sendDaikin160(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_NEOCLIMA + if (strstr(protocol_name, "NEOCLIMA") != NULL) + { + if (valueBITS == 0) + valueBITS = kNeoclimaStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kNeoclimaMinRepeat); + irsend.sendNeoclima(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN176 + if (strstr(protocol_name, "DAIKIN176") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikin176StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikin176DefaultRepeat); + irsend.sendDaikin176(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN128 + if (strstr(protocol_name, "DAIKIN128") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikin128StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikin128DefaultRepeat); + irsend.sendDaikin128(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_AMCOR + if (strstr(protocol_name, "AMCOR") != NULL) + { + if (valueBITS == 0) + valueBITS = kAmcorStateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kAmcorDefaultRepeat); + irsend.sendAmcor(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_DAIKIN152 + if (strstr(protocol_name, "DAIKIN152") != NULL) + { + if (valueBITS == 0) + valueBITS = kDaikin152StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kDaikin152DefaultRepeat); + irsend.sendDaikin152(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHI136 + if (strstr(protocol_name, "MITSUBISHI136") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishi136StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishi136MinRepeat); + irsend.sendMitsubishi136(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_MITSUBISHI112 + if (strstr(protocol_name, "MITSUBISHI112") != NULL) + { + if (valueBITS == 0) + valueBITS = kMitsubishi112StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kMitsubishi112MinRepeat); + irsend.sendMitsubishi112(dataarray, valueBITS, valueRPT); + return true; + } +#endif +#ifdef IR_HITACHI_AC424 + if (strstr(protocol_name, "HITACHI_AC424") != NULL) + { + if (valueBITS == 0) + valueBITS = kHitachiAc424StateLength; + if (valueRPT == repeatIRwNumber) + valueRPT = std::max(valueRPT, kHitachiAcDefaultRepeat); + irsend.sendHitachiAc424(dataarray, valueBITS, valueRPT); + return true; + } +#endif + return false; +#endif } #endif diff --git a/main/ZgatewayLORA.ino b/main/ZgatewayLORA.ino index b3687b8..f212d00 100644 --- a/main/ZgatewayLORA.ino +++ b/main/ZgatewayLORA.ino @@ -31,15 +31,18 @@ #include #include -#include +#include -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)) { +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)) + { trc(F("ZgatewayLORA setup failed!")); - while (1); + while (1) + ; } LoRa.receive(); trc(F("LORA_SCK")); @@ -55,78 +58,91 @@ void setupLORA() { trc(F("LORA_DI0")); trc(LORA_DI0); trc(F("ZgatewayLORA setup done")); - } -void LORAtoMQTT(){ +void LORAtoMQTT() +{ int packetSize = LoRa.parsePacket(); - if (packetSize) { + if (packetSize) + { StaticJsonBuffer jsonBuffer; - JsonObject& LORAdata = jsonBuffer.createObject(); + JsonObject &LORAdata = jsonBuffer.createObject(); trc(F("Rcv. LORA")); - #ifdef ESP32 - String taskMessage = "LORA Task running on core "; - taskMessage = taskMessage + xPortGetCoreID(); - trc(taskMessage); - #endif - String packet ; - packet =""; - for (int i = 0; i < packetSize; i++) { packet += (char) LoRa.read(); } +#ifdef ESP32 + String taskMessage = "LORA Task running on core "; + taskMessage = taskMessage + xPortGetCoreID(); + trc(taskMessage); +#endif + String packet; + packet = ""; + 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("snr", (float)LoRa.packetSnr()); + LORAdata.set("pferror", (float)LoRa.packetFrequencyError()); LORAdata.set("packetSize", (int)packetSize); LORAdata.set("message", (char *)packet.c_str()); - pub(subjectLORAtoMQTT,LORAdata); - if (repeatLORAwMQTT){ - trc(F("Pub LORA for rpt")); - pub(subjectMQTTtoLORA,LORAdata); + pub(subjectLORAtoMQTT, LORAdata); + if (repeatLORAwMQTT) + { + trc(F("Pub LORA for rpt")); + pub(subjectMQTTtoLORA, LORAdata); } } } #ifdef jsonReceiving - void MQTTtoLORA(char * topicOri, JsonObject& LORAdata) { // json object decoding - if (cmpToMainTopic(topicOri,subjectMQTTtoLORA)){ - trc(F("MQTTtoLORA json")); - 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; - long int signalBandwidth = LORAdata["signalbandwidth"]|LORA_SIGNAL_BANDWIDTH; - int codingRateDenominator = LORAdata["codingrate"]|LORA_CODING_RATE; - int preambleLength = LORAdata["preamblelength"]|LORA_PREAMBLE_LENGTH; - byte syncWord = LORAdata["syncword"]|LORA_SYNC_WORD; - bool Crc = LORAdata["enablecrc"]|DEFAULT_CRC; - if (message) { - LoRa.setTxPower(txPower); - LoRa.setFrequency(frequency); - LoRa.setSpreadingFactor(spreadingFactor); - LoRa.setSignalBandwidth(signalBandwidth); - LoRa.setCodingRate4(codingRateDenominator); - LoRa.setPreambleLength(preambleLength); - LoRa.setSyncWord(syncWord); - if (Crc) LoRa.enableCrc(); - LoRa.beginPacket(); - LoRa.print(message); - LoRa.endPacket(); - trc(F("MQTTtoLORA OK")); - 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{ - trc(F("MQTTtoLORA Fail json")); - } +void MQTTtoLORA(char *topicOri, JsonObject &LORAdata) +{ // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) + { + trc(F("MQTTtoLORA json")); + 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; + long int signalBandwidth = LORAdata["signalbandwidth"] | LORA_SIGNAL_BANDWIDTH; + int codingRateDenominator = LORAdata["codingrate"] | LORA_CODING_RATE; + int preambleLength = LORAdata["preamblelength"] | LORA_PREAMBLE_LENGTH; + byte syncWord = LORAdata["syncword"] | LORA_SYNC_WORD; + bool Crc = LORAdata["enablecrc"] | DEFAULT_CRC; + if (message) + { + LoRa.setTxPower(txPower); + LoRa.setFrequency(frequency); + LoRa.setSpreadingFactor(spreadingFactor); + LoRa.setSignalBandwidth(signalBandwidth); + LoRa.setCodingRate4(codingRateDenominator); + LoRa.setPreambleLength(preambleLength); + LoRa.setSyncWord(syncWord); + if (Crc) + LoRa.enableCrc(); + LoRa.beginPacket(); + LoRa.print(message); + LoRa.endPacket(); + trc(F("MQTTtoLORA OK")); + 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 + { + trc(F("MQTTtoLORA Fail json")); } } +} #endif #ifdef simpleReceiving - void MQTTtoLORA(char * topicOri, char * LORAdata) { // json object decoding - if (cmpToMainTopic(topicOri,subjectMQTTtoLORA)){ - LoRa.beginPacket(); - LoRa.print(LORAdata); - LoRa.endPacket(); - trc(F("MQTTtoLORA OK")); - 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 - } +void MQTTtoLORA(char *topicOri, char *LORAdata) +{ // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) + { + LoRa.beginPacket(); + LoRa.print(LORAdata); + LoRa.endPacket(); + trc(F("MQTTtoLORA OK")); + 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 diff --git a/main/ZgatewayPilight.ino b/main/ZgatewayPilight.ino index e8a165e..032edfb 100644 --- a/main/ZgatewayPilight.ino +++ b/main/ZgatewayPilight.ino @@ -27,114 +27,134 @@ */ #include "User_config.h" - #ifdef ZgatewayPilight - #include - ESPiLight rf(RF_EMITTER_PIN); // use -1 to disable transmitter +#ifdef ZgatewayPilight +#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) + { trc(F("Creating RF PiLight buffer")); 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("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){ - trc(F("Pub Pilight for rpt")); - pub(subjectMQTTtoPilight,RFPiLightdata); + pub(subjectPilighttoMQTT, RFPiLightdata); + if (repeatPilightwMQTT) + { + trc(F("Pub Pilight for rpt")); + pub(subjectMQTTtoPilight, RFPiLightdata); } - } + } } -void setupPilight(){ - #ifndef ZgatewayRF && ZgatewayRF2 && ZgatewayRF315 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell - rf.setCallback(pilightCallback); - rf.initReceiver(RF_RECEIVER_PIN); - trc(F("RF_EMITTER_PIN ")); - trc(String(RF_EMITTER_PIN)); - trc(F("RF_RECEIVER_PIN ")); - trc(String(RF_RECEIVER_PIN)); - trc(F("ZgatewayPilight setup done ")); - #else - trc(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2 && ZgatewayRF315")); - #endif +void setupPilight() +{ +#ifndef ZgatewayRF &&ZgatewayRF2 &&ZgatewayRF315 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell + rf.setCallback(pilightCallback); + rf.initReceiver(RF_RECEIVER_PIN); + trc(F("RF_EMITTER_PIN ")); + trc(String(RF_EMITTER_PIN)); + trc(F("RF_RECEIVER_PIN ")); + trc(String(RF_RECEIVER_PIN)); + trc(F("ZgatewayPilight setup done ")); +#else + trc(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2 && ZgatewayRF315")); +#endif } -void PilighttoMQTT(){ +void PilighttoMQTT() +{ rf.loop(); } -void MQTTtoPilight(char * topicOri, JsonObject& Pilightdata) { +void MQTTtoPilight(char *topicOri, JsonObject &Pilightdata) +{ int result = 0; - - if (cmpToMainTopic(topicOri,subjectMQTTtoPilight)){ + + if (cmpToMainTopic(topicOri, subjectMQTTtoPilight)) + { trc(F("MQTTtoPilight json data analysis")); - 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) + { trc(F("MQTTtoPilight raw ok")); rf.sendPulseTrain(codes, msgLength); result = msgLength; - }else{ + } + else + { trc(F("MQTTtoPilight raw KO")); - switch (result) { - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C: - trc(F("'c' not found in string, or has no data")); - break; - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P: - trc(F("'p' not found in string, or has no data")); - break; - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END: - trc(F("';' or '@' not found in data string")); - break; - case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE: - trc(F("pulse type not defined")); - break; + switch (result) + { + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C: + trc(F("'c' not found in string, or has no data")); + break; + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P: + trc(F("'p' not found in string, or has no data")); + break; + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END: + trc(F("';' or '@' not found in data string")); + break; + case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE: + trc(F("pulse type not defined")); + break; } } - }else if (message && protocol) { + } + else if (message && protocol) + { trc(F("MQTTtoPilight msg & protocol ok")); result = rf.send(protocol, message); - }else{ + } + else + { trc(F("MQTTtoPilight failed json read")); } - if (result > 0) { + if (result > 0) + { trc(F("Adv data MQTTtoPilight push state via PilighttoMQTT")); pub(subjectGTWPilighttoMQTT, Pilightdata); - } else { - switch (result) { - case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: - trc(F("protocol is not available")); - break; - case ESPiLight::ERROR_INVALID_PILIGHT_MSG: - trc(F("message is invalid")); - break; - case ESPiLight::ERROR_INVALID_JSON: - trc(F("message is not a proper json object")); - break; - case ESPiLight::ERROR_NO_OUTPUT_PIN: - trc(F("no transmitter pin")); - break; - default: - trc(F("invalid json data, can't read raw or message/protocol")); - break; + } + else + { + switch (result) + { + case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: + trc(F("protocol is not available")); + break; + case ESPiLight::ERROR_INVALID_PILIGHT_MSG: + trc(F("message is invalid")); + break; + case ESPiLight::ERROR_INVALID_JSON: + trc(F("message is not a proper json object")); + break; + case ESPiLight::ERROR_NO_OUTPUT_PIN: + trc(F("no transmitter pin")); + break; + default: + trc(F("invalid json data, can't read raw or message/protocol")); + break; } } } } - #endif +#endif diff --git a/main/ZgatewayRF.ino b/main/ZgatewayRF.ino index 16335ec..4a457e1 100644 --- a/main/ZgatewayRF.ino +++ b/main/ZgatewayRF.ino @@ -34,146 +34,167 @@ RCSwitch mySwitch = RCSwitch(); #ifdef ZmqttDiscovery -void RFtoMQTTdiscovery(unsigned long MQTTvalue){//on the fly switch creation from received RF values +void RFtoMQTTdiscovery(unsigned long MQTTvalue) +{ //on the fly switch creation from received RF values char val[11]; sprintf(val, "%lu", MQTTvalue); trc(F("switchRFDiscovery")); - char * switchRF[8] = {"switch", val, "", "","",val, "", ""}; - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement + char *switchRF[8] = {"switch", val, "", "", "", val, "", ""}; + //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement - trc(F("CreateDiscoverySwitch")); - trc(switchRF[1]); - createDiscovery(switchRF[0], - 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); + trc(F("CreateDiscoverySwitch")); + trc(switchRF[1]); + createDiscovery(switchRF[0], + 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(){ +void setupRF() +{ //RF init parameters mySwitch.enableTransmit(RF_EMITTER_PIN); trc(F("RF_EMITTER_PIN ")); trc(RF_EMITTER_PIN); - mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); - mySwitch.enableReceive(RF_RECEIVER_PIN); + mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); + mySwitch.enableReceive(RF_RECEIVER_PIN); trc(F("RF_RECEIVER_PIN ")); trc(RF_RECEIVER_PIN); trc(F("RF setup ok")); } -void RFtoMQTT(){ +void RFtoMQTT() +{ - if (mySwitch.available()){ + if (mySwitch.available()) + { const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4); StaticJsonBuffer jsonBuffer; - JsonObject& RFdata = jsonBuffer.createObject(); + JsonObject &RFdata = jsonBuffer.createObject(); trc(F("Rcv. RF")); - #ifdef ESP32 - String taskMessage = "RF Task running on core "; - taskMessage = taskMessage + xPortGetCoreID(); - trc(taskMessage); - #endif +#ifdef ESP32 + String taskMessage = "RF Task running on core "; + taskMessage = taskMessage + xPortGetCoreID(); + trc(taskMessage); +#endif RFdata.set("value", (unsigned long)mySwitch.getReceivedValue()); - RFdata.set("protocol",(int)mySwitch.getReceivedProtocol()); + RFdata.set("protocol", (int)mySwitch.getReceivedProtocol()); RFdata.set("length", (int)mySwitch.getReceivedBitlength()); RFdata.set("delay", (int)mySwitch.getReceivedDelay()); 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 - RFtoMQTTdiscovery(MQTTvalue); - #endif - pub(subjectRFtoMQTT,RFdata); - trc(F("Store val")); - storeValue(MQTTvalue); - if (repeatRFwMQTT){ - trc(F("Pub RF for rpt")); - pub(subjectMQTTtoRF,RFdata); - } - } + if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) + { // conditions to avoid duplications of RF -->MQTT +#ifdef ZmqttDiscovery //component creation for HA + RFtoMQTTdiscovery(MQTTvalue); +#endif + pub(subjectRFtoMQTT, RFdata); + trc(F("Store val")); + storeValue(MQTTvalue); + if (repeatRFwMQTT) + { + trc(F("Pub RF for rpt")); + pub(subjectMQTTtoRF, RFdata); + } + } } } #ifdef simpleReceiving -void MQTTtoRF(char * topicOri, char * datacallback) { +void MQTTtoRF(char *topicOri, char *datacallback) +{ unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 // RF DATA ANALYSIS - //We look into the subject to see if a special RF protocol is defined + //We look into the subject to see if a special RF protocol is defined String topic = topicOri; int valuePRT = 0; - int valuePLSL = 0; - int valueBITS = 0; - int pos = topic.lastIndexOf(RFprotocolKey); - if (pos != -1){ + int valuePLSL = 0; + int valueBITS = 0; + int pos = topic.lastIndexOf(RFprotocolKey); + if (pos != -1) + { pos = pos + +strlen(RFprotocolKey); - valuePRT = (topic.substring(pos,pos + 1)).toInt(); + valuePRT = (topic.substring(pos, pos + 1)).toInt(); trc(F("RF Protocol:")); trc(valuePRT); } - //We look into the subject to see if a special RF pulselength is defined + //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(); + valuePLSL = (topic.substring(pos2, pos2 + 3)).toInt(); trc(F("RF Pulse Lgth:")); trc(valuePLSL); } - int pos3 = topic.lastIndexOf(RFbitsKey); - if (pos3 != -1){ + int pos3 = topic.lastIndexOf(RFbitsKey); + if (pos3 != -1) + { pos3 = pos3 + strlen(RFbitsKey); - valueBITS = (topic.substring(pos3,pos3 + 2)).toInt(); + valueBITS = (topic.substring(pos3, pos3 + 2)).toInt(); trc(F("Bits nb:")); trc(valueBITS); } - - if ((cmpToMainTopic(topicOri,subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)){ + + if ((cmpToMainTopic(topicOri, subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)) + { trc(F("MQTTtoRF dflt")); - mySwitch.setProtocol(1,350); + mySwitch.setProtocol(1, 350); mySwitch.send(data, 24); // Acknowledgement to the GTWRF topic - pub(subjectGTWRFtoMQTT, datacallback); - } else if ((valuePRT != 0) || (valuePLSL != 0)|| (valueBITS != 0)){ + pub(subjectGTWRFtoMQTT, datacallback); + } + else if ((valuePRT != 0) || (valuePLSL != 0) || (valueBITS != 0)) + { trc(F("MQTTtoRF usr par.")); - if (valuePRT == 0) valuePRT = 1; - if (valuePLSL == 0) valuePLSL = 350; - if (valueBITS == 0) valueBITS = 24; + if (valuePRT == 0) + valuePRT = 1; + if (valuePLSL == 0) + valuePLSL = 350; + if (valueBITS == 0) + valueBITS = 24; trc(valuePRT); trc(valuePLSL); trc(valueBITS); - mySwitch.setProtocol(valuePRT,valuePLSL); + mySwitch.setProtocol(valuePRT, valuePLSL); mySwitch.send(data, valueBITS); - // 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 - } + // 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 + } } #endif #ifdef jsonReceiving - void MQTTtoRF(char * topicOri, JsonObject& RFdata) { // json object decoding - if (cmpToMainTopic(topicOri,subjectMQTTtoRF)){ - trc(F("MQTTtoRF json")); - unsigned long data = RFdata["value"]; - if (data != 0) { - int valuePRT = RFdata["protocol"]|1; - int valuePLSL = RFdata["delay"]|350; - int valueBITS = RFdata["length"]|24; - int valueRPT = RFdata["repeat"]|RF_EMITTER_REPEAT; - mySwitch.setRepeatTransmit(valueRPT); - mySwitch.setProtocol(valuePRT,valuePLSL); - mySwitch.send(data, valueBITS); - trc(F("MQTTtoRF OK")); - 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{ - trc(F("MQTTtoRF Fail json")); - } +void MQTTtoRF(char *topicOri, JsonObject &RFdata) +{ // json object decoding + if (cmpToMainTopic(topicOri, subjectMQTTtoRF)) + { + trc(F("MQTTtoRF json")); + unsigned long data = RFdata["value"]; + if (data != 0) + { + int valuePRT = RFdata["protocol"] | 1; + int valuePLSL = RFdata["delay"] | 350; + int valueBITS = RFdata["length"] | 24; + int valueRPT = RFdata["repeat"] | RF_EMITTER_REPEAT; + mySwitch.setRepeatTransmit(valueRPT); + mySwitch.setProtocol(valuePRT, valuePLSL); + mySwitch.send(data, valueBITS); + trc(F("MQTTtoRF OK")); + 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 + { + trc(F("MQTTtoRF Fail json")); } } +} #endif #endif diff --git a/main/ZgatewayRF2.ino b/main/ZgatewayRF2.ino index 859c1e4..ed82f6c 100644 --- a/main/ZgatewayRF2.ino +++ b/main/ZgatewayRF2.ino @@ -52,220 +52,256 @@ struct RF2rxd RF2rxd rf2rd; -void setupRF2(){ - #ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF - NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback); - trc(F("RF_EMITTER_PIN ")); - trc(RF_EMITTER_PIN); - trc(F("RF_RECEIVER_PIN ")); - trc(RF_RECEIVER_PIN); - trc(F("ZgatewayRF2 setup done ")); - #endif - pinMode(RF_EMITTER_PIN, OUTPUT); - digitalWrite(RF_EMITTER_PIN, LOW); +void setupRF2() +{ +#ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF + NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback); + trc(F("RF_EMITTER_PIN ")); + trc(RF_EMITTER_PIN); + trc(F("RF_RECEIVER_PIN ")); + trc(RF_RECEIVER_PIN); + trc(F("ZgatewayRF2 setup done ")); +#endif + pinMode(RF_EMITTER_PIN, OUTPUT); + digitalWrite(RF_EMITTER_PIN, LOW); } -void RF2toMQTT(){ +void RF2toMQTT() +{ - if(rf2rd.hasNewData){ + if (rf2rd.hasNewData) + { trc(F("Creating RF2 buffer")); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5); StaticJsonBuffer jsonBuffer; - JsonObject& RF2data = jsonBuffer.createObject(); - + JsonObject &RF2data = jsonBuffer.createObject(); + rf2rd.hasNewData = false; - + trc(F("Rcv. RF2")); RF2data.set("unit", (int)rf2rd.unit); RF2data.set("groupBit", (int)rf2rd.groupBit); RF2data.set("period", (int)rf2rd.period); RF2data.set("address", (unsigned long)rf2rd.address); RF2data.set("switchType", (int)rf2rd.switchType); - + trc(F("Adv data RF2toMQTT")); - pub(subjectRF2toMQTT,RF2data); + pub(subjectRF2toMQTT, RF2data); } } -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; - rf2rd.unit=unit; - rf2rd.switchType=switchType; - rf2rd.hasNewData=true; +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; + rf2rd.unit = unit; + rf2rd.switchType = switchType; + rf2rd.hasNewData = true; } #ifdef simpleReceiving - void MQTTtoRF2(char * topicOri, char * datacallback) { - - // RF DATA ANALYSIS - //We look into the subject to see if a special RF protocol is defined - String topic = topicOri; - bool boolSWITCHTYPE; - boolSWITCHTYPE = to_bool(datacallback); - bool isDimCommand = false; - - long valueCODE = 0; - int valueUNIT = -1; - int valuePERIOD = 0; - int valueGROUP = 0; - int valueDIM = -1; - - int pos = topic.lastIndexOf(RF2codeKey); - if (pos != -1){ - pos = pos + +strlen(RF2codeKey); - valueCODE = (topic.substring(pos,pos + 8)).toInt(); - trc(F("RF2 code:")); - trc(valueCODE); - } - int pos2 = topic.lastIndexOf(RF2periodKey); - if (pos2 != -1) { - pos2 = pos2 + strlen(RF2periodKey); - valuePERIOD = (topic.substring(pos2,pos2 + 3)).toInt(); - trc(F("RF2 Period:")); - trc(valuePERIOD); - } - int pos3 = topic.lastIndexOf(RF2unitKey); - if (pos3 != -1){ - pos3 = pos3 + strlen(RF2unitKey); - valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt(); - trc(F("Unit:")); - trc(valueUNIT); - } - int pos4 = topic.lastIndexOf(RF2groupKey); - if (pos4 != -1) { - pos4 = pos4 + strlen(RF2groupKey); - valueGROUP = (topic.substring(pos4,pos4 + 1)).toInt(); - trc(F("RF2 Group:")); - trc(valueGROUP); - } - int pos5 = topic.lastIndexOf(RF2dimKey); - if (pos5 != -1) { - isDimCommand = true; - valueDIM = atoi(datacallback); - trc(F("RF2 Dim:")); - trc(valueDIM); - } - - if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){ - trc(F("MQTTtoRF2")); - if (valueCODE == 0) valueCODE = 8233378; - if (valueUNIT == -1) valueUNIT = 0; - if (valuePERIOD == 0) valuePERIOD = 272; - trc(valueCODE); - trc(valueUNIT); - trc(valuePERIOD); - trc(valueGROUP); - trc(boolSWITCHTYPE); - trc(valueDIM); - NewRemoteReceiver::disable(); - trc(F("Creating transmitter")); - NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); - trc(F("Sending data")); - if (valueGROUP) { - if (isDimCommand) { - transmitter.sendGroupDim(valueDIM); - } - else { - transmitter.sendGroup(boolSWITCHTYPE); - } +void MQTTtoRF2(char *topicOri, char *datacallback) +{ + + // RF DATA ANALYSIS + //We look into the subject to see if a special RF protocol is defined + String topic = topicOri; + bool boolSWITCHTYPE; + boolSWITCHTYPE = to_bool(datacallback); + bool isDimCommand = false; + + long valueCODE = 0; + int valueUNIT = -1; + int valuePERIOD = 0; + int valueGROUP = 0; + int valueDIM = -1; + + int pos = topic.lastIndexOf(RF2codeKey); + if (pos != -1) + { + pos = pos + +strlen(RF2codeKey); + valueCODE = (topic.substring(pos, pos + 8)).toInt(); + trc(F("RF2 code:")); + trc(valueCODE); + } + int pos2 = topic.lastIndexOf(RF2periodKey); + if (pos2 != -1) + { + pos2 = pos2 + strlen(RF2periodKey); + valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt(); + trc(F("RF2 Period:")); + trc(valuePERIOD); + } + int pos3 = topic.lastIndexOf(RF2unitKey); + if (pos3 != -1) + { + pos3 = pos3 + strlen(RF2unitKey); + valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt(); + trc(F("Unit:")); + trc(valueUNIT); + } + int pos4 = topic.lastIndexOf(RF2groupKey); + if (pos4 != -1) + { + pos4 = pos4 + strlen(RF2groupKey); + valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt(); + trc(F("RF2 Group:")); + trc(valueGROUP); + } + int pos5 = topic.lastIndexOf(RF2dimKey); + if (pos5 != -1) + { + isDimCommand = true; + valueDIM = atoi(datacallback); + trc(F("RF2 Dim:")); + trc(valueDIM); + } + + if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) + { + trc(F("MQTTtoRF2")); + if (valueCODE == 0) + valueCODE = 8233378; + if (valueUNIT == -1) + valueUNIT = 0; + if (valuePERIOD == 0) + valuePERIOD = 272; + trc(valueCODE); + trc(valueUNIT); + trc(valuePERIOD); + trc(valueGROUP); + trc(boolSWITCHTYPE); + trc(valueDIM); + NewRemoteReceiver::disable(); + trc(F("Creating transmitter")); + NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); + trc(F("Sending data")); + if (valueGROUP) + { + if (isDimCommand) + { + transmitter.sendGroupDim(valueDIM); } - else { - if (isDimCommand) { - transmitter.sendDim(valueUNIT, valueDIM); - } - else { - transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); - } + else + { + transmitter.sendGroup(boolSWITCHTYPE); } - trc(F("Data sent")); - NewRemoteReceiver::enable(); - - // Publish state change back to MQTT - String MQTTAddress; - String MQTTperiod; - String MQTTunit; - String MQTTgroupBit; - String MQTTswitchType; - String MQTTdimLevel; - - MQTTAddress = String(valueCODE); - MQTTperiod = String(valuePERIOD); - MQTTunit = String(valueUNIT); - MQTTgroupBit = String(rf2rd.groupBit); - MQTTswitchType = String(boolSWITCHTYPE); - MQTTdimLevel = String(valueDIM); - String MQTTRF2string; - trc(F("Adv data MQTTtoRF2 push state via RF2toMQTT")); - 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 + { + if (isDimCommand) + { + transmitter.sendDim(valueUNIT, valueDIM); } - else { - MQTTRF2string = subjectRF2toMQTT+String("/")+RF2codeKey+MQTTAddress+String("/")+RF2unitKey+MQTTunit+String("/")+RF2groupKey+MQTTgroupBit+String("/")+RF2periodKey+MQTTperiod; - pub((char *)MQTTRF2string.c_str(),(char *)MQTTswitchType.c_str()); + else + { + transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); } } + trc(F("Data sent")); + NewRemoteReceiver::enable(); + + // Publish state change back to MQTT + String MQTTAddress; + String MQTTperiod; + String MQTTunit; + String MQTTgroupBit; + String MQTTswitchType; + String MQTTdimLevel; + + MQTTAddress = String(valueCODE); + MQTTperiod = String(valuePERIOD); + MQTTunit = String(valueUNIT); + MQTTgroupBit = String(rf2rd.groupBit); + MQTTswitchType = String(boolSWITCHTYPE); + MQTTdimLevel = String(valueDIM); + String MQTTRF2string; + trc(F("Adv data MQTTtoRF2 push state via RF2toMQTT")); + 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 + { + MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod; + pub((char *)MQTTRF2string.c_str(), (char *)MQTTswitchType.c_str()); + } } +} #endif #ifdef jsonReceiving - void MQTTtoRF2(char * topicOri, JsonObject& RF2data) { // json object decoding - - if (cmpToMainTopic(topicOri,subjectMQTTtoRF2)){ - trc(F("MQTTtoRF2 json")); - int boolSWITCHTYPE = RF2data["switchType"] | 99; - if (boolSWITCHTYPE != 99) { - trc(F("MQTTtoRF2 switch type ok")); - bool isDimCommand = boolSWITCHTYPE == 2; - unsigned long valueCODE = RF2data["address"]; - int valueUNIT = RF2data["unit"] | -1; - int valuePERIOD = RF2data["period"]; - int valueGROUP = RF2data["group"]; - int valueDIM = RF2data["dim"] | -1; - if ((valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){ - trc(F("MQTTtoRF2")); - if (valueCODE == 0) valueCODE = 8233378; - if (valueUNIT == -1) valueUNIT = 0; - if (valuePERIOD == 0) valuePERIOD = 272; - trc(valueCODE); - trc(valueUNIT); - trc(valuePERIOD); - trc(valueGROUP); - trc(boolSWITCHTYPE); - trc(valueDIM); - NewRemoteReceiver::disable(); - NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); - trc(F("Sending")); - if (valueGROUP) { - if (isDimCommand) { - transmitter.sendGroupDim(valueDIM); - } - else { - transmitter.sendGroup(boolSWITCHTYPE); - } +void MQTTtoRF2(char *topicOri, JsonObject &RF2data) +{ // json object decoding + + if (cmpToMainTopic(topicOri, subjectMQTTtoRF2)) + { + trc(F("MQTTtoRF2 json")); + int boolSWITCHTYPE = RF2data["switchType"] | 99; + if (boolSWITCHTYPE != 99) + { + trc(F("MQTTtoRF2 switch type ok")); + bool isDimCommand = boolSWITCHTYPE == 2; + unsigned long valueCODE = RF2data["address"]; + int valueUNIT = RF2data["unit"] | -1; + int valuePERIOD = RF2data["period"]; + int valueGROUP = RF2data["group"]; + int valueDIM = RF2data["dim"] | -1; + if ((valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) + { + trc(F("MQTTtoRF2")); + if (valueCODE == 0) + valueCODE = 8233378; + if (valueUNIT == -1) + valueUNIT = 0; + if (valuePERIOD == 0) + valuePERIOD = 272; + trc(valueCODE); + trc(valueUNIT); + trc(valuePERIOD); + trc(valueGROUP); + trc(boolSWITCHTYPE); + trc(valueDIM); + NewRemoteReceiver::disable(); + NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); + trc(F("Sending")); + if (valueGROUP) + { + if (isDimCommand) + { + transmitter.sendGroupDim(valueDIM); } - else { - if (isDimCommand) { - transmitter.sendDim(valueUNIT, valueDIM); - } - else { - transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); - } + else + { + transmitter.sendGroup(boolSWITCHTYPE); } - trc(F("MQTTtoRF2 OK")); - NewRemoteReceiver::enable(); - - // Publish state change back to MQTT - pub(subjectGTWRF2toMQTT,RF2data); } - }else{ - trc(F("MQTTtoRF2 failed json read")); + else + { + if (isDimCommand) + { + transmitter.sendDim(valueUNIT, valueDIM); + } + else + { + transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); + } + } + trc(F("MQTTtoRF2 OK")); + NewRemoteReceiver::enable(); + + // Publish state change back to MQTT + pub(subjectGTWRF2toMQTT, RF2data); } } + else + { + trc(F("MQTTtoRF2 failed json read")); + } } +} #endif #endif diff --git a/main/ZgatewayRFM69.ino b/main/ZgatewayRFM69.ino index 1f0484a..c3c163b 100644 --- a/main/ZgatewayRFM69.ino +++ b/main/ZgatewayRFM69.ino @@ -32,7 +32,7 @@ #ifdef ZgatewayRFM69 -#include //https://www.github.com/lowpowerlab/rfm69 +#include //https://www.github.com/lowpowerlab/rfm69 #include #include @@ -40,46 +40,51 @@ char RadioConfig[128]; // vvvvvvvvv Global Configuration vvvvvvvvvvv -struct _GLOBAL_CONFIG { - uint32_t checksum; - char rfmapname[32]; - char encryptkey[16+1]; - uint8_t networkid; - uint8_t nodeid; - uint8_t powerlevel; // bits 0..4 power leve, bit 7 RFM69HCW 1=true - uint8_t rfmfrequency; +struct _GLOBAL_CONFIG +{ + uint32_t checksum; + char rfmapname[32]; + char encryptkey[16 + 1]; + uint8_t networkid; + uint8_t nodeid; + uint8_t powerlevel; // bits 0..4 power leve, bit 7 RFM69HCW 1=true + 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; // vvvvvvvvv Global Configuration vvvvvvvvvvv -uint32_t gc_checksum() { +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() { +void eeprom_setup() +{ EEPROM.begin(4096); 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) + { trc(F("Factory reset")); memset(pGC, 0, sizeof(*pGC)); strcpy_P(pGC->encryptkey, ENCRYPTKEY); strcpy_P(pGC->rfmapname, RFM69AP_NAME); pGC->networkid = NETWORKID; pGC->nodeid = NODEID; - pGC->powerlevel = ((IS_RFM69HCW)?0x80:0x00) | POWER_LEVEL; + pGC->powerlevel = ((IS_RFM69HCW) ? 0x80 : 0x00) | POWER_LEVEL; pGC->rfmfrequency = FREQUENCY; pGC->checksum = gc_checksum(); EEPROM.commit(); @@ -89,13 +94,14 @@ void eeprom_setup() { RFM69 radio; -void setupRFM69(void) { - #if defined(ESP8266) || defined(ESP32) - eeprom_setup(); - #endif +void setupRFM69(void) +{ +#if defined(ESP8266) || defined(ESP32) + eeprom_setup(); +#endif int freq; static const char PROGMEM JSONtemplate[] = - R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})"; + R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})"; char payload[128]; radio = RFM69(RFM69_CS, RFM69_IRQ, GC_IS_RFM69HCW, RFM69_IRQN); @@ -104,57 +110,62 @@ void setupRFM69(void) { if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid)) { trc(F("ZgatewayRFM69 initialization failed")); - } + } - if (GC_IS_RFM69HCW) { - radio.setHighPower(); // Only for RFM69HCW & HW! + if (GC_IS_RFM69HCW) + { + radio.setHighPower(); // Only for RFM69HCW & HW! } radio.setPowerLevel(GC_POWER_LEVEL); // power output ranges from 0 (5dBm) to 31 (20dBm) - if (pGC->encryptkey[0] != '\0') radio.encrypt(pGC->encryptkey); + if (pGC->encryptkey[0] != '\0') + radio.encrypt(pGC->encryptkey); trc(F("ZgatewayRFM69 Listening and transmitting at")); - 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; } trc(freq); size_t len = snprintf_P(RadioConfig, sizeof(RadioConfig), JSONtemplate, - freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL); - if (len >= sizeof(RadioConfig)) { + freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL); + if (len >= sizeof(RadioConfig)) + { trc(F("\n\n*** RFM69 config truncated ***\n")); } } -bool RFM69toMQTT(void) { +bool RFM69toMQTT(void) +{ //check if something was received (could be an interrupt from the radio) if (radio.receiveDone()) { trc(F("Creating RFM69 buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& RFM69data = jsonBuffer.createObject(); - uint8_t data[RF69_MAX_DATA_LEN+1]; // For the null character + 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); - data[DATALEN] = '\0'; // Terminate the string + data[DATALEN] = '\0'; // Terminate the string // Ack as soon as possible //check if sender wanted an ACK @@ -167,73 +178,88 @@ bool RFM69toMQTT(void) { trc(F("Data received")); trc((const char *)data); - char buff[sizeof(subjectRFM69toMQTT)+4]; + char buff[sizeof(subjectRFM69toMQTT) + 4]; sprintf(buff, "%s/%d", subjectRFM69toMQTT, SENDERID); RFM69data.set("data", (char *)data); - RFM69data.set("rssi", (int)radio.RSSI); + RFM69data.set("rssi", (int)radio.RSSI); RFM69data.set("senderid", (int)radio.SENDERID); - pub(buff,RFM69data); + pub(buff, RFM69data); return true; - - } else { + } + else + { return false; } } #ifdef simpleReceiving - void MQTTtoRFM69(char * topicOri, char * datacallback) { +void MQTTtoRFM69(char *topicOri, char *datacallback) +{ - if(cmpToMainTopic(topicOri,subjectMQTTtoRFM69)){ - trc(F("MQTTtoRFM69 data analysis")); - char data[RF69_MAX_DATA_LEN+1]; - 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){ - pos = pos + +strlen(RFM69receiverKey); - valueRCV = (topic.substring(pos,pos + 3)).toInt(); - trc(F("RFM69 receiver ID:")); - trc(valueRCV); - } - if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) { - trc(F(" OK ")); - // Acknowledgement to the GTWRF topic - char buff[sizeof(subjectGTWRFM69toMQTT)+4]; - sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID); - pub(buff, data); - } else { - trc(F("RFM69 sending failed")); - } + if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) + { + trc(F("MQTTtoRFM69 data analysis")); + char data[RF69_MAX_DATA_LEN + 1]; + 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) + { + pos = pos + +strlen(RFM69receiverKey); + valueRCV = (topic.substring(pos, pos + 3)).toInt(); + trc(F("RFM69 receiver ID:")); + trc(valueRCV); + } + if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) + { + trc(F(" OK ")); + // Acknowledgement to the GTWRF topic + char buff[sizeof(subjectGTWRFM69toMQTT) + 4]; + sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID); + pub(buff, data); + } + else + { + trc(F("RFM69 sending failed")); } } +} #endif #ifdef jsonReceiving - void MQTTtoRFM69(char * topicOri, JsonObject& RFM69data) { - - if (cmpToMainTopic(topicOri,subjectMQTTtoRFM69)){ - const char * data = RFM69data["data"]; - trc(F("MQTTtoRFM69 json data analysis")); - if(data){ - trc(F("MQTTtoRFM69 data ok")); - int valueRCV = RFM69data["receiverid"]| defaultRFM69ReceiverId; //default receiver id value - trc(F("RFM69 receiver ID:")); - trc(valueRCV); - if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) { - trc(F(" OK ")); - // 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 { - trc(F("MQTTtoRFM69 sending failed")); - } - }else{ - trc(F("MQTTtoRFM69 failed json read")); +void MQTTtoRFM69(char *topicOri, JsonObject &RFM69data) +{ + + if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) + { + const char *data = RFM69data["data"]; + trc(F("MQTTtoRFM69 json data analysis")); + if (data) + { + trc(F("MQTTtoRFM69 data ok")); + int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value + trc(F("RFM69 receiver ID:")); + trc(valueRCV); + if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) + { + trc(F(" OK ")); + // 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 + { + trc(F("MQTTtoRFM69 sending failed")); } } + else + { + trc(F("MQTTtoRFM69 failed json read")); + } } +} #endif #endif diff --git a/main/ZgatewaySRFB.ino b/main/ZgatewaySRFB.ino index 3a7ba3f..e527293 100644 --- a/main/ZgatewaySRFB.ino +++ b/main/ZgatewaySRFB.ino @@ -32,307 +32,357 @@ #ifdef ZgatewaySRFB -unsigned char _uartbuf[RF_MESSAGE_SIZE+3] = {0}; +unsigned char _uartbuf[RF_MESSAGE_SIZE + 3] = {0}; unsigned char _uartpos = 0; -void setupSRFB(){ +void setupSRFB() +{ trc(F("ZgatewaySRFB setup done ")); trc("Serial Baud" + String(SERIAL_BAUD)); } -void _rfbSend(byte * message) { - Serial.println(); - Serial.write(RF_CODE_START); - Serial.write(RF_CODE_RFOUT); - for (unsigned char j=0; j0) { - unsigned long start = millis(); - while (millis() - start < RF_SEND_DELAY) delay(1); - } - _rfbSend(message); + for (int i = 0; i < times; i++) + { + if (i > 0) + { + unsigned long start = millis(); + while (millis() - start < RF_SEND_DELAY) + delay(1); } + _rfbSend(message); + } } -bool SRFBtoMQTT() { - - static bool receiving = false; +bool SRFBtoMQTT() +{ - while (Serial.available()) { - yield(); - byte c = Serial.read(); + static bool receiving = false; - if (receiving) { - if (c == RF_CODE_STOP) { - _rfbDecode(); - receiving = false; - } else { - _uartbuf[_uartpos++] = c; - } - } else if (c == RF_CODE_START) { - _uartpos = 0; - receiving = true; - } + while (Serial.available()) + { + yield(); + byte c = Serial.read(); + if (receiving) + { + if (c == RF_CODE_STOP) + { + _rfbDecode(); + receiving = false; + } + else + { + _uartbuf[_uartpos++] = c; + } } - return receiving; + else if (c == RF_CODE_START) + { + _uartpos = 0; + receiving = true; + } + } + return receiving; } -void _rfbDecode() { +void _rfbDecode() +{ - static unsigned long last = 0; - if (millis() - last < RF_RECEIVE_DELAY) return; - last = millis(); + static unsigned long last = 0; + if (millis() - last < RF_RECEIVE_DELAY) + return; + last = millis(); - byte action = _uartbuf[0]; - char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0}; + byte action = _uartbuf[0]; + char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0}; - if (action == RF_CODE_RFIN) { - _rfbToChar(&_uartbuf[1], buffer); + if (action == RF_CODE_RFIN) + { + _rfbToChar(&_uartbuf[1], buffer); - trc(F("Creating SRFB buffer")); - StaticJsonBuffer jsonBuffer; - JsonObject& SRFBdata = jsonBuffer.createObject(); - SRFBdata.set("raw", (char *)buffer); + trc(F("Creating SRFB buffer")); + StaticJsonBuffer jsonBuffer; + JsonObject &SRFBdata = jsonBuffer.createObject(); + SRFBdata.set("raw", (char *)buffer); - char Tsyn[4]= {0}; - extract_char(buffer, Tsyn , 0 ,4, false, true); - int val_Tsyn = (int)strtol(Tsyn, NULL, 10); - SRFBdata.set("delay", (int)val_Tsyn); + char Tsyn[4] = {0}; + extract_char(buffer, Tsyn, 0, 4, false, true); + int val_Tsyn = (int)strtol(Tsyn, NULL, 10); + SRFBdata.set("delay", (int)val_Tsyn); - char Tlow[4]= {0}; - extract_char(buffer,Tlow , 4 ,4, false, true); - int val_Tlow = (int)strtol(Tlow, NULL, 10); - SRFBdata.set("val_Tlow", (int)val_Tlow); + char Tlow[4] = {0}; + extract_char(buffer, Tlow, 4, 4, false, true); + int val_Tlow = (int)strtol(Tlow, NULL, 10); + SRFBdata.set("val_Tlow", (int)val_Tlow); - char Thigh[4]= {0}; - extract_char(buffer, Thigh , 8 ,4, false, true); - int val_Thigh = (int)strtol(Thigh, NULL, 10); - SRFBdata.set("val_Thigh", (int)val_Thigh); + char Thigh[4] = {0}; + extract_char(buffer, Thigh, 8, 4, false, true); + int val_Thigh = (int)strtol(Thigh, NULL, 10); + SRFBdata.set("val_Thigh", (int)val_Thigh); - char val[8]= {0}; - extract_char(buffer, val, 12 ,8, false,true); - 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 - trc(F("Adv data SRFBtoMQTT")); - pub(subjectSRFBtoMQTT,SRFBdata); - trc(F("Store val")); - storeValue(MQTTvalue); - if (repeatSRFBwMQTT){ - trc(F("Publish SRFB for rpt")); - pub(subjectMQTTtoSRFB,SRFBdata); - } - } - _rfbAck(); + char val[8] = {0}; + extract_char(buffer, val, 12, 8, false, true); + 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 + trc(F("Adv data SRFBtoMQTT")); + pub(subjectSRFBtoMQTT, SRFBdata); + trc(F("Store val")); + storeValue(MQTTvalue); + if (repeatSRFBwMQTT) + { + trc(F("Publish SRFB for rpt")); + pub(subjectMQTTtoSRFB, SRFBdata); + } } + _rfbAck(); + } } -void _rfbAck() { - trc(F("[RFBRIDGE] Sending ACK\n")); - Serial.println(); - Serial.write(RF_CODE_START); - Serial.write(RF_CODE_ACK); - Serial.write(RF_CODE_STOP); - Serial.flush(); - Serial.println(); +void _rfbAck() +{ + trc(F("[RFBRIDGE] Sending ACK\n")); + Serial.println(); + Serial.write(RF_CODE_START); + Serial.write(RF_CODE_ACK); + Serial.write(RF_CODE_STOP); + Serial.flush(); + Serial.println(); } /* From an hexa char array ("A220EE...") to a byte array (half the size) */ -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> 8) & 0xFF); + hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF); + + byte hex_valueMaxiPLSL[2]; + hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF); + hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF); + + byte hex_valueSYNC[2]; + hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF); + hex_valueSYNC[1] = (int)(valueSYNC & 0xFF); + + unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 + byte hex_data[3]; + hex_data[0] = (unsigned long)((data >> 16) & 0xFF); + hex_data[1] = (unsigned long)((data >> 8) & 0xFF); + hex_data[2] = (unsigned long)(data & 0xFF); + + byte message_b[RF_MESSAGE_SIZE]; + + memcpy(message_b, hex_valueSYNC, 2); + memcpy(message_b + 2, hex_valueMiniPLSL, 2); + memcpy(message_b + 4, hex_valueMaxiPLSL, 2); + memcpy(message_b + 6, hex_data, 3); + + _rfbSend(message_b, valueRPT); + // 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) + { + + int pos = topic.lastIndexOf(SRFBRptKey); + if (pos != -1) + { + pos = pos + +strlen(SRFBRptKey); + valueRPT = (topic.substring(pos, pos + 1)).toInt(); + trc(F("SRFB Repeat:")); + trc(valueRPT); + } + if (valueRPT == 0) + valueRPT = 1; + + byte message_b[RF_MESSAGE_SIZE]; + _rfbToArray(datacallback, message_b); + _rfbSend(message_b, valueRPT); + // 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 + } +} +#endif +#ifdef jsonReceiving +void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata) +{ + + // RF DATA ANALYSIS + const char *raw = SRFBdata["raw"]; + int valueRPT = SRFBdata["repeat"] | 1; + if (cmpToMainTopic(topicOri, subjectMQTTtoSRFB)) + { + trc(F("MQTTtoSRFB json")); + if (raw) + { // send raw in priority when defined in the json + trc(F("MQTTtoSRFB raw ok")); + byte message_b[RF_MESSAGE_SIZE]; + _rfbToArray(raw, message_b); + _rfbSend(message_b, valueRPT); + } + else + { + unsigned long data = SRFBdata["value"]; + if (data != 0) + { + trc(F("MQTTtoSRFB data ok")); + int valueMiniPLSL = SRFBdata["val_Tlow"]; + int valueMaxiPLSL = SRFBdata["val_Thigh"]; + int valueSYNC = SRFBdata["delay"]; + + if (valueRPT == 0) + valueRPT = 1; + if (valueMiniPLSL == 0) + valueMiniPLSL = 320; + if (valueMaxiPLSL == 0) + valueMaxiPLSL = 900; + if (valueSYNC == 0) + valueSYNC = 9500; + byte hex_valueMiniPLSL[2]; - hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF) ; - hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF) ; - + hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF); + hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF); + byte hex_valueMaxiPLSL[2]; - hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF) ; - hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF) ; - + hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF); + hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF); + byte hex_valueSYNC[2]; - hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF) ; - hex_valueSYNC[1] = (int)(valueSYNC & 0xFF) ; - - unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 + hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF); + hex_valueSYNC[1] = (int)(valueSYNC & 0xFF); + byte hex_data[3]; - hex_data[0] = (unsigned long)((data >> 16) & 0xFF) ; - hex_data[1] = (unsigned long)((data >> 8) & 0xFF) ; - hex_data[2] = (unsigned long)(data & 0xFF) ; - + hex_data[0] = (unsigned long)((data >> 16) & 0xFF); + hex_data[1] = (unsigned long)((data >> 8) & 0xFF); + hex_data[2] = (unsigned long)(data & 0xFF); + byte message_b[RF_MESSAGE_SIZE]; - + memcpy(message_b, hex_valueSYNC, 2); memcpy(message_b + 2, hex_valueMiniPLSL, 2); memcpy(message_b + 4, hex_valueMaxiPLSL, 2); memcpy(message_b + 6, hex_data, 3); - + + trc(F("MQTTtoSRFB OK")); _rfbSend(message_b, valueRPT); - // 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){ - - int pos = topic.lastIndexOf(SRFBRptKey); - if (pos != -1){ - pos = pos + +strlen(SRFBRptKey); - valueRPT = (topic.substring(pos,pos + 1)).toInt(); - trc(F("SRFB Repeat:")); - trc(valueRPT); - } - if (valueRPT == 0) valueRPT = 1; - - byte message_b[RF_MESSAGE_SIZE]; - _rfbToArray(datacallback,message_b); - _rfbSend(message_b, valueRPT); - // 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 - } - } -#endif -#ifdef jsonReceiving - void MQTTtoSRFB(char * topicOri, JsonObject& SRFBdata) { - - // RF DATA ANALYSIS - const char * raw = SRFBdata["raw"]; - int valueRPT = SRFBdata["repeat"]|1; - if (cmpToMainTopic(topicOri,subjectMQTTtoSRFB)){ - trc(F("MQTTtoSRFB json")); - if (raw){ // send raw in priority when defined in the json - trc(F("MQTTtoSRFB raw ok")); - byte message_b[RF_MESSAGE_SIZE]; - _rfbToArray(raw,message_b); - _rfbSend(message_b, valueRPT); - }else{ - unsigned long data = SRFBdata["value"]; - if (data != 0) { - trc(F("MQTTtoSRFB data ok")); - int valueMiniPLSL = SRFBdata["val_Tlow"]; - int valueMaxiPLSL =SRFBdata["val_Thigh"]; - int valueSYNC = SRFBdata["delay"]; - - if (valueRPT == 0) valueRPT = 1; - if (valueMiniPLSL == 0) valueMiniPLSL = 320; - if (valueMaxiPLSL == 0) valueMaxiPLSL = 900; - if (valueSYNC == 0) valueSYNC = 9500; - - byte hex_valueMiniPLSL[2]; - hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF) ; - hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF) ; - - byte hex_valueMaxiPLSL[2]; - hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF) ; - hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF) ; - - byte hex_valueSYNC[2]; - hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF) ; - hex_valueSYNC[1] = (int)(valueSYNC & 0xFF) ; - - byte hex_data[3]; - hex_data[0] = (unsigned long)((data >> 16) & 0xFF) ; - hex_data[1] = (unsigned long)((data >> 8) & 0xFF) ; - hex_data[2] = (unsigned long)(data & 0xFF) ; - - byte message_b[RF_MESSAGE_SIZE]; - - memcpy(message_b, hex_valueSYNC, 2); - memcpy(message_b + 2, hex_valueMiniPLSL, 2); - memcpy(message_b + 4, hex_valueMaxiPLSL, 2); - memcpy(message_b + 6, hex_data, 3); - - trc(F("MQTTtoSRFB OK")); - _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{ - trc(F("MQTTtoSRFB error decoding value")); - } + // 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 + { + trc(F("MQTTtoSRFB error decoding value")); } } } +} #endif #endif diff --git a/main/ZmqttDiscovery.ino b/main/ZmqttDiscovery.ino index fcd93e0..352664e 100644 --- a/main/ZmqttDiscovery.ino +++ b/main/ZmqttDiscovery.ino @@ -31,15 +31,15 @@ String getMacAddress() { uint8_t baseMac[6]; char baseMacChr[13] = {0}; - #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) - 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 - sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - #endif +#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) + 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 + sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); +#endif return String(baseMacChr); } @@ -49,41 +49,50 @@ String getUniqueId(String name, String sufix) return String(uniqueId); } -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); + const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(1); StaticJsonBuffer jsonBuffer; JsonObject &sensor = jsonBuffer.createObject(); char state_topic[mqtt_topic_max_size]; - strcpy(state_topic,mqtt_topic); - strcat(state_topic,st_topic); + 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("uniq_id", unique_id); //unique_id - if (device_class[0]) sensor.set("dev_cla", device_class); //device_class - if (value_template[0]) sensor.set("val_tpl", value_template); //value_template - if (payload_on[0]) sensor.set("pl_on", payload_on); // payload_on - if (payload_off[0]) sensor.set("pl_off", payload_off); //payload_off - if (unit_of_meas[0]) sensor.set("unit_of_meas", unit_of_meas); //unit_of_measurement*/ - if (off_delay != 0) sensor.set("off_delay", off_delay); //off_delay - if (payload_available[0]) sensor.set("pl_avail", payload_available); // payload_on - if (payload_not_avalaible[0]) sensor.set("pl_not_avail", payload_not_avalaible); //payload_off - if (cmd_topic[0]) { + 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 + if (value_template[0]) + sensor.set("val_tpl", value_template); //value_template + if (payload_on[0]) + sensor.set("pl_on", payload_on); // payload_on + if (payload_off[0]) + sensor.set("pl_off", payload_off); //payload_off + if (unit_of_meas[0]) + sensor.set("unit_of_meas", unit_of_meas); //unit_of_measurement*/ + if (off_delay != 0) + sensor.set("off_delay", off_delay); //off_delay + if (payload_available[0]) + sensor.set("pl_avail", payload_available); // payload_on + if (payload_not_avalaible[0]) + sensor.set("pl_not_avail", payload_not_avalaible); //payload_off + + if (cmd_topic[0]) + { char command_topic[mqtt_topic_max_size]; - strcpy(command_topic,mqtt_topic); - strcat(command_topic,cmd_topic); + strcpy(command_topic, mqtt_topic); + strcat(command_topic, cmd_topic); sensor.set("cmd_t", command_topic); //command_topic - } + } -/*if (strcmp(s_name, Gateway_Name) == 0){ + /*if (strcmp(s_name, Gateway_Name) == 0){ JsonArray &json_attributes = sensor.createNestedArray("json_attributes"); json_attributes.add("uptime"); json_attributes.add("freemem"); @@ -91,7 +100,8 @@ void createDiscovery(char * sensor_type, json_attributes.add("SSID"); }*/ - if (child_device){ + if (child_device) + { const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(2); StaticJsonBuffer jsonDeviceBuffer; JsonObject &device = jsonDeviceBuffer.createObject(); @@ -109,325 +119,328 @@ void createDiscovery(char * sensor_type, void pubMqttDiscovery() { trc(F("omgStatusDiscovery")); - createDiscovery("binary_sensor", //set sensorType + createDiscovery("binary_sensor", //set sensorType 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 optimistic,retain, off_delay - Gateway_AnnouncementMsg, will_Message,true,"" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic, state on, state off - ); + will_Topic, "connectivity", "", //set availability_topic,device_class,value_template, + Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas, + 0, //set optimistic,retain, off_delay + Gateway_AnnouncementMsg, will_Message, true, "" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic, state on, state off + ); #ifdef ZsensorBME280 - #define BMEparametersCount 6 +#define BMEparametersCount 6 trc(F("bme280Discovery")); - char * BMEsensor[BMEparametersCount][8] = { - {"sensor", "tempc", "bme","temperature","{{ value_json.tempc }}","", "", "°C"} , - {"sensor", "tempf", "bme","temperature","{{ value_json.tempf }}","", "", "°F"} , - {"sensor", "pa", "bme","","{{ float(value_json.pa) * 0.01 }}","", "", "hPa"} , - {"sensor", "hum", "bme","humidity","{{ value_json.hum }}","", "", "%"} , - {"sensor", "altim", "bme","","{{ value_json.altim }}","", "", "m"} , - {"sensor", "altift", "bme","","{{ value_json.altift }}","", "", "ft"} - //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement + char *BMEsensor[BMEparametersCount][8] = { + {"sensor", "tempc", "bme", "temperature", "{{ value_json.tempc }}", "", "", "°C"}, + {"sensor", "tempf", "bme", "temperature", "{{ value_json.tempf }}", "", "", "°F"}, + {"sensor", "pa", "bme", "", "{{ float(value_json.pa) * 0.01 }}", "", "", "hPa"}, + {"sensor", "hum", "bme", "humidity", "{{ value_json.hum }}", "", "", "%"}, + {"sensor", "altim", "bme", "", "{{ value_json.altim }}", "", "", "m"}, + {"sensor", "altift", "bme", "", "{{ value_json.altift }}", "", "", "ft"} + //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement }; - - for (int i=0;i (timeadc + TimeBetweenReadingADC)) {//retriving value of temperature and humidity of the box from DHT every xUL - #if defined(ESP8266) - yield(); - #endif +void MeasureADC() +{ + if (millis() > (timeadc + TimeBetweenReadingADC)) + { //retriving value of temperature and humidity of the box from DHT every xUL +#if defined(ESP8266) + yield(); +#endif timeadc = millis(); static int persistedadc; int val = analogRead(ADC_PIN); - if (isnan(val)) { + if (isnan(val)) + { trc(F("Failed to read from ADC !")); - }else{ - if(val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC){ + } + else + { + if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC) + { trc(F("Creating ADC buffer")); 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); + pub(ADCTOPIC, ADCdata); persistedadc = val; - } + } } } } diff --git a/main/ZsensorBH1750.ino b/main/ZsensorBH1750.ino index 75597e9..5e6a6af 100644 --- a/main/ZsensorBH1750.ino +++ b/main/ZsensorBH1750.ino @@ -1,4 +1,4 @@ - /* +/* OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker @@ -46,21 +46,22 @@ void setupZsensorBH1750() { Wire.begin(); Wire.beginTransmission(BH1750_i2c_addr); - Wire.write(0x10); // Set resolution to 1 Lux + Wire.write(0x10); // Set resolution to 1 Lux Wire.endTransmission(); delay(300); } - -// void loop() + +// void loop() void MeasureLightIntensity() { - if (millis() > (timebh1750 + TimeBetweenReadingBH1750)) {//retriving value of Lux, FtCd and Wattsm2 from BH1750 + if (millis() > (timebh1750 + TimeBetweenReadingBH1750)) + { //retriving value of Lux, FtCd and Wattsm2 from BH1750 trc(F("Creating BH1750 buffer")); StaticJsonBuffer jsonBuffer; - JsonObject& BH1750data = jsonBuffer.createObject(); - + JsonObject &BH1750data = jsonBuffer.createObject(); + timebh1750 = millis(); - unsigned int i=0; + unsigned int i = 0; static float persistedll; static float persistedlf; static float persistedlw; @@ -70,39 +71,52 @@ 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) + { trc(F("Failed to read from LightSensor BH1750!")); - }else{ + } + else + { i = Wire.read(); - i <<=8; - i |= Wire.read(); + i <<= 8; + i |= Wire.read(); // Calculate the Values - Lux = i/1.2; // Convert to Lux - ftcd = Lux/10.764; - Wattsm2 = Lux/683.0; + Lux = i / 1.2; // Convert to Lux + ftcd = Lux / 10.764; + Wattsm2 = Lux / 683.0; // Generate Lux - if(Lux != persistedll || bh1750_always){ + if (Lux != persistedll || bh1750_always) + { BH1750data.set("lux", (unsigned int)Lux); - }else{ + } + else + { trc(F("Same lux don't send it")); - } + } // Generate FtCd - if(ftcd != persistedlf || bh1750_always){ + if (ftcd != persistedlf || bh1750_always) + { BH1750data.set("ftcd", (unsigned int)ftcd); - }else{ + } + else + { trc(F("Same ftcd don't send it")); } // Generate Watts/m2 - if(Wattsm2 != persistedlw || bh1750_always){ + if (Wattsm2 != persistedlw || bh1750_always) + { BH1750data.set("wattsm2", (unsigned int)Wattsm2); - }else{ + } + else + { trc(F("Same wattsm2 don't send it")); } - if(BH1750data.size()>0) pub(subjectBH1750toMQTT,BH1750data); + if (BH1750data.size() > 0) + pub(subjectBH1750toMQTT, BH1750data); } persistedll = Lux; persistedlf = ftcd; diff --git a/main/ZsensorBME280.ino b/main/ZsensorBME280.ino index 07deffb..39beb85 100644 --- a/main/ZsensorBME280.ino +++ b/main/ZsensorBME280.ino @@ -50,17 +50,17 @@ BME280 mySensor; void setupZsensorBME280() { mySensor.settings.commInterface = I2C_MODE; - mySensor.settings.I2CAddress = 0x76; // Bosch BME280 I2C Address - + mySensor.settings.I2CAddress = 0x76; // Bosch BME280 I2C Address + //***Operation settings*****************************// - + // runMode Setting - Values: // ------------------------- // 0, Sleep mode // 1 or 2, Forced mode // 3, Normal mode mySensor.settings.runMode = 3; //Normal mode - + // tStandby Setting - Values: // -------------------------- // 0, 0.5ms @@ -72,7 +72,7 @@ void setupZsensorBME280() // 6, 10ms // 7, 20ms mySensor.settings.tStandby = 1; - + // Filter can be off or number of FIR coefficients - Values: // --------------------------------------------------------- // 0, filter off @@ -81,7 +81,7 @@ void setupZsensorBME280() // 3, coefficients = 8 // 4, coefficients = 16 mySensor.settings.filter = 4; - + // tempOverSample - Values: // ------------------------ // 0, skipped @@ -92,14 +92,14 @@ void setupZsensorBME280() // ------------------------- // 0, skipped // 1 through 5, oversampling *1, *2, *4, *8, *16 respectively - mySensor.settings.pressOverSample = 1; - + mySensor.settings.pressOverSample = 1; + // humidOverSample - Values: // ------------------------- // 0, skipped // 1 through 5, oversampling *1, *2, *4, *8, *16 respectively mySensor.settings.humidOverSample = 1; - + delay(10); // Gives the Sensor enough time to turn on (The BME280 requires 2ms to start up) Serial.print("Bosch BME280 Initialized - Result of .begin(): 0x"); Serial.println(mySensor.begin(), HEX); @@ -108,7 +108,8 @@ void setupZsensorBME280() void MeasureTempHumAndPressure() { - if (millis() > (timebme280 + TimeBetweenReadingbme280)) { + if (millis() > (timebme280 + TimeBetweenReadingbme280)) + { timebme280 = millis(); static float persisted_bme_tempc; @@ -126,55 +127,77 @@ 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)) + { trc(F("Failed to read from Weather Sensor BME280!")); - }else{ - trc(F("Creating BME280 buffer")); - StaticJsonBuffer jsonBuffer; - JsonObject& BME280data = jsonBuffer.createObject(); + } + else + { + trc(F("Creating BME280 buffer")); + StaticJsonBuffer jsonBuffer; + 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 + { trc(F("Same Degrees C don't send it")); } - + // 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 + { trc(F("Same Degrees F don't send it")); } - + // 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 + { trc(F("Same Humidity don't send it")); } // 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 + { trc(F("Same Pressure don't send it")); } // Generate Altitude in Meter - if(BmeAltiM != persisted_bme_altim || bme280_always){ + if (BmeAltiM != persisted_bme_altim || bme280_always) + { trc(F("Sending Altitude Meter to MQTT")); BME280data.set("altim", (float)BmeAltiM); - }else{ + } + else + { trc(F("Same Altitude Meter don't send it")); } // 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 + { trc(F("Same Altitude Feet don't send it")); } - if(BME280data.size()>0) pub(BMETOPIC,BME280data); + if (BME280data.size() > 0) + pub(BMETOPIC, BME280data); } persisted_bme_tempc = BmeTempC; persisted_bme_tempf = BmeTempF; @@ -182,7 +205,6 @@ void MeasureTempHumAndPressure() persisted_bme_pa = BmePa; persisted_bme_altim = BmeAltiM; persisted_bme_altift = BmeAltiFt; - } } diff --git a/main/ZsensorDHT.ino b/main/ZsensorDHT.ino index 50d804d..0c39f95 100644 --- a/main/ZsensorDHT.ino +++ b/main/ZsensorDHT.ino @@ -33,37 +33,49 @@ #include #include -DHT dht(DHT_RECEIVER_PIN,DHT_SENSOR_TYPE); +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 MeasureTempAndHum(){ - if (millis() > (timedht + TimeBetweenReadingDHT)) {//retriving value of temperature and humidity of the box from DHT every xUL +void MeasureTempAndHum() +{ + if (millis() > (timedht + TimeBetweenReadingDHT)) + { //retriving value of temperature and humidity of the box from DHT every xUL timedht = millis(); static float persistedh; static float persistedt; float h = dht.readHumidity(); // Read temperature as Celsius (the default) - float t = dht.readTemperature(); + 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)) + { trc(F("Failed to read from DHT sensor!")); - }else{ + } + else + { trc(F("Creating DHT buffer")); 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 + { trc(F("Same hum don't send it")); - } - if(t != persistedt || dht_always){ + } + if (t != persistedt || dht_always) + { DHTdata.set("temp", (float)t); - }else{ + } + else + { trc(F("Same temp don't send it")); } - if(DHTdata.size()>0) pub(DHTTOPIC,DHTdata); + if (DHTdata.size() > 0) + pub(DHTTOPIC, DHTdata); } persistedh = h; persistedt = t; diff --git a/main/ZsensorGPIOInput.ino b/main/ZsensorGPIOInput.ino index 83d29b7..d24187c 100644 --- a/main/ZsensorGPIOInput.ino +++ b/main/ZsensorGPIOInput.ino @@ -31,15 +31,16 @@ #ifdef ZsensorGPIOInput unsigned long lastDebounceTime = 0; -int InputState = 3; // Set to 3 so that it reads on startup -int lastInputState = 3; +int InputState = 3; // Set to 3 so that it reads on startup +int lastInputState = 3; - -void setupGPIOInput() { - pinMode(GPIOInput_PIN, INPUT_PULLUP); // declare GPIOInput pin as input_pullup to prevent floating. Pin will be high when not connected to ground +void setupGPIOInput() +{ + 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 @@ -47,41 +48,45 @@ 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; trc(F("Creating GPIOInput buffer")); 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) + { trc(F("GPIO HIGH")); - pub(subjectGPIOInputtoMQTT,"HIGH"); + pub(subjectGPIOInputtoMQTT, "HIGH"); GPIOdata.set("gpio", "HIGH"); } - if (InputState == LOW) { + if (InputState == LOW) + { trc(F("GPIO LOW")); - GPIOdata.set("gpio","LOW"); - pub(subjectGPIOInputtoMQTT,"LOW"); + GPIOdata.set("gpio", "LOW"); + pub(subjectGPIOInputtoMQTT, "LOW"); } - if(GPIOdata.size()>0) pub(subjectGPIOInputtoMQTT,GPIOdata); + if (GPIOdata.size() > 0) + pub(subjectGPIOInputtoMQTT, GPIOdata); } } // save the reading. Next time through the loop, it'll be the lastInputState: lastInputState = reading; - } #endif diff --git a/main/ZsensorGPIOKeyCode.ino b/main/ZsensorGPIOKeyCode.ino index 4e97078..725ca81 100644 --- a/main/ZsensorGPIOKeyCode.ino +++ b/main/ZsensorGPIOKeyCode.ino @@ -27,19 +27,21 @@ #ifdef ZsensorGPIOKeyCode -int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on startup -int lastInputStateGPIOKeyCode = 0x0f; +int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on startup +int lastInputStateGPIOKeyCode = 0x0f; int lastLatchStateGPIOKeyCode = 0; -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_D3_PIN, INPUT_PULLUP); // +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_D3_PIN, INPUT_PULLUP); // } -void MeasureGPIOKeyCode(){ +void MeasureGPIOKeyCode() +{ int latch = digitalRead(GPIOKeyCode_LATCH_PIN); @@ -50,15 +52,14 @@ 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) { - int reading = digitalRead(GPIOKeyCode_D0_PIN) - | (digitalRead(GPIOKeyCode_D1_PIN) << 1) - | (digitalRead(GPIOKeyCode_D2_PIN) << 2); - //| digitalRead(GPIOKeyCode_D3_PIN) << 3; + 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; char hex[3]; @@ -66,19 +67,20 @@ void MeasureGPIOKeyCode(){ sprintf(hex, "%02x", InputStateGPIOKeyCode); hex[2] = 0; Serial.printf("GPIOKeyCode %s\n", hex); - client.publish(subjectGPIOKeyCodetoMQTT,hex); + client.publish(subjectGPIOKeyCodetoMQTT, hex); lastLatchStateGPIOKeyCode = latch; } - - if (latch != lastLatchStateGPIOKeyCode) { - lastLatchStateGPIOKeyCode = latch; - Serial.printf("GPIOKeyCode latch %d\n", latch); - if (latch == 0) - client.publish(subjectGPIOKeyCodeStatetoMQTT, "done"); - } - // save the reading. Next time through the loop, it'll be the lastInputState: - lastInputStateGPIOKeyCode = InputStateGPIOKeyCode; + if (latch != lastLatchStateGPIOKeyCode) + { + lastLatchStateGPIOKeyCode = latch; + Serial.printf("GPIOKeyCode latch %d\n", latch); + if (latch == 0) + client.publish(subjectGPIOKeyCodeStatetoMQTT, "done"); + } + + // save the reading. Next time through the loop, it'll be the lastInputState: + lastInputStateGPIOKeyCode = InputStateGPIOKeyCode; } } #endif diff --git a/main/ZsensorHCSR04.ino b/main/ZsensorHCSR04.ino index b379a40..412b369 100644 --- a/main/ZsensorHCSR04.ino +++ b/main/ZsensorHCSR04.ino @@ -33,41 +33,53 @@ unsigned long timeHCSR04 = 0; -void setupHCSR04() { - 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 +void setupHCSR04() +{ + 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 } -void MeasureDistance() { - if (millis() > (timeHCSR04 + TimeBetweenReadingHCSR04)) { +void MeasureDistance() +{ + if (millis() > (timeHCSR04 + TimeBetweenReadingHCSR04)) + { timeHCSR04 = millis(); trc(F("Creating HCSR04 buffer")); 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)) + { trc(F("Failed to read from HC SR04 sensor!")); - } else { + } + else + { static unsigned int distance = 99999; - unsigned int d = duration/58.2; + unsigned int d = duration / 58.2; HCSR04data.set("distance", (int)d); - if (d > distance) { + if (d > distance) + { HCSR04data.set("direction", "away"); trc(F("HC SR04 Distance changed")); - } else if (d < distance) { + } + else if (d < distance) + { HCSR04data.set("direction", "towards"); trc(F("HC SR04 Distance changed")); - } else if (HCSR04_always) { + } + else if (HCSR04_always) + { HCSR04data.set("direction", "static"); trc(F("HC SR04 Distance hasn't changed")); } distance = d; - if(HCSR04data.size()>0) pub(subjectHCSR04,HCSR04data); + if (HCSR04data.size() > 0) + pub(subjectHCSR04, HCSR04data); } } } diff --git a/main/ZsensorHCSR501.ino b/main/ZsensorHCSR501.ino index e48bee0..0e343d2 100644 --- a/main/ZsensorHCSR501.ino +++ b/main/ZsensorHCSR501.ino @@ -30,36 +30,45 @@ #ifdef ZsensorHCSR501 -void setupHCSR501() { - pinMode(HCSR501_PIN, INPUT); // declare HC SR-501 pin as input +void setupHCSR501() +{ + 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(); - static int pirState = LOW; - int PresenceValue = digitalRead(HCSR501_PIN); - #if defined(ESP8266) || defined(ESP32) + JsonObject &HCSR501data = jsonBuffer.createObject(); + static int pirState = LOW; + int PresenceValue = digitalRead(HCSR501_PIN); + #if defined(ESP8266) || defined(ESP32) yield(); - #endif - if (PresenceValue == HIGH) { - if (pirState == LOW) { - //turned on - HCSR501data.set("hcsr501", "true"); - trc(F("HC SR501 Motion started")); - pirState = HIGH; - } - } else { - if (pirState == HIGH){ - // turned off - HCSR501data.set("hcsr501", "false"); - trc(F("HC SR501 Motion ended")); - pirState = LOW; + #endif + if (PresenceValue == HIGH) + { + if (pirState == LOW) + { + //turned on + HCSR501data.set("hcsr501", "true"); + trc(F("HC SR501 Motion started")); + pirState = HIGH; } } - if(HCSR501data.size()>0) pub(subjectHCSR501toMQTT,HCSR501data); + else + { + if (pirState == HIGH) + { + // turned off + HCSR501data.set("hcsr501", "false"); + trc(F("HC SR501 Motion ended")); + pirState = LOW; + } + } + if (HCSR501data.size() > 0) + pub(subjectHCSR501toMQTT, HCSR501data); } } #endif diff --git a/main/ZsensorINA226.ino b/main/ZsensorINA226.ino index 645b099..0e96352 100644 --- a/main/ZsensorINA226.ino +++ b/main/ZsensorINA226.ino @@ -37,59 +37,64 @@ #ifdef ZsensorINA226 #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() { - Wire.begin(); +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)) {//retriving value of temperature and humidity of the box from DHT every xUL - timeINA226 = millis(); - trc(F("Creating INA226 buffer")); - StaticJsonBuffer jsonBuffer; - JsonObject& INA226data = jsonBuffer.createObject(); - // Topic on which we will send data - trc(F("Retrieving electrical data")); - // Bus Spannung, read-only, 16Bit, 0...40.96V max., LSB 1.25mV - trc(F(" Volt: ")); - float volt = readRegister(0x02) * 0.00125; - trc(volt); - trc(F(" V, Current: ")); - // 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 - shuntvolt = ~shuntvolt; // alle Bits invertieren - shuntvolt += 1; // 1 dazuzählen - shuntvolt *= -1 ; // negativ machen - } - float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R - trc(current); - trc(F(" A, Power: ")); - float power=abs(volt*current); - trc(power); - trc(F(" W")); - - char volt_c[7]; - char current_c[7]; - char power_c[7]; - 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); - pub(subjectINA226toMQTT,INA226data); +void MeasureINA226() +{ + if (millis() > (timeINA226 + TimeBetweenReadingINA226)) + { //retriving value of temperature and humidity of the box from DHT every xUL + timeINA226 = millis(); + trc(F("Creating INA226 buffer")); + StaticJsonBuffer jsonBuffer; + JsonObject &INA226data = jsonBuffer.createObject(); + // Topic on which we will send data + trc(F("Retrieving electrical data")); + // Bus Spannung, read-only, 16Bit, 0...40.96V max., LSB 1.25mV + trc(F(" Volt: ")); + float volt = readRegister(0x02) * 0.00125; + trc(volt); + trc(F(" V, Current: ")); + // 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 + shuntvolt = ~shuntvolt; // alle Bits invertieren + shuntvolt += 1; // 1 dazuzählen + shuntvolt *= -1; // negativ machen } + float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R + trc(current); + trc(F(" A, Power: ")); + float power = abs(volt * current); + trc(power); + trc(F(" W")); + + char volt_c[7]; + char current_c[7]; + char power_c[7]; + 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); + 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); @@ -97,13 +102,16 @@ 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) { - res = Wire.read() * 256; + 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 faede07..7857381 100644 --- a/main/ZsensorTSL2561.ino +++ b/main/ZsensorTSL2561.ino @@ -1,4 +1,4 @@ - /* +/* OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker @@ -72,47 +72,53 @@ void setupZsensorTSL2561() { trc(F("No TSL2561 detected")); } - + // enable auto ranging // tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */ // tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */ - tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */ + tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */ // since we're slowly sampling, enable high resolution but slow mode TSL2561 // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */ // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */ tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); trc(F("TSL2561 Initialized. Printing detials now.")); - displaySensorDetails(); + displaySensorDetails(); } void MeasureLightIntensityTSL2561() { - if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) { + if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) + { static uint32_t persisted_lux; timetsl2561 = millis(); trc(F("Creating TSL2561 buffer")); 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 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; + persisted_lux = event.light; - TSL2561data.set("lux", (float)event.light); - TSL2561data.set("ftcd", (float)(event.light)/10.764); - TSL2561data.set("wattsm2", (float)(event.light)/683.0); + TSL2561data.set("lux", (float)event.light); + TSL2561data.set("ftcd", (float)(event.light) / 10.764); + TSL2561data.set("wattsm2", (float)(event.light) / 683.0); - pub(subjectTSL12561toMQTT,TSL2561data); - } else { - trc(F("Same lux value, do not send")); - } - } else { + pub(subjectTSL12561toMQTT, TSL2561data); + } + else + { + trc(F("Same lux value, do not send")); + } + } + else + { trc(F("Failed to read from TSL2561")); } } diff --git a/main/config_2G.h b/main/config_2G.h index 7ad9e59..15ba8d0 100644 --- a/main/config_2G.h +++ b/main/config_2G.h @@ -28,13 +28,13 @@ 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 subjectGTW2GtoMQTT "/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 _2G_MODULE_BAUDRATE 9600 @@ -43,16 +43,16 @@ extern void MQTTto2G(char * topicOri, JsonObject& SMSdata); /*-------------------PIN DEFINITIONS----------------------*/ #ifdef ESP8266 - #define _2G_TX_PIN D6 //D6 to A6 RX, - #define _2G_RX_PIN D7 //D7 to A6 TX + #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_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_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 diff --git a/main/config_RF.h b/main/config_RF.h index 349ab05..f2cada0 100644 --- a/main/config_RF.h +++ b/main/config_RF.h @@ -30,31 +30,31 @@ #include #ifdef ZgatewayRF - extern void setupRF(); - extern void RFtoMQTT(); - extern void MQTTtoRF(char * topicOri, char * datacallback); - extern void MQTTtoRF(char * topicOri, JsonObject& RFdata); +extern void setupRF(); +extern void RFtoMQTT(); +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 setupRF2(); +extern void RF2toMQTT(); +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 setupPilight(); +extern void PilighttoMQTT(); +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 subjectGTWRFtoMQTT "/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 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,31 +73,31 @@ RF supported protocols /*-------------------RF2 topics & parameters----------------------*/ //433Mhz newremoteswitch MQTT Subjects and keys -#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 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 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 subjectGTWPilighttoMQTT "/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 /*-------------------PIN DEFINITIONS----------------------*/ #ifndef RF_RECEIVER_PIN #ifdef ESP8266 - #define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod + #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 + #define RF_RECEIVER_PIN 1 //1 = D3 on mega #else #define RF_RECEIVER_PIN 1 //1 = D3 on arduino #endif diff --git a/main/main.ino b/main/main.ino index 64bce81..cefebc7 100644 --- a/main/main.ino +++ b/main/main.ino @@ -29,13 +29,13 @@ // 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 - 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; +#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 - unsigned long ReceivedSignal[array_size][2] ={{0,0},{0,0},{0,0},{0,0}}; +#define array_size 4 +unsigned long ReceivedSignal[array_size][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}}; #endif #include @@ -43,100 +43,97 @@ // Modules config inclusion #if defined(ZgatewayRF) || defined(ZgatewayRF2) || defined(ZgatewayPilight) - #include "config_RF.h" -#endif -#ifdef ZgatewayRF315 - #include "config_RF315.h" +#include "config_RF.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 ZsensorHCSR04 - #include "config_HCSR04.h" +#include "config_HCSR04.h" #endif #ifdef ZsensorDHT - #include "config_DHT.h" +#include "config_DHT.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 /*------------------------------------------------------------------------*/ //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 = 0; // number of failure connecting to MQTT #ifdef ESP32 - #include + #include #include "SPIFFS.h" #include #include #include WiFiClient eClient; - #include - #ifdef MDNS_SD - #include - #endif + #include +#ifdef MDNS_SD + #include +#endif #elif defined(ESP8266) - #include + #include #include #include #include #include - #include + #include WiFiClient eClient; - #ifdef MDNS_SD - #include - #endif +#ifdef MDNS_SD + #include +#endif #else #include EthernetClient eClient; @@ -149,285 +146,345 @@ PubSubClient client(eClient); unsigned long lastMQTTReconnectAttempt = 0; unsigned long lastNTWKReconnectAttempt = 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 ) { - if (i%2 == 0) out[j] = in[i+1]; - else out[j] = in[i-1]; + int i = l - 2, j = 0; + while (i != -2) + { + if (i % 2 == 0) + out[j] = in[i + 1]; + else + out[j] = in[i - 1]; j++; i--; } - out[l-1] = '\0'; + out[l - 1] = '\0'; } -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){ - char tmp_subset2[l+1]; - if (reverse) revert_hex_data(tmp_subset, tmp_subset2, l+1); - else strncpy( tmp_subset2, tmp_subset , l+1); - long long_value = strtoul(tmp_subset2, NULL, 16); - sprintf(tmp_subset2, "%ld", long_value); - strncpy( subset, tmp_subset2 , l+1); - }else{ - if (reverse) revert_hex_data(tmp_subset, subset, l+1); - else strncpy( subset, tmp_subset , l+1); - } - subset[l] = '\0'; +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) + { + char tmp_subset2[l + 1]; + if (reverse) + revert_hex_data(tmp_subset, tmp_subset2, l + 1); + else + strncpy(tmp_subset2, tmp_subset, l + 1); + long long_value = strtoul(tmp_subset2, NULL, 16); + sprintf(tmp_subset2, "%ld", long_value); + strncpy(subset, tmp_subset2, l + 1); + } + else + { + if (reverse) + revert_hex_data(tmp_subset, subset, l + 1); + else + strncpy(subset, tmp_subset, l + 1); + } + subset[l] = '\0'; } int strpos(char *haystack, char *needle) //from @miere https://stackoverflow.com/users/548685/miere { - char *p = strstr(haystack, needle); - if (p) - return p - haystack; - return -1; + char *p = strstr(haystack, needle); + if (p) + return p - haystack; + return -1; } -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 - return s != "0"; +bool to_bool(String const &s) +{ // thanks Chris Jester-Young from stackoverflow + return s != "0"; } //trace -void trc(String msg){ +void trc(String msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(int msg){ +void trc(int msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(unsigned int msg){ +void trc(unsigned int msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(long msg){ +void trc(long msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(unsigned long msg){ +void trc(unsigned long msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(double msg){ +void trc(double msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(float msg){ +void trc(float msg) +{ #ifdef TRACE - Serial.println(msg); - digitalWrite(led_info, HIGH); + Serial.println(msg); + digitalWrite(led_info, HIGH); #endif #ifdef subjectTRACEtoMQTT - pubMQTT(subjectTRACEtoMQTT,msg); + pubMQTT(subjectTRACEtoMQTT, msg); #endif } -void trc(JsonObject& data){ +void trc(JsonObject &data) +{ char JSONmessageBuffer[JSON_MSG_BUFFER]; data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); trc(JSONmessageBuffer); } -void pub(char * topicori, char * payload, bool retainFlag){ +void pub(char *topicori, char *payload, bool retainFlag) +{ String topic = String(mqtt_topic) + String(topicori); client.publish((char *)topic.c_str(), payload, retainFlag); } -void pub(char * topicori, JsonObject& data){ - if(client.connected()) { +void pub(char *topicori, JsonObject &data) +{ + if (client.connected()) + { digitalWrite(led_receive, HIGH); String topic = String(mqtt_topic) + String(topicori); - #ifdef valueAsASubject - unsigned long value = data["value"]; - if (value != 0){ - topic = topic + "/"+ String(value); - } - #endif - - #ifdef jsonPublishing - char JSONmessageBuffer[JSON_MSG_BUFFER]; - trc(F("Pub json into:")); - trc(topic); - data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); - trc(JSONmessageBuffer); - pubMQTT(topic, JSONmessageBuffer); - #endif +#ifdef valueAsASubject + unsigned long value = data["value"]; + if (value != 0) + { + topic = topic + "/" + String(value); + } +#endif - #ifdef simplePublishing - trc(F("Pub data per topic")); - // Loop through all the key-value pairs in obj - 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 - trc(p.key); - trc(p.value.as()); - 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 - pubMQTT(topic + "/" + String(p.key),p.value.as()); - } - }else if (p.value.is()) { - trc(p.key); - trc(p.value.as()); - pubMQTT(topic + "/" + String(p.key),p.value.as()); - } else if (p.value.is()) { - trc(p.key); - trc(p.value.as()); - pubMQTT(topic + "/" + String(p.key),p.value.as()); - } else if (p.value.is()) { - trc(p.key); - trc(p.value.as()); - pubMQTT(topic + "/" + String(p.key),p.value.as()); +#ifdef jsonPublishing + char JSONmessageBuffer[JSON_MSG_BUFFER]; + trc(F("Pub json into:")); + trc(topic); + data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); + trc(JSONmessageBuffer); + pubMQTT(topic, JSONmessageBuffer); +#endif + +#ifdef simplePublishing + trc(F("Pub data per topic")); + // Loop through all the key-value pairs in obj + 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 + trc(p.key); + trc(p.value.as()); + 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 + pubMQTT(topic + "/" + String(p.key), p.value.as()); } } - #endif - }else{ + else if (p.value.is()) + { + trc(p.key); + trc(p.value.as()); + pubMQTT(topic + "/" + String(p.key), p.value.as()); + } + else if (p.value.is()) + { + trc(p.key); + trc(p.value.as()); + pubMQTT(topic + "/" + String(p.key), p.value.as()); + } + else if (p.value.is()) + { + trc(p.key); + trc(p.value.as()); + pubMQTT(topic + "/" + String(p.key), p.value.as()); + } + } +#endif + } + else + { trc("client not connected can't pub"); } } -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); trc(F("Pub ack into:")); trc(topic); pubMQTT(topic, payload); - }else{ + } + else + { trc("client not connected can't pub"); } } -void pub_custom_topic(char * topicori, JsonObject& data){ - if(client.connected()) { +void pub_custom_topic(char *topicori, JsonObject &data) +{ + if (client.connected()) + { char JSONmessageBuffer[JSON_MSG_BUFFER]; trc(F("Pub json discovery into:")); trc(topicori); data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); trc(JSONmessageBuffer); pubMQTT(topicori, JSONmessageBuffer); - }else{ + } + else + { trc("client not connected can't pub"); } } -void pubMQTT(char * topic, char * payload){ - client.publish(topic, payload); +void pubMQTT(char *topic, char *payload) +{ + client.publish(topic, payload); } -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){ - char val[11]; - sprintf(val, "%lu", payload); - client.publish(topic,val); +void pubMQTT(char *topic, unsigned long payload) +{ + char val[11]; + sprintf(val, "%lu", 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){ - char val[12]; - sprintf(val, "%d", payload); - client.publish((char *)topic.c_str(),val); +void pubMQTT(String topic, int payload) +{ + char val[12]; + sprintf(val, "%d", payload); + client.publish((char *)topic.c_str(), val); } -void pubMQTT(String topic, float payload){ - char val[12]; - dtostrf(payload,3,1,val); - client.publish((char *)topic.c_str(),val); +void pubMQTT(String topic, float payload) +{ + char val[12]; + dtostrf(payload, 3, 1, val); + client.publish((char *)topic.c_str(), val); } -void pubMQTT(char * topic, float payload){ - char val[12]; - dtostrf(payload,3,1,val); - client.publish(topic,val); +void pubMQTT(char *topic, float payload) +{ + char val[12]; + dtostrf(payload, 3, 1, val); + client.publish(topic, val); } -void pubMQTT(char * topic, int payload){ - char val[6]; - sprintf(val, "%d", payload); - client.publish(topic,val); +void pubMQTT(char *topic, int payload) +{ + char val[6]; + sprintf(val, "%d", payload); + client.publish(topic, val); } -void pubMQTT(char * topic, unsigned int payload){ - char val[6]; - sprintf(val, "%u", payload); - client.publish(topic,val); +void pubMQTT(char *topic, unsigned int payload) +{ + char val[6]; + sprintf(val, "%u", payload); + client.publish(topic, val); } -void pubMQTT(char * topic, long payload){ - char val[11]; - sprintf(val, "%l", payload); - client.publish(topic,val); +void pubMQTT(char *topic, long payload) +{ + char val[11]; + sprintf(val, "%l", payload); + client.publish(topic, val); } -void pubMQTT(char * topic, double payload){ - char val[16]; - sprintf(val, "%d", payload); - client.publish(topic,val); +void pubMQTT(char *topic, double payload) +{ + char val[16]; + sprintf(val, "%d", payload); + client.publish(topic, val); } -void pubMQTT(String topic, unsigned long payload){ - char val[11]; - sprintf(val, "%lu", payload); - client.publish((char *)topic.c_str(),val); +void pubMQTT(String topic, unsigned long payload) +{ + char val[11]; + sprintf(val, "%lu", payload); + client.publish((char *)topic.c_str(), val); } - + bool cmpToMainTopic(char * topicOri, char * toAdd){ char topic[mqtt_topic_max_size]; strcpy(topic,mqtt_topic); @@ -439,81 +496,91 @@ bool cmpToMainTopic(char * topicOri, char * toAdd){ } } -void reconnect() { - #ifndef ESPWifiManualSetup - #if defined(ESP8266) || defined(ESP32) - checkButton(); // check if a reset of wifi/mqtt settings is asked - #endif +void reconnect() +{ + +#ifndef ESPWifiManualSetup + #if defined(ESP8266) || defined(ESP32) + checkButton(); // check if a reset of wifi/mqtt settings is asked #endif +#endif // Loop until we're reconnected - while (!client.connected()) { + while (!client.connected()) + { trc(F("MQTT connection...")); //F function enable to decrease sram usage - if (client.connect(gateway_name, mqtt_user, mqtt_pass, will_Topic, will_QoS, will_Retain, will_Message)) { + if (client.connect(gateway_name, mqtt_user, mqtt_pass, will_Topic, will_QoS, will_Retain, will_Message)) + { trc(F("Connected to broker")); failure_number = 0; // Once connected, publish an announcement... - pub(will_Topic,Gateway_AnnouncementMsg,will_Retain); + pub(will_Topic, Gateway_AnnouncementMsg, will_Retain); // publish version - pub(version_Topic,OMG_VERSION,will_Retain); + pub(version_Topic, OMG_VERSION, will_Retain); //Subscribing to topic char topic[mqtt_topic_max_size]; strcpy(topic,mqtt_topic); strcat(topic,subjectMQTTtoX); - if (client.subscribe(topic)) { + if (client.subscribe(topic)) + { #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 + 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 - 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 + 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 trc(F("Subscription OK to the subjects")); } - } else { - failure_number ++; // we count the failure + } + else + { + failure_number++; // we count the failure trc(F("failure_number")); trc(failure_number); - if (failure_number > maxMQTTretry && !connectedOnce){ - #ifndef ESPWifiManualSetup - #if defined(ESP8266) || defined(ESP32) - trc(F("failed connecting first time to mqtt, reset wifi manager & erase network credentials")); - setup_wifimanager(true); - #endif + if (failure_number > maxMQTTretry && !connectedOnce) + { + #ifndef ESPWifiManualSetup + #if defined(ESP8266) || defined(ESP32) + trc(F("failed connecting first time to mqtt, reset wifi manager & erase network credentials")); + setup_wifimanager(true); #endif + #endif } trc(F("failed, rc=")); trc(client.state()); delay(5000); - // On ESP32 force wifi begin https://github.com/espressif/arduino-esp32/issues/2501 - #if defined(ESP32) - WiFi.begin(); - #endif +// On ESP32 force wifi begin https://github.com/espressif/arduino-esp32/issues/2501 + #if defined(ESP32) + WiFi.begin(); + #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. trc(F("Hey I got a callback ")); // 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); + 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); + if ((strstr(topic, subjectMultiGTWKey) != NULL) || (strstr(topic, subjectGTWSendKey) != NULL)) + receivingMQTT(topic, (char *)p); // Free the memory free(p); } void setup_parameters() { - strcat(mqtt_topic,gateway_name); + strcat(mqtt_topic, gateway_name); } void setup() @@ -521,61 +588,65 @@ void setup() //Launch serial for debugging purposes Serial.begin(SERIAL_BAUD); - #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 - #endif - - #if defined(ESPWifiManualSetup) - setup_wifi(); - #else - setup_wifimanager(false); +#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 + #endif - trc(F("OpenMQTTGateway mac: ")); - trc(WiFi.macAddress()); + #if defined(ESPWifiManualSetup) + setup_wifi(); + #else + setup_wifimanager(false); + #endif - trc(F("OpenMQTTGateway ip: ")); - trc(WiFi.localIP().toString()); + trc(F("OpenMQTTGateway mac: ")); + trc(WiFi.macAddress()); - // Port defaults to 8266 - ArduinoOTA.setPort(ota_port); + trc(F("OpenMQTTGateway ip: ")); + trc(WiFi.localIP().toString()); - // Hostname defaults to esp8266-[ChipID] - ArduinoOTA.setHostname(ota_hostname); + // Port defaults to 8266 + ArduinoOTA.setPort(ota_port); - // No authentication by default - ArduinoOTA.setPassword(ota_password); + // Hostname defaults to esp8266-[ChipID] + ArduinoOTA.setHostname(ota_hostname); - ArduinoOTA.onStart([]() { - trc(F("Start")); - }); - ArduinoOTA.onEnd([]() { - trc(F("\nEnd")); - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - Serial.printf("Progress: %u%%\r", (progress / (total / 100))); - }); - ArduinoOTA.onError([](ota_error_t error) { - Serial.printf("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) trc(F("Auth Failed")); - else if (error == OTA_BEGIN_ERROR) trc(F("Begin Failed")); - else if (error == OTA_CONNECT_ERROR) trc(F("Connect Failed")); - else if (error == OTA_RECEIVE_ERROR) trc(F("Receive Failed")); - else if (error == OTA_END_ERROR) trc(F("End Failed")); - }); - ArduinoOTA.begin(); + // No authentication by default + ArduinoOTA.setPassword(ota_password); + + ArduinoOTA.onStart([]() { + trc(F("Start")); + }); + ArduinoOTA.onEnd([]() { + trc(F("\nEnd")); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) + trc(F("Auth Failed")); + else if (error == OTA_BEGIN_ERROR) + trc(F("Begin Failed")); + else if (error == OTA_CONNECT_ERROR) + trc(F("Connect Failed")); + else if (error == OTA_RECEIVE_ERROR) + trc(F("Receive Failed")); + else if (error == OTA_END_ERROR) + trc(F("End Failed")); + }); + ArduinoOTA.begin(); #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(); + //Launch serial for debugging purposes + Serial.begin(SERIAL_BAUD); + //Begining ethernet connection in case of Arduino + W5100 + setup_ethernet(); #endif //setup LED status @@ -587,122 +658,128 @@ void setup() digitalWrite(led_info, LOW); #if defined(MDNS_SD) && defined(ESP8266) - trc(F("Connecting to MQTT by mDNS without mqtt hostname")); - connectMQTTmdns(); + trc(F("Connecting to MQTT by mDNS without mqtt hostname")); + connectMQTTmdns(); #else - long port; - port = strtol(mqtt_port,NULL,10); - trc(port); - #ifdef mqtt_server_name // if name is defined we define the mqtt server by its name - trc(F("Connecting to MQTT with mqtt hostname")); - IPAddress mqtt_server_ip; - WiFi.hostByName(mqtt_server_name, mqtt_server_ip); - client.setServer(mqtt_server_ip, port); - trc(mqtt_server_ip.toString()); - #else // if not by its IP adress - trc(F("Connecting to MQTT by IP adress")); - client.setServer(mqtt_server, port); - trc(mqtt_server); - #endif + long port; + port = strtol(mqtt_port, NULL, 10); + trc(port); + #ifdef mqtt_server_name // if name is defined we define the mqtt server by its name + trc(F("Connecting to MQTT with mqtt hostname")); + IPAddress mqtt_server_ip; + WiFi.hostByName(mqtt_server_name, mqtt_server_ip); + client.setServer(mqtt_server_ip, port); + trc(mqtt_server_ip.toString()); + #else // if not by its IP adress + trc(F("Connecting to MQTT by IP adress")); + client.setServer(mqtt_server, port); + trc(mqtt_server); + #endif #endif setup_parameters(); client.setCallback(callback); - + delay(1500); lastMQTTReconnectAttempt = 0; lastNTWKReconnectAttempt = 0; #ifdef ZsensorBME280 - setupZsensorBME280(); + setupZsensorBME280(); #endif #ifdef ZsensorBH1750 - setupZsensorBH1750(); + setupZsensorBH1750(); #endif #ifdef ZsensorTSL2561 - setupZsensorTSL2561(); + setupZsensorTSL2561(); #endif #ifdef Zgateway2G - setup2G(); + setup2G(); #endif #ifdef ZgatewayIR - setupIR(); + setupIR(); #endif #ifdef ZgatewayLORA - setupLORA(); + setupLORA(); #endif #ifdef ZgatewayRF - setupRF(); - #endif - #ifdef ZgatewayRF315 - setupRF315(); + setupRF(); #endif #ifdef ZgatewayRF2 - setupRF2(); + setupRF2(); #endif #ifdef ZgatewayPilight - setupPilight(); + setupPilight(); #endif #ifdef ZgatewaySRFB - setupSRFB(); + setupSRFB(); #endif #ifdef ZgatewayBT - setupBT(); + setupBT(); #endif #ifdef ZgatewayRFM69 - setupRFM69(); + setupRFM69(); #endif #ifdef ZsensorINA226 - setupINA226(); + setupINA226(); #endif #ifdef ZsensorHCSR501 - setupHCSR501(); + setupHCSR501(); #endif #ifdef ZsensorHCSR04 - setupHCSR04(); + setupHCSR04(); #endif #ifdef ZsensorGPIOInput - setupGPIOInput(); + setupGPIOInput(); #endif #ifdef ZsensorGPIOKeyCode - setupGPIOKeyCode(); + setupGPIOKeyCode(); #endif #ifdef ZactuatorFASTLED - setupFASTLED(); + setupFASTLED(); #endif - trc(F("MQTT_MAX_PACKET_SIZE")); trc(MQTT_MAX_PACKET_SIZE); #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) - if(MQTT_MAX_PACKET_SIZE == 128) trc(F("WRONG PUBSUBCLIENT LIBRARY USED PLEASE INSTALL THE ONE FROM RELEASE PAGE")); + if (MQTT_MAX_PACKET_SIZE == 128) + trc(F("WRONG PUBSUBCLIENT LIBRARY USED PLEASE INSTALL THE ONE FROM RELEASE PAGE")); #endif trc(F("Setup OpenMQTTGateway end")); } - #if defined(ESPWifiManualSetup) -void setup_wifi() { +void setup_wifi() +{ delay(10); int failureAttempt = 0; //DIRTY FIX ESP32 waiting for https://github.com/espressif/arduino-esp32/issues/653 WiFi.mode(WIFI_STA); // We start by connecting to a WiFi network trc(F("Connecting to ")); trc(wifi_ssid); + #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)) + { + trc("STA Failed to configure"); + } WiFi.begin(wifi_ssid, wifi_password); - //WiFi.config(ip_adress,gateway_adress,subnet_adress,dns_adress); //Uncomment this line if you want to use advanced network config - - while (WiFi.status() != WL_CONNECTED) { + #else + WiFi.begin(wifi_ssid, wifi_password); + #endif + + while (WiFi.status() != WL_CONNECTED) + { delay(500); trc(F(".")); failureAttempt++; //DIRTY FIX ESP32 - if (failureAttempt > 30) setup_wifi(); //DIRTY FIX ESP32 + if (failureAttempt > 30) + setup_wifi(); //DIRTY FIX ESP32 } trc(F("WiFi ok with manual config credentials")); } @@ -716,21 +793,26 @@ bool shouldSaveConfig = true; //do we have been connected once to mqtt //callback notifying us of the need to save config -void saveConfigCallback () { +void saveConfigCallback() +{ trc(F("Should save config")); 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) + { trc(F("Trigger button Pressed")); // 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) + { trc(F("Button Held")); trc(F("Erasing ESP Config, restarting")); setup_wifimanager(true); @@ -738,165 +820,189 @@ void checkButton(){ // code from tzapu/wifimanager examples } } } -void eraseAndRestart(){ - #if defined(ESP8266) - WiFi.disconnect(true); + +void eraseAndRestart() +{ + #if defined(ESP8266) + WiFi.disconnect(true); #else - WiFi.disconnect(true,true); + WiFi.disconnect(true, true); #endif + trc("Formatting requested, result:"); trc(SPIFFS.format()); - #if defined(ESP8266) - ESP.reset(); + + #if defined(ESP8266) + ESP.reset(); #else - ESP.restart(); + ESP.restart(); #endif } -void setup_wifimanager(bool reset_settings){ - - pinMode(TRIGGER_PIN, INPUT_PULLUP); +void setup_wifimanager(bool reset_settings) +{ - if(reset_settings) eraseAndRestart(); + pinMode(TRIGGER_PIN, INPUT_PULLUP); - WiFi.mode(WIFI_STA); + if (reset_settings) + eraseAndRestart(); - //read configuration from FS json - trc(F("mounting FS...")); - - if (SPIFFS.begin()) { - trc(F("mounted file system")); - }else{ - trc(F("failed to mount FS -> formating")); - SPIFFS.format(); - if(SPIFFS.begin()) - trc(F("mounted file system after formating")); - } - if (SPIFFS.exists("/config.json")) { - //file exists, reading and loading - trc(F("reading config file")); - File configFile = SPIFFS.open("/config.json", "r"); - if (configFile) { - trc(F("opened config file")); - 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()); - json.printTo(Serial); - if (json.success()) { - trc(F("\nparsed json")); - if (json.containsKey("mqtt_server")) strcpy(mqtt_server, json["mqtt_server"]); - if (json.containsKey("mqtt_port")) strcpy(mqtt_port, json["mqtt_port"]); - if (json.containsKey("mqtt_user")) strcpy(mqtt_user, json["mqtt_user"]); - if (json.containsKey("mqtt_pass")) strcpy(mqtt_pass, json["mqtt_pass"]); - if (json.containsKey("mqtt_topic")) strcpy(mqtt_topic, json["mqtt_topic"]); - if (json.containsKey("gateway_name")) strcpy(gateway_name, json["gateway_name"]); - } else { - trc(F("failed to load json config")); - } - } - } - - // The extra parameters to be configured (can be either global or just in the setup) - // After connecting, parameter.getValue() will get you the configured value - // id/name placeholder/prompt default length - WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, parameters_size); - WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, parameters_size); - WiFiManagerParameter custom_mqtt_pass("pass", "mqtt pass", mqtt_pass, parameters_size); - WiFiManagerParameter custom_mqtt_topic("topic", "mqtt base topic", mqtt_topic, mqtt_topic_max_size); - WiFiManagerParameter custom_gateway_name("name", "gateway name", gateway_name, parameters_size * 2); + WiFi.mode(WIFI_STA); - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around + //read configuration from FS json + trc(F("mounting FS...")); - wifiManager.setConnectTimeout(WifiManager_TimeOut); - //Set timeout before going to portal - wifiManager.setConfigPortalTimeout(WifiManager_ConfigPortalTimeOut); - - //set config save notify callback - wifiManager.setSaveConfigCallback(saveConfigCallback); - - //set static ip - //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - //add all your parameters here - wifiManager.addParameter(&custom_mqtt_server); - wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_mqtt_user); - wifiManager.addParameter(&custom_mqtt_pass); - wifiManager.addParameter(&custom_gateway_name); - wifiManager.addParameter(&custom_mqtt_topic); - - //set minimum quality of signal so it ignores AP's under that quality - wifiManager.setMinimumSignalQuality(MinimumWifiSignalQuality); - - //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)) { - trc(F("failed to connect and hit timeout")); - delay(3000); - //reset and try again, or maybe put it to deep sleep - #if defined(ESP8266) - ESP.reset(); - #else - ESP.restart(); - #endif - delay(5000); - } - - //if you get here you have connected to the WiFi - trc(F("connected...yeey :)")); - - //read updated parameters - strcpy(mqtt_server, custom_mqtt_server.getValue()); - strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(mqtt_user, custom_mqtt_user.getValue()); - strcpy(mqtt_pass, custom_mqtt_pass.getValue()); - strcpy(mqtt_topic, custom_mqtt_topic.getValue()); - strcpy(gateway_name, custom_gateway_name.getValue()); - - //save the custom parameters to FS - if (shouldSaveConfig) { - trc(F("saving config")); - DynamicJsonBuffer jsonBuffer; - JsonObject& json = jsonBuffer.createObject(); - json["mqtt_server"] = mqtt_server; - json["mqtt_port"] = mqtt_port; - json["mqtt_user"] = mqtt_user; - json["mqtt_pass"] = mqtt_pass; - json["mqtt_topic"] = mqtt_topic; - json["gateway_name"] = gateway_name; - - File configFile = SPIFFS.open("/config.json", "w"); - if (!configFile) { - trc(F("failed to open config file for writing")); - } - - json.printTo(Serial); - json.printTo(configFile); - configFile.close(); - //end save - } -} - -#else // Arduino case - -void setup_ethernet() { - if (gateway[0] != 0 || Dns[0]!=0) + if (SPIFFS.begin()) { - trc(F("Adv eth cfg")); - Ethernet.begin(mac, ip, Dns, gateway, subnet); - }else{ - trc(F("Spl eth cfg")); - Ethernet.begin(mac, ip); + trc(F("mounted file system")); } - if (Ethernet.hardwareStatus() == EthernetNoHardware) { + else + { + trc(F("failed to mount FS -> formating")); + SPIFFS.format(); + if (SPIFFS.begin()) + trc(F("mounted file system after formating")); + } + if (SPIFFS.exists("/config.json")) + { + //file exists, reading and loading + trc(F("reading config file")); + File configFile = SPIFFS.open("/config.json", "r"); + if (configFile) + { + trc(F("opened config file")); + 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()); + json.printTo(Serial); + if (json.success()) + { + trc(F("\nparsed json")); + if (json.containsKey("mqtt_server")) + strcpy(mqtt_server, json["mqtt_server"]); + if (json.containsKey("mqtt_port")) + strcpy(mqtt_port, json["mqtt_port"]); + if (json.containsKey("mqtt_user")) + strcpy(mqtt_user, json["mqtt_user"]); + if (json.containsKey("mqtt_pass")) + strcpy(mqtt_pass, json["mqtt_pass"]); + if (json.containsKey("mqtt_topic")) + strcpy(mqtt_topic, json["mqtt_topic"]); + if (json.containsKey("gateway_name")) + strcpy(gateway_name, json["gateway_name"]); + } + else + { + trc(F("failed to load json config")); + } + } + } + + // The extra parameters to be configured (can be either global or just in the setup) + // After connecting, parameter.getValue() will get you the configured value + // id/name placeholder/prompt default length + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, parameters_size); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); + WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, parameters_size); + WiFiManagerParameter custom_mqtt_pass("pass", "mqtt pass", mqtt_pass, parameters_size); + WiFiManagerParameter custom_mqtt_topic("topic", "mqtt base topic", mqtt_topic, mqtt_topic_max_size); + WiFiManagerParameter custom_gateway_name("name", "gateway name", gateway_name, parameters_size * 2); + + //WiFiManager + //Local intialization. Once its business is done, there is no need to keep it around + + wifiManager.setConnectTimeout(WifiManager_TimeOut); + //Set timeout before going to portal + wifiManager.setConfigPortalTimeout(WifiManager_ConfigPortalTimeOut); + + //set config save notify callback + wifiManager.setSaveConfigCallback(saveConfigCallback); + + //set static ip + //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + + //add all your parameters here + wifiManager.addParameter(&custom_mqtt_server); + wifiManager.addParameter(&custom_mqtt_port); + wifiManager.addParameter(&custom_mqtt_user); + wifiManager.addParameter(&custom_mqtt_pass); + wifiManager.addParameter(&custom_gateway_name); + wifiManager.addParameter(&custom_mqtt_topic); + + //set minimum quality of signal so it ignores AP's under that quality + wifiManager.setMinimumSignalQuality(MinimumWifiSignalQuality); + + //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)) + { + trc(F("failed to connect and hit timeout")); + delay(3000); +//reset and try again, or maybe put it to deep sleep + #if defined(ESP8266) + ESP.reset(); + #else + ESP.restart(); + #endif + delay(5000); + } + + //if you get here you have connected to the WiFi + trc(F("connected...yeey :)")); + + //read updated parameters + strcpy(mqtt_server, custom_mqtt_server.getValue()); + strcpy(mqtt_port, custom_mqtt_port.getValue()); + strcpy(mqtt_user, custom_mqtt_user.getValue()); + strcpy(mqtt_pass, custom_mqtt_pass.getValue()); + strcpy(mqtt_topic, custom_mqtt_topic.getValue()); + strcpy(gateway_name, custom_gateway_name.getValue()); + + //save the custom parameters to FS + if (shouldSaveConfig) + { + trc(F("saving config")); + DynamicJsonBuffer jsonBuffer; + JsonObject &json = jsonBuffer.createObject(); + json["mqtt_server"] = mqtt_server; + json["mqtt_port"] = mqtt_port; + json["mqtt_user"] = mqtt_user; + json["mqtt_pass"] = mqtt_pass; + json["mqtt_topic"] = mqtt_topic; + json["gateway_name"] = gateway_name; + + File configFile = SPIFFS.open("/config.json", "w"); + if (!configFile) + { + trc(F("failed to open config file for writing")); + } + + json.printTo(Serial); + json.printTo(configFile); + configFile.close(); + //end save + } +} +#else // Arduino case +void setup_ethernet() +{ + #ifdef NetworkAdvancedSetup + trc(F("Adv eth cfg")); + Ethernet.begin(mac, ip, Dns, gateway, subnet); + #else + trc(F("Spl eth cfg")); + Ethernet.begin(mac, ip); + #endif + if (Ethernet.hardwareStatus() == EthernetNoHardware) + { trc("Ethernet shield was not found."); - }else{ + } + else + { trc(F("ip: ")); Serial.println(Ethernet.localIP()); trc(F("Eth ok")); @@ -905,35 +1011,45 @@ void setup_ethernet() { #endif #if defined(MDNS_SD) && defined(ESP8266) - void connectMQTTmdns(){ - if (!MDNS.begin("ESP_MQTT")) { - trc(F("Error setting up MDNS responder!")); - while(1){ - delay(1000); - } - } - trc(F("Browsing for service MQTT ")); - int n = MDNS.queryService("mqtt", "tcp"); - if (n == 0) { - trc(F("no services found")); - }else { - trc(n); - trc(F(" service(s) found")); - for (int i=0; i < n; ++i) { - // Print details for each service found - trc(i + 1); - trc(MDNS.hostname(i)); - trc(MDNS.IP(i).toString()); - trc(MDNS.port(i)); - } - if (n==1) { - trc(F("One MQTT server found setting parameters")); - client.setServer(MDNS.IP(0), int(MDNS.port(0))); - }else{ - trc(F("Several MQTT servers found, please deactivate mDNS and set your default server")); - } +void connectMQTTmdns() +{ + if (!MDNS.begin("ESP_MQTT")) + { + trc(F("Error setting up MDNS responder!")); + while (1) + { + delay(1000); } } + trc(F("Browsing for service MQTT ")); + int n = MDNS.queryService("mqtt", "tcp"); + if (n == 0) + { + trc(F("no services found")); + } + else + { + trc(n); + trc(F(" service(s) found")); + for (int i = 0; i < n; ++i) + { + // Print details for each service found + trc(i + 1); + trc(MDNS.hostname(i)); + trc(MDNS.IP(i).toString()); + trc(MDNS.port(i)); + } + if (n == 1) + { + trc(F("One MQTT server found setting parameters")); + client.setServer(MDNS.IP(0), int(MDNS.port(0))); + } + else + { + trc(F("Several MQTT servers found, please deactivate mDNS and set your default server")); + } + } +} #endif void loop() @@ -951,254 +1067,262 @@ void loop() unsigned long now = millis(); #if defined(ESP8266) || defined(ESP32) - if (WiFi.status() == WL_CONNECTED){ + 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 + if ((Ethernet.hardwareStatus() != EthernetW5100 && Ethernet.linkStatus() == LinkON) || (Ethernet.hardwareStatus() == EthernetW5100)) + { //we are able to detect disconnection only on w5200 and w5500 #endif lastNTWKReconnectAttempt = 0; - if (client.connected()) { - // MQTT loop - connectedOnce = true; - lastMQTTReconnectAttempt = 0; - client.loop(); + if (client.connected()) + { + // MQTT loop + connectedOnce = true; + lastMQTTReconnectAttempt = 0; + client.loop(); - #if defined(ESP8266) || defined(ESP32) - ArduinoOTA.handle(); - #endif + #if defined(ESP8266) || defined(ESP32) + ArduinoOTA.handle(); + #endif - #ifdef ZsensorBME280 - MeasureTempHumAndPressure(); //Addon to measure Temperature, Humidity, Pressure and Altitude with a Bosch BME280 + #ifdef ZsensorBME280 + MeasureTempHumAndPressure(); //Addon to measure Temperature, Humidity, Pressure and Altitude with a Bosch BME280 + #endif + #ifdef ZsensorHCSR04 + MeasureDistance(); //Addon to measure distance with a HC-SR04 + #endif + #ifdef ZsensorBH1750 + MeasureLightIntensity(); //Addon to measure Light Intensity with a BH1750 + #endif + #ifdef ZsensorTSL2561 + MeasureLightIntensityTSL2561(); + #endif + #ifdef ZsensorDHT + MeasureTempAndHum(); //Addon to measure the temperature with a DHT + #endif + #ifdef ZsensorINA226 + MeasureINA226(); + #endif + #ifdef ZsensorHCSR501 + MeasureHCSR501(); + #endif + #ifdef ZsensorGPIOInput + MeasureGPIOInput(); + #endif + #ifdef ZsensorGPIOKeyCode + MeasureGPIOKeyCode(); + #endif + #ifdef ZsensorADC + MeasureADC(); //Addon to measure the analog value of analog pin + #endif + #ifdef ZgatewayLORA + LORAtoMQTT(); + #endif + #ifdef ZgatewayRF + RFtoMQTT(); + #endif + #ifdef ZgatewayRF2 + RF2toMQTT(); + #endif + #ifdef ZgatewayPilight + PilighttoMQTT(); + #endif + #ifdef ZgatewayBT + #ifndef ESP32 + if (BTtoMQTT()) + trc(F("BTtoMQTT OK")); #endif - #ifdef ZsensorHCSR04 - MeasureDistance(); //Addon to measure distance with a HC-SR04 - #endif - #ifdef ZsensorBH1750 - MeasureLightIntensity(); //Addon to measure Light Intensity with a BH1750 - #endif - #ifdef ZsensorTSL2561 - MeasureLightIntensityTSL2561(); - #endif - #ifdef ZsensorDHT - MeasureTempAndHum(); //Addon to measure the temperature with a DHT - #endif - #ifdef ZsensorINA226 - MeasureINA226(); - #endif - #ifdef ZsensorHCSR501 - MeasureHCSR501(); - #endif - #ifdef ZsensorGPIOInput - MeasureGPIOInput(); - #endif - #ifdef ZsensorGPIOKeyCode - MeasureGPIOKeyCode(); - #endif - #ifdef ZsensorADC - MeasureADC(); //Addon to measure the analog value of analog pin - #endif - #ifdef ZgatewayLORA - LORAtoMQTT(); - #endif - #ifdef ZgatewayRF - RFtoMQTT(); - #endif - #ifdef ZgatewayRF315 - RF315toMQTT(); - #endif - #ifdef ZgatewayRF2 - RF2toMQTT(); - #endif - #ifdef ZgatewayPilight - PilighttoMQTT(); - #endif - #ifdef ZgatewayBT - #ifndef ESP32 - if(BTtoMQTT()) - trc(F("BTtoMQTT OK")); - #endif - #endif - #ifdef ZgatewaySRFB - SRFBtoMQTT(); - #endif - #ifdef ZgatewayIR - IRtoMQTT(); - #endif - #ifdef Zgateway2G - if(_2GtoMQTT()){ - trc(F("2GtoMQTT OK")); - } - #endif - #ifdef ZgatewayRFM69 - if(RFM69toMQTT()) - trc(F("RFM69toMQTT OK")); - #endif - #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) - stateMeasures(); - #endif - #ifdef ZactuatorFASTLED - FASTLEDLoop(); - #endif - }else{ - if (now - lastMQTTReconnectAttempt > 5000) { - lastMQTTReconnectAttempt = now; - reconnect(); - } + #endif + #ifdef ZgatewaySRFB + SRFBtoMQTT(); + #endif + #ifdef ZgatewayIR + IRtoMQTT(); + #endif + #ifdef Zgateway2G + if (_2GtoMQTT()) + trc(F("2GtoMQTT OK")); + #endif + #ifdef ZgatewayRFM69 + if (RFM69toMQTT()) + trc(F("RFM69toMQTT OK")); + #endif + #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) + stateMeasures(); + #endif + #ifdef ZactuatorFASTLED + FASTLEDLoop(); + #endif + } + else + { + if (now - lastMQTTReconnectAttempt > 5000) + { + lastMQTTReconnectAttempt = now; + reconnect(); } - } else { // disconnected from network - if ( now - lastNTWKReconnectAttempt > 10000) { - lastNTWKReconnectAttempt = now; - #if defined(ESP8266) || defined(ESP32) - trc("wifi disconnected"); - delay(10000);// add a delay to avoid ESP32 crash and reset - #if defined(ESPWifiManualSetup) - trc(F("restarting ESP")); - #ifdef ESP32 - ESP.restart(); - #endif - #ifdef ESP8266 - ESP.reset(); - #endif - #else - if (!connectedOnce) { - trc(F("reseting wifi manager")); - setup_wifimanager(true); // if we didn't connected once to mqtt we reset and start in AP mode again to have a chance to change the parameters - } + } + } + else + { // disconnected from network + if (now - lastNTWKReconnectAttempt > 10000) + { + lastNTWKReconnectAttempt = now; + #if defined(ESP8266) || defined(ESP32) + trc("wifi disconnected"); + delay(10000); // add a delay to avoid ESP32 crash and reset + #if defined(ESPWifiManualSetup) + trc(F("restarting ESP")); + #ifdef ESP32 + ESP.restart(); + #endif + #ifdef ESP8266 + ESP.reset(); #endif #else - trc("eth disconnected"); - #endif + if (!connectedOnce) + { + trc(F("reseting wifi manager")); + setup_wifimanager(true); // if we didn't connected once to mqtt we reset and start in AP mode again to have a chance to change the parameters } - } + #endif + #else + trc("eth disconnected"); + #endif + } + } } #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) -void stateMeasures(){ - unsigned long now = millis(); - if (now > (timer_sys_measures + TimeBetweenReadingSYS)) {//retriving value of memory ram every TimeBetweenReadingSYS - timer_sys_measures = millis(); - StaticJsonBuffer jsonBuffer; - JsonObject& SYSdata = jsonBuffer.createObject(); - trc(F("Uptime (s)")); - unsigned long uptime = millis()/1000; - trc(uptime); - SYSdata["uptime"] = 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(); - #else - SYSdata["ip"] = ip2CharArray(Ethernet.localIP()); - #endif - String modules = ""; - #ifdef ZgatewayRF - modules = modules + ZgatewayRF; - #endif - #ifdef ZgatewayRF315 - modules = modules + ZgatewayRF315; - #endif - #ifdef ZsensorBME280 - modules = modules + ZsensorBME280; - #endif - #ifdef ZsensorHCSR04 - modules = modules + ZsensorHCSR04; - #endif - #ifdef ZsensorBH1750 - modules = modules + ZsensorBH1750; - #endif - #ifdef ZsensorTSL2561 - modules = modules + ZsensorTSL2561; - #endif - #ifdef ZsensorDHT - modules = modules + ZsensorDHT; - #endif - #ifdef ZactuatorONOFF - modules = modules + ZactuatorONOFF; - #endif - #ifdef Zgateway2G - modules = modules + Zgateway2G; - #endif - #ifdef ZgatewayIR - modules = modules + ZgatewayIR; - #endif - #ifdef ZgatewayLORA - modules = modules + ZgatewayLORA; - #endif - #ifdef ZgatewayRF2 - modules = modules + ZgatewayRF2; - #endif - #ifdef ZgatewayPilight - modules = modules + ZgatewayPilight; - #endif - #ifdef ZgatewaySRFB - modules = modules + ZgatewaySRFB; - #endif - #ifdef ZgatewayBT - modules = modules + ZgatewayBT; - #endif - #ifdef ZgatewayRFM69 - modules = modules + ZgatewayRFM69; - #endif - #ifdef ZsensorINA226 - modules = modules + ZsensorINA226; - #endif - #ifdef ZsensorHCSR501 - modules = modules + ZsensorHCSR501; - #endif - #ifdef ZsensorGPIOInput - modules = modules + ZsensorGPIOInput; - #endif - #ifdef ZsensorGPIOKeyCode - modules = modules + ZsensorGPIOKeyCode; - #endif - #ifdef ZsensorGPIOKeyCode - modules = modules + ZsensorGPIOKeyCode; - #endif - #ifdef ZmqttDiscovery - modules = modules + ZmqttDiscovery; - pubMqttDiscovery(); - #endif - #ifdef ZactuatorFASTLED - modules = modules + ZactuatorFASTLED; - #endif +void stateMeasures() +{ + unsigned long now = millis(); + if (now > (timer_sys_measures + TimeBetweenReadingSYS)) + { //retriving value of memory ram every TimeBetweenReadingSYS + timer_sys_measures = millis(); + StaticJsonBuffer jsonBuffer; + JsonObject &SYSdata = jsonBuffer.createObject(); + trc(F("Uptime (s)")); + unsigned long uptime = millis() / 1000; + trc(uptime); + SYSdata["uptime"] = 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(); + #else + SYSdata["ip"] = ip2CharArray(Ethernet.localIP()); + #endif + String modules = ""; + #ifdef ZgatewayRF + modules = modules + ZgatewayRF; + #endif + #ifdef ZsensorBME280 + modules = modules + ZsensorBME280; + #endif + #ifdef ZsensorHCSR04 + modules = modules + ZsensorHCSR04; + #endif + #ifdef ZsensorBH1750 + modules = modules + ZsensorBH1750; + #endif + #ifdef ZsensorTSL2561 + modules = modules + ZsensorTSL2561; + #endif + #ifdef ZsensorDHT + modules = modules + ZsensorDHT; + #endif + #ifdef ZactuatorONOFF + modules = modules + ZactuatorONOFF; + #endif + #ifdef Zgateway2G + modules = modules + Zgateway2G; + #endif + #ifdef ZgatewayIR + modules = modules + ZgatewayIR; + #endif + #ifdef ZgatewayLORA + modules = modules + ZgatewayLORA; + #endif + #ifdef ZgatewayRF2 + modules = modules + ZgatewayRF2; + #endif + #ifdef ZgatewayPilight + modules = modules + ZgatewayPilight; + #endif + #ifdef ZgatewaySRFB + modules = modules + ZgatewaySRFB; + #endif + #ifdef ZgatewayBT + modules = modules + ZgatewayBT; + #endif + #ifdef ZgatewayRFM69 + modules = modules + ZgatewayRFM69; + #endif + #ifdef ZsensorINA226 + modules = modules + ZsensorINA226; + #endif + #ifdef ZsensorHCSR501 + modules = modules + ZsensorHCSR501; + #endif + #ifdef ZsensorGPIOInput + modules = modules + ZsensorGPIOInput; + #endif + #ifdef ZsensorGPIOKeyCode + modules = modules + ZsensorGPIOKeyCode; + #endif + #ifdef ZsensorGPIOKeyCode + modules = modules + ZsensorGPIOKeyCode; + #endif + #ifdef ZmqttDiscovery + modules = modules + ZmqttDiscovery; + pubMqttDiscovery(); + #endif + #ifdef ZactuatorFASTLED + modules = modules + ZactuatorFASTLED; + #endif - SYSdata["modules"] = modules; - trc(SYSdata); - pub(subjectSYStoMQTT,SYSdata); - } + SYSdata["modules"] = modules; + trc(SYSdata); + pub(subjectSYStoMQTT, SYSdata); + } } #endif -void storeValue(unsigned long MQTTvalue){ - unsigned long now = millis(); - // find oldest value of the buffer - int o = getMin(); - trc(F("Min ind: ")); - trc(o); - // replace it by the new one - ReceivedSignal[o][0] = MQTTvalue; - ReceivedSignal[o][1] = now; - trc(F("store code :")); - trc(String(ReceivedSignal[o][0])+"/"+String(ReceivedSignal[o][1])); - trc(F("Col: val/timestamp")); - for (int i = 0; i < array_size; i++) - { - trc(String(i) + ":" + String(ReceivedSignal[i][0])+"/"+String(ReceivedSignal[i][1])); - } -} - -int getMin(){ - unsigned int minimum = ReceivedSignal[0][1]; - int minindex=0; +void storeValue(unsigned long MQTTvalue) +{ + unsigned long now = millis(); + // find oldest value of the buffer + int o = getMin(); + trc(F("Min ind: ")); + trc(o); + // replace it by the new one + ReceivedSignal[o][0] = MQTTvalue; + ReceivedSignal[o][1] = now; + trc(F("store code :")); + trc(String(ReceivedSignal[o][0]) + "/" + String(ReceivedSignal[o][1])); + trc(F("Col: val/timestamp")); for (int i = 0; i < array_size; i++) { - if (ReceivedSignal[i][1] < minimum) { + trc(String(i) + ":" + String(ReceivedSignal[i][0]) + "/" + String(ReceivedSignal[i][1])); + } +} + +int getMin() +{ + unsigned int minimum = ReceivedSignal[0][1]; + int minindex = 0; + for (int i = 0; i < array_size; i++) + { + if (ReceivedSignal[i][1] < minimum) + { minimum = ReceivedSignal[i][1]; minindex = i; } @@ -1206,13 +1330,17 @@ int getMin(){ return minindex; } -bool isAduplicate(unsigned long value){ +bool isAduplicate(unsigned long value) +{ trc(F("isAdupl?")); // 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){ - unsigned long now = millis(); - if (now - ReceivedSignal[i][1] < time_avoid_duplicate){ // change + 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 trc(F("no pub. dupl")); return true; } @@ -1221,133 +1349,141 @@ 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 { trc(F("Store str")); unsigned long data = 0; #ifdef jsonPublishing - if (jsondata.success()) data = jsondata["value"]; + if (jsondata.success()) + data = jsondata["value"]; #endif #ifdef simplePublishing - data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 + data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 #endif - - if (data != 0) { + + if (data != 0) + { storeValue(data); trc(F("JSON str")); } } - if (jsondata.success()) { // json object ok -> json decoding - #ifdef ZgatewayPilight // ZgatewayPilight is only defined with json publishing - MQTTtoPilight(topicOri, jsondata); - #endif - #ifdef jsonReceiving - #ifdef ZgatewayLORA + if (jsondata.success()) + { // json object ok -> json decoding + #ifdef ZgatewayPilight // ZgatewayPilight is only defined with json publishing + MQTTtoPilight(topicOri, jsondata); + #endif + #ifdef jsonReceiving + #ifdef ZgatewayLORA MQTTtoLORA(topicOri, jsondata); - #endif - #ifdef ZgatewayRF + #endif + #ifdef ZgatewayRF MQTTtoRF(topicOri, jsondata); - #endif - #ifdef ZgatewayRF315 - MQTTtoRF315(topicOri, jsondata); - #endif - #ifdef ZgatewayRF2 + #endif + #ifdef ZgatewayRF2 MQTTtoRF2(topicOri, jsondata); - #endif - #ifdef Zgateway2G + #endif + #ifdef Zgateway2G MQTTto2G(topicOri, jsondata); - #endif - #ifdef ZgatewaySRFB + #endif + #ifdef ZgatewaySRFB MQTTtoSRFB(topicOri, jsondata); - #endif - #ifdef ZgatewayIR + #endif + #ifdef ZgatewayIR MQTTtoIR(topicOri, jsondata); - #endif - #ifdef ZgatewayRFM69 + #endif + #ifdef ZgatewayRFM69 MQTTtoRFM69(topicOri, jsondata); - #endif - #ifdef ZgatewayBT + #endif + #ifdef ZgatewayBT MQTTtoBT(topicOri, jsondata); + #endif #endif - #endif #ifdef ZactuatorONOFF // outside the jsonpublishing macro due to the fact that we need to use simplepublishing with HA discovery - MQTTtoONOFF(topicOri, jsondata); + MQTTtoONOFF(topicOri, jsondata); #endif digitalWrite(led_send, HIGH); #ifdef ZactuatorFASTLED - MQTTtoFASTLEDJSON(topicOri, jsondata); + MQTTtoFASTLEDJSON(topicOri, jsondata); #endif MQTTtoSYS(topicOri, jsondata); - - } else { // not a json object --> simple decoding - #ifdef simpleReceiving + } + else + { // not a json object --> simple decoding + #ifdef simpleReceiving #ifdef ZgatewayLORA - MQTTtoLORA(topicOri, datacallback); + MQTTtoLORA(topicOri, datacallback); #endif #ifdef ZgatewayRF - MQTTtoRF(topicOri, datacallback); + MQTTtoRF(topicOri, datacallback); #endif #ifdef ZgatewayRF315 - MQTTtoRF315(topicOri, datacallback); + MQTTtoRF315(topicOri, datacallback); #endif #ifdef ZgatewayRF2 - MQTTtoRF2(topicOri, datacallback); + MQTTtoRF2(topicOri, datacallback); #endif #ifdef Zgateway2G - MQTTto2G(topicOri, datacallback); + MQTTto2G(topicOri, datacallback); #endif #ifdef ZgatewaySRFB - MQTTtoSRFB(topicOri, datacallback); + MQTTtoSRFB(topicOri, datacallback); #endif #ifdef ZgatewayIR - MQTTtoIR(topicOri, datacallback); + MQTTtoIR(topicOri, datacallback); #endif #ifdef ZgatewayRFM69 - MQTTtoRFM69(topicOri, datacallback); + MQTTtoRFM69(topicOri, datacallback); #endif - #endif - #ifdef ZactuatorONOFF + #endif + #ifdef ZactuatorONOFF MQTTtoONOFF(topicOri, datacallback); - #endif - digitalWrite(led_send, HIGH); - - #ifdef ZactuatorFASTLED + #endif + #ifdef ZactuatorFASTLED MQTTtoFASTLED(topicOri, datacallback); - #endif - + #endif + digitalWrite(led_send, HIGH); } -//YELLOW OFF -digitalWrite(led_send, HIGH); + //YELLOW OFF + 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)) + { trc(F("MQTTtoSYS json set")); #if defined(ESP8266) || defined(ESP32) - if (SYSdata.containsKey("cmd")){ - trc(F("Command")); - const char * cmd = SYSdata["cmd"]; - trc(cmd); - if (strstr(cmd,restartCmd) != NULL) {//restart - #if defined(ESP8266) - ESP.reset(); - #else - ESP.restart(); - #endif - }else if (strstr(cmd,eraseCmd) != NULL) {//erase and restart - setup_wifimanager(true); - }else{ - trc(F("wrong command")); - } + if (SYSdata.containsKey("cmd")) + { + trc(F("Command")); + const char *cmd = SYSdata["cmd"]; + trc(cmd); + if (strstr(cmd, restartCmd) != NULL) + { //restart + #if defined(ESP8266) + ESP.reset(); + #else + ESP.restart(); + #endif } + else if (strstr(cmd, eraseCmd) != NULL) + { //erase and restart + setup_wifimanager(true); + } + else + { + trc(F("wrong command")); + } + } #endif } }