Apply VSC auto format to the code and indent macros for readability

This commit is contained in:
1technophile committed 2019-12-14 17:14:36 +01:00
1 parent f7ec81ffaa
commit 7f9d8d18da
24 files changed
+1655 -835

No files matched your search

+2
View File
@@ -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 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 Fork the [development branch](https://github.com/1technophile/OpenMQTTGateway/tree/development), then clone the repo
Make your modification, Make your modification,
+1 -8
View File
@@ -24,12 +24,8 @@
#ifdef ZactuatorFASTLED #ifdef ZactuatorFASTLED
#ifdef ESP8266
#include <FastLED.h> #include <FastLED.h>
#else
#include <FastLED.h>
#endif
#include <ArduinoJson.h>
enum LEDState enum LEDState
{ {
OFF, OFF,
@@ -130,8 +126,6 @@ void MQTTtoFASTLEDJSON(char *topicOri, JsonObject& jsonData)
trc(topicOri); trc(topicOri);
//number = (long)strtol(&datacallback[1], NULL, 16); //number = (long)strtol(&datacallback[1], NULL, 16);
if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled)) if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled))
{ {
trc(F("JSON parsed")); trc(F("JSON parsed"));
@@ -151,7 +145,6 @@ void MQTTtoFASTLEDJSON(char *topicOri, JsonObject& jsonData)
blinkLED[ledNr] = blink; blinkLED[ledNr] = blink;
leds[ledNr] = number; leds[ledNr] = number;
} }
} }
} }
void MQTTtoFASTLED(char *topicOri, char *datacallback) void MQTTtoFASTLED(char *topicOri, char *datacallback)
+17 -10
View File
@@ -31,13 +31,15 @@
#ifdef ZactuatorONOFF #ifdef ZactuatorONOFF
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTtoONOFF(char * topicOri, JsonObject& ONOFFdata){ void MQTTtoONOFF(char *topicOri, JsonObject &ONOFFdata)
{
if (cmpToMainTopic(topicOri,subjectMQTTtoONOFF)){ if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF))
{
trc(F("MQTTtoONOFF json data analysis")); trc(F("MQTTtoONOFF json data analysis"));
int boolSWITCHTYPE = ONOFFdata["state"] | 99; int boolSWITCHTYPE = ONOFFdata["state"] | 99;
int pin = ONOFFdata["pin"] | ACTUATOR_ONOFF_PIN; int pin = ONOFFdata["pin"] | ACTUATOR_ONOFF_PIN;
if (boolSWITCHTYPE != 99) { if (boolSWITCHTYPE != 99)
{
trc(F("MQTTtoONOFF boolSWITCHTYPE ok")); trc(F("MQTTtoONOFF boolSWITCHTYPE ok"));
trc(boolSWITCHTYPE); trc(boolSWITCHTYPE);
trc(F("pin number")); trc(F("pin number"));
@@ -46,7 +48,9 @@ void MQTTtoONOFF(char * topicOri, JsonObject& ONOFFdata){
digitalWrite(pin, boolSWITCHTYPE); digitalWrite(pin, boolSWITCHTYPE);
// we acknowledge the sending by publishing the value to an acknowledgement topic // we acknowledge the sending by publishing the value to an acknowledgement topic
pub(subjectGTWONOFFtoMQTT, ONOFFdata); pub(subjectGTWONOFFtoMQTT, ONOFFdata);
}else{ }
else
{
trc(F("MQTTtoONOFF failed json read")); trc(F("MQTTtoONOFF failed json read"));
} }
} }
@@ -54,8 +58,10 @@ void MQTTtoONOFF(char * topicOri, JsonObject& ONOFFdata){
#endif #endif
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoONOFF(char * topicOri, char * datacallback) { void MQTTtoONOFF(char *topicOri, char *datacallback)
if ((cmpToMainTopic(topicOri,subjectMQTTtoONOFF)) ){ {
if ((cmpToMainTopic(topicOri, subjectMQTTtoONOFF)))
{
trc(F("MQTTtoONOFF")); trc(F("MQTTtoONOFF"));
int pin = strtol(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 int pin = strtol(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
@@ -64,8 +70,10 @@ void MQTTtoONOFF(char * topicOri, char * datacallback) {
pinMode(pin, OUTPUT); pinMode(pin, OUTPUT);
bool ON = false; bool ON = false;
if (strstr(topicOri,ONKey) != NULL) ON = true; if (strstr(topicOri, ONKey) != NULL)
if (strstr(topicOri,OFFKey) != NULL) ON = false; ON = true;
if (strstr(topicOri, OFFKey) != NULL)
ON = false;
digitalWrite(pin, ON); digitalWrite(pin, ON);
// we acknowledge the sending by publishing the value to an acknowledgement topic // we acknowledge the sending by publishing the value to an acknowledgement topic
@@ -75,5 +83,4 @@ void MQTTtoONOFF(char * topicOri, char * datacallback) {
} }
#endif #endif
#endif #endif
+47 -22
View File
@@ -39,7 +39,8 @@ int unreadSMSLocs[50] = {0};
int unreadSMSNum = 0; int unreadSMSNum = 0;
SMSmessage sms; SMSmessage sms;
void setup2G(){ void setup2G()
{
trc(F("_2G_TX_PIN ")); trc(F("_2G_TX_PIN "));
trc(_2G_TX_PIN); trc(_2G_TX_PIN);
@@ -49,7 +50,8 @@ void setup2G(){
trc(F("Zgateway2G setup done ")); trc(F("Zgateway2G setup done "));
} }
void setupGSM(bool deleteSMS){ void setupGSM(bool deleteSMS)
{
trc(F("Init 2G module: ")); trc(F("Init 2G module: "));
trc(_2G_PWR_PIN); trc(_2G_PWR_PIN);
delay(1000); delay(1000);
@@ -61,33 +63,41 @@ void setupGSM(bool deleteSMS){
signalStrengthAnalysis(); signalStrengthAnalysis();
delay(1000); delay(1000);
// deleting all sms // deleting all sms
if (deleteSMS){ if (deleteSMS)
if (A6l.deleteSMS(1,4) == A6_OK ) { {
if (A6l.deleteSMS(1, 4) == A6_OK)
{
trc(F("delete SMS OK")); trc(F("delete SMS OK"));
}else{ }
else
{
trc(F("delete SMS KO")); trc(F("delete SMS KO"));
} }
} }
} }
void signalStrengthAnalysis(){ void signalStrengthAnalysis()
{
int signalStrength = 0; int signalStrength = 0;
signalStrength = A6l.getSignalStrength(); signalStrength = A6l.getSignalStrength();
trc(F("Signal strength: ")); trc(F("Signal strength: "));
trc(signalStrength); trc(signalStrength);
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL ) { if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL)
{
trc(F("Signal too low restart the module")); 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 setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module
} }
} }
bool _2GtoMQTT(){ bool _2GtoMQTT()
{
// Get the memory locations of unread SMS messages. // Get the memory locations of unread SMS messages.
unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512); unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512);
trc(F("Creating SMS buffer")); trc(F("Creating SMS buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &SMSdata = jsonBuffer.createObject(); JsonObject &SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++) { for (int i = 0; i < unreadSMSNum; i++)
{
trc(F("New message at index: ")); trc(F("New message at index: "));
trc(unreadSMSNum); trc(unreadSMSNum);
sms = A6l.readSMS(unreadSMSLocs[i]); sms = A6l.readSMS(unreadSMSLocs[i]);
@@ -102,33 +112,41 @@ bool _2GtoMQTT(){
return false; return false;
} }
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTto2G(char * topicOri, char * datacallback) { void MQTTto2G(char *topicOri, char *datacallback)
{
String data = datacallback; String data = datacallback;
String topic = topicOri; String topic = topicOri;
if (cmpToMainTopic(topicOri,subjectMQTTto2G)) { if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
trc(F("MQTTto2G data analysis")); trc(F("MQTTto2G data analysis"));
// 2G DATA ANALYSIS // 2G DATA ANALYSIS
String phone_number = ""; String phone_number = "";
int pos0 = topic.lastIndexOf(_2GPhoneKey); int pos0 = topic.lastIndexOf(_2GPhoneKey);
if (pos0 != -1) { if (pos0 != -1)
{
pos0 = pos0 + strlen(_2GPhoneKey); pos0 = pos0 + strlen(_2GPhoneKey);
phone_number = topic.substring(pos0); phone_number = topic.substring(pos0);
trc(F("MQTTto2G phone ok")); trc(F("MQTTto2G phone ok"));
trc(phone_number); trc(phone_number);
trc(F("MQTTto2G sms")); trc(F("MQTTto2G sms"));
trc(data); trc(data);
if (A6l.sendSMS(phone_number,data) == A6_OK ) { if (A6l.sendSMS(phone_number, data) == A6_OK)
{
trc(F("SMS OK")); trc(F("SMS OK"));
// Acknowledgement to the GTW2G topic // 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 pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{ }
else
{
trc(F("SMS KO")); trc(F("SMS KO"));
// Acknowledgement to the GTW2G topic // 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 pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} }
}else{ }
else
{
trc(F("MQTTto2G Fail reading phone number")); trc(F("MQTTto2G Fail reading phone number"));
} }
} }
@@ -136,28 +154,35 @@ bool _2GtoMQTT(){
#endif #endif
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTto2G(char * topicOri, JsonObject& SMSdata) { void MQTTto2G(char *topicOri, JsonObject &SMSdata)
{
if (cmpToMainTopic(topicOri,subjectMQTTto2G)){ if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
const char *sms = SMSdata["message"]; const char *sms = SMSdata["message"];
const char *phone = SMSdata["phone"]; const char *phone = SMSdata["phone"];
trc(F("MQTTto2G json data analysis")); trc(F("MQTTto2G json data analysis"));
if (sms && phone) { if (sms && phone)
{
trc(F("MQTTto2G sms & phone ok")); trc(F("MQTTto2G sms & phone ok"));
trc(sms); trc(sms);
if (A6l.sendSMS(String(phone),String(sms)) == A6_OK ) { if (A6l.sendSMS(String(phone), String(sms)) == A6_OK)
{
trc(F("SMS OK")); trc(F("SMS OK"));
// Acknowledgement to the GTW2G topic // 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 pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{ }
else
{
trc(F("SMS KO")); 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 pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} }
}else{ }
else
{
trc(F("MQTTto2G failed json read")); trc(F("MQTTto2G failed json read"));
} }
} }
} }
#endif #endif
#endif #endif
+284 -140
View File
@@ -36,16 +36,20 @@ Thanks to wolass https://github.com/wolass for suggesting me HM 10 and dinosd ht
using namespace std; using namespace std;
vector<BLEdevice> devices; vector<BLEdevice> devices;
void setWorBMac(char * mac , bool isWhite){ void setWorBMac(char *mac, bool isWhite)
{
bool foundMac = false; bool foundMac = false;
for(vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p){ for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
if((strcmp(p->macAdr,mac) == 0)){ {
if ((strcmp(p->macAdr, mac) == 0))
{
p->isWhtL = isWhite; p->isWhtL = isWhite;
p->isBlkL = !isWhite; p->isBlkL = !isWhite;
foundMac = true; foundMac = true;
} }
} }
if (!foundMac) { if (!foundMac)
{
BLEdevice device; BLEdevice device;
strcpy(device.macAdr, mac); strcpy(device.macAdr, mac);
device.isDisc = false; device.isDisc = false;
@@ -55,42 +59,56 @@ void setWorBMac(char * mac , bool isWhite){
} }
} }
bool oneWhite(){ bool oneWhite()
for(vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p){ {
if(p->isWhtL) return true; for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
if (p->isWhtL)
return true;
} }
return false; return false;
} }
bool isWhite(char * mac){ bool isWhite(char *mac)
for(vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p){ {
if((strcmp(p->macAdr,mac) == 0)){ for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
if ((strcmp(p->macAdr, mac) == 0))
{
return p->isWhtL; return p->isWhtL;
} }
} }
return false; return false;
} }
bool isBlack(char * mac){ bool isBlack(char *mac)
for(vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p){ {
if((strcmp(p->macAdr,mac) == 0)){ for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
if ((strcmp(p->macAdr, mac) == 0))
{
return p->isBlkL; return p->isBlkL;
} }
} }
return false; return false;
} }
bool isDiscovered(char * mac){ bool isDiscovered(char *mac)
for(vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p){ {
if((strcmp(p->macAdr,mac) == 0)){ for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
if ((strcmp(p->macAdr, mac) == 0))
{
return p->isDisc; return p->isDisc;
} }
} }
return false; return false;
} }
void dumpDevices(){ void dumpDevices()
for(vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p){ {
for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
trc(p->macAdr); trc(p->macAdr);
trc(p->isDisc); trc(p->isDisc);
trc(p->isWhtL); trc(p->isWhtL);
@@ -105,7 +123,8 @@ void strupp(char* beg)
} }
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
void MiFloraDiscovery(char * mac){ void MiFloraDiscovery(char *mac)
{
#define MiFloraparametersCount 4 #define MiFloraparametersCount 4
trc(F("MiFloraDiscovery")); trc(F("MiFloraDiscovery"));
char *MiFlorasensor[MiFloraparametersCount][8] = { char *MiFlorasensor[MiFloraparametersCount][8] = {
@@ -116,7 +135,8 @@ void MiFloraDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<MiFloraparametersCount;i++){ for (int i = 0; i < MiFloraparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(MiFlorasensor[i][1]); trc(MiFlorasensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -135,7 +155,8 @@ void MiFloraDiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void VegTrugDiscovery(char * mac){ void VegTrugDiscovery(char *mac)
{
#define VegTrugparametersCount 4 #define VegTrugparametersCount 4
trc(F("VegTrugDiscovery")); trc(F("VegTrugDiscovery"));
char *VegTrugsensor[VegTrugparametersCount][8] = { char *VegTrugsensor[VegTrugparametersCount][8] = {
@@ -146,7 +167,8 @@ void VegTrugDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<VegTrugparametersCount;i++){ for (int i = 0; i < VegTrugparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(VegTrugsensor[i][1]); trc(VegTrugsensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -165,7 +187,8 @@ void VegTrugDiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void MiJiaDiscovery(char * mac){ void MiJiaDiscovery(char *mac)
{
#define MiJiaparametersCount 3 #define MiJiaparametersCount 3
trc(F("MiJiaDiscovery")); trc(F("MiJiaDiscovery"));
char *MiJiasensor[MiJiaparametersCount][8] = { char *MiJiasensor[MiJiaparametersCount][8] = {
@@ -175,7 +198,8 @@ void MiJiaDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<MiJiaparametersCount;i++){ for (int i = 0; i < MiJiaparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(MiJiasensor[i][1]); trc(MiJiasensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -194,7 +218,8 @@ void MiJiaDiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void LYWSD02Discovery(char * mac){ void LYWSD02Discovery(char *mac)
{
#define LYWSD02parametersCount 3 #define LYWSD02parametersCount 3
trc(F("LYWSD02Discovery")); trc(F("LYWSD02Discovery"));
char *LYWSD02sensor[LYWSD02parametersCount][8] = { char *LYWSD02sensor[LYWSD02parametersCount][8] = {
@@ -204,7 +229,8 @@ void LYWSD02Discovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<LYWSD02parametersCount;i++){ for (int i = 0; i < LYWSD02parametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(LYWSD02sensor[i][1]); trc(LYWSD02sensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -223,7 +249,8 @@ void LYWSD02Discovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void CLEARGRASSTRHDiscovery(char * mac){ void CLEARGRASSTRHDiscovery(char *mac)
{
#define CLEARGRASSTRHparametersCount 3 #define CLEARGRASSTRHparametersCount 3
trc(F("CLEARGRASSTRHDiscovery")); trc(F("CLEARGRASSTRHDiscovery"));
char *CLEARGRASSTRHsensor[CLEARGRASSTRHparametersCount][8] = { char *CLEARGRASSTRHsensor[CLEARGRASSTRHparametersCount][8] = {
@@ -233,7 +260,8 @@ void CLEARGRASSTRHDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<CLEARGRASSTRHparametersCount;i++){ for (int i = 0; i < CLEARGRASSTRHparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(CLEARGRASSTRHsensor[i][1]); trc(CLEARGRASSTRHsensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -252,7 +280,8 @@ void CLEARGRASSTRHDiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void CLEARGRASSTRHKPADiscovery(char * mac){ void CLEARGRASSTRHKPADiscovery(char *mac)
{
#define CLEARGRASSTRHKPAparametersCount 3 #define CLEARGRASSTRHKPAparametersCount 3
trc(F("CLEARGRASSTRHKPADiscovery")); trc(F("CLEARGRASSTRHKPADiscovery"));
char *CLEARGRASSTRHKPAsensor[CLEARGRASSTRHKPAparametersCount][8] = { char *CLEARGRASSTRHKPAsensor[CLEARGRASSTRHKPAparametersCount][8] = {
@@ -262,7 +291,8 @@ void CLEARGRASSTRHKPADiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<CLEARGRASSTRHKPAparametersCount;i++){ for (int i = 0; i < CLEARGRASSTRHKPAparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(CLEARGRASSTRHKPAsensor[i][1]); trc(CLEARGRASSTRHKPAsensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -281,8 +311,8 @@ void CLEARGRASSTRHKPADiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void MiScaleDiscovery(char *mac)
void MiScaleDiscovery(char * mac){ {
#define MiScaleparametersCount 1 #define MiScaleparametersCount 1
trc(F("MiScaleDiscovery")); trc(F("MiScaleDiscovery"));
char *MiScalesensor[MiScaleparametersCount][8] = { char *MiScalesensor[MiScaleparametersCount][8] = {
@@ -290,7 +320,8 @@ void MiScaleDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<MiScaleparametersCount;i++){ for (int i = 0; i < MiScaleparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(MiScalesensor[i][1]); trc(MiScalesensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -309,7 +340,8 @@ void MiScaleDiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void MiLampDiscovery(char * mac){ void MiLampDiscovery(char *mac)
{
#define MiLampparametersCount 1 #define MiLampparametersCount 1
trc(F("MiLampDiscovery")); trc(F("MiLampDiscovery"));
char *MiLampsensor[MiLampparametersCount][8] = { char *MiLampsensor[MiLampparametersCount][8] = {
@@ -317,7 +349,8 @@ void MiLampDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<MiLampparametersCount;i++){ for (int i = 0; i < MiLampparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(MiLampsensor[i][1]); trc(MiLampsensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -336,7 +369,8 @@ void MiLampDiscovery(char * mac){
devices.push_back(device); devices.push_back(device);
} }
void MiBandDiscovery(char * mac){ void MiBandDiscovery(char *mac)
{
#define MiBandparametersCount 1 #define MiBandparametersCount 1
trc(F("MiBandDiscovery")); trc(F("MiBandDiscovery"));
char *MiBandsensor[MiBandparametersCount][8] = { char *MiBandsensor[MiBandparametersCount][8] = {
@@ -344,7 +378,8 @@ void MiBandDiscovery(char * mac){
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<MiBandparametersCount;i++){ for (int i = 0; i < MiBandparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(MiBandsensor[i][1]); trc(MiBandsensor[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + String(mac); String discovery_topic = String(subjectBTtoMQTT) + String(mac);
@@ -382,8 +417,10 @@ void MiBandDiscovery(char * mac){
//core on which the BLE detection task will run //core on which the BLE detection task will run
static int taskCore = 0; static int taskCore = 0;
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
void onResult(BLEAdvertisedDevice advertisedDevice) { {
void onResult(BLEAdvertisedDevice advertisedDevice)
{
trc(F("Creating BLE buffer")); trc(F("Creating BLE buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &BLEdata = jsonBuffer.createObject(); JsonObject &BLEdata = jsonBuffer.createObject();
@@ -396,26 +433,35 @@ void MiBandDiscovery(char * mac){
mac_adress.toCharArray(mac, mac_adress.length() + 1); mac_adress.toCharArray(mac, mac_adress.length() + 1);
trc("device detected"); trc("device detected");
trc(mac); 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 ((!oneWhite() || isWhite(mac)) && !isBlack(mac))
if (advertisedDevice.haveName()) BLEdata.set("name", (char *)advertisedDevice.getName().c_str()); { //if not black listed mac we go AND if we have no white mac or this mac is white we go out
if (advertisedDevice.haveManufacturerData()) BLEdata.set("manufacturerdata", (char *)advertisedDevice.getManufacturerData().c_str()); if (advertisedDevice.haveName())
if (advertisedDevice.haveRSSI()) BLEdata.set("rssi", (int) advertisedDevice.getRSSI()); BLEdata.set("name", (char *)advertisedDevice.getName().c_str());
if (advertisedDevice.haveTXPower()) BLEdata.set("txpower", (int8_t) advertisedDevice.getTXPower()); 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 #ifdef subjectHomePresence
if (advertisedDevice.haveRSSI()) haRoomPresence(BLEdata);// this device has an rssi in consequence we can use it for home assistant room presence component if (advertisedDevice.haveRSSI())
haRoomPresence(BLEdata); // this device has an rssi in consequence we can use it for home assistant room presence component
#endif #endif
if (advertisedDevice.haveServiceData()){ if (advertisedDevice.haveServiceData())
{
trc(F("Get services data :")); trc(F("Get services data :"));
int serviceDataCount = advertisedDevice.getServiceDataCount(); int serviceDataCount = advertisedDevice.getServiceDataCount();
trc(serviceDataCount); trc(serviceDataCount);
for (int j = 0; j < serviceDataCount;j++){ for (int j = 0; j < serviceDataCount; j++)
{
std::string serviceData = advertisedDevice.getServiceData(j); std::string serviceData = advertisedDevice.getServiceData(j);
int serviceDataLength = serviceData.length(); int serviceDataLength = serviceData.length();
String returnedString = ""; String returnedString = "";
for (int i = 0; i < serviceDataLength; i++) for (int i = 0; i < serviceDataLength; i++)
{ {
int a = serviceData[i]; int a = serviceData[i];
if (a < 16) { if (a < 16)
{
returnedString = returnedString + "0"; returnedString = returnedString + "0";
} }
returnedString = returnedString + String(a, HEX); returnedString = returnedString + String(a, HEX);
@@ -427,126 +473,159 @@ void MiBandDiscovery(char * mac){
BLEdata.set("servicedata", service_data); BLEdata.set("servicedata", service_data);
#endif #endif
BLEdata.set("servicedatauuid", (char *)advertisedDevice.getServiceDataUUID(j).toString().c_str()); BLEdata.set("servicedatauuid", (char *)advertisedDevice.getServiceDataUUID(j).toString().c_str());
if(abs((int)BLEdata["rssi"]|0) < abs(Minrssi)) { // publish only the devices close enough if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi))
{ // publish only the devices close enough
pub((char *)mactopic.c_str(), BLEdata); pub((char *)mactopic.c_str(), BLEdata);
if (strstr(BLEdata["servicedatauuid"].as<char*>(),"fe95") != NULL ){ //Mi FLora, Mi jia, Cleargrass Method 1, LYWDS02, VegTrug if (strstr(BLEdata["servicedatauuid"].as<char *>(), "fe95") != NULL)
{ //Mi FLora, Mi jia, Cleargrass Method 1, LYWDS02, VegTrug
trc("Processing BLE device data"); trc("Processing BLE device data");
int pos = -1; int pos = -1;
pos = strpos(service_data, "209800"); pos = strpos(service_data, "209800");
if (pos != -1){ if (pos != -1)
{
trc(F("mi flora data reading")); trc(F("mi flora data reading"));
//example "servicedata":"71209800bc63b6658d7cc40d0910023200" //example "servicedata":"71209800bc63b6658d7cc40d0910023200"
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) MiFloraDiscovery(mac); if (!isDiscovered(mac))
MiFloraDiscovery(mac);
#endif #endif
process_sensors(pos - 24, service_data, mac); process_sensors(pos - 24, service_data, mac);
} }
pos = -1; pos = -1;
pos = strpos(service_data, "20bc03"); pos = strpos(service_data, "20bc03");
if (pos != -1){ if (pos != -1)
{
trc(F("vegtrug data reading")); trc(F("vegtrug data reading"));
//example "servicedata":"7120bc0399c309688d7cc40d0910020000" //example "servicedata":"7120bc0399c309688d7cc40d0910020000"
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) VegTrugDiscovery(mac); if (!isDiscovered(mac))
VegTrugDiscovery(mac);
#endif #endif
process_sensors(pos - 24, service_data, mac); process_sensors(pos - 24, service_data, mac);
} }
pos = -1; pos = -1;
pos = strpos(service_data, "20aa01"); pos = strpos(service_data, "20aa01");
if (pos != -1){ if (pos != -1)
{
trc(F("mi jia data reading")); trc(F("mi jia data reading"));
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) MiJiaDiscovery(mac); if (!isDiscovered(mac))
MiJiaDiscovery(mac);
#endif #endif
process_sensors(pos - 26, service_data, mac); process_sensors(pos - 26, service_data, mac);
} }
pos = -1; pos = -1;
pos = strpos(service_data, "205b04"); pos = strpos(service_data, "205b04");
if (pos != -1){ if (pos != -1)
{
trc(F("LYWSD02 data reading")); trc(F("LYWSD02 data reading"));
//example "servicedata":"70205b04b96ab883c8593f09041002e000" //example "servicedata":"70205b04b96ab883c8593f09041002e000"
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) LYWSD02Discovery(mac); if (!isDiscovered(mac))
LYWSD02Discovery(mac);
#endif #endif
process_sensors(pos - 24, service_data, mac); process_sensors(pos - 24, service_data, mac);
} }
pos = -1; pos = -1;
pos = strpos(service_data, "304703"); pos = strpos(service_data, "304703");
if (pos != -1){ if (pos != -1)
{
trc(F("ClearGrass T RH data reading method 1")); trc(F("ClearGrass T RH data reading method 1"));
//example "servicedata":"5030470340743e10342d58041002d6000a100164" //example "servicedata":"5030470340743e10342d58041002d6000a100164"
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) CLEARGRASSTRHDiscovery(mac); if (!isDiscovered(mac))
CLEARGRASSTRHDiscovery(mac);
#endif #endif
process_sensors(pos - 26, service_data, mac); process_sensors(pos - 26, service_data, mac);
} }
pos = -1; pos = -1;
pos = strpos(service_data, "4030dd"); pos = strpos(service_data, "4030dd");
if (pos != -1){ if (pos != -1)
{
trc(F("Mi Lamp data reading")); trc(F("Mi Lamp data reading"));
//example "servicedata":4030DD031D0300010100 //example "servicedata":4030DD031D0300010100
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) MiLampDiscovery(mac); if (!isDiscovered(mac))
MiLampDiscovery(mac);
#endif #endif
process_milamp(service_data, mac); process_milamp(service_data, mac);
} }
} }
if (strstr(BLEdata["servicedatauuid"].as<char*>(),"181d") != NULL){ // Mi Scale V1 if (strstr(BLEdata["servicedatauuid"].as<char *>(), "181d") != NULL)
{ // Mi Scale V1
trc(F("Mi Scale V1 data reading")); trc(F("Mi Scale V1 data reading"));
//example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28"
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) MiScaleDiscovery(mac); if (!isDiscovered(mac))
MiScaleDiscovery(mac);
#endif #endif
process_scale_v1(service_data, mac); process_scale_v1(service_data, mac);
} }
if (strstr(BLEdata["servicedatauuid"].as<char*>(),"181b") != NULL){ // Mi Scale V2 if (strstr(BLEdata["servicedatauuid"].as<char *>(), "181b") != NULL)
{ // Mi Scale V2
trc(F("Mi Scale V2 data reading")); trc(F("Mi Scale V2 data reading"));
//example "servicedata":02c4e1070b1e13050c00002607 / 02a6e20705150a251df401443e /02a6e20705180c0d04d701943e //example "servicedata":02c4e1070b1e13050c00002607 / 02a6e20705150a251df401443e /02a6e20705180c0d04d701943e
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) MiScaleDiscovery(mac); if (!isDiscovered(mac))
MiScaleDiscovery(mac);
#endif #endif
process_scale_v2(service_data, mac); process_scale_v2(service_data, mac);
} }
if (strstr(BLEdata["servicedatauuid"].as<char*>(),"fee0") != NULL){ // Mi Band //0000fee0-0000-1000-8000-00805f9b34fb // ESP32 only if (strstr(BLEdata["servicedatauuid"].as<char *>(), "fee0") != NULL)
{ // Mi Band //0000fee0-0000-1000-8000-00805f9b34fb // ESP32 only
trc(F("Mi Band data reading")); trc(F("Mi Band data reading"));
//example "servicedata":a21e0000 //example "servicedata":a21e0000
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) MiBandDiscovery(mac); if (!isDiscovered(mac))
MiBandDiscovery(mac);
#endif #endif
process_miband(service_data, mac); process_miband(service_data, mac);
} }
if (strstr(BLEdata["servicedata"].as<char*>(),"08094c") != NULL){ // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a if (strstr(BLEdata["servicedata"].as<char *>(), "08094c") != NULL)
{ // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a
trc(F("Clear grass data with air pressure reading")); trc(F("Clear grass data with air pressure reading"));
//example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a //example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(mac)) CLEARGRASSTRHKPADiscovery(mac); if (!isDiscovered(mac))
CLEARGRASSTRHKPADiscovery(mac);
#endif #endif
process_cleargrass_air(service_data, mac); process_cleargrass_air(service_data, mac);
} }
if (strstr(BLEdata["servicedata"].as<char*>(),"080774") != NULL){ // Clear grass standard method 2/0807743e10342d580104c3002c0202012a if (strstr(BLEdata["servicedata"].as<char *>(), "080774") != NULL)
{ // Clear grass standard method 2/0807743e10342d580104c3002c0202012a
trc(F("Clear grass data reading method 2")); trc(F("Clear grass data reading method 2"));
//example "servicedata":0807743e10342d580104 c300 2c02 02012a //example "servicedata":0807743e10342d580104 c300 2c02 02012a
// no discovery as it is already available with method 1 // no discovery as it is already available with method 1
process_cleargrass(service_data, mac); process_cleargrass(service_data, mac);
} }
}else{ }
else
{
trc("Low rssi, device filtered"); trc("Low rssi, device filtered");
} }
} }
}else{ }
if(abs((int)BLEdata["rssi"]|0) < abs(Minrssi)) { // publish only the devices close enough 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 pub((char *)mactopic.c_str(), BLEdata); // publish device even if there is no service data
}else{ }
else
{
trc("Low rssi, device filtered"); trc("Low rssi, device filtered");
} }
} }
}else{ }
else
{
trc(F("Filtered mac device")); trc(F("Filtered mac device"));
} }
} }
}; };
void BLEscan(){ void BLEscan()
{
TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed = 1; TIMERG0.wdt_feed = 1;
@@ -562,24 +641,30 @@ void MiBandDiscovery(char * mac){
esp_bt_controller_deinit(); esp_bt_controller_deinit();
} }
void coreTask( void * pvParameters ){ void coreTask(void *pvParameters)
{
String taskMessage = "BT Task running on core "; String taskMessage = "BT Task running on core ";
taskMessage = taskMessage + xPortGetCoreID(); taskMessage = taskMessage + xPortGetCoreID();
while(true){ while (true)
{
trc(taskMessage); trc(taskMessage);
delay(BLEinterval); delay(BLEinterval);
if (client.state() == 0) { if (client.state() == 0)
{
BLEscan(); BLEscan();
}else{ }
else
{
trc("MQTT client disconnected no BLE scan"); trc("MQTT client disconnected no BLE scan");
delay(1000); delay(1000);
} }
} }
} }
void setupBT(){ void setupBT()
{
BLEinterval = TimeBtw_Read; BLEinterval = TimeBtw_Read;
Minrssi = MinimumRSSI; Minrssi = MinimumRSSI;
trc(F("BLEinterval btw scans")); trc(F("BLEinterval btw scans"));
@@ -598,7 +683,8 @@ void MiBandDiscovery(char * mac){
trc(F("ZgatewayBT multicore ESP32 setup done ")); trc(F("ZgatewayBT multicore ESP32 setup done "));
} }
bool BTtoMQTT(){ // for on demand BLE scans bool BTtoMQTT()
{ // for on demand BLE scans
BLEscan(); BLEscan();
} }
#else // arduino or ESP8266 working with HM10/11 #else // arduino or ESP8266 working with HM10/11
@@ -619,7 +705,8 @@ void MiBandDiscovery(char * mac){
// this struct define which parts of the hexadecimal chain we extract and what to do with these parts // 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}}; 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() { void setupBT()
{
BLEinterval = TimeBtw_Read; BLEinterval = TimeBtw_Read;
Minrssi = MinimumRSSI; Minrssi = MinimumRSSI;
trc(F("BLEinterval btw scans")); trc(F("BLEinterval btw scans"));
@@ -640,25 +727,31 @@ void MiBandDiscovery(char * mac){
trc(F("ZgatewayBT HM1X setup done ")); trc(F("ZgatewayBT HM1X setup done "));
} }
bool BTtoMQTT() { bool BTtoMQTT()
{
//extract serial data from module in hexa format //extract serial data from module in hexa format
while (softserial.available() > 0) { while (softserial.available() > 0)
{
int a = softserial.read(); int a = softserial.read();
if (a < 16) { if (a < 16)
{
returnedString = returnedString + "0"; returnedString = returnedString + "0";
} }
returnedString = returnedString + String(a, HEX); returnedString = returnedString + String(a, HEX);
} }
if (millis() > (timebt + BLEinterval)) {//retriving data if (millis() > (timebt + BLEinterval))
{ //retriving data
timebt = millis(); timebt = millis();
#if defined(ESP8266) #if defined(ESP8266)
yield(); yield();
#endif #endif
if (returnedString != "") { if (returnedString != "")
{
size_t pos = 0; size_t pos = 0;
while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1) { while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1)
{
#if defined(ESP8266) #if defined(ESP8266)
yield(); yield();
#endif #endif
@@ -667,11 +760,13 @@ void MiBandDiscovery(char * mac){
char token_char[token.length() + 1]; char token_char[token.length() + 1];
token.toCharArray(token_char, token.length() + 1); token.toCharArray(token_char, token.length() + 1);
trc(token); trc(token);
if ( token.length() > 60){// we extract data only if we have detailled infos if (token.length() > 60)
{ // we extract data only if we have detailled infos
for (int i = 0; i < 6; i++) for (int i = 0; i < 6; i++)
{ {
extract_char(token_char, d[i].extract, d[i].start, d[i].len, d[i].reverse, false); 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 (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 if ((strlen(d[0].extract)) == 12) // if a mac adress is detected we publish it
@@ -680,13 +775,17 @@ void MiBandDiscovery(char * mac){
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &BLEdata = jsonBuffer.createObject(); JsonObject &BLEdata = jsonBuffer.createObject();
strupp(d[0].extract); strupp(d[0].extract);
if(isBlack(d[0].extract)) return false; //if black listed mac we go out if (isBlack(d[0].extract))
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 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 #ifdef subjectHomePresence
String HomePresenceId; String HomePresenceId;
for (int i = 0; i<12; i++){ for (int i = 0; i < 12; i++)
{
HomePresenceId += String(d[0].extract[i]); HomePresenceId += String(d[0].extract[i]);
if(((i-1) % 2 == 0) && (i!=11)) HomePresenceId += ":"; if (((i - 1) % 2 == 0) && (i != 11))
HomePresenceId += ":";
} }
trc(F("HomePresenceId")); trc(F("HomePresenceId"));
trc(HomePresenceId); trc(HomePresenceId);
@@ -703,86 +802,104 @@ void MiBandDiscovery(char * mac){
#ifdef pubBLEServiceData #ifdef pubBLEServiceData
BLEdata.set("servicedata", (char *)service_data.c_str()); BLEdata.set("servicedata", (char *)service_data.c_str());
#endif #endif
if(abs((int)BLEdata["rssi"]|0) < abs(Minrssi)) { // publish only the devices close enough if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi))
{ // publish only the devices close enough
pub((char *)topic.c_str(), BLEdata); pub((char *)topic.c_str(), BLEdata);
int pos = -1; int pos = -1;
pos = strpos(d[5].extract, "209800"); pos = strpos(d[5].extract, "209800");
if (pos != -1) { if (pos != -1)
{
trc("mi flora data reading"); trc("mi flora data reading");
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) MiFloraDiscovery(d[0].extract); if (!isDiscovered(d[0].extract))
MiFloraDiscovery(d[0].extract);
#endif #endif
bool result = process_sensors(pos - 38, (char *)service_data.c_str(), d[0].extract); bool result = process_sensors(pos - 38, (char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "20aa01"); pos = strpos(d[5].extract, "20aa01");
//example "servicedata":"5020aa0194dfaa33342d580d1004e3002c02" //example "servicedata":"5020aa0194dfaa33342d580d1004e3002c02"
if (pos != -1){ if (pos != -1)
{
trc("mi jia data reading"); trc("mi jia data reading");
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) MiJiaDiscovery(d[0].extract); if (!isDiscovered(d[0].extract))
MiJiaDiscovery(d[0].extract);
#endif #endif
bool result = process_sensors(pos - 40, (char *)service_data.c_str(), d[0].extract); bool result = process_sensors(pos - 40, (char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "205b04"); pos = strpos(d[5].extract, "205b04");
//example "servicedata":"141695fe70205b0461298882c8593f09061002d002" //example "servicedata":"141695fe70205b0461298882c8593f09061002d002"
if (pos != -1){ if (pos != -1)
{
trc("LYWSD02 data reading"); trc("LYWSD02 data reading");
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) LYWSD02Discovery(d[0].extract); if (!isDiscovered(d[0].extract))
LYWSD02Discovery(d[0].extract);
#endif #endif
bool result = process_sensors(pos - 38, (char *)service_data.c_str(), d[0].extract); bool result = process_sensors(pos - 38, (char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "304703"); pos = strpos(d[5].extract, "304703");
if (pos != -1){ if (pos != -1)
{
trc("CLEARGRASSTRH data reading method 1"); trc("CLEARGRASSTRH data reading method 1");
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) CLEARGRASSTRHDiscovery(d[0].extract); if (!isDiscovered(d[0].extract))
CLEARGRASSTRHDiscovery(d[0].extract);
#endif #endif
bool result = process_sensors(pos - 40, (char *)service_data.c_str(), d[0].extract); bool result = process_sensors(pos - 40, (char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "e30706"); pos = strpos(d[5].extract, "e30706");
if (pos != -1){ if (pos != -1)
{
trc("Mi Scale data reading"); trc("Mi Scale data reading");
//example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28" //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28"
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) MiScaleDiscovery(d[0].extract); if (!isDiscovered(d[0].extract))
MiScaleDiscovery(d[0].extract);
#endif #endif
bool result = process_scale_v1((char *)service_data.c_str(), d[0].extract); bool result = process_scale_v1((char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "4030dd"); pos = strpos(d[5].extract, "4030dd");
if (pos != -1){ if (pos != -1)
{
trc(F("Mi Lamp data reading")); trc(F("Mi Lamp data reading"));
//example "servicedata":4030dd31d0300010100 //example "servicedata":4030dd31d0300010100
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) MiLampDiscovery(d[0].extract); if (!isDiscovered(d[0].extract))
MiLampDiscovery(d[0].extract);
#endif #endif
process_milamp((char *)service_data.c_str(), d[0].extract); process_milamp((char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "08094c"); // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a pos = strpos(d[5].extract, "08094c"); // Clear grass with air pressure//08094c0140342d580104d8000c020702612702015a
if (pos != -1){ if (pos != -1)
{
trc(F("Clear grass data with air pressure reading")); trc(F("Clear grass data with air pressure reading"));
//example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a //example "servicedata":08094c0140342d580104 c400 2402 0702 5d27 02015a
#ifdef ZmqttDiscovery #ifdef ZmqttDiscovery
if(!isDiscovered(d[0].extract)) CLEARGRASSTRHKPADiscovery(d[0].extract); if (!isDiscovered(d[0].extract))
CLEARGRASSTRHKPADiscovery(d[0].extract);
#endif #endif
process_cleargrass_air((char *)service_data.c_str(), d[0].extract); process_cleargrass_air((char *)service_data.c_str(), d[0].extract);
} }
pos = -1; pos = -1;
pos = strpos(d[5].extract, "080774"); // Clear grass standard method 2/0807743e10342d580104c3002c0202012a pos = strpos(d[5].extract, "080774"); // Clear grass standard method 2/0807743e10342d580104c3002c0202012a
if (pos != -1){ if (pos != -1)
{
trc(F("Clear grass data reading method 2")); trc(F("Clear grass data reading method 2"));
//example "servicedata":0807743e10342d580104 c300 2c02 02012a //example "servicedata":0807743e10342d580104 c300 2c02 02012a
// no discovery as it is already available with method 1 // no discovery as it is already available with method 1
process_cleargrass((char *)service_data.c_str(), d[0].extract); process_cleargrass((char *)service_data.c_str(), d[0].extract);
} }
return true; return true;
}else{ }
else
{
trc("Low rssi, device filtered"); trc("Low rssi, device filtered");
} }
} }
@@ -793,13 +910,16 @@ void MiBandDiscovery(char * mac){
} }
softserial.print(F(QUESTION_MSG)); softserial.print(F(QUESTION_MSG));
return false; return false;
}else{ }
else
{
return false; return false;
} }
} }
#endif #endif
double value_from_service_data(char * service_data, int offset, int data_length){ double value_from_service_data(char *service_data, int offset, int data_length)
{
char rev_data[data_length + 1]; char rev_data[data_length + 1];
char data[data_length + 1]; char data[data_length + 1];
memcpy(rev_data, &service_data[offset], data_length); memcpy(rev_data, &service_data[offset], data_length);
@@ -808,12 +928,14 @@ double value_from_service_data(char * service_data, int offset, int data_length)
// reverse data order // 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); 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); trc(value);
return 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")); trc(F("Creating BLE buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
@@ -823,7 +945,8 @@ bool process_sensors(int offset, char * rest_data, char * mac_adress){
int data_length = 0; int data_length = 0;
trc("data_length"); trc("data_length");
trc(rest_data[51 + offset]); trc(rest_data[51 + offset]);
switch (rest_data[51 + offset]) { switch (rest_data[51 + offset])
{
case '1': case '1':
case '2': case '2':
case '3': case '3':
@@ -842,7 +965,8 @@ bool process_sensors(int offset, char * rest_data, char * mac_adress){
// Mi flora provides tem(perature), (earth) moi(sture), fer(tility) and lux (illuminance) // Mi flora provides tem(perature), (earth) moi(sture), fer(tility) and lux (illuminance)
// Mi Jia provides tem(perature), batt(erry) and hum(idity) // 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 // following the value of digit 47 we determine the type of data we get from the sensor
switch (rest_data[47 + offset]) { switch (rest_data[47 + offset])
{
case '9': case '9':
BLEdata.set("fer", (double)value); BLEdata.set("fer", (double)value);
break; break;
@@ -881,7 +1005,8 @@ bool process_sensors(int offset, char * rest_data, char * mac_adress){
return true; 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" //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28"
trc("rest_data"); trc("rest_data");
trc(rest_data); trc(rest_data);
@@ -902,7 +1027,8 @@ bool process_scale_v1(char * rest_data, char * mac_adress){
return true; 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" //example "servicedata":"a2ac2be307060207122b" /"a28039e3070602070e28"
trc("rest_data"); trc("rest_data");
trc(rest_data); trc(rest_data);
@@ -925,7 +1051,8 @@ bool process_scale_v2(char * rest_data, char * mac_adress){
return true; return true;
} }
bool process_miband(char * rest_data, char * mac_adress){ bool process_miband(char *rest_data, char *mac_adress)
{
//example "servicedata":"a21e0000" //example "servicedata":"a21e0000"
trc("rest_data"); trc("rest_data");
trc(rest_data); trc(rest_data);
@@ -946,7 +1073,8 @@ bool process_miband(char * rest_data, char * mac_adress){
return true; return true;
} }
bool process_milamp(char * rest_data, char * mac_adress){ bool process_milamp(char *rest_data, char *mac_adress)
{
//example "servicedata":"4030dd31d0300010100" //example "servicedata":"4030dd31d0300010100"
trc("rest_data"); trc("rest_data");
trc(rest_data); trc(rest_data);
@@ -968,7 +1096,8 @@ bool process_milamp(char * rest_data, char * mac_adress){
return true; 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" //example "servicedata":"08094c0140342d580104c400240207025d2702015a"
//decoding "08094c0140342d580104 temp:c400 hum:2402 0702 pressure:5d27 02015a" //decoding "08094c0140342d580104 temp:c400 hum:2402 0702 pressure:5d27 02015a"
trc("rest_data"); trc("rest_data");
@@ -995,8 +1124,8 @@ bool process_cleargrass_air(char * rest_data, char * mac_adress){
return true; 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 //example "servicedata":0807743e10342d580104 c300 2c02 02012a
trc("rest_data"); trc("rest_data");
trc(rest_data); trc(rest_data);
@@ -1020,19 +1149,24 @@ bool process_cleargrass(char * rest_data, char * mac_adress){
} }
#ifdef subjectHomePresence #ifdef subjectHomePresence
void haRoomPresence(JsonObject& HomePresence){ void haRoomPresence(JsonObject &HomePresence)
{
int BLErssi = HomePresence["rssi"]; int BLErssi = HomePresence["rssi"];
trc(F("BLErssi")); trc(F("BLErssi"));
trc(BLErssi); trc(BLErssi);
int txPower = HomePresence["txpower"] | 0; int txPower = HomePresence["txpower"] | 0;
if (txPower >= 0) txPower = -59; //if tx power is not found we set a default calibration value if (txPower >= 0)
txPower = -59; //if tx power is not found we set a default calibration value
trc(F("txPower")); trc(F("txPower"));
trc(txPower); trc(txPower);
double ratio = BLErssi * 1.0 / txPower; double ratio = BLErssi * 1.0 / txPower;
double distance; double distance;
if (ratio < 1.0) { if (ratio < 1.0)
{
distance = pow(ratio, 10); distance = pow(ratio, 10);
}else{ }
else
{
distance = (0.89976) * pow(ratio, 7.7095) + 0.111; distance = (0.89976) * pow(ratio, 7.7095) + 0.111;
} }
HomePresence["distance"] = distance; HomePresence["distance"] = distance;
@@ -1043,31 +1177,39 @@ void haRoomPresence(JsonObject& HomePresence){
} }
#endif #endif
void MQTTtoBT(char * topicOri, JsonObject& BTdata) { // json object decoding void MQTTtoBT(char *topicOri, JsonObject &BTdata)
if (cmpToMainTopic(topicOri,subjectMQTTtoBTset)){ { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoBTset))
{
trc(F("MQTTtoBT json set")); trc(F("MQTTtoBT json set"));
// Black list & white list set // Black list & white list set
int WLsize = BTdata["white-list"].size(); int WLsize = BTdata["white-list"].size();
if(WLsize > 0){ if (WLsize > 0)
{
trc(F("WL set")); trc(F("WL set"));
for (int i = 0; i < WLsize; i++){ for (int i = 0; i < WLsize; i++)
{
const char *whiteMac = BTdata["white-list"][i]; const char *whiteMac = BTdata["white-list"][i];
setWorBMac((char *)whiteMac, true); setWorBMac((char *)whiteMac, true);
} }
} }
int BLsize = BTdata["black-list"].size(); int BLsize = BTdata["black-list"].size();
if(BLsize > 0){ if (BLsize > 0)
{
trc(F("BL set")); trc(F("BL set"));
for (int i = 0; i < BLsize; i++){ for (int i = 0; i < BLsize; i++)
{
const char *blackMac = BTdata["black-list"][i]; const char *blackMac = BTdata["black-list"][i];
setWorBMac((char *)blackMac, false); setWorBMac((char *)blackMac, false);
} }
} }
if (BLsize > 0 || WLsize > 0) dumpDevices(); if (BLsize > 0 || WLsize > 0)
dumpDevices();
// Scan interval set // Scan interval set
if (BTdata.containsKey("interval")){ if (BTdata.containsKey("interval"))
{
trc(F("BLE interval")); trc(F("BLE interval"));
// storing BLE interval for further use if needed // storing BLE interval for further use if needed
unsigned int prevBLEinterval = BLEinterval; unsigned int prevBLEinterval = BLEinterval;
@@ -1077,14 +1219,16 @@ void MQTTtoBT(char * topicOri, JsonObject& BTdata) { // json object decoding
BLEinterval = (unsigned int)BTdata["interval"]; BLEinterval = (unsigned int)BTdata["interval"];
trc("new interval"); trc("new interval");
trc(BLEinterval); trc(BLEinterval);
if (BLEinterval == 0) { if (BLEinterval == 0)
{
if (BTtoMQTT()) // as BLEinterval is = to 0 we can launch the loop and the scan will execute immediately if (BTtoMQTT()) // as BLEinterval is = to 0 we can launch the loop and the scan will execute immediately
trc(F("Scan done")); trc(F("Scan done"));
BLEinterval = prevBLEinterval; // as 0 was just used as a command we recover previous scan duration BLEinterval = prevBLEinterval; // as 0 was just used as a command we recover previous scan duration
} }
} }
// MinRSSI set // MinRSSI set
if (BTdata.containsKey("minrssi")){ if (BTdata.containsKey("minrssi"))
{
trc(F("Min RSSI")); trc(F("Min RSSI"));
// storing Min RSSI for further use if needed // storing Min RSSI for further use if needed
trc("previous Minrssi"); trc("previous Minrssi");
+464 -229
View File
File diff suppressed because it is too large. Load diff
+31 -15
View File
@@ -33,13 +33,16 @@
#include <LoRa.h> #include <LoRa.h>
#include <Wire.h> #include <Wire.h>
void setupLORA() { void setupLORA()
{
SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_SS); SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_SS);
LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0); LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0);
if (!LoRa.begin(LORA_BAND)) { if (!LoRa.begin(LORA_BAND))
{
trc(F("ZgatewayLORA setup failed!")); trc(F("ZgatewayLORA setup failed!"));
while (1); while (1)
;
} }
LoRa.receive(); LoRa.receive();
trc(F("LORA_SCK")); trc(F("LORA_SCK"));
@@ -55,12 +58,13 @@ void setupLORA() {
trc(F("LORA_DI0")); trc(F("LORA_DI0"));
trc(LORA_DI0); trc(LORA_DI0);
trc(F("ZgatewayLORA setup done")); trc(F("ZgatewayLORA setup done"));
} }
void LORAtoMQTT(){ void LORAtoMQTT()
{
int packetSize = LoRa.parsePacket(); int packetSize = LoRa.parsePacket();
if (packetSize) { if (packetSize)
{
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &LORAdata = jsonBuffer.createObject(); JsonObject &LORAdata = jsonBuffer.createObject();
trc(F("Rcv. LORA")); trc(F("Rcv. LORA"));
@@ -71,14 +75,18 @@ void LORAtoMQTT(){
#endif #endif
String packet; String packet;
packet = ""; packet = "";
for (int i = 0; i < packetSize; i++) { packet += (char) LoRa.read(); } for (int i = 0; i < packetSize; i++)
{
packet += (char)LoRa.read();
}
LORAdata.set("rssi", (int)LoRa.packetRssi()); LORAdata.set("rssi", (int)LoRa.packetRssi());
LORAdata.set("snr", (float)LoRa.packetSnr()); LORAdata.set("snr", (float)LoRa.packetSnr());
LORAdata.set("pferror", (float)LoRa.packetFrequencyError()); LORAdata.set("pferror", (float)LoRa.packetFrequencyError());
LORAdata.set("packetSize", (int)packetSize); LORAdata.set("packetSize", (int)packetSize);
LORAdata.set("message", (char *)packet.c_str()); LORAdata.set("message", (char *)packet.c_str());
pub(subjectLORAtoMQTT, LORAdata); pub(subjectLORAtoMQTT, LORAdata);
if (repeatLORAwMQTT){ if (repeatLORAwMQTT)
{
trc(F("Pub LORA for rpt")); trc(F("Pub LORA for rpt"));
pub(subjectMQTTtoLORA, LORAdata); pub(subjectMQTTtoLORA, LORAdata);
} }
@@ -86,8 +94,10 @@ void LORAtoMQTT(){
} }
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTtoLORA(char * topicOri, JsonObject& LORAdata) { // json object decoding void MQTTtoLORA(char *topicOri, JsonObject &LORAdata)
if (cmpToMainTopic(topicOri,subjectMQTTtoLORA)){ { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoLORA))
{
trc(F("MQTTtoLORA json")); trc(F("MQTTtoLORA json"));
const char *message = LORAdata["message"]; const char *message = LORAdata["message"];
int txPower = LORAdata["txpower"] | LORA_TX_POWER; int txPower = LORAdata["txpower"] | LORA_TX_POWER;
@@ -98,7 +108,8 @@ void LORAtoMQTT(){
int preambleLength = LORAdata["preamblelength"] | LORA_PREAMBLE_LENGTH; int preambleLength = LORAdata["preamblelength"] | LORA_PREAMBLE_LENGTH;
byte syncWord = LORAdata["syncword"] | LORA_SYNC_WORD; byte syncWord = LORAdata["syncword"] | LORA_SYNC_WORD;
bool Crc = LORAdata["enablecrc"] | DEFAULT_CRC; bool Crc = LORAdata["enablecrc"] | DEFAULT_CRC;
if (message) { if (message)
{
LoRa.setTxPower(txPower); LoRa.setTxPower(txPower);
LoRa.setFrequency(frequency); LoRa.setFrequency(frequency);
LoRa.setSpreadingFactor(spreadingFactor); LoRa.setSpreadingFactor(spreadingFactor);
@@ -106,21 +117,26 @@ void LORAtoMQTT(){
LoRa.setCodingRate4(codingRateDenominator); LoRa.setCodingRate4(codingRateDenominator);
LoRa.setPreambleLength(preambleLength); LoRa.setPreambleLength(preambleLength);
LoRa.setSyncWord(syncWord); LoRa.setSyncWord(syncWord);
if (Crc) LoRa.enableCrc(); if (Crc)
LoRa.enableCrc();
LoRa.beginPacket(); LoRa.beginPacket();
LoRa.print(message); LoRa.print(message);
LoRa.endPacket(); LoRa.endPacket();
trc(F("MQTTtoLORA OK")); 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 pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{ }
else
{
trc(F("MQTTtoLORA Fail json")); trc(F("MQTTtoLORA Fail json"));
} }
} }
} }
#endif #endif
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoLORA(char * topicOri, char * LORAdata) { // json object decoding void MQTTtoLORA(char *topicOri, char *LORAdata)
if (cmpToMainTopic(topicOri,subjectMQTTtoLORA)){ { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoLORA))
{
LoRa.beginPacket(); LoRa.beginPacket();
LoRa.print(LORAdata); LoRa.print(LORAdata);
LoRa.endPacket(); LoRa.endPacket();
+36 -16
View File
@@ -32,8 +32,10 @@
ESPiLight rf(RF_EMITTER_PIN); // use -1 to disable transmitter ESPiLight rf(RF_EMITTER_PIN); // use -1 to disable transmitter
void pilightCallback(const String &protocol, const String &message, int status, void pilightCallback(const String &protocol, const String &message, int status,
size_t repeats, const String &deviceID) { size_t repeats, const String &deviceID)
if (status == VALID) { {
if (status == VALID)
{
trc(F("Creating RF PiLight buffer")); trc(F("Creating RF PiLight buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &RFPiLightdata = jsonBuffer.createObject(); JsonObject &RFPiLightdata = jsonBuffer.createObject();
@@ -45,14 +47,16 @@ void pilightCallback(const String &protocol,const String &message, int status,
RFPiLightdata.set("repeats", (int)repeats); RFPiLightdata.set("repeats", (int)repeats);
RFPiLightdata.set("status", (int)status); RFPiLightdata.set("status", (int)status);
pub(subjectPilighttoMQTT, RFPiLightdata); pub(subjectPilighttoMQTT, RFPiLightdata);
if (repeatPilightwMQTT){ if (repeatPilightwMQTT)
{
trc(F("Pub Pilight for rpt")); trc(F("Pub Pilight for rpt"));
pub(subjectMQTTtoPilight, RFPiLightdata); pub(subjectMQTTtoPilight, RFPiLightdata);
} }
} }
} }
void setupPilight(){ void setupPilight()
{
#ifndef ZgatewayRF &&ZgatewayRF2 &&ZgatewayRF315 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell #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.setCallback(pilightCallback);
rf.initReceiver(RF_RECEIVER_PIN); rf.initReceiver(RF_RECEIVER_PIN);
@@ -66,32 +70,40 @@ void setupPilight(){
#endif #endif
} }
void PilighttoMQTT(){ void PilighttoMQTT()
{
rf.loop(); rf.loop();
} }
void MQTTtoPilight(char * topicOri, JsonObject& Pilightdata) { void MQTTtoPilight(char *topicOri, JsonObject &Pilightdata)
{
int result = 0; int result = 0;
if (cmpToMainTopic(topicOri,subjectMQTTtoPilight)){ if (cmpToMainTopic(topicOri, subjectMQTTtoPilight))
{
trc(F("MQTTtoPilight json data analysis")); trc(F("MQTTtoPilight json data analysis"));
const char *message = Pilightdata["message"]; const char *message = Pilightdata["message"];
const char *protocol = Pilightdata["protocol"]; const char *protocol = Pilightdata["protocol"];
const char *raw = Pilightdata["raw"]; const char *raw = Pilightdata["raw"];
if(raw){ if (raw)
{
int msgLength = 0; int msgLength = 0;
uint16_t codes[MAXPULSESTREAMLENGTH]; uint16_t codes[MAXPULSESTREAMLENGTH];
msgLength = rf.stringToPulseTrain( msgLength = rf.stringToPulseTrain(
raw, raw,
codes, MAXPULSESTREAMLENGTH); codes, MAXPULSESTREAMLENGTH);
if (msgLength > 0) { if (msgLength > 0)
{
trc(F("MQTTtoPilight raw ok")); trc(F("MQTTtoPilight raw ok"));
rf.sendPulseTrain(codes, msgLength); rf.sendPulseTrain(codes, msgLength);
result = msgLength; result = msgLength;
}else{ }
else
{
trc(F("MQTTtoPilight raw KO")); trc(F("MQTTtoPilight raw KO"));
switch (result) { switch (result)
{
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C: case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C:
trc(F("'c' not found in string, or has no data")); trc(F("'c' not found in string, or has no data"));
break; break;
@@ -106,18 +118,26 @@ void MQTTtoPilight(char * topicOri, JsonObject& Pilightdata) {
break; break;
} }
} }
}else if (message && protocol) { }
else if (message && protocol)
{
trc(F("MQTTtoPilight msg & protocol ok")); trc(F("MQTTtoPilight msg & protocol ok"));
result = rf.send(protocol, message); result = rf.send(protocol, message);
}else{ }
else
{
trc(F("MQTTtoPilight failed json read")); trc(F("MQTTtoPilight failed json read"));
} }
if (result > 0) { if (result > 0)
{
trc(F("Adv data MQTTtoPilight push state via PilighttoMQTT")); trc(F("Adv data MQTTtoPilight push state via PilighttoMQTT"));
pub(subjectGTWPilighttoMQTT, Pilightdata); pub(subjectGTWPilighttoMQTT, Pilightdata);
} else { }
switch (result) { else
{
switch (result)
{
case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL:
trc(F("protocol is not available")); trc(F("protocol is not available"));
break; break;
+40 -19
View File
@@ -34,7 +34,8 @@
RCSwitch mySwitch = RCSwitch(); RCSwitch mySwitch = RCSwitch();
#ifdef ZmqttDiscovery #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]; char val[11];
sprintf(val, "%lu", MQTTvalue); sprintf(val, "%lu", MQTTvalue);
trc(F("switchRFDiscovery")); trc(F("switchRFDiscovery"));
@@ -51,7 +52,8 @@ void RFtoMQTTdiscovery(unsigned long MQTTvalue){//on the fly switch creation fro
} }
#endif #endif
void setupRF(){ void setupRF()
{
//RF init parameters //RF init parameters
mySwitch.enableTransmit(RF_EMITTER_PIN); mySwitch.enableTransmit(RF_EMITTER_PIN);
@@ -64,9 +66,11 @@ void setupRF(){
trc(F("RF setup ok")); 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); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &RFdata = jsonBuffer.createObject(); JsonObject &RFdata = jsonBuffer.createObject();
@@ -83,14 +87,16 @@ void RFtoMQTT(){
mySwitch.resetAvailable(); mySwitch.resetAvailable();
unsigned long MQTTvalue = RFdata.get<unsigned long>("value"); unsigned long MQTTvalue = RFdata.get<unsigned long>("value");
if (!isAduplicate(MQTTvalue) && MQTTvalue!=0) {// conditions to avoid duplications of RF -->MQTT if (!isAduplicate(MQTTvalue) && MQTTvalue != 0)
{ // conditions to avoid duplications of RF -->MQTT
#ifdef ZmqttDiscovery //component creation for HA #ifdef ZmqttDiscovery //component creation for HA
RFtoMQTTdiscovery(MQTTvalue); RFtoMQTTdiscovery(MQTTvalue);
#endif #endif
pub(subjectRFtoMQTT, RFdata); pub(subjectRFtoMQTT, RFdata);
trc(F("Store val")); trc(F("Store val"));
storeValue(MQTTvalue); storeValue(MQTTvalue);
if (repeatRFwMQTT){ if (repeatRFwMQTT)
{
trc(F("Pub RF for rpt")); trc(F("Pub RF for rpt"));
pub(subjectMQTTtoRF, RFdata); pub(subjectMQTTtoRF, RFdata);
} }
@@ -99,7 +105,8 @@ void RFtoMQTT(){
} }
#ifdef simpleReceiving #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 unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
@@ -110,7 +117,8 @@ void MQTTtoRF(char * topicOri, char * datacallback) {
int valuePLSL = 0; int valuePLSL = 0;
int valueBITS = 0; int valueBITS = 0;
int pos = topic.lastIndexOf(RFprotocolKey); int pos = topic.lastIndexOf(RFprotocolKey);
if (pos != -1){ if (pos != -1)
{
pos = pos + +strlen(RFprotocolKey); pos = pos + +strlen(RFprotocolKey);
valuePRT = (topic.substring(pos, pos + 1)).toInt(); valuePRT = (topic.substring(pos, pos + 1)).toInt();
trc(F("RF Protocol:")); trc(F("RF Protocol:"));
@@ -118,31 +126,39 @@ void MQTTtoRF(char * topicOri, char * datacallback) {
} }
//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); int pos2 = topic.lastIndexOf(RFpulselengthKey);
if (pos2 != -1) { if (pos2 != -1)
{
pos2 = pos2 + strlen(RFpulselengthKey); pos2 = pos2 + strlen(RFpulselengthKey);
valuePLSL = (topic.substring(pos2, pos2 + 3)).toInt(); valuePLSL = (topic.substring(pos2, pos2 + 3)).toInt();
trc(F("RF Pulse Lgth:")); trc(F("RF Pulse Lgth:"));
trc(valuePLSL); trc(valuePLSL);
} }
int pos3 = topic.lastIndexOf(RFbitsKey); int pos3 = topic.lastIndexOf(RFbitsKey);
if (pos3 != -1){ if (pos3 != -1)
{
pos3 = pos3 + strlen(RFbitsKey); pos3 = pos3 + strlen(RFbitsKey);
valueBITS = (topic.substring(pos3, pos3 + 2)).toInt(); valueBITS = (topic.substring(pos3, pos3 + 2)).toInt();
trc(F("Bits nb:")); trc(F("Bits nb:"));
trc(valueBITS); 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")); trc(F("MQTTtoRF dflt"));
mySwitch.setProtocol(1, 350); mySwitch.setProtocol(1, 350);
mySwitch.send(data, 24); mySwitch.send(data, 24);
// Acknowledgement to the GTWRF topic // Acknowledgement to the GTWRF topic
pub(subjectGTWRFtoMQTT, datacallback); pub(subjectGTWRFtoMQTT, datacallback);
} else if ((valuePRT != 0) || (valuePLSL != 0)|| (valueBITS != 0)){ }
else if ((valuePRT != 0) || (valuePLSL != 0) || (valueBITS != 0))
{
trc(F("MQTTtoRF usr par.")); trc(F("MQTTtoRF usr par."));
if (valuePRT == 0) valuePRT = 1; if (valuePRT == 0)
if (valuePLSL == 0) valuePLSL = 350; valuePRT = 1;
if (valueBITS == 0) valueBITS = 24; if (valuePLSL == 0)
valuePLSL = 350;
if (valueBITS == 0)
valueBITS = 24;
trc(valuePRT); trc(valuePRT);
trc(valuePLSL); trc(valuePLSL);
trc(valueBITS); trc(valueBITS);
@@ -155,11 +171,14 @@ void MQTTtoRF(char * topicOri, char * datacallback) {
#endif #endif
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTtoRF(char * topicOri, JsonObject& RFdata) { // json object decoding void MQTTtoRF(char *topicOri, JsonObject &RFdata)
if (cmpToMainTopic(topicOri,subjectMQTTtoRF)){ { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoRF))
{
trc(F("MQTTtoRF json")); trc(F("MQTTtoRF json"));
unsigned long data = RFdata["value"]; unsigned long data = RFdata["value"];
if (data != 0) { if (data != 0)
{
int valuePRT = RFdata["protocol"] | 1; int valuePRT = RFdata["protocol"] | 1;
int valuePLSL = RFdata["delay"] | 350; int valuePLSL = RFdata["delay"] | 350;
int valueBITS = RFdata["length"] | 24; int valueBITS = RFdata["length"] | 24;
@@ -170,7 +189,9 @@ void MQTTtoRF(char * topicOri, char * datacallback) {
trc(F("MQTTtoRF OK")); 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 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 mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); // Restore the default value
}else{ }
else
{
trc(F("MQTTtoRF Fail json")); trc(F("MQTTtoRF Fail json"));
} }
} }
+73 -37
View File
@@ -52,7 +52,8 @@ struct RF2rxd
RF2rxd rf2rd; RF2rxd rf2rd;
void setupRF2(){ void setupRF2()
{
#ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF #ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF
NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback); NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback);
trc(F("RF_EMITTER_PIN ")); trc(F("RF_EMITTER_PIN "));
@@ -65,9 +66,11 @@ void setupRF2(){
digitalWrite(RF_EMITTER_PIN, LOW); digitalWrite(RF_EMITTER_PIN, LOW);
} }
void RF2toMQTT(){ void RF2toMQTT()
{
if(rf2rd.hasNewData){ if (rf2rd.hasNewData)
{
trc(F("Creating RF2 buffer")); trc(F("Creating RF2 buffer"));
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
@@ -87,7 +90,8 @@ void RF2toMQTT(){
} }
} }
void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType) { void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType)
{
rf2rd.period = period; rf2rd.period = period;
rf2rd.address = address; rf2rd.address = address;
@@ -95,11 +99,11 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
rf2rd.unit = unit; rf2rd.unit = unit;
rf2rd.switchType = switchType; rf2rd.switchType = switchType;
rf2rd.hasNewData = true; rf2rd.hasNewData = true;
} }
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoRF2(char * topicOri, char * datacallback) { void MQTTtoRF2(char *topicOri, char *datacallback)
{
// RF DATA ANALYSIS // 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
@@ -115,46 +119,55 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
int valueDIM = -1; int valueDIM = -1;
int pos = topic.lastIndexOf(RF2codeKey); int pos = topic.lastIndexOf(RF2codeKey);
if (pos != -1){ if (pos != -1)
{
pos = pos + +strlen(RF2codeKey); pos = pos + +strlen(RF2codeKey);
valueCODE = (topic.substring(pos, pos + 8)).toInt(); valueCODE = (topic.substring(pos, pos + 8)).toInt();
trc(F("RF2 code:")); trc(F("RF2 code:"));
trc(valueCODE); trc(valueCODE);
} }
int pos2 = topic.lastIndexOf(RF2periodKey); int pos2 = topic.lastIndexOf(RF2periodKey);
if (pos2 != -1) { if (pos2 != -1)
{
pos2 = pos2 + strlen(RF2periodKey); pos2 = pos2 + strlen(RF2periodKey);
valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt(); valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt();
trc(F("RF2 Period:")); trc(F("RF2 Period:"));
trc(valuePERIOD); trc(valuePERIOD);
} }
int pos3 = topic.lastIndexOf(RF2unitKey); int pos3 = topic.lastIndexOf(RF2unitKey);
if (pos3 != -1){ if (pos3 != -1)
{
pos3 = pos3 + strlen(RF2unitKey); pos3 = pos3 + strlen(RF2unitKey);
valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt(); valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt();
trc(F("Unit:")); trc(F("Unit:"));
trc(valueUNIT); trc(valueUNIT);
} }
int pos4 = topic.lastIndexOf(RF2groupKey); int pos4 = topic.lastIndexOf(RF2groupKey);
if (pos4 != -1) { if (pos4 != -1)
{
pos4 = pos4 + strlen(RF2groupKey); pos4 = pos4 + strlen(RF2groupKey);
valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt(); valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt();
trc(F("RF2 Group:")); trc(F("RF2 Group:"));
trc(valueGROUP); trc(valueGROUP);
} }
int pos5 = topic.lastIndexOf(RF2dimKey); int pos5 = topic.lastIndexOf(RF2dimKey);
if (pos5 != -1) { if (pos5 != -1)
{
isDimCommand = true; isDimCommand = true;
valueDIM = atoi(datacallback); valueDIM = atoi(datacallback);
trc(F("RF2 Dim:")); trc(F("RF2 Dim:"));
trc(valueDIM); trc(valueDIM);
} }
if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){ if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0))
{
trc(F("MQTTtoRF2")); trc(F("MQTTtoRF2"));
if (valueCODE == 0) valueCODE = 8233378; if (valueCODE == 0)
if (valueUNIT == -1) valueUNIT = 0; valueCODE = 8233378;
if (valuePERIOD == 0) valuePERIOD = 272; if (valueUNIT == -1)
valueUNIT = 0;
if (valuePERIOD == 0)
valuePERIOD = 272;
trc(valueCODE); trc(valueCODE);
trc(valueUNIT); trc(valueUNIT);
trc(valuePERIOD); trc(valuePERIOD);
@@ -165,19 +178,25 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
trc(F("Creating transmitter")); trc(F("Creating transmitter"));
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
trc(F("Sending data")); trc(F("Sending data"));
if (valueGROUP) { if (valueGROUP)
if (isDimCommand) { {
if (isDimCommand)
{
transmitter.sendGroupDim(valueDIM); transmitter.sendGroupDim(valueDIM);
} }
else { else
{
transmitter.sendGroup(boolSWITCHTYPE); transmitter.sendGroup(boolSWITCHTYPE);
} }
} }
else { else
if (isDimCommand) { {
if (isDimCommand)
{
transmitter.sendDim(valueUNIT, valueDIM); transmitter.sendDim(valueUNIT, valueDIM);
} }
else { else
{
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
} }
} }
@@ -200,11 +219,13 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
MQTTdimLevel = String(valueDIM); MQTTdimLevel = String(valueDIM);
String MQTTRF2string; String MQTTRF2string;
trc(F("Adv data MQTTtoRF2 push state via RF2toMQTT")); trc(F("Adv data MQTTtoRF2 push state via RF2toMQTT"));
if (isDimCommand) { if (isDimCommand)
{
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2dimKey + String("/") + RF2periodKey + MQTTperiod; 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()); pub((char *)MQTTRF2string.c_str(), (char *)MQTTdimLevel.c_str());
} }
else { else
{
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod; MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod;
pub((char *)MQTTRF2string.c_str(), (char *)MQTTswitchType.c_str()); pub((char *)MQTTRF2string.c_str(), (char *)MQTTswitchType.c_str());
} }
@@ -213,12 +234,15 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
#endif #endif
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTtoRF2(char * topicOri, JsonObject& RF2data) { // json object decoding void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
{ // json object decoding
if (cmpToMainTopic(topicOri,subjectMQTTtoRF2)){ if (cmpToMainTopic(topicOri, subjectMQTTtoRF2))
{
trc(F("MQTTtoRF2 json")); trc(F("MQTTtoRF2 json"));
int boolSWITCHTYPE = RF2data["switchType"] | 99; int boolSWITCHTYPE = RF2data["switchType"] | 99;
if (boolSWITCHTYPE != 99) { if (boolSWITCHTYPE != 99)
{
trc(F("MQTTtoRF2 switch type ok")); trc(F("MQTTtoRF2 switch type ok"));
bool isDimCommand = boolSWITCHTYPE == 2; bool isDimCommand = boolSWITCHTYPE == 2;
unsigned long valueCODE = RF2data["address"]; unsigned long valueCODE = RF2data["address"];
@@ -226,11 +250,15 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
int valuePERIOD = RF2data["period"]; int valuePERIOD = RF2data["period"];
int valueGROUP = RF2data["group"]; int valueGROUP = RF2data["group"];
int valueDIM = RF2data["dim"] | -1; int valueDIM = RF2data["dim"] | -1;
if ((valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){ if ((valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0))
{
trc(F("MQTTtoRF2")); trc(F("MQTTtoRF2"));
if (valueCODE == 0) valueCODE = 8233378; if (valueCODE == 0)
if (valueUNIT == -1) valueUNIT = 0; valueCODE = 8233378;
if (valuePERIOD == 0) valuePERIOD = 272; if (valueUNIT == -1)
valueUNIT = 0;
if (valuePERIOD == 0)
valuePERIOD = 272;
trc(valueCODE); trc(valueCODE);
trc(valueUNIT); trc(valueUNIT);
trc(valuePERIOD); trc(valuePERIOD);
@@ -240,19 +268,25 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
NewRemoteReceiver::disable(); NewRemoteReceiver::disable();
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
trc(F("Sending")); trc(F("Sending"));
if (valueGROUP) { if (valueGROUP)
if (isDimCommand) { {
if (isDimCommand)
{
transmitter.sendGroupDim(valueDIM); transmitter.sendGroupDim(valueDIM);
} }
else { else
{
transmitter.sendGroup(boolSWITCHTYPE); transmitter.sendGroup(boolSWITCHTYPE);
} }
} }
else { else
if (isDimCommand) { {
if (isDimCommand)
{
transmitter.sendDim(valueUNIT, valueDIM); transmitter.sendDim(valueUNIT, valueDIM);
} }
else { else
{
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE); transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
} }
} }
@@ -262,7 +296,9 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
// Publish state change back to MQTT // Publish state change back to MQTT
pub(subjectGTWRF2toMQTT, RF2data); pub(subjectGTWRF2toMQTT, RF2data);
} }
}else{ }
else
{
trc(F("MQTTtoRF2 failed json read")); trc(F("MQTTtoRF2 failed json read"));
} }
} }
+50 -24
View File
@@ -40,7 +40,8 @@ char RadioConfig[128];
// vvvvvvvvv Global Configuration vvvvvvvvvvv // vvvvvvvvv Global Configuration vvvvvvvvvvv
struct _GLOBAL_CONFIG { struct _GLOBAL_CONFIG
{
uint32_t checksum; uint32_t checksum;
char rfmapname[32]; char rfmapname[32];
char encryptkey[16 + 1]; char encryptkey[16 + 1];
@@ -57,22 +58,26 @@ struct _GLOBAL_CONFIG {
struct _GLOBAL_CONFIG *pGC; struct _GLOBAL_CONFIG *pGC;
// vvvvvvvvv Global Configuration vvvvvvvvvvv // vvvvvvvvv Global Configuration vvvvvvvvvvv
uint32_t gc_checksum() { uint32_t gc_checksum()
{
uint8_t *p = (uint8_t *)pGC; uint8_t *p = (uint8_t *)pGC;
uint32_t checksum = 0; uint32_t checksum = 0;
p += sizeof(pGC->checksum); 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++; checksum += *p++;
} }
return checksum; return checksum;
} }
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
void eeprom_setup() { void eeprom_setup()
{
EEPROM.begin(4096); EEPROM.begin(4096);
pGC = (struct _GLOBAL_CONFIG *)EEPROM.getDataPtr(); pGC = (struct _GLOBAL_CONFIG *)EEPROM.getDataPtr();
// if checksum bad init GC else use GC values // if checksum bad init GC else use GC values
if (gc_checksum() != pGC->checksum) { if (gc_checksum() != pGC->checksum)
{
trc(F("Factory reset")); trc(F("Factory reset"));
memset(pGC, 0, sizeof(*pGC)); memset(pGC, 0, sizeof(*pGC));
strcpy_P(pGC->encryptkey, ENCRYPTKEY); strcpy_P(pGC->encryptkey, ENCRYPTKEY);
@@ -89,7 +94,8 @@ void eeprom_setup() {
RFM69 radio; RFM69 radio;
void setupRFM69(void) { void setupRFM69(void)
{
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
eeprom_setup(); eeprom_setup();
#endif #endif
@@ -106,15 +112,18 @@ void setupRFM69(void) {
trc(F("ZgatewayRFM69 initialization failed")); trc(F("ZgatewayRFM69 initialization failed"));
} }
if (GC_IS_RFM69HCW) { if (GC_IS_RFM69HCW)
{
radio.setHighPower(); // Only for RFM69HCW & HW! radio.setHighPower(); // Only for RFM69HCW & HW!
} }
radio.setPowerLevel(GC_POWER_LEVEL); // power output ranges from 0 (5dBm) to 31 (20dBm) 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")); trc(F("ZgatewayRFM69 Listening and transmitting at"));
switch (pGC->rfmfrequency) { switch (pGC->rfmfrequency)
{
case RF69_433MHZ: case RF69_433MHZ:
freq = 433; freq = 433;
break; break;
@@ -135,12 +144,14 @@ void setupRFM69(void) {
size_t len = snprintf_P(RadioConfig, sizeof(RadioConfig), JSONtemplate, size_t len = snprintf_P(RadioConfig, sizeof(RadioConfig), JSONtemplate,
freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL); freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL);
if (len >= sizeof(RadioConfig)) { if (len >= sizeof(RadioConfig))
{
trc(F("\n\n*** RFM69 config truncated ***\n")); 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) //check if something was received (could be an interrupt from the radio)
if (radio.receiveDone()) if (radio.receiveDone())
{ {
@@ -175,16 +186,19 @@ bool RFM69toMQTT(void) {
pub(buff, RFM69data); pub(buff, RFM69data);
return true; return true;
}
} else { else
{
return false; return false;
} }
} }
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoRFM69(char * topicOri, char * datacallback) { void MQTTtoRFM69(char *topicOri, char *datacallback)
{
if(cmpToMainTopic(topicOri,subjectMQTTtoRFM69)){ if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
trc(F("MQTTtoRFM69 data analysis")); trc(F("MQTTtoRFM69 data analysis"));
char data[RF69_MAX_DATA_LEN + 1]; char data[RF69_MAX_DATA_LEN + 1];
memcpy(data, (void *)datacallback, RF69_MAX_DATA_LEN); memcpy(data, (void *)datacallback, RF69_MAX_DATA_LEN);
@@ -194,43 +208,55 @@ bool RFM69toMQTT(void) {
String topic = topicOri; String topic = topicOri;
int valueRCV = defaultRFM69ReceiverId; //default receiver id value int valueRCV = defaultRFM69ReceiverId; //default receiver id value
int pos = topic.lastIndexOf(RFM69receiverKey); int pos = topic.lastIndexOf(RFM69receiverKey);
if (pos != -1){ if (pos != -1)
{
pos = pos + +strlen(RFM69receiverKey); pos = pos + +strlen(RFM69receiverKey);
valueRCV = (topic.substring(pos, pos + 3)).toInt(); valueRCV = (topic.substring(pos, pos + 3)).toInt();
trc(F("RFM69 receiver ID:")); trc(F("RFM69 receiver ID:"));
trc(valueRCV); trc(valueRCV);
} }
if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) { if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
{
trc(F(" OK ")); trc(F(" OK "));
// Acknowledgement to the GTWRF topic // Acknowledgement to the GTWRF topic
char buff[sizeof(subjectGTWRFM69toMQTT) + 4]; char buff[sizeof(subjectGTWRFM69toMQTT) + 4];
sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID); sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID);
pub(buff, data); pub(buff, data);
} else { }
else
{
trc(F("RFM69 sending failed")); trc(F("RFM69 sending failed"));
} }
} }
} }
#endif #endif
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTtoRFM69(char * topicOri, JsonObject& RFM69data) { void MQTTtoRFM69(char *topicOri, JsonObject &RFM69data)
{
if (cmpToMainTopic(topicOri,subjectMQTTtoRFM69)){ if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
const char *data = RFM69data["data"]; const char *data = RFM69data["data"];
trc(F("MQTTtoRFM69 json data analysis")); trc(F("MQTTtoRFM69 json data analysis"));
if(data){ if (data)
{
trc(F("MQTTtoRFM69 data ok")); trc(F("MQTTtoRFM69 data ok"));
int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value
trc(F("RFM69 receiver ID:")); trc(F("RFM69 receiver ID:"));
trc(valueRCV); trc(valueRCV);
if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) { if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
{
trc(F(" OK ")); trc(F(" OK "));
// Acknowledgement to the GTWRF topic // 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 pub(subjectGTWRFM69toMQTT, RFM69data); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} else { }
else
{
trc(F("MQTTtoRFM69 sending failed")); trc(F("MQTTtoRFM69 sending failed"));
} }
}else{ }
else
{
trc(F("MQTTtoRFM69 failed json read")); trc(F("MQTTtoRFM69 failed json read"));
} }
} }
+98 -48
View File
@@ -35,16 +35,19 @@
unsigned char _uartbuf[RF_MESSAGE_SIZE + 3] = {0}; unsigned char _uartbuf[RF_MESSAGE_SIZE + 3] = {0};
unsigned char _uartpos = 0; unsigned char _uartpos = 0;
void setupSRFB(){ void setupSRFB()
{
trc(F("ZgatewaySRFB setup done ")); trc(F("ZgatewaySRFB setup done "));
trc("Serial Baud" + String(SERIAL_BAUD)); trc("Serial Baud" + String(SERIAL_BAUD));
} }
void _rfbSend(byte * message) { void _rfbSend(byte *message)
{
Serial.println(); Serial.println();
Serial.write(RF_CODE_START); Serial.write(RF_CODE_START);
Serial.write(RF_CODE_RFOUT); Serial.write(RF_CODE_RFOUT);
for (unsigned char j=0; j<RF_MESSAGE_SIZE; j++) { for (unsigned char j = 0; j < RF_MESSAGE_SIZE; j++)
{
Serial.write(message[j]); Serial.write(message[j]);
} }
Serial.write(RF_CODE_STOP); Serial.write(RF_CODE_STOP);
@@ -52,55 +55,69 @@ void _rfbSend(byte * message) {
Serial.println(); Serial.println();
} }
void _rfbSend(byte * message, int times) { void _rfbSend(byte *message, int times)
{
char buffer[RF_MESSAGE_SIZE]; char buffer[RF_MESSAGE_SIZE];
_rfbToChar(message, buffer); _rfbToChar(message, buffer);
trc(F("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n")); trc(F("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n"));
for (int i=0; i<times; i++) { for (int i = 0; i < times; i++)
if (i>0) { {
if (i > 0)
{
unsigned long start = millis(); unsigned long start = millis();
while (millis() - start < RF_SEND_DELAY) delay(1); while (millis() - start < RF_SEND_DELAY)
delay(1);
} }
_rfbSend(message); _rfbSend(message);
} }
} }
bool SRFBtoMQTT() { bool SRFBtoMQTT()
{
static bool receiving = false; static bool receiving = false;
while (Serial.available()) { while (Serial.available())
{
yield(); yield();
byte c = Serial.read(); byte c = Serial.read();
if (receiving) { if (receiving)
if (c == RF_CODE_STOP) { {
if (c == RF_CODE_STOP)
{
_rfbDecode(); _rfbDecode();
receiving = false; receiving = false;
} else { }
else
{
_uartbuf[_uartpos++] = c; _uartbuf[_uartpos++] = c;
} }
} else if (c == RF_CODE_START) { }
else if (c == RF_CODE_START)
{
_uartpos = 0; _uartpos = 0;
receiving = true; receiving = true;
} }
} }
return receiving; return receiving;
} }
void _rfbDecode() { void _rfbDecode()
{
static unsigned long last = 0; static unsigned long last = 0;
if (millis() - last < RF_RECEIVE_DELAY) return; if (millis() - last < RF_RECEIVE_DELAY)
return;
last = millis(); last = millis();
byte action = _uartbuf[0]; byte action = _uartbuf[0];
char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0}; char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0};
if (action == RF_CODE_RFIN) { if (action == RF_CODE_RFIN)
{
_rfbToChar(&_uartbuf[1], buffer); _rfbToChar(&_uartbuf[1], buffer);
trc(F("Creating SRFB buffer")); trc(F("Creating SRFB buffer"));
@@ -128,12 +145,14 @@ void _rfbDecode() {
unsigned long MQTTvalue = (unsigned long)strtoul(val, NULL, 10); unsigned long MQTTvalue = (unsigned long)strtoul(val, NULL, 10);
SRFBdata.set("value", (unsigned long)MQTTvalue); SRFBdata.set("value", (unsigned long)MQTTvalue);
if (!isAduplicate(MQTTvalue) && MQTTvalue!=0) {// conditions to avoid duplications of RF -->MQTT if (!isAduplicate(MQTTvalue) && MQTTvalue != 0)
{ // conditions to avoid duplications of RF -->MQTT
trc(F("Adv data SRFBtoMQTT")); trc(F("Adv data SRFBtoMQTT"));
pub(subjectSRFBtoMQTT, SRFBdata); pub(subjectSRFBtoMQTT, SRFBdata);
trc(F("Store val")); trc(F("Store val"));
storeValue(MQTTvalue); storeValue(MQTTvalue);
if (repeatSRFBwMQTT){ if (repeatSRFBwMQTT)
{
trc(F("Publish SRFB for rpt")); trc(F("Publish SRFB for rpt"));
pub(subjectMQTTtoSRFB, SRFBdata); pub(subjectMQTTtoSRFB, SRFBdata);
} }
@@ -142,7 +161,8 @@ void _rfbDecode() {
} }
} }
void _rfbAck() { void _rfbAck()
{
trc(F("[RFBRIDGE] Sending ACK\n")); trc(F("[RFBRIDGE] Sending ACK\n"));
Serial.println(); Serial.println();
Serial.write(RF_CODE_START); Serial.write(RF_CODE_START);
@@ -155,10 +175,13 @@ void _rfbAck() {
/* /*
From an hexa char array ("A220EE...") to a byte array (half the size) From an hexa char array ("A220EE...") to a byte array (half the size)
*/ */
bool _rfbToArray(const char * in, byte * out) { bool _rfbToArray(const char *in, byte *out)
if (strlen(in) != RF_MESSAGE_SIZE * 2) return false; {
if (strlen(in) != RF_MESSAGE_SIZE * 2)
return false;
char tmp[3] = {0}; char tmp[3] = {0};
for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) { for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++)
{
memcpy(tmp, &in[p * 2], 2); memcpy(tmp, &in[p * 2], 2);
out[p] = strtol(tmp, NULL, 16); out[p] = strtol(tmp, NULL, 16);
} }
@@ -168,28 +191,33 @@ bool _rfbToArray(const char * in, byte * out) {
/* /*
From a byte array to an hexa char array ("A220EE...", double the size) From a byte array to an hexa char array ("A220EE...", double the size)
*/ */
bool _rfbToChar(byte * in, char * out) { bool _rfbToChar(byte *in, char *out)
for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) { {
for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++)
{
sprintf_P(&out[p * 2], PSTR("%02X"), in[p]); sprintf_P(&out[p * 2], PSTR("%02X"), in[p]);
} }
return true; return true;
} }
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoSRFB(char * topicOri, char * datacallback) { void MQTTtoSRFB(char *topicOri, char *datacallback)
{
// RF DATA ANALYSIS // RF DATA ANALYSIS
String topic = topicOri; String topic = topicOri;
int valueRPT = 0; int valueRPT = 0;
if (topic == subjectMQTTtoSRFB){ if (topic == subjectMQTTtoSRFB)
{
int valueMiniPLSL = 0; int valueMiniPLSL = 0;
int valueMaxiPLSL = 0; int valueMaxiPLSL = 0;
int valueSYNC = 0; int valueSYNC = 0;
int pos = topic.lastIndexOf(SRFBRptKey); int pos = topic.lastIndexOf(SRFBRptKey);
if (pos != -1){ if (pos != -1)
{
pos = pos + +strlen(SRFBRptKey); pos = pos + +strlen(SRFBRptKey);
valueRPT = (topic.substring(pos, pos + 1)).toInt(); valueRPT = (topic.substring(pos, pos + 1)).toInt();
trc(F("SRFB Repeat:")); trc(F("SRFB Repeat:"));
@@ -197,7 +225,8 @@ bool _rfbToChar(byte * in, char * out) {
} }
int pos2 = topic.lastIndexOf(SRFBminipulselengthKey); int pos2 = topic.lastIndexOf(SRFBminipulselengthKey);
if (pos2 != -1) { if (pos2 != -1)
{
pos2 = pos2 + strlen(SRFBminipulselengthKey); pos2 = pos2 + strlen(SRFBminipulselengthKey);
valueMiniPLSL = (topic.substring(pos2, pos2 + 3)).toInt(); valueMiniPLSL = (topic.substring(pos2, pos2 + 3)).toInt();
trc(F("RF Mini Pulse Lgth:")); trc(F("RF Mini Pulse Lgth:"));
@@ -205,7 +234,8 @@ bool _rfbToChar(byte * in, char * out) {
} }
int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey); int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey);
if (pos3 != -1){ if (pos3 != -1)
{
pos3 = pos3 + strlen(SRFBmaxipulselengthKey); pos3 = pos3 + strlen(SRFBmaxipulselengthKey);
valueMaxiPLSL = (topic.substring(pos3, pos3 + 2)).toInt(); valueMaxiPLSL = (topic.substring(pos3, pos3 + 2)).toInt();
trc(F("RF Maxi Pulse Lgth:")); trc(F("RF Maxi Pulse Lgth:"));
@@ -213,7 +243,8 @@ bool _rfbToChar(byte * in, char * out) {
} }
int pos4 = topic.lastIndexOf(SRFBsyncKey); int pos4 = topic.lastIndexOf(SRFBsyncKey);
if (pos4 != -1){ if (pos4 != -1)
{
pos4 = pos4 + strlen(SRFBsyncKey); pos4 = pos4 + strlen(SRFBsyncKey);
valueSYNC = (topic.substring(pos4, pos4 + 2)).toInt(); valueSYNC = (topic.substring(pos4, pos4 + 2)).toInt();
trc(F("RF sync:")); trc(F("RF sync:"));
@@ -221,10 +252,14 @@ bool _rfbToChar(byte * in, char * out) {
} }
trc(F("MQTTtoSRFB prts")); trc(F("MQTTtoSRFB prts"));
if (valueRPT == 0) valueRPT = 1; if (valueRPT == 0)
if (valueMiniPLSL == 0) valueMiniPLSL = 320; valueRPT = 1;
if (valueMaxiPLSL == 0) valueMaxiPLSL = 900; if (valueMiniPLSL == 0)
if (valueSYNC == 0) valueSYNC = 9500; valueMiniPLSL = 320;
if (valueMaxiPLSL == 0)
valueMaxiPLSL = 900;
if (valueSYNC == 0)
valueSYNC = 9500;
byte hex_valueMiniPLSL[2]; byte hex_valueMiniPLSL[2];
hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF); hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF);
@@ -255,16 +290,19 @@ bool _rfbToChar(byte * in, char * out) {
// Acknowledgement to the GTWRF topic // 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 pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} }
if (topic == subjectMQTTtoSRFBRaw){ if (topic == subjectMQTTtoSRFBRaw)
{
int pos = topic.lastIndexOf(SRFBRptKey); int pos = topic.lastIndexOf(SRFBRptKey);
if (pos != -1){ if (pos != -1)
{
pos = pos + +strlen(SRFBRptKey); pos = pos + +strlen(SRFBRptKey);
valueRPT = (topic.substring(pos, pos + 1)).toInt(); valueRPT = (topic.substring(pos, pos + 1)).toInt();
trc(F("SRFB Repeat:")); trc(F("SRFB Repeat:"));
trc(valueRPT); trc(valueRPT);
} }
if (valueRPT == 0) valueRPT = 1; if (valueRPT == 0)
valueRPT = 1;
byte message_b[RF_MESSAGE_SIZE]; byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(datacallback, message_b); _rfbToArray(datacallback, message_b);
@@ -275,30 +313,40 @@ bool _rfbToChar(byte * in, char * out) {
} }
#endif #endif
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTtoSRFB(char * topicOri, JsonObject& SRFBdata) { void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata)
{
// RF DATA ANALYSIS // RF DATA ANALYSIS
const char *raw = SRFBdata["raw"]; const char *raw = SRFBdata["raw"];
int valueRPT = SRFBdata["repeat"] | 1; int valueRPT = SRFBdata["repeat"] | 1;
if (cmpToMainTopic(topicOri,subjectMQTTtoSRFB)){ if (cmpToMainTopic(topicOri, subjectMQTTtoSRFB))
{
trc(F("MQTTtoSRFB json")); trc(F("MQTTtoSRFB json"));
if (raw){ // send raw in priority when defined in the json if (raw)
{ // send raw in priority when defined in the json
trc(F("MQTTtoSRFB raw ok")); trc(F("MQTTtoSRFB raw ok"));
byte message_b[RF_MESSAGE_SIZE]; byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(raw, message_b); _rfbToArray(raw, message_b);
_rfbSend(message_b, valueRPT); _rfbSend(message_b, valueRPT);
}else{ }
else
{
unsigned long data = SRFBdata["value"]; unsigned long data = SRFBdata["value"];
if (data != 0) { if (data != 0)
{
trc(F("MQTTtoSRFB data ok")); trc(F("MQTTtoSRFB data ok"));
int valueMiniPLSL = SRFBdata["val_Tlow"]; int valueMiniPLSL = SRFBdata["val_Tlow"];
int valueMaxiPLSL = SRFBdata["val_Thigh"]; int valueMaxiPLSL = SRFBdata["val_Thigh"];
int valueSYNC = SRFBdata["delay"]; int valueSYNC = SRFBdata["delay"];
if (valueRPT == 0) valueRPT = 1; if (valueRPT == 0)
if (valueMiniPLSL == 0) valueMiniPLSL = 320; valueRPT = 1;
if (valueMaxiPLSL == 0) valueMaxiPLSL = 900; if (valueMiniPLSL == 0)
if (valueSYNC == 0) valueSYNC = 9500; valueMiniPLSL = 320;
if (valueMaxiPLSL == 0)
valueMaxiPLSL = 900;
if (valueSYNC == 0)
valueSYNC = 9500;
byte hex_valueMiniPLSL[2]; byte hex_valueMiniPLSL[2];
hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF); hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF);
@@ -328,7 +376,9 @@ bool _rfbToChar(byte * in, char * out) {
_rfbSend(message_b, valueRPT); _rfbSend(message_b, valueRPT);
// Acknowledgement to the GTWRF topic // 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 pub(subjectGTWSRFBtoMQTT, SRFBdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{ }
else
{
trc(F("MQTTtoSRFB error decoding value")); trc(F("MQTTtoSRFB error decoding value"));
} }
} }
+31 -18
View File
@@ -67,16 +67,25 @@ void createDiscovery(char * sensor_type,
sensor.set("name", s_name); //name sensor.set("name", s_name); //name
sensor.set("uniq_id", unique_id); //unique_id sensor.set("uniq_id", unique_id); //unique_id
if (device_class[0]) sensor.set("dev_cla", device_class); //device_class if (device_class[0])
if (value_template[0]) sensor.set("val_tpl", value_template); //value_template sensor.set("dev_cla", device_class); //device_class
if (payload_on[0]) sensor.set("pl_on", payload_on); // payload_on if (value_template[0])
if (payload_off[0]) sensor.set("pl_off", payload_off); //payload_off sensor.set("val_tpl", value_template); //value_template
if (unit_of_meas[0]) sensor.set("unit_of_meas", unit_of_meas); //unit_of_measurement*/ if (payload_on[0])
if (off_delay != 0) sensor.set("off_delay", off_delay); //off_delay sensor.set("pl_on", payload_on); // payload_on
if (payload_available[0]) sensor.set("pl_avail", payload_available); // payload_on if (payload_off[0])
if (payload_not_avalaible[0]) sensor.set("pl_not_avail", payload_not_avalaible); //payload_off 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]) { if (cmd_topic[0])
{
char command_topic[mqtt_topic_max_size]; char command_topic[mqtt_topic_max_size];
strcpy(command_topic, mqtt_topic); strcpy(command_topic, mqtt_topic);
strcat(command_topic, cmd_topic); strcat(command_topic, cmd_topic);
@@ -91,7 +100,8 @@ void createDiscovery(char * sensor_type,
json_attributes.add("SSID"); json_attributes.add("SSID");
}*/ }*/
if (child_device){ if (child_device)
{
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(2); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(2);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonDeviceBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonDeviceBuffer;
JsonObject &device = jsonDeviceBuffer.createObject(); JsonObject &device = jsonDeviceBuffer.createObject();
@@ -130,7 +140,8 @@ void pubMqttDiscovery()
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<BMEparametersCount;i++){ for (int i = 0; i < BMEparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(BMEsensor[i][1]); trc(BMEsensor[i][1]);
createDiscovery(BMEsensor[i][0], createDiscovery(BMEsensor[i][0],
@@ -146,10 +157,10 @@ void pubMqttDiscovery()
trc(F("DHTDiscovery")); trc(F("DHTDiscovery"));
char *DHTsensor[DHTparametersCount][8] = { char *DHTsensor[DHTparametersCount][8] = {
{"sensor", "tempc", "dht", "temperature", "{{ value_json.temp }}", "", "", "°C"}, {"sensor", "tempc", "dht", "temperature", "{{ value_json.temp }}", "", "", "°C"},
{"sensor", "hum", "dht", "humidity","{{ value_json.hum }}","", "", "%"} {"sensor", "hum", "dht", "humidity", "{{ value_json.hum }}", "", "", "%"}};
};
for (int i=0;i<DHTparametersCount;i++){ for (int i = 0; i < DHTparametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(DHTsensor[i][1]); trc(DHTsensor[i][1]);
createDiscovery(DHTsensor[i][0], createDiscovery(DHTsensor[i][0],
@@ -184,7 +195,8 @@ void pubMqttDiscovery()
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<BH1750parametersCount;i++){ for (int i = 0; i < BH1750parametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(BH1750sensor[i][1]); trc(BH1750sensor[i][1]);
createDiscovery(BH1750sensor[i][0], createDiscovery(BH1750sensor[i][0],
@@ -205,7 +217,8 @@ void pubMqttDiscovery()
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<TSL2561parametersCount;i++){ for (int i = 0; i < TSL2561parametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(TSL2561sensor[i][1]); trc(TSL2561sensor[i][1]);
createDiscovery(TSL2561sensor[i][0], createDiscovery(TSL2561sensor[i][0],
@@ -254,7 +267,8 @@ void pubMqttDiscovery()
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
}; };
for (int i=0;i<INA226parametersCount;i++){ for (int i = 0; i < INA226parametersCount; i++)
{
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(INA226sensor[i][1]); trc(INA226sensor[i][1]);
createDiscovery(INA226sensor[i][0], createDiscovery(INA226sensor[i][0],
@@ -279,7 +293,6 @@ void pubMqttDiscovery()
0, "", "", true, subjectMQTTtoONOFF); 0, "", "", true, subjectMQTTtoONOFF);
#endif #endif
#ifdef ZgatewayRF #ifdef ZgatewayRF
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewayRFDiscovery")); trc(F("gatewayRFDiscovery"));
+11 -5
View File
@@ -37,18 +37,24 @@
//Time used to wait for an interval before resending adc value //Time used to wait for an interval before resending adc value
unsigned long timeadc = 0; unsigned long timeadc = 0;
void MeasureADC(){ void MeasureADC()
if (millis() > (timeadc + TimeBetweenReadingADC)) {//retriving value of temperature and humidity of the box from DHT every xUL {
if (millis() > (timeadc + TimeBetweenReadingADC))
{ //retriving value of temperature and humidity of the box from DHT every xUL
#if defined(ESP8266) #if defined(ESP8266)
yield(); yield();
#endif #endif
timeadc = millis(); timeadc = millis();
static int persistedadc; static int persistedadc;
int val = analogRead(ADC_PIN); int val = analogRead(ADC_PIN);
if (isnan(val)) { if (isnan(val))
{
trc(F("Failed to read from ADC !")); 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")); trc(F("Creating ADC buffer"));
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
+24 -10
View File
@@ -54,7 +54,8 @@ void setupZsensorBH1750()
// void loop() // void loop()
void MeasureLightIntensity() 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")); trc(F("Creating BH1750 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &BH1750data = jsonBuffer.createObject(); JsonObject &BH1750data = jsonBuffer.createObject();
@@ -70,9 +71,12 @@ void MeasureLightIntensity()
// Check if reads failed and exit early (to try again). // Check if reads failed and exit early (to try again).
Wire.requestFrom(BH1750_i2c_addr, 2); Wire.requestFrom(BH1750_i2c_addr, 2);
if(Wire.available() != 2) { if (Wire.available() != 2)
{
trc(F("Failed to read from LightSensor BH1750!")); trc(F("Failed to read from LightSensor BH1750!"));
}else{ }
else
{
i = Wire.read(); i = Wire.read();
i <<= 8; i <<= 8;
i |= Wire.read(); i |= Wire.read();
@@ -83,26 +87,36 @@ void MeasureLightIntensity()
Wattsm2 = Lux / 683.0; Wattsm2 = Lux / 683.0;
// Generate Lux // Generate Lux
if(Lux != persistedll || bh1750_always){ if (Lux != persistedll || bh1750_always)
{
BH1750data.set("lux", (unsigned int)Lux); BH1750data.set("lux", (unsigned int)Lux);
}else{ }
else
{
trc(F("Same lux don't send it")); trc(F("Same lux don't send it"));
} }
// Generate FtCd // Generate FtCd
if(ftcd != persistedlf || bh1750_always){ if (ftcd != persistedlf || bh1750_always)
{
BH1750data.set("ftcd", (unsigned int)ftcd); BH1750data.set("ftcd", (unsigned int)ftcd);
}else{ }
else
{
trc(F("Same ftcd don't send it")); trc(F("Same ftcd don't send it"));
} }
// Generate Watts/m2 // Generate Watts/m2
if(Wattsm2 != persistedlw || bh1750_always){ if (Wattsm2 != persistedlw || bh1750_always)
{
BH1750data.set("wattsm2", (unsigned int)Wattsm2); BH1750data.set("wattsm2", (unsigned int)Wattsm2);
}else{ }
else
{
trc(F("Same wattsm2 don't send it")); trc(F("Same wattsm2 don't send it"));
} }
if(BH1750data.size()>0) pub(subjectBH1750toMQTT,BH1750data); if (BH1750data.size() > 0)
pub(subjectBH1750toMQTT, BH1750data);
} }
persistedll = Lux; persistedll = Lux;
persistedlf = ftcd; persistedlf = ftcd;
+39 -17
View File
@@ -108,7 +108,8 @@ void setupZsensorBME280()
void MeasureTempHumAndPressure() void MeasureTempHumAndPressure()
{ {
if (millis() > (timebme280 + TimeBetweenReadingbme280)) { if (millis() > (timebme280 + TimeBetweenReadingbme280))
{
timebme280 = millis(); timebme280 = millis();
static float persisted_bme_tempc; static float persisted_bme_tempc;
@@ -126,55 +127,77 @@ void MeasureTempHumAndPressure()
float BmeAltiFt = mySensor.readFloatAltitudeFeet(); float BmeAltiFt = mySensor.readFloatAltitudeFeet();
// Check if reads failed and exit early (to try again). // 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!")); trc(F("Failed to read from Weather Sensor BME280!"));
}else{ }
else
{
trc(F("Creating BME280 buffer")); trc(F("Creating BME280 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &BME280data = jsonBuffer.createObject(); JsonObject &BME280data = jsonBuffer.createObject();
// Generate Temperature in degrees C // Generate Temperature in degrees C
if(BmeTempC != persisted_bme_tempc || bme280_always){ if (BmeTempC != persisted_bme_tempc || bme280_always)
{
BME280data.set("tempc", (float)BmeTempC); BME280data.set("tempc", (float)BmeTempC);
}else{ }
else
{
trc(F("Same Degrees C don't send it")); trc(F("Same Degrees C don't send it"));
} }
// Generate Temperature in degrees F // Generate Temperature in degrees F
if(BmeTempF != persisted_bme_tempf || bme280_always){ if (BmeTempF != persisted_bme_tempf || bme280_always)
{
BME280data.set("tempf", (float)BmeTempF); BME280data.set("tempf", (float)BmeTempF);
}else{ }
else
{
trc(F("Same Degrees F don't send it")); trc(F("Same Degrees F don't send it"));
} }
// Generate Humidity in percent // Generate Humidity in percent
if(BmeHum != persisted_bme_hum || bme280_always){ if (BmeHum != persisted_bme_hum || bme280_always)
{
BME280data.set("hum", (float)BmeHum); BME280data.set("hum", (float)BmeHum);
}else{ }
else
{
trc(F("Same Humidity don't send it")); trc(F("Same Humidity don't send it"));
} }
// Generate Pressure in Pa // Generate Pressure in Pa
if(BmePa != persisted_bme_pa || bme280_always){ if (BmePa != persisted_bme_pa || bme280_always)
{
BME280data.set("pa", (float)BmePa); BME280data.set("pa", (float)BmePa);
}else{ }
else
{
trc(F("Same Pressure don't send it")); trc(F("Same Pressure don't send it"));
} }
// Generate Altitude in Meter // 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")); trc(F("Sending Altitude Meter to MQTT"));
BME280data.set("altim", (float)BmeAltiM); BME280data.set("altim", (float)BmeAltiM);
}else{ }
else
{
trc(F("Same Altitude Meter don't send it")); trc(F("Same Altitude Meter don't send it"));
} }
// Generate Altitude in Feet // Generate Altitude in Feet
if(BmeAltiFt != persisted_bme_altift || bme280_always){ if (BmeAltiFt != persisted_bme_altift || bme280_always)
{
BME280data.set("altift", (float)BmeAltiFt); BME280data.set("altift", (float)BmeAltiFt);
}else{ }
else
{
trc(F("Same Altitude Feet don't send it")); 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_tempc = BmeTempC;
persisted_bme_tempf = BmeTempF; persisted_bme_tempf = BmeTempF;
@@ -182,7 +205,6 @@ void MeasureTempHumAndPressure()
persisted_bme_pa = BmePa; persisted_bme_pa = BmePa;
persisted_bme_altim = BmeAltiM; persisted_bme_altim = BmeAltiM;
persisted_bme_altift = BmeAltiFt; persisted_bme_altift = BmeAltiFt;
} }
} }
+21 -9
View File
@@ -38,8 +38,10 @@ DHT dht(DHT_RECEIVER_PIN,DHT_SENSOR_TYPE);
//Time used to wait for an interval before resending temp and hum //Time used to wait for an interval before resending temp and hum
unsigned long timedht = 0; unsigned long timedht = 0;
void MeasureTempAndHum(){ void MeasureTempAndHum()
if (millis() > (timedht + TimeBetweenReadingDHT)) {//retriving value of temperature and humidity of the box from DHT every xUL {
if (millis() > (timedht + TimeBetweenReadingDHT))
{ //retriving value of temperature and humidity of the box from DHT every xUL
timedht = millis(); timedht = millis();
static float persistedh; static float persistedh;
static float persistedt; static float persistedt;
@@ -47,23 +49,33 @@ void MeasureTempAndHum(){
// Read temperature as Celsius (the default) // 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). // 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!")); trc(F("Failed to read from DHT sensor!"));
}else{ }
else
{
trc(F("Creating DHT buffer")); trc(F("Creating DHT buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &DHTdata = jsonBuffer.createObject(); JsonObject &DHTdata = jsonBuffer.createObject();
if(h != persistedh || dht_always){ if (h != persistedh || dht_always)
{
DHTdata.set("hum", (float)h); DHTdata.set("hum", (float)h);
}else{ }
else
{
trc(F("Same hum don't send it")); trc(F("Same hum don't send it"));
} }
if(t != persistedt || dht_always){ if (t != persistedt || dht_always)
{
DHTdata.set("temp", (float)t); DHTdata.set("temp", (float)t);
}else{ }
else
{
trc(F("Same temp don't send it")); trc(F("Same temp don't send it"));
} }
if(DHTdata.size()>0) pub(DHTTOPIC,DHTdata); if (DHTdata.size() > 0)
pub(DHTTOPIC, DHTdata);
} }
persistedh = h; persistedh = h;
persistedt = t; persistedt = t;
+16 -11
View File
@@ -34,12 +34,13 @@ unsigned long lastDebounceTime = 0;
int InputState = 3; // Set to 3 so that it reads on startup int InputState = 3; // Set to 3 so that it reads on startup
int lastInputState = 3; int lastInputState = 3;
void setupGPIOInput()
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 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); int reading = digitalRead(GPIOInput_PIN);
// check to see if you just pressed the button // check to see if you just pressed the button
@@ -47,41 +48,45 @@ void MeasureGPIOInput(){
// since the last press to ignore any noise: // since the last press to ignore any noise:
// If the switch changed, due to noise or pressing: // If the switch changed, due to noise or pressing:
if (reading != lastInputState) { if (reading != lastInputState)
{
// reset the debouncing timer // reset the debouncing timer
lastDebounceTime = millis(); lastDebounceTime = millis();
} }
if ((millis() - lastDebounceTime) > GPIOInputDebounceDelay) { if ((millis() - lastDebounceTime) > GPIOInputDebounceDelay)
{
// whatever the reading is at, it's been there for longer than the debounce // whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state: // delay, so take it as the actual current state:
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
yield(); yield();
#endif #endif
// if the Input state has changed: // if the Input state has changed:
if (reading != InputState) { if (reading != InputState)
{
InputState = reading; InputState = reading;
trc(F("Creating GPIOInput buffer")); trc(F("Creating GPIOInput buffer"));
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &GPIOdata = jsonBuffer.createObject(); JsonObject &GPIOdata = jsonBuffer.createObject();
if (InputState == HIGH) { if (InputState == HIGH)
{
trc(F("GPIO HIGH")); trc(F("GPIO HIGH"));
pub(subjectGPIOInputtoMQTT, "HIGH"); pub(subjectGPIOInputtoMQTT, "HIGH");
GPIOdata.set("gpio", "HIGH"); GPIOdata.set("gpio", "HIGH");
} }
if (InputState == LOW) { if (InputState == LOW)
{
trc(F("GPIO LOW")); trc(F("GPIO LOW"));
GPIOdata.set("gpio", "LOW"); GPIOdata.set("gpio", "LOW");
pub(subjectGPIOInputtoMQTT, "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: // save the reading. Next time through the loop, it'll be the lastInputState:
lastInputState = reading; lastInputState = reading;
} }
#endif #endif
+9 -7
View File
@@ -31,7 +31,8 @@ int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on st
int lastInputStateGPIOKeyCode = 0x0f; int lastInputStateGPIOKeyCode = 0x0f;
int lastLatchStateGPIOKeyCode = 0; int lastLatchStateGPIOKeyCode = 0;
void setupGPIOKeyCode() { void setupGPIOKeyCode()
{
pinMode(GPIOKeyCode_LATCH_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_LATCH_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); //
@@ -39,7 +40,8 @@ void setupGPIOKeyCode() {
//pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); // //pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); //
} }
void MeasureGPIOKeyCode(){ void MeasureGPIOKeyCode()
{
int latch = digitalRead(GPIOKeyCode_LATCH_PIN); int latch = digitalRead(GPIOKeyCode_LATCH_PIN);
@@ -54,10 +56,9 @@ void MeasureGPIOKeyCode(){
yield(); yield();
#endif #endif
// if the Input state has changed: // if the Input state has changed:
if (latch > 0 && lastLatchStateGPIOKeyCode != latch) { if (latch > 0 && lastLatchStateGPIOKeyCode != latch)
int reading = digitalRead(GPIOKeyCode_D0_PIN) {
| (digitalRead(GPIOKeyCode_D1_PIN) << 1) int reading = digitalRead(GPIOKeyCode_D0_PIN) | (digitalRead(GPIOKeyCode_D1_PIN) << 1) | (digitalRead(GPIOKeyCode_D2_PIN) << 2);
| (digitalRead(GPIOKeyCode_D2_PIN) << 2);
//| digitalRead(GPIOKeyCode_D3_PIN) << 3; //| digitalRead(GPIOKeyCode_D3_PIN) << 3;
char hex[3]; char hex[3];
@@ -70,7 +71,8 @@ void MeasureGPIOKeyCode(){
lastLatchStateGPIOKeyCode = latch; lastLatchStateGPIOKeyCode = latch;
} }
if (latch != lastLatchStateGPIOKeyCode) { if (latch != lastLatchStateGPIOKeyCode)
{
lastLatchStateGPIOKeyCode = latch; lastLatchStateGPIOKeyCode = latch;
Serial.printf("GPIOKeyCode latch %d\n", latch); Serial.printf("GPIOKeyCode latch %d\n", latch);
if (latch == 0) if (latch == 0)
+21 -9
View File
@@ -33,13 +33,16 @@
unsigned long timeHCSR04 = 0; unsigned long timeHCSR04 = 0;
void setupHCSR04() { void setupHCSR04()
{
pinMode(HCSR04_TRI_PIN, OUTPUT); // declare HC SR-04 trigger pin as output pinMode(HCSR04_TRI_PIN, OUTPUT); // declare HC SR-04 trigger pin as output
pinMode(HCSR04_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input pinMode(HCSR04_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input
} }
void MeasureDistance() { void MeasureDistance()
if (millis() > (timeHCSR04 + TimeBetweenReadingHCSR04)) { {
if (millis() > (timeHCSR04 + TimeBetweenReadingHCSR04))
{
timeHCSR04 = millis(); timeHCSR04 = millis();
trc(F("Creating HCSR04 buffer")); trc(F("Creating HCSR04 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
@@ -50,24 +53,33 @@ void MeasureDistance() {
delayMicroseconds(10); delayMicroseconds(10);
digitalWrite(HCSR04_TRI_PIN, LOW); digitalWrite(HCSR04_TRI_PIN, LOW);
unsigned long duration = pulseIn(HCSR04_ECH_PIN, HIGH); unsigned long duration = pulseIn(HCSR04_ECH_PIN, HIGH);
if (isnan(duration)) { if (isnan(duration))
{
trc(F("Failed to read from HC SR04 sensor!")); trc(F("Failed to read from HC SR04 sensor!"));
} else { }
else
{
static unsigned int distance = 99999; static unsigned int distance = 99999;
unsigned int d = duration / 58.2; unsigned int d = duration / 58.2;
HCSR04data.set("distance", (int)d); HCSR04data.set("distance", (int)d);
if (d > distance) { if (d > distance)
{
HCSR04data.set("direction", "away"); HCSR04data.set("direction", "away");
trc(F("HC SR04 Distance changed")); trc(F("HC SR04 Distance changed"));
} else if (d < distance) { }
else if (d < distance)
{
HCSR04data.set("direction", "towards"); HCSR04data.set("direction", "towards");
trc(F("HC SR04 Distance changed")); trc(F("HC SR04 Distance changed"));
} else if (HCSR04_always) { }
else if (HCSR04_always)
{
HCSR04data.set("direction", "static"); HCSR04data.set("direction", "static");
trc(F("HC SR04 Distance hasn't changed")); trc(F("HC SR04 Distance hasn't changed"));
} }
distance = d; distance = d;
if(HCSR04data.size()>0) pub(subjectHCSR04,HCSR04data); if (HCSR04data.size() > 0)
pub(subjectHCSR04, HCSR04data);
} }
} }
} }
+17 -8
View File
@@ -30,12 +30,15 @@
#ifdef ZsensorHCSR501 #ifdef ZsensorHCSR501
void setupHCSR501() { void setupHCSR501()
{
pinMode(HCSR501_PIN, INPUT); // declare HC SR-501 pin as input pinMode(HCSR501_PIN, INPUT); // declare HC SR-501 pin as input
} }
void MeasureHCSR501(){ void MeasureHCSR501()
if (millis() > TimeBeforeStartHCSR501) {//let time to init the PIR sensor {
if (millis() > TimeBeforeStartHCSR501)
{ //let time to init the PIR sensor
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &HCSR501data = jsonBuffer.createObject(); JsonObject &HCSR501data = jsonBuffer.createObject();
@@ -44,22 +47,28 @@ void MeasureHCSR501(){
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
yield(); yield();
#endif #endif
if (PresenceValue == HIGH) { if (PresenceValue == HIGH)
if (pirState == LOW) { {
if (pirState == LOW)
{
//turned on //turned on
HCSR501data.set("hcsr501", "true"); HCSR501data.set("hcsr501", "true");
trc(F("HC SR501 Motion started")); trc(F("HC SR501 Motion started"));
pirState = HIGH; pirState = HIGH;
} }
} else { }
if (pirState == HIGH){ else
{
if (pirState == HIGH)
{
// turned off // turned off
HCSR501data.set("hcsr501", "false"); HCSR501data.set("hcsr501", "false");
trc(F("HC SR501 Motion ended")); trc(F("HC SR501 Motion ended"));
pirState = LOW; pirState = LOW;
} }
} }
if(HCSR501data.size()>0) pub(subjectHCSR501toMQTT,HCSR501data); if (HCSR501data.size() > 0)
pub(subjectHCSR501toMQTT, HCSR501data);
} }
} }
#endif #endif
+16 -8
View File
@@ -43,14 +43,17 @@ const int INA226_ADDR = 0x40; // A0 und A1 auf GND > Adresse 40 Hex auf Seite 18
//Time used to wait for an interval before resending temp and hum //Time used to wait for an interval before resending temp and hum
unsigned long timeINA226 = 0; unsigned long timeINA226 = 0;
void setupINA226() { void setupINA226()
{
Wire.begin(); Wire.begin();
// Configuration Register Standard Einstellung 0x4127, hier aber 16 Werte Mitteln > 0x4427 // 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 writeRegister(0x00, 0x4427); // 1.1ms Volt und Strom A/D-Wandlung, Shunt und VBus continous
} }
void MeasureINA226(){ void MeasureINA226()
if (millis() > (timeINA226 + TimeBetweenReadingINA226)) {//retriving value of temperature and humidity of the box from DHT every xUL {
if (millis() > (timeINA226 + TimeBetweenReadingINA226))
{ //retriving value of temperature and humidity of the box from DHT every xUL
timeINA226 = millis(); timeINA226 = millis();
trc(F("Creating INA226 buffer")); trc(F("Creating INA226 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
@@ -64,7 +67,8 @@ void MeasureINA226(){
trc(F(" V, Current: ")); trc(F(" V, Current: "));
// Seite 24: Shunt Spannung +- 81,92mV mit 16 Bit, LSB 2,5uV // Seite 24: Shunt Spannung +- 81,92mV mit 16 Bit, LSB 2,5uV
int shuntvolt = readRegister(0x01); int shuntvolt = readRegister(0x01);
if (shuntvolt && 0x8000) {// eine negative Zahl? Dann 2er Komplement bilden if (shuntvolt && 0x8000)
{ // eine negative Zahl? Dann 2er Komplement bilden
shuntvolt = ~shuntvolt; // alle Bits invertieren shuntvolt = ~shuntvolt; // alle Bits invertieren
shuntvolt += 1; // 1 dazuzählen shuntvolt += 1; // 1 dazuzählen
shuntvolt *= -1; // negativ machen shuntvolt *= -1; // negativ machen
@@ -89,7 +93,8 @@ void MeasureINA226(){
} }
} }
static void writeRegister(byte reg, word value) { static void writeRegister(byte reg, word value)
{
Wire.beginTransmission(INA226_ADDR); Wire.beginTransmission(INA226_ADDR);
Wire.write(reg); Wire.write(reg);
Wire.write((value >> 8) & 0xFF); Wire.write((value >> 8) & 0xFF);
@@ -97,12 +102,15 @@ static void writeRegister(byte reg, word value) {
Wire.endTransmission(); Wire.endTransmission();
} }
static word readRegister(byte reg) { static word readRegister(byte reg)
{
word res = 0x0000; word res = 0x0000;
Wire.beginTransmission(INA226_ADDR); Wire.beginTransmission(INA226_ADDR);
Wire.write(reg); Wire.write(reg);
if (Wire.endTransmission() == 0) { if (Wire.endTransmission() == 0)
if (Wire.requestFrom(INA226_ADDR, 2) >= 2) { {
if (Wire.requestFrom(INA226_ADDR, 2) >= 2)
{
res = Wire.read() * 256; res = Wire.read() * 256;
res += Wire.read(); res += Wire.read();
} }
+10 -4
View File
@@ -88,7 +88,8 @@ void setupZsensorTSL2561()
void MeasureLightIntensityTSL2561() void MeasureLightIntensityTSL2561()
{ {
if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) { if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561))
{
static uint32_t persisted_lux; static uint32_t persisted_lux;
timetsl2561 = millis(); timetsl2561 = millis();
@@ -101,7 +102,8 @@ void MeasureLightIntensityTSL2561()
if (event.light) 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("lux", (float)event.light);
@@ -109,10 +111,14 @@ void MeasureLightIntensityTSL2561()
TSL2561data.set("wattsm2", (float)(event.light) / 683.0); TSL2561data.set("wattsm2", (float)(event.light) / 683.0);
pub(subjectTSL12561toMQTT, TSL2561data); pub(subjectTSL12561toMQTT, TSL2561data);
} else { }
else
{
trc(F("Same lux value, do not send")); trc(F("Same lux value, do not send"));
} }
} else { }
else
{
trc(F("Failed to read from TSL2561")); trc(F("Failed to read from TSL2561"));
} }
} }
+297 -161
View File
@@ -45,9 +45,6 @@
#if defined(ZgatewayRF) || defined(ZgatewayRF2) || defined(ZgatewayPilight) #if defined(ZgatewayRF) || defined(ZgatewayRF2) || defined(ZgatewayPilight)
#include "config_RF.h" #include "config_RF.h"
#endif #endif
#ifdef ZgatewayRF315
#include "config_RF315.h"
#endif
#ifdef ZgatewayLORA #ifdef ZgatewayLORA
#include "config_LORA.h" #include "config_LORA.h"
#endif #endif
@@ -149,32 +146,44 @@ PubSubClient client(eClient);
unsigned long lastMQTTReconnectAttempt = 0; unsigned long lastMQTTReconnectAttempt = 0;
unsigned long lastNTWKReconnectAttempt = 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 //reverting array 2 by 2 to get the data in good order
int i = l - 2, j = 0; int i = l - 2, j = 0;
while ( i != -2 ) { while (i != -2)
if (i%2 == 0) out[j] = in[i+1]; {
else out[j] = in[i-1]; if (i % 2 == 0)
out[j] = in[i + 1];
else
out[j] = in[i - 1];
j++; j++;
i--; 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){ void extract_char(char *token_char, char *subset, int start, int l, bool reverse, bool isNumber)
{
char tmp_subset[l + 1]; char tmp_subset[l + 1];
memcpy(tmp_subset, &token_char[start], l); memcpy(tmp_subset, &token_char[start], l);
tmp_subset[l] = '\0'; tmp_subset[l] = '\0';
if (isNumber){ if (isNumber)
{
char tmp_subset2[l + 1]; char tmp_subset2[l + 1];
if (reverse) revert_hex_data(tmp_subset, tmp_subset2, l+1); if (reverse)
else strncpy( tmp_subset2, tmp_subset , l+1); 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); long long_value = strtoul(tmp_subset2, NULL, 16);
sprintf(tmp_subset2, "%ld", long_value); sprintf(tmp_subset2, "%ld", long_value);
strncpy(subset, tmp_subset2, l + 1); strncpy(subset, tmp_subset2, l + 1);
}else{ }
if (reverse) revert_hex_data(tmp_subset, subset, l+1); else
else strncpy( subset, tmp_subset , l+1); {
if (reverse)
revert_hex_data(tmp_subset, subset, l + 1);
else
strncpy(subset, tmp_subset, l + 1);
} }
subset[l] = '\0'; subset[l] = '\0';
} }
@@ -187,18 +196,21 @@ int strpos(char *haystack, char *needle) //from @miere https://stackoverflow.com
return -1; 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]; static char a[16];
sprintf(a, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); sprintf(a, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return a; return a;
} }
bool to_bool(String const& s) { // thanks Chris Jester-Young from stackoverflow bool to_bool(String const &s)
{ // thanks Chris Jester-Young from stackoverflow
return s != "0"; return s != "0";
} }
//trace //trace
void trc(String msg){ void trc(String msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -208,7 +220,8 @@ void trc(String msg){
#endif #endif
} }
void trc(int msg){ void trc(int msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -218,7 +231,8 @@ void trc(int msg){
#endif #endif
} }
void trc(unsigned int msg){ void trc(unsigned int msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -228,7 +242,8 @@ void trc(unsigned int msg){
#endif #endif
} }
void trc(long msg){ void trc(long msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -238,7 +253,8 @@ void trc(long msg){
#endif #endif
} }
void trc(unsigned long msg){ void trc(unsigned long msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -248,7 +264,8 @@ void trc(unsigned long msg){
#endif #endif
} }
void trc(double msg){ void trc(double msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -258,7 +275,8 @@ void trc(double msg){
#endif #endif
} }
void trc(float msg){ void trc(float msg)
{
#ifdef TRACE #ifdef TRACE
Serial.println(msg); Serial.println(msg);
digitalWrite(led_info, HIGH); digitalWrite(led_info, HIGH);
@@ -268,24 +286,29 @@ void trc(float msg){
#endif #endif
} }
void trc(JsonObject& data){ void trc(JsonObject &data)
{
char JSONmessageBuffer[JSON_MSG_BUFFER]; char JSONmessageBuffer[JSON_MSG_BUFFER];
data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
trc(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); String topic = String(mqtt_topic) + String(topicori);
client.publish((char *)topic.c_str(), payload, retainFlag); client.publish((char *)topic.c_str(), payload, retainFlag);
} }
void pub(char * topicori, JsonObject& data){ void pub(char *topicori, JsonObject &data)
if(client.connected()) { {
if (client.connected())
{
digitalWrite(led_receive, HIGH); digitalWrite(led_receive, HIGH);
String topic = String(mqtt_topic) + String(topicori); String topic = String(mqtt_topic) + String(topicori);
#ifdef valueAsASubject #ifdef valueAsASubject
unsigned long value = data["value"]; unsigned long value = data["value"];
if (value != 0){ if (value != 0)
{
topic = topic + "/" + String(value); topic = topic + "/" + String(value);
} }
#endif #endif
@@ -302,127 +325,161 @@ void pub(char * topicori, JsonObject& data){
#ifdef simplePublishing #ifdef simplePublishing
trc(F("Pub data per topic")); trc(F("Pub data per topic"));
// Loop through all the key-value pairs in obj // Loop through all the key-value pairs in obj
for (JsonPair& p : data) { for (JsonPair &p : data)
{
#if defined(ESP8266) #if defined(ESP8266)
yield(); yield();
#endif #endif
if (p.value.is<unsigned long>() && strcmp(p.key, "rssi") != 0) { //test rssi , bypass solution due to the fact that a int is considered as an unsigned long if (p.value.is<unsigned long>() && 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.key);
trc(p.value.as<unsigned long>()); trc(p.value.as<unsigned long>());
if (strcmp(p.key, "value") == 0){ // if data is a value we don't integrate the name into the topic 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<unsigned long>()); pubMQTT(topic, p.value.as<unsigned long>());
}else{ // if data is not a value we integrate the name into the topic }
else
{ // if data is not a value we integrate the name into the topic
pubMQTT(topic + "/" + String(p.key), p.value.as<unsigned long>()); pubMQTT(topic + "/" + String(p.key), p.value.as<unsigned long>());
} }
}else if (p.value.is<int>()) { }
else if (p.value.is<int>())
{
trc(p.key); trc(p.key);
trc(p.value.as<int>()); trc(p.value.as<int>());
pubMQTT(topic + "/" + String(p.key), p.value.as<int>()); pubMQTT(topic + "/" + String(p.key), p.value.as<int>());
} else if (p.value.is<float>()) { }
else if (p.value.is<float>())
{
trc(p.key); trc(p.key);
trc(p.value.as<float>()); trc(p.value.as<float>());
pubMQTT(topic + "/" + String(p.key), p.value.as<float>()); pubMQTT(topic + "/" + String(p.key), p.value.as<float>());
} else if (p.value.is<char*>()) { }
else if (p.value.is<char *>())
{
trc(p.key); trc(p.key);
trc(p.value.as<const char *>()); trc(p.value.as<const char *>());
pubMQTT(topic + "/" + String(p.key), p.value.as<const char *>()); pubMQTT(topic + "/" + String(p.key), p.value.as<const char *>());
} }
} }
#endif #endif
}else{ }
else
{
trc("client not connected can't pub"); trc("client not connected can't pub");
} }
} }
void pub(char * topicori, char * payload){ void pub(char *topicori, char *payload)
if(client.connected()) { {
if (client.connected())
{
String topic = String(mqtt_topic) + String(topicori); String topic = String(mqtt_topic) + String(topicori);
trc(F("Pub ack into:")); trc(F("Pub ack into:"));
trc(topic); trc(topic);
pubMQTT(topic, payload); pubMQTT(topic, payload);
}else{ }
else
{
trc("client not connected can't pub"); trc("client not connected can't pub");
} }
} }
void pub_custom_topic(char * topicori, JsonObject& data){ void pub_custom_topic(char *topicori, JsonObject &data)
if(client.connected()) { {
if (client.connected())
{
char JSONmessageBuffer[JSON_MSG_BUFFER]; char JSONmessageBuffer[JSON_MSG_BUFFER];
trc(F("Pub json discovery into:")); trc(F("Pub json discovery into:"));
trc(topicori); trc(topicori);
data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer)); data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
trc(JSONmessageBuffer); trc(JSONmessageBuffer);
pubMQTT(topicori, JSONmessageBuffer); pubMQTT(topicori, JSONmessageBuffer);
}else{ }
else
{
trc("client not connected can't pub"); trc("client not connected can't pub");
} }
} }
void pubMQTT(char * topic, char * payload){ void pubMQTT(char *topic, char *payload)
{
client.publish(topic, payload); client.publish(topic, payload);
} }
void pubMQTT(String topic, char * payload){ void pubMQTT(String topic, char *payload)
{
client.publish((char *)topic.c_str(), payload); client.publish((char *)topic.c_str(), payload);
} }
void pubMQTT(char * topic, unsigned long payload){ void pubMQTT(char *topic, unsigned long payload)
{
char val[11]; char val[11];
sprintf(val, "%lu", payload); sprintf(val, "%lu", payload);
client.publish(topic, val); client.publish(topic, val);
} }
void pubMQTT(char * topic, String payload){ void pubMQTT(char *topic, String payload)
{
client.publish(topic, (char *)payload.c_str()); client.publish(topic, (char *)payload.c_str());
} }
void pubMQTT(String topic, String payload){ void pubMQTT(String topic, String payload)
{
client.publish((char *)topic.c_str(), (char *)payload.c_str()); client.publish((char *)topic.c_str(), (char *)payload.c_str());
} }
void pubMQTT(String topic, int payload){ void pubMQTT(String topic, int payload)
{
char val[12]; char val[12];
sprintf(val, "%d", payload); sprintf(val, "%d", payload);
client.publish((char *)topic.c_str(), val); client.publish((char *)topic.c_str(), val);
} }
void pubMQTT(String topic, float payload){ void pubMQTT(String topic, float payload)
{
char val[12]; char val[12];
dtostrf(payload, 3, 1, val); dtostrf(payload, 3, 1, val);
client.publish((char *)topic.c_str(), val); client.publish((char *)topic.c_str(), val);
} }
void pubMQTT(char * topic, float payload){ void pubMQTT(char *topic, float payload)
{
char val[12]; char val[12];
dtostrf(payload, 3, 1, val); dtostrf(payload, 3, 1, val);
client.publish(topic, val); client.publish(topic, val);
} }
void pubMQTT(char * topic, int payload){ void pubMQTT(char *topic, int payload)
{
char val[6]; char val[6];
sprintf(val, "%d", payload); sprintf(val, "%d", payload);
client.publish(topic, val); client.publish(topic, val);
} }
void pubMQTT(char * topic, unsigned int payload){ void pubMQTT(char *topic, unsigned int payload)
{
char val[6]; char val[6];
sprintf(val, "%u", payload); sprintf(val, "%u", payload);
client.publish(topic, val); client.publish(topic, val);
} }
void pubMQTT(char * topic, long payload){ void pubMQTT(char *topic, long payload)
{
char val[11]; char val[11];
sprintf(val, "%l", payload); sprintf(val, "%l", payload);
client.publish(topic, val); client.publish(topic, val);
} }
void pubMQTT(char * topic, double payload){ void pubMQTT(char *topic, double payload)
{
char val[16]; char val[16];
sprintf(val, "%d", payload); sprintf(val, "%d", payload);
client.publish(topic, val); client.publish(topic, val);
} }
void pubMQTT(String topic, unsigned long payload){ void pubMQTT(String topic, unsigned long payload)
{
char val[11]; char val[11];
sprintf(val, "%lu", payload); sprintf(val, "%lu", payload);
client.publish((char *)topic.c_str(), val); client.publish((char *)topic.c_str(), val);
@@ -439,7 +496,9 @@ bool cmpToMainTopic(char * topicOri, char * toAdd){
} }
} }
void reconnect() {
void reconnect()
{
#ifndef ESPWifiManualSetup #ifndef ESPWifiManualSetup
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
@@ -448,9 +507,11 @@ void reconnect() {
#endif #endif
// Loop until we're reconnected // Loop until we're reconnected
while (!client.connected()) { while (!client.connected())
{
trc(F("MQTT connection...")); //F function enable to decrease sram usage 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")); trc(F("Connected to broker"));
failure_number = 0; failure_number = 0;
// Once connected, publish an announcement... // Once connected, publish an announcement...
@@ -461,7 +522,8 @@ void reconnect() {
char topic[mqtt_topic_max_size]; char topic[mqtt_topic_max_size];
strcpy(topic,mqtt_topic); strcpy(topic,mqtt_topic);
strcat(topic,subjectMQTTtoX); strcat(topic,subjectMQTTtoX);
if (client.subscribe(topic)) { if (client.subscribe(topic))
{
#ifdef ZgatewayRF #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 #endif
@@ -470,11 +532,14 @@ void reconnect() {
#endif #endif
trc(F("Subscription OK to the subjects")); trc(F("Subscription OK to the subjects"));
} }
} else { }
else
{
failure_number++; // we count the failure failure_number++; // we count the failure
trc(F("failure_number")); trc(F("failure_number"));
trc(failure_number); trc(failure_number);
if (failure_number > maxMQTTretry && !connectedOnce){ if (failure_number > maxMQTTretry && !connectedOnce)
{
#ifndef ESPWifiManualSetup #ifndef ESPWifiManualSetup
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
trc(F("failed connecting first time to mqtt, reset wifi manager & erase network credentials")); trc(F("failed connecting first time to mqtt, reset wifi manager & erase network credentials"));
@@ -494,7 +559,8 @@ void reconnect() {
} }
// Callback function, when the gateway receive an MQTT value on the topics subscribed this function is called // 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 // In order to republish this payload, a copy must be made
// as the orignal payload buffer will be overwritten whilst // as the orignal payload buffer will be overwritten whilst
// constructing the PUBLISH packet. // constructing the PUBLISH packet.
@@ -506,7 +572,8 @@ void callback(char* topic, byte* payload, unsigned int length) {
// Conversion to a printable string // Conversion to a printable string
p[length] = '\0'; p[length] = '\0';
//launch the function to treat received data if this data concern OpenMQTTGateway //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 the memory
free(p); free(p);
} }
@@ -522,7 +589,6 @@ void setup()
Serial.begin(SERIAL_BAUD); Serial.begin(SERIAL_BAUD);
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
#ifdef ESP8266 #ifdef ESP8266
#ifndef ZgatewaySRFB // if we are not in sonoff rf bridge case we apply the ESP8266 pin optimization #ifndef ZgatewaySRFB // if we are not in sonoff rf bridge case we apply the ESP8266 pin optimization
Serial.end(); Serial.end();
@@ -562,11 +628,16 @@ void setup()
}); });
ArduinoOTA.onError([](ota_error_t error) { ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error); Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) trc(F("Auth Failed")); if (error == OTA_AUTH_ERROR)
else if (error == OTA_BEGIN_ERROR) trc(F("Begin Failed")); trc(F("Auth Failed"));
else if (error == OTA_CONNECT_ERROR) trc(F("Connect Failed")); else if (error == OTA_BEGIN_ERROR)
else if (error == OTA_RECEIVE_ERROR) trc(F("Receive Failed")); trc(F("Begin Failed"));
else if (error == OTA_END_ERROR) trc(F("End 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(); ArduinoOTA.begin();
@@ -636,9 +707,6 @@ void setup()
#ifdef ZgatewayRF #ifdef ZgatewayRF
setupRF(); setupRF();
#endif #endif
#ifdef ZgatewayRF315
setupRF315();
#endif
#ifdef ZgatewayRF2 #ifdef ZgatewayRF2
setupRF2(); setupRF2();
#endif #endif
@@ -673,36 +741,45 @@ void setup()
setupFASTLED(); setupFASTLED();
#endif #endif
trc(F("MQTT_MAX_PACKET_SIZE")); trc(F("MQTT_MAX_PACKET_SIZE"));
trc(MQTT_MAX_PACKET_SIZE); trc(MQTT_MAX_PACKET_SIZE);
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) #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 #endif
trc(F("Setup OpenMQTTGateway end")); trc(F("Setup OpenMQTTGateway end"));
} }
#if defined(ESPWifiManualSetup) #if defined(ESPWifiManualSetup)
void setup_wifi() { void setup_wifi()
{
delay(10); delay(10);
int failureAttempt = 0; //DIRTY FIX ESP32 waiting for https://github.com/espressif/arduino-esp32/issues/653 int failureAttempt = 0; //DIRTY FIX ESP32 waiting for https://github.com/espressif/arduino-esp32/issues/653
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
// We start by connecting to a WiFi network // We start by connecting to a WiFi network
trc(F("Connecting to ")); trc(F("Connecting to "));
trc(wifi_ssid); trc(wifi_ssid);
#ifdef ESPWifiAdvancedSetup
IPAddress ip_adress(ip); IPAddress ip_adress(ip);
IPAddress gateway_adress(gateway); IPAddress gateway_adress(gateway);
IPAddress subnet_adress(subnet); IPAddress subnet_adress(subnet);
IPAddress dns_adress(Dns); 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.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 #else
WiFi.begin(wifi_ssid, wifi_password);
#endif
while (WiFi.status() != WL_CONNECTED) { while (WiFi.status() != WL_CONNECTED)
{
delay(500); delay(500);
trc(F(".")); trc(F("."));
failureAttempt++; //DIRTY FIX ESP32 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")); trc(F("WiFi ok with manual config credentials"));
} }
@@ -716,21 +793,26 @@ bool shouldSaveConfig = true;
//do we have been connected once to mqtt //do we have been connected once to mqtt
//callback notifying us of the need to save config //callback notifying us of the need to save config
void saveConfigCallback () { void saveConfigCallback()
{
trc(F("Should save config")); trc(F("Should save config"));
shouldSaveConfig = true; shouldSaveConfig = true;
} }
void checkButton(){ // code from tzapu/wifimanager examples void checkButton()
{ // code from tzapu/wifimanager examples
// check for button press // check for button press
if ( digitalRead(TRIGGER_PIN) == LOW ) { if (digitalRead(TRIGGER_PIN) == LOW)
{
// poor mans debounce/press-hold, code not ideal for production // poor mans debounce/press-hold, code not ideal for production
delay(50); delay(50);
if( digitalRead(TRIGGER_PIN) == LOW ){ if (digitalRead(TRIGGER_PIN) == LOW)
{
trc(F("Trigger button Pressed")); trc(F("Trigger button Pressed"));
// still holding button for 3000 ms, reset settings, code not ideaa for production // still holding button for 3000 ms, reset settings, code not ideaa for production
delay(3000); // reset delay hold delay(3000); // reset delay hold
if( digitalRead(TRIGGER_PIN) == LOW ){ if (digitalRead(TRIGGER_PIN) == LOW)
{
trc(F("Button Held")); trc(F("Button Held"));
trc(F("Erasing ESP Config, restarting")); trc(F("Erasing ESP Config, restarting"));
setup_wifimanager(true); setup_wifimanager(true);
@@ -738,14 +820,18 @@ void checkButton(){ // code from tzapu/wifimanager examples
} }
} }
} }
void eraseAndRestart(){
void eraseAndRestart()
{
#if defined(ESP8266) #if defined(ESP8266)
WiFi.disconnect(true); WiFi.disconnect(true);
#else #else
WiFi.disconnect(true, true); WiFi.disconnect(true, true);
#endif #endif
trc("Formatting requested, result:"); trc("Formatting requested, result:");
trc(SPIFFS.format()); trc(SPIFFS.format());
#if defined(ESP8266) #if defined(ESP8266)
ESP.reset(); ESP.reset();
#else #else
@@ -753,30 +839,37 @@ void eraseAndRestart(){
#endif #endif
} }
void setup_wifimanager(bool reset_settings){ void setup_wifimanager(bool reset_settings)
{
pinMode(TRIGGER_PIN, INPUT_PULLUP); pinMode(TRIGGER_PIN, INPUT_PULLUP);
if(reset_settings) eraseAndRestart(); if (reset_settings)
eraseAndRestart();
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
//read configuration from FS json //read configuration from FS json
trc(F("mounting FS...")); trc(F("mounting FS..."));
if (SPIFFS.begin()) { if (SPIFFS.begin())
{
trc(F("mounted file system")); trc(F("mounted file system"));
}else{ }
else
{
trc(F("failed to mount FS -> formating")); trc(F("failed to mount FS -> formating"));
SPIFFS.format(); SPIFFS.format();
if (SPIFFS.begin()) if (SPIFFS.begin())
trc(F("mounted file system after formating")); trc(F("mounted file system after formating"));
} }
if (SPIFFS.exists("/config.json")) { if (SPIFFS.exists("/config.json"))
{
//file exists, reading and loading //file exists, reading and loading
trc(F("reading config file")); trc(F("reading config file"));
File configFile = SPIFFS.open("/config.json", "r"); File configFile = SPIFFS.open("/config.json", "r");
if (configFile) { if (configFile)
{
trc(F("opened config file")); trc(F("opened config file"));
size_t size = configFile.size(); size_t size = configFile.size();
// Allocate a buffer to store contents of the file. // Allocate a buffer to store contents of the file.
@@ -785,15 +878,24 @@ void setup_wifimanager(bool reset_settings){
DynamicJsonBuffer jsonBuffer; DynamicJsonBuffer jsonBuffer;
JsonObject &json = jsonBuffer.parseObject(buf.get()); JsonObject &json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial); json.printTo(Serial);
if (json.success()) { if (json.success())
{
trc(F("\nparsed json")); trc(F("\nparsed json"));
if (json.containsKey("mqtt_server")) strcpy(mqtt_server, json["mqtt_server"]); if (json.containsKey("mqtt_server"))
if (json.containsKey("mqtt_port")) strcpy(mqtt_port, json["mqtt_port"]); strcpy(mqtt_server, json["mqtt_server"]);
if (json.containsKey("mqtt_user")) strcpy(mqtt_user, json["mqtt_user"]); if (json.containsKey("mqtt_port"))
if (json.containsKey("mqtt_pass")) strcpy(mqtt_pass, json["mqtt_pass"]); strcpy(mqtt_port, json["mqtt_port"]);
if (json.containsKey("mqtt_topic")) strcpy(mqtt_topic, json["mqtt_topic"]); if (json.containsKey("mqtt_user"))
if (json.containsKey("gateway_name")) strcpy(gateway_name, json["gateway_name"]); strcpy(mqtt_user, json["mqtt_user"]);
} else { 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")); trc(F("failed to load json config"));
} }
} }
@@ -836,7 +938,8 @@ void setup_wifimanager(bool reset_settings){
//fetches ssid and pass and tries to connect //fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name //if it does not connect it starts an access point with the specified name
//and goes into a blocking loop awaiting configuration //and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password)) { if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password))
{
trc(F("failed to connect and hit timeout")); trc(F("failed to connect and hit timeout"));
delay(3000); delay(3000);
//reset and try again, or maybe put it to deep sleep //reset and try again, or maybe put it to deep sleep
@@ -860,7 +963,8 @@ void setup_wifimanager(bool reset_settings){
strcpy(gateway_name, custom_gateway_name.getValue()); strcpy(gateway_name, custom_gateway_name.getValue());
//save the custom parameters to FS //save the custom parameters to FS
if (shouldSaveConfig) { if (shouldSaveConfig)
{
trc(F("saving config")); trc(F("saving config"));
DynamicJsonBuffer jsonBuffer; DynamicJsonBuffer jsonBuffer;
JsonObject &json = jsonBuffer.createObject(); JsonObject &json = jsonBuffer.createObject();
@@ -872,7 +976,8 @@ void setup_wifimanager(bool reset_settings){
json["gateway_name"] = gateway_name; json["gateway_name"] = gateway_name;
File configFile = SPIFFS.open("/config.json", "w"); File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) { if (!configFile)
{
trc(F("failed to open config file for writing")); trc(F("failed to open config file for writing"));
} }
@@ -882,21 +987,22 @@ void setup_wifimanager(bool reset_settings){
//end save //end save
} }
} }
#else // Arduino case #else // Arduino case
void setup_ethernet()
void setup_ethernet() {
if (gateway[0] != 0 || Dns[0]!=0)
{ {
#ifdef NetworkAdvancedSetup
trc(F("Adv eth cfg")); trc(F("Adv eth cfg"));
Ethernet.begin(mac, ip, Dns, gateway, subnet); Ethernet.begin(mac, ip, Dns, gateway, subnet);
}else{ #else
trc(F("Spl eth cfg")); trc(F("Spl eth cfg"));
Ethernet.begin(mac, ip); Ethernet.begin(mac, ip);
} #endif
if (Ethernet.hardwareStatus() == EthernetNoHardware) { if (Ethernet.hardwareStatus() == EthernetNoHardware)
{
trc("Ethernet shield was not found."); trc("Ethernet shield was not found.");
}else{ }
else
{
trc(F("ip: ")); trc(F("ip: "));
Serial.println(Ethernet.localIP()); Serial.println(Ethernet.localIP());
trc(F("Eth ok")); trc(F("Eth ok"));
@@ -905,31 +1011,41 @@ void setup_ethernet() {
#endif #endif
#if defined(MDNS_SD) && defined(ESP8266) #if defined(MDNS_SD) && defined(ESP8266)
void connectMQTTmdns(){ void connectMQTTmdns()
if (!MDNS.begin("ESP_MQTT")) { {
if (!MDNS.begin("ESP_MQTT"))
{
trc(F("Error setting up MDNS responder!")); trc(F("Error setting up MDNS responder!"));
while(1){ while (1)
{
delay(1000); delay(1000);
} }
} }
trc(F("Browsing for service MQTT ")); trc(F("Browsing for service MQTT "));
int n = MDNS.queryService("mqtt", "tcp"); int n = MDNS.queryService("mqtt", "tcp");
if (n == 0) { if (n == 0)
{
trc(F("no services found")); trc(F("no services found"));
}else { }
else
{
trc(n); trc(n);
trc(F(" service(s) found")); trc(F(" service(s) found"));
for (int i=0; i < n; ++i) { for (int i = 0; i < n; ++i)
{
// Print details for each service found // Print details for each service found
trc(i + 1); trc(i + 1);
trc(MDNS.hostname(i)); trc(MDNS.hostname(i));
trc(MDNS.IP(i).toString()); trc(MDNS.IP(i).toString());
trc(MDNS.port(i)); trc(MDNS.port(i));
} }
if (n==1) { if (n == 1)
{
trc(F("One MQTT server found setting parameters")); trc(F("One MQTT server found setting parameters"));
client.setServer(MDNS.IP(0), int(MDNS.port(0))); client.setServer(MDNS.IP(0), int(MDNS.port(0)));
}else{ }
else
{
trc(F("Several MQTT servers found, please deactivate mDNS and set your default server")); trc(F("Several MQTT servers found, please deactivate mDNS and set your default server"));
} }
} }
@@ -951,12 +1067,15 @@ void loop()
unsigned long now = millis(); unsigned long now = millis();
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
if (WiFi.status() == WL_CONNECTED){ if (WiFi.status() == WL_CONNECTED)
{
#else #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 #endif
lastNTWKReconnectAttempt = 0; lastNTWKReconnectAttempt = 0;
if (client.connected()) { if (client.connected())
{
// MQTT loop // MQTT loop
connectedOnce = true; connectedOnce = true;
lastMQTTReconnectAttempt = 0; lastMQTTReconnectAttempt = 0;
@@ -1002,9 +1121,6 @@ void loop()
#ifdef ZgatewayRF #ifdef ZgatewayRF
RFtoMQTT(); RFtoMQTT();
#endif #endif
#ifdef ZgatewayRF315
RF315toMQTT();
#endif
#ifdef ZgatewayRF2 #ifdef ZgatewayRF2
RF2toMQTT(); RF2toMQTT();
#endif #endif
@@ -1024,9 +1140,8 @@ void loop()
IRtoMQTT(); IRtoMQTT();
#endif #endif
#ifdef Zgateway2G #ifdef Zgateway2G
if(_2GtoMQTT()){ if (_2GtoMQTT())
trc(F("2GtoMQTT OK")); trc(F("2GtoMQTT OK"));
}
#endif #endif
#ifdef ZgatewayRFM69 #ifdef ZgatewayRFM69
if (RFM69toMQTT()) if (RFM69toMQTT())
@@ -1038,14 +1153,20 @@ void loop()
#ifdef ZactuatorFASTLED #ifdef ZactuatorFASTLED
FASTLEDLoop(); FASTLEDLoop();
#endif #endif
}else{ }
if (now - lastMQTTReconnectAttempt > 5000) { else
{
if (now - lastMQTTReconnectAttempt > 5000)
{
lastMQTTReconnectAttempt = now; lastMQTTReconnectAttempt = now;
reconnect(); reconnect();
} }
} }
} else { // disconnected from network }
if ( now - lastNTWKReconnectAttempt > 10000) { else
{ // disconnected from network
if (now - lastNTWKReconnectAttempt > 10000)
{
lastNTWKReconnectAttempt = now; lastNTWKReconnectAttempt = now;
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
trc("wifi disconnected"); trc("wifi disconnected");
@@ -1059,7 +1180,8 @@ void loop()
ESP.reset(); ESP.reset();
#endif #endif
#else #else
if (!connectedOnce) { if (!connectedOnce)
{
trc(F("reseting wifi manager")); 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 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
} }
@@ -1072,9 +1194,11 @@ void loop()
} }
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__) #if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
void stateMeasures(){ void stateMeasures()
{
unsigned long now = millis(); unsigned long now = millis();
if (now > (timer_sys_measures + TimeBetweenReadingSYS)) {//retriving value of memory ram every TimeBetweenReadingSYS if (now > (timer_sys_measures + TimeBetweenReadingSYS))
{ //retriving value of memory ram every TimeBetweenReadingSYS
timer_sys_measures = millis(); timer_sys_measures = millis();
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &SYSdata = jsonBuffer.createObject(); JsonObject &SYSdata = jsonBuffer.createObject();
@@ -1100,9 +1224,6 @@ void stateMeasures(){
#ifdef ZgatewayRF #ifdef ZgatewayRF
modules = modules + ZgatewayRF; modules = modules + ZgatewayRF;
#endif #endif
#ifdef ZgatewayRF315
modules = modules + ZgatewayRF315;
#endif
#ifdef ZsensorBME280 #ifdef ZsensorBME280
modules = modules + ZsensorBME280; modules = modules + ZsensorBME280;
#endif #endif
@@ -1175,7 +1296,8 @@ void stateMeasures(){
} }
#endif #endif
void storeValue(unsigned long MQTTvalue){ void storeValue(unsigned long MQTTvalue)
{
unsigned long now = millis(); unsigned long now = millis();
// find oldest value of the buffer // find oldest value of the buffer
int o = getMin(); int o = getMin();
@@ -1193,12 +1315,14 @@ void storeValue(unsigned long MQTTvalue){
} }
} }
int getMin(){ int getMin()
{
unsigned int minimum = ReceivedSignal[0][1]; unsigned int minimum = ReceivedSignal[0][1];
int minindex = 0; int minindex = 0;
for (int i = 0; i < array_size; i++) for (int i = 0; i < array_size; i++)
{ {
if (ReceivedSignal[i][1] < minimum) { if (ReceivedSignal[i][1] < minimum)
{
minimum = ReceivedSignal[i][1]; minimum = ReceivedSignal[i][1];
minindex = i; minindex = i;
} }
@@ -1206,13 +1330,17 @@ int getMin(){
return minindex; return minindex;
} }
bool isAduplicate(unsigned long value){ bool isAduplicate(unsigned long value)
{
trc(F("isAdupl?")); trc(F("isAdupl?"));
// check if the value has been already sent during the last time_avoid_duplicate // check if the value has been already sent during the last time_avoid_duplicate
for (int i = 0; i < array_size;i++){ for (int i = 0; i < array_size; i++)
if (ReceivedSignal[i][0] == value){ {
if (ReceivedSignal[i][0] == value)
{
unsigned long now = millis(); unsigned long now = millis();
if (now - ReceivedSignal[i][1] < time_avoid_duplicate){ // change if (now - ReceivedSignal[i][1] < time_avoid_duplicate)
{ // change
trc(F("no pub. dupl")); trc(F("no pub. dupl"));
return true; return true;
} }
@@ -1221,7 +1349,8 @@ bool isAduplicate(unsigned long value){
return false; return false;
} }
void receivingMQTT(char * topicOri, char * datacallback) { void receivingMQTT(char *topicOri, char *datacallback)
{
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &jsondata = jsonBuffer.parseObject(datacallback); JsonObject &jsondata = jsonBuffer.parseObject(datacallback);
@@ -1231,20 +1360,23 @@ void receivingMQTT(char * topicOri, char * datacallback) {
trc(F("Store str")); trc(F("Store str"));
unsigned long data = 0; unsigned long data = 0;
#ifdef jsonPublishing #ifdef jsonPublishing
if (jsondata.success()) data = jsondata["value"]; if (jsondata.success())
data = jsondata["value"];
#endif #endif
#ifdef simplePublishing #ifdef simplePublishing
data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
#endif #endif
if (data != 0) { if (data != 0)
{
storeValue(data); storeValue(data);
trc(F("JSON str")); trc(F("JSON str"));
} }
} }
if (jsondata.success()) { // json object ok -> json decoding if (jsondata.success())
{ // json object ok -> json decoding
#ifdef ZgatewayPilight // ZgatewayPilight is only defined with json publishing #ifdef ZgatewayPilight // ZgatewayPilight is only defined with json publishing
MQTTtoPilight(topicOri, jsondata); MQTTtoPilight(topicOri, jsondata);
#endif #endif
@@ -1255,9 +1387,6 @@ void receivingMQTT(char * topicOri, char * datacallback) {
#ifdef ZgatewayRF #ifdef ZgatewayRF
MQTTtoRF(topicOri, jsondata); MQTTtoRF(topicOri, jsondata);
#endif #endif
#ifdef ZgatewayRF315
MQTTtoRF315(topicOri, jsondata);
#endif
#ifdef ZgatewayRF2 #ifdef ZgatewayRF2
MQTTtoRF2(topicOri, jsondata); MQTTtoRF2(topicOri, jsondata);
#endif #endif
@@ -1286,8 +1415,9 @@ void receivingMQTT(char * topicOri, char * datacallback) {
MQTTtoFASTLEDJSON(topicOri, jsondata); MQTTtoFASTLEDJSON(topicOri, jsondata);
#endif #endif
MQTTtoSYS(topicOri, jsondata); MQTTtoSYS(topicOri, jsondata);
}
} else { // not a json object --> simple decoding else
{ // not a json object --> simple decoding
#ifdef simpleReceiving #ifdef simpleReceiving
#ifdef ZgatewayLORA #ifdef ZgatewayLORA
MQTTtoLORA(topicOri, datacallback); MQTTtoLORA(topicOri, datacallback);
@@ -1317,34 +1447,40 @@ void receivingMQTT(char * topicOri, char * datacallback) {
#ifdef ZactuatorONOFF #ifdef ZactuatorONOFF
MQTTtoONOFF(topicOri, datacallback); MQTTtoONOFF(topicOri, datacallback);
#endif #endif
digitalWrite(led_send, HIGH);
#ifdef ZactuatorFASTLED #ifdef ZactuatorFASTLED
MQTTtoFASTLED(topicOri, datacallback); MQTTtoFASTLED(topicOri, datacallback);
#endif #endif
digitalWrite(led_send, HIGH);
} }
//YELLOW OFF //YELLOW OFF
digitalWrite(led_send, HIGH); digitalWrite(led_send, HIGH);
} }
void MQTTtoSYS(char * topicOri, JsonObject& SYSdata) { // json object decoding void MQTTtoSYS(char *topicOri, JsonObject &SYSdata)
if (cmpToMainTopic(topicOri,subjectMQTTtoSYSset)){ { // json object decoding
if (cmpToMainTopic(topicOri,subjectMQTTtoSYSset))
{
trc(F("MQTTtoSYS json set")); trc(F("MQTTtoSYS json set"));
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
if (SYSdata.containsKey("cmd")){ if (SYSdata.containsKey("cmd"))
{
trc(F("Command")); trc(F("Command"));
const char *cmd = SYSdata["cmd"]; const char *cmd = SYSdata["cmd"];
trc(cmd); trc(cmd);
if (strstr(cmd,restartCmd) != NULL) {//restart if (strstr(cmd, restartCmd) != NULL)
{ //restart
#if defined(ESP8266) #if defined(ESP8266)
ESP.reset(); ESP.reset();
#else #else
ESP.restart(); ESP.restart();
#endif #endif
}else if (strstr(cmd,eraseCmd) != NULL) {//erase and restart }
else if (strstr(cmd, eraseCmd) != NULL)
{ //erase and restart
setup_wifimanager(true); setup_wifimanager(true);
}else{ }
else
{
trc(F("wrong command")); trc(F("wrong command"));
} }
} }