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
+2510 -1690

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,
+8 -15
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,16 +119,14 @@ 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"];
@@ -151,7 +145,6 @@ void MQTTtoFASTLEDJSON(char *topicOri, JsonObject& jsonData)
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++)
{
+17 -10
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,8 +70,10 @@ 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
@@ -75,5 +83,4 @@ void MQTTtoONOFF(char * topicOri, char * datacallback) {
}
#endif
#endif
+58 -33
View File
@@ -39,7 +39,8 @@ int unreadSMSLocs[50] = {0};
int unreadSMSNum = 0;
SMSmessage sms;
void setup2G(){
void setup2G()
{
trc(F("_2G_TX_PIN "));
trc(_2G_TX_PIN);
@@ -49,7 +50,8 @@ void setup2G(){
trc(F("Zgateway2G setup done "));
}
void setupGSM(bool deleteSMS){
void setupGSM(bool deleteSMS)
{
trc(F("Init 2G module: "));
trc(_2G_PWR_PIN);
delay(1000);
@@ -61,33 +63,41 @@ void setupGSM(bool deleteSMS){
signalStrengthAnalysis();
delay(1000);
// deleting all sms
if (deleteSMS){
if (A6l.deleteSMS(1,4) == A6_OK ) {
if (deleteSMS)
{
if (A6l.deleteSMS(1, 4) == A6_OK)
{
trc(F("delete SMS OK"));
}else{
}
else
{
trc(F("delete SMS KO"));
}
}
}
void signalStrengthAnalysis(){
void signalStrengthAnalysis()
{
int signalStrength = 0;
signalStrength = A6l.getSignalStrength();
trc(F("Signal strength: "));
trc(signalStrength);
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL ) {
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL)
{
trc(F("Signal too low restart the module"));
setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module
}
}
bool _2GtoMQTT(){
bool _2GtoMQTT()
{
// Get the memory locations of unread SMS messages.
unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512);
trc(F("Creating SMS buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++) {
JsonObject &SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++)
{
trc(F("New message at index: "));
trc(unreadSMSNum);
sms = A6l.readSMS(unreadSMSLocs[i]);
@@ -96,68 +106,83 @@ bool _2GtoMQTT(){
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);
pub(subject2GtoMQTT, SMSdata);
return true;
}
return false;
}
#ifdef simpleReceiving
void MQTTto2G(char * topicOri, char * datacallback) {
void MQTTto2G(char *topicOri, char *datacallback)
{
String data = datacallback;
String topic = topicOri;
if (cmpToMainTopic(topicOri,subjectMQTTto2G)) {
if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
trc(F("MQTTto2G data analysis"));
// 2G DATA ANALYSIS
String phone_number = "";
int pos0 = topic.lastIndexOf(_2GPhoneKey);
if (pos0 != -1) {
if (pos0 != -1)
{
pos0 = pos0 + strlen(_2GPhoneKey);
phone_number = topic.substring(pos0);
trc(F("MQTTto2G phone ok"));
trc(phone_number);
trc(F("MQTTto2G sms"));
trc(data);
if (A6l.sendSMS(phone_number,data) == A6_OK ) {
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{
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
pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}else{
}
else
{
trc(F("MQTTto2G Fail reading phone number"));
}
}
}
}
#endif
#ifdef jsonReceiving
void MQTTto2G(char * topicOri, JsonObject& SMSdata) {
void MQTTto2G(char *topicOri, JsonObject &SMSdata)
{
if (cmpToMainTopic(topicOri,subjectMQTTto2G)){
const char * sms = SMSdata["message"];
const char * phone = SMSdata["phone"];
if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
const char *sms = SMSdata["message"];
const char *phone = SMSdata["phone"];
trc(F("MQTTto2G json data analysis"));
if (sms && phone) {
if (sms && phone)
{
trc(F("MQTTto2G sms & phone ok"));
trc(sms);
if (A6l.sendSMS(String(phone),String(sms)) == A6_OK ) {
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
pub(subjectGTW2GtoMQTT, "SMS OK"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}else{
else
{
trc(F("SMS KO"));
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
+481 -337
View File
File diff suppressed because it is too large. Load diff
+723 -488
View File
File diff suppressed because it is too large. Load diff
+55 -39
View File
@@ -33,13 +33,16 @@
#include <LoRa.h>
#include <Wire.h>
void setupLORA() {
SPI.begin(LORA_SCK,LORA_MISO,LORA_MOSI,LORA_SS);
LoRa.setPins(LORA_SS,LORA_RST,LORA_DI0);
void setupLORA()
{
SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_SS);
LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0);
if (!LoRa.begin(LORA_BAND)) {
if (!LoRa.begin(LORA_BAND))
{
trc(F("ZgatewayLORA setup failed!"));
while (1);
while (1)
;
}
LoRa.receive();
trc(F("LORA_SCK"));
@@ -55,50 +58,58 @@ 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
#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(); }
#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){
pub(subjectLORAtoMQTT, LORAdata);
if (repeatLORAwMQTT)
{
trc(F("Pub LORA for rpt"));
pub(subjectMQTTtoLORA,LORAdata);
pub(subjectMQTTtoLORA, LORAdata);
}
}
}
#ifdef jsonReceiving
void MQTTtoLORA(char * topicOri, JsonObject& LORAdata) { // json object decoding
if (cmpToMainTopic(topicOri,subjectMQTTtoLORA)){
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) {
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);
@@ -106,27 +117,32 @@ void LORAtoMQTT(){
LoRa.setCodingRate4(codingRateDenominator);
LoRa.setPreambleLength(preambleLength);
LoRa.setSyncWord(syncWord);
if (Crc) LoRa.enableCrc();
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{
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)){
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
}
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
+52 -32
View File
@@ -27,33 +27,37 @@
*/
#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){
pub(subjectPilighttoMQTT, RFPiLightdata);
if (repeatPilightwMQTT)
{
trc(F("Pub Pilight for rpt"));
pub(subjectMQTTtoPilight,RFPiLightdata);
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
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 "));
@@ -61,37 +65,45 @@ void setupPilight(){
trc(F("RF_RECEIVER_PIN "));
trc(String(RF_RECEIVER_PIN));
trc(F("ZgatewayPilight setup done "));
#else
#else
trc(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2 && ZgatewayRF315"));
#endif
#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) {
switch (result)
{
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C:
trc(F("'c' not found in string, or has no data"));
break;
@@ -106,18 +118,26 @@ void MQTTtoPilight(char * topicOri, JsonObject& Pilightdata) {
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) {
}
else
{
switch (result)
{
case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL:
trc(F("protocol is not available"));
break;
@@ -137,4 +157,4 @@ void MQTTtoPilight(char * topicOri, JsonObject& Pilightdata) {
}
}
}
#endif
#endif
+63 -42
View File
@@ -34,11 +34,12 @@
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, "", ""};
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"));
@@ -47,11 +48,12 @@ void RFtoMQTTdiscovery(unsigned long MQTTvalue){//on the fly switch creation fro
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);
0, "", "", true, subjectMQTTtoRF);
}
#endif
void setupRF(){
void setupRF()
{
//RF init parameters
mySwitch.enableTransmit(RF_EMITTER_PIN);
@@ -64,42 +66,47 @@ void setupRF(){
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
#ifdef ESP32
String taskMessage = "RF Task running on core ";
taskMessage = taskMessage + xPortGetCoreID();
trc(taskMessage);
#endif
#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
if (!isAduplicate(MQTTvalue) && MQTTvalue != 0)
{ // conditions to avoid duplications of RF -->MQTT
#ifdef ZmqttDiscovery //component creation for HA
RFtoMQTTdiscovery(MQTTvalue);
#endif
pub(subjectRFtoMQTT,RFdata);
#endif
pub(subjectRFtoMQTT, RFdata);
trc(F("Store val"));
storeValue(MQTTvalue);
if (repeatRFwMQTT){
if (repeatRFwMQTT)
{
trc(F("Pub RF for rpt"));
pub(subjectMQTTtoRF,RFdata);
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
@@ -110,70 +117,84 @@ void MQTTtoRF(char * topicOri, char * datacallback) {
int valuePLSL = 0;
int valueBITS = 0;
int pos = topic.lastIndexOf(RFprotocolKey);
if (pos != -1){
if (pos != -1)
{
pos = pos + +strlen(RFprotocolKey);
valuePRT = (topic.substring(pos,pos + 1)).toInt();
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
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){
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)){
}
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
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)){
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;
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.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
pub(subjectGTWRFtoMQTT, RFdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT); // Restore the default value
}else{
}
else
{
trc(F("MQTTtoRF Fail json"));
}
}
}
}
#endif
#endif
+93 -57
View File
@@ -52,26 +52,29 @@ struct RF2rxd
RF2rxd rf2rd;
void setupRF2(){
#ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF
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
#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;
@@ -83,23 +86,24 @@ void RF2toMQTT(){
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) {
void MQTTtoRF2(char *topicOri, char *datacallback)
{
// RF DATA ANALYSIS
//We look into the subject to see if a special RF protocol is defined
@@ -115,46 +119,55 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
int valueDIM = -1;
int pos = topic.lastIndexOf(RF2codeKey);
if (pos != -1){
if (pos != -1)
{
pos = pos + +strlen(RF2codeKey);
valueCODE = (topic.substring(pos,pos + 8)).toInt();
valueCODE = (topic.substring(pos, pos + 8)).toInt();
trc(F("RF2 code:"));
trc(valueCODE);
}
int pos2 = topic.lastIndexOf(RF2periodKey);
if (pos2 != -1) {
if (pos2 != -1)
{
pos2 = pos2 + strlen(RF2periodKey);
valuePERIOD = (topic.substring(pos2,pos2 + 3)).toInt();
valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt();
trc(F("RF2 Period:"));
trc(valuePERIOD);
}
int pos3 = topic.lastIndexOf(RF2unitKey);
if (pos3 != -1){
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) {
if (pos4 != -1)
{
pos4 = pos4 + strlen(RF2groupKey);
valueGROUP = (topic.substring(pos4,pos4 + 1)).toInt();
valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt();
trc(F("RF2 Group:"));
trc(valueGROUP);
}
int pos5 = topic.lastIndexOf(RF2dimKey);
if (pos5 != -1) {
if (pos5 != -1)
{
isDimCommand = true;
valueDIM = atoi(datacallback);
trc(F("RF2 Dim:"));
trc(valueDIM);
}
if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){
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;
if (valueCODE == 0)
valueCODE = 8233378;
if (valueUNIT == -1)
valueUNIT = 0;
if (valuePERIOD == 0)
valuePERIOD = 272;
trc(valueCODE);
trc(valueUNIT);
trc(valuePERIOD);
@@ -165,19 +178,25 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
trc(F("Creating transmitter"));
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
trc(F("Sending data"));
if (valueGROUP) {
if (isDimCommand) {
if (valueGROUP)
{
if (isDimCommand)
{
transmitter.sendGroupDim(valueDIM);
}
else {
else
{
transmitter.sendGroup(boolSWITCHTYPE);
}
}
else {
if (isDimCommand) {
else
{
if (isDimCommand)
{
transmitter.sendDim(valueUNIT, valueDIM);
}
else {
else
{
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
}
}
@@ -200,25 +219,30 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
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());
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
void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
{ // json object decoding
if (cmpToMainTopic(topicOri,subjectMQTTtoRF2)){
if (cmpToMainTopic(topicOri, subjectMQTTtoRF2))
{
trc(F("MQTTtoRF2 json"));
int boolSWITCHTYPE = RF2data["switchType"] | 99;
if (boolSWITCHTYPE != 99) {
if (boolSWITCHTYPE != 99)
{
trc(F("MQTTtoRF2 switch type ok"));
bool isDimCommand = boolSWITCHTYPE == 2;
unsigned long valueCODE = RF2data["address"];
@@ -226,11 +250,15 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
int valuePERIOD = RF2data["period"];
int valueGROUP = RF2data["group"];
int valueDIM = RF2data["dim"] | -1;
if ((valueCODE != 0) || (valueUNIT != -1)|| (valuePERIOD != 0)){
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;
if (valueCODE == 0)
valueCODE = 8233378;
if (valueUNIT == -1)
valueUNIT = 0;
if (valuePERIOD == 0)
valuePERIOD = 272;
trc(valueCODE);
trc(valueUNIT);
trc(valuePERIOD);
@@ -240,19 +268,25 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
NewRemoteReceiver::disable();
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
trc(F("Sending"));
if (valueGROUP) {
if (isDimCommand) {
if (valueGROUP)
{
if (isDimCommand)
{
transmitter.sendGroupDim(valueDIM);
}
else {
else
{
transmitter.sendGroup(boolSWITCHTYPE);
}
}
else {
if (isDimCommand) {
else
{
if (isDimCommand)
{
transmitter.sendDim(valueUNIT, valueDIM);
}
else {
else
{
transmitter.sendUnit(valueUNIT, boolSWITCHTYPE);
}
}
@@ -260,12 +294,14 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
NewRemoteReceiver::enable();
// Publish state change back to MQTT
pub(subjectGTWRF2toMQTT,RF2data);
pub(subjectGTWRF2toMQTT, RF2data);
}
}else{
}
else
{
trc(F("MQTTtoRF2 failed json read"));
}
}
}
}
#endif
#endif
+67 -41
View File
@@ -40,10 +40,11 @@ char RadioConfig[128];
// vvvvvvvvv Global Configuration vvvvvvvvvvv
struct _GLOBAL_CONFIG {
struct _GLOBAL_CONFIG
{
uint32_t checksum;
char rfmapname[32];
char encryptkey[16+1];
char encryptkey[16 + 1];
uint8_t networkid;
uint8_t nodeid;
uint8_t powerlevel; // bits 0..4 power leve, bit 7 RFM69HCW 1=true
@@ -52,34 +53,38 @@ struct _GLOBAL_CONFIG {
#define GC_POWER_LEVEL (pGC->powerlevel & 0x1F)
#define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0)
#define SELECTED_FREQ(f) ((pGC->rfmfrequency==f)?"selected":"")
#define SELECTED_FREQ(f) ((pGC->rfmfrequency == f) ? "selected" : "")
struct _GLOBAL_CONFIG *pGC;
// 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,10 +94,11 @@ void eeprom_setup() {
RFM69 radio;
void setupRFM69(void) {
#if defined(ESP8266) || defined(ESP32)
void setupRFM69(void)
{
#if defined(ESP8266) || defined(ESP32)
eeprom_setup();
#endif
#endif
int freq;
static const char PROGMEM JSONtemplate[] =
R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})";
@@ -106,15 +112,18 @@ void setupRFM69(void) {
trc(F("ZgatewayRFM69 initialization failed"));
}
if (GC_IS_RFM69HCW) {
if (GC_IS_RFM69HCW)
{
radio.setHighPower(); // Only for RFM69HCW & HW!
}
radio.setPowerLevel(GC_POWER_LEVEL); // power output ranges from 0 (5dBm) to 31 (20dBm)
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) {
switch (pGC->rfmfrequency)
{
case RF69_433MHZ:
freq = 433;
break;
@@ -135,19 +144,21 @@ void setupRFM69(void) {
size_t len = snprintf_P(RadioConfig, sizeof(RadioConfig), JSONtemplate,
freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL);
if (len >= sizeof(RadioConfig)) {
if (len >= sizeof(RadioConfig))
{
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;
@@ -167,26 +178,29 @@ 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("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)){
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
trc(F("MQTTtoRFM69 data analysis"));
char data[RF69_MAX_DATA_LEN+1];
char data[RF69_MAX_DATA_LEN + 1];
memcpy(data, (void *)datacallback, RF69_MAX_DATA_LEN);
data[RF69_MAX_DATA_LEN] = '\0';
@@ -194,46 +208,58 @@ bool RFM69toMQTT(void) {
String topic = topicOri;
int valueRCV = defaultRFM69ReceiverId; //default receiver id value
int pos = topic.lastIndexOf(RFM69receiverKey);
if (pos != -1){
if (pos != -1)
{
pos = pos + +strlen(RFM69receiverKey);
valueRCV = (topic.substring(pos,pos + 3)).toInt();
valueRCV = (topic.substring(pos, pos + 3)).toInt();
trc(F("RFM69 receiver ID:"));
trc(valueRCV);
}
if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) {
if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
{
trc(F(" OK "));
// Acknowledgement to the GTWRF topic
char buff[sizeof(subjectGTWRFM69toMQTT)+4];
char buff[sizeof(subjectGTWRFM69toMQTT) + 4];
sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID);
pub(buff, data);
} else {
}
else
{
trc(F("RFM69 sending failed"));
}
}
}
}
#endif
#ifdef jsonReceiving
void MQTTtoRFM69(char * topicOri, JsonObject& RFM69data) {
void MQTTtoRFM69(char *topicOri, JsonObject &RFM69data)
{
if (cmpToMainTopic(topicOri,subjectMQTTtoRFM69)){
const char * data = RFM69data["data"];
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
const char *data = RFM69data["data"];
trc(F("MQTTtoRFM69 json data analysis"));
if(data){
if (data)
{
trc(F("MQTTtoRFM69 data ok"));
int valueRCV = RFM69data["receiverid"]| defaultRFM69ReceiverId; //default receiver id value
int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value
trc(F("RFM69 receiver ID:"));
trc(valueRCV);
if(radio.sendWithRetry(valueRCV, data, strlen(data),10)) {
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 {
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{
}
else
{
trc(F("MQTTtoRFM69 failed json read"));
}
}
}
}
#endif
#endif
+145 -95
View File
@@ -32,19 +32,22 @@
#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) {
void _rfbSend(byte *message)
{
Serial.println();
Serial.write(RF_CODE_START);
Serial.write(RF_CODE_RFOUT);
for (unsigned char j=0; j<RF_MESSAGE_SIZE; j++) {
for (unsigned char j = 0; j < RF_MESSAGE_SIZE; j++)
{
Serial.write(message[j]);
}
Serial.write(RF_CODE_STOP);
@@ -52,97 +55,114 @@ void _rfbSend(byte * message) {
Serial.println();
}
void _rfbSend(byte * message, int times) {
void _rfbSend(byte *message, int times)
{
char buffer[RF_MESSAGE_SIZE];
_rfbToChar(message, buffer);
trc(F("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n"));
for (int i=0; i<times; i++) {
if (i>0) {
for (int i = 0; i < times; i++)
{
if (i > 0)
{
unsigned long start = millis();
while (millis() - start < RF_SEND_DELAY) delay(1);
while (millis() - start < RF_SEND_DELAY)
delay(1);
}
_rfbSend(message);
}
}
bool SRFBtoMQTT() {
bool SRFBtoMQTT()
{
static bool receiving = false;
while (Serial.available()) {
while (Serial.available())
{
yield();
byte c = Serial.read();
if (receiving) {
if (c == RF_CODE_STOP) {
if (receiving)
{
if (c == RF_CODE_STOP)
{
_rfbDecode();
receiving = false;
} else {
}
else
{
_uartbuf[_uartpos++] = c;
}
} else if (c == RF_CODE_START) {
}
else if (c == RF_CODE_START)
{
_uartpos = 0;
receiving = true;
}
}
return receiving;
}
void _rfbDecode() {
void _rfbDecode()
{
static unsigned long last = 0;
if (millis() - last < RF_RECEIVE_DELAY) return;
if (millis() - last < RF_RECEIVE_DELAY)
return;
last = millis();
byte action = _uartbuf[0];
char buffer[RF_MESSAGE_SIZE * 2 + 1] = {0};
if (action == RF_CODE_RFIN) {
if (action == RF_CODE_RFIN)
{
_rfbToChar(&_uartbuf[1], buffer);
trc(F("Creating SRFB buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& SRFBdata = jsonBuffer.createObject();
JsonObject &SRFBdata = jsonBuffer.createObject();
SRFBdata.set("raw", (char *)buffer);
char Tsyn[4]= {0};
extract_char(buffer, Tsyn , 0 ,4, false, true);
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);
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);
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);
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
if (!isAduplicate(MQTTvalue) && MQTTvalue != 0)
{ // conditions to avoid duplications of RF -->MQTT
trc(F("Adv data SRFBtoMQTT"));
pub(subjectSRFBtoMQTT,SRFBdata);
pub(subjectSRFBtoMQTT, SRFBdata);
trc(F("Store val"));
storeValue(MQTTvalue);
if (repeatSRFBwMQTT){
if (repeatSRFBwMQTT)
{
trc(F("Publish SRFB for rpt"));
pub(subjectMQTTtoSRFB,SRFBdata);
pub(subjectMQTTtoSRFB, SRFBdata);
}
}
_rfbAck();
}
}
void _rfbAck() {
void _rfbAck()
{
trc(F("[RFBRIDGE] Sending ACK\n"));
Serial.println();
Serial.write(RF_CODE_START);
@@ -155,11 +175,14 @@ void _rfbAck() {
/*
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;
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);
for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++)
{
memcpy(tmp, &in[p * 2], 2);
out[p] = strtol(tmp, NULL, 16);
}
return true;
@@ -168,81 +191,93 @@ bool _rfbToArray(const char * in, byte * out) {
/*
From a byte array to an hexa char array ("A220EE...", double the size)
*/
bool _rfbToChar(byte * in, char * out) {
for (unsigned char p = 0; p<RF_MESSAGE_SIZE; p++) {
sprintf_P(&out[p*2], PSTR("%02X"), in[p]);
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) {
void MQTTtoSRFB(char *topicOri, char *datacallback)
{
// RF DATA ANALYSIS
String topic = topicOri;
int valueRPT = 0;
if (topic == subjectMQTTtoSRFB){
if (topic == subjectMQTTtoSRFB)
{
int valueMiniPLSL = 0;
int valueMaxiPLSL = 0;
int valueSYNC = 0;
int pos = topic.lastIndexOf(SRFBRptKey);
if (pos != -1){
if (pos != -1)
{
pos = pos + +strlen(SRFBRptKey);
valueRPT = (topic.substring(pos,pos + 1)).toInt();
valueRPT = (topic.substring(pos, pos + 1)).toInt();
trc(F("SRFB Repeat:"));
trc(valueRPT);
}
int pos2 = topic.lastIndexOf(SRFBminipulselengthKey);
if (pos2 != -1) {
if (pos2 != -1)
{
pos2 = pos2 + strlen(SRFBminipulselengthKey);
valueMiniPLSL = (topic.substring(pos2,pos2 + 3)).toInt();
valueMiniPLSL = (topic.substring(pos2, pos2 + 3)).toInt();
trc(F("RF Mini Pulse Lgth:"));
trc(valueMiniPLSL);
}
int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey);
if (pos3 != -1){
if (pos3 != -1)
{
pos3 = pos3 + strlen(SRFBmaxipulselengthKey);
valueMaxiPLSL = (topic.substring(pos3,pos3 + 2)).toInt();
valueMaxiPLSL = (topic.substring(pos3, pos3 + 2)).toInt();
trc(F("RF Maxi Pulse Lgth:"));
trc(valueMaxiPLSL);
}
int pos4 = topic.lastIndexOf(SRFBsyncKey);
if (pos4 != -1){
if (pos4 != -1)
{
pos4 = pos4 + strlen(SRFBsyncKey);
valueSYNC = (topic.substring(pos4,pos4 + 2)).toInt();
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;
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) ;
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) ;
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];
@@ -253,69 +288,82 @@ bool _rfbToChar(byte * in, char * out) {
_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
pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
if (topic == subjectMQTTtoSRFBRaw){
if (topic == subjectMQTTtoSRFBRaw)
{
int pos = topic.lastIndexOf(SRFBRptKey);
if (pos != -1){
if (pos != -1)
{
pos = pos + +strlen(SRFBRptKey);
valueRPT = (topic.substring(pos,pos + 1)).toInt();
valueRPT = (topic.substring(pos, pos + 1)).toInt();
trc(F("SRFB Repeat:"));
trc(valueRPT);
}
if (valueRPT == 0) valueRPT = 1;
if (valueRPT == 0)
valueRPT = 1;
byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(datacallback,message_b);
_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
}
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) {
void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata)
{
// RF DATA ANALYSIS
const char * raw = SRFBdata["raw"];
int valueRPT = SRFBdata["repeat"]|1;
if (cmpToMainTopic(topicOri,subjectMQTTtoSRFB)){
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
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);
_rfbToArray(raw, message_b);
_rfbSend(message_b, valueRPT);
}else{
}
else
{
unsigned long data = SRFBdata["value"];
if (data != 0) {
if (data != 0)
{
trc(F("MQTTtoSRFB data ok"));
int valueMiniPLSL = SRFBdata["val_Tlow"];
int valueMaxiPLSL =SRFBdata["val_Thigh"];
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;
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) ;
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];
@@ -327,12 +375,14 @@ bool _rfbToChar(byte * in, char * out) {
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{
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
+106 -93
View File
@@ -31,15 +31,15 @@ String getMacAddress()
{
uint8_t baseMac[6];
char baseMacChr[13] = {0};
#if defined(ESP8266)
#if defined(ESP8266)
WiFi.macAddress(baseMac);
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#elif defined(ESP32)
#elif defined(ESP32)
esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#else
#else
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
#endif
#endif
return String(baseMacChr);
}
@@ -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 (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]) {
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();
@@ -114,55 +124,56 @@ void pubMqttDiscovery()
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
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"}
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++){
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 }}","", "", "%"}
};
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++){
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 }}","", "", ""};
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"));
@@ -171,54 +182,56 @@ void pubMqttDiscovery()
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,"");
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²"}
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++){
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²"}
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++){
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", ""};
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"));
@@ -227,12 +240,12 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZsensorGPIOInput
trc(F("GPIOInputDiscovery"));
char * GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "GPIOInput", "","{{value_json.gpio}}","HIGH", "LOW", ""};
char *GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "GPIOInput", "", "{{value_json.gpio}}", "HIGH", "LOW", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -241,33 +254,34 @@ void pubMqttDiscovery()
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,"");
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"}
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++){
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", ""};
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"));
@@ -276,14 +290,13 @@ void pubMqttDiscovery()
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);
0, "", "", true, subjectMQTTtoONOFF);
#endif
#ifdef ZgatewayRF
// Sensor to display RF received value
trc(F("gatewayRFDiscovery"));
char * gatewayRF[8] = {"sensor", "gatewayRF", "", "","{{ value_json.value }}","", "", ""};
char *gatewayRF[8] = {"sensor", "gatewayRF", "", "", "{{ value_json.value }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -292,13 +305,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayRF2
// Sensor to display RF received value
trc(F("gatewayRF2Discovery"));
char * gatewayRF2[8] = {"sensor", "gatewayRF2", "", "","{{ value_json.value }}","", "", ""};
char *gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", "{{ value_json.value }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -307,13 +320,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayRF315
// Sensor to display RF received value
trc(F("gatewayRF315Discovery"));
char * gatewayRF315[8] = {"sensor", "gatewayRF315", "", "","{{ value_json.value }}","", "", ""};
char *gatewayRF315[8] = {"sensor", "gatewayRF315", "", "", "{{ value_json.value }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -322,13 +335,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayRFM69
// Sensor to display RF received value
trc(F("gatewayRFM69Discovery"));
char * gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "","{{ value_json.value }}","", "", ""};
char *gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", "{{ value_json.value }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -337,13 +350,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayLORA
// Sensor to display RF received value
trc(F("gatewayLORADiscovery"));
char * gatewayLORA[8] = {"sensor", "gatewayLORA", "", "","{{ value_json.message }}","", "", ""};
char *gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", "{{ value_json.message }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -352,13 +365,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewaySRFB
// Sensor to display RF received value
trc(F("gatewaySRFBDiscovery"));
char * gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "","{{ value_json.value }}","", "", ""};
char *gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", "{{ value_json.value }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -367,13 +380,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayPilight
// Sensor to display RF received value
trc(F("gatewayPilightDiscovery"));
char * gatewayPilight[8] = {"sensor", "gatewayPilight", "", "","{{ value_json.message }}","", "", ""};
char *gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", "{{ value_json.message }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -382,13 +395,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayIR
// Sensor to display IR received value
trc(F("gatewayIRDiscovery"));
char * gatewayIR[8] = {"sensor", "gatewayIR", "", "","{{ value_json.value }}","", "", ""};
char *gatewayIR[8] = {"sensor", "gatewayIR", "", "", "{{ value_json.value }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -397,13 +410,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef Zgateway2G
// Sensor to display 2G received value
trc(F("gateway2GDiscovery"));
char * gateway2G[8] = {"sensor", "gateway2G", "", "","{{ value_json.message }}","", "", ""};
char *gateway2G[8] = {"sensor", "gateway2G", "", "", "{{ value_json.message }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -412,13 +425,13 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
#ifdef ZgatewayBT
// Sensor to display BT received value
trc(F("gatewayBTDiscovery"));
char * gatewayBT[8] = {"sensor", "gatewayBT", "", "","{{ value_json.id }}","", "", ""};
char *gatewayBT[8] = {"sensor", "gatewayBT", "", "", "{{ value_json.id }}", "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
trc(F("CreateDiscoverySensor"));
@@ -427,7 +440,7 @@ void pubMqttDiscovery()
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,"");
0, "", "", true, "");
#endif
}
+16 -10
View File
@@ -31,30 +31,36 @@
#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)
void MeasureADC()
{
if (millis() > (timeadc + TimeBetweenReadingADC))
{ //retriving value of temperature and humidity of the box from DHT every xUL
#if defined(ESP8266)
yield();
#endif
#endif
timeadc = millis();
static int persistedadc;
int val = analogRead(ADC_PIN);
if (isnan(val)) {
if (isnan(val))
{
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;
}
}
+31 -17
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
@@ -54,13 +54,14 @@ void setupZsensorBH1750()
// 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 <<= 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;
+40 -18
View File
@@ -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{
}
else
{
trc(F("Creating BME280 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& BME280data = jsonBuffer.createObject();
JsonObject &BME280data = jsonBuffer.createObject();
// Generate Temperature in degrees C
if(BmeTempC != persisted_bme_tempc || bme280_always){
if (BmeTempC != persisted_bme_tempc || bme280_always)
{
BME280data.set("tempc", (float)BmeTempC);
}else{
}
else
{
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;
}
}
+23 -11
View File
@@ -33,13 +33,15 @@
#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;
@@ -47,23 +49,33 @@ void MeasureTempAndHum(){
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
if (isnan(h) || isnan(t))
{
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;
+22 -17
View File
@@ -34,12 +34,13 @@ unsigned long lastDebounceTime = 0;
int InputState = 3; // Set to 3 so that it reads on startup
int lastInputState = 3;
void setupGPIOInput() {
void setupGPIOInput()
{
pinMode(GPIOInput_PIN, INPUT_PULLUP); // declare GPIOInput pin as input_pullup to prevent floating. Pin will be high when not connected to ground
}
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
+12 -10
View File
@@ -31,7 +31,8 @@ int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on st
int lastInputStateGPIOKeyCode = 0x0f;
int lastLatchStateGPIOKeyCode = 0;
void setupGPIOKeyCode() {
void setupGPIOKeyCode()
{
pinMode(GPIOKeyCode_LATCH_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); //
@@ -39,7 +40,8 @@ void setupGPIOKeyCode() {
//pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); //
}
void MeasureGPIOKeyCode(){
void MeasureGPIOKeyCode()
{
int latch = digitalRead(GPIOKeyCode_LATCH_PIN);
@@ -50,14 +52,13 @@ 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);
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,11 +67,12 @@ 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) {
if (latch != lastLatchStateGPIOKeyCode)
{
lastLatchStateGPIOKeyCode = latch;
Serial.printf("GPIOKeyCode latch %d\n", latch);
if (latch == 0)
+23 -11
View File
@@ -33,41 +33,53 @@
unsigned long timeHCSR04 = 0;
void setupHCSR04() {
void setupHCSR04()
{
pinMode(HCSR04_TRI_PIN, OUTPUT); // declare HC SR-04 trigger pin as output
pinMode(HCSR04_ECH_PIN, INPUT); // declare HC SR-04 echo pin as input
}
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);
}
}
}
+18 -9
View File
@@ -30,36 +30,45 @@
#ifdef ZsensorHCSR501
void setupHCSR501() {
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();
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) {
if (PresenceValue == HIGH)
{
if (pirState == LOW)
{
//turned on
HCSR501data.set("hcsr501", "true");
trc(F("HC SR501 Motion started"));
pirState = HIGH;
}
} else {
if (pirState == HIGH){
}
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);
if (HCSR501data.size() > 0)
pub(subjectHCSR501toMQTT, HCSR501data);
}
}
#endif
+24 -16
View File
@@ -37,24 +37,27 @@
#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() {
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
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();
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
@@ -64,32 +67,34 @@ void MeasureINA226(){
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
if (shuntvolt && 0x8000)
{ // eine negative Zahl? Dann 2er Komplement bilden
shuntvolt = ~shuntvolt; // alle Bits invertieren
shuntvolt += 1; // 1 dazuzählen
shuntvolt *= -1 ; // negativ machen
shuntvolt *= -1; // negativ machen
}
float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R
trc(current);
trc(F(" A, Power: "));
float power=abs(volt*current);
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);
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);
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,12 +102,15 @@ static void writeRegister(byte reg, word value) {
Wire.endTransmission();
}
static word readRegister(byte reg) {
static word readRegister(byte reg)
{
word res = 0x0000;
Wire.beginTransmission(INA226_ADDR);
Wire.write(reg);
if (Wire.endTransmission() == 0) {
if (Wire.requestFrom(INA226_ADDR, 2) >= 2) {
if (Wire.endTransmission() == 0)
{
if (Wire.requestFrom(INA226_ADDR, 2) >= 2)
{
res = Wire.read() * 256;
res += Wire.read();
}
+15 -9
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
@@ -88,31 +88,37 @@ void setupZsensorTSL2561()
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 (persisted_lux != event.light || tsl2561_always ) {
if (persisted_lux != event.light || tsl2561_always)
{
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("ftcd", (float)(event.light) / 10.764);
TSL2561data.set("wattsm2", (float)(event.light) / 683.0);
pub(subjectTSL12561toMQTT,TSL2561data);
} else {
pub(subjectTSL12561toMQTT, TSL2561data);
}
else
{
trc(F("Same lux value, do not send"));
}
} else {
}
else
{
trc(F("Failed to read from TSL2561"));
}
}
+2 -2
View File
@@ -28,8 +28,8 @@
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"
+12 -12
View File
@@ -30,22 +30,22 @@
#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
+402 -266
View File
File diff suppressed because it is too large. Load diff