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