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
26 files changed
+4512 -3692

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,
+25 -32
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,
@@ -123,35 +119,32 @@ boolean FASTLEDtoMQTT()
{ {
return false; return false;
} }
void MQTTtoFASTLEDJSON(char *topicOri, JsonObject& jsonData) void MQTTtoFASTLEDJSON(char *topicOri, JsonObject &jsonData)
{ {
trc(F("MQTTtoFASTLEDJSON: ")); trc(F("MQTTtoFASTLEDJSON: "));
currentLEDState = GENERAL; currentLEDState = GENERAL;
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"));
int ledNr = jsonData["led"]; int ledNr = jsonData["led"];
trc(F("led")); trc(F("led"));
trc(ledNr); trc(ledNr);
const char *color = jsonData["hex"]; const char *color = jsonData["hex"];
trc(F("hex")); trc(F("hex"));
long number = (long)strtol(color, NULL, 16); long number = (long)strtol(color, NULL, 16);
trc(number); trc(number);
bool blink = jsonData["blink"]; bool blink = jsonData["blink"];
if (ledNr <= FASTLED_NUM_LEDS) if (ledNr <= FASTLED_NUM_LEDS)
{ {
trc(F("blink")); trc(F("blink"));
trc(blink); trc(blink);
blinkLED[ledNr] = blink; blinkLED[ledNr] = blink;
leds[ledNr] = number; leds[ledNr] = number;
} }
} }
} }
void MQTTtoFASTLED(char *topicOri, char *datacallback) void MQTTtoFASTLED(char *topicOri, char *datacallback)
@@ -160,7 +153,7 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback)
currentLEDState = GENERAL; currentLEDState = GENERAL;
long number = 0; long number = 0;
trc(topicOri); trc(topicOri);
if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLED)) if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED))
{ {
number = (long)strtol(&datacallback[1], NULL, 16); number = (long)strtol(&datacallback[1], NULL, 16);
trc(number); trc(number);
@@ -170,18 +163,18 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback)
} }
FastLED.show(); FastLED.show();
} }
else if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLEDsetbrightness)) else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness))
{ {
number = (long)strtol(&datacallback[1], NULL, 16); number = (long)strtol(&datacallback[1], NULL, 16);
trc(number); trc(number);
FastLED.setBrightness(number); FastLED.setBrightness(number);
FastLED.show(); FastLED.show();
} }
else if (cmpToMainTopic(topicOri,subjectMQTTtoFASTLEDsetanimation)) else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation))
{ {
String payload = datacallback; String payload = datacallback;
trc(payload); trc(payload);
if ( strstr(datacallback,"fire") != NULL) if (strstr(datacallback, "fire") != NULL)
{ {
currentLEDState = FIRE; currentLEDState = FIRE;
gPal = HeatColors_p; gPal = HeatColors_p;
@@ -195,7 +188,7 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback)
{ {
currentLEDState = OFF; currentLEDState = OFF;
} }
if (currentLEDState==OFF) if (currentLEDState == OFF)
{ {
for (int i = 0; i < FASTLED_NUM_LEDS; i++) for (int i = 0; i < FASTLED_NUM_LEDS; i++)
{ {
+18 -11
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,16 +70,17 @@ 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
char b = ON; char b = ON;
pub(subjectGTWONOFFtoMQTT, &b); pub(subjectGTWONOFFtoMQTT, &b);
} }
} }
#endif #endif
#endif #endif
+129 -104
View File
@@ -33,13 +33,14 @@
#include <A6lib.h> // library for controling A6 or A7 module #include <A6lib.h> // library for controling A6 or A7 module
// Instantiate the library with TxPin, RxPin. // Instantiate the library with TxPin, RxPin.
A6lib A6l(_2G_TX_PIN, _2G_RX_PIN); //D6 to A6 RX, D7 to A6 TX A6lib A6l(_2G_TX_PIN, _2G_RX_PIN); //D6 to A6 RX, D7 to A6 TX
int unreadSMSLocs[50] = {0}; int 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,115 +50,139 @@ 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(_2G_PWR_PIN); trc(F("Init 2G module: "));
delay(1000); trc(_2G_PWR_PIN);
// Power-cycle the module to reset it. delay(1000);
A6l.powerCycle(_2G_PWR_PIN); // Power-cycle the module to reset it.
trc(F("waiting for network connection")); A6l.powerCycle(_2G_PWR_PIN);
A6l.blockUntilReady(_2G_MODULE_BAUDRATE); trc(F("waiting for network connection"));
trc(F("A6/A7 gsm ready")); A6l.blockUntilReady(_2G_MODULE_BAUDRATE);
signalStrengthAnalysis(); trc(F("A6/A7 gsm ready"));
delay(1000); signalStrengthAnalysis();
// deleting all sms delay(1000);
if (deleteSMS){ // deleting all sms
if (A6l.deleteSMS(1,4) == A6_OK ) { if (deleteSMS)
trc(F("delete SMS OK")); {
}else{ if (A6l.deleteSMS(1, 4) == A6_OK)
trc(F("delete SMS KO")); {
} trc(F("delete SMS OK"));
} }
} else
{
void signalStrengthAnalysis(){ trc(F("delete SMS KO"));
int signalStrength = 0;
signalStrength = A6l.getSignalStrength();
trc(F("Signal strength: "));
trc(signalStrength);
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL ) {
trc(F("Signal too low restart the module"));
setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module
}
}
bool _2GtoMQTT(){
// Get the memory locations of unread SMS messages.
unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512);
trc(F("Creating SMS buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++) {
trc(F("New message at index: "));
trc(unreadSMSNum);
sms = A6l.readSMS(unreadSMSLocs[i]);
SMSdata.set("message", (char *)sms.message.c_str());
SMSdata.set("date", (char *)sms.date.c_str());
SMSdata.set("phone", (char *)sms.number.c_str());
A6l.deleteSMS(unreadSMSLocs[i]); // we delete the SMS received
trc(F("Adv data 2GtoMQTT"));
pub(subject2GtoMQTT,SMSdata);
return true;
}
return false;
}
#ifdef simpleReceiving
void MQTTto2G(char * topicOri, char * datacallback) {
String data = datacallback;
String topic = topicOri;
if (cmpToMainTopic(topicOri,subjectMQTTto2G)) {
trc(F("MQTTto2G data analysis"));
// 2G DATA ANALYSIS
String phone_number = "";
int pos0 = topic.lastIndexOf(_2GPhoneKey);
if (pos0 != -1) {
pos0 = pos0 + strlen(_2GPhoneKey);
phone_number = topic.substring(pos0);
trc(F("MQTTto2G phone ok"));
trc(phone_number);
trc(F("MQTTto2G sms"));
trc(data);
if (A6l.sendSMS(phone_number,data) == A6_OK ) {
trc(F("SMS OK"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, "SMS OK");// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{
trc(F("SMS KO"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, "SMS KO");// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}else{
trc(F("MQTTto2G Fail reading phone number"));
}
} }
} }
}
void signalStrengthAnalysis()
{
int signalStrength = 0;
signalStrength = A6l.getSignalStrength();
trc(F("Signal strength: "));
trc(signalStrength);
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL)
{
trc(F("Signal too low restart the module"));
setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module
}
}
bool _2GtoMQTT()
{
// Get the memory locations of unread SMS messages.
unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512);
trc(F("Creating SMS buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++)
{
trc(F("New message at index: "));
trc(unreadSMSNum);
sms = A6l.readSMS(unreadSMSLocs[i]);
SMSdata.set("message", (char *)sms.message.c_str());
SMSdata.set("date", (char *)sms.date.c_str());
SMSdata.set("phone", (char *)sms.number.c_str());
A6l.deleteSMS(unreadSMSLocs[i]); // we delete the SMS received
trc(F("Adv data 2GtoMQTT"));
pub(subject2GtoMQTT, SMSdata);
return true;
}
return false;
}
#ifdef simpleReceiving
void MQTTto2G(char *topicOri, char *datacallback)
{
String data = datacallback;
String topic = topicOri;
if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
trc(F("MQTTto2G data analysis"));
// 2G DATA ANALYSIS
String phone_number = "";
int pos0 = topic.lastIndexOf(_2GPhoneKey);
if (pos0 != -1)
{
pos0 = pos0 + strlen(_2GPhoneKey);
phone_number = topic.substring(pos0);
trc(F("MQTTto2G phone ok"));
trc(phone_number);
trc(F("MQTTto2G sms"));
trc(data);
if (A6l.sendSMS(phone_number, data) == A6_OK)
{
trc(F("SMS OK"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
else
{
trc(F("SMS KO"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}
else
{
trc(F("MQTTto2G Fail reading phone number"));
}
}
}
#endif #endif
#ifdef jsonReceiving #ifdef jsonReceiving
void MQTTto2G(char * topicOri, JsonObject& SMSdata) { void MQTTto2G(char *topicOri, JsonObject &SMSdata)
{
if (cmpToMainTopic(topicOri,subjectMQTTto2G)){
const char * sms = SMSdata["message"]; if (cmpToMainTopic(topicOri, subjectMQTTto2G))
const char * phone = SMSdata["phone"]; {
trc(F("MQTTto2G json data analysis")); const char *sms = SMSdata["message"];
if (sms && phone) { const char *phone = SMSdata["phone"];
trc(F("MQTTto2G sms & phone ok")); trc(F("MQTTto2G json data analysis"));
trc(sms); if (sms && phone)
if (A6l.sendSMS(String(phone),String(sms)) == A6_OK ) { {
trc(F("SMS OK")); trc(F("MQTTto2G sms & phone ok"));
// Acknowledgement to the GTW2G topic trc(sms);
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 if (A6l.sendSMS(String(phone), String(sms)) == A6_OK)
}else{ {
trc(F("SMS KO")); trc(F("SMS OK"));
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 // Acknowledgement to the GTW2G topic
} pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{ }
trc(F("MQTTto2G failed json read")); else
{
trc(F("SMS KO"));
pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} }
} }
else
{
trc(F("MQTTto2G failed json read"));
}
} }
}
#endif #endif
#endif #endif
+839 -695
View File
File diff suppressed because it is too large. Load diff
+1059 -824
View File
File diff suppressed because it is too large. Load diff
+78 -62
View File
@@ -31,15 +31,18 @@
#include <SPI.h> #include <SPI.h>
#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); {
LoRa.setPins(LORA_SS,LORA_RST,LORA_DI0); SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_SS);
LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0);
if (!LoRa.begin(LORA_BAND)) {
if (!LoRa.begin(LORA_BAND))
{
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,78 +58,91 @@ 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"));
#ifdef ESP32 #ifdef ESP32
String taskMessage = "LORA Task running on core "; String taskMessage = "LORA Task running on core ";
taskMessage = taskMessage + xPortGetCoreID(); taskMessage = taskMessage + xPortGetCoreID();
trc(taskMessage); trc(taskMessage);
#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")); {
pub(subjectMQTTtoLORA,LORAdata); trc(F("Pub LORA for rpt"));
pub(subjectMQTTtoLORA, LORAdata);
} }
} }
} }
#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
trc(F("MQTTtoLORA json")); if (cmpToMainTopic(topicOri, subjectMQTTtoLORA))
const char * message = LORAdata["message"]; {
int txPower = LORAdata["txpower"]|LORA_TX_POWER; trc(F("MQTTtoLORA json"));
int spreadingFactor = LORAdata["spreadingfactor"]|LORA_SPREADING_FACTOR; const char *message = LORAdata["message"];
long int frequency = LORAdata["frequency "]|LORA_BAND; int txPower = LORAdata["txpower"] | LORA_TX_POWER;
long int signalBandwidth = LORAdata["signalbandwidth"]|LORA_SIGNAL_BANDWIDTH; int spreadingFactor = LORAdata["spreadingfactor"] | LORA_SPREADING_FACTOR;
int codingRateDenominator = LORAdata["codingrate"]|LORA_CODING_RATE; long int frequency = LORAdata["frequency "] | LORA_BAND;
int preambleLength = LORAdata["preamblelength"]|LORA_PREAMBLE_LENGTH; long int signalBandwidth = LORAdata["signalbandwidth"] | LORA_SIGNAL_BANDWIDTH;
byte syncWord = LORAdata["syncword"]|LORA_SYNC_WORD; int codingRateDenominator = LORAdata["codingrate"] | LORA_CODING_RATE;
bool Crc = LORAdata["enablecrc"]|DEFAULT_CRC; int preambleLength = LORAdata["preamblelength"] | LORA_PREAMBLE_LENGTH;
if (message) { byte syncWord = LORAdata["syncword"] | LORA_SYNC_WORD;
LoRa.setTxPower(txPower); bool Crc = LORAdata["enablecrc"] | DEFAULT_CRC;
LoRa.setFrequency(frequency); if (message)
LoRa.setSpreadingFactor(spreadingFactor); {
LoRa.setSignalBandwidth(signalBandwidth); LoRa.setTxPower(txPower);
LoRa.setCodingRate4(codingRateDenominator); LoRa.setFrequency(frequency);
LoRa.setPreambleLength(preambleLength); LoRa.setSpreadingFactor(spreadingFactor);
LoRa.setSyncWord(syncWord); LoRa.setSignalBandwidth(signalBandwidth);
if (Crc) LoRa.enableCrc(); LoRa.setCodingRate4(codingRateDenominator);
LoRa.beginPacket(); LoRa.setPreambleLength(preambleLength);
LoRa.print(message); LoRa.setSyncWord(syncWord);
LoRa.endPacket(); if (Crc)
trc(F("MQTTtoLORA OK")); LoRa.enableCrc();
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 LoRa.beginPacket();
}else{ LoRa.print(message);
trc(F("MQTTtoLORA Fail json")); LoRa.endPacket();
} trc(F("MQTTtoLORA OK"));
pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
else
{
trc(F("MQTTtoLORA Fail json"));
} }
} }
}
#endif #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
LoRa.beginPacket(); if (cmpToMainTopic(topicOri, subjectMQTTtoLORA))
LoRa.print(LORAdata); {
LoRa.endPacket(); LoRa.beginPacket();
trc(F("MQTTtoLORA OK")); LoRa.print(LORAdata);
pub(subjectGTWLORAtoMQTT, LORAdata);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also LoRa.endPacket();
} trc(F("MQTTtoLORA OK"));
pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} }
}
#endif #endif
#endif #endif
+90 -70
View File
@@ -27,114 +27,134 @@
*/ */
#include "User_config.h" #include "User_config.h"
#ifdef ZgatewayPilight #ifdef ZgatewayPilight
#include <ESPiLight.h> #include <ESPiLight.h>
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();
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer2; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer2;
JsonObject& msg = jsonBuffer2.parseObject(message); JsonObject &msg = jsonBuffer2.parseObject(message);
RFPiLightdata.set("message", msg); RFPiLightdata.set("message", msg);
RFPiLightdata.set("protocol",(char *)protocol.c_str()); RFPiLightdata.set("protocol", (char *)protocol.c_str());
RFPiLightdata.set("length", (char *)deviceID.c_str()); RFPiLightdata.set("length", (char *)deviceID.c_str());
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")); {
pub(subjectMQTTtoPilight,RFPiLightdata); trc(F("Pub Pilight for rpt"));
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 {
rf.setCallback(pilightCallback); #ifndef ZgatewayRF &&ZgatewayRF2 &&ZgatewayRF315 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell
rf.initReceiver(RF_RECEIVER_PIN); rf.setCallback(pilightCallback);
trc(F("RF_EMITTER_PIN ")); rf.initReceiver(RF_RECEIVER_PIN);
trc(String(RF_EMITTER_PIN)); trc(F("RF_EMITTER_PIN "));
trc(F("RF_RECEIVER_PIN ")); trc(String(RF_EMITTER_PIN));
trc(String(RF_RECEIVER_PIN)); trc(F("RF_RECEIVER_PIN "));
trc(F("ZgatewayPilight setup done ")); trc(String(RF_RECEIVER_PIN));
#else trc(F("ZgatewayPilight setup done "));
trc(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2 && ZgatewayRF315")); #else
#endif trc(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2 && ZgatewayRF315"));
#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: {
trc(F("'c' not found in string, or has no data")); case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C:
break; trc(F("'c' not found in string, or has no data"));
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P: break;
trc(F("'p' not found in string, or has no data")); case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P:
break; trc(F("'p' not found in string, or has no data"));
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END: break;
trc(F("';' or '@' not found in data string")); case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END:
break; trc(F("';' or '@' not found in data string"));
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE: break;
trc(F("pulse type not defined")); case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE:
break; trc(F("pulse type not defined"));
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
case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL: {
trc(F("protocol is not available")); switch (result)
break; {
case ESPiLight::ERROR_INVALID_PILIGHT_MSG: case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL:
trc(F("message is invalid")); trc(F("protocol is not available"));
break; break;
case ESPiLight::ERROR_INVALID_JSON: case ESPiLight::ERROR_INVALID_PILIGHT_MSG:
trc(F("message is not a proper json object")); trc(F("message is invalid"));
break; break;
case ESPiLight::ERROR_NO_OUTPUT_PIN: case ESPiLight::ERROR_INVALID_JSON:
trc(F("no transmitter pin")); trc(F("message is not a proper json object"));
break; break;
default: case ESPiLight::ERROR_NO_OUTPUT_PIN:
trc(F("invalid json data, can't read raw or message/protocol")); trc(F("no transmitter pin"));
break; break;
default:
trc(F("invalid json data, can't read raw or message/protocol"));
break;
} }
} }
} }
} }
#endif #endif
+99 -78
View File
@@ -34,146 +34,167 @@
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"));
char * switchRF[8] = {"switch", val, "", "","",val, "", ""}; char *switchRF[8] = {"switch", val, "", "", "", val, "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement //component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySwitch")); trc(F("CreateDiscoverySwitch"));
trc(switchRF[1]); trc(switchRF[1]);
createDiscovery(switchRF[0], createDiscovery(switchRF[0],
subjectRFtoMQTT, switchRF[1], (char *)getUniqueId(switchRF[1], switchRF[2]).c_str(), subjectRFtoMQTT, switchRF[1], (char *)getUniqueId(switchRF[1], switchRF[2]).c_str(),
will_Topic, switchRF[3], switchRF[4], will_Topic, switchRF[3], switchRF[4],
switchRF[5], switchRF[6], switchRF[7], switchRF[5], switchRF[6], switchRF[7],
0,"","",true,subjectMQTTtoRF); 0, "", "", true, subjectMQTTtoRF);
} }
#endif #endif
void setupRF(){ void setupRF()
{
//RF init parameters //RF init parameters
mySwitch.enableTransmit(RF_EMITTER_PIN); mySwitch.enableTransmit(RF_EMITTER_PIN);
trc(F("RF_EMITTER_PIN ")); trc(F("RF_EMITTER_PIN "));
trc(RF_EMITTER_PIN); trc(RF_EMITTER_PIN);
mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT);
mySwitch.enableReceive(RF_RECEIVER_PIN); mySwitch.enableReceive(RF_RECEIVER_PIN);
trc(F("RF_RECEIVER_PIN ")); trc(F("RF_RECEIVER_PIN "));
trc(RF_RECEIVER_PIN); trc(RF_RECEIVER_PIN);
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();
trc(F("Rcv. RF")); trc(F("Rcv. RF"));
#ifdef ESP32 #ifdef ESP32
String taskMessage = "RF Task running on core "; String taskMessage = "RF Task running on core ";
taskMessage = taskMessage + xPortGetCoreID(); taskMessage = taskMessage + xPortGetCoreID();
trc(taskMessage); trc(taskMessage);
#endif #endif
RFdata.set("value", (unsigned long)mySwitch.getReceivedValue()); RFdata.set("value", (unsigned long)mySwitch.getReceivedValue());
RFdata.set("protocol",(int)mySwitch.getReceivedProtocol()); RFdata.set("protocol", (int)mySwitch.getReceivedProtocol());
RFdata.set("length", (int)mySwitch.getReceivedBitlength()); RFdata.set("length", (int)mySwitch.getReceivedBitlength());
RFdata.set("delay", (int)mySwitch.getReceivedDelay()); RFdata.set("delay", (int)mySwitch.getReceivedDelay());
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)
#ifdef ZmqttDiscovery //component creation for HA { // conditions to avoid duplications of RF -->MQTT
RFtoMQTTdiscovery(MQTTvalue); #ifdef ZmqttDiscovery //component creation for HA
#endif RFtoMQTTdiscovery(MQTTvalue);
pub(subjectRFtoMQTT,RFdata); #endif
trc(F("Store val")); pub(subjectRFtoMQTT, RFdata);
storeValue(MQTTvalue); trc(F("Store val"));
if (repeatRFwMQTT){ storeValue(MQTTvalue);
trc(F("Pub RF for rpt")); if (repeatRFwMQTT)
pub(subjectMQTTtoRF,RFdata); {
} trc(F("Pub RF for rpt"));
} pub(subjectMQTTtoRF, RFdata);
}
}
} }
} }
#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
// 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
String topic = topicOri; String topic = topicOri;
int valuePRT = 0; int valuePRT = 0;
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:"));
trc(valuePRT); trc(valuePRT);
} }
//We look into the subject to see if a special RF pulselength is defined //We look into the subject to see if a special RF pulselength is defined
int pos2 = topic.lastIndexOf(RFpulselengthKey); 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);
mySwitch.setProtocol(valuePRT,valuePLSL); mySwitch.setProtocol(valuePRT, valuePLSL);
mySwitch.send(data, valueBITS); mySwitch.send(data, valueBITS);
// Acknowledgement to the GTWRF topic // Acknowledgement to the GTWRF topic
pub(subjectGTWRFtoMQTT, datacallback);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also pub(subjectGTWRFtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} }
} }
#endif #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
trc(F("MQTTtoRF json")); if (cmpToMainTopic(topicOri, subjectMQTTtoRF))
unsigned long data = RFdata["value"]; {
if (data != 0) { trc(F("MQTTtoRF json"));
int valuePRT = RFdata["protocol"]|1; unsigned long data = RFdata["value"];
int valuePLSL = RFdata["delay"]|350; if (data != 0)
int valueBITS = RFdata["length"]|24; {
int valueRPT = RFdata["repeat"]|RF_EMITTER_REPEAT; int valuePRT = RFdata["protocol"] | 1;
mySwitch.setRepeatTransmit(valueRPT); int valuePLSL = RFdata["delay"] | 350;
mySwitch.setProtocol(valuePRT,valuePLSL); int valueBITS = RFdata["length"] | 24;
mySwitch.send(data, valueBITS); int valueRPT = RFdata["repeat"] | RF_EMITTER_REPEAT;
trc(F("MQTTtoRF OK")); mySwitch.setRepeatTransmit(valueRPT);
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.setProtocol(valuePRT, valuePLSL);
mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); // Restore the default value mySwitch.send(data, valueBITS);
}else{ trc(F("MQTTtoRF OK"));
trc(F("MQTTtoRF Fail json")); pub(subjectGTWRFtoMQTT, RFdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
} mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); // Restore the default value
}
else
{
trc(F("MQTTtoRF Fail json"));
} }
} }
}
#endif #endif
#endif #endif
+215 -179
View File
@@ -52,220 +52,256 @@ struct RF2rxd
RF2rxd rf2rd; RF2rxd rf2rd;
void setupRF2(){ void setupRF2()
#ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF {
NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback); #ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF
trc(F("RF_EMITTER_PIN ")); NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback);
trc(RF_EMITTER_PIN); trc(F("RF_EMITTER_PIN "));
trc(F("RF_RECEIVER_PIN ")); trc(RF_EMITTER_PIN);
trc(RF_RECEIVER_PIN); trc(F("RF_RECEIVER_PIN "));
trc(F("ZgatewayRF2 setup done ")); trc(RF_RECEIVER_PIN);
#endif trc(F("ZgatewayRF2 setup done "));
pinMode(RF_EMITTER_PIN, OUTPUT); #endif
digitalWrite(RF_EMITTER_PIN, LOW); pinMode(RF_EMITTER_PIN, OUTPUT);
digitalWrite(RF_EMITTER_PIN, LOW);
} }
void RF2toMQTT(){ void RF2toMQTT()
{
if(rf2rd.hasNewData){ if (rf2rd.hasNewData)
{
trc(F("Creating RF2 buffer")); 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;
JsonObject& RF2data = jsonBuffer.createObject(); JsonObject &RF2data = jsonBuffer.createObject();
rf2rd.hasNewData = false; rf2rd.hasNewData = false;
trc(F("Rcv. RF2")); trc(F("Rcv. RF2"));
RF2data.set("unit", (int)rf2rd.unit); RF2data.set("unit", (int)rf2rd.unit);
RF2data.set("groupBit", (int)rf2rd.groupBit); RF2data.set("groupBit", (int)rf2rd.groupBit);
RF2data.set("period", (int)rf2rd.period); RF2data.set("period", (int)rf2rd.period);
RF2data.set("address", (unsigned long)rf2rd.address); RF2data.set("address", (unsigned long)rf2rd.address);
RF2data.set("switchType", (int)rf2rd.switchType); RF2data.set("switchType", (int)rf2rd.switchType);
trc(F("Adv data RF2toMQTT")); trc(F("Adv data RF2toMQTT"));
pub(subjectRF2toMQTT,RF2data); pub(subjectRF2toMQTT, RF2data);
} }
} }
void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType) { void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType)
{
rf2rd.period=period;
rf2rd.address=address;
rf2rd.groupBit=groupBit;
rf2rd.unit=unit;
rf2rd.switchType=switchType;
rf2rd.hasNewData=true;
rf2rd.period = period;
rf2rd.address = address;
rf2rd.groupBit = groupBit;
rf2rd.unit = unit;
rf2rd.switchType = switchType;
rf2rd.hasNewData = true;
} }
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoRF2(char * topicOri, char * datacallback) { void MQTTtoRF2(char *topicOri, char *datacallback)
{
// RF DATA ANALYSIS
//We look into the subject to see if a special RF protocol is defined // RF DATA ANALYSIS
String topic = topicOri; //We look into the subject to see if a special RF protocol is defined
bool boolSWITCHTYPE; String topic = topicOri;
boolSWITCHTYPE = to_bool(datacallback); bool boolSWITCHTYPE;
bool isDimCommand = false; boolSWITCHTYPE = to_bool(datacallback);
bool isDimCommand = false;
long valueCODE = 0;
int valueUNIT = -1; long valueCODE = 0;
int valuePERIOD = 0; int valueUNIT = -1;
int valueGROUP = 0; int valuePERIOD = 0;
int valueDIM = -1; int valueGROUP = 0;
int valueDIM = -1;
int pos = topic.lastIndexOf(RF2codeKey);
if (pos != -1){ int pos = topic.lastIndexOf(RF2codeKey);
pos = pos + +strlen(RF2codeKey); if (pos != -1)
valueCODE = (topic.substring(pos,pos + 8)).toInt(); {
trc(F("RF2 code:")); pos = pos + +strlen(RF2codeKey);
trc(valueCODE); valueCODE = (topic.substring(pos, pos + 8)).toInt();
} trc(F("RF2 code:"));
int pos2 = topic.lastIndexOf(RF2periodKey); trc(valueCODE);
if (pos2 != -1) { }
pos2 = pos2 + strlen(RF2periodKey); int pos2 = topic.lastIndexOf(RF2periodKey);
valuePERIOD = (topic.substring(pos2,pos2 + 3)).toInt(); if (pos2 != -1)
trc(F("RF2 Period:")); {
trc(valuePERIOD); pos2 = pos2 + strlen(RF2periodKey);
} valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt();
int pos3 = topic.lastIndexOf(RF2unitKey); trc(F("RF2 Period:"));
if (pos3 != -1){ trc(valuePERIOD);
pos3 = pos3 + strlen(RF2unitKey); }
valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt(); int pos3 = topic.lastIndexOf(RF2unitKey);
trc(F("Unit:")); if (pos3 != -1)
trc(valueUNIT); {
} pos3 = pos3 + strlen(RF2unitKey);
int pos4 = topic.lastIndexOf(RF2groupKey); valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt();
if (pos4 != -1) { trc(F("Unit:"));
pos4 = pos4 + strlen(RF2groupKey); trc(valueUNIT);
valueGROUP = (topic.substring(pos4,pos4 + 1)).toInt(); }
trc(F("RF2 Group:")); int pos4 = topic.lastIndexOf(RF2groupKey);
trc(valueGROUP); if (pos4 != -1)
} {
int pos5 = topic.lastIndexOf(RF2dimKey); pos4 = pos4 + strlen(RF2groupKey);
if (pos5 != -1) { valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt();
isDimCommand = true; trc(F("RF2 Group:"));
valueDIM = atoi(datacallback); trc(valueGROUP);
trc(F("RF2 Dim:")); }
trc(valueDIM); int pos5 = topic.lastIndexOf(RF2dimKey);
} if (pos5 != -1)
{
if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){ isDimCommand = true;
trc(F("MQTTtoRF2")); valueDIM = atoi(datacallback);
if (valueCODE == 0) valueCODE = 8233378; trc(F("RF2 Dim:"));
if (valueUNIT == -1) valueUNIT = 0; trc(valueDIM);
if (valuePERIOD == 0) valuePERIOD = 272; }
trc(valueCODE);
trc(valueUNIT); if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0))
trc(valuePERIOD); {
trc(valueGROUP); trc(F("MQTTtoRF2"));
trc(boolSWITCHTYPE); if (valueCODE == 0)
trc(valueDIM); valueCODE = 8233378;
NewRemoteReceiver::disable(); if (valueUNIT == -1)
trc(F("Creating transmitter")); valueUNIT = 0;
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); if (valuePERIOD == 0)
trc(F("Sending data")); valuePERIOD = 272;
if (valueGROUP) { trc(valueCODE);
if (isDimCommand) { trc(valueUNIT);
transmitter.sendGroupDim(valueDIM); trc(valuePERIOD);
} trc(valueGROUP);
else { trc(boolSWITCHTYPE);
transmitter.sendGroup(boolSWITCHTYPE); trc(valueDIM);
} NewRemoteReceiver::disable();
trc(F("Creating transmitter"));
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
trc(F("Sending data"));
if (valueGROUP)
{
if (isDimCommand)
{
transmitter.sendGroupDim(valueDIM);
} }
else { else
if (isDimCommand) { {
transmitter.sendDim(valueUNIT, valueDIM); transmitter.sendGroup(boolSWITCHTYPE);
}
else {
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
}
} }
trc(F("Data sent")); }
NewRemoteReceiver::enable(); else
{
// Publish state change back to MQTT if (isDimCommand)
String MQTTAddress; {
String MQTTperiod; transmitter.sendDim(valueUNIT, valueDIM);
String MQTTunit;
String MQTTgroupBit;
String MQTTswitchType;
String MQTTdimLevel;
MQTTAddress = String(valueCODE);
MQTTperiod = String(valuePERIOD);
MQTTunit = String(valueUNIT);
MQTTgroupBit = String(rf2rd.groupBit);
MQTTswitchType = String(boolSWITCHTYPE);
MQTTdimLevel = String(valueDIM);
String MQTTRF2string;
trc(F("Adv data MQTTtoRF2 push state via RF2toMQTT"));
if (isDimCommand) {
MQTTRF2string = subjectRF2toMQTT+String("/")+RF2codeKey+MQTTAddress+String("/")+RF2unitKey+MQTTunit+String("/")+RF2groupKey+MQTTgroupBit+String("/")+RF2dimKey+String("/")+RF2periodKey+MQTTperiod;
pub((char *)MQTTRF2string.c_str(),(char *)MQTTdimLevel.c_str());
} }
else { else
MQTTRF2string = subjectRF2toMQTT+String("/")+RF2codeKey+MQTTAddress+String("/")+RF2unitKey+MQTTunit+String("/")+RF2groupKey+MQTTgroupBit+String("/")+RF2periodKey+MQTTperiod; {
pub((char *)MQTTRF2string.c_str(),(char *)MQTTswitchType.c_str()); transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
} }
} }
trc(F("Data sent"));
NewRemoteReceiver::enable();
// Publish state change back to MQTT
String MQTTAddress;
String MQTTperiod;
String MQTTunit;
String MQTTgroupBit;
String MQTTswitchType;
String MQTTdimLevel;
MQTTAddress = String(valueCODE);
MQTTperiod = String(valuePERIOD);
MQTTunit = String(valueUNIT);
MQTTgroupBit = String(rf2rd.groupBit);
MQTTswitchType = String(boolSWITCHTYPE);
MQTTdimLevel = String(valueDIM);
String MQTTRF2string;
trc(F("Adv data MQTTtoRF2 push state via RF2toMQTT"));
if (isDimCommand)
{
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2dimKey + String("/") + RF2periodKey + MQTTperiod;
pub((char *)MQTTRF2string.c_str(), (char *)MQTTdimLevel.c_str());
}
else
{
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod;
pub((char *)MQTTRF2string.c_str(), (char *)MQTTswitchType.c_str());
}
} }
}
#endif #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)){
trc(F("MQTTtoRF2 json")); if (cmpToMainTopic(topicOri, subjectMQTTtoRF2))
int boolSWITCHTYPE = RF2data["switchType"] | 99; {
if (boolSWITCHTYPE != 99) { trc(F("MQTTtoRF2 json"));
trc(F("MQTTtoRF2 switch type ok")); int boolSWITCHTYPE = RF2data["switchType"] | 99;
bool isDimCommand = boolSWITCHTYPE == 2; if (boolSWITCHTYPE != 99)
unsigned long valueCODE = RF2data["address"]; {
int valueUNIT = RF2data["unit"] | -1; trc(F("MQTTtoRF2 switch type ok"));
int valuePERIOD = RF2data["period"]; bool isDimCommand = boolSWITCHTYPE == 2;
int valueGROUP = RF2data["group"]; unsigned long valueCODE = RF2data["address"];
int valueDIM = RF2data["dim"] | -1; int valueUNIT = RF2data["unit"] | -1;
if ((valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){ int valuePERIOD = RF2data["period"];
trc(F("MQTTtoRF2")); int valueGROUP = RF2data["group"];
if (valueCODE == 0) valueCODE = 8233378; int valueDIM = RF2data["dim"] | -1;
if (valueUNIT == -1) valueUNIT = 0; if ((valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0))
if (valuePERIOD == 0) valuePERIOD = 272; {
trc(valueCODE); trc(F("MQTTtoRF2"));
trc(valueUNIT); if (valueCODE == 0)
trc(valuePERIOD); valueCODE = 8233378;
trc(valueGROUP); if (valueUNIT == -1)
trc(boolSWITCHTYPE); valueUNIT = 0;
trc(valueDIM); if (valuePERIOD == 0)
NewRemoteReceiver::disable(); valuePERIOD = 272;
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD); trc(valueCODE);
trc(F("Sending")); trc(valueUNIT);
if (valueGROUP) { trc(valuePERIOD);
if (isDimCommand) { trc(valueGROUP);
transmitter.sendGroupDim(valueDIM); trc(boolSWITCHTYPE);
} trc(valueDIM);
else { NewRemoteReceiver::disable();
transmitter.sendGroup(boolSWITCHTYPE); NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
} trc(F("Sending"));
if (valueGROUP)
{
if (isDimCommand)
{
transmitter.sendGroupDim(valueDIM);
} }
else { else
if (isDimCommand) { {
transmitter.sendDim(valueUNIT, valueDIM); transmitter.sendGroup(boolSWITCHTYPE);
}
else {
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
}
} }
trc(F("MQTTtoRF2 OK"));
NewRemoteReceiver::enable();
// Publish state change back to MQTT
pub(subjectGTWRF2toMQTT,RF2data);
} }
}else{ else
trc(F("MQTTtoRF2 failed json read")); {
if (isDimCommand)
{
transmitter.sendDim(valueUNIT, valueDIM);
}
else
{
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
}
}
trc(F("MQTTtoRF2 OK"));
NewRemoteReceiver::enable();
// Publish state change back to MQTT
pub(subjectGTWRF2toMQTT, RF2data);
} }
} }
else
{
trc(F("MQTTtoRF2 failed json read"));
}
} }
}
#endif #endif
#endif #endif
+124 -98
View File
@@ -32,7 +32,7 @@
#ifdef ZgatewayRFM69 #ifdef ZgatewayRFM69
#include <RFM69.h> //https://www.github.com/lowpowerlab/rfm69 #include <RFM69.h> //https://www.github.com/lowpowerlab/rfm69
#include <SPI.h> #include <SPI.h>
#include <EEPROM.h> #include <EEPROM.h>
@@ -40,46 +40,51 @@ char RadioConfig[128];
// vvvvvvvvv Global Configuration vvvvvvvvvvv // vvvvvvvvv Global Configuration vvvvvvvvvvv
struct _GLOBAL_CONFIG { struct _GLOBAL_CONFIG
uint32_t checksum; {
char rfmapname[32]; uint32_t checksum;
char encryptkey[16+1]; char rfmapname[32];
uint8_t networkid; char encryptkey[16 + 1];
uint8_t nodeid; uint8_t networkid;
uint8_t powerlevel; // bits 0..4 power leve, bit 7 RFM69HCW 1=true uint8_t nodeid;
uint8_t rfmfrequency; uint8_t powerlevel; // bits 0..4 power leve, bit 7 RFM69HCW 1=true
uint8_t rfmfrequency;
}; };
#define GC_POWER_LEVEL (pGC->powerlevel & 0x1F) #define GC_POWER_LEVEL (pGC->powerlevel & 0x1F)
#define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0) #define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0)
#define SELECTED_FREQ(f) ((pGC->rfmfrequency==f)?"selected":"") #define SELECTED_FREQ(f) ((pGC->rfmfrequency == f) ? "selected" : "")
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);
strcpy_P(pGC->rfmapname, RFM69AP_NAME); strcpy_P(pGC->rfmapname, RFM69AP_NAME);
pGC->networkid = NETWORKID; pGC->networkid = NETWORKID;
pGC->nodeid = NODEID; pGC->nodeid = NODEID;
pGC->powerlevel = ((IS_RFM69HCW)?0x80:0x00) | POWER_LEVEL; pGC->powerlevel = ((IS_RFM69HCW) ? 0x80 : 0x00) | POWER_LEVEL;
pGC->rfmfrequency = FREQUENCY; pGC->rfmfrequency = FREQUENCY;
pGC->checksum = gc_checksum(); pGC->checksum = gc_checksum();
EEPROM.commit(); EEPROM.commit();
@@ -89,13 +94,14 @@ void eeprom_setup() {
RFM69 radio; RFM69 radio;
void setupRFM69(void) { void setupRFM69(void)
#if defined(ESP8266) || defined(ESP32) {
eeprom_setup(); #if defined(ESP8266) || defined(ESP32)
#endif eeprom_setup();
#endif
int freq; int freq;
static const char PROGMEM JSONtemplate[] = static const char PROGMEM JSONtemplate[] =
R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})"; R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})";
char payload[128]; char payload[128];
radio = RFM69(RFM69_CS, RFM69_IRQ, GC_IS_RFM69HCW, RFM69_IRQN); radio = RFM69(RFM69_CS, RFM69_IRQ, GC_IS_RFM69HCW, RFM69_IRQN);
@@ -104,57 +110,62 @@ void setupRFM69(void) {
if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid)) if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid))
{ {
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: {
freq = 433; case RF69_433MHZ:
break; freq = 433;
case RF69_868MHZ: break;
freq = 868; case RF69_868MHZ:
break; freq = 868;
case RF69_915MHZ: break;
freq = 915; case RF69_915MHZ:
break; freq = 915;
case RF69_315MHZ: break;
freq = 315; case RF69_315MHZ:
break; freq = 315;
default: break;
freq = -1; default:
break; freq = -1;
break;
} }
trc(freq); trc(freq);
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())
{ {
trc(F("Creating RFM69 buffer")); trc(F("Creating RFM69 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& RFM69data = jsonBuffer.createObject(); JsonObject &RFM69data = jsonBuffer.createObject();
uint8_t data[RF69_MAX_DATA_LEN+1]; // For the null character uint8_t data[RF69_MAX_DATA_LEN + 1]; // For the null character
uint8_t SENDERID = radio.SENDERID; uint8_t SENDERID = radio.SENDERID;
uint8_t DATALEN = radio.DATALEN; uint8_t DATALEN = radio.DATALEN;
uint16_t RSSI = radio.RSSI; uint16_t RSSI = radio.RSSI;
//save packet because it may be overwritten //save packet because it may be overwritten
memcpy(data, (void *)radio.DATA, DATALEN); memcpy(data, (void *)radio.DATA, DATALEN);
data[DATALEN] = '\0'; // Terminate the string data[DATALEN] = '\0'; // Terminate the string
// Ack as soon as possible // Ack as soon as possible
//check if sender wanted an ACK //check if sender wanted an ACK
@@ -167,73 +178,88 @@ bool RFM69toMQTT(void) {
trc(F("Data received")); trc(F("Data received"));
trc((const char *)data); trc((const char *)data);
char buff[sizeof(subjectRFM69toMQTT)+4]; char buff[sizeof(subjectRFM69toMQTT) + 4];
sprintf(buff, "%s/%d", subjectRFM69toMQTT, SENDERID); sprintf(buff, "%s/%d", subjectRFM69toMQTT, SENDERID);
RFM69data.set("data", (char *)data); RFM69data.set("data", (char *)data);
RFM69data.set("rssi", (int)radio.RSSI); RFM69data.set("rssi", (int)radio.RSSI);
RFM69data.set("senderid", (int)radio.SENDERID); RFM69data.set("senderid", (int)radio.SENDERID);
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")); {
char data[RF69_MAX_DATA_LEN+1]; trc(F("MQTTtoRFM69 data analysis"));
memcpy(data, (void *)datacallback, RF69_MAX_DATA_LEN); char data[RF69_MAX_DATA_LEN + 1];
data[RF69_MAX_DATA_LEN] = '\0'; memcpy(data, (void *)datacallback, RF69_MAX_DATA_LEN);
data[RF69_MAX_DATA_LEN] = '\0';
//We look into the subject to see if a special RF protocol is defined
String topic = topicOri; //We look into the subject to see if a special RF protocol is defined
int valueRCV = defaultRFM69ReceiverId; //default receiver id value String topic = topicOri;
int pos = topic.lastIndexOf(RFM69receiverKey); int valueRCV = defaultRFM69ReceiverId; //default receiver id value
if (pos != -1){ int pos = topic.lastIndexOf(RFM69receiverKey);
pos = pos + +strlen(RFM69receiverKey); if (pos != -1)
valueRCV = (topic.substring(pos,pos + 3)).toInt(); {
trc(F("RFM69 receiver ID:")); pos = pos + +strlen(RFM69receiverKey);
trc(valueRCV); valueRCV = (topic.substring(pos, pos + 3)).toInt();
} trc(F("RFM69 receiver ID:"));
if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) { trc(valueRCV);
trc(F(" OK ")); }
// Acknowledgement to the GTWRF topic if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
char buff[sizeof(subjectGTWRFM69toMQTT)+4]; {
sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID); trc(F(" OK "));
pub(buff, data); // Acknowledgement to the GTWRF topic
} else { char buff[sizeof(subjectGTWRFM69toMQTT) + 4];
trc(F("RFM69 sending failed")); sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID);
} pub(buff, data);
}
else
{
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)){
const char * data = RFM69data["data"]; if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
trc(F("MQTTtoRFM69 json data analysis")); {
if(data){ const char *data = RFM69data["data"];
trc(F("MQTTtoRFM69 data ok")); trc(F("MQTTtoRFM69 json data analysis"));
int valueRCV = RFM69data["receiverid"]| defaultRFM69ReceiverId; //default receiver id value if (data)
trc(F("RFM69 receiver ID:")); {
trc(valueRCV); trc(F("MQTTtoRFM69 data ok"));
if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) { int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value
trc(F(" OK ")); trc(F("RFM69 receiver ID:"));
// Acknowledgement to the GTWRF topic trc(valueRCV);
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 if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
} else { {
trc(F("MQTTtoRFM69 sending failed")); trc(F(" OK "));
} // Acknowledgement to the GTWRF topic
}else{ 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
trc(F("MQTTtoRFM69 failed json read")); }
else
{
trc(F("MQTTtoRFM69 sending failed"));
} }
} }
else
{
trc(F("MQTTtoRFM69 failed json read"));
}
} }
}
#endif #endif
#endif #endif
+296 -246
View File
@@ -32,307 +32,357 @@
#ifdef ZgatewaySRFB #ifdef ZgatewaySRFB
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.write(RF_CODE_START); Serial.println();
Serial.write(RF_CODE_RFOUT); Serial.write(RF_CODE_START);
for (unsigned char j=0; j<RF_MESSAGE_SIZE; j++) { Serial.write(RF_CODE_RFOUT);
Serial.write(message[j]); for (unsigned char j = 0; j < RF_MESSAGE_SIZE; j++)
} {
Serial.write(RF_CODE_STOP); Serial.write(message[j]);
Serial.flush(); }
Serial.println(); Serial.write(RF_CODE_STOP);
Serial.flush();
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) { {
unsigned long start = millis(); if (i > 0)
while (millis() - start < RF_SEND_DELAY) delay(1); {
} unsigned long start = millis();
_rfbSend(message); while (millis() - start < RF_SEND_DELAY)
delay(1);
} }
_rfbSend(message);
}
} }
bool SRFBtoMQTT() { bool SRFBtoMQTT()
{
static bool receiving = false;
while (Serial.available()) { static bool receiving = false;
yield();
byte c = Serial.read();
if (receiving) { while (Serial.available())
if (c == RF_CODE_STOP) { {
_rfbDecode(); yield();
receiving = false; byte c = Serial.read();
} else {
_uartbuf[_uartpos++] = c;
}
} else if (c == RF_CODE_START) {
_uartpos = 0;
receiving = true;
}
if (receiving)
{
if (c == RF_CODE_STOP)
{
_rfbDecode();
receiving = false;
}
else
{
_uartbuf[_uartpos++] = c;
}
} }
return receiving; else if (c == RF_CODE_START)
{
_uartpos = 0;
receiving = true;
}
}
return receiving;
} }
void _rfbDecode() { void _rfbDecode()
{
static unsigned long last = 0; static unsigned long last = 0;
if (millis() - last < RF_RECEIVE_DELAY) return; if (millis() - last < RF_RECEIVE_DELAY)
last = millis(); return;
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"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& SRFBdata = jsonBuffer.createObject(); JsonObject &SRFBdata = jsonBuffer.createObject();
SRFBdata.set("raw", (char *)buffer); SRFBdata.set("raw", (char *)buffer);
char Tsyn[4]= {0}; char Tsyn[4] = {0};
extract_char(buffer, Tsyn , 0 ,4, false, true); extract_char(buffer, Tsyn, 0, 4, false, true);
int val_Tsyn = (int)strtol(Tsyn, NULL, 10); int val_Tsyn = (int)strtol(Tsyn, NULL, 10);
SRFBdata.set("delay", (int)val_Tsyn); SRFBdata.set("delay", (int)val_Tsyn);
char Tlow[4]= {0}; char Tlow[4] = {0};
extract_char(buffer,Tlow , 4 ,4, false, true); extract_char(buffer, Tlow, 4, 4, false, true);
int val_Tlow = (int)strtol(Tlow, NULL, 10); int val_Tlow = (int)strtol(Tlow, NULL, 10);
SRFBdata.set("val_Tlow", (int)val_Tlow); SRFBdata.set("val_Tlow", (int)val_Tlow);
char Thigh[4]= {0}; char Thigh[4] = {0};
extract_char(buffer, Thigh , 8 ,4, false, true); extract_char(buffer, Thigh, 8, 4, false, true);
int val_Thigh = (int)strtol(Thigh, NULL, 10); int val_Thigh = (int)strtol(Thigh, NULL, 10);
SRFBdata.set("val_Thigh", (int)val_Thigh); SRFBdata.set("val_Thigh", (int)val_Thigh);
char val[8]= {0}; char val[8] = {0};
extract_char(buffer, val, 12 ,8, false,true); extract_char(buffer, val, 12, 8, false, true);
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)
trc(F("Adv data SRFBtoMQTT")); { // conditions to avoid duplications of RF -->MQTT
pub(subjectSRFBtoMQTT,SRFBdata); trc(F("Adv data SRFBtoMQTT"));
trc(F("Store val")); pub(subjectSRFBtoMQTT, SRFBdata);
storeValue(MQTTvalue); trc(F("Store val"));
if (repeatSRFBwMQTT){ storeValue(MQTTvalue);
trc(F("Publish SRFB for rpt")); if (repeatSRFBwMQTT)
pub(subjectMQTTtoSRFB,SRFBdata); {
} trc(F("Publish SRFB for rpt"));
} pub(subjectMQTTtoSRFB, SRFBdata);
_rfbAck(); }
} }
_rfbAck();
}
} }
void _rfbAck() { void _rfbAck()
trc(F("[RFBRIDGE] Sending ACK\n")); {
Serial.println(); trc(F("[RFBRIDGE] Sending ACK\n"));
Serial.write(RF_CODE_START); Serial.println();
Serial.write(RF_CODE_ACK); Serial.write(RF_CODE_START);
Serial.write(RF_CODE_STOP); Serial.write(RF_CODE_ACK);
Serial.flush(); Serial.write(RF_CODE_STOP);
Serial.println(); Serial.flush();
Serial.println();
} }
/* /*
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; {
char tmp[3] = {0}; if (strlen(in) != RF_MESSAGE_SIZE * 2)
for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) { return false;
memcpy(tmp, &in[p*2], 2); char tmp[3] = {0};
out[p] = strtol(tmp, NULL, 16); for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++)
} {
return true; memcpy(tmp, &in[p * 2], 2);
out[p] = strtol(tmp, NULL, 16);
}
return true;
} }
/* /*
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++) { {
sprintf_P(&out[p*2], PSTR("%02X"), in[p]); for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++)
} {
return true; sprintf_P(&out[p * 2], PSTR("%02X"), in[p]);
}
return true;
} }
#ifdef simpleReceiving #ifdef simpleReceiving
void MQTTtoSRFB(char * topicOri, char * datacallback) { void MQTTtoSRFB(char *topicOri, char *datacallback)
{
// RF DATA ANALYSIS
String topic = topicOri; // RF DATA ANALYSIS
int valueRPT = 0; String topic = topicOri;
int valueRPT = 0;
if (topic == subjectMQTTtoSRFB){
if (topic == subjectMQTTtoSRFB)
int valueMiniPLSL = 0; {
int valueMaxiPLSL = 0;
int valueSYNC = 0; int valueMiniPLSL = 0;
int valueMaxiPLSL = 0;
int pos = topic.lastIndexOf(SRFBRptKey); int valueSYNC = 0;
if (pos != -1){
pos = pos + +strlen(SRFBRptKey); int pos = topic.lastIndexOf(SRFBRptKey);
valueRPT = (topic.substring(pos,pos + 1)).toInt(); if (pos != -1)
trc(F("SRFB Repeat:")); {
trc(valueRPT); pos = pos + +strlen(SRFBRptKey);
} valueRPT = (topic.substring(pos, pos + 1)).toInt();
trc(F("SRFB Repeat:"));
int pos2 = topic.lastIndexOf(SRFBminipulselengthKey); trc(valueRPT);
if (pos2 != -1) { }
pos2 = pos2 + strlen(SRFBminipulselengthKey);
valueMiniPLSL = (topic.substring(pos2,pos2 + 3)).toInt(); int pos2 = topic.lastIndexOf(SRFBminipulselengthKey);
trc(F("RF Mini Pulse Lgth:")); if (pos2 != -1)
trc(valueMiniPLSL); {
} pos2 = pos2 + strlen(SRFBminipulselengthKey);
valueMiniPLSL = (topic.substring(pos2, pos2 + 3)).toInt();
int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey); trc(F("RF Mini Pulse Lgth:"));
if (pos3 != -1){ trc(valueMiniPLSL);
pos3 = pos3 + strlen(SRFBmaxipulselengthKey); }
valueMaxiPLSL = (topic.substring(pos3,pos3 + 2)).toInt();
trc(F("RF Maxi Pulse Lgth:")); int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey);
trc(valueMaxiPLSL); if (pos3 != -1)
} {
pos3 = pos3 + strlen(SRFBmaxipulselengthKey);
int pos4 = topic.lastIndexOf(SRFBsyncKey); valueMaxiPLSL = (topic.substring(pos3, pos3 + 2)).toInt();
if (pos4 != -1){ trc(F("RF Maxi Pulse Lgth:"));
pos4 = pos4 + strlen(SRFBsyncKey); trc(valueMaxiPLSL);
valueSYNC = (topic.substring(pos4,pos4 + 2)).toInt(); }
trc(F("RF sync:"));
trc(valueSYNC); int pos4 = topic.lastIndexOf(SRFBsyncKey);
} if (pos4 != -1)
{
trc(F("MQTTtoSRFB prts")); pos4 = pos4 + strlen(SRFBsyncKey);
if (valueRPT == 0) valueRPT = 1; valueSYNC = (topic.substring(pos4, pos4 + 2)).toInt();
if (valueMiniPLSL == 0) valueMiniPLSL = 320; trc(F("RF sync:"));
if (valueMaxiPLSL == 0) valueMaxiPLSL = 900; trc(valueSYNC);
if (valueSYNC == 0) valueSYNC = 9500; }
trc(F("MQTTtoSRFB prts"));
if (valueRPT == 0)
valueRPT = 1;
if (valueMiniPLSL == 0)
valueMiniPLSL = 320;
if (valueMaxiPLSL == 0)
valueMaxiPLSL = 900;
if (valueSYNC == 0)
valueSYNC = 9500;
byte hex_valueMiniPLSL[2];
hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF);
hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF);
byte hex_valueMaxiPLSL[2];
hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF);
hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF);
byte hex_valueSYNC[2];
hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF);
hex_valueSYNC[1] = (int)(valueSYNC & 0xFF);
unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
byte hex_data[3];
hex_data[0] = (unsigned long)((data >> 16) & 0xFF);
hex_data[1] = (unsigned long)((data >> 8) & 0xFF);
hex_data[2] = (unsigned long)(data & 0xFF);
byte message_b[RF_MESSAGE_SIZE];
memcpy(message_b, hex_valueSYNC, 2);
memcpy(message_b + 2, hex_valueMiniPLSL, 2);
memcpy(message_b + 4, hex_valueMaxiPLSL, 2);
memcpy(message_b + 6, hex_data, 3);
_rfbSend(message_b, valueRPT);
// Acknowledgement to the GTWRF topic
pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
if (topic == subjectMQTTtoSRFBRaw)
{
int pos = topic.lastIndexOf(SRFBRptKey);
if (pos != -1)
{
pos = pos + +strlen(SRFBRptKey);
valueRPT = (topic.substring(pos, pos + 1)).toInt();
trc(F("SRFB Repeat:"));
trc(valueRPT);
}
if (valueRPT == 0)
valueRPT = 1;
byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(datacallback, message_b);
_rfbSend(message_b, valueRPT);
// Acknowledgement to the GTWRF topic
pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}
#endif
#ifdef jsonReceiving
void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata)
{
// RF DATA ANALYSIS
const char *raw = SRFBdata["raw"];
int valueRPT = SRFBdata["repeat"] | 1;
if (cmpToMainTopic(topicOri, subjectMQTTtoSRFB))
{
trc(F("MQTTtoSRFB json"));
if (raw)
{ // send raw in priority when defined in the json
trc(F("MQTTtoSRFB raw ok"));
byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(raw, message_b);
_rfbSend(message_b, valueRPT);
}
else
{
unsigned long data = SRFBdata["value"];
if (data != 0)
{
trc(F("MQTTtoSRFB data ok"));
int valueMiniPLSL = SRFBdata["val_Tlow"];
int valueMaxiPLSL = SRFBdata["val_Thigh"];
int valueSYNC = SRFBdata["delay"];
if (valueRPT == 0)
valueRPT = 1;
if (valueMiniPLSL == 0)
valueMiniPLSL = 320;
if (valueMaxiPLSL == 0)
valueMaxiPLSL = 900;
if (valueSYNC == 0)
valueSYNC = 9500;
byte hex_valueMiniPLSL[2]; byte hex_valueMiniPLSL[2];
hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF) ; hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF);
hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF) ; hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF);
byte hex_valueMaxiPLSL[2]; byte hex_valueMaxiPLSL[2];
hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF) ; hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF);
hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF) ; hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF);
byte hex_valueSYNC[2]; byte hex_valueSYNC[2];
hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF) ; hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF);
hex_valueSYNC[1] = (int)(valueSYNC & 0xFF) ; hex_valueSYNC[1] = (int)(valueSYNC & 0xFF);
unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
byte hex_data[3]; byte hex_data[3];
hex_data[0] = (unsigned long)((data >> 16) & 0xFF) ; hex_data[0] = (unsigned long)((data >> 16) & 0xFF);
hex_data[1] = (unsigned long)((data >> 8) & 0xFF) ; hex_data[1] = (unsigned long)((data >> 8) & 0xFF);
hex_data[2] = (unsigned long)(data & 0xFF) ; hex_data[2] = (unsigned long)(data & 0xFF);
byte message_b[RF_MESSAGE_SIZE]; byte message_b[RF_MESSAGE_SIZE];
memcpy(message_b, hex_valueSYNC, 2); memcpy(message_b, hex_valueSYNC, 2);
memcpy(message_b + 2, hex_valueMiniPLSL, 2); memcpy(message_b + 2, hex_valueMiniPLSL, 2);
memcpy(message_b + 4, hex_valueMaxiPLSL, 2); memcpy(message_b + 4, hex_valueMaxiPLSL, 2);
memcpy(message_b + 6, hex_data, 3); memcpy(message_b + 6, hex_data, 3);
trc(F("MQTTtoSRFB OK"));
_rfbSend(message_b, valueRPT); _rfbSend(message_b, valueRPT);
// 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, 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
} }
if (topic == subjectMQTTtoSRFBRaw){ else
{
int pos = topic.lastIndexOf(SRFBRptKey); trc(F("MQTTtoSRFB error decoding value"));
if (pos != -1){
pos = pos + +strlen(SRFBRptKey);
valueRPT = (topic.substring(pos,pos + 1)).toInt();
trc(F("SRFB Repeat:"));
trc(valueRPT);
}
if (valueRPT == 0) valueRPT = 1;
byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(datacallback,message_b);
_rfbSend(message_b, valueRPT);
// Acknowledgement to the GTWRF topic
pub(subjectGTWSRFBtoMQTT, datacallback);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}
#endif
#ifdef jsonReceiving
void MQTTtoSRFB(char * topicOri, JsonObject& SRFBdata) {
// RF DATA ANALYSIS
const char * raw = SRFBdata["raw"];
int valueRPT = SRFBdata["repeat"]|1;
if (cmpToMainTopic(topicOri,subjectMQTTtoSRFB)){
trc(F("MQTTtoSRFB json"));
if (raw){ // send raw in priority when defined in the json
trc(F("MQTTtoSRFB raw ok"));
byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(raw,message_b);
_rfbSend(message_b, valueRPT);
}else{
unsigned long data = SRFBdata["value"];
if (data != 0) {
trc(F("MQTTtoSRFB data ok"));
int valueMiniPLSL = SRFBdata["val_Tlow"];
int valueMaxiPLSL =SRFBdata["val_Thigh"];
int valueSYNC = SRFBdata["delay"];
if (valueRPT == 0) valueRPT = 1;
if (valueMiniPLSL == 0) valueMiniPLSL = 320;
if (valueMaxiPLSL == 0) valueMaxiPLSL = 900;
if (valueSYNC == 0) valueSYNC = 9500;
byte hex_valueMiniPLSL[2];
hex_valueMiniPLSL[0] = (int)((valueMiniPLSL >> 8) & 0xFF) ;
hex_valueMiniPLSL[1] = (int)(valueMiniPLSL & 0xFF) ;
byte hex_valueMaxiPLSL[2];
hex_valueMaxiPLSL[0] = (int)((valueMaxiPLSL >> 8) & 0xFF) ;
hex_valueMaxiPLSL[1] = (int)(valueMaxiPLSL & 0xFF) ;
byte hex_valueSYNC[2];
hex_valueSYNC[0] = (int)((valueSYNC >> 8) & 0xFF) ;
hex_valueSYNC[1] = (int)(valueSYNC & 0xFF) ;
byte hex_data[3];
hex_data[0] = (unsigned long)((data >> 16) & 0xFF) ;
hex_data[1] = (unsigned long)((data >> 8) & 0xFF) ;
hex_data[2] = (unsigned long)(data & 0xFF) ;
byte message_b[RF_MESSAGE_SIZE];
memcpy(message_b, hex_valueSYNC, 2);
memcpy(message_b + 2, hex_valueMiniPLSL, 2);
memcpy(message_b + 4, hex_valueMaxiPLSL, 2);
memcpy(message_b + 6, hex_data, 3);
trc(F("MQTTtoSRFB OK"));
_rfbSend(message_b, valueRPT);
// Acknowledgement to the GTWRF topic
pub(subjectGTWSRFBtoMQTT, SRFBdata);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{
trc(F("MQTTtoSRFB error decoding value"));
}
} }
} }
} }
}
#endif #endif
#endif #endif
+247 -234
View File
@@ -31,15 +31,15 @@ String getMacAddress()
{ {
uint8_t baseMac[6]; uint8_t baseMac[6];
char baseMacChr[13] = {0}; char baseMacChr[13] = {0};
#if defined(ESP8266) #if defined(ESP8266)
WiFi.macAddress(baseMac); WiFi.macAddress(baseMac);
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]); sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#elif defined(ESP32) #elif defined(ESP32)
esp_read_mac(baseMac, ESP_MAC_WIFI_STA); esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]); sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#else #else
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
#endif #endif
return String(baseMacChr); return String(baseMacChr);
} }
@@ -49,41 +49,50 @@ String getUniqueId(String name, String sufix)
return String(uniqueId); return String(uniqueId);
} }
void createDiscovery(char * sensor_type, void createDiscovery(char *sensor_type,
char * st_topic, char * s_name, char * unique_id, char *st_topic, char *s_name, char *unique_id,
char * availability_topic, char * device_class, char * value_template, char *availability_topic, char *device_class, char *value_template,
char * payload_on, char * payload_off, char * unit_of_meas, char *payload_on, char *payload_off, char *unit_of_meas,
int off_delay, int off_delay,
char * payload_available, char * payload_not_avalaible, bool child_device , char * cmd_topic) char *payload_available, char *payload_not_avalaible, bool child_device, char *cmd_topic)
{ {
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(5)+ JSON_ARRAY_SIZE(1); const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &sensor = jsonBuffer.createObject(); JsonObject &sensor = jsonBuffer.createObject();
char state_topic[mqtt_topic_max_size]; char state_topic[mqtt_topic_max_size];
strcpy(state_topic,mqtt_topic); strcpy(state_topic, mqtt_topic);
strcat(state_topic,st_topic); strcat(state_topic, st_topic);
sensor.set("stat_t", state_topic); //state_topic sensor.set("stat_t", state_topic); //state_topic
sensor.set("name", s_name); //name
sensor.set("uniq_id", unique_id); //unique_id
if (device_class[0]) sensor.set("dev_cla", device_class); //device_class
if (value_template[0]) sensor.set("val_tpl", value_template); //value_template
if (payload_on[0]) sensor.set("pl_on", payload_on); // payload_on
if (payload_off[0]) sensor.set("pl_off", payload_off); //payload_off
if (unit_of_meas[0]) sensor.set("unit_of_meas", unit_of_meas); //unit_of_measurement*/
if (off_delay != 0) sensor.set("off_delay", off_delay); //off_delay
if (payload_available[0]) sensor.set("pl_avail", payload_available); // payload_on
if (payload_not_avalaible[0]) sensor.set("pl_not_avail", payload_not_avalaible); //payload_off
if (cmd_topic[0]) { sensor.set("name", s_name); //name
sensor.set("uniq_id", unique_id); //unique_id
if (device_class[0])
sensor.set("dev_cla", device_class); //device_class
if (value_template[0])
sensor.set("val_tpl", value_template); //value_template
if (payload_on[0])
sensor.set("pl_on", payload_on); // payload_on
if (payload_off[0])
sensor.set("pl_off", payload_off); //payload_off
if (unit_of_meas[0])
sensor.set("unit_of_meas", unit_of_meas); //unit_of_measurement*/
if (off_delay != 0)
sensor.set("off_delay", off_delay); //off_delay
if (payload_available[0])
sensor.set("pl_avail", payload_available); // payload_on
if (payload_not_avalaible[0])
sensor.set("pl_not_avail", payload_not_avalaible); //payload_off
if (cmd_topic[0])
{
char command_topic[mqtt_topic_max_size]; 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);
sensor.set("cmd_t", command_topic); //command_topic sensor.set("cmd_t", command_topic); //command_topic
} }
/*if (strcmp(s_name, Gateway_Name) == 0){ /*if (strcmp(s_name, Gateway_Name) == 0){
JsonArray &json_attributes = sensor.createNestedArray("json_attributes"); JsonArray &json_attributes = sensor.createNestedArray("json_attributes");
json_attributes.add("uptime"); json_attributes.add("uptime");
json_attributes.add("freemem"); json_attributes.add("freemem");
@@ -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();
@@ -109,325 +119,328 @@ void createDiscovery(char * sensor_type,
void pubMqttDiscovery() void pubMqttDiscovery()
{ {
trc(F("omgStatusDiscovery")); trc(F("omgStatusDiscovery"));
createDiscovery("binary_sensor", //set sensorType createDiscovery("binary_sensor", //set sensorType
will_Topic, Gateway_Name, (char *)getUniqueId("", "").c_str(), //set state_topic,name,uniqueId will_Topic, Gateway_Name, (char *)getUniqueId("", "").c_str(), //set state_topic,name,uniqueId
will_Topic, "connectivity", "", //set availability_topic,device_class,value_template, will_Topic, "connectivity", "", //set availability_topic,device_class,value_template,
Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas, Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas,
0, //set optimistic,retain, off_delay 0, //set optimistic,retain, off_delay
Gateway_AnnouncementMsg, will_Message,true,"" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic, state on, state off Gateway_AnnouncementMsg, will_Message, true, "" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic, state on, state off
); );
#ifdef ZsensorBME280 #ifdef ZsensorBME280
#define BMEparametersCount 6 #define BMEparametersCount 6
trc(F("bme280Discovery")); trc(F("bme280Discovery"));
char * BMEsensor[BMEparametersCount][8] = { char *BMEsensor[BMEparametersCount][8] = {
{"sensor", "tempc", "bme","temperature","{{ value_json.tempc }}","", "", "°C"} , {"sensor", "tempc", "bme", "temperature", "{{ value_json.tempc }}", "", "", "°C"},
{"sensor", "tempf", "bme","temperature","{{ value_json.tempf }}","", "", "°F"} , {"sensor", "tempf", "bme", "temperature", "{{ value_json.tempf }}", "", "", "°F"},
{"sensor", "pa", "bme","","{{ float(value_json.pa) * 0.01 }}","", "", "hPa"} , {"sensor", "pa", "bme", "", "{{ float(value_json.pa) * 0.01 }}", "", "", "hPa"},
{"sensor", "hum", "bme","humidity","{{ value_json.hum }}","", "", "%"} , {"sensor", "hum", "bme", "humidity", "{{ value_json.hum }}", "", "", "%"},
{"sensor", "altim", "bme","","{{ value_json.altim }}","", "", "m"} , {"sensor", "altim", "bme", "", "{{ value_json.altim }}", "", "", "m"},
{"sensor", "altift", "bme","","{{ value_json.altift }}","", "", "ft"} {"sensor", "altift", "bme", "", "{{ value_json.altift }}", "", "", "ft"}
//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(BMEsensor[i][1]); trc(F("CreateDiscoverySensor"));
trc(BMEsensor[i][1]);
createDiscovery(BMEsensor[i][0], createDiscovery(BMEsensor[i][0],
BMETOPIC, BMEsensor[i][1], (char *)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(), BMETOPIC, BMEsensor[i][1], (char *)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(),
will_Topic, BMEsensor[i][3], BMEsensor[i][4], will_Topic, BMEsensor[i][3], BMEsensor[i][4],
BMEsensor[i][5], BMEsensor[i][6], BMEsensor[i][7], BMEsensor[i][5], BMEsensor[i][6], BMEsensor[i][7],
0,"","",true,""); 0, "", "", true, "");
} }
#endif #endif
#ifdef ZsensorDHT #ifdef ZsensorDHT
#define DHTparametersCount 2 #define DHTparametersCount 2
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],
DHTTOPIC, DHTsensor[i][1], (char *)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(), DHTTOPIC, DHTsensor[i][1], (char *)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(),
will_Topic, DHTsensor[i][3], DHTsensor[i][4], will_Topic, DHTsensor[i][3], DHTsensor[i][4],
DHTsensor[i][5], DHTsensor[i][6], DHTsensor[i][7], DHTsensor[i][5], DHTsensor[i][6], DHTsensor[i][7],
0,"","",true,""); 0, "", "", true, "");
} }
#endif #endif
#ifdef ZsensorADC #ifdef ZsensorADC
trc(F("ADCDiscovery")); trc(F("ADCDiscovery"));
char * ADCsensor[8] = {"sensor", "adc", "adc", "","{{ value_json.adc }}","", "", ""}; char *ADCsensor[8] = {"sensor", "adc", "adc", "", "{{ value_json.adc }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(ADCsensor[1]); trc(ADCsensor[1]);
createDiscovery(ADCsensor[0], createDiscovery(ADCsensor[0],
ADCTOPIC, ADCsensor[1], (char *)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(), ADCTOPIC, ADCsensor[1], (char *)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(),
will_Topic, ADCsensor[3], ADCsensor[4], will_Topic, ADCsensor[3], ADCsensor[4],
ADCsensor[5], ADCsensor[6], ADCsensor[7], ADCsensor[5], ADCsensor[6], ADCsensor[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZsensorBH1750 #ifdef ZsensorBH1750
#define BH1750parametersCount 3 #define BH1750parametersCount 3
trc(F("BH1750Discovery")); trc(F("BH1750Discovery"));
char * BH1750sensor[BH1750parametersCount][8] = { char *BH1750sensor[BH1750parametersCount][8] = {
{"sensor", "lux", "BH1750", "illuminance","{{ value_json.lux }}","", "", "lu"} , {"sensor", "lux", "BH1750", "illuminance", "{{ value_json.lux }}", "", "", "lu"},
{"sensor", "ftCd", "BH1750","","{{ value_json.ftCd }}","", "", ""} , {"sensor", "ftCd", "BH1750", "", "{{ value_json.ftCd }}", "", "", ""},
{"sensor", "wattsm2", "BH1750","","{{ value_json.wattsm2 }}","", "", "wm²"} {"sensor", "wattsm2", "BH1750", "", "{{ value_json.wattsm2 }}", "", "", "wm²"}
//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(BH1750sensor[i][1]); trc(F("CreateDiscoverySensor"));
trc(BH1750sensor[i][1]);
createDiscovery(BH1750sensor[i][0], createDiscovery(BH1750sensor[i][0],
subjectBH1750toMQTT, BH1750sensor[i][1], (char *)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(), subjectBH1750toMQTT, BH1750sensor[i][1], (char *)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(),
will_Topic, BH1750sensor[i][3], BH1750sensor[i][4], will_Topic, BH1750sensor[i][3], BH1750sensor[i][4],
BH1750sensor[i][5], BH1750sensor[i][6], BH1750sensor[i][7], BH1750sensor[i][5], BH1750sensor[i][6], BH1750sensor[i][7],
0,"","",true,""); 0, "", "", true, "");
} }
#endif #endif
#ifdef ZsensorTSL2561 #ifdef ZsensorTSL2561
#define TSL2561parametersCount 3 #define TSL2561parametersCount 3
trc(F("TSL2561Discovery")); trc(F("TSL2561Discovery"));
char * TSL2561sensor[TSL2561parametersCount][8] = { char *TSL2561sensor[TSL2561parametersCount][8] = {
{"sensor", "lux", "TSL2561", "illuminance","{{ value_json.lux }}","", "", "lu"} , {"sensor", "lux", "TSL2561", "illuminance", "{{ value_json.lux }}", "", "", "lu"},
{"sensor", "ftcd", "TSL2561","","{{ value_json.ftcd }}","", "", ""} , {"sensor", "ftcd", "TSL2561", "", "{{ value_json.ftcd }}", "", "", ""},
{"sensor", "wattsm2", "TSL2561","","{{ value_json.wattsm2 }}","", "", "wm²"} {"sensor", "wattsm2", "TSL2561", "", "{{ value_json.wattsm2 }}", "", "", "wm²"}
//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(TSL2561sensor[i][1]); trc(F("CreateDiscoverySensor"));
trc(TSL2561sensor[i][1]);
createDiscovery(TSL2561sensor[i][0], createDiscovery(TSL2561sensor[i][0],
subjectTSL12561toMQTT, TSL2561sensor[i][1], (char *)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(), subjectTSL12561toMQTT, TSL2561sensor[i][1], (char *)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(),
will_Topic, TSL2561sensor[i][3], TSL2561sensor[i][4], will_Topic, TSL2561sensor[i][3], TSL2561sensor[i][4],
TSL2561sensor[i][5], TSL2561sensor[i][6], TSL2561sensor[i][7], TSL2561sensor[i][5], TSL2561sensor[i][6], TSL2561sensor[i][7],
0,"","",true,""); 0, "", "", true, "");
} }
#endif #endif
#ifdef ZsensorHCSR501 #ifdef ZsensorHCSR501
trc(F("HCSR501Discovery")); trc(F("HCSR501Discovery"));
char * HCSR501sensor[8] = {"binary_sensor", "hcsr501", "hcsr501", "","{{value_json.hcsr501}}","true", "false", ""}; char *HCSR501sensor[8] = {"binary_sensor", "hcsr501", "hcsr501", "", "{{value_json.hcsr501}}", "true", "false", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(HCSR501sensor[1]); trc(HCSR501sensor[1]);
createDiscovery(HCSR501sensor[0], createDiscovery(HCSR501sensor[0],
subjectHCSR501toMQTT, HCSR501sensor[1], (char *)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(), subjectHCSR501toMQTT, HCSR501sensor[1], (char *)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(),
will_Topic, HCSR501sensor[3], HCSR501sensor[4], will_Topic, HCSR501sensor[3], HCSR501sensor[4],
HCSR501sensor[5], HCSR501sensor[6], HCSR501sensor[7], HCSR501sensor[5], HCSR501sensor[6], HCSR501sensor[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZsensorGPIOInput #ifdef ZsensorGPIOInput
trc(F("GPIOInputDiscovery")); trc(F("GPIOInputDiscovery"));
char * GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "GPIOInput", "","{{value_json.gpio}}","HIGH", "LOW", ""}; char *GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "GPIOInput", "", "{{value_json.gpio}}", "HIGH", "LOW", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(GPIOInputsensor[1]); trc(GPIOInputsensor[1]);
createDiscovery(GPIOInputsensor[0], createDiscovery(GPIOInputsensor[0],
subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char *)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(), subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char *)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(),
will_Topic, GPIOInputsensor[3], GPIOInputsensor[4], will_Topic, GPIOInputsensor[3], GPIOInputsensor[4],
GPIOInputsensor[5], GPIOInputsensor[6], GPIOInputsensor[7], GPIOInputsensor[5], GPIOInputsensor[6], GPIOInputsensor[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZsensorINA226 #ifdef ZsensorINA226
#define INA226parametersCount 3 #define INA226parametersCount 3
trc(F("INA226Discovery")); trc(F("INA226Discovery"));
char * INA226sensor[INA226parametersCount][8] = { char *INA226sensor[INA226parametersCount][8] = {
{"sensor", "volt", "INA226", "","{{ value_json.volt }}","", "", "V"} , {"sensor", "volt", "INA226", "", "{{ value_json.volt }}", "", "", "V"},
{"sensor", "current", "INA226","","{{ value_json.current }}","", "", "A"} , {"sensor", "current", "INA226", "", "{{ value_json.current }}", "", "", "A"},
{"sensor", "power", "INA226","","{{ value_json.power }}","", "", "W"} {"sensor", "power", "INA226", "", "{{ value_json.power }}", "", "", "W"}
//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(INA226sensor[i][1]); trc(F("CreateDiscoverySensor"));
trc(INA226sensor[i][1]);
createDiscovery(INA226sensor[i][0], createDiscovery(INA226sensor[i][0],
subjectINA226toMQTT, INA226sensor[i][1], (char *)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(), subjectINA226toMQTT, INA226sensor[i][1], (char *)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(),
will_Topic, INA226sensor[i][3], INA226sensor[i][4], will_Topic, INA226sensor[i][3], INA226sensor[i][4],
INA226sensor[i][5], INA226sensor[i][6], INA226sensor[i][7], INA226sensor[i][5], INA226sensor[i][6], INA226sensor[i][7],
0,"","",true,""); 0, "", "", true, "");
} }
#endif #endif
#ifdef ZactuatorONOFF #ifdef ZactuatorONOFF
trc(F("actuatorONOFFDiscovery")); trc(F("actuatorONOFFDiscovery"));
char * actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "","","ON", "OFF", ""}; char *actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "", "", "ON", "OFF", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(actuatorONOFF[1]); trc(actuatorONOFF[1]);
createDiscovery(actuatorONOFF[0], createDiscovery(actuatorONOFF[0],
subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char *)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(), subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char *)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(),
will_Topic, actuatorONOFF[3], actuatorONOFF[4], will_Topic, actuatorONOFF[3], actuatorONOFF[4],
actuatorONOFF[5], actuatorONOFF[6], actuatorONOFF[7], actuatorONOFF[5], actuatorONOFF[6], actuatorONOFF[7],
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"));
char * gatewayRF[8] = {"sensor", "gatewayRF", "", "","{{ value_json.value }}","", "", ""}; char *gatewayRF[8] = {"sensor", "gatewayRF", "", "", "{{ value_json.value }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayRF[1]); trc(gatewayRF[1]);
createDiscovery(gatewayRF[0], createDiscovery(gatewayRF[0],
subjectRFtoMQTT, gatewayRF[1], (char *)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(), subjectRFtoMQTT, gatewayRF[1], (char *)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(),
will_Topic, gatewayRF[3], gatewayRF[4], will_Topic, gatewayRF[3], gatewayRF[4],
gatewayRF[5], gatewayRF[6], gatewayRF[7], gatewayRF[5], gatewayRF[6], gatewayRF[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayRF2 #ifdef ZgatewayRF2
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewayRF2Discovery")); trc(F("gatewayRF2Discovery"));
char * gatewayRF2[8] = {"sensor", "gatewayRF2", "", "","{{ value_json.value }}","", "", ""}; char *gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", "{{ value_json.value }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayRF2[1]); trc(gatewayRF2[1]);
createDiscovery(gatewayRF2[0], createDiscovery(gatewayRF2[0],
subjectRF2toMQTT, gatewayRF2[1], (char *)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(), subjectRF2toMQTT, gatewayRF2[1], (char *)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(),
will_Topic, gatewayRF2[3], gatewayRF2[4], will_Topic, gatewayRF2[3], gatewayRF2[4],
gatewayRF2[5], gatewayRF2[6], gatewayRF2[7], gatewayRF2[5], gatewayRF2[6], gatewayRF2[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayRF315 #ifdef ZgatewayRF315
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewayRF315Discovery")); trc(F("gatewayRF315Discovery"));
char * gatewayRF315[8] = {"sensor", "gatewayRF315", "", "","{{ value_json.value }}","", "", ""}; char *gatewayRF315[8] = {"sensor", "gatewayRF315", "", "", "{{ value_json.value }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayRF315[1]); trc(gatewayRF315[1]);
createDiscovery(gatewayRF315[0], createDiscovery(gatewayRF315[0],
subjectRF315toMQTT, gatewayRF315[1], (char *)getUniqueId(gatewayRF315[1], gatewayRF315[2]).c_str(), subjectRF315toMQTT, gatewayRF315[1], (char *)getUniqueId(gatewayRF315[1], gatewayRF315[2]).c_str(),
will_Topic, gatewayRF315[3], gatewayRF315[4], will_Topic, gatewayRF315[3], gatewayRF315[4],
gatewayRF315[5], gatewayRF315[6], gatewayRF315[7], gatewayRF315[5], gatewayRF315[6], gatewayRF315[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayRFM69 #ifdef ZgatewayRFM69
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewayRFM69Discovery")); trc(F("gatewayRFM69Discovery"));
char * gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "","{{ value_json.value }}","", "", ""}; char *gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", "{{ value_json.value }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayRFM69[1]); trc(gatewayRFM69[1]);
createDiscovery(gatewayRFM69[0], createDiscovery(gatewayRFM69[0],
subjectRFM69toMQTT, gatewayRFM69[1], (char *)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(), subjectRFM69toMQTT, gatewayRFM69[1], (char *)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(),
will_Topic, gatewayRFM69[3], gatewayRFM69[4], will_Topic, gatewayRFM69[3], gatewayRFM69[4],
gatewayRFM69[5], gatewayRFM69[6], gatewayRFM69[7], gatewayRFM69[5], gatewayRFM69[6], gatewayRFM69[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayLORA #ifdef ZgatewayLORA
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewayLORADiscovery")); trc(F("gatewayLORADiscovery"));
char * gatewayLORA[8] = {"sensor", "gatewayLORA", "", "","{{ value_json.message }}","", "", ""}; char *gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", "{{ value_json.message }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayLORA[1]); trc(gatewayLORA[1]);
createDiscovery(gatewayLORA[0], createDiscovery(gatewayLORA[0],
subjectLORAtoMQTT, gatewayLORA[1], (char *)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(), subjectLORAtoMQTT, gatewayLORA[1], (char *)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(),
will_Topic, gatewayLORA[3], gatewayLORA[4], will_Topic, gatewayLORA[3], gatewayLORA[4],
gatewayLORA[5], gatewayLORA[6], gatewayLORA[7], gatewayLORA[5], gatewayLORA[6], gatewayLORA[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewaySRFB #ifdef ZgatewaySRFB
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewaySRFBDiscovery")); trc(F("gatewaySRFBDiscovery"));
char * gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "","{{ value_json.value }}","", "", ""}; char *gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", "{{ value_json.value }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewaySRFB[1]); trc(gatewaySRFB[1]);
createDiscovery(gatewaySRFB[0], createDiscovery(gatewaySRFB[0],
subjectSRFBtoMQTT, gatewaySRFB[1], (char *)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(), subjectSRFBtoMQTT, gatewaySRFB[1], (char *)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(),
will_Topic, gatewaySRFB[3], gatewaySRFB[4], will_Topic, gatewaySRFB[3], gatewaySRFB[4],
gatewaySRFB[5], gatewaySRFB[6], gatewaySRFB[7], gatewaySRFB[5], gatewaySRFB[6], gatewaySRFB[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayPilight #ifdef ZgatewayPilight
// Sensor to display RF received value // Sensor to display RF received value
trc(F("gatewayPilightDiscovery")); trc(F("gatewayPilightDiscovery"));
char * gatewayPilight[8] = {"sensor", "gatewayPilight", "", "","{{ value_json.message }}","", "", ""}; char *gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", "{{ value_json.message }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayPilight[1]); trc(gatewayPilight[1]);
createDiscovery(gatewayPilight[0], createDiscovery(gatewayPilight[0],
subjectPilighttoMQTT, gatewayPilight[1], (char *)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(), subjectPilighttoMQTT, gatewayPilight[1], (char *)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(),
will_Topic, gatewayPilight[3], gatewayPilight[4], will_Topic, gatewayPilight[3], gatewayPilight[4],
gatewayPilight[5], gatewayPilight[6], gatewayPilight[7], gatewayPilight[5], gatewayPilight[6], gatewayPilight[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayIR #ifdef ZgatewayIR
// Sensor to display IR received value // Sensor to display IR received value
trc(F("gatewayIRDiscovery")); trc(F("gatewayIRDiscovery"));
char * gatewayIR[8] = {"sensor", "gatewayIR", "", "","{{ value_json.value }}","", "", ""}; char *gatewayIR[8] = {"sensor", "gatewayIR", "", "", "{{ value_json.value }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayIR[1]); trc(gatewayIR[1]);
createDiscovery(gatewayIR[0], createDiscovery(gatewayIR[0],
subjectIRtoMQTT, gatewayIR[1], (char *)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(), subjectIRtoMQTT, gatewayIR[1], (char *)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(),
will_Topic, gatewayIR[3], gatewayIR[4], will_Topic, gatewayIR[3], gatewayIR[4],
gatewayIR[5], gatewayIR[6], gatewayIR[7], gatewayIR[5], gatewayIR[6], gatewayIR[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef Zgateway2G #ifdef Zgateway2G
// Sensor to display 2G received value // Sensor to display 2G received value
trc(F("gateway2GDiscovery")); trc(F("gateway2GDiscovery"));
char * gateway2G[8] = {"sensor", "gateway2G", "", "","{{ value_json.message }}","", "", ""}; char *gateway2G[8] = {"sensor", "gateway2G", "", "", "{{ value_json.message }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gateway2G[1]); trc(gateway2G[1]);
createDiscovery(gateway2G[0], createDiscovery(gateway2G[0],
subject2GtoMQTT, gateway2G[1], (char *)getUniqueId(gateway2G[1], gateway2G[2]).c_str(), subject2GtoMQTT, gateway2G[1], (char *)getUniqueId(gateway2G[1], gateway2G[2]).c_str(),
will_Topic, gateway2G[3], gateway2G[4], will_Topic, gateway2G[3], gateway2G[4],
gateway2G[5], gateway2G[6], gateway2G[7], gateway2G[5], gateway2G[6], gateway2G[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
#ifdef ZgatewayBT #ifdef ZgatewayBT
// Sensor to display BT received value // Sensor to display BT received value
trc(F("gatewayBTDiscovery")); trc(F("gatewayBTDiscovery"));
char * gatewayBT[8] = {"sensor", "gatewayBT", "", "","{{ value_json.id }}","", "", ""}; char *gatewayBT[8] = {"sensor", "gatewayBT", "", "", "{{ value_json.id }}", "", "", ""};
//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
trc(F("CreateDiscoverySensor")); trc(F("CreateDiscoverySensor"));
trc(gatewayBT[1]); trc(gatewayBT[1]);
createDiscovery(gatewayBT[0], createDiscovery(gatewayBT[0],
subjectBTtoMQTT, gatewayBT[1], (char *)getUniqueId(gatewayBT[1], gatewayBT[2]).c_str(), subjectBTtoMQTT, gatewayBT[1], (char *)getUniqueId(gatewayBT[1], gatewayBT[2]).c_str(),
will_Topic, gatewayBT[3], gatewayBT[4], will_Topic, gatewayBT[3], gatewayBT[4],
gatewayBT[5], gatewayBT[6], gatewayBT[7], gatewayBT[5], gatewayBT[6], gatewayBT[7],
0,"","",true,""); 0, "", "", true, "");
#endif #endif
} }
+18 -12
View File
@@ -31,32 +31,38 @@
#ifdef ZsensorADC #ifdef ZsensorADC
#if defined(ESP8266) #if defined(ESP8266)
ADC_MODE(ADC_TOUT); ADC_MODE(ADC_TOUT);
#endif #endif
//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 defined(ESP8266) if (millis() > (timeadc + TimeBetweenReadingADC))
yield(); { //retriving value of temperature and humidity of the box from DHT every xUL
#endif #if defined(ESP8266)
yield();
#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;
JsonObject& ADCdata = jsonBuffer.createObject(); JsonObject &ADCdata = jsonBuffer.createObject();
ADCdata.set("adc", (int)val); ADCdata.set("adc", (int)val);
pub(ADCTOPIC,ADCdata); pub(ADCTOPIC, ADCdata);
persistedadc = val; persistedadc = val;
} }
} }
} }
} }
+37 -23
View File
@@ -1,4 +1,4 @@
/* /*
OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation
Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker
@@ -46,21 +46,22 @@ void setupZsensorBH1750()
{ {
Wire.begin(); Wire.begin();
Wire.beginTransmission(BH1750_i2c_addr); Wire.beginTransmission(BH1750_i2c_addr);
Wire.write(0x10); // Set resolution to 1 Lux Wire.write(0x10); // Set resolution to 1 Lux
Wire.endTransmission(); Wire.endTransmission();
delay(300); delay(300);
} }
// 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();
timebh1750 = millis(); timebh1750 = millis();
unsigned int i=0; unsigned int i = 0;
static float persistedll; static float persistedll;
static float persistedlf; static float persistedlf;
static float persistedlw; static float persistedlw;
@@ -70,39 +71,52 @@ 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();
// Calculate the Values // Calculate the Values
Lux = i/1.2; // Convert to Lux Lux = i / 1.2; // Convert to Lux
ftcd = Lux/10.764; ftcd = Lux / 10.764;
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;
+53 -31
View File
@@ -50,17 +50,17 @@ BME280 mySensor;
void setupZsensorBME280() void setupZsensorBME280()
{ {
mySensor.settings.commInterface = I2C_MODE; mySensor.settings.commInterface = I2C_MODE;
mySensor.settings.I2CAddress = 0x76; // Bosch BME280 I2C Address mySensor.settings.I2CAddress = 0x76; // Bosch BME280 I2C Address
//***Operation settings*****************************// //***Operation settings*****************************//
// runMode Setting - Values: // runMode Setting - Values:
// ------------------------- // -------------------------
// 0, Sleep mode // 0, Sleep mode
// 1 or 2, Forced mode // 1 or 2, Forced mode
// 3, Normal mode // 3, Normal mode
mySensor.settings.runMode = 3; //Normal mode mySensor.settings.runMode = 3; //Normal mode
// tStandby Setting - Values: // tStandby Setting - Values:
// -------------------------- // --------------------------
// 0, 0.5ms // 0, 0.5ms
@@ -72,7 +72,7 @@ void setupZsensorBME280()
// 6, 10ms // 6, 10ms
// 7, 20ms // 7, 20ms
mySensor.settings.tStandby = 1; mySensor.settings.tStandby = 1;
// Filter can be off or number of FIR coefficients - Values: // Filter can be off or number of FIR coefficients - Values:
// --------------------------------------------------------- // ---------------------------------------------------------
// 0, filter off // 0, filter off
@@ -81,7 +81,7 @@ void setupZsensorBME280()
// 3, coefficients = 8 // 3, coefficients = 8
// 4, coefficients = 16 // 4, coefficients = 16
mySensor.settings.filter = 4; mySensor.settings.filter = 4;
// tempOverSample - Values: // tempOverSample - Values:
// ------------------------ // ------------------------
// 0, skipped // 0, skipped
@@ -92,14 +92,14 @@ void setupZsensorBME280()
// ------------------------- // -------------------------
// 0, skipped // 0, skipped
// 1 through 5, oversampling *1, *2, *4, *8, *16 respectively // 1 through 5, oversampling *1, *2, *4, *8, *16 respectively
mySensor.settings.pressOverSample = 1; mySensor.settings.pressOverSample = 1;
// humidOverSample - Values: // humidOverSample - Values:
// ------------------------- // -------------------------
// 0, skipped // 0, skipped
// 1 through 5, oversampling *1, *2, *4, *8, *16 respectively // 1 through 5, oversampling *1, *2, *4, *8, *16 respectively
mySensor.settings.humidOverSample = 1; mySensor.settings.humidOverSample = 1;
delay(10); // Gives the Sensor enough time to turn on (The BME280 requires 2ms to start up) delay(10); // Gives the Sensor enough time to turn on (The BME280 requires 2ms to start up)
Serial.print("Bosch BME280 Initialized - Result of .begin(): 0x"); Serial.print("Bosch BME280 Initialized - Result of .begin(): 0x");
Serial.println(mySensor.begin(), HEX); Serial.println(mySensor.begin(), HEX);
@@ -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{ }
trc(F("Creating BME280 buffer")); else
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; {
JsonObject& BME280data = jsonBuffer.createObject(); trc(F("Creating BME280 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
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;
} }
} }
+25 -13
View File
@@ -33,37 +33,49 @@
#include <DHT.h> #include <DHT.h>
#include <DHT_U.h> #include <DHT_U.h>
DHT dht(DHT_RECEIVER_PIN,DHT_SENSOR_TYPE); DHT dht(DHT_RECEIVER_PIN, DHT_SENSOR_TYPE);
//Time used to wait for an interval before resending temp and hum //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;
float h = dht.readHumidity(); float h = dht.readHumidity();
// 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;
+25 -20
View File
@@ -31,15 +31,16 @@
#ifdef ZsensorGPIOInput #ifdef ZsensorGPIOInput
unsigned long lastDebounceTime = 0; 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
+28 -26
View File
@@ -27,19 +27,21 @@
#ifdef ZsensorGPIOKeyCode #ifdef ZsensorGPIOKeyCode
int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on startup int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on startup
int lastInputStateGPIOKeyCode = 0x0f; int lastInputStateGPIOKeyCode = 0x0f;
int lastLatchStateGPIOKeyCode = 0; int lastLatchStateGPIOKeyCode = 0;
void setupGPIOKeyCode() { void setupGPIOKeyCode()
pinMode(GPIOKeyCode_LATCH_PIN, INPUT_PULLUP); // {
pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_LATCH_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D2_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); //
//pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); // pinMode(GPIOKeyCode_D2_PIN, INPUT_PULLUP); //
//pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); //
} }
void MeasureGPIOKeyCode(){ void MeasureGPIOKeyCode()
{
int latch = digitalRead(GPIOKeyCode_LATCH_PIN); int latch = digitalRead(GPIOKeyCode_LATCH_PIN);
@@ -50,15 +52,14 @@ void MeasureGPIOKeyCode(){
{ {
// whatever the reading is at, it's been there for longer than the debounce // 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 (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];
@@ -66,19 +67,20 @@ void MeasureGPIOKeyCode(){
sprintf(hex, "%02x", InputStateGPIOKeyCode); sprintf(hex, "%02x", InputStateGPIOKeyCode);
hex[2] = 0; hex[2] = 0;
Serial.printf("GPIOKeyCode %s\n", hex); Serial.printf("GPIOKeyCode %s\n", hex);
client.publish(subjectGPIOKeyCodetoMQTT,hex); client.publish(subjectGPIOKeyCodetoMQTT, hex);
lastLatchStateGPIOKeyCode = latch; lastLatchStateGPIOKeyCode = latch;
} }
if (latch != lastLatchStateGPIOKeyCode) {
lastLatchStateGPIOKeyCode = latch;
Serial.printf("GPIOKeyCode latch %d\n", latch);
if (latch == 0)
client.publish(subjectGPIOKeyCodeStatetoMQTT, "done");
}
// save the reading. Next time through the loop, it'll be the lastInputState: if (latch != lastLatchStateGPIOKeyCode)
lastInputStateGPIOKeyCode = InputStateGPIOKeyCode; {
lastLatchStateGPIOKeyCode = latch;
Serial.printf("GPIOKeyCode latch %d\n", latch);
if (latch == 0)
client.publish(subjectGPIOKeyCodeStatetoMQTT, "done");
}
// save the reading. Next time through the loop, it'll be the lastInputState:
lastInputStateGPIOKeyCode = InputStateGPIOKeyCode;
} }
} }
#endif #endif
+25 -13
View File
@@ -33,41 +33,53 @@
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_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input pinMode(HCSR04_TRI_PIN, OUTPUT); // declare HC SR-04 trigger pin as output
pinMode(HCSR04_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input
} }
void MeasureDistance() { 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;
JsonObject& HCSR04data = jsonBuffer.createObject(); JsonObject &HCSR04data = jsonBuffer.createObject();
digitalWrite(HCSR04_TRI_PIN, LOW); digitalWrite(HCSR04_TRI_PIN, LOW);
delayMicroseconds(2); delayMicroseconds(2);
digitalWrite(HCSR04_TRI_PIN, HIGH); digitalWrite(HCSR04_TRI_PIN, HIGH);
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);
} }
} }
} }
+32 -23
View File
@@ -30,36 +30,45 @@
#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();
static int pirState = LOW; static int pirState = LOW;
int PresenceValue = digitalRead(HCSR501_PIN); int PresenceValue = digitalRead(HCSR501_PIN);
#if defined(ESP8266) || defined(ESP32) #if defined(ESP8266) || defined(ESP32)
yield(); yield();
#endif #endif
if (PresenceValue == HIGH) { if (PresenceValue == HIGH)
if (pirState == LOW) { {
//turned on if (pirState == LOW)
HCSR501data.set("hcsr501", "true"); {
trc(F("HC SR501 Motion started")); //turned on
pirState = HIGH; HCSR501data.set("hcsr501", "true");
} trc(F("HC SR501 Motion started"));
} else { pirState = HIGH;
if (pirState == HIGH){
// turned off
HCSR501data.set("hcsr501", "false");
trc(F("HC SR501 Motion ended"));
pirState = LOW;
} }
} }
if(HCSR501data.size()>0) pub(subjectHCSR501toMQTT,HCSR501data); else
{
if (pirState == HIGH)
{
// turned off
HCSR501data.set("hcsr501", "false");
trc(F("HC SR501 Motion ended"));
pirState = LOW;
}
}
if (HCSR501data.size() > 0)
pub(subjectHCSR501toMQTT, HCSR501data);
} }
} }
#endif #endif
+53 -45
View File
@@ -37,59 +37,64 @@
#ifdef ZsensorINA226 #ifdef ZsensorINA226
#include <Wire.h> #include <Wire.h>
float rShunt=0.1; // Shunt Widerstand festlegen, hier 0.1 Ohm float rShunt = 0.1; // Shunt Widerstand festlegen, hier 0.1 Ohm
const int INA226_ADDR = 0x40; // A0 und A1 auf GND > Adresse 40 Hex auf Seite 18 im Datenblatt const int INA226_ADDR = 0x40; // A0 und A1 auf GND > Adresse 40 Hex auf Seite 18 im Datenblatt
//Time used to wait for an interval before resending temp and hum //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 {
timeINA226 = millis(); if (millis() > (timeINA226 + TimeBetweenReadingINA226))
trc(F("Creating INA226 buffer")); { //retriving value of temperature and humidity of the box from DHT every xUL
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; timeINA226 = millis();
JsonObject& INA226data = jsonBuffer.createObject(); trc(F("Creating INA226 buffer"));
// Topic on which we will send data StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
trc(F("Retrieving electrical data")); JsonObject &INA226data = jsonBuffer.createObject();
// Bus Spannung, read-only, 16Bit, 0...40.96V max., LSB 1.25mV // Topic on which we will send data
trc(F(" Volt: ")); trc(F("Retrieving electrical data"));
float volt = readRegister(0x02) * 0.00125; // Bus Spannung, read-only, 16Bit, 0...40.96V max., LSB 1.25mV
trc(volt); trc(F(" Volt: "));
trc(F(" V, Current: ")); float volt = readRegister(0x02) * 0.00125;
// Seite 24: Shunt Spannung +- 81,92mV mit 16 Bit, LSB 2,5uV trc(volt);
int shuntvolt = readRegister(0x01); trc(F(" V, Current: "));
if (shuntvolt && 0x8000) {// eine negative Zahl? Dann 2er Komplement bilden // Seite 24: Shunt Spannung +- 81,92mV mit 16 Bit, LSB 2,5uV
shuntvolt = ~shuntvolt; // alle Bits invertieren int shuntvolt = readRegister(0x01);
shuntvolt += 1; // 1 dazuzählen if (shuntvolt && 0x8000)
shuntvolt *= -1 ; // negativ machen { // eine negative Zahl? Dann 2er Komplement bilden
} shuntvolt = ~shuntvolt; // alle Bits invertieren
float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R shuntvolt += 1; // 1 dazuzählen
trc(current); shuntvolt *= -1; // negativ machen
trc(F(" A, Power: "));
float power=abs(volt*current);
trc(power);
trc(F(" W"));
char volt_c[7];
char current_c[7];
char power_c[7];
dtostrf(volt,6,3,volt_c);
dtostrf(current,6,3,current_c);
dtostrf(power,6,3,power_c);
INA226data.set("volt", (char *)volt_c);
INA226data.set("current", (char *)current_c);
INA226data.set("power", (char *)power_c);
pub(subjectINA226toMQTT,INA226data);
} }
float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R
trc(current);
trc(F(" A, Power: "));
float power = abs(volt * current);
trc(power);
trc(F(" W"));
char volt_c[7];
char current_c[7];
char power_c[7];
dtostrf(volt, 6, 3, volt_c);
dtostrf(current, 6, 3, current_c);
dtostrf(power, 6, 3, power_c);
INA226data.set("volt", (char *)volt_c);
INA226data.set("current", (char *)current_c);
INA226data.set("power", (char *)power_c);
pub(subjectINA226toMQTT, INA226data);
}
} }
static void writeRegister(byte reg, word value) { static void writeRegister(byte reg, word value)
{
Wire.beginTransmission(INA226_ADDR); Wire.beginTransmission(INA226_ADDR);
Wire.write(reg); Wire.write(reg);
Wire.write((value >> 8) & 0xFF); Wire.write((value >> 8) & 0xFF);
@@ -97,13 +102,16 @@ 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) { {
res = Wire.read() * 256; if (Wire.requestFrom(INA226_ADDR, 2) >= 2)
{
res = Wire.read() * 256;
res += Wire.read(); res += Wire.read();
} }
} }
+24 -18
View File
@@ -1,4 +1,4 @@
/* /*
OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation OpenMQTTGateway Addon - ESP8266 or Arduino program for home automation
Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker
@@ -72,47 +72,53 @@ void setupZsensorTSL2561()
{ {
trc(F("No TSL2561 detected")); trc(F("No TSL2561 detected"));
} }
// enable auto ranging // enable auto ranging
// tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */ // tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */
// tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */ // tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */
tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */ tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */
// since we're slowly sampling, enable high resolution but slow mode TSL2561 // since we're slowly sampling, enable high resolution but slow mode TSL2561
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */ // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */ // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);
trc(F("TSL2561 Initialized. Printing detials now.")); trc(F("TSL2561 Initialized. Printing detials now."));
displaySensorDetails(); displaySensorDetails();
} }
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();
trc(F("Creating TSL2561 buffer")); trc(F("Creating TSL2561 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer; StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& TSL2561data = jsonBuffer.createObject(); JsonObject &TSL2561data = jsonBuffer.createObject();
sensors_event_t event; sensors_event_t event;
tsl.getEvent(&event); tsl.getEvent(&event);
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);
TSL2561data.set("ftcd", (float)(event.light)/10.764); TSL2561data.set("ftcd", (float)(event.light) / 10.764);
TSL2561data.set("wattsm2", (float)(event.light)/683.0); TSL2561data.set("wattsm2", (float)(event.light) / 683.0);
pub(subjectTSL12561toMQTT,TSL2561data); pub(subjectTSL12561toMQTT, TSL2561data);
} else { }
trc(F("Same lux value, do not send")); else
} {
} else { trc(F("Same lux value, do not send"));
}
}
else
{
trc(F("Failed to read from TSL2561")); trc(F("Failed to read from TSL2561"));
} }
} }
+10 -10
View File
@@ -28,13 +28,13 @@
extern void setup2G(); extern void setup2G();
extern bool _2GtoMQTT(); extern bool _2GtoMQTT();
extern void MQTTto2G(char * topicOri, char * datacallback); extern void MQTTto2G(char *topicOri, char *datacallback);
extern void MQTTto2G(char * topicOri, JsonObject& SMSdata); extern void MQTTto2G(char *topicOri, JsonObject &SMSdata);
/*-------------------2G topics & parameters----------------------*/ /*-------------------2G topics & parameters----------------------*/
//433Mhz MQTT Subjects and keys //433Mhz MQTT Subjects and keys
#define subjectMQTTto2G "/commands/MQTTto2G" #define subjectMQTTto2G "/commands/MQTTto2G"
#define subject2GtoMQTT "/2GtoMQTT" #define subject2GtoMQTT "/2GtoMQTT"
#define subjectGTW2GtoMQTT "/2GtoMQTT" #define subjectGTW2GtoMQTT "/2GtoMQTT"
#define _2GPhoneKey "PHO_" // phone number define the phone number to send the SMS MQTT->2G #define _2GPhoneKey "PHO_" // phone number define the phone number to send the SMS MQTT->2G
#define _2G_MODULE_BAUDRATE 9600 #define _2G_MODULE_BAUDRATE 9600
@@ -43,16 +43,16 @@ extern void MQTTto2G(char * topicOri, JsonObject& SMSdata);
/*-------------------PIN DEFINITIONS----------------------*/ /*-------------------PIN DEFINITIONS----------------------*/
#ifdef ESP8266 #ifdef ESP8266
#define _2G_TX_PIN D6 //D6 to A6 RX, #define _2G_TX_PIN D6 //D6 to A6 RX,
#define _2G_RX_PIN D7 //D7 to A6 TX #define _2G_RX_PIN D7 //D7 to A6 TX
#define _2G_PWR_PIN D5 // connect a MOSFET to power on and off your A6/7 module #define _2G_PWR_PIN D5 // connect a MOSFET to power on and off your A6/7 module
#elif defined(ESP32) #elif defined(ESP32)
#define _2G_TX_PIN 16 //D16 to A6 RX, #define _2G_TX_PIN 16 //D16 to A6 RX,
#define _2G_RX_PIN 17 //D17 to A6 TX #define _2G_RX_PIN 17 //D17 to A6 TX
#define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module #define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module
#else #else
#define _2G_TX_PIN 6 //D6 to A6 RX, #define _2G_TX_PIN 6 //D6 to A6 RX,
#define _2G_RX_PIN 7 //D7 to A6 TX #define _2G_RX_PIN 7 //D7 to A6 TX
#define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module #define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module
#endif #endif
+29 -29
View File
@@ -30,31 +30,31 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
#ifdef ZgatewayRF #ifdef ZgatewayRF
extern void setupRF(); extern void setupRF();
extern void RFtoMQTT(); extern void RFtoMQTT();
extern void MQTTtoRF(char * topicOri, char * datacallback); extern void MQTTtoRF(char *topicOri, char *datacallback);
extern void MQTTtoRF(char * topicOri, JsonObject& RFdata); extern void MQTTtoRF(char *topicOri, JsonObject &RFdata);
#endif #endif
#ifdef ZgatewayRF2 #ifdef ZgatewayRF2
extern void setupRF2(); extern void setupRF2();
extern void RF2toMQTT(); extern void RF2toMQTT();
extern void MQTTtoRF2(char * topicOri, char * datacallback); extern void MQTTtoRF2(char *topicOri, char *datacallback);
extern void MQTTtoRF2(char * topicOri, JsonObject& RFdata); extern void MQTTtoRF2(char *topicOri, JsonObject &RFdata);
#endif #endif
#ifdef ZgatewayPilight #ifdef ZgatewayPilight
extern void setupPilight(); extern void setupPilight();
extern void PilighttoMQTT(); extern void PilighttoMQTT();
extern void MQTTtoPilight(char * topicOri, char * datacallback); extern void MQTTtoPilight(char *topicOri, char *datacallback);
extern void MQTTtoPilight(char * topicOri, JsonObject& RFdata); extern void MQTTtoPilight(char *topicOri, JsonObject &RFdata);
#endif #endif
/*-------------------RF topics & parameters----------------------*/ /*-------------------RF topics & parameters----------------------*/
//433Mhz MQTT Subjects and keys //433Mhz MQTT Subjects and keys
#define subjectMQTTtoRF "/commands/MQTTto433" #define subjectMQTTtoRF "/commands/MQTTto433"
#define subjectRFtoMQTT "/433toMQTT" #define subjectRFtoMQTT "/433toMQTT"
#define subjectGTWRFtoMQTT "/433toMQTT" #define subjectGTWRFtoMQTT "/433toMQTT"
#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit #define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit
#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits #define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits
#define repeatRFwMQTT false // do we repeat a received signal by using mqtt with RF gateway #define repeatRFwMQTT false // do we repeat a received signal by using mqtt with RF gateway
/* /*
RF supported protocols RF supported protocols
@@ -73,31 +73,31 @@ RF supported protocols
/*-------------------RF2 topics & parameters----------------------*/ /*-------------------RF2 topics & parameters----------------------*/
//433Mhz newremoteswitch MQTT Subjects and keys //433Mhz newremoteswitch MQTT Subjects and keys
#define subjectMQTTtoRF2 "/commands/MQTTtoRF2" #define subjectMQTTtoRF2 "/commands/MQTTtoRF2"
#define subjectRF2toMQTT "/RF2toMQTT" #define subjectRF2toMQTT "/RF2toMQTT"
#define subjectGTWRF2toMQTT "/433toMQTT" #define subjectGTWRF2toMQTT "/433toMQTT"
#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits #define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits
#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits #define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits
#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits #define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits
#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit #define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit
#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits #define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits
/*-------------------ESPPiLight topics & parameters----------------------*/ /*-------------------ESPPiLight topics & parameters----------------------*/
//433Mhz Pilight MQTT Subjects and keys //433Mhz Pilight MQTT Subjects and keys
#define subjectMQTTtoPilight "/commands/MQTTtoPilight" #define subjectMQTTtoPilight "/commands/MQTTtoPilight"
#define subjectPilighttoMQTT "/PilighttoMQTT" #define subjectPilighttoMQTT "/PilighttoMQTT"
#define subjectGTWPilighttoMQTT "/PilighttoMQTT" #define subjectGTWPilighttoMQTT "/PilighttoMQTT"
#define PilightRAW "RAW" #define PilightRAW "RAW"
#define repeatPilightwMQTT false // do we repeat a received signal by using mqtt with Pilight gateway #define repeatPilightwMQTT false // do we repeat a received signal by using mqtt with Pilight gateway
/*-------------------PIN DEFINITIONS----------------------*/ /*-------------------PIN DEFINITIONS----------------------*/
#ifndef RF_RECEIVER_PIN #ifndef RF_RECEIVER_PIN
#ifdef ESP8266 #ifdef ESP8266
#define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod #define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod
#elif ESP32 #elif ESP32
#define RF_RECEIVER_PIN 27 // D27 on DOIT ESP32 #define RF_RECEIVER_PIN 27 // D27 on DOIT ESP32
#elif __AVR_ATmega2560__ #elif __AVR_ATmega2560__
#define RF_RECEIVER_PIN 1 //1 = D3 on mega #define RF_RECEIVER_PIN 1 //1 = D3 on mega
#else #else
#define RF_RECEIVER_PIN 1 //1 = D3 on arduino #define RF_RECEIVER_PIN 1 //1 = D3 on arduino
#endif #endif
+932 -796
View File
File diff suppressed because it is too large. Load diff