Added clang-format (#623)

* added .clang-format
* added names to travis jobs
removed deprecated travis option
* check github action
* added .gitignore
This commit is contained in:
Leon Kiefer authored and GitHub committed 2020-06-09 16:09:23 -05:00
1 parent 661ef9c55e
commit 10a9d00aaf
33 files changed
+753 -1501

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
BasedOnStyle: Google
Language: Cpp
ColumnLimit: 0
IndentWidth: 2
TabWidth: 2
UseTab: Never
IndentPPDirectives: AfterHash
ReflowComments: false
SpacesBeforeTrailingComments: 1
AlignConsecutiveMacros: true
AlignTrailingComments: false
AccessModifierOffset: -2
DerivePointerAlignment: false
PointerAlignment: Left
+8
View File
@@ -0,0 +1,8 @@
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = true
+22
View File
@@ -0,0 +1,22 @@
name: Check Code Format
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Check main format
uses: DoozyX/clang-format-lint-action@v0.6
with:
source: "./main"
extensions: "h,ino"
clangFormatVersion: 9
- name: Check test format
uses: DoozyX/clang-format-lint-action@v0.6
with:
source: "./test"
extensions: "h,ino"
clangFormatVersion: 9
+2
View File
@@ -0,0 +1,2 @@
.pio
.vscode
+8 -8
View File
@@ -19,15 +19,14 @@
# Travis CI documentation (see above).
#
#
# Template #1: General project. Test it using existing `platformio.ini`.
#
matrix:
jobs:
include:
- language: python
- name: "Build and deploy with PlatformIO"
language: python
python: 2.7
sudo: false
cache:
directories:
- "~/.platformio"
@@ -52,7 +51,8 @@ matrix:
- toDeploy/*
skip_cleanup: true
- language: node_js
- name: "Build and deploy docs"
language: node_js
node_js:
- lts/*
install:
@@ -63,10 +63,10 @@ matrix:
before_deploy: echo "docs.openmqttgateway.com" >> docs/.vuepress/dist/CNAME
deploy:
provider: pages
skip-cleanup: true
skip_cleanup: true
local_dir: docs/.vuepress/dist
github-token: $GITHUB_TOKEN # a token generated on github allowing travis to push code on you repository
keep-history: true
github_token: $GITHUB_TOKEN # a token generated on github allowing travis to push code on you repository
keep_history: true
on:
repo: 1technophile/OpenMQTTGateway
all_branches: true
+34 -79
View File
@@ -26,8 +26,7 @@
# include <FastLED.h>
enum LEDState
{
enum LEDState {
OFF,
FIRE,
GENERAL
@@ -42,8 +41,7 @@ const long blinkInterval = 300;
const long fireUpdate = 10;
CRGBPalette16 gPal;
void setupFASTLED()
{
void setupFASTLED() {
Log.notice(F("FASTLED_DATA_PIN: %d" CR), FASTLED_DATA_PIN);
Log.notice(F("FASTLED_NUM_LEDS: %d" CR), FASTLED_NUM_LEDS);
Log.trace(F("ZactuatorFASTLED setup done " CR));
@@ -51,15 +49,13 @@ void setupFASTLED()
}
//returns the current step of the animation
int animation_step(int duration, int steps)
{
int animation_step(int duration, int steps) {
int currentStep = ((currentUpdate % duration) / ((float)duration)) * steps;
return currentStep;
}
//returns the number of steps since the last update
int animation_step_count(int duration, int steps)
{
int animation_step_count(int duration, int steps) {
long lastAnimationNumber = lastUpdate / duration;
long currentAnimationNumber = currentUpdate / duration;
int lastStep = ((lastUpdate % duration) / ((float)duration)) * steps;
@@ -68,44 +64,29 @@ int animation_step_count(int duration, int steps)
return currentStep - lastStep + (currentAnimationNumber - lastAnimationNumber) * steps;
}
void FASTLEDLoop()
{
void FASTLEDLoop() {
lastUpdate = currentUpdate;
currentUpdate = millis();
if (currentLEDState == GENERAL)
{
for (int i = 0; i < FASTLED_NUM_LEDS; i++)
{
if (currentLEDState == GENERAL) {
for (int i = 0; i < FASTLED_NUM_LEDS; i++) {
int count = animation_step_count(blinkInterval, 2);
int step = animation_step(blinkInterval, 2);
if (count > 0)
{
if (blinkLED[i])
{
if (step == 0)
{
if (count > 0) {
if (blinkLED[i]) {
if (step == 0) {
leds[i] = ledColorBlink[i];
}
else
{
} else {
ledColorBlink[i] = leds[i];
leds[i] = CRGB::Black;
}
}
}
}
}
else if (currentLEDState == FIRE)
{
} else if (currentLEDState == FIRE) {
int count = animation_step_count(fireUpdate, 1);
if (count > 0)
{
if (count > 0) {
//random16_add_entropy( random(0)); //random() don't exists in ESP framework - workaround?
Fire2012WithPalette();
}
@@ -113,19 +94,16 @@ void FASTLEDLoop()
FastLED.show();
}
boolean FASTLEDtoMQTT()
{
boolean FASTLEDtoMQTT() {
return false;
}
# ifdef jsonReceiving
void MQTTtoFASTLED(char *topicOri, JsonObject &jsonData)
{
void MQTTtoFASTLED(char* topicOri, JsonObject& jsonData) {
currentLEDState = GENERAL;
//trc(topicOri);
//number = (long)strtol(&datacallback[1], NULL, 16);
if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled))
{
if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetled)) {
Log.trace(F("MQTTtoFASTLED JSON analysis" CR));
int ledNr = jsonData["led"];
Log.notice(F("Led numero: %d" CR), ledNr);
@@ -134,8 +112,7 @@ void MQTTtoFASTLED(char *topicOri, JsonObject &jsonData)
long number = (long)strtol(color, NULL, 16);
bool blink = jsonData["blink"];
if (ledNr <= FASTLED_NUM_LEDS)
{
if (ledNr <= FASTLED_NUM_LEDS) {
Log.notice(F("Blink: %d" CR), blink);
blinkLED[ledNr] = blink;
leds[ledNr] = number;
@@ -145,50 +122,36 @@ void MQTTtoFASTLED(char *topicOri, JsonObject &jsonData)
# endif
# ifdef simpleReceiving
void MQTTtoFASTLED(char *topicOri, char *datacallback)
{
void MQTTtoFASTLED(char* topicOri, char* datacallback) {
Log.trace(F("MQTTtoFASTLED: " CR));
currentLEDState = GENERAL;
long number = 0;
if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED))
{
if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLED)) {
number = (long)strtol(&datacallback[1], NULL, 16);
Log.notice(F("Number: %l" CR), number);
for (int i = 0; i < FASTLED_NUM_LEDS; i++)
{
for (int i = 0; i < FASTLED_NUM_LEDS; i++) {
leds[i] = number;
}
FastLED.show();
}
else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness))
{
} else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetbrightness)) {
number = (long)strtol(&datacallback[1], NULL, 16);
Log.notice(F("Number: %l" CR), number);
FastLED.setBrightness(number);
FastLED.show();
}
else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation))
{
} else if (cmpToMainTopic(topicOri, subjectMQTTtoFASTLEDsetanimation)) {
String payload = datacallback;
Log.notice(F("Datacallback: %s" CR), datacallback);
if (strstr(datacallback, "fire") != NULL)
{
if (strstr(datacallback, "fire") != NULL) {
currentLEDState = FIRE;
gPal = HeatColors_p;
}
else
{
} else {
currentLEDState = OFF;
}
}
else
{
} else {
currentLEDState = OFF;
}
if (currentLEDState == OFF)
{
for (int i = 0; i < FASTLED_NUM_LEDS; i++)
{
if (currentLEDState == OFF) {
for (int i = 0; i < FASTLED_NUM_LEDS; i++) {
leds[i] = CRGB::Black;
}
}
@@ -233,44 +196,36 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback)
# define SPARKING 120
bool gReverseDirection = false;
void Fire2012WithPalette()
{
void Fire2012WithPalette() {
// Array of temperature readings at each simulation cell
static byte heat[FASTLED_NUM_LEDS];
// Step 1. Cool down every cell a little
for (int i = 0; i < FASTLED_NUM_LEDS; i++)
{
for (int i = 0; i < FASTLED_NUM_LEDS; i++) {
heat[i] = qsub8(heat[i], random8(0, ((COOLING * 10) / FASTLED_NUM_LEDS) + 2));
}
// Step 2. Heat from each cell drifts 'up' and diffuses a little
for (int k = FASTLED_NUM_LEDS - 1; k >= 2; k--)
{
for (int k = FASTLED_NUM_LEDS - 1; k >= 2; k--) {
heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3;
}
// Step 3. Randomly ignite new 'sparks' of heat near the bottom
if (random8() < SPARKING)
{
if (random8() < SPARKING) {
int y = random8(7);
heat[y] = qadd8(heat[y], random8(160, 255));
}
// Step 4. Map from heat cells to LED colors
for (int j = 0; j < FASTLED_NUM_LEDS; j++)
{
for (int j = 0; j < FASTLED_NUM_LEDS; j++) {
// Scale the heat value from 0-255 down to 0-240
// for best results with color palettes.
byte colorindex = scale8(heat[j], 240);
CRGB color = ColorFromPalette(gPal, colorindex);
int pixelnumber;
if (gReverseDirection)
{
if (gReverseDirection) {
pixelnumber = (FASTLED_NUM_LEDS - 1) - j;
}
else
{
} else {
pixelnumber = j;
}
leds[pixelnumber] = color;
+6 -14
View File
@@ -31,24 +31,19 @@
#ifdef ZactuatorONOFF
# ifdef jsonReceiving
void MQTTtoONOFF(char *topicOri, JsonObject &ONOFFdata)
{
if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF))
{
void MQTTtoONOFF(char* topicOri, JsonObject& ONOFFdata) {
if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF)) {
Log.trace(F("MQTTtoONOFF json data analysis" CR));
int boolSWITCHTYPE = ONOFFdata["cmd"] | 99;
int pin = ONOFFdata["pin"] | ACTUATOR_ONOFF_PIN;
if (boolSWITCHTYPE != 99)
{
if (boolSWITCHTYPE != 99) {
Log.notice(F("MQTTtoONOFF boolSWITCHTYPE ok: %d" CR), boolSWITCHTYPE);
Log.notice(F("Pin number: %d" CR), pin);
pinMode(pin, OUTPUT);
digitalWrite(pin, boolSWITCHTYPE);
// we acknowledge the sending by publishing the value to an acknowledgement topic
pub(subjectGTWONOFFtoMQTT, ONOFFdata);
}
else
{
} else {
Log.error(F("MQTTtoONOFF failed json read" CR));
}
}
@@ -56,11 +51,8 @@ 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))) {
Log.trace(F("MQTTtoONOFF" CR));
int pin = strtol(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
Log.notice(F("Pin number: %d" CR), pin);
+23 -46
View File
@@ -35,13 +35,11 @@
# ifdef ZboardM5STACK
# include <M5Stack.h>
# endif
void logToLCD(bool display)
{
void logToLCD(bool display) {
display ? Log.begin(LOG_LEVEL_LCD, &M5.Lcd) : Log.begin(LOG_LEVEL, &Serial); // Log on LCD following LOG_LEVEL_LCD
}
void setBrightness(int brightness)
{
void setBrightness(int brightness) {
# ifdef ZboardM5STACK
M5.Lcd.setBrightness(brightness * 2);
# endif
@@ -50,8 +48,7 @@ void setBrightness(int brightness)
# endif
}
void setupM5()
{
void setupM5() {
Log.notice(F("Setup M5" CR));
pinMode(SLEEP_BUTTON, INPUT);
// M5 stack 320*240
@@ -82,8 +79,7 @@ void setupM5()
Log.notice(F("Setup M5 end" CR));
}
void sleepScreen()
{
void sleepScreen() {
Log.trace(F("Screen going to sleep" CR));
# ifdef ZboardM5STACK
M5.begin(false, false, false); // M5.lcd.sleep() provokes a reset of the ESP
@@ -94,8 +90,7 @@ void sleepScreen()
# endif
}
void wakeScreen(int brightness)
{
void wakeScreen(int brightness) {
Log.trace(F("Screen wake up" CR));
M5.begin();
M5.Lcd.setCursor(0, 0, (M5.Lcd.height() > 200) ? 4 : 2);
@@ -104,40 +99,34 @@ void wakeScreen(int brightness)
setBrightness(brightness);
}
void loopM5()
{
void loopM5() {
static int previousBtnState;
int currentBtnState = digitalRead(SLEEP_BUTTON);
if(currentBtnState != previousBtnState && currentBtnState == 0)
{
if (currentBtnState != previousBtnState && currentBtnState == 0) {
int newlow_power_mode = low_power_mode;
(low_power_mode == 2) ? newlow_power_mode = 0 : newlow_power_mode = newlow_power_mode + 1;
changelow_power_mode(newlow_power_mode);
}
previousBtnState = currentBtnState;
static int previousLogLevel;
switch (Log.getLastMsgLevel())
{
switch (Log.getLastMsgLevel()) {
case 1:
case 2:
if (low_power_mode != 2)
{
if (low_power_mode != 2) {
wakeScreen(NORMAL_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(TFT_RED); // FATAL, ERROR
M5.Lcd.setTextColor(TFT_BLACK, TFT_RED);
}
break;
case 3:
if (low_power_mode != 2)
{
if (low_power_mode != 2) {
wakeScreen(NORMAL_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(TFT_ORANGE); // WARNING
M5.Lcd.setTextColor(TFT_BLACK, TFT_ORANGE);
}
break;
default:
if (previousLogLevel != Log.getLastMsgLevel() && low_power_mode != 2)
{
if (previousLogLevel != Log.getLastMsgLevel() && low_power_mode != 2) {
wakeScreen(SLEEP_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(TFT_WHITE);
drawLogo(M5.Lcd.width() * 0.1875, (M5.Lcd.width() / 2) - M5.Lcd.width() * 0.24, M5.Lcd.height() * 0.5, true, true, true, true, true, true);
@@ -147,14 +136,11 @@ void loopM5()
previousLogLevel = Log.getLastMsgLevel();
}
void MQTTtoM5(char *topicOri, JsonObject &M5data)
{ // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoM5set))
{
void MQTTtoM5(char* topicOri, JsonObject& M5data) { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoM5set)) {
Log.trace(F("MQTTtoM5 json set" CR));
// Log display set between M5 lcd (true) and serial monitor (false)
if (M5data.containsKey("log-lcd"))
{
if (M5data.containsKey("log-lcd")) {
bool displayOnLCD = M5data["log-lcd"];
Log.notice(F("Set lcd log: %T" CR), displayOnLCD);
logToLCD(displayOnLCD);
@@ -162,8 +148,7 @@ void MQTTtoM5(char *topicOri, JsonObject &M5data)
}
}
void displayIntro(int i, int X, int Y)
{
void displayIntro(int i, int X, int Y) {
Log.trace(F("Intro display on screen" CR));
drawLogo(i, X, Y, false, true, false, false, false, false);
delay(50);
@@ -182,8 +167,7 @@ void displayIntro(int i, int X, int Y)
drawLogo(i, X, Y, true, true, true, true, true, false);
}
void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circle2, bool circle3, bool line1, bool line2, bool name)
{
void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circle2, bool circle3, bool line1, bool line2, bool name) {
int circle1T = logoSize / 15;
int circle2T = logoSize / 25;
int circle3T = logoSize / 30;
@@ -193,8 +177,7 @@ void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circl
int circle2X = circle1X - (logoSize * 1.05);
int circle2Y = circle1Y - (logoSize * 0.8);
if (line1)
{
if (line1) {
M5.Lcd.drawLine(circle1X - 2, circle1Y, circle2X - 2, circle2Y, BLUE);
M5.Lcd.drawLine(circle1X - 1, circle1Y, circle2X - 1, circle2Y, BLUE);
M5.Lcd.drawLine(circle1X, circle1Y, circle2X, circle2Y, BLUE);
@@ -202,8 +185,7 @@ void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circl
M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, BLUE);
M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE);
}
if (line2)
{
if (line2) {
M5.Lcd.drawLine(circle1X - 2, circle1Y, circle3X - 2, circle3Y, BLUE);
M5.Lcd.drawLine(circle1X - 1, circle1Y, circle3X - 1, circle3Y, BLUE);
M5.Lcd.drawLine(circle1X, circle1Y, circle3X, circle3Y, BLUE);
@@ -211,33 +193,28 @@ void drawLogo(int logoSize, int circle1X, int circle1Y, bool circle1, bool circl
M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE);
}
M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE);
if (circle1)
{
if (circle1) {
M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2, WHITE);
M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T, TFT_GREEN);
M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE);
}
if (circle2)
{
if (circle2) {
M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3, WHITE);
M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T, TFT_ORANGE);
M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE);
}
if (circle3)
{
if (circle3) {
M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4, WHITE);
M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T, TFT_PINK);
M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE);
}
if (name)
{
if (name) {
M5.Lcd.setTextColor(BLUE);
M5.Lcd.drawString("penMQTTGateway", circle1X + (circle1X * 0.27), circle1Y, (M5.Lcd.height() > 200) ? 4 : 2);
}
}
void M5Display(char * line1, char * line2, char * line3)
{
void M5Display(char* line1, char* line2, char* line3) {
if (low_power_mode == 2) digitalWrite(LOW_POWER_LED, 1 - LOW_POWER_LED_OFF);
wakeScreen(NORMAL_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(TFT_WHITE);
+22 -50
View File
@@ -29,8 +29,8 @@
#ifdef Zgateway2G
#include <ArduinoJson.h>
# include <A6lib.h> // library for controling A6 or A7 module
# include <ArduinoJson.h>
// Instantiate the library with TxPin, RxPin.
A6lib A6l(_2G_TX_PIN, _2G_RX_PIN); //D6 to A6 RX, D7 to A6 TX
@@ -39,16 +39,14 @@ int unreadSMSLocs[50] = {0};
int unreadSMSNum = 0;
SMSmessage sms;
void setup2G()
{
void setup2G() {
Log.notice(F("_2G_TX_PIN: %d " CR), _2G_TX_PIN);
Log.notice(F("_2G_RX_PIN: %d " CR), _2G_RX_PIN);
setupGSM(false);
Log.trace(F("Zgateway2G setup done " CR));
}
void setupGSM(bool deleteSMS)
{
void setupGSM(bool deleteSMS) {
Log.trace(F("Init 2G module: %d" CR), _2G_PWR_PIN);
delay(1000);
// Power-cycle the module to reset it.
@@ -59,40 +57,32 @@ 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) {
Log.notice(F("delete SMS OK" CR));
}
else
{
} else {
Log.error(F("delete SMS KO" CR));
}
}
}
void signalStrengthAnalysis()
{
void signalStrengthAnalysis() {
int signalStrength = 0;
signalStrength = A6l.getSignalStrength();
Log.trace(F("Signal strength: %d" CR), signalStrength);
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL)
{
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL) {
Log.trace(F("Signal too low restart the module" CR));
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);
Log.trace(F("Creating SMS buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++)
{
for (int i = 0; i < unreadSMSNum; i++) {
Log.notice(F("New message at index: %d" CR), unreadSMSNum);
sms = A6l.readSMS(unreadSMSLocs[i]);
SMSdata.set("message", (char*)sms.message.c_str());
@@ -106,39 +96,30 @@ bool _2GtoMQTT()
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)) {
Log.trace(F("MQTTto2G data analysis" CR));
// 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);
Log.notice(F("MQTTto2G phone: %s" CR), (char*)phone_number.c_str());
Log.notice(F("MQTTto2G sms: %s" CR), (char*)data.c_str());
if (A6l.sendSMS(phone_number, data) == A6_OK)
{
if (A6l.sendSMS(phone_number, data) == A6_OK) {
Log.notice(F("SMS OK" CR));
// 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
{
} else {
Log.error(F("SMS KO" CR));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, "SMS KO"); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}
else
{
} else {
Log.error(F("MQTTto2G Fail reading phone number" CR));
}
}
@@ -146,32 +127,23 @@ void MQTTto2G(char *topicOri, char *datacallback)
# endif
# ifdef jsonReceiving
void MQTTto2G(char *topicOri, JsonObject &SMSdata)
{
if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
void MQTTto2G(char* topicOri, JsonObject& SMSdata) {
if (cmpToMainTopic(topicOri, subjectMQTTto2G)) {
const char* sms = SMSdata["message"];
const char* phone = SMSdata["phone"];
Log.trace(F("MQTTto2G json data analysis" CR));
if (sms && phone)
{
if (sms && phone) {
Log.notice(F("MQTTto2G phone: %s" CR), phone);
Log.notice(F("MQTTto2G sms: %s" CR), sms);
if (A6l.sendSMS(String(phone), String(sms)) == A6_OK)
{
if (A6l.sendSMS(String(phone), String(sms)) == A6_OK) {
Log.notice(F("SMS OK" CR));
// 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
{
} else {
Log.error(F("SMS KO" CR));
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 {
Log.error(F("MQTTto2G failed json read" CR));
}
}
+107 -211
View File
@@ -34,10 +34,10 @@ Thanks to wolass https://github.com/wolass for suggesting me HM 10 and dinosd ht
# include "FreeRTOS.h"
FreeRTOS::Semaphore semaphoreCreateOrUpdateDevice = FreeRTOS::Semaphore("createOrUpdateDevice");
// Headers used for deep sleep functions
#include <esp_wifi.h>
# include <driver/adc.h>
# include <esp_bt.h>
# include <esp_bt_main.h>
#include <driver/adc.h>
# include <esp_wifi.h>
#endif
#ifdef ZgatewayBT
@@ -48,23 +48,20 @@ vector<BLEdevice> devices;
static BLEdevice NO_DEVICE_FOUND = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false, false, false};
static bool oneWhite = false;
BLEdevice* getDeviceByMac(const char* mac);
BLEdevice * getDeviceByMac(const char *mac)
{
BLEdevice* getDeviceByMac(const char* mac) {
Log.trace(F("getDeviceByMac %s" CR), mac);
for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
if ((strcmp(p->macAdr, mac) == 0))
{
for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p) {
if ((strcmp(p->macAdr, mac) == 0)) {
return &(*p);
}
}
return &NO_DEVICE_FOUND;
}
bool updateWorB(JsonObject &BTdata, bool isWhite)
{
bool updateWorB(JsonObject& BTdata, bool isWhite) {
Log.trace(F("update WorB" CR));
const char* jsonKey = isWhite ? "white-list" : "black-list";
@@ -72,8 +69,7 @@ bool updateWorB(JsonObject &BTdata, bool isWhite)
if (size == 0)
return false;
for (int i = 0; i < size; i++)
{
for (int i = 0; i < size; i++) {
const char* mac = BTdata[jsonKey][i];
createOrUpdateDevice(mac, (isWhite ? device_flags_isWhiteL : device_flags_isBlackL));
@@ -82,16 +78,14 @@ bool updateWorB(JsonObject &BTdata, bool isWhite)
return true;
}
void createOrUpdateDevice(const char *mac, uint8_t flags)
{
void createOrUpdateDevice(const char* mac, uint8_t flags) {
# ifdef ESP32
if (!semaphoreCreateOrUpdateDevice.take(30000, "createOrUpdateDevice"))
return;
# endif
BLEdevice* device = getDeviceByMac(mac);
if(device == &NO_DEVICE_FOUND)
{
if (device == &NO_DEVICE_FOUND) {
Log.trace(F("add %s" CR), mac);
//new device
device = new BLEdevice();
@@ -100,18 +94,14 @@ void createOrUpdateDevice(const char *mac, uint8_t flags)
device->isWhtL = flags & device_flags_isWhiteL;
device->isBlkL = flags & device_flags_isBlackL;
devices.push_back(*device);
}
else
{
} else {
Log.trace(F("update %s" CR), mac);
if(flags & device_flags_isDisc)
{
if (flags & device_flags_isDisc) {
device->isDisc = true;
}
if(flags & device_flags_isWhiteL || flags & device_flags_isBlackL)
{
if (flags & device_flags_isWhiteL || flags & device_flags_isBlackL) {
device->isWhtL = flags & device_flags_isWhiteL;
device->isBlkL = flags & device_flags_isBlackL;
}
@@ -129,10 +119,8 @@ void createOrUpdateDevice(const char *mac, uint8_t flags)
# define isBlack(device) device->isBlkL
# define isDiscovered(device) device->isDisc
void dumpDevices()
{
for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p)
{
void dumpDevices() {
for (vector<BLEdevice>::iterator p = devices.begin(); p != devices.end(); ++p) {
Log.trace(F("macAdr %s" CR), p->macAdr);
Log.trace(F("isDisc %d" CR), p->isDisc);
Log.trace(F("isWhtL %d" CR), p->isWhtL);
@@ -140,15 +128,13 @@ void dumpDevices()
}
}
void strupp(char *beg)
{
void strupp(char* beg) {
while (*beg = toupper(*beg))
++beg;
}
# ifdef ZmqttDiscovery
void MiFloraDiscovery(char *mac)
{
void MiFloraDiscovery(char* mac) {
# define MiFloraparametersCount 4
Log.trace(F("MiFloraDiscovery" CR));
char* MiFlorasensor[MiFloraparametersCount][8] = {
@@ -163,8 +149,7 @@ void MiFloraDiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void VegTrugDiscovery(char *mac)
{
void VegTrugDiscovery(char* mac) {
# define VegTrugparametersCount 4
Log.trace(F("VegTrugDiscovery" CR));
char* VegTrugsensor[VegTrugparametersCount][8] = {
@@ -179,8 +164,7 @@ void VegTrugDiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void MiJiaDiscovery(char *mac)
{
void MiJiaDiscovery(char* mac) {
# define MiJiaparametersCount 3
Log.trace(F("MiJiaDiscovery" CR));
char* MiJiasensor[MiJiaparametersCount][8] = {
@@ -194,8 +178,7 @@ void MiJiaDiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void LYWSD02Discovery(char *mac)
{
void LYWSD02Discovery(char* mac) {
# define LYWSD02parametersCount 3
Log.trace(F("LYWSD02Discovery" CR));
char* LYWSD02sensor[LYWSD02parametersCount][8] = {
@@ -209,8 +192,7 @@ void LYWSD02Discovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void CLEARGRASSTRHDiscovery(char *mac)
{
void CLEARGRASSTRHDiscovery(char* mac) {
# define CLEARGRASSTRHparametersCount 3
Log.trace(F("CLEARGRASSTRHDiscovery" CR));
char* CLEARGRASSTRHsensor[CLEARGRASSTRHparametersCount][8] = {
@@ -224,8 +206,7 @@ void CLEARGRASSTRHDiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void CLEARGRASSCGD1Discovery(char *mac)
{
void CLEARGRASSCGD1Discovery(char* mac) {
# define CLEARGRASSCGD1parametersCount 3
Log.trace(F("CLEARGRASSCGD1Discovery" CR));
char* CLEARGRASSCGD1sensor[CLEARGRASSCGD1parametersCount][8] = {
@@ -239,8 +220,7 @@ void CLEARGRASSCGD1Discovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void CLEARGRASSTRHKPADiscovery(char *mac)
{
void CLEARGRASSTRHKPADiscovery(char* mac) {
# define CLEARGRASSTRHKPAparametersCount 3
Log.trace(F("CLEARGRASSTRHKPADiscovery" CR));
char* CLEARGRASSTRHKPAsensor[CLEARGRASSTRHKPAparametersCount][8] = {
@@ -254,8 +234,7 @@ void CLEARGRASSTRHKPADiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void MiScaleDiscovery(char *mac)
{
void MiScaleDiscovery(char* mac) {
# define MiScaleparametersCount 1
Log.trace(F("MiScaleDiscovery" CR));
char* MiScalesensor[MiScaleparametersCount][8] = {
@@ -267,8 +246,7 @@ void MiScaleDiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void MiLampDiscovery(char *mac)
{
void MiLampDiscovery(char* mac) {
# define MiLampparametersCount 1
Log.trace(F("MiLampDiscovery" CR));
char* MiLampsensor[MiLampparametersCount][8] = {
@@ -280,8 +258,7 @@ void MiLampDiscovery(char *mac)
createOrUpdateDevice(mac, device_flags_isDisc);
}
void MiBandDiscovery(char *mac)
{
void MiBandDiscovery(char* mac) {
# define MiBandparametersCount 1
Log.trace(F("MiBandDiscovery" CR));
char* MiBandsensor[MiBandparametersCount][8] = {
@@ -312,20 +289,19 @@ void MiBandDiscovery(char *mac){}
*/
// core task implementation thanks to https://techtutorialsx.com/2017/05/09/esp32-running-code-on-a-specific-core/
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
# include <BLEAdvertisedDevice.h>
#include "soc/timer_group_struct.h"
# include <BLEDevice.h>
# include <BLEScan.h>
# include <BLEUtils.h>
# include "soc/timer_group_reg.h"
# include "soc/timer_group_struct.h"
//core on which the BLE detection task will run
static int taskCore = 0;
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
{
void onResult(BLEAdvertisedDevice advertisedDevice)
{
class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Log.trace(F("Creating BLE buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& BLEdata = jsonBuffer.createObject();
@@ -339,13 +315,11 @@ class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
Log.notice(F("Device detected: %s" CR), mac);
BLEdevice* device = getDeviceByMac(mac);
if ((!oneWhite || isWhite(device)) && !isBlack(device))
{ //if not black listed mac we go AND if we have no white mac or this mac is white we go out
if ((!oneWhite || isWhite(device)) && !isBlack(device)) { //if not black listed mac we go AND if we have no white mac or this mac is white we go out
if (advertisedDevice.haveName())
BLEdata.set("name", (char*)advertisedDevice.getName().c_str());
# if pubBLEManufacturerData
if (advertisedDevice.haveManufacturerData())
{
if (advertisedDevice.haveManufacturerData()) {
char* manufacturerdata = BLEUtils::buildHexData(NULL, (uint8_t*)advertisedDevice.getManufacturerData().data(), advertisedDevice.getManufacturerData().length());
Log.trace(F("Manufacturer Data: %s" CR), manufacturerdata);
BLEdata.set("manufacturerdata", manufacturerdata);
@@ -359,20 +333,16 @@ class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
if (advertisedDevice.haveRSSI())
haRoomPresence(BLEdata); // this device has an rssi in consequence we can use it for home assistant room presence component
# endif
if (advertisedDevice.haveServiceData())
{
if (advertisedDevice.haveServiceData()) {
int serviceDataCount = advertisedDevice.getServiceDataCount();
Log.trace(F("Get services data number: %d" CR), serviceDataCount);
for (int j = 0; j < serviceDataCount; j++)
{
for (int j = 0; j < serviceDataCount; j++) {
std::string serviceData = advertisedDevice.getServiceData(j);
int serviceDataLength = serviceData.length();
String returnedString = "";
for (int i = 0; i < serviceDataLength; i++)
{
for (int i = 0; i < serviceDataLength; i++) {
int a = serviceData[i];
if (a < 16)
{
if (a < 16) {
returnedString = returnedString + "0";
}
returnedString = returnedString + String(a, HEX);
@@ -387,21 +357,16 @@ class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
BLEdata.set("servicedatauuid", (char*)serviceDatauuid.c_str());
PublishDeviceData(BLEdata);
}
}
else
{
} else {
PublishDeviceData(BLEdata); // publish device even if there is no service data
}
}
else
{
} else {
Log.trace(F("Filtered mac device" CR));
}
}
};
void BLEscan()
{
void BLEscan() {
TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed = 1;
TIMERG0.wdt_wprotect = 0;
@@ -416,27 +381,21 @@ void BLEscan()
esp_bt_controller_deinit();
}
void coreTask(void *pvParameters)
{
while (true)
{
void coreTask(void* pvParameters) {
while (true) {
Log.trace(F("BT Task running on core: %d" CR), xPortGetCoreID());
if (!low_power_mode)
delay(BLEinterval);
int n = 0;
while (client.state() != 0 && n <= TimeBeforeMQTTconnect)
{
while (client.state() != 0 && n <= TimeBeforeMQTTconnect) {
n++;
Log.trace(F("Wait for MQTT on core: %d attempt: %d" CR), xPortGetCoreID(), n);
delay(1000);
}
if(client.state() != 0 )
{
if (client.state() != 0) {
Log.warning(F("MQTT client disconnected no BLE scan" CR));
delay(1000);
}
else
{
} else {
pinMode(LOW_POWER_LED, OUTPUT);
if (low_power_mode == 2)
digitalWrite(LOW_POWER_LED, 1 - LOW_POWER_LED_OFF);
@@ -456,8 +415,7 @@ void lowPowerESP32() // low power mode
deepSleep(BLEinterval * 1000);
}
void deepSleep(uint64_t time_in_us)
{
void deepSleep(uint64_t time_in_us) {
# if defined(ZboardM5STACK) || defined(ZboardM5STICKC)
sleepScreen();
esp_sleep_enable_ext0_wakeup((gpio_num_t)SLEEP_BUTTON, LOW);
@@ -475,12 +433,10 @@ void deepSleep(uint64_t time_in_us)
esp_deep_sleep(time_in_us);
}
void changelow_power_mode(int newLowPowerMode)
{
void changelow_power_mode(int newLowPowerMode) {
Log.notice(F("Changing LOW POWER mode to: %d" CR), newLowPowerMode);
# if defined(ZboardM5STACK) || defined(ZboardM5STICKC)
if (low_power_mode == 2)
{
if (low_power_mode == 2) {
# ifdef ZboardM5STACK
M5.Lcd.wakeup();
# endif
@@ -499,8 +455,7 @@ void changelow_power_mode(int newLowPowerMode)
preferences.end();
}
void setupBT()
{
void setupBT() {
Log.notice(F("BLEinterval: %d" CR), BLEinterval);
Log.notice(F("Minrssi: %d" CR), Minrssi);
Log.notice(F("Low Power Mode: %d" CR), low_power_mode);
@@ -517,8 +472,7 @@ void setupBT()
Log.trace(F("ZgatewayBT multicore ESP32 setup done " CR));
}
bool BTtoMQTT()
{ // for on demand BLE scans
bool BTtoMQTT() { // for on demand BLE scans
BLEscan();
}
# else // arduino or ESP8266 working with HM10/11
@@ -534,8 +488,7 @@ unsigned long timebt = 0;
// this struct define which parts of the hexadecimal chain we extract and what to do with these parts
struct decompose d[6] = {{"mac", 16, 12, true}, {"typ", 28, 2, false}, {"rsi", 30, 2, false}, {"rdl", 32, 2, false}, {"sty", 44, 4, true}, {"rda", 56, 60, false}};
void setupBT()
{
void setupBT() {
BLEinterval = TimeBtw_Read;
Minrssi = MinimumRSSI;
Log.notice(F("BLEinterval: %d" CR), BLEinterval);
@@ -554,31 +507,25 @@ void setupBT()
Log.trace(F("ZgatewayBT HM1X setup done " CR));
}
bool BTtoMQTT()
{
bool BTtoMQTT() {
//extract serial data from module in hexa format
while (softserial.available() > 0)
{
while (softserial.available() > 0) {
int a = softserial.read();
if (a < 16)
{
if (a < 16) {
returnedString = returnedString + "0";
}
returnedString = returnedString + String(a, HEX);
}
if (millis() > (timebt + BLEinterval))
{ //retrieving data
if (millis() > (timebt + BLEinterval)) { //retrieving data
timebt = millis();
# if defined(ESP8266)
yield();
# endif
if (returnedString != "")
{
if (returnedString != "") {
Log.verbose(F("returnedString: %s" CR), (char*)returnedString.c_str());
size_t pos = 0;
while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1)
{
while ((pos = returnedString.lastIndexOf(BLEdelimiter)) != -1) {
# if defined(ESP8266)
yield();
# endif
@@ -587,10 +534,8 @@ bool BTtoMQTT()
char token_char[token.length() + 1];
token.toCharArray(token_char, token.length() + 1);
Log.trace(F("Token: %s" CR), token_char);
if (token.length() > 60)
{ // we extract data only if we have infos (BLEdelimiter length + 4)
for (int i = 0; i < 6; i++)
{
if (token.length() > 60) { // we extract data only if we have infos (BLEdelimiter length + 4)
for (int i = 0; i < 6; i++) {
extract_char(token_char, d[i].extract, d[i].start, d[i].len, d[i].reverse, false);
if (i == 3)
d[5].len = (int)strtol(d[i].extract, NULL, 16) * 2; // extracting the length of the rest data
@@ -611,8 +556,7 @@ bool BTtoMQTT()
return false; //if we have at least one white mac and this mac is not white we go out
# ifdef subjectHomePresence
String HomePresenceId;
for (int i = 0; i < 12; i++)
{
for (int i = 0; i < 12; i++) {
HomePresenceId += String(d[0].extract[i]);
if (((i - 1) % 2 == 0) && (i != 11))
HomePresenceId += ":";
@@ -636,24 +580,20 @@ bool BTtoMQTT()
}
softserial.print(F(QUESTION_MSG));
return false;
}
else
{
} else {
return false;
}
}
# endif
void RemoveJsonPropertyIf(JsonObject &obj, char* key, bool condition)
{
void RemoveJsonPropertyIf(JsonObject& obj, char* key, bool condition) {
if (condition) {
Log.trace(F("Removing %s" CR), key);
obj.remove(key);
}
}
double value_from_service_data(const char *service_data, int offset, int data_length)
{
double value_from_service_data(const char* service_data, int offset, int data_length) {
char rev_data[data_length + 1];
char data[data_length + 1];
memcpy(rev_data, &service_data[offset], data_length);
@@ -668,8 +608,7 @@ double value_from_service_data(const char *service_data, int offset, int data_le
return value;
}
boolean valid_service_data(const char * data)
{
boolean valid_service_data(const char* data) {
int size = strlen(data);
for (int i = 0; i < size; ++i) {
if (data[i] != 48) // 48 correspond to 0 in ASCII table
@@ -680,8 +619,7 @@ boolean valid_service_data(const char * data)
void launch_discovery(JsonObject& BLEdata, char* mac) {
BLEdevice* device = getDeviceByMac(mac);
if (!isDiscovered(device) && BLEdata.containsKey("model"))
{
if (!isDiscovered(device) && BLEdata.containsKey("model")) {
Log.trace(F("Launching discovery of %s" CR), mac);
if (strcmp(BLEdata["model"].as<const char*>(), "HHCCJCY01HHCC") == 0) MiFloraDiscovery(mac);
if (strcmp(BLEdata["model"].as<const char*>(), "VegTrug") == 0) VegTrugDiscovery(mac);
@@ -694,17 +632,13 @@ void launch_discovery(JsonObject &BLEdata, char * mac){
if (strcmp(BLEdata["model"].as<const char*>(), "MiBand") == 0) MiBandDiscovery(mac);
if (strcmp(BLEdata["model"].as<const char*>(), "XMTZC04HM") == 0 ||
strcmp(BLEdata["model"].as<const char*>(), "XMTZC05HM") == 0) MiScaleDiscovery(mac);
}
else
{
} else {
Log.trace(F("Device already discovered or model not detected" CR));
}
}
void PublishDeviceData(JsonObject &BLEdata)
{
if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi))
{ // process only the devices close enough
void PublishDeviceData(JsonObject& BLEdata) {
if (abs((int)BLEdata["rssi"] | 0) < abs(Minrssi)) { // process only the devices close enough
JsonObject& BLEdataOut = process_bledata(BLEdata);
String mac_adress = BLEdataOut["id"].as<const char*>();
mac_adress.replace(":", "");
@@ -722,126 +656,107 @@ void PublishDeviceData(JsonObject &BLEdata)
String mactopic(mac);
mactopic = subjectBTtoMQTT + String("/") + mactopic;
pub((char*)mactopic.c_str(), BLEdataOut);
}
else
{
} else {
Log.trace(F("Low rssi, device filtered" CR));
}
}
JsonObject& process_bledata(JsonObject& BLEdata) {
if(BLEdata.containsKey("servicedata"))
{
if (BLEdata.containsKey("servicedata")) {
Log.trace(F("Checking BLE service data validity" CR));
const char* service_data = (const char*)(BLEdata["servicedata"] | "");
if(valid_service_data(service_data))
{
if (valid_service_data(service_data)) {
Log.trace(F("Searching BLE device data %s size %d" CR), service_data, strlen(service_data));
Log.trace(F("Is it a mi flora ?" CR));
if (strstr(service_data, "209800") != NULL)
{
if (strstr(service_data, "209800") != NULL) {
Log.trace(F("mi flora data reading" CR));
BLEdata.set("model", "HHCCJCY01HHCC");
return process_sensors(2, BLEdata);
}
Log.trace(F("Is it a vegtrug ?" CR));
if (strstr(service_data, "20bc03") != NULL && strlen(service_data) > ServicedataMinLength)
{
if (strstr(service_data, "20bc03") != NULL && strlen(service_data) > ServicedataMinLength) {
Log.trace(F("vegtrug data reading" CR));
BLEdata.set("model", "VegTrug");
return process_sensors(2, BLEdata);
}
Log.trace(F("Is it a LYWSDCGQ?" CR));
if (strstr(service_data, "20aa01") != NULL && strlen(service_data) > ServicedataMinLength)
{
if (strstr(service_data, "20aa01") != NULL && strlen(service_data) > ServicedataMinLength) {
Log.trace(F("LYWSDCGQ data reading" CR));
BLEdata.set("model", "LYWSDCGQ");
return process_sensors(0, BLEdata);
}
Log.trace(F("Is it a LYWSD02?" CR));
if (strstr(service_data, "205b04") != NULL && strlen(service_data) > ServicedataMinLength)
{
if (strstr(service_data, "205b04") != NULL && strlen(service_data) > ServicedataMinLength) {
Log.trace(F("LYWSD02 data reading" CR));
BLEdata.set("model", "LYWSD02");
return process_sensors(2, BLEdata);
}
Log.trace(F("Is it a CGG1?" CR));
if (strstr(service_data, "304703") != NULL && strlen(service_data) > ServicedataMinLength)
{
if (strstr(service_data, "304703") != NULL && strlen(service_data) > ServicedataMinLength) {
Log.trace(F("CGG1 data reading method 1" CR));
BLEdata.set("model", "CGG1");
return process_sensors(0, BLEdata);
}
Log.trace(F("Is it a MUE4094RT?" CR));
if (strstr(service_data, "4030dd") != NULL)
{
if (strstr(service_data, "4030dd") != NULL) {
Log.trace(F("MUE4094RT data reading" CR));
BLEdata.set("model", "MUE4094RT");
return process_milamp(BLEdata);
}
Log.trace(F("Is it a CGP1W?" CR));
if (strstr(service_data, "08094c") != NULL && strlen(service_data) > ServicedataMinLength)
{
if (strstr(service_data, "08094c") != NULL && strlen(service_data) > ServicedataMinLength) {
Log.trace(F("CGP1W data reading" CR));
BLEdata.set("model", "CGP1W");
return process_cleargrass(BLEdata, true);
}
Log.trace(F("Is it a CGG1" CR));
if (strstr(service_data, "080774") != NULL)
{
if (strstr(service_data, "080774") != NULL) {
Log.trace(F("CGG1 method 2" CR));
BLEdata.set("model", "CGG1");
// no discovery as it is already available with method 1
return process_cleargrass(BLEdata, false);
}
Log.trace(F("Is it a CGD1?" CR));
if ((strstr(service_data, "080caf") != NULL || strstr(service_data, "080c09") != NULL)
&& (strlen(service_data) > ServicedataMinLength))
{
if ((strstr(service_data, "080caf") != NULL || strstr(service_data, "080c09") != NULL) && (strlen(service_data) > ServicedataMinLength)) {
Log.trace(F("CGD1 data reading" CR));
BLEdata.set("model", "CGD1");
return process_cleargrass(BLEdata, false);
}
if(BLEdata.containsKey("servicedatauuid"))
{
if (BLEdata.containsKey("servicedatauuid")) {
const char* service_datauuid = (const char*)(BLEdata["servicedatauuid"] | "");
Log.trace(F("servicedatauuid %s" CR), service_datauuid);
Log.trace(F("Is it a MiBand?" CR));
if (strstr(service_datauuid, "fee0") != NULL)
{
if (strstr(service_datauuid, "fee0") != NULL) {
Log.trace(F("Mi Band data reading" CR));
BLEdata.set("model", "MiBand");
return process_miband(BLEdata);
}
Log.trace(F("Is it a XMTZC04HM?" CR));
if (strstr(service_datauuid, "181d") != NULL)
{
if (strstr(service_datauuid, "181d") != NULL) {
Log.trace(F("XMTZC04HM data reading" CR));
BLEdata.set("model", "XMTZC04HM");
return process_scale_v1(BLEdata);
}
Log.trace(F("Is it a XMTZC05HM?" CR));
if (strstr(service_datauuid, "181b") != NULL)
{
if (strstr(service_datauuid, "181b") != NULL) {
Log.trace(F("XMTZC05HM data reading" CR));
BLEdata.set("model", "XMTZC05HM");;
BLEdata.set("model", "XMTZC05HM");
;
return process_scale_v2(BLEdata);
}
}
}
else
{
} else {
Log.trace(F("Non valid service data, removing it" CR));
BLEdata.remove("servicedata");
}
@@ -855,13 +770,11 @@ JsonObject& process_bledata(JsonObject &BLEdata){
return BLEdata;
}
JsonObject& process_sensors(int offset, JsonObject &BLEdata)
{
JsonObject& process_sensors(int offset, JsonObject& BLEdata) {
const char* servicedata = BLEdata["servicedata"].as<const char*>();
int data_length = 0;
switch (servicedata[27 + offset])
{
switch (servicedata[27 + offset]) {
case '1':
case '2':
case '3':
@@ -880,8 +793,7 @@ JsonObject& process_sensors(int offset, JsonObject &BLEdata)
// Mi flora provides tem(perature), (earth) moi(sture), fer(tility) and lux (illuminance)
// Mi Jia provides tem(perature), batt(erry) and hum(idity)
// following the value of digit 23 + offset we determine the type of data we get from the sensor
switch (servicedata[23 + offset])
{
switch (servicedata[23 + offset]) {
case '9':
BLEdata.set("fer", (double)value);
break;
@@ -915,8 +827,7 @@ JsonObject& process_sensors(int offset, JsonObject &BLEdata)
return BLEdata;
}
JsonObject& process_scale_v1(JsonObject &BLEdata)
{
JsonObject& process_scale_v1(JsonObject& BLEdata) {
const char* servicedata = BLEdata["servicedata"].as<const char*>();
double weight = value_from_service_data(servicedata, 2, 4) / 200;
@@ -927,8 +838,7 @@ JsonObject& process_scale_v1(JsonObject &BLEdata)
return BLEdata;
}
JsonObject& process_scale_v2(JsonObject &BLEdata)
{
JsonObject& process_scale_v2(JsonObject& BLEdata) {
const char* servicedata = BLEdata["servicedata"].as<const char*>();
double weight = value_from_service_data(servicedata, 22, 4) / 200;
@@ -941,8 +851,7 @@ JsonObject& process_scale_v2(JsonObject &BLEdata)
return BLEdata;
}
JsonObject& process_miband(JsonObject &BLEdata)
{
JsonObject& process_miband(JsonObject& BLEdata) {
const char* servicedata = BLEdata["servicedata"].as<const char*>();
double steps = value_from_service_data(servicedata, 0, 4);
@@ -953,8 +862,7 @@ JsonObject& process_miband(JsonObject &BLEdata)
return BLEdata;
}
JsonObject& process_milamp(JsonObject &BLEdata)
{
JsonObject& process_milamp(JsonObject& BLEdata) {
const char* servicedata = BLEdata["servicedata"].as<const char*>();
long darkness = value_from_service_data(servicedata, 8, 2);
@@ -966,8 +874,7 @@ JsonObject& process_milamp(JsonObject &BLEdata)
return BLEdata;
}
JsonObject& process_cleargrass(JsonObject &BLEdata, boolean air)
{
JsonObject& process_cleargrass(JsonObject& BLEdata, boolean air) {
const char* servicedata = BLEdata["servicedata"].as<const char*>();
double value = 9999;
@@ -977,8 +884,7 @@ JsonObject& process_cleargrass(JsonObject &BLEdata, boolean air)
// temperature
value = value_from_service_data(servicedata, 24, 4);
BLEdata.set("hum", (double)value / 10);
if (air)
{
if (air) {
// air pressure
value = value_from_service_data(servicedata, 32, 4);
BLEdata.set("pres", (double)value / 100);
@@ -988,8 +894,7 @@ JsonObject& process_cleargrass(JsonObject &BLEdata, boolean air)
}
# ifdef subjectHomePresence
void haRoomPresence(JsonObject &HomePresence)
{
void haRoomPresence(JsonObject& HomePresence) {
int BLErssi = HomePresence["rssi"];
Log.trace(F("BLErssi %d" CR), BLErssi);
int txPower = HomePresence["txpower"] | 0;
@@ -998,12 +903,9 @@ void haRoomPresence(JsonObject &HomePresence)
Log.trace(F("TxPower: %d" CR), txPower);
double ratio = BLErssi * 1.0 / txPower;
double distance;
if (ratio < 1.0)
{
if (ratio < 1.0) {
distance = pow(ratio, 10);
}
else
{
} else {
distance = (0.89976) * pow(ratio, 7.7095) + 0.111;
}
HomePresence["distance"] = distance;
@@ -1013,10 +915,8 @@ void haRoomPresence(JsonObject &HomePresence)
}
# endif
void MQTTtoBT(char *topicOri, JsonObject &BTdata)
{ // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoBTset))
{
void MQTTtoBT(char* topicOri, JsonObject& BTdata) { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoBTset)) {
Log.trace(F("MQTTtoBT json set" CR));
// Black list & white list set
@@ -1028,8 +928,7 @@ void MQTTtoBT(char *topicOri, JsonObject &BTdata)
dumpDevices();
// Scan interval set
if (BTdata.containsKey("interval"))
{
if (BTdata.containsKey("interval")) {
Log.trace(F("BLE interval setup" CR));
// storing BLE interval for further use if needed
unsigned int prevBLEinterval = BLEinterval;
@@ -1037,16 +936,14 @@ void MQTTtoBT(char *topicOri, JsonObject &BTdata)
// set BLE interval if present if not setting default value
BLEinterval = (unsigned int)BTdata["interval"];
Log.notice(F("New interval: %d ms" CR), BLEinterval);
if (BLEinterval == 0)
{
if (BLEinterval == 0) {
if (BTtoMQTT()) // as BLEinterval is = to 0 we can launch the loop and the scan will execute immediately
Log.trace(F("Scan done" CR));
BLEinterval = prevBLEinterval; // as 0 was just used as a command we recover previous scan duration
}
}
// MinRSSI set
if (BTdata.containsKey("minrssi"))
{
if (BTdata.containsKey("minrssi")) {
// storing Min RSSI for further use if needed
Log.trace(F("Previous Minrssi: %d" CR), Minrssi);
// set Min RSSI if present if not setting default value
@@ -1054,8 +951,7 @@ void MQTTtoBT(char *topicOri, JsonObject &BTdata)
Log.notice(F("New Minrssi: %d" CR), Minrssi);
}
# ifdef ESP32
if (BTdata.containsKey("low_power_mode"))
{
if (BTdata.containsKey("low_power_mode")) {
changelow_power_mode((int)BTdata["low_power_mode"]);
}
# endif
+96 -197
View File
@@ -30,9 +30,9 @@
#ifdef ZgatewayIR
# if defined(ESP8266) || defined(ESP32)
# include <IRrecv.h> // Needed if you want to receive IR commands.
# include <IRremoteESP8266.h>
# include <IRsend.h> // Needed if you want to send IR commands.
#include <IRrecv.h> // Needed if you want to receive IR commands.
# include <IRutils.h>
# ifdef DumpMode // in dump mode we increase the size of the buffer to catch big codes
IRrecv irrecv(IR_RECEIVER_PIN, 1024, 15U, true);
@@ -94,8 +94,7 @@ uint64_t getUInt64fromHex(char const *str) {
return result;
}
void setupIR()
{
void setupIR() {
//IR init parameters
# if defined(ESP8266) || defined(ESP32)
irsend.begin();
@@ -108,12 +107,10 @@ void setupIR()
Log.trace(F("ZgatewayIR setup done " CR));
}
void IRtoMQTT()
{
void IRtoMQTT() {
decode_results results;
if (irrecv.decode(&results))
{
if (irrecv.decode(&results)) {
Log.trace(F("Creating IR buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& IRdata = jsonBuffer.createObject();
@@ -134,8 +131,7 @@ void IRtoMQTT()
# endif
String rawCode = "";
// Dump data
for (uint16_t i = 1; i < results.rawlen; i++)
{
for (uint16_t i = 1; i < results.rawlen; i++) {
# if defined(ESP8266) || defined(ESP32)
if (i % 100 == 0)
yield(); // Preemptive yield every 100th entry to feed the WDT.
@@ -152,14 +148,12 @@ void IRtoMQTT()
# ifdef RawDirectForward
# if defined(ESP8266) || defined(ESP32)
uint16_t rawsend[results.rawlen];
for (uint16_t i = 1; i < results.rawlen; i++)
{
for (uint16_t i = 1; i < results.rawlen; i++) {
if (i % 100 == 0)
yield(); // Preemptive yield every 100th entry to feed the WDT.
# else
unsigned int rawsend[results.rawlen];
for (int i = 1; i < results.rawlen; i++)
{
for (int i = 1; i < results.rawlen; i++) {
# endif
rawsend[i] = results.rawbuf[i];
}
@@ -169,18 +163,14 @@ void IRtoMQTT()
irrecv.resume(); // Receive the next value
unsigned long long MQTTvalue = IRdata.get<unsigned long long>("value");
//trc(MQTTvalue);
if ((pubIRunknownPrtcl == false && IRdata.get<int>("protocol") == -1))
{ // don't publish unknown IR protocol
if ((pubIRunknownPrtcl == false && IRdata.get<int>("protocol") == -1)) { // don't publish unknown IR protocol
Log.notice(F("--no pub unknwn prt--" CR));
}
else if (!isAduplicate(MQTTvalue) && MQTTvalue != 0)
{ // conditions to avoid duplications of IR -->MQTT
} else if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of IR -->MQTT
Log.trace(F("Adv data IRtoMQTT" CR));
pub(subjectIRtoMQTT, IRdata);
Log.trace(F("Store val: %D" CR), MQTTvalue);
storeValue(MQTTvalue);
if (repeatIRwMQTT)
{
if (repeatIRwMQTT) {
Log.trace(F("Pub. IR for rpt" CR));
pubMQTT(subjectMQTTtoIR, MQTTvalue);
}
@@ -189,11 +179,8 @@ void IRtoMQTT()
}
# ifdef jsonReceiving
void MQTTtoIR(char *topicOri, JsonObject &IRdata)
{
if (cmpToMainTopic(topicOri, subjectMQTTtoIR))
{
void MQTTtoIR(char* topicOri, JsonObject& IRdata) {
if (cmpToMainTopic(topicOri, subjectMQTTtoIR)) {
Log.trace(F("MQTTtoIR json" CR));
uint64_t data = IRdata["value"];
const char* raw = IRdata["raw"];
@@ -202,43 +189,35 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata)
Log.trace(F("hex: %s" CR), hex);
data = getUInt64fromHex(hex);
}
if (data != 0 || raw)
{
if (data != 0 || raw) {
Log.trace(F("MQTTtoIR value || raw detected" CR));
bool signalSent = false;
const char* protocol_name = IRdata["protocol_name"];
unsigned int valueBITS = IRdata["bits"] | 0;
uint16_t valueRPT = IRdata["repeat"] | repeatIRwNumber;
if (raw)
{
if (raw) {
Log.trace(F("Raw: %s" CR), raw);
unsigned int s = strlen(raw);
//number of "," value count
int count = 0;
for (int i = 0; i < s; i++)
{
if (raw[i] == ',')
{
for (int i = 0; i < s; i++) {
if (raw[i] == ',') {
count++;
}
}
# ifdef IR_GC
if (strcmp(protocol_name, "GC") == 1)
{ // sending GC data from https://irdb.globalcache.com
if (strcmp(protocol_name, "GC") == 1) { // sending GC data from https://irdb.globalcache.com
Log.trace(F("GC" CR));
//buffer allocation from char datacallback
uint16_t GC[count + 1];
String value = "";
int j = 0;
for (int i = 0; i < s; i++)
{
if (raw[i] != ',')
{
for (int i = 0; i < s; i++) {
if (raw[i] != ',') {
value = value + String(raw[i]);
}
if ((raw[i] == ',') || (i == s - 1))
{
if ((raw[i] == ',') || (i == s - 1)) {
GC[j] = value.toInt();
value = "";
j++;
@@ -249,8 +228,7 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata)
}
# endif
# ifdef IR_RAW
if (strcmp(protocol_name, "Raw") == 1)
{ // sending Raw data
if (strcmp(protocol_name, "Raw") == 1) { // sending Raw data
Log.trace(F("Raw" CR));
//buffer allocation from char datacallback
# if defined(ESP8266) || defined(ESP32)
@@ -260,14 +238,11 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata)
# endif
String value = "";
int j = 0;
for (int i = 0; i < s; i++)
{
if (raw[i] != ',')
{
for (int i = 0; i < s; i++) {
if (raw[i] != ',') {
value = value + String(raw[i]);
}
if ((raw[i] == ',') || (i == s - 1))
{
if ((raw[i] == ',') || (i == s - 1)) {
Raw[j] = value.toInt();
value = "";
j++;
@@ -277,14 +252,10 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata)
signalSent = true;
}
# endif
}
else if (protocol_name && (strcmp(protocol_name, "NEC") != 1))
{
} else if (protocol_name && (strcmp(protocol_name, "NEC") != 1)) {
Log.trace(F("Using Identified Protocol: %s bits: %d repeat: %d" CR), protocol_name, valueBITS, valueRPT);
signalSent = sendIdentifiedProtocol(protocol_name, data, hex, valueBITS, valueRPT);
}
else
{
} else {
Log.trace(F("Using NEC protocol" CR));
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
@@ -297,27 +268,21 @@ void MQTTtoIR(char *topicOri, JsonObject &IRdata)
# endif
signalSent = true;
}
if (signalSent)
{ // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
if (signalSent) { // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
Log.notice(F("MQTTtoIR OK" CR));
pub(subjectGTWIRtoMQTT, IRdata);
}
irrecv.enableIRIn(); // ReStart the IR receiver (if not restarted it is not able to receive data)
}
else
{
} else {
Log.error(F("MQTTtoIR failed json read" CR));
}
}
}
# endif
bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data, const char *hex, unsigned int valueBITS, uint16_t valueRPT)
{
bool sendIdentifiedProtocol(const char* protocol_name, unsigned long long data, const char* hex, unsigned int valueBITS, uint16_t valueRPT) {
uint8_t dataarray[valueBITS];
if(hex)
{
if (hex) {
const char* ptr = NULL;
(strstr(hex, "0x") != NULL) ? ptr = hex += 2 : ptr = hex;
for (int i = 0; i < sizeof dataarray / sizeof *dataarray; i++) {
@@ -329,8 +294,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
}
# ifdef IR_WHYNTER
if (strcmp(protocol_name, "WHYNTER") == 1)
{
if (strcmp(protocol_name, "WHYNTER") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = WHYNTER_BITS;
@@ -344,8 +308,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_LG
if (strcmp(protocol_name, "LG") == 1)
{
if (strcmp(protocol_name, "LG") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = LG_BITS;
@@ -359,8 +322,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SONY
if (strcmp(protocol_name, "SONY") == 1)
{
if (strcmp(protocol_name, "SONY") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = SONY_12_BITS;
@@ -374,8 +336,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DISH
if (strcmp(protocol_name, "DISH") == 1)
{
if (strcmp(protocol_name, "DISH") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = DISH_BITS;
@@ -389,8 +350,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_RC5
if (strcmp(protocol_name, "RC5") == 1)
{
if (strcmp(protocol_name, "RC5") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = RC5_BITS;
@@ -404,8 +364,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_RC6
if (strcmp(protocol_name, "RC6") == 1)
{
if (strcmp(protocol_name, "RC6") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = RC6_MODE0_BITS;
@@ -419,8 +378,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SHARP
if (strcmp(protocol_name, "SHARP") == 1)
{
if (strcmp(protocol_name, "SHARP") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = SHARP_BITS;
@@ -434,8 +392,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SAMSUNG
if (strcmp(protocol_name, "SAMSUNG") == 1)
{
if (strcmp(protocol_name, "SAMSUNG") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = SAMSUNG_BITS;
@@ -449,8 +406,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_JVC
if (strcmp(protocol_name, "JVC") == 1)
{
if (strcmp(protocol_name, "JVC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = JVC_BITS;
@@ -464,8 +420,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_PANASONIC
if (strcmp(protocol_name, "PANASONIC") == 1)
{
if (strcmp(protocol_name, "PANASONIC") == 1) {
# if defined(ESP8266) || defined(ESP32)
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
@@ -481,8 +436,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
# if defined(ESP8266) || defined(ESP32)
# ifdef IR_COOLIX
if (strcmp(protocol_name, "COOLIX") == 1)
{
if (strcmp(protocol_name, "COOLIX") == 1) {
Log.trace(F("Sending %s:" CR), protocol_name);
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
@@ -494,8 +448,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_RCMM
if (strcmp(protocol_name, "RCMM") == 1)
{
if (strcmp(protocol_name, "RCMM") == 1) {
Log.trace(F("Sending %s:" CR), protocol_name);
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
@@ -505,8 +458,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DENON
if (strcmp(protocol_name, "DENON") == 1)
{
if (strcmp(protocol_name, "DENON") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = DENON_BITS;
@@ -515,8 +467,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_GICABLE
if (strcmp(protocol_name, "GICABLE") == 1)
{
if (strcmp(protocol_name, "GICABLE") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kGicableBits;
@@ -527,8 +478,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SHERWOOD
if (strcmp(protocol_name, "SHERWOOD") == 1)
{
if (strcmp(protocol_name, "SHERWOOD") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kSherwoodBits;
@@ -539,8 +489,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHI
if (strcmp(protocol_name, "MITSUBISHI") == 1)
{
if (strcmp(protocol_name, "MITSUBISHI") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishiBits;
@@ -551,8 +500,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_NIKAI
if (strcmp(protocol_name, "NIKAI") == 1)
{
if (strcmp(protocol_name, "NIKAI") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kNikaiBits;
@@ -561,8 +509,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MIDEA
if (strcmp(protocol_name, "MIDEA") == 1)
{
if (strcmp(protocol_name, "MIDEA") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMideaBits;
@@ -573,8 +520,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MAGIQUEST
if (strcmp(protocol_name, "MAGIQUEST") == 1)
{
if (strcmp(protocol_name, "MAGIQUEST") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMagiquestBits;
@@ -583,8 +529,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_LASERTAG
if (strcmp(protocol_name, "LASERTAG") == 1)
{
if (strcmp(protocol_name, "LASERTAG") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kLasertagBits;
@@ -595,8 +540,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_CARRIER_AC
if (strcmp(protocol_name, "CARRIER_AC") == 1)
{
if (strcmp(protocol_name, "CARRIER_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kCarrierAcBits;
@@ -607,8 +551,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHI2
if (strcmp(protocol_name, "MITSUBISHI2") == 1)
{
if (strcmp(protocol_name, "MITSUBISHI2") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishiBits;
@@ -619,8 +562,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_AIWA_RC_T501
if (strcmp(protocol_name, "AIWA_RC_T501") == 1)
{
if (strcmp(protocol_name, "AIWA_RC_T501") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kAiwaRcT501Bits;
@@ -631,8 +573,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DAIKIN
if (strcmp(protocol_name, "DAIKIN") == 1)
{
if (strcmp(protocol_name, "DAIKIN") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikinStateLength;
@@ -643,8 +584,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_KELVINATOR
if (strcmp(protocol_name, "KELVINATOR") == 1)
{
if (strcmp(protocol_name, "KELVINATOR") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kKelvinatorStateLength;
@@ -655,8 +595,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHI_AC
if (strcmp(protocol_name, "MITSUBISHI_AC") == 1)
{
if (strcmp(protocol_name, "MITSUBISHI_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishiACStateLength;
@@ -667,8 +606,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SANYO
if (strcmp(protocol_name, "SANYOLC7461") == 1)
{
if (strcmp(protocol_name, "SANYOLC7461") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kSanyoLC7461Bits;
@@ -677,8 +615,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_GREE
if (strcmp(protocol_name, "GREE") == 1)
{
if (strcmp(protocol_name, "GREE") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kGreeStateLength;
@@ -689,8 +626,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_ARGO
if (strcmp(protocol_name, "ARGO") == 1)
{
if (strcmp(protocol_name, "ARGO") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kArgoStateLength;
@@ -701,8 +637,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_TROTEC
if (strcmp(protocol_name, "TROTEC") == 1)
{
if (strcmp(protocol_name, "TROTEC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kTrotecStateLength;
@@ -713,8 +648,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_TOSHIBA_AC
if (strcmp(protocol_name, "TOSHIBA_AC") == 1)
{
if (strcmp(protocol_name, "TOSHIBA_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kToshibaACBits;
@@ -725,8 +659,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_FUJITSU_AC
if (strcmp(protocol_name, "FUJITSU_AC") == 1)
{
if (strcmp(protocol_name, "FUJITSU_AC") == 1) {
if (valueRPT == repeatIRwNumber)
valueRPT = std::max(valueRPT, kFujitsuAcMinRepeat);
irsend.sendFujitsuAC(dataarray, valueBITS, valueRPT);
@@ -734,8 +667,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_HAIER_AC
if (strcmp(protocol_name, "HAIER_AC") == 1)
{
if (strcmp(protocol_name, "HAIER_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kHaierACStateLength;
@@ -746,8 +678,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_HITACHI_AC
if (strcmp(protocol_name, "HITACHI_AC") == 1)
{
if (strcmp(protocol_name, "HITACHI_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kHitachiAcStateLength;
@@ -758,8 +689,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_HITACHI_AC1
if (strcmp(protocol_name, "HITACHI_AC1") == 1)
{
if (strcmp(protocol_name, "HITACHI_AC1") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kHitachiAc1StateLength;
@@ -770,8 +700,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_HITACHI_AC2
if (strcmp(protocol_name, "HITACHI_AC2") == 1)
{
if (strcmp(protocol_name, "HITACHI_AC2") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kHitachiAc2StateLength;
@@ -782,8 +711,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_HAIER_AC_YRW02
if (strcmp(protocol_name, "HAIER_AC_YRW02") == 1)
{
if (strcmp(protocol_name, "HAIER_AC_YRW02") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kHaierACYRW02StateLength;
@@ -794,8 +722,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_WHIRLPOOL_AC
if (strcmp(protocol_name, "WHIRLPOOL_AC") == 1)
{
if (strcmp(protocol_name, "WHIRLPOOL_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kWhirlpoolAcStateLength;
@@ -806,8 +733,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SAMSUNG_AC
if (strcmp(protocol_name, "SAMSUNG_AC") == 1)
{
if (strcmp(protocol_name, "SAMSUNG_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kSamsungAcStateLength;
@@ -818,8 +744,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_LUTRON
if (strcmp(protocol_name, "LUTRON") == 1)
{
if (strcmp(protocol_name, "LUTRON") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kLutronBits;
@@ -828,8 +753,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_ELECTRA_AC
if (strcmp(protocol_name, "ELECTRA_AC") == 1)
{
if (strcmp(protocol_name, "ELECTRA_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kElectraAcStateLength;
@@ -838,8 +762,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_PANASONIC_AC
if (strcmp(protocol_name, "PANASONIC_AC") == 1)
{
if (strcmp(protocol_name, "PANASONIC_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kPanasonicAcStateLength;
@@ -850,8 +773,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_PIONEER
if (strcmp(protocol_name, "PIONEER") == 1)
{
if (strcmp(protocol_name, "PIONEER") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kPioneerBits;
@@ -860,8 +782,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_LG2
if (strcmp(protocol_name, "LG2") == 1)
{
if (strcmp(protocol_name, "LG2") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kLgBits;
@@ -870,15 +791,13 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MWM
if (strcmp(protocol_name, "MWM") == 1)
{
if (strcmp(protocol_name, "MWM") == 1) {
irsend.sendMWM(dataarray, valueBITS, valueRPT);
return true;
}
# endif
# ifdef IR_DAIKIN2
if (strcmp(protocol_name, "DAIKIN2") == 1)
{
if (strcmp(protocol_name, "DAIKIN2") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikin2StateLength;
@@ -889,8 +808,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_VESTEL_AC
if (strcmp(protocol_name, "VESTEL_AC") == 1)
{
if (strcmp(protocol_name, "VESTEL_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kVestelAcBits;
@@ -899,8 +817,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SAMSUNG36
if (strcmp(protocol_name, "SAMSUNG36") == 1)
{
if (strcmp(protocol_name, "SAMSUNG36") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kSamsung36Bits;
@@ -909,8 +826,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_TCL112AC
if (strcmp(protocol_name, "TCL112AC") == 1)
{
if (strcmp(protocol_name, "TCL112AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kTcl112AcStateLength;
@@ -921,8 +837,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_TECO
if (strcmp(protocol_name, "TECO") == 1)
{
if (strcmp(protocol_name, "TECO") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kTecoBits;
@@ -931,8 +846,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_LEGOPF
if (strcmp(protocol_name, "LEGOPF") == 1)
{
if (strcmp(protocol_name, "LEGOPF") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kLegoPfBits;
@@ -943,8 +857,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHIHEAVY88
if (strcmp(protocol_name, "MITSUBISHIHEAVY88") == 1)
{
if (strcmp(protocol_name, "MITSUBISHIHEAVY88") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishiHeavy88StateLength;
@@ -955,8 +868,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHIHEAVY152
if (strcmp(protocol_name, "MITSUBISHIHEAVY152") == 1)
{
if (strcmp(protocol_name, "MITSUBISHIHEAVY152") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishiHeavy152StateLength;
@@ -967,8 +879,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DAIKIN216
if (strcmp(protocol_name, "DAIKIN216") == 1)
{
if (strcmp(protocol_name, "DAIKIN216") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikin216StateLength;
@@ -979,8 +890,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_SHARP_AC
if (strcmp(protocol_name, "SHARP_AC") == 1)
{
if (strcmp(protocol_name, "SHARP_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kSharpAcStateLength;
@@ -991,8 +901,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_GOODWEATHER
if (strcmp(protocol_name, "GOODWEATHER_AC") == 1)
{
if (strcmp(protocol_name, "GOODWEATHER_AC") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kGoodweatherBits;
@@ -1003,8 +912,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_INAX
if (strcmp(protocol_name, "INAX") == 1)
{
if (strcmp(protocol_name, "INAX") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kInaxBits;
@@ -1015,8 +923,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DAIKIN160
if (strcmp(protocol_name, "DAIKIN160") == 1)
{
if (strcmp(protocol_name, "DAIKIN160") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikin160StateLength;
@@ -1027,8 +934,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_NEOCLIMA
if (strcmp(protocol_name, "NEOCLIMA") == 1)
{
if (strcmp(protocol_name, "NEOCLIMA") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kNeoclimaStateLength;
@@ -1039,8 +945,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DAIKIN176
if (strcmp(protocol_name, "DAIKIN176") == 1)
{
if (strcmp(protocol_name, "DAIKIN176") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikin176StateLength;
@@ -1051,8 +956,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DAIKIN128
if (strcmp(protocol_name, "DAIKIN128") == 1)
{
if (strcmp(protocol_name, "DAIKIN128") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikin128StateLength;
@@ -1063,8 +967,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_AMCOR
if (strcmp(protocol_name, "AMCOR") == 1)
{
if (strcmp(protocol_name, "AMCOR") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kAmcorStateLength;
@@ -1075,8 +978,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_DAIKIN152
if (strcmp(protocol_name, "DAIKIN152") == 1)
{
if (strcmp(protocol_name, "DAIKIN152") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kDaikin152StateLength;
@@ -1087,8 +989,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHI136
if (strcmp(protocol_name, "MITSUBISHI136") == 1)
{
if (strcmp(protocol_name, "MITSUBISHI136") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishi136StateLength;
@@ -1099,8 +1000,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_MITSUBISHI112
if (strcmp(protocol_name, "MITSUBISHI112") == 1)
{
if (strcmp(protocol_name, "MITSUBISHI112") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
valueBITS = kMitsubishi112StateLength;
@@ -1111,8 +1011,7 @@ bool sendIdentifiedProtocol(const char *protocol_name, unsigned long long data,
}
# endif
# ifdef IR_HITACHI_AC424
if (strcmp(protocol_name, "HITACHI_AC424") == 1)
{
if (strcmp(protocol_name, "HITACHI_AC424") == 1) {
Log.notice(F("Sending IR signal with %s"), protocol_name);
Log.notice(F("Sending IR signal with %s"), protocol_name);
if (valueBITS == 0)
+13 -26
View File
@@ -29,17 +29,15 @@
#ifdef ZgatewayLORA
#include <SPI.h>
# include <LoRa.h>
# include <SPI.h>
# include <Wire.h>
void setupLORA()
{
void setupLORA() {
SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_SS);
LoRa.setPins(LORA_SS, LORA_RST, LORA_DI0);
if (!LoRa.begin(LORA_BAND))
{
if (!LoRa.begin(LORA_BAND)) {
Log.error(F("ZgatewayLORA setup failed!" CR));
while (1)
;
@@ -54,11 +52,9 @@ void setupLORA()
Log.trace(F("ZgatewayLORA setup done" CR));
}
void LORAtoMQTT()
{
void LORAtoMQTT() {
int packetSize = LoRa.parsePacket();
if (packetSize)
{
if (packetSize) {
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& LORAdata = jsonBuffer.createObject();
Log.trace(F("Rcv. LORA" CR));
@@ -69,8 +65,7 @@ void LORAtoMQTT()
# endif
String packet;
packet = "";
for (int i = 0; i < packetSize; i++)
{
for (int i = 0; i < packetSize; i++) {
packet += (char)LoRa.read();
}
LORAdata.set("rssi", (int)LoRa.packetRssi());
@@ -79,8 +74,7 @@ void LORAtoMQTT()
LORAdata.set("packetSize", (int)packetSize);
LORAdata.set("message", (char*)packet.c_str());
pub(subjectLORAtoMQTT, LORAdata);
if (repeatLORAwMQTT)
{
if (repeatLORAwMQTT) {
Log.trace(F("Pub LORA for rpt" CR));
pub(subjectMQTTtoLORA, LORAdata);
}
@@ -88,10 +82,8 @@ void LORAtoMQTT()
}
# 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)) {
Log.trace(F("MQTTtoLORA json" CR));
const char* message = LORAdata["message"];
int txPower = LORAdata["txpower"] | LORA_TX_POWER;
@@ -102,8 +94,7 @@ void MQTTtoLORA(char *topicOri, JsonObject &LORAdata)
int preambleLength = LORAdata["preamblelength"] | LORA_PREAMBLE_LENGTH;
byte syncWord = LORAdata["syncword"] | LORA_SYNC_WORD;
bool Crc = LORAdata["enablecrc"] | DEFAULT_CRC;
if (message)
{
if (message) {
LoRa.setTxPower(txPower);
LoRa.setFrequency(frequency);
LoRa.setSpreadingFactor(spreadingFactor);
@@ -118,19 +109,15 @@ void MQTTtoLORA(char *topicOri, JsonObject &LORAdata)
LoRa.endPacket();
Log.trace(F("MQTTtoLORA OK" CR));
pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
else
{
} else {
Log.error(F("MQTTtoLORA Fail json" CR));
}
}
}
# 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();
+16 -36
View File
@@ -37,10 +37,8 @@
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)
{
size_t repeats, const String& deviceID) {
if (status == VALID) {
Log.trace(F("Creating RF PiLight buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& RFPiLightdata = jsonBuffer.createObject();
@@ -52,16 +50,14 @@ void pilightCallback(const String &protocol, const String &message, int status,
RFPiLightdata.set("repeats", (int)repeats);
RFPiLightdata.set("status", (int)status);
pub(subjectPilighttoMQTT, RFPiLightdata);
if (repeatPilightwMQTT)
{
if (repeatPilightwMQTT) {
Log.trace(F("Pub Pilight for rpt" CR));
pub(subjectMQTTtoPilight, RFPiLightdata);
}
}
}
void setupPilight()
{
void setupPilight() {
# ifndef ZgatewayRF&& ZgatewayRF2 //receiving with Pilight is not compatible with ZgatewayRF or RF2 or RF315 as far as I can tell
# ifdef ZradioCC1101 //receiving with CC1101
ELECHOUSE_cc1101.Init();
@@ -80,43 +76,35 @@ void setupPilight()
# endif
}
void PilighttoMQTT()
{
void PilighttoMQTT() {
rf.loop();
}
void MQTTtoPilight(char *topicOri, JsonObject &Pilightdata)
{
void MQTTtoPilight(char* topicOri, JsonObject& Pilightdata) {
# ifdef ZradioCC1101
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
rf.disableReceiver();
# endif
int result = 0;
if (cmpToMainTopic(topicOri, subjectMQTTtoPilight))
{
if (cmpToMainTopic(topicOri, subjectMQTTtoPilight)) {
Log.trace(F("MQTTtoPilight json data analysis" CR));
const char* message = Pilightdata["message"];
const char* protocol = Pilightdata["protocol"];
const char* raw = Pilightdata["raw"];
if (raw)
{
if (raw) {
int msgLength = 0;
uint16_t codes[MAXPULSESTREAMLENGTH];
msgLength = rf.stringToPulseTrain(
raw,
codes, MAXPULSESTREAMLENGTH);
if (msgLength > 0)
{
if (msgLength > 0) {
rf.sendPulseTrain(codes, msgLength);
Log.notice(F("MQTTtoPilight raw ok" CR));
result = msgLength;
}
else
{
} else {
Log.trace(F("MQTTtoPilight raw KO" CR));
switch (result)
{
switch (result) {
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C:
Log.trace(F("'c' not found in string, or has no data" CR));
break;
@@ -131,26 +119,18 @@ void MQTTtoPilight(char *topicOri, JsonObject &Pilightdata)
break;
}
}
}
else if (message && protocol)
{
} else if (message && protocol) {
Log.trace(F("MQTTtoPilight msg & protocol ok" CR));
result = rf.send(protocol, message);
}
else
{
} else {
Log.error(F("MQTTtoPilight failed json read" CR));
}
if (result > 0)
{
if (result > 0) {
Log.trace(F("Adv data MQTTtoPilight push state via PilighttoMQTT" CR));
pub(subjectGTWPilighttoMQTT, Pilightdata);
}
else
{
switch (result)
{
} else {
switch (result) {
case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL:
Log.error(F("protocol is not available" CR));
break;
+16 -37
View File
@@ -38,8 +38,7 @@
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);
Log.trace(F("switchRFDiscovery" CR));
@@ -55,9 +54,7 @@ void RFtoMQTTdiscovery(unsigned long MQTTvalue)
}
# endif
void setupRF()
{
void setupRF() {
//RF init parameters
Log.notice(F("RF_EMITTER_PIN: %d " CR), RF_EMITTER_PIN);
Log.notice(F("RF_RECEIVER_PIN: %d " CR), RF_RECEIVER_PIN);
@@ -72,11 +69,8 @@ void setupRF()
Log.trace(F("ZgatewayRF setup done" CR));
}
void RFtoMQTT()
{
if (mySwitch.available())
{
void RFtoMQTT() {
if (mySwitch.available()) {
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
@@ -91,16 +85,14 @@ void RFtoMQTT()
mySwitch.resetAvailable();
unsigned long MQTTvalue = RFdata.get<unsigned long>("value");
if (!isAduplicate(MQTTvalue) && MQTTvalue != 0)
{ // conditions to avoid duplications of RF -->MQTT
if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of RF -->MQTT
# ifdef ZmqttDiscovery //component creation for HA
RFtoMQTTdiscovery(MQTTvalue);
# endif
pub(subjectRFtoMQTT, RFdata);
Log.trace(F("Store val: %lu" CR), MQTTvalue);
storeValue(MQTTvalue);
if (repeatRFwMQTT)
{
if (repeatRFwMQTT) {
Log.trace(F("Pub RF for rpt" CR));
pub(subjectMQTTtoRF, RFdata);
}
@@ -109,9 +101,7 @@ void RFtoMQTT()
}
# ifdef simpleReceiving
void MQTTtoRF(char *topicOri, char *datacallback)
{
void MQTTtoRF(char* topicOri, char* datacallback) {
# ifdef ZradioCC1101 // set Receive off and Transmitt on
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY);
mySwitch.disableReceive();
@@ -126,35 +116,29 @@ 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();
}
//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();
}
int pos3 = topic.lastIndexOf(RFbitsKey);
if (pos3 != -1)
{
if (pos3 != -1) {
pos3 = pos3 + strlen(RFbitsKey);
valueBITS = (topic.substring(pos3, pos3 + 2)).toInt();
}
if ((cmpToMainTopic(topicOri, subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0))
{
if ((cmpToMainTopic(topicOri, subjectMQTTtoRF)) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)) {
Log.trace(F("MQTTtoRF dflt" CR));
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)) {
Log.trace(F("MQTTtoRF usr par." CR));
if (valuePRT == 0)
valuePRT = 1;
@@ -179,19 +163,16 @@ void MQTTtoRF(char *topicOri, char *datacallback)
# endif
# ifdef jsonReceiving
void MQTTtoRF(char *topicOri, JsonObject &RFdata)
{ // json object decoding
void MQTTtoRF(char* topicOri, JsonObject& RFdata) { // json object decoding
# ifdef ZradioCC1101 // set Receive off and Transmitt on
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY);
mySwitch.disableReceive();
mySwitch.enableTransmit(RF_EMITTER_PIN);
# endif
if (cmpToMainTopic(topicOri, subjectMQTTtoRF))
{
if (cmpToMainTopic(topicOri, subjectMQTTtoRF)) {
Log.trace(F("MQTTtoRF json" CR));
unsigned long data = RFdata["value"];
if (data != 0)
{
if (data != 0) {
int valuePRT = RFdata["protocol"] | 1;
int valuePLSL = RFdata["delay"] | 350;
int valueBITS = RFdata["length"] | 24;
@@ -205,9 +186,7 @@ void MQTTtoRF(char *topicOri, JsonObject &RFdata)
Log.notice(F("MQTTtoRF OK" CR));
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 {
Log.error(F("MQTTtoRF Fail json" CR));
}
}
+32 -73
View File
@@ -41,11 +41,10 @@ sudo mosquitto_pub -t home/commands/MQTTtoRF2/CODE_8233372/UNIT_0/PERIOD_272 -m/
# include <ELECHOUSE_CC1101_SRC_DRV.h>
# endif
#include <NewRemoteTransmitter.h>
# include <NewRemoteReceiver.h>
# include <NewRemoteTransmitter.h>
struct RF2rxd
{
struct RF2rxd {
unsigned int period;
unsigned long address;
unsigned long groupBit;
@@ -56,8 +55,7 @@ struct RF2rxd
RF2rxd rf2rd;
void setupRF2()
{
void setupRF2() {
# ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF
# ifdef ZradioCC1101 //receiving with CC1101
ELECHOUSE_cc1101.Init();
@@ -73,11 +71,8 @@ void setupRF2()
digitalWrite(RF_EMITTER_PIN, LOW);
}
void RF2toMQTT()
{
if (rf2rd.hasNewData)
{
void RF2toMQTT() {
if (rf2rd.hasNewData) {
Log.trace(F("Creating RF2 buffer" CR));
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
@@ -96,9 +91,7 @@ void RF2toMQTT()
}
}
void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType)
{
void rf2Callback(unsigned int period, unsigned long address, unsigned long groupBit, unsigned long unit, unsigned long switchType) {
rf2rd.period = period;
rf2rd.address = address;
rf2rd.groupBit = groupBit;
@@ -108,8 +101,7 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
}
# ifdef simpleReceiving
void MQTTtoRF2(char *topicOri, char *datacallback)
{
void MQTTtoRF2(char* topicOri, char* datacallback) {
# ifdef ZradioCC1101
NewRemoteReceiver::disable();
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
@@ -129,43 +121,37 @@ void MQTTtoRF2(char *topicOri, char *datacallback)
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();
Log.notice(F("RF2 code: %l" CR), valueCODE);
}
int pos2 = topic.lastIndexOf(RF2periodKey);
if (pos2 != -1)
{
if (pos2 != -1) {
pos2 = pos2 + strlen(RF2periodKey);
valuePERIOD = (topic.substring(pos2, pos2 + 3)).toInt();
Log.notice(F("RF2 Period: %d" CR), valuePERIOD);
}
int pos3 = topic.lastIndexOf(RF2unitKey);
if (pos3 != -1)
{
if (pos3 != -1) {
pos3 = pos3 + strlen(RF2unitKey);
valueUNIT = (topic.substring(pos3, topic.indexOf("/", pos3))).toInt();
Log.notice(F("Unit: %d" CR), valueUNIT);
}
int pos4 = topic.lastIndexOf(RF2groupKey);
if (pos4 != -1)
{
if (pos4 != -1) {
pos4 = pos4 + strlen(RF2groupKey);
valueGROUP = (topic.substring(pos4, pos4 + 1)).toInt();
Log.notice(F("RF2 Group: %d" CR), valueGROUP);
}
int pos5 = topic.lastIndexOf(RF2dimKey);
if (pos5 != -1)
{
if (pos5 != -1) {
isDimCommand = true;
valueDIM = atoi(datacallback);
Log.notice(F("RF2 Dim: %d" CR), valueDIM);
}
if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0))
{
if ((topic == subjectMQTTtoRF2) || (valueCODE != 0) || (valueUNIT != -1) || (valuePERIOD != 0)) {
Log.trace(F("MQTTtoRF2" CR));
if (valueCODE == 0)
valueCODE = 8233378;
@@ -177,25 +163,16 @@ void MQTTtoRF2(char *topicOri, char *datacallback)
Log.trace(F("Creating transmitter" CR));
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
Log.trace(F("Sending data" CR));
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);
}
}
@@ -218,13 +195,10 @@ void MQTTtoRF2(char *topicOri, char *datacallback)
MQTTdimLevel = String(valueDIM);
String MQTTRF2string;
Log.trace(F("Adv data MQTTtoRF2 push state via RF2toMQTT" CR));
if (isDimCommand)
{
if (isDimCommand) {
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2dimKey + String("/") + RF2periodKey + MQTTperiod;
pub((char*)MQTTRF2string.c_str(), (char*)MQTTdimLevel.c_str());
}
else
{
} else {
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod;
pub((char*)MQTTRF2string.c_str(), (char*)MQTTswitchType.c_str());
}
@@ -237,19 +211,16 @@ void MQTTtoRF2(char *topicOri, char *datacallback)
# endif
# ifdef jsonReceiving
void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
{ // json object decoding
void MQTTtoRF2(char* topicOri, JsonObject& RF2data) { // json object decoding
# ifdef ZradioCC1101
NewRemoteReceiver::disable();
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
# endif
if (cmpToMainTopic(topicOri, subjectMQTTtoRF2))
{
if (cmpToMainTopic(topicOri, subjectMQTTtoRF2)) {
Log.trace(F("MQTTtoRF2 json" CR));
int boolSWITCHTYPE = RF2data["switchType"] | 99;
if (boolSWITCHTYPE != 99)
{
if (boolSWITCHTYPE != 99) {
Log.trace(F("MQTTtoRF2 switch type ok" CR));
bool isDimCommand = boolSWITCHTYPE == 2;
unsigned long valueCODE = RF2data["address"];
@@ -257,8 +228,7 @@ void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
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)) {
Log.trace(F("MQTTtoRF2" CR));
if (valueCODE == 0)
valueCODE = 8233378;
@@ -269,25 +239,16 @@ void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
NewRemoteReceiver::disable();
NewRemoteTransmitter transmitter(valueCODE, RF_EMITTER_PIN, valuePERIOD);
Log.trace(F("Sending" CR));
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);
}
}
@@ -297,9 +258,7 @@ void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
// Publish state change back to MQTT
pub(subjectGTWRF2toMQTT, RF2data);
}
}
else
{
} else {
Log.error(F("MQTTtoRF2 failed json read" CR));
}
}
+26 -57
View File
@@ -32,16 +32,15 @@
#ifdef ZgatewayRFM69
# include <EEPROM.h>
# include <RFM69.h> //https://www.github.com/lowpowerlab/rfm69
# include <SPI.h>
#include <EEPROM.h>
char RadioConfig[128];
// vvvvvvvvv Global Configuration vvvvvvvvvvv
struct _GLOBAL_CONFIG
{
struct _GLOBAL_CONFIG {
uint32_t checksum;
char rfmapname[32];
char encryptkey[16 + 1];
@@ -58,26 +57,22 @@ struct _GLOBAL_CONFIG
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) {
Log.trace(F("Factory reset" CR));
memset(pGC, 0, sizeof(*pGC));
strcpy_P(pGC->encryptkey, ENCRYPTKEY);
@@ -94,8 +89,7 @@ void eeprom_setup()
RFM69 radio;
void setupRFM69(void)
{
void setupRFM69(void) {
# if defined(ESP8266) || defined(ESP32)
eeprom_setup();
# endif
@@ -107,13 +101,11 @@ void setupRFM69(void)
radio = RFM69(RFM69_CS, RFM69_IRQ, GC_IS_RFM69HCW, RFM69_IRQN);
// Initialize radio
if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid))
{
if (!radio.initialize(pGC->rfmfrequency, pGC->nodeid, pGC->networkid)) {
Log.error(F("ZgatewayRFM69 initialization failed" CR));
}
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)
@@ -121,8 +113,7 @@ void setupRFM69(void)
if (pGC->encryptkey[0] != '\0')
radio.encrypt(pGC->encryptkey);
switch (pGC->rfmfrequency)
{
switch (pGC->rfmfrequency) {
case RF69_433MHZ:
freq = 433;
break;
@@ -143,17 +134,14 @@ 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)) {
Log.trace(F("\n\n*** RFM69 config truncated ***\n" CR));
}
}
bool RFM69toMQTT(void)
{
bool RFM69toMQTT(void) {
//check if something was received (could be an interrupt from the radio)
if (radio.receiveDone())
{
if (radio.receiveDone()) {
Log.trace(F("Creating RFM69 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& RFM69data = jsonBuffer.createObject();
@@ -168,8 +156,7 @@ bool RFM69toMQTT(void)
// Ack as soon as possible
//check if sender wanted an ACK
if (radio.ACKRequested())
{
if (radio.ACKRequested()) {
radio.sendACK();
}
//updateClients(senderId, rssi, (const char *)data);
@@ -184,19 +171,14 @@ bool RFM69toMQTT(void)
pub(buff, RFM69data);
return true;
}
else
{
} else {
return false;
}
}
# ifdef simpleReceiving
void MQTTtoRFM69(char *topicOri, char *datacallback)
{
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
void MQTTtoRFM69(char* topicOri, char* datacallback) {
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) {
Log.trace(F("MQTTtoRFM69 data analysis" CR));
char data[RF69_MAX_DATA_LEN + 1];
memcpy(data, (void*)datacallback, RF69_MAX_DATA_LEN);
@@ -206,53 +188,40 @@ void MQTTtoRFM69(char *topicOri, char *datacallback)
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();
Log.notice(F("RFM69 receiver ID: %d" CR), valueRCV);
}
if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
{
if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) {
Log.notice(F(" OK " CR));
// Acknowledgement to the GTWRF topic
char buff[sizeof(subjectGTWRFM69toMQTT) + 4];
sprintf(buff, "%s/%d", subjectGTWRFM69toMQTT, radio.SENDERID);
pub(buff, data);
}
else
{
} else {
Log.error(F("RFM69 sending failed" CR));
}
}
}
# endif
# ifdef jsonReceiving
void MQTTtoRFM69(char *topicOri, JsonObject &RFM69data)
{
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
void MQTTtoRFM69(char* topicOri, JsonObject& RFM69data) {
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69)) {
const char* data = RFM69data["data"];
Log.trace(F("MQTTtoRFM69 json data analysis" CR));
if (data)
{
if (data) {
Log.trace(F("MQTTtoRFM69 data ok" CR));
int valueRCV = RFM69data["receiverid"] | defaultRFM69ReceiverId; //default receiver id value
Log.notice(F("RFM69 receiver ID: %d" CR), valueRCV);
if (radio.sendWithRetry(valueRCV, data, strlen(data), 10))
{
if (radio.sendWithRetry(valueRCV, data, strlen(data), 10)) {
Log.notice(F(" OK " CR));
// 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
{
} else {
Log.error(F("MQTTtoRFM69 sending failed" CR));
}
}
else
{
} else {
Log.error(F("MQTTtoRFM69 failed json read" CR));
}
}
+35 -81
View File
@@ -35,19 +35,16 @@
unsigned char _uartbuf[RF_MESSAGE_SIZE + 3] = {0};
unsigned char _uartpos = 0;
void setupSRFB()
{
void setupSRFB() {
Log.trace(F("ZgatewaySRFB setup done " CR));
Log.trace(F("Serial Baud: %l" CR), 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);
@@ -55,17 +52,13 @@ 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);
Log.notice(F("[RFBRIDGE] Sending MESSAGE" CR));
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);
@@ -74,30 +67,21 @@ void _rfbSend(byte *message, int times)
}
}
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;
}
@@ -105,9 +89,7 @@ bool SRFBtoMQTT()
return receiving;
}
void _rfbDecode()
{
void _rfbDecode() {
static unsigned long last = 0;
if (millis() - last < RF_RECEIVE_DELAY)
return;
@@ -116,8 +98,7 @@ void _rfbDecode()
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);
Log.trace(F("Creating SRFB buffer" CR));
@@ -145,14 +126,12 @@ void _rfbDecode()
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
Log.trace(F("Adv data SRFBtoMQTT" CR));
pub(subjectSRFBtoMQTT, SRFBdata);
Log.trace(F("Store val: %lu" CR), MQTTvalue);
storeValue(MQTTvalue);
if (repeatSRFBwMQTT)
{
if (repeatSRFBwMQTT) {
Log.trace(F("Publish SRFB for rpt" CR));
pub(subjectMQTTtoSRFB, SRFBdata);
}
@@ -161,8 +140,7 @@ void _rfbDecode()
}
}
void _rfbAck()
{
void _rfbAck() {
Log.trace(F("[RFBRIDGE] Sending ACK\n" CR));
Serial.println();
Serial.write(RF_CODE_START);
@@ -175,13 +153,11 @@ void _rfbAck()
/*
From an hexa char array ("A220EE...") to a byte array (half the size)
*/
bool _rfbToArray(const char *in, byte *out)
{
bool _rfbToArray(const char* in, byte* out) {
if (strlen(in) != RF_MESSAGE_SIZE * 2)
return false;
char tmp[3] = {0};
for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++)
{
for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++) {
memcpy(tmp, &in[p * 2], 2);
out[p] = strtol(tmp, NULL, 16);
}
@@ -191,57 +167,47 @@ 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++)
{
bool _rfbToChar(byte* in, char* out) {
for (unsigned char p = 0; p < RF_MESSAGE_SIZE; p++) {
sprintf_P(&out[p * 2], PSTR("%02X" CR), 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();
Log.notice(F("SRFB Repeat: %d" CR), valueRPT);
}
int pos2 = topic.lastIndexOf(SRFBminipulselengthKey);
if (pos2 != -1)
{
if (pos2 != -1) {
pos2 = pos2 + strlen(SRFBminipulselengthKey);
valueMiniPLSL = (topic.substring(pos2, pos2 + 3)).toInt();
Log.notice(F("RF Mini Pulse Lgth: %d" CR), valueMiniPLSL);
}
int pos3 = topic.lastIndexOf(SRFBmaxipulselengthKey);
if (pos3 != -1)
{
if (pos3 != -1) {
pos3 = pos3 + strlen(SRFBmaxipulselengthKey);
valueMaxiPLSL = (topic.substring(pos3, pos3 + 2)).toInt();
Log.notice(F("RF Maxi Pulse Lgth: %d" CR), valueMaxiPLSL);
}
int pos4 = topic.lastIndexOf(SRFBsyncKey);
if (pos4 != -1)
{
if (pos4 != -1) {
pos4 = pos4 + strlen(SRFBsyncKey);
valueSYNC = (topic.substring(pos4, pos4 + 2)).toInt();
Log.notice(F("RF sync: %d" CR), valueSYNC);
@@ -286,12 +252,9 @@ void MQTTtoSRFB(char *topicOri, char *datacallback)
// Acknowledgement to the GTWRF topic
pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
if (topic == subjectMQTTtoSRFBRaw)
{
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();
Log.notice(F("SRFB Repeat: %d" CR), valueRPT);
@@ -308,27 +271,20 @@ void MQTTtoSRFB(char *topicOri, char *datacallback)
}
# 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))
{
if (cmpToMainTopic(topicOri, subjectMQTTtoSRFB)) {
Log.trace(F("MQTTtoSRFB json" CR));
if (raw)
{ // send raw in priority when defined in the json
if (raw) { // send raw in priority when defined in the json
Log.trace(F("MQTTtoSRFB raw ok" CR));
byte message_b[RF_MESSAGE_SIZE];
_rfbToArray(raw, message_b);
_rfbSend(message_b, valueRPT);
}
else
{
} else {
unsigned long data = SRFBdata["value"];
if (data != 0)
{
if (data != 0) {
Log.notice(F("MQTTtoSRFB data ok" CR));
int valueMiniPLSL = SRFBdata["val_Tlow"];
int valueMaxiPLSL = SRFBdata["val_Thigh"];
@@ -376,9 +332,7 @@ void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata)
_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
{
} else {
Log.error(F("MQTTtoSRFB error decoding value" CR));
}
}
+12 -25
View File
@@ -29,8 +29,7 @@
# include <WeatherStationDataRx.h>
WeatherStationDataRx wsdr(RF_WS_RECEIVER_PIN, true);
void PairedDeviceAdded(byte newID)
{
void PairedDeviceAdded(byte newID) {
# if defined(ESP8266) || defined(ESP32)
Serial.printf("ZgatewayWeatherStation: New device paired %d\r\n", newID);
# else
@@ -46,19 +45,16 @@ void PairedDeviceAdded(byte newID)
wsdr.pair(NULL, PairedDeviceAdded);
}
void setupWeatherStation()
{
void setupWeatherStation() {
Log.notice(F("RF_WS_RECEIVER_PIN %d" CR), RF_WS_RECEIVER_PIN);
wsdr.begin();
wsdr.pair(NULL, PairedDeviceAdded);
Log.trace(F("ZgatewayWeatherStation setup done " CR));
}
void sendWindSpeedData(byte id, float wind_speed, byte battery_status)
{
void sendWindSpeedData(byte id, float wind_speed, byte battery_status) {
unsigned long MQTTvalue = 10000 + round(wind_speed);
if (!isAduplicate(MQTTvalue))
{ // conditions to avoid duplications of RF -->MQTT
if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
@@ -71,11 +67,9 @@ void sendWindSpeedData(byte id, float wind_speed, byte battery_status)
}
}
void sendRainData(byte id, float rain_volume, byte battery_status)
{
void sendRainData(byte id, float rain_volume, byte battery_status) {
unsigned long MQTTvalue = 11000 + round(rain_volume * 10.0);
if (!isAduplicate(MQTTvalue))
{ // conditions to avoid duplications of RF -->MQTT
if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
@@ -88,11 +82,9 @@ void sendRainData(byte id, float rain_volume, byte battery_status)
}
}
void sendWindData(byte id, int wind_direction, float wind_gust, byte battery_status)
{
void sendWindData(byte id, int wind_direction, float wind_gust, byte battery_status) {
unsigned long MQTTvalue = 20000 + round(wind_gust * 10.0) + wind_direction;
if (!isAduplicate(MQTTvalue))
{ // conditions to avoid duplications of RF -->MQTT
if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
@@ -106,11 +98,9 @@ void sendWindData(byte id, int wind_direction, float wind_gust, byte battery_sta
}
}
void sendTemperatureData(byte id, float temperature, int humidity, byte battery_status)
{
void sendTemperatureData(byte id, float temperature, int humidity, byte battery_status) {
unsigned long MQTTvalue = 40000 + abs(round(temperature * 100.0)) + humidity;
if (!isAduplicate(MQTTvalue))
{ // conditions to avoid duplications of RF -->MQTT
if (!isAduplicate(MQTTvalue)) { // conditions to avoid duplications of RF -->MQTT
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
@@ -124,11 +114,9 @@ void sendTemperatureData(byte id, float temperature, int humidity, byte battery_
}
}
void ZgatewayWeatherStationtoMQTT()
{
void ZgatewayWeatherStationtoMQTT() {
char newData = wsdr.readData();
switch (newData)
{
switch (newData) {
case 'T':
Log.trace(F("Temperature" CR));
sendTemperatureData(wsdr.sensorID(), wsdr.readTemperature(), wsdr.readHumidity(), wsdr.batteryStatus());
@@ -152,7 +140,6 @@ void ZgatewayWeatherStationtoMQTT()
default:
break;
}
}
#endif
+14 -28
View File
@@ -27,8 +27,7 @@
#ifdef ZmqttDiscovery
String getMacAddress()
{
String getMacAddress() {
uint8_t baseMac[6];
char baseMacChr[13] = {0};
# if defined(ESP8266)
@@ -43,17 +42,14 @@ String getMacAddress()
return String(baseMacChr);
}
String getUniqueId(String name, String sufix)
{
String getUniqueId(String name, String sufix) {
String uniqueId = (String)getMacAddress() + name + sufix;
return String(uniqueId);
}
# ifdef ZgatewayBT
void createDiscoveryFromList(char *mac, char *sensorList[][8], int sensorCount)
{
for (int i = 0; i < sensorCount; i++)
{
void createDiscoveryFromList(char* mac, char* sensorList[][8], int sensorCount) {
for (int i = 0; i < sensorCount; i++) {
Log.trace(F("CreateDiscoverySensor %s" CR), sensorList[i][1]);
String discovery_topic = String(subjectBTtoMQTT) + "/" + String(mac);
String unique_id = String(mac) + "-" + sensorList[i][1];
@@ -71,8 +67,7 @@ void createDiscovery(char *sensor_type,
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);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& sensor = jsonBuffer.createObject();
@@ -101,16 +96,14 @@ void createDiscovery(char *sensor_type,
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);
sensor.set("cmd_t", command_topic); //command_topic
}
if (child_device)
{
if (child_device) {
StaticJsonBuffer<JSON_MSG_BUFFER> jsonDeviceBuffer;
JsonObject& device = jsonDeviceBuffer.createObject();
device.set("name", gateway_name);
@@ -124,8 +117,7 @@ void createDiscovery(char *sensor_type,
pub_custom_topic((char*)topic.c_str(), sensor, true);
}
void pubMqttDiscovery()
{
void pubMqttDiscovery() {
Log.trace(F("omgStatusDiscovery" CR));
createDiscovery("binary_sensor", //set Type
will_Topic, Gateway_Name, (char*)getUniqueId("", "").c_str(), //set state_topic,name,uniqueId
@@ -162,8 +154,7 @@ void pubMqttDiscovery()
//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++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(BMEsensor[i][1]);
createDiscovery(BMEsensor[i][0],
@@ -184,8 +175,7 @@ void pubMqttDiscovery()
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
};
for (int i = 0; i < HTUparametersCount; i++)
{
for (int i = 0; i < HTUparametersCount; i++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(HTUsensor[i][1]);
createDiscovery(HTUsensor[i][0],
@@ -203,8 +193,7 @@ void pubMqttDiscovery()
{"sensor", "tempc", "dht", "temperature", jsonTemp, "", "", "°C"},
{"sensor", "hum", "dht", "humidity", jsonHum, "", "", "%"}};
for (int i = 0; i < DHTparametersCount; i++)
{
for (int i = 0; i < DHTparametersCount; i++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(DHTsensor[i][1]);
createDiscovery(DHTsensor[i][0],
@@ -239,8 +228,7 @@ void pubMqttDiscovery()
//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++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(BH1750sensor[i][1]);
createDiscovery(BH1750sensor[i][0],
@@ -261,8 +249,7 @@ void pubMqttDiscovery()
//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++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(TSL2561sensor[i][1]);
createDiscovery(TSL2561sensor[i][0],
@@ -311,8 +298,7 @@ void pubMqttDiscovery()
//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++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(INA226sensor[i][1]);
createDiscovery(INA226sensor[i][0],
+6 -13
View File
@@ -37,29 +37,22 @@ ADC_MODE(ADC_TOUT);
//Time used to wait for an interval before resending adc value
unsigned long timeadc = 0;
void setupADC()
{
void setupADC() {
Log.notice(F("Reading ADC on pin: %d" CR), ADC_PIN);
}
void MeasureADC()
{
if (millis() > (timeadc + TimeBetweenReadingADC))
{ //retrieving value of temperature and humidity of the box from DHT every xUL
void MeasureADC() {
if (millis() > (timeadc + TimeBetweenReadingADC)) { //retrieving value of temperature and humidity of the box from DHT every xUL
# if defined(ESP8266)
yield();
# endif
timeadc = millis();
static int persistedadc;
int val = analogRead(ADC_PIN);
if (isnan(val))
{
if (isnan(val)) {
Log.error(F("Failed to read from ADC !" CR));
}
else
{
if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC)
{
} else {
if (val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC) {
Log.trace(F("Creating ADC buffer" CR));
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
+12 -28
View File
@@ -39,11 +39,10 @@
#include "User_config.h"
#ifdef ZsensorBH1750
#include "math.h" // Library for trig and exponential functions
# include "Wire.h" // Library for communication with I2C / TWI devices
# include "math.h" // Library for trig and exponential functions
void setupZsensorBH1750()
{
void setupZsensorBH1750() {
Log.notice(F("Setup BH1750 on adress: %H" CR), BH1750_i2c_addr);
Wire.begin();
Wire.beginTransmission(BH1750_i2c_addr);
@@ -52,11 +51,8 @@ void setupZsensorBH1750()
delay(300);
}
// void loop()
void MeasureLightIntensity()
{
if (millis() > (timebh1750 + TimeBetweenReadingBH1750))
{ //retrieving value of Lux, FtCd and Wattsm2 from BH1750
void MeasureLightIntensity() {
if (millis() > (timebh1750 + TimeBetweenReadingBH1750)) { //retrieving value of Lux, FtCd and Wattsm2 from BH1750
Log.trace(F("Creating BH1750 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& BH1750data = jsonBuffer.createObject();
@@ -72,12 +68,9 @@ 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) {
Log.error(F("Failed to read from LightSensor BH1750!" CR));
}
else
{
} else {
i = Wire.read();
i <<= 8;
i |= Wire.read();
@@ -88,32 +81,23 @@ void MeasureLightIntensity()
Wattsm2 = Lux / 683.0;
// Generate Lux
if (Lux != persistedll || bh1750_always)
{
if (Lux != persistedll || bh1750_always) {
BH1750data.set("lux", (unsigned int)Lux);
}
else
{
} else {
Log.trace(F("Same lux don't send it" CR));
}
// Generate FtCd
if (ftcd != persistedlf || bh1750_always)
{
if (ftcd != persistedlf || bh1750_always) {
BH1750data.set("ftcd", (unsigned int)ftcd);
}
else
{
} else {
Log.trace(F("Same ftcd don't send it" CR));
}
// Generate Watts/m2
if (Wattsm2 != persistedlw || bh1750_always)
{
if (Wattsm2 != persistedlw || bh1750_always) {
BH1750data.set("wattsm2", (unsigned int)Wattsm2);
}
else
{
} else {
Log.trace(F("Same wattsm2 don't send it" CR));
}
if (BH1750data.size() > 0)
+19 -44
View File
@@ -40,15 +40,15 @@
#include "User_config.h"
#ifdef ZsensorBME280
#include "Wire.h" // Library for communication with I2C / TWI devices
# include <stdint.h>
# include "SparkFunBME280.h"
# include "Wire.h" // Library for communication with I2C / TWI devices
//Global sensor object
BME280 mySensor;
void setupZsensorBME280()
{
void setupZsensorBME280() {
mySensor.settings.commInterface = I2C_MODE;
mySensor.settings.I2CAddress = BME280_i2c_addr;
Log.notice(F("Setup BME280 on adress: %H" CR), BME280_i2c_addr);
@@ -104,12 +104,8 @@ void setupZsensorBME280()
Log.notice(F("Bosch BME280 Initialized - Result of .begin(): 0x %h" CR), mySensor.begin());
}
void MeasureTempHumAndPressure()
{
if (millis() > (timebme280 + TimeBetweenReadingbme280))
{
void MeasureTempHumAndPressure() {
if (millis() > (timebme280 + TimeBetweenReadingbme280)) {
timebme280 = millis();
static float persisted_bme_tempc;
static float persisted_bme_tempf;
@@ -126,73 +122,52 @@ 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)) {
Log.error(F("Failed to read from BME280!" CR));
}
else
{
} else {
Log.trace(F("Creating BME280 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& BME280data = jsonBuffer.createObject();
// Generate Temperature in degrees C
if (BmeTempC != persisted_bme_tempc || bme280_always)
{
if (BmeTempC != persisted_bme_tempc || bme280_always) {
BME280data.set("tempc", (float)BmeTempC);
}
else
{
} else {
Log.trace(F("Same Degrees C don't send it" CR));
}
// 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 {
Log.trace(F("Same Degrees F don't send it" CR));
}
// 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 {
Log.trace(F("Same Humidity don't send it" CR));
}
// 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 {
Log.trace(F("Same Pressure don't send it" CR));
}
// Generate Altitude in Meter
if (BmeAltiM != persisted_bme_altim || bme280_always)
{
if (BmeAltiM != persisted_bme_altim || bme280_always) {
Log.trace(F("Sending Altitude Meter to MQTT" CR));
BME280data.set("altim", (float)BmeAltiM);
}
else
{
} else {
Log.trace(F("Same Altitude Meter don't send it" CR));
}
// 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 {
Log.trace(F("Same Altitude Feet don't send it" CR));
}
if (BME280data.size() > 0)
+9 -21
View File
@@ -38,15 +38,12 @@ 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 setupDHT()
{
void setupDHT() {
Log.notice(F("Reading DHT on pin: %d" CR), DHT_RECEIVER_PIN);
}
void MeasureTempAndHum()
{
if (millis() > (timedht + TimeBetweenReadingDHT))
{ //retrieving value of temperature and humidity of the box from DHT every xUL
void MeasureTempAndHum() {
if (millis() > (timedht + TimeBetweenReadingDHT)) { //retrieving value of temperature and humidity of the box from DHT every xUL
timedht = millis();
static float persistedh;
static float persistedt;
@@ -54,29 +51,20 @@ 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)) {
Log.error(F("Failed to read from DHT sensor!" CR));
}
else
{
} else {
Log.trace(F("Creating DHT buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& DHTdata = jsonBuffer.createObject();
if (h != persistedh || dht_always)
{
if (h != persistedh || dht_always) {
DHTdata.set("hum", (float)h);
}
else
{
} else {
Log.trace(F("Same hum don't send it" CR));
}
if (t != persistedt || dht_always)
{
if (t != persistedt || dht_always) {
DHTdata.set("temp", (float)t);
}
else
{
} else {
Log.trace(F("Same temp don't send it" CR));
}
if (DHTdata.size() > 0)
+21 -49
View File
@@ -26,8 +26,8 @@
#include "User_config.h"
#ifdef ZsensorDS1820
#include <OneWire.h>
# include <DallasTemperature.h>
# include <OneWire.h>
OneWire owbus(DS1820_OWBUS_PIN);
DallasTemperature ds1820(&owbus);
@@ -38,9 +38,7 @@ static uint8_t ds1820_resolution[OW_MAX_SENSORS];
static String ds1820_type[OW_MAX_SENSORS];
static String ds1820_addr[OW_MAX_SENSORS];
void setupZsensorDS1820()
{
void setupZsensorDS1820() {
Log.trace(F("DS1820: configured pin: %d for 1-wire bus" CR), DS1820_OWBUS_PIN);
ds1820.begin();
@@ -51,42 +49,32 @@ void setupZsensorDS1820()
Log.notice(F("DS1820: Found %d devices" CR), numDevicesOnBus);
// Cycle though all of the devices on the OneWire bus
for (int deviceIndex = 0; deviceIndex < numDevicesOnBus && ds1820_count < OW_MAX_SENSORS; deviceIndex++)
{
for (int deviceIndex = 0; deviceIndex < numDevicesOnBus && ds1820_count < OW_MAX_SENSORS; deviceIndex++) {
// get the next device on the OneWire bus and confirm it is a sensor the library can handle (Dallas DS18X20 1-wire devices)
if ( ds1820.getAddress(ds1820_address, deviceIndex) && ds1820.validFamily(ds1820_address) )
{
if (ds1820.getAddress(ds1820_address, deviceIndex) && ds1820.validFamily(ds1820_address)) {
ds1820_addr[ds1820_count] = String("0x");
for (uint8_t i = 0; i < 8; i++)
{
for (uint8_t i = 0; i < 8; i++) {
if (ds1820_address[i] < 0x10) ds1820_addr[ds1820_count] += String("0");
ds1820_devices[ds1820_count][i] = ds1820_address[i];
ds1820_addr[ds1820_count] += String(ds1820_address[i], HEX);
}
// set the resolution and thus conversion timing
if (ds1820_address[0] == 0x10)
{
if (ds1820_address[0] == 0x10) {
// DS1820/DS18S20 have no resolution configuration register,
// both have a 9-bit temperature register. Resolutions greater
// than 9-bit can be calculated using the data from the temperature,
// and COUNT REMAIN and COUNT PER °C registers in the scratchpad.
// The resolution of the calculation depends on the model.
ds1820_type[ds1820_count] = String("DS1820/DS18S20");
}
else if (ds1820_address[0] == 0x28)
{
} else if (ds1820_address[0] == 0x28) {
// DS18B20 and 18B22 are capable of different resolutions (9-12 bit)
ds1820_type[ds1820_count] = String("DS18B20");
ds1820.setResolution(ds1820_address, DS1820_RESOLUTION);
}
else if (ds1820_address[0] == 0x22)
{
} else if (ds1820_address[0] == 0x22) {
ds1820_type[ds1820_count] = String("DS1822");
ds1820.setResolution(ds1820_address, DS1820_RESOLUTION);
}
else
{
} else {
ds1820_type[ds1820_count] = String("DS1825");
ds1820.setResolution(ds1820_address, DS1820_RESOLUTION);
}
@@ -100,8 +88,7 @@ void setupZsensorDS1820()
}
}
if (ds1820.getDS18Count() == 0)
{
if (ds1820.getDS18Count() == 0) {
Log.error(F("DS1820: Failed to enumerate sensors on 1-wire bus. Check your pin assignment!" CR));
}
@@ -110,13 +97,11 @@ void setupZsensorDS1820()
ds1820.setWaitForConversion(false);
}
void pubOneWire_HADiscovery()
{
void pubOneWire_HADiscovery() {
// If zmqttDiscovery is enabled, create a sensor topic for each DS18b20 sensor found on the bus, using addr as uniqueID
# ifdef ZmqttDiscovery
Log.notice(F("CreateDiscoverySensor - Found %d" CR), ds1820_count);
for (int index=0; index<ds1820_count; index++)
{
for (int index = 0; index < ds1820_count; index++) {
# if DS1820_FAHRENHEIT
createDiscovery("sensor",
(char*)(String(OW_TOPIC) + "/" + ds1820_addr[index]).c_str(),
@@ -142,8 +127,7 @@ void pubOneWire_HADiscovery()
# endif
}
void MeasureDS1820Temp()
{
void MeasureDS1820Temp() {
static float persisted_temp[OW_MAX_SENSORS];
static unsigned long timeDS1820 = 0;
static boolean triggeredConversion = false;
@@ -151,36 +135,26 @@ void MeasureDS1820Temp()
// trigger temperature conversion some time before actually
// calling getTempC() to make reading temperatures non-blocking
if (!triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC*1000) - DS1820_CONV_TIME)))
{
if (!triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC * 1000) - DS1820_CONV_TIME))) {
Log.trace(F("DS1820: Trigger temperature conversion..." CR));
ds1820.requestTemperatures();
triggeredConversion = true;
}
else if (triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC*1000))))
{
} else if (triggeredConversion && (millis() > (timeDS1820 + (DS1820_INTERVAL_SEC * 1000)))) {
timeDS1820 = millis();
triggeredConversion = false;
if (ds1820_count < 1)
{
if (ds1820_count < 1) {
Log.error(F("DS1820: Failed to identify any temperature sensors on 1-wire bus during setup!" CR));
}
else
{
} else {
Log.trace(F("DS1820: Reading temperature(s) from %d sensor(s)..." CR), ds1820_count);
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& DS1820data = jsonBuffer.createObject();
for (uint8_t i=0; i < ds1820_count; i++)
{
for (uint8_t i = 0; i < ds1820_count; i++) {
current_temp[i] = round(ds1820.getTempC(ds1820_devices[i]) * 10) / 10.0;
if (current_temp[i] == -127)
{
if (current_temp[i] == -127) {
Log.error(F("DS1820: Device %s currently disconnected!" CR), (char*)ds1820_addr[i].c_str());
}
else if (DS1820_ALWAYS || current_temp[i] != persisted_temp[i])
{
} else if (DS1820_ALWAYS || current_temp[i] != persisted_temp[i]) {
if (DS1820_FAHRENHEIT) {
Log.notice(F("DS1820: Temperature %s %d F" CR),
(char*)ds1820_addr[i].c_str(),
@@ -203,9 +177,7 @@ void MeasureDS1820Temp()
}
pub((char*)(String(OW_TOPIC) + "/" + ds1820_addr[i]).c_str(), DS1820data);
delay(10);
}
else
{
} else {
Log.trace(F("DS1820: Temperature for device %s didn't change, don't publish it." CR), (char*)ds1820_addr[i].c_str());
}
persisted_temp[i] = current_temp[i];
+7 -14
View File
@@ -34,14 +34,12 @@ unsigned long lastDebounceTime = 0;
int InputState = 3; // Set to 3 so that it reads on startup
int lastInputState = 3;
void setupGPIOInput()
{
void setupGPIOInput() {
Log.notice(F("Reading GPIO at pin: %d" CR), GPIOInput_PIN);
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
@@ -49,33 +47,28 @@ 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)
yield();
# endif
// if the Input state has changed:
if (reading != InputState)
{
if (reading != InputState) {
InputState = reading;
Log.trace(F("Creating GPIOInput buffer" CR));
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& GPIOdata = jsonBuffer.createObject();
if (InputState == HIGH)
{
if (InputState == HIGH) {
GPIOdata.set("gpio", "HIGH");
}
if (InputState == LOW)
{
if (InputState == LOW) {
GPIOdata.set("gpio", "LOW");
}
if (GPIOdata.size() > 0)
+4 -9
View File
@@ -31,8 +31,7 @@ int InputStateGPIOKeyCode = 0x0f; // Set to 3 so that it reads on startup
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); //
@@ -40,9 +39,7 @@ void setupGPIOKeyCode()
//pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); //
}
void MeasureGPIOKeyCode()
{
void MeasureGPIOKeyCode() {
int latch = digitalRead(GPIOKeyCode_LATCH_PIN);
// check to see if you just pressed the button
@@ -56,8 +53,7 @@ void MeasureGPIOKeyCode()
yield();
# endif
// if the Input state has changed:
if (latch > 0 && lastLatchStateGPIOKeyCode != latch)
{
if (latch > 0 && lastLatchStateGPIOKeyCode != latch) {
int reading = digitalRead(GPIOKeyCode_D0_PIN) | (digitalRead(GPIOKeyCode_D1_PIN) << 1) | (digitalRead(GPIOKeyCode_D2_PIN) << 2);
//| digitalRead(GPIOKeyCode_D3_PIN) << 3;
@@ -71,8 +67,7 @@ void MeasureGPIOKeyCode()
lastLatchStateGPIOKeyCode = latch;
}
if (latch != lastLatchStateGPIOKeyCode)
{
if (latch != lastLatchStateGPIOKeyCode) {
lastLatchStateGPIOKeyCode = latch;
Log.notice(F("GPIOKeyCode latch %d" CR), latch);
if (latch == 0)
+8 -19
View File
@@ -33,18 +33,15 @@
unsigned long timeHCSR04 = 0;
void setupHCSR04()
{
void setupHCSR04() {
Log.notice(F("HCSR04 trigger pin: %d" CR), HCSR04_TRI_PIN);
Log.notice(F("HCSR04 echo pin: %d" CR), HCSR04_ECH_PIN);
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();
Log.trace(F("Creating HCSR04 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
@@ -55,27 +52,19 @@ void MeasureDistance()
delayMicroseconds(10);
digitalWrite(HCSR04_TRI_PIN, LOW);
unsigned long duration = pulseIn(HCSR04_ECH_PIN, HIGH);
if (isnan(duration))
{
if (isnan(duration)) {
Log.error(F("Failed to read from HC SR04 sensor!" CR));
}
else
{
} else {
static unsigned int distance = 99999;
unsigned int d = duration / 58.2;
HCSR04data.set("distance", (int)d);
if (d > distance)
{
if (d > distance) {
HCSR04data.set("direction", "away");
Log.trace(F("HC SR04 Distance changed" CR));
}
else if (d < distance)
{
} else if (d < distance) {
HCSR04data.set("direction", "towards");
Log.trace(F("HC SR04 Distance changed" CR));
}
else if (HCSR04_always)
{
} else if (HCSR04_always) {
HCSR04data.set("direction", "static");
Log.trace(F("HC SR04 Distance hasn't changed" CR));
}
+7 -15
View File
@@ -30,16 +30,13 @@
#ifdef ZsensorHCSR501
void setupHCSR501()
{
void setupHCSR501() {
Log.notice(F("HCSR501 pin: %d" CR), HCSR501_PIN);
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();
@@ -48,19 +45,14 @@ void MeasureHCSR501()
# 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");
pirState = HIGH;
}
}
else
{
if (pirState == HIGH)
{
} else {
if (pirState == HIGH) {
// turned off
HCSR501data.set("hcsr501", "false");
pirState = LOW;
+12 -25
View File
@@ -38,9 +38,10 @@
#include "User_config.h"
#ifdef ZsensorHTU21
#include "Wire.h" // Library for communication with I2C / TWI devices
# include <stdint.h>
# include "SparkFunHTU21D.h"
# include "Wire.h" // Library for communication with I2C / TWI devices
# include "config_HTU21.h"
//Time used to wait for an interval before resending measured values
@@ -49,8 +50,7 @@ unsigned long timehtu21 = 0;
//Global sensor object
HTU21D htuSensor;
void setupZsensorHTU21()
{
void setupZsensorHTU21() {
delay(10); // Gives the Sensor enough time to turn on
Log.notice(F("HTU21 Initialized - begin()" CR));
@@ -62,11 +62,8 @@ void setupZsensorHTU21()
# endif
}
void MeasureTempHum()
{
if (millis() > (timehtu21 + TimeBetweenReadinghtu21))
{
void MeasureTempHum() {
if (millis() > (timehtu21 + TimeBetweenReadinghtu21)) {
Log.trace(F("Read HTU21 Sensor" CR));
timehtu21 = millis();
@@ -76,41 +73,31 @@ void MeasureTempHum()
float HtuTempC = htuSensor.readTemperature();
float HtuHum = htuSensor.readHumidity();
if (HtuTempC >= 998 || HtuHum >= 998 )
{
if (HtuTempC >= 998 || HtuHum >= 998) {
Log.error(F("Failed to read from sensor HTU21!" CR));
return;
}
// Check if reads failed and exit early (to try again).
if (isnan(HtuTempC) || isnan(HtuHum))
{
if (isnan(HtuTempC) || isnan(HtuHum)) {
Log.error(F("Failed to read from sensor HTU21!" CR));
}
else
{
} else {
Log.notice(F("Creating HTU21 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& HTU21data = jsonBuffer.createObject();
// Generate Temperature in degrees C
if (HtuTempC != persisted_htu_tempc || htu21_always)
{
if (HtuTempC != persisted_htu_tempc || htu21_always) {
float HtuTempF = (HtuTempC * 1.8) + 32;
HTU21data.set("tempc", (float)HtuTempC);
HTU21data.set("tempf", (float)HtuTempF);
}
else
{
} else {
Log.notice(F("Same Temp. Don't send it" CR));
}
// Generate Humidity in percent
if (HtuHum != persisted_htu_hum || htu21_always)
{
if (HtuHum != persisted_htu_hum || htu21_always) {
HTU21data.set("hum", (float)HtuHum);
}
else
{
} else {
Log.notice(F("Same Humidity. Don't send it" CR));
}
+8 -16
View File
@@ -43,17 +43,14 @@ const int INA226_ADDR = 0x40; // A0 und A1 auf GND > Adresse 40 Hex auf Seite 18
//Time used to wait for an interval before resending temp and hum
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))
{ //retrieving value of temperature and humidity of the box from DHT every xUL
void MeasureINA226() {
if (millis() > (timeINA226 + TimeBetweenReadingINA226)) { //retrieving value of temperature and humidity of the box from DHT every xUL
timeINA226 = millis();
Log.trace(F("Creating INA226 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
@@ -64,8 +61,7 @@ void MeasureINA226()
float volt = readRegister(0x02) * 0.00125;
// 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
@@ -86,8 +82,7 @@ void MeasureINA226()
}
}
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);
@@ -95,15 +90,12 @@ 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();
}
+11 -20
View File
@@ -40,15 +40,15 @@
#include "User_config.h"
#ifdef ZsensorTSL2561
#include "math.h"
#include "Wire.h"
# include <Adafruit_Sensor.h>
# include <Adafruit_TSL2561_U.h>
# include "Wire.h"
# include "math.h"
Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);
void displaySensorDetails(void)
{
void displaySensorDetails(void) {
sensor_t sensor;
tsl.getSensor(&sensor);
Log.trace(F("------------------------------------" CR));
@@ -62,14 +62,12 @@ void displaySensorDetails(void)
delay(500);
}
void setupZsensorTSL2561()
{
void setupZsensorTSL2561() {
Log.notice(F("Setup TSL2561 on adress: %H" CR), TSL2561_ADDR_FLOAT);
Wire.begin();
Wire.beginTransmission(TSL2561_ADDR_FLOAT);
if (!tsl.begin())
{
if (!tsl.begin()) {
Log.error(F("No TSL2561 detected" CR));
}
@@ -86,10 +84,8 @@ void setupZsensorTSL2561()
displaySensorDetails();
}
void MeasureLightIntensityTSL2561()
{
if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561))
{
void MeasureLightIntensityTSL2561() {
if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) {
static uint32_t persisted_lux;
timetsl2561 = millis();
@@ -102,8 +98,7 @@ void MeasureLightIntensityTSL2561()
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);
@@ -111,14 +106,10 @@ void MeasureLightIntensityTSL2561()
TSL2561data.set("wattsm2", (float)(event.light) / 683.0);
pub(subjectTSL12561toMQTT, TSL2561data);
}
else
{
} else {
Log.trace(F("Same lux value, do not send" CR));
}
}
else
{
} else {
Log.error(F("Failed to read from TSL2561" CR));
}
}
-1
View File
@@ -35,7 +35,6 @@ extern void ZgatewayWeatherStationtoMQTT();
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectRFtoMQTT "/433toMQTT"
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef RF_WS_RECEIVER_PIN
# ifdef ESP8266
+123 -259
View File
@@ -38,9 +38,9 @@ unsigned long timer_sys_measures = 0;
unsigned long ReceivedSignal[array_size][2] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};
#endif
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <ArduinoLog.h>
#include <PubSubClient.h>
// Modules config inclusion
#if defined(ZgatewayRF) || defined(ZgatewayRF2) || defined(ZgatewayPilight)
@@ -125,25 +125,26 @@ int failure_number_ntwk = 0; // number of failure connecting to network
int failure_number_mqtt = 0; // number of failure connecting to MQTT
#ifdef ESP32
#include <FS.h>
#include "SPIFFS.h"
#include <WiFi.h>
# include <ArduinoOTA.h>
# include <FS.h>
# include <WiFi.h>
# include <WiFiUdp.h>
# include "SPIFFS.h"
# include "esp_wifi.h"
WiFiClient eClient;
#include <WiFiManager.h>
# include <Preferences.h>
# include <WiFiManager.h>
Preferences preferences;
# ifdef MDNS_SD
# include <ESPmDNS.h>
# endif
#elif defined(ESP8266)
#include <FS.h>
#include <ESP8266WiFi.h>
# include <ArduinoOTA.h>
# include <DNSServer.h>
# include <ESP8266WebServer.h>
# include <ESP8266WiFi.h>
# include <FS.h>
# include <WiFiManager.h>
WiFiClient eClient;
# ifdef MDNS_SD
@@ -160,12 +161,10 @@ PubSubClient client(eClient);
//MQTT last attemps reconnection date
unsigned long lastMQTTReconnectAttempt = 0;
void revert_hex_data(char *in, char *out, int l)
{
void revert_hex_data(char* in, char* out, int l) {
//reverting array 2 by 2 to get the data in good order
int i = l - 2, j = 0;
while (i != -2)
{
while (i != -2) {
if (i % 2 == 0)
out[j] = in[i + 1];
else
@@ -176,13 +175,11 @@ void revert_hex_data(char *in, char *out, int l)
out[l - 1] = '\0';
}
void extract_char(char *token_char, char *subset, int start, int l, bool reverse, bool isNumber)
{
void extract_char(char* token_char, char* subset, int start, int l, bool reverse, bool isNumber) {
char tmp_subset[l + 1];
memcpy(tmp_subset, &token_char[start], l);
tmp_subset[l] = '\0';
if (isNumber)
{
if (isNumber) {
char tmp_subset2[l + 1];
if (reverse)
revert_hex_data(tmp_subset, tmp_subset2, l + 1);
@@ -191,9 +188,7 @@ void extract_char(char *token_char, char *subset, int start, int l, bool reverse
long long_value = strtoul(tmp_subset2, NULL, 16);
sprintf(tmp_subset2, "%ld", long_value);
strncpy(subset, tmp_subset2, l + 1);
}
else
{
} else {
if (reverse)
revert_hex_data(tmp_subset, subset, l + 1);
else
@@ -202,36 +197,30 @@ void extract_char(char *token_char, char *subset, int start, int l, bool reverse
subset[l] = '\0';
}
char *ip2CharArray(IPAddress ip)
{ //from Nick Lee https://stackoverflow.com/questions/28119653/arduino-display-ethernet-localip
char* ip2CharArray(IPAddress ip) { //from Nick Lee https://stackoverflow.com/questions/28119653/arduino-display-ethernet-localip
static char a[16];
sprintf(a, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
return a;
}
bool to_bool(String const &s)
{ // thanks Chris Jester-Young from stackoverflow
bool to_bool(String const& s) { // thanks Chris Jester-Young from stackoverflow
return s != "0";
}
void pub(char *topicori, char *payload, bool retainFlag)
{
void pub(char* topicori, char* payload, bool retainFlag) {
String topic = String(mqtt_topic) + String(topicori);
pubMQTT((char*)topic.c_str(), payload, retainFlag);
}
void pub(char *topicori, JsonObject &data)
{
void pub(char* topicori, JsonObject& data) {
Log.notice(F("Subject: %s" CR), topicori);
logJson(data);
if (client.connected())
{
if (client.connected()) {
digitalWrite(led_receive, HIGH);
String topic = String(mqtt_topic) + String(topicori);
#ifdef valueAsASubject
unsigned long value = data["value"];
if (value != 0)
{
if (value != 0) {
topic = topic + "/" + String(value);
}
#endif
@@ -250,61 +239,42 @@ void pub(char *topicori, JsonObject &data)
#ifdef simplePublishing
Log.trace(F("simplePublishing" CR));
// Loop through all the key-value pairs in obj
for (JsonPair &p : data)
{
for (JsonPair& p : data) {
# if defined(ESP8266)
yield();
# endif
if (p.value.is<unsigned long>() && strcmp(p.key, "rssi") != 0)
{ //test rssi , bypass solution due to the fact that a int is considered as an unsigned long
if (strcmp(p.key, "value") == 0)
{ // if data is a value we don't integrate the name into the topic
if (p.value.is<unsigned long>() && strcmp(p.key, "rssi") != 0) { //test rssi , bypass solution due to the fact that a int is considered as an unsigned long
if (strcmp(p.key, "value") == 0) { // if data is a value we don't integrate the name into the topic
pubMQTT(topic, p.value.as<unsigned long>());
}
else
{ // if data is not a value we integrate the name into the topic
} else { // if data is not a value we integrate the name into the topic
pubMQTT(topic + "/" + String(p.key), p.value.as<unsigned long>());
}
}
else if (p.value.is<int>())
{
} else if (p.value.is<int>()) {
pubMQTT(topic + "/" + String(p.key), p.value.as<int>());
}
else if (p.value.is<float>())
{
} else if (p.value.is<float>()) {
pubMQTT(topic + "/" + String(p.key), p.value.as<float>());
}
else if (p.value.is<char *>())
{
} else if (p.value.is<char*>()) {
pubMQTT(topic + "/" + String(p.key), p.value.as<const char*>());
}
}
#endif
}
else
{
} else {
Log.warning(F("client not connected can't pub" CR));
}
}
void pub(char *topicori, char *payload)
{
if (client.connected())
{
void pub(char* topicori, char* payload) {
if (client.connected()) {
String topic = String(mqtt_topic) + String(topicori);
Log.trace(F("Pub ack %s into: %s" CR), payload, topic.c_str());
pubMQTT(topic, payload);
}
else
{
} else {
Log.warning(F("client not connected can't pub" CR));
}
}
void pub_custom_topic(char *topicori, JsonObject &data, boolean retain)
{
if (client.connected())
{
void pub_custom_topic(char* topicori, JsonObject& data, boolean retain) {
if (client.connected()) {
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
char JSONmessageBuffer[data.measureLength() + 1];
#else
@@ -313,111 +283,93 @@ void pub_custom_topic(char *topicori, JsonObject &data, boolean retain)
data.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Log.trace(F("Pub json :%s into custom topic: %s" CR), JSONmessageBuffer, topicori);
pubMQTT(topicori, JSONmessageBuffer, retain);
}
else
{
} else {
Log.warning(F("client not connected can't pub" CR));
}
}
// Low level MQTT functions
void pubMQTT(char * topic, char * payload)
{
void pubMQTT(char* topic, char* payload) {
client.publish(topic, payload);
}
void pubMQTT(char * topicori, char * payload, bool retainFlag)
{
void pubMQTT(char* topicori, char* payload, bool retainFlag) {
client.publish(topicori, payload, retainFlag);
}
void pubMQTT(String topic, char * payload)
{
void pubMQTT(String topic, char* payload) {
client.publish((char*)topic.c_str(), payload);
}
void pubMQTT(char *topic, unsigned long payload)
{
void pubMQTT(char* topic, unsigned long payload) {
char val[11];
sprintf(val, "%lu", payload);
client.publish(topic, val);
}
void pubMQTT(char *topic, unsigned long long payload)
{
void pubMQTT(char* topic, unsigned long long payload) {
char val[21];
sprintf(val, "%llu", payload);
client.publish(topic, val);
}
void pubMQTT(char *topic, String payload)
{
void pubMQTT(char* topic, String payload) {
client.publish(topic, (char*)payload.c_str());
}
void pubMQTT(String topic, String payload)
{
void pubMQTT(String topic, String payload) {
client.publish((char*)topic.c_str(), (char*)payload.c_str());
}
void pubMQTT(String topic, int payload)
{
void pubMQTT(String topic, int payload) {
char val[12];
sprintf(val, "%d", payload);
client.publish((char*)topic.c_str(), val);
}
void pubMQTT(String topic, float payload)
{
void pubMQTT(String topic, float payload) {
char val[12];
dtostrf(payload, 3, 1, val);
client.publish((char*)topic.c_str(), val);
}
void pubMQTT(char *topic, float payload)
{
void pubMQTT(char* topic, float payload) {
char val[12];
dtostrf(payload, 3, 1, val);
client.publish(topic, val);
}
void pubMQTT(char *topic, int payload)
{
void pubMQTT(char* topic, int payload) {
char val[6];
sprintf(val, "%d", payload);
client.publish(topic, val);
}
void pubMQTT(char *topic, unsigned int payload)
{
void pubMQTT(char* topic, unsigned int payload) {
char val[6];
sprintf(val, "%u", payload);
client.publish(topic, val);
}
void pubMQTT(char *topic, long payload)
{
void pubMQTT(char* topic, long payload) {
char val[11];
sprintf(val, "%l", payload);
client.publish(topic, val);
}
void pubMQTT(char *topic, double payload)
{
void pubMQTT(char* topic, double payload) {
char val[16];
sprintf(val, "%d", payload);
client.publish(topic, val);
}
void pubMQTT(String topic, unsigned long payload)
{
void pubMQTT(String topic, unsigned long payload) {
char val[11];
sprintf(val, "%lu", payload);
client.publish((char*)topic.c_str(), val);
}
void logJson(JsonObject &jsondata)
{
void logJson(JsonObject& jsondata) {
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
char JSONmessageBuffer[jsondata.measureLength() + 1];
#else
@@ -438,9 +390,7 @@ bool cmpToMainTopic(char * topicOri, char * toAdd){
}
}
void connectMQTT()
{
void connectMQTT() {
#ifndef ESPWifiManualSetup
# if defined(ESP8266) || defined(ESP32)
checkButton(); // check if a reset of wifi/mqtt settings is asked
@@ -451,8 +401,7 @@ void connectMQTT()
char topic[mqtt_topic_max_size];
strcpy(topic, mqtt_topic);
strcat(topic, will_Topic);
if (client.connect(gateway_name, mqtt_user, mqtt_pass, topic, will_QoS, will_Retain, will_Message))
{
if (client.connect(gateway_name, mqtt_user, mqtt_pass, topic, will_QoS, will_Retain, will_Message)) {
#if defined(ZboardM5STICKC) || defined(ZboardM5STACK)
if (low_power_mode < 2)
M5Display("MQTT connected", "", "");
@@ -467,8 +416,7 @@ void connectMQTT()
char topic2[mqtt_topic_max_size];
strcpy(topic2, mqtt_topic);
strcat(topic2, subjectMQTTtoX);
if (client.subscribe(topic2))
{
if (client.subscribe(topic2)) {
#ifdef ZgatewayRF
client.subscribe(subjectMultiGTWRF); // subject on which other OMG will publish, this OMG will store these msg and by the way don't republish them if they have been already published
#endif
@@ -477,9 +425,7 @@ void connectMQTT()
#endif
Log.trace(F("Subscription OK to the subjects" CR));
}
}
else
{
} else {
failure_number_mqtt++; // we count the failure
Log.warning(F("failure_number_mqtt: %d" CR), failure_number_mqtt);
Log.warning(F("failed, rc=%d" CR), client.state());
@@ -491,8 +437,7 @@ void connectMQTT()
}
// Callback function, when the gateway receive an MQTT value on the topics subscribed this function is called
void callback(char *topic, byte *payload, unsigned int length)
{
void callback(char* topic, byte* payload, unsigned int length) {
// In order to republish this payload, a copy must be made
// as the orignal payload buffer will be overwritten whilst
// constructing the PUBLISH packet.
@@ -510,13 +455,11 @@ void callback(char *topic, byte *payload, unsigned int length)
free(p);
}
void setup_parameters()
{
void setup_parameters() {
strcat(mqtt_topic, gateway_name);
}
void setup()
{
void setup() {
//Launch serial for debugging purposes
Serial.begin(SERIAL_BAUD);
Log.begin(LOG_LEVEL, &Serial);
@@ -683,8 +626,7 @@ bool wifi_reconnect_bypass(){
delay(500);
wifi_autoreconnect_cnt++;
}
if(wifi_autoreconnect_cnt < maxConnectionRetryWifi)
{
if (wifi_autoreconnect_cnt < maxConnectionRetryWifi) {
return true;
} else {
return false;
@@ -702,8 +644,7 @@ void forceWifiProtocol(){
# endif
}
void reinit_wifi()
{
void reinit_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
if (!wifiProtocol) forceWifiProtocol();
@@ -712,19 +653,15 @@ void reinit_wifi()
void disconnection_handling(int failure_number) {
Log.warning(F("disconnection_handling, failed %d times" CR), failure_number);
if (failure_number > maxConnectionRetry && !connectedOnce)
{
if (failure_number > maxConnectionRetry && !connectedOnce) {
# ifndef ESPWifiManualSetup
Log.error(F("Failed connecting 1st time to mqtt, reset wifi manager & erase network credentials" CR));
setup_wifimanager(true);
# endif
}
else if (failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_BG && connectedOnce)
{
} else if (failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_BG && connectedOnce) {
Log.warning(F("Attempt to reinit wifi: %d" CR), wifiProtocol);
reinit_wifi();
}
else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_BG && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B ) // After maxConnectionRetry + ATTEMPTS_BEFORE_BG try to connect with BG protocol
} else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_BG && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B) // After maxConnectionRetry + ATTEMPTS_BEFORE_BG try to connect with BG protocol
{
# ifdef ESP32
wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G;
@@ -733,8 +670,7 @@ void disconnection_handling( int failure_number){
# endif
Log.warning(F("Wifi Protocol changed to WIFI_11G: %d" CR), wifiProtocol);
reinit_wifi();
}
else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG ) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol
} else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B && failure_number <= maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol
{
# ifdef ESP32
wifiProtocol = WIFI_PROTOCOL_11B;
@@ -743,8 +679,7 @@ void disconnection_handling( int failure_number){
# endif
Log.warning(F("Wifi Protocol changed to WIFI_11B: %d" CR), wifiProtocol);
reinit_wifi();
}
else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG ) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol
} else if (failure_number > maxConnectionRetry + ATTEMPTS_BEFORE_B + ATTEMPTS_BEFORE_BG) // After maxConnectionRetry + ATTEMPTS_BEFORE_B try to connect with B protocol
{
# ifdef ESP32
wifiProtocol = 0;
@@ -793,9 +728,7 @@ void setOTA(){
#endif
#if defined(ESPWifiManualSetup)
void setup_wifi()
{
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
if (!wifiProtocol) forceWifiProtocol();
@@ -807,8 +740,7 @@ void setup_wifi()
IPAddress gateway_adress(gateway);
IPAddress subnet_adress(subnet);
IPAddress dns_adress(Dns);
if (!WiFi.config(ip_adress, gateway_adress, subnet_adress, dns_adress))
{
if (!WiFi.config(ip_adress, gateway_adress, subnet_adress, dns_adress)) {
Log.error(F("Wifi STA Failed to configure" CR));
}
WiFi.begin(wifi_ssid, wifi_password);
@@ -816,11 +748,11 @@ void setup_wifi()
WiFi.begin(wifi_ssid, wifi_password);
# endif
if(wifi_reconnect_bypass());
if (wifi_reconnect_bypass())
;
Log.notice(F("Connected with saved credentials" CR));
while (WiFi.status() != WL_CONNECTED)
{
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Log.trace(F("." CR));
failure_number_ntwk++;
@@ -838,26 +770,21 @@ bool shouldSaveConfig = true;
//do we have been connected once to mqtt
//callback notifying us of the need to save config
void saveConfigCallback()
{
void saveConfigCallback() {
Log.trace(F("Should save config" CR));
shouldSaveConfig = true;
}
void checkButton()
{ // code from tzapu/wifimanager examples
void checkButton() { // code from tzapu/wifimanager examples
// check for button press
if (digitalRead(TRIGGER_PIN) == LOW)
{
if (digitalRead(TRIGGER_PIN) == LOW) {
// poor mans debounce/press-hold, code not ideal for production
delay(50);
if (digitalRead(TRIGGER_PIN) == LOW)
{
if (digitalRead(TRIGGER_PIN) == LOW) {
Log.trace(F("Trigger button Pressed" CR));
// still holding button for 3000 ms, reset settings, code not ideaa for production
delay(3000); // reset delay hold
if (digitalRead(TRIGGER_PIN) == LOW)
{
if (digitalRead(TRIGGER_PIN) == LOW) {
Log.trace(F("Button Held" CR));
Log.notice(F("Erasing ESP Config, restarting" CR));
setup_wifimanager(true);
@@ -866,8 +793,7 @@ void checkButton()
}
}
void eraseAndRestart()
{
void eraseAndRestart() {
# if defined(ESP8266)
WiFi.disconnect(true);
# else
@@ -885,9 +811,7 @@ void eraseAndRestart()
# endif
}
void setup_wifimanager(bool reset_settings)
{
void setup_wifimanager(bool reset_settings) {
pinMode(TRIGGER_PIN, INPUT_PULLUP);
delay(10);
@@ -900,24 +824,19 @@ void setup_wifimanager(bool reset_settings)
//read configuration from FS json
Log.trace(F("mounting FS..." CR));
if (SPIFFS.begin())
{
if (SPIFFS.begin()) {
Log.trace(F("mounted file system" CR));
}
else
{
} else {
Log.warning(F("failed to mount FS -> formating" CR));
SPIFFS.format();
if (SPIFFS.begin())
Log.trace(F("mounted file system after formating" CR));
}
if (SPIFFS.exists("/config.json"))
{
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Log.trace(F("reading config file" CR));
File configFile = SPIFFS.open("/config.json", "r");
if (configFile)
{
if (configFile) {
Log.trace(F("opened config file" CR));
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
@@ -926,8 +845,7 @@ void setup_wifimanager(bool reset_settings)
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success())
{
if (json.success()) {
Log.trace(F("\nparsed json" CR));
if (json.containsKey("mqtt_server"))
strcpy(mqtt_server, json["mqtt_server"]);
@@ -941,9 +859,7 @@ void setup_wifimanager(bool reset_settings)
strcpy(mqtt_topic, json["mqtt_topic"]);
if (json.containsKey("gateway_name"))
strcpy(gateway_name, json["gateway_name"]);
}
else
{
} else {
Log.warning(F("failed to load json config" CR));
}
}
@@ -992,8 +908,7 @@ void setup_wifimanager(bool reset_settings)
if (!wifi_reconnect_bypass()) // if we didn't connect with saved credential we start Wifimanager web portal
{
# ifdef ESP32
if (low_power_mode < 2)
{
if (low_power_mode < 2) {
# if defined(ZboardM5STICKC) || defined(ZboardM5STACK)
M5Display("Connect your phone to WIFI AP:", WifiManager_ssid, WifiManager_password);
# endif
@@ -1008,8 +923,7 @@ void setup_wifimanager(bool reset_settings)
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password))
{
if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password)) {
Log.warning(F("failed to connect and hit timeout" CR));
delay(3000);
//reset and try again
@@ -1036,8 +950,7 @@ void setup_wifimanager(bool reset_settings)
strcpy(gateway_name, custom_gateway_name.getValue());
//save the custom parameters to FS
if (shouldSaveConfig)
{
if (shouldSaveConfig) {
Log.trace(F("saving config" CR));
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
@@ -1049,8 +962,7 @@ void setup_wifimanager(bool reset_settings)
json["gateway_name"] = gateway_name;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile)
{
if (!configFile) {
Log.error(F("failed to open config file for writing" CR));
}
@@ -1062,8 +974,7 @@ void setup_wifimanager(bool reset_settings)
}
#else // Arduino case
void setup_ethernet()
{
void setup_ethernet() {
# ifdef NetworkAdvancedSetup
Log.trace(F("Adv eth cfg" CR));
Ethernet.begin(mac, ip, Dns, gateway, subnet);
@@ -1071,57 +982,43 @@ void setup_ethernet()
Log.trace(F("Spl eth cfg" CR));
Ethernet.begin(mac, ip);
# endif
if (Ethernet.hardwareStatus() == EthernetNoHardware)
{
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Log.error(F("Ethernet shield was not found." CR));
}
else
{
} else {
Log.trace(F("ip: %s " CR), Ethernet.localIP());
}
}
#endif
#if defined(MDNS_SD) && defined(ESP8266)
void connectMQTTmdns()
{
if (!MDNS.begin("ESP_MQTT"))
{
void connectMQTTmdns() {
if (!MDNS.begin("ESP_MQTT")) {
Log.error(F("Error setting up MDNS responder!" CR));
while (1)
{
while (1) {
delay(1000);
}
}
Log.trace(F("Browsing for MQTT service" CR));
int n = MDNS.queryService("mqtt", "tcp");
if (n == 0)
{
if (n == 0) {
Log.error(F("no services found" CR));
}
else
{
} else {
Log.trace(F("%d service(s) found" CR), n);
for (int i = 0; i < n; ++i)
{
for (int i = 0; i < n; ++i) {
Log.trace(F("Service %d %s found" CR), i, MDNS.hostname(i).c_str());
Log.trace(F("IP %s Port %d" CR), MDNS.IP(i).toString().c_str(), MDNS.port(i));
}
if (n == 1)
{
if (n == 1) {
Log.trace(F("One MQTT server found setting parameters" CR));
client.setServer(MDNS.IP(0), int(MDNS.port(0)));
}
else
{
} else {
Log.error(F("Several MQTT servers found, please deactivate mDNS and set your default server" CR));
}
}
}
#endif
void loop()
{
void loop() {
#ifndef ESPWifiManualSetup
# if defined(ESP8266) || defined(ESP32)
checkButton(); // check if a reset of wifi/mqtt settings is asked
@@ -1135,16 +1032,12 @@ void loop()
unsigned long now = millis();
#if defined(ESP8266) || defined(ESP32)
if (WiFi.status() == WL_CONNECTED)
{
if (WiFi.status() == WL_CONNECTED) {
#else
if ((Ethernet.hardwareStatus() != EthernetW5100 && Ethernet.linkStatus() == LinkON) || (Ethernet.hardwareStatus() == EthernetW5100))
{ //we are able to detect disconnection only on w5200 and w5500
if ((Ethernet.hardwareStatus() != EthernetW5100 && Ethernet.linkStatus() == LinkON) || (Ethernet.hardwareStatus() == EthernetW5100)) { //we are able to detect disconnection only on w5200 and w5500
#endif
failure_number_ntwk = 0;
if (client.connected())
{
if (client.connected()) {
#ifdef ZmqttDiscovery
if (!connectedOnce) pubMqttDiscovery(); // at first connection we publish the discovery payloads
#endif
@@ -1159,8 +1052,7 @@ void loop()
#endif
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
if (now > (timer_sys_measures + (TimeBetweenReadingSYS * 1000)) || !timer_sys_measures)
{
if (now > (timer_sys_measures + (TimeBetweenReadingSYS * 1000)) || !timer_sys_measures) {
timer_sys_measures = millis();
stateMeasures();
}
@@ -1239,14 +1131,10 @@ void loop()
#ifdef ZactuatorFASTLED
FASTLEDLoop();
#endif
}
else
{
} else {
connectMQTT();
}
}
else
{ // disconnected from network
} else { // disconnected from network
#if defined(ESP8266) || defined(ESP32)
Log.warning(F("wifi disconnected" CR));
delay(10000); // add a delay to avoid ESP32 crash and reset
@@ -1263,8 +1151,7 @@ void loop()
}
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
void stateMeasures()
{
void stateMeasures() {
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& SYSdata = jsonBuffer.createObject();
unsigned long uptime = millis() / 1000;
@@ -1389,8 +1276,7 @@ void stateMeasures()
}
#endif
void storeValue(unsigned long MQTTvalue)
{
void storeValue(unsigned long MQTTvalue) {
unsigned long now = millis();
// find oldest value of the buffer
int o = getMin();
@@ -1400,20 +1286,16 @@ void storeValue(unsigned long MQTTvalue)
ReceivedSignal[o][1] = now;
Log.trace(F("store code : %u / %u" CR), ReceivedSignal[o][0], ReceivedSignal[o][1]);
Log.trace(F("Col: val/timestamp" CR));
for (int i = 0; i < array_size; i++)
{
for (int i = 0; i < array_size; i++) {
Log.trace(F("mem code : %u / %u" CR), ReceivedSignal[i][0], ReceivedSignal[i][1]);
}
}
int getMin()
{
int getMin() {
unsigned int minimum = ReceivedSignal[0][1];
int minindex = 0;
for (int i = 0; i < array_size; i++)
{
if (ReceivedSignal[i][1] < minimum)
{
for (int i = 0; i < array_size; i++) {
if (ReceivedSignal[i][1] < minimum) {
minimum = ReceivedSignal[i][1];
minindex = i;
}
@@ -1421,17 +1303,13 @@ int getMin()
return minindex;
}
bool isAduplicate(unsigned long value)
{
bool isAduplicate(unsigned long value) {
Log.trace(F("isAdupl?" CR));
// check if the value has been already sent during the last time_avoid_duplicate
for (int i = 0; i < array_size; i++)
{
if (ReceivedSignal[i][0] == value)
{
for (int i = 0; i < array_size; i++) {
if (ReceivedSignal[i][0] == value) {
unsigned long now = millis();
if (now - ReceivedSignal[i][1] < time_avoid_duplicate)
{ // change
if (now - ReceivedSignal[i][1] < time_avoid_duplicate) { // change
Log.notice(F("no pub. dupl" CR));
return true;
}
@@ -1440,9 +1318,7 @@ bool isAduplicate(unsigned long value)
return false;
}
void receivingMQTT(char *topicOri, char *datacallback)
{
void receivingMQTT(char* topicOri, char* datacallback) {
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& jsondata = jsonBuffer.parseObject(datacallback);
@@ -1458,14 +1334,12 @@ void receivingMQTT(char *topicOri, char *datacallback)
data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
#endif
if (data != 0)
{
if (data != 0) {
storeValue(data);
}
}
if (jsondata.success())
{ // json object ok -> json decoding
if (jsondata.success()) { // json object ok -> json decoding
// log the received json
logJson(jsondata);
@@ -1510,9 +1384,7 @@ void receivingMQTT(char *topicOri, char *datacallback)
digitalWrite(led_send, HIGH);
MQTTtoSYS(topicOri, jsondata);
}
else
{ // not a json object --> simple decoding
} else { // not a json object --> simple decoding
#ifdef simpleReceiving
# ifdef ZgatewayLORA
MQTTtoLORA(topicOri, datacallback);
@@ -1549,32 +1421,24 @@ void receivingMQTT(char *topicOri, char *datacallback)
digitalWrite(led_send, HIGH);
}
void MQTTtoSYS(char *topicOri, JsonObject &SYSdata)
{ // json object decoding
if (cmpToMainTopic(topicOri,subjectMQTTtoSYSset))
{
void MQTTtoSYS(char* topicOri, JsonObject& SYSdata) { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoSYSset)) {
Log.trace(F("MQTTtoSYS json" CR));
#if defined(ESP8266) || defined(ESP32)
if (SYSdata.containsKey("cmd"))
{
if (SYSdata.containsKey("cmd")) {
const char* cmd = SYSdata["cmd"];
Log.notice(F("Command: %s" CR), cmd);
if (strstr(cmd, restartCmd) != NULL)
{ //restart
if (strstr(cmd, restartCmd) != NULL) { //restart
# if defined(ESP8266)
ESP.reset();
# else
ESP.restart();
# endif
}
else if (strstr(cmd, eraseCmd) != NULL)
{ //erase and restart
} else if (strstr(cmd, eraseCmd) != NULL) { //erase and restart
# ifndef ESPWifiManualSetup
setup_wifimanager(true);
# endif
}
else
{
} else {
Log.warning(F("wrong command" CR));
}
}