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
2020-06-09 23:09:23 +02:00
committed by GitHub
parent 661ef9c55e
commit 10a9d00aaf
59 changed files with 2892 additions and 3640 deletions

14
.clang-format Normal file
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
.editorconfig Normal file
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
.github/workflows/lint.yml vendored Normal file
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
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.pio
.vscode

View File

@@ -19,22 +19,21 @@
# 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"
directories:
- "~/.platformio"
install:
- pip install -U platformio
- platformio update
script:
script:
- sed -i 's/version_tag/'$TRAVIS_TAG'/g' main/User_config.h
- platformio run
- bash scripts/prepare_deploy.sh
@@ -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

View File

@@ -48,10 +48,10 @@
*/
/*-------------DEFINE GATEWAY NAME BELOW IT CAN ALSO BE DEFINED IN platformio.ini----------------*/
#ifndef Gateway_Name
#define Gateway_Name "OpenMQTTGateway"
# define Gateway_Name "OpenMQTTGateway"
#endif
#ifndef Gateway_Short_Name
#define Gateway_Short_Name "OMG"
# define Gateway_Short_Name "OMG"
#endif
#define Base_Topic "home/"
@@ -60,35 +60,35 @@
//#define NetworkAdvancedSetup true //uncomment if you want to set advanced network parameters for arduino boards, not uncommented you can set the IP and mac only
#ifdef NetworkAdvancedSetup // for arduino boards advanced config
#if defined(ESP8266)||defined(ESP32)
const byte ip[] = { 192, 168, 1, 99 }; //ip adress of the gateway, already defined for arduino below
#endif
const byte gateway[] = { 0, 0, 0, 0 };
const byte Dns[] = { 0, 0, 0, 0 };
const byte subnet[] = { 255, 255, 255, 0 };
# if defined(ESP8266) || defined(ESP32)
const byte ip[] = {192, 168, 1, 99}; //ip adress of the gateway, already defined for arduino below
# endif
const byte gateway[] = {0, 0, 0, 0};
const byte Dns[] = {0, 0, 0, 0};
const byte subnet[] = {255, 255, 255, 0};
#endif
#if defined(ESP8266)||defined(ESP32) // for nodemcu, weemos and esp8266
//#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP
#if defined(ESP8266) || defined(ESP32) // for nodemcu, weemos and esp8266
//#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP
#else // for arduino boards
const byte ip[] = { 192, 168, 1, 99 };
const byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95 }; //W5100 ethernet shield mac adress
const byte ip[] = {192, 168, 1, 99};
const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield mac adress
#endif
#if defined(ESPWifiManualSetup) // for nodemcu, weemos and esp8266
#define wifi_ssid "wifi ssid"
#define wifi_password "wifi password"
# define wifi_ssid "wifi ssid"
# define wifi_password "wifi password"
#endif
#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point
#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point
#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point
#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point
#define WifiManager_ConfigPortalTimeOut 120
#define WifiManager_TimeOut 5
#define WifiManager_TimeOut 5
/*-------------DEFINE YOUR ADVANCED NETWORK PARAMETERS BELOW----------------*/
//#define MDNS_SD //uncomment if you want to use mdns for discovering automatically your ip server, please note that MDNS with ESP32 can cause the BLE to not work
#define maxConnectionRetry 10 //maximum MQTT connection attempts before going to wifimanager setup if never connected once
#define maxConnectionRetryWifi 5 //maximum Wifi connection attempts with existing credential at start (used to bypass ESP32 issue on wifi connect)
#define maxConnectionRetry 10 //maximum MQTT connection attempts before going to wifimanager setup if never connected once
#define maxConnectionRetryWifi 5 //maximum Wifi connection attempts with existing credential at start (used to bypass ESP32 issue on wifi connect)
//set minimum quality of signal so it ignores AP's under that quality
#define MinimumWifiSignalQuality 8
@@ -97,11 +97,11 @@
//MQTT Parameters definition
//#define mqtt_server_name "www.mqtt_broker.com" // instead of defining the server by its IP you can define it by its name, uncomment this line and set the correct MQTT server host name
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
#define parameters_size 20
#define mqtt_topic_max_size 100
# define parameters_size 20
# define mqtt_topic_max_size 100
#else
#define parameters_size 15
#define mqtt_topic_max_size 50
# define parameters_size 15
# define mqtt_topic_max_size 50
#endif
char mqtt_user[parameters_size] = "your_username"; // not compulsory only if your broker needs authentication
char mqtt_pass[parameters_size] = "your_password"; // not compulsory only if your broker needs authentication
@@ -110,9 +110,9 @@ char mqtt_port[6] = "1883";
char mqtt_topic[mqtt_topic_max_size] = Base_Topic;
char gateway_name[parameters_size * 2] = Gateway_Name;
#if defined(ESP8266)||defined(ESP32)
#define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol
#define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol
#if defined(ESP8266) || defined(ESP32)
# define ATTEMPTS_BEFORE_BG 10 // Number of wifi connection attempts before going to BG protocol
# define ATTEMPTS_BEFORE_B 20 // Number of wifi connection attempts before going to B protocol
#endif
/*------------------DEEP SLEEP parameters ------------------*/
@@ -120,34 +120,34 @@ char gateway_name[parameters_size * 2] = Gateway_Name;
//DEFAULT_LOW_POWER_MODE 1 to activate deep sleep with LCD ON when a function is processing,
//DEFAULT_LOW_POWER_MODE 2 to activate deep sleep with LED ON when a function is processing (LCD is turned OFF)
#ifdef ESP32
#ifndef SLEEP_BUTTON
#define SLEEP_BUTTON 33
#endif
#ifndef DEFAULT_LOW_POWER_MODE
#define DEFAULT_LOW_POWER_MODE 0
#endif
#ifndef LOW_POWER_LED
#define LOW_POWER_LED 2
#endif
#ifndef LOW_POWER_LED_OFF
#define LOW_POWER_LED_OFF 1
#endif
# ifndef SLEEP_BUTTON
# define SLEEP_BUTTON 33
# endif
# ifndef DEFAULT_LOW_POWER_MODE
# define DEFAULT_LOW_POWER_MODE 0
# endif
# ifndef LOW_POWER_LED
# define LOW_POWER_LED 2
# endif
# ifndef LOW_POWER_LED_OFF
# define LOW_POWER_LED_OFF 1
# endif
int low_power_mode = DEFAULT_LOW_POWER_MODE;
#endif
// WIFI mode, uncomment to force a wifi mode, if not uncommented the ESP will connect without a mode forced
// if there is a reconnection issue it will try to connect with G mode and if not working with B mode
#ifdef ESP32
#include "esp_wifi.h"
uint8_t wifiProtocol = 0; // default mode, automatic selection
//uint8_t wifiProtocol = WIFI_PROTOCOL_11B;
//uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G; // can't have only one https://github.com/espressif/esp-idf/issues/702
//uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N; // can't have only one https://github.com/espressif/esp-idf/issues/702
# include "esp_wifi.h"
uint8_t wifiProtocol = 0; // default mode, automatic selection
//uint8_t wifiProtocol = WIFI_PROTOCOL_11B;
//uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G; // can't have only one https://github.com/espressif/esp-idf/issues/702
//uint8_t wifiProtocol = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N; // can't have only one https://github.com/espressif/esp-idf/issues/702
#elif ESP8266
uint8_t wifiProtocol = 0; // default mode, automatic selection
//uint8_t wifiProtocol = WIFI_PHY_MODE_11B;
//uint8_t wifiProtocol = WIFI_PHY_MODE_11G;
//uint8_t wifiProtocol = WIFI_PHY_MODE_11N;
uint8_t wifiProtocol = 0; // default mode, automatic selection
//uint8_t wifiProtocol = WIFI_PHY_MODE_11B;
//uint8_t wifiProtocol = WIFI_PHY_MODE_11G;
//uint8_t wifiProtocol = WIFI_PHY_MODE_11N;
#endif
/*-------------DEFINE THE MODULES YOU WANT BELOW----------------*/
@@ -183,11 +183,11 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE;
//#define ZradioCC1101 "CC1101" //ESP8266, ESP32
/*-------------DEFINE YOUR MQTT ADVANCED PARAMETERS BELOW----------------*/
#define version_Topic "/version"
#define will_Topic "/LWT"
#define will_QoS 0
#define will_Retain true
#define will_Message "offline"
#define version_Topic "/version"
#define will_Topic "/LWT"
#define will_QoS 0
#define will_Retain true
#define will_Message "offline"
#define Gateway_AnnouncementMsg "online"
#define jsonPublishing true //comment if you don't want to use Json publishing (one topic for all the parameters)
@@ -195,7 +195,7 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE;
#define jsonReceiving true //comment if you don't want to use Json reception analysis
//#define simplePublishing true //comment if you don't want to use simple publishing (one topic for one parameter)
//example
//example
// home/OpenMQTTGateway_ESP32_DEVKIT/BTtoMQTT/4XXXXXXXXXX4/rssi -63.0
// home/OpenMQTTGateway_ESP32_DEVKIT/BTtoMQTT/4XXXXXXXXXX4/servicedata fe0000000000000000000000000000000000000000
//#define simpleReceiving true //comment if you don't want to use old way reception analysis
@@ -203,49 +203,49 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE;
/*-------------DEFINE YOUR OTA PARAMETERS BELOW----------------*/
#define ota_hostname Gateway_Name
#define ota_password "OTAPASSWORD"
#define ota_port 8266
#define ota_port 8266
/*-------------DEFINE PINs FOR STATUS LEDs----------------*/
#ifndef led_receive
#ifdef ESP8266
#define led_receive 40
#elif ESP32
#define led_receive 40
#elif __AVR_ATmega2560__ //arduino mega
#define led_receive 40
#else //arduino uno/nano
#define led_receive 40
#endif
# ifdef ESP8266
# define led_receive 40
# elif ESP32
# define led_receive 40
# elif __AVR_ATmega2560__ //arduino mega
# define led_receive 40
# else //arduino uno/nano
# define led_receive 40
# endif
#endif
#ifndef led_send
#ifdef ESP8266
#define led_send 42
#elif ESP32
#define led_send 42
#elif __AVR_ATmega2560__ //arduino mega
#define led_send 42
#else //arduino uno/nano
#define led_send 42
#endif
# ifdef ESP8266
# define led_send 42
# elif ESP32
# define led_send 42
# elif __AVR_ATmega2560__ //arduino mega
# define led_send 42
# else //arduino uno/nano
# define led_send 42
# endif
#endif
#ifndef led_info
#ifdef ESP8266
#define led_info 44
#elif ESP32
#define led_info 44
#elif __AVR_ATmega2560__ //arduino mega
#define led_info 44
#else //arduino uno/nano
#define led_info 44
#endif
# ifdef ESP8266
# define led_info 44
# elif ESP32
# define led_info 44
# elif __AVR_ATmega2560__ //arduino mega
# define led_info 44
# else //arduino uno/nano
# define led_info 44
# endif
#endif
#ifndef TRIGGER_PIN
#ifdef ESP8266
#define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s)
#elif ESP32
#define TRIGGER_PIN 0 // boot button as full reset button (long press >10s)
#endif
# ifdef ESP8266
# define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s)
# elif ESP32
# define TRIGGER_PIN 0 // boot button as full reset button (long press >10s)
# endif
#endif
// VCC ------------D|-----------/\/\/\/\ ----------------- Arduino PIN
@@ -255,19 +255,19 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE;
/*-------------------CHANGING THEM IS NOT COMPULSORY-----------------------*/
/*----------------------------USER PARAMETERS-----------------------------*/
#ifdef ZgatewaySRFB
#define SERIAL_BAUD 19200
# define SERIAL_BAUD 19200
#else
#define SERIAL_BAUD 115200
# define SERIAL_BAUD 115200
#endif
/*--------------MQTT general topics-----------------*/
// global MQTT subject listened by the gateway to execute commands (send RF, IR or others)
#define subjectMQTTtoX "/commands/#"
#define subjectMultiGTWKey "toMQTT"
#define subjectGTWSendKey "MQTTto"
#define subjectMQTTtoX "/commands/#"
#define subjectMultiGTWKey "toMQTT"
#define subjectGTWSendKey "MQTTto"
// key used for launching commands to the gateway
#define restartCmd "restart"
#define eraseCmd "erase"
#define restartCmd "restart"
#define eraseCmd "erase"
// uncomment the line below to integrate msg value into the subject when receiving
//#define valueAsASubject true
@@ -276,16 +276,16 @@ int low_power_mode = DEFAULT_LOW_POWER_MODE;
#define time_avoid_duplicate 3000 // if you want to avoid duplicate mqtt message received set this to > 0, the value is the time in milliseconds during which we don't publish duplicates
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
#define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
#define ARDUINOJSON_USE_LONG_LONG 1
# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
# define ARDUINOJSON_USE_LONG_LONG 1
#else // boards with smaller memory
#define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
# define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
#endif
#define TimeBetweenReadingSYS 120 // time between (s) system readings (like memory)
#define TimeBeforeMQTTconnect 10 // time estimated (s) before the board is connected to MQTT
#define subjectSYStoMQTT "/SYStoMQTT"
#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config"
#define TimeBeforeMQTTconnect 10 // time estimated (s) before the board is connected to MQTT
#define subjectSYStoMQTT "/SYStoMQTT"
#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config"
/*-------------------DEFINE LOG LEVEL----------------------*/
#define LOG_LEVEL LOG_LEVEL_NOTICE

View File

@@ -24,10 +24,9 @@
#ifdef ZactuatorFASTLED
#include <FastLED.h>
# 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,87 +94,69 @@ void FASTLEDLoop()
FastLED.show();
}
boolean FASTLEDtoMQTT()
{
boolean FASTLEDtoMQTT() {
return false;
}
#ifdef jsonReceiving
void MQTTtoFASTLED(char *topicOri, JsonObject &jsonData)
{
# ifdef jsonReceiving
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);
const char *color = jsonData["hex"];
const char* color = jsonData["hex"];
Log.notice(F("Color hex: %s" CR), color);
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;
}
}
}
#endif
# endif
#ifdef simpleReceiving
void MQTTtoFASTLED(char *topicOri, char *datacallback)
{
# ifdef simpleReceiving
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;
}
}
}
#endif
# endif
// Fire2012 by Mark Kriegsman, July 2012
// as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
////
@@ -225,52 +188,44 @@ void MQTTtoFASTLED(char *topicOri, char *datacallback)
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames. More cooling = shorter flames.
// Default 55, suggested range 20-100
#define COOLING 55
# define COOLING 55
// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire. Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
#define SPARKING 120
# 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;

View File

@@ -30,37 +30,29 @@
#ifdef ZactuatorONOFF
#ifdef jsonReceiving
void MQTTtoONOFF(char *topicOri, JsonObject &ONOFFdata)
{
if (cmpToMainTopic(topicOri, subjectMQTTtoONOFF))
{
# ifdef jsonReceiving
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));
}
}
}
#endif
#ifdef simpleReceiving
void MQTTtoONOFF(char *topicOri, char *datacallback)
{
if ((cmpToMainTopic(topicOri, subjectMQTTtoONOFF)))
{
# endif
# ifdef simpleReceiving
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);
@@ -78,6 +70,6 @@ void MQTTtoONOFF(char *topicOri, char *datacallback)
pub(subjectGTWONOFFtoMQTT, &b);
}
}
#endif
# endif
#endif

View File

@@ -29,224 +29,201 @@
#include "User_config.h"
#if defined(ZboardM5STICKC) || defined(ZboardM5STACK)
#ifdef ZboardM5STICKC
#include <M5StickC.h>
#endif
#ifdef ZboardM5STACK
#include <M5Stack.h>
#endif
void logToLCD(bool display)
{
display ? Log.begin(LOG_LEVEL_LCD, &M5.Lcd) : Log.begin(LOG_LEVEL, &Serial); // Log on LCD following LOG_LEVEL_LCD
# ifdef ZboardM5STICKC
# include <M5StickC.h>
# endif
# ifdef ZboardM5STACK
# include <M5Stack.h>
# endif
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)
{
#ifdef ZboardM5STACK
M5.Lcd.setBrightness(brightness * 2);
#endif
#ifdef ZboardM5STICKC
(!brightness) ? M5.Axp.ScreenBreath(0) : M5.Axp.ScreenBreath(7 + (int)brightness * 0.08);
#endif
void setBrightness(int brightness) {
# ifdef ZboardM5STACK
M5.Lcd.setBrightness(brightness * 2);
# endif
# ifdef ZboardM5STICKC
(!brightness) ? M5.Axp.ScreenBreath(0) : M5.Axp.ScreenBreath(7 + (int)brightness * 0.08);
# endif
}
void setupM5()
{
Log.notice(F("Setup M5" CR));
pinMode(SLEEP_BUTTON, INPUT);
// M5 stack 320*240
// M5StickC 160*80
// M5Stick LCD not supported
Log.notice(F("Low power set to: %d" CR), low_power_mode);
switch (low_power_mode)// if LOW POWER the intro is bypassed and the brightness set to sleep brightness
{
case 0:
wakeScreen(NORMAL_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(WHITE);
displayIntro(M5.Lcd.width() * 0.25, (M5.Lcd.width() / 2) + M5.Lcd.width() * 0.12, (M5.Lcd.height()/2) + M5.Lcd.height() * 0.2);
#if LOG_TO_LCD
Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD
#endif
break;
case 1:
wakeScreen(SLEEP_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(WHITE);
#if LOG_TO_LCD
Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD
#endif
break;
case 2:
M5.begin(false,false,false);
break;
}
Log.notice(F("Setup M5 end" CR));
void setupM5() {
Log.notice(F("Setup M5" CR));
pinMode(SLEEP_BUTTON, INPUT);
// M5 stack 320*240
// M5StickC 160*80
// M5Stick LCD not supported
Log.notice(F("Low power set to: %d" CR), low_power_mode);
switch (low_power_mode) // if LOW POWER the intro is bypassed and the brightness set to sleep brightness
{
case 0:
wakeScreen(NORMAL_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(WHITE);
displayIntro(M5.Lcd.width() * 0.25, (M5.Lcd.width() / 2) + M5.Lcd.width() * 0.12, (M5.Lcd.height() / 2) + M5.Lcd.height() * 0.2);
# if LOG_TO_LCD
Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD
# endif
break;
case 1:
wakeScreen(SLEEP_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(WHITE);
# if LOG_TO_LCD
Log.begin(LOG_LEVEL_LCD, &M5.Lcd); // Log on LCD following LOG_LEVEL_LCD
# endif
break;
case 2:
M5.begin(false, false, false);
break;
}
Log.notice(F("Setup M5 end" CR));
}
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
#endif
#ifdef ZboardM5STICKC
M5.Axp.ScreenBreath(0);
M5.Axp.SetLDO2(false);
#endif
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
# endif
# ifdef ZboardM5STICKC
M5.Axp.ScreenBreath(0);
M5.Axp.SetLDO2(false);
# endif
}
void wakeScreen(int brightness)
{
Log.trace(F("Screen wake up" CR));
M5.begin();
M5.Lcd.setCursor(0, 0, (M5.Lcd.height() > 200) ? 4:2);
M5.Lcd.setTextSize(1);
M5.Lcd.setRotation(1);
setBrightness(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);
M5.Lcd.setTextSize(1);
M5.Lcd.setRotation(1);
setBrightness(brightness);
}
void loopM5()
{
static int previousBtnState;
int currentBtnState = digitalRead(SLEEP_BUTTON);
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())
{
void loopM5() {
static int previousBtnState;
int currentBtnState = digitalRead(SLEEP_BUTTON);
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()) {
case 1:
case 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;
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)
{
wakeScreen(NORMAL_LCD_BRIGHTNESS);
M5.Lcd.fillScreen(TFT_ORANGE); // WARNING
M5.Lcd.setTextColor(TFT_BLACK, TFT_ORANGE);
}
break;
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)
{
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);
}
break;
}
previousLogLevel = Log.getLastMsgLevel();
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);
}
break;
}
previousLogLevel = Log.getLastMsgLevel();
}
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"))
{
bool displayOnLCD = M5data["log-lcd"];
Log.notice(F("Set lcd log: %T" CR), displayOnLCD);
logToLCD(displayOnLCD);
}
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")) {
bool displayOnLCD = M5data["log-lcd"];
Log.notice(F("Set lcd log: %T" CR), displayOnLCD);
logToLCD(displayOnLCD);
}
}
}
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);
drawLogo(i, X, Y, false, false, true, false, false, false);
delay(50);
drawLogo(i, X, Y, false, true, false, false, false, false);
delay(50);
drawLogo(i, X, Y, false, true, true, false, false, false);
delay(50);
drawLogo(i, X, Y, false, true, true, true, false, false);
delay(50);
drawLogo(i, X, Y, false, true, true, false, true, false);
delay(50);
drawLogo(i, X, Y, false, true, true, true, true, false);
delay(50);
drawLogo(i, X, Y, true, true, true, true, true, false);
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);
drawLogo(i, X, Y, false, false, true, false, false, false);
delay(50);
drawLogo(i, X, Y, false, true, false, false, false, false);
delay(50);
drawLogo(i, X, Y, false, true, true, false, false, false);
delay(50);
drawLogo(i, X, Y, false, true, true, true, false, false);
delay(50);
drawLogo(i, X, Y, false, true, true, false, true, false);
delay(50);
drawLogo(i, X, Y, false, true, true, true, true, false);
delay(50);
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)
{
int circle1T = logoSize / 15;
int circle2T = logoSize / 25;
int circle3T = logoSize / 30;
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;
int circle3Y = circle1Y - (logoSize * 1.2);
int circle3X = circle1X - (logoSize * 0.13);
int circle2X = circle1X - (logoSize * 1.05);
int circle2Y = circle1Y - (logoSize * 0.8);
int circle3Y = circle1Y - (logoSize * 1.2);
int circle3X = circle1X - (logoSize * 0.13);
int circle2X = circle1X - (logoSize * 1.05);
int circle2Y = circle1Y - (logoSize * 0.8);
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);
M5.Lcd.drawLine(circle1X + 1, circle1Y, circle2X + 1, circle2Y, BLUE);
M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, BLUE);
M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE);
}
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);
M5.Lcd.drawLine(circle1X + 1, circle1Y, circle3X + 1, circle3Y, BLUE);
M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE);
}
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);
M5.Lcd.drawLine(circle1X + 1, circle1Y, circle2X + 1, circle2Y, BLUE);
M5.Lcd.drawLine(circle1X + 2, circle1Y, circle2X + 2, circle2Y, BLUE);
M5.Lcd.fillCircle(circle3X, circle3Y, logoSize / 4 - circle3T * 2, WHITE);
}
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);
M5.Lcd.drawLine(circle1X + 1, circle1Y, circle3X + 1, circle3Y, BLUE);
M5.Lcd.fillCircle(circle2X, circle2Y, logoSize / 3 - circle2T * 2, WHITE);
}
M5.Lcd.fillCircle(circle1X, circle1Y, logoSize / 2 - circle1T * 2, WHITE);
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 (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)
{
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)
{
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)
{
M5.Lcd.setTextColor(BLUE);
M5.Lcd.drawString("penMQTTGateway", circle1X + (circle1X * 0.27), circle1Y, (M5.Lcd.height() > 200) ? 4:2);
}
}
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) {
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) {
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)
{
if (low_power_mode == 2) digitalWrite(LOW_POWER_LED, 1 - LOW_POWER_LED_OFF);
wakeScreen(NORMAL_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);
M5.Lcd.setTextColor(BLUE);
M5.Lcd.drawString(line1, 5, M5.Lcd.height() * 0.7, 1);
M5.Lcd.drawString(line2, 5, M5.Lcd.height() * 0.8, 1);
M5.Lcd.drawString(line3, 5, M5.Lcd.height() * 0.9, 1);
delay(2000);
digitalWrite(LOW_POWER_LED, LOW_POWER_LED_OFF); // to switch off no need of condition
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);
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);
M5.Lcd.setTextColor(BLUE);
M5.Lcd.drawString(line1, 5, M5.Lcd.height() * 0.7, 1);
M5.Lcd.drawString(line2, 5, M5.Lcd.height() * 0.8, 1);
M5.Lcd.drawString(line3, 5, M5.Lcd.height() * 0.9, 1);
delay(2000);
digitalWrite(LOW_POWER_LED, LOW_POWER_LED_OFF); // to switch off no need of condition
}
#endif

View File

@@ -29,8 +29,8 @@
#ifdef Zgateway2G
#include <ArduinoJson.h>
#include <A6lib.h> // library for controling A6 or A7 module
# 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,45 +57,37 @@ 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++)
{
JsonObject& SMSdata = jsonBuffer.createObject();
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());
SMSdata.set("date", (char *)sms.date.c_str());
SMSdata.set("phone", (char *)sms.number.c_str());
SMSdata.set("message", (char*)sms.message.c_str());
SMSdata.set("date", (char*)sms.date.c_str());
SMSdata.set("phone", (char*)sms.number.c_str());
A6l.deleteSMS(unreadSMSLocs[i]); // we delete the SMS received
Log.trace(F("Adv data 2GtoMQTT" CR));
pub(subject2GtoMQTT, SMSdata);
@@ -105,76 +95,58 @@ bool _2GtoMQTT()
}
return false;
}
#ifdef simpleReceiving
void MQTTto2G(char *topicOri, char *datacallback)
{
# ifdef simpleReceiving
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)
{
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) {
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));
}
}
}
#endif
# endif
#ifdef jsonReceiving
void MQTTto2G(char *topicOri, JsonObject &SMSdata)
{
if (cmpToMainTopic(topicOri, subjectMQTTto2G))
{
const char *sms = SMSdata["message"];
const char *phone = SMSdata["phone"];
# ifdef jsonReceiving
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)
{
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 (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) {
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));
}
}
}
#endif
# endif
#endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -29,17 +29,15 @@
#ifdef ZgatewayLORA
#include <SPI.h>
#include <LoRa.h>
#include <Wire.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,46 +52,40 @@ 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();
JsonObject& LORAdata = jsonBuffer.createObject();
Log.trace(F("Rcv. LORA" CR));
#ifdef ESP32
# ifdef ESP32
String taskMessage = "LORA Task running on core ";
taskMessage = taskMessage + xPortGetCoreID();
//trc(taskMessage);
#endif
# 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());
LORAdata.set("snr", (float)LoRa.packetSnr());
LORAdata.set("pferror", (float)LoRa.packetFrequencyError());
LORAdata.set("packetSize", (int)packetSize);
LORAdata.set("message", (char *)packet.c_str());
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);
}
}
}
#ifdef jsonReceiving
void MQTTtoLORA(char *topicOri, JsonObject &LORAdata)
{ // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoLORA))
{
# ifdef jsonReceiving
void MQTTtoLORA(char* topicOri, JsonObject& LORAdata) { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) {
Log.trace(F("MQTTtoLORA json" CR));
const char *message = LORAdata["message"];
const char* message = LORAdata["message"];
int txPower = LORAdata["txpower"] | LORA_TX_POWER;
int spreadingFactor = LORAdata["spreadingfactor"] | LORA_SPREADING_FACTOR;
long int frequency = LORAdata["frequency "] | LORA_BAND;
@@ -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))
{
# endif
# ifdef simpleReceiving
void MQTTtoLORA(char* topicOri, char* LORAdata) { // json object decoding
if (cmpToMainTopic(topicOri, subjectMQTTtoLORA)) {
LoRa.beginPacket();
LoRa.print(LORAdata);
LoRa.endPacket();
@@ -138,5 +125,5 @@ void MQTTtoLORA(char *topicOri, char *LORAdata)
pub(subjectGTWLORAtoMQTT, LORAdata); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}
#endif
# endif
#endif

View File

@@ -29,149 +29,129 @@
#ifdef ZgatewayPilight
#ifdef ZradioCC1101
#include <ELECHOUSE_CC1101_SRC_DRV.h>
#endif
# ifdef ZradioCC1101
# include <ELECHOUSE_CC1101_SRC_DRV.h>
# endif
#include <ESPiLight.h>
# include <ESPiLight.h>
ESPiLight rf(RF_EMITTER_PIN); // use -1 to disable transmitter
void pilightCallback(const String &protocol, const String &message, int status,
size_t repeats, const String &deviceID)
{
if (status == VALID)
{
void pilightCallback(const String& protocol, const String& message, int status,
size_t repeats, const String& deviceID) {
if (status == VALID) {
Log.trace(F("Creating RF PiLight buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &RFPiLightdata = jsonBuffer.createObject();
JsonObject& RFPiLightdata = jsonBuffer.createObject();
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer2;
JsonObject &msg = jsonBuffer2.parseObject(message);
JsonObject& msg = jsonBuffer2.parseObject(message);
RFPiLightdata.set("message", msg);
RFPiLightdata.set("protocol", (char *)protocol.c_str());
RFPiLightdata.set("length", (char *)deviceID.c_str());
RFPiLightdata.set("protocol", (char*)protocol.c_str());
RFPiLightdata.set("length", (char*)deviceID.c_str());
RFPiLightdata.set("repeats", (int)repeats);
RFPiLightdata.set("status", (int)status);
pub(subjectPilighttoMQTT, RFPiLightdata);
if (repeatPilightwMQTT)
{
if (repeatPilightwMQTT) {
Log.trace(F("Pub Pilight for rpt" CR));
pub(subjectMQTTtoPilight, RFPiLightdata);
}
}
}
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();
ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY);
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
rf.enableReceiver();
#endif
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();
ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY);
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
rf.enableReceiver();
# endif
rf.setCallback(pilightCallback);
rf.initReceiver(RF_RECEIVER_PIN);
pinMode(RF_EMITTER_PIN, OUTPUT); // Set this here, because if this is the RX pin it was reset to INPUT by Serial.end();
Log.notice(F("RF_EMITTER_PIN: %d " CR), RF_EMITTER_PIN);
Log.notice(F("RF_RECEIVER_PIN: %d " CR), RF_RECEIVER_PIN);
Log.trace(F("ZgatewayPilight setup done " CR));
#else
# else
Log.trace(F("ZgatewayPilight setup cannot be done, comment first ZgatewayRF && ZgatewayRF2" CR));
#endif
# endif
}
void PilighttoMQTT()
{
void PilighttoMQTT() {
rf.loop();
}
void MQTTtoPilight(char *topicOri, JsonObject &Pilightdata)
{
#ifdef ZradioCC1101
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
rf.disableReceiver();
#endif
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)
{
const char* message = Pilightdata["message"];
const char* protocol = Pilightdata["protocol"];
const char* raw = Pilightdata["raw"];
if (raw) {
int msgLength = 0;
uint16_t codes[MAXPULSESTREAMLENGTH];
msgLength = rf.stringToPulseTrain(
raw,
codes, MAXPULSESTREAMLENGTH);
if (msgLength > 0)
{
if (msgLength > 0) {
rf.sendPulseTrain(codes, msgLength);
Log.notice(F("MQTTtoPilight raw ok" CR));
result = msgLength;
}
else
{
} else {
Log.trace(F("MQTTtoPilight raw KO" CR));
switch (result)
{
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C:
Log.trace(F("'c' not found in string, or has no data" CR));
break;
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P:
Log.trace(F("'p' not found in string, or has no data" CR));
break;
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END:
Log.trace(F("';' or '@' not found in data string" CR));
break;
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE:
Log.trace(F("pulse type not defined" CR));
break;
switch (result) {
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_C:
Log.trace(F("'c' not found in string, or has no data" CR));
break;
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_P:
Log.trace(F("'p' not found in string, or has no data" CR));
break;
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_END:
Log.trace(F("';' or '@' not found in data string" CR));
break;
case ESPiLight::ERROR_INVALID_PULSETRAIN_MSG_TYPE:
Log.trace(F("pulse type not defined" CR));
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)
{
case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL:
Log.error(F("protocol is not available" CR));
break;
case ESPiLight::ERROR_INVALID_PILIGHT_MSG:
Log.error(F("message is invalid" CR));
break;
case ESPiLight::ERROR_INVALID_JSON:
Log.error(F("message is not a proper json object" CR));
break;
case ESPiLight::ERROR_NO_OUTPUT_PIN:
Log.error(F("no transmitter pin" CR));
break;
default:
Log.error(F("invalid json data, can't read raw or message/protocol" CR));
break;
} else {
switch (result) {
case ESPiLight::ERROR_UNAVAILABLE_PROTOCOL:
Log.error(F("protocol is not available" CR));
break;
case ESPiLight::ERROR_INVALID_PILIGHT_MSG:
Log.error(F("message is invalid" CR));
break;
case ESPiLight::ERROR_INVALID_JSON:
Log.error(F("message is not a proper json object" CR));
break;
case ESPiLight::ERROR_NO_OUTPUT_PIN:
Log.error(F("no transmitter pin" CR));
break;
default:
Log.error(F("invalid json data, can't read raw or message/protocol" CR));
break;
}
}
}
#ifdef ZradioCC1101
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on
rf.enableReceiver();
#endif
# ifdef ZradioCC1101
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on
rf.enableReceiver();
# endif
}
#endif

View File

@@ -29,61 +29,55 @@
#ifdef ZgatewayRF
#ifdef ZradioCC1101
#include <ELECHOUSE_CC1101_SRC_DRV.h>
#endif
# ifdef ZradioCC1101
# include <ELECHOUSE_CC1101_SRC_DRV.h>
# endif
#include <RCSwitch.h> // library for controling Radio frequency switch
# include <RCSwitch.h> // library for controling Radio frequency switch
RCSwitch mySwitch = RCSwitch();
#ifdef ZmqttDiscovery
void RFtoMQTTdiscovery(unsigned long MQTTvalue)
{ //on the fly switch creation from received RF values
# ifdef ZmqttDiscovery
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));
char *switchRF[8] = {"switch", val, "", "", "", val, "", ""};
char* switchRF[8] = {"switch", val, "", "", "", val, "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySwitch: %s" CR),switchRF[1]);
Log.trace(F("CreateDiscoverySwitch: %s" CR), switchRF[1]);
createDiscovery(switchRF[0],
subjectRFtoMQTT, switchRF[1], (char *)getUniqueId(switchRF[1], switchRF[2]).c_str(),
subjectRFtoMQTT, switchRF[1], (char*)getUniqueId(switchRF[1], switchRF[2]).c_str(),
will_Topic, switchRF[3], switchRF[4],
switchRF[5], switchRF[6], switchRF[7],
0, "", "", true, subjectMQTTtoRF);
}
#endif
void setupRF()
{
# endif
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);
#ifdef ZradioCC1101 //receiving with CC1101
ELECHOUSE_cc1101.Init();
ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY);
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
#endif
# ifdef ZradioCC1101 //receiving with CC1101
ELECHOUSE_cc1101.Init();
ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY);
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
# endif
mySwitch.enableTransmit(RF_EMITTER_PIN);
mySwitch.setRepeatTransmit(RF_EMITTER_REPEAT);
mySwitch.enableReceive(RF_RECEIVER_PIN);
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();
JsonObject& RFdata = jsonBuffer.createObject();
Log.trace(F("Rcv. RF" CR));
#ifdef ESP32
Log.trace(F("RF Task running on core :%d" CR),xPortGetCoreID());
#endif
# ifdef ESP32
Log.trace(F("RF Task running on core :%d" CR), xPortGetCoreID());
# endif
RFdata.set("value", (unsigned long)mySwitch.getReceivedValue());
RFdata.set("protocol", (int)mySwitch.getReceivedProtocol());
RFdata.set("length", (int)mySwitch.getReceivedBitlength());
@@ -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
#ifdef ZmqttDiscovery //component creation for HA
if (!isAduplicate(MQTTvalue) && MQTTvalue != 0) { // conditions to avoid duplications of RF -->MQTT
# ifdef ZmqttDiscovery //component creation for HA
RFtoMQTTdiscovery(MQTTvalue);
#endif
# 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);
}
@@ -108,15 +100,13 @@ void RFtoMQTT()
}
}
#ifdef simpleReceiving
void MQTTtoRF(char *topicOri, char *datacallback)
{
#ifdef ZradioCC1101 // set Receive off and Transmitt on
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY);
mySwitch.disableReceive();
mySwitch.enableTransmit(RF_EMITTER_PIN);
#endif
# ifdef simpleReceiving
void MQTTtoRF(char* topicOri, char* datacallback) {
# ifdef ZradioCC1101 // set Receive off and Transmitt on
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY);
mySwitch.disableReceive();
mySwitch.enableTransmit(RF_EMITTER_PIN);
# endif
unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295
// RF DATA ANALYSIS
@@ -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;
@@ -170,28 +154,25 @@ void MQTTtoRF(char *topicOri, char *datacallback)
// Acknowledgement to the GTWRF topic
pub(subjectGTWRFtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
#ifdef ZradioCC1101 // set Receive on and Transmitt off
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
mySwitch.disableTransmit();
mySwitch.enableReceive(RF_RECEIVER_PIN);
#endif
# ifdef ZradioCC1101 // set Receive on and Transmitt off
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
mySwitch.disableTransmit();
mySwitch.enableReceive(RF_RECEIVER_PIN);
# endif
}
#endif
# endif
#ifdef jsonReceiving
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))
{
# ifdef jsonReceiving
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)) {
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;
@@ -203,19 +184,17 @@ void MQTTtoRF(char *topicOri, JsonObject &RFdata)
mySwitch.setProtocol(valuePRT, valuePLSL);
mySwitch.send(data, valueBITS);
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
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));
}
}
#ifdef ZradioCC1101 // set Receive on and Transmitt off
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
mySwitch.disableTransmit();
mySwitch.enableReceive(RF_RECEIVER_PIN);
#endif
# ifdef ZradioCC1101 // set Receive on and Transmitt off
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
mySwitch.disableTransmit();
mySwitch.enableReceive(RF_RECEIVER_PIN);
# endif
}
#endif
# endif
#endif

View File

@@ -37,15 +37,14 @@ sudo mosquitto_pub -t home/commands/MQTTtoRF2/CODE_8233372/UNIT_0/PERIOD_272 -m/
#ifdef ZgatewayRF2
#ifdef ZradioCC1101
#include <ELECHOUSE_CC1101_SRC_DRV.h>
#endif
# ifdef ZradioCC1101
# include <ELECHOUSE_CC1101_SRC_DRV.h>
# endif
#include <NewRemoteTransmitter.h>
#include <NewRemoteReceiver.h>
# include <NewRemoteReceiver.h>
# include <NewRemoteTransmitter.h>
struct RF2rxd
{
struct RF2rxd {
unsigned int period;
unsigned long address;
unsigned long groupBit;
@@ -56,32 +55,28 @@ struct RF2rxd
RF2rxd rf2rd;
void setupRF2()
{
#ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF
#ifdef ZradioCC1101 //receiving with CC1101
ELECHOUSE_cc1101.Init();
ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY);
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
#endif
void setupRF2() {
# ifndef ZgatewayRF //receiving with RF2 is not compatible with ZgatewayRF
# ifdef ZradioCC1101 //receiving with CC1101
ELECHOUSE_cc1101.Init();
ELECHOUSE_cc1101.setMHZ(CC1101_FREQUENCY);
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY);
# endif
NewRemoteReceiver::init(RF_RECEIVER_PIN, 2, rf2Callback);
Log.notice(F("RF_EMITTER_PIN: %d " CR), RF_EMITTER_PIN);
Log.notice(F("RF_RECEIVER_PIN: %d " CR), RF_RECEIVER_PIN);
Log.trace(F("ZgatewayRF2 setup done " CR));
#endif
# endif
pinMode(RF_EMITTER_PIN, OUTPUT);
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;
JsonObject &RF2data = jsonBuffer.createObject();
JsonObject& RF2data = jsonBuffer.createObject();
rf2rd.hasNewData = false;
@@ -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;
@@ -107,13 +100,12 @@ void rf2Callback(unsigned int period, unsigned long address, unsigned long group
rf2rd.hasNewData = true;
}
#ifdef simpleReceiving
void MQTTtoRF2(char *topicOri, char *datacallback)
{
#ifdef ZradioCC1101
NewRemoteReceiver::disable();
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
#endif
# ifdef simpleReceiving
void MQTTtoRF2(char* topicOri, char* datacallback) {
# ifdef ZradioCC1101
NewRemoteReceiver::disable();
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
# endif
// RF DATA ANALYSIS
//We look into the subject to see if a special RF protocol is defined
@@ -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);
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,38 +195,32 @@ 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
{
pub((char*)MQTTRF2string.c_str(), (char*)MQTTdimLevel.c_str());
} else {
MQTTRF2string = subjectRF2toMQTT + String("/") + RF2codeKey + MQTTAddress + String("/") + RF2unitKey + MQTTunit + String("/") + RF2groupKey + MQTTgroupBit + String("/") + RF2periodKey + MQTTperiod;
pub((char *)MQTTRF2string.c_str(), (char *)MQTTswitchType.c_str());
pub((char*)MQTTRF2string.c_str(), (char*)MQTTswitchType.c_str());
}
}
#ifdef ZradioCC1101
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on
NewRemoteReceiver::enable();
#endif
# ifdef ZradioCC1101
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on
NewRemoteReceiver::enable();
# endif
}
#endif
# endif
#ifdef jsonReceiving
void MQTTtoRF2(char *topicOri, JsonObject &RF2data)
{ // json object decoding
#ifdef ZradioCC1101
NewRemoteReceiver::disable();
ELECHOUSE_cc1101.SetTx(CC1101_FREQUENCY); // set Transmit on
#endif
# ifdef jsonReceiving
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,16 +258,14 @@ 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));
}
}
#ifdef ZradioCC1101
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on
NewRemoteReceiver::enable();
#endif
# ifdef ZradioCC1101
ELECHOUSE_cc1101.SetRx(CC1101_FREQUENCY); // set Receive on
NewRemoteReceiver::enable();
# endif
}
#endif
# endif
#endif

View File

@@ -32,16 +32,15 @@
#ifdef ZgatewayRFM69
#include <RFM69.h> //https://www.github.com/lowpowerlab/rfm69
#include <SPI.h>
#include <EEPROM.h>
# include <EEPROM.h>
# include <RFM69.h> //https://www.github.com/lowpowerlab/rfm69
# include <SPI.h>
char RadioConfig[128];
// vvvvvvvvv Global Configuration vvvvvvvvvvv
struct _GLOBAL_CONFIG
{
struct _GLOBAL_CONFIG {
uint32_t checksum;
char rfmapname[32];
char encryptkey[16 + 1];
@@ -51,33 +50,29 @@ struct _GLOBAL_CONFIG
uint8_t rfmfrequency;
};
#define GC_POWER_LEVEL (pGC->powerlevel & 0x1F)
#define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0)
#define SELECTED_FREQ(f) ((pGC->rfmfrequency == f) ? "selected" : "")
# define GC_POWER_LEVEL (pGC->powerlevel & 0x1F)
# define GC_IS_RFM69HCW ((pGC->powerlevel & 0x80) != 0)
# define SELECTED_FREQ(f) ((pGC->rfmfrequency == f) ? "selected" : "")
struct _GLOBAL_CONFIG *pGC;
struct _GLOBAL_CONFIG* pGC;
// vvvvvvvvv Global Configuration vvvvvvvvvvv
uint32_t gc_checksum()
{
uint8_t *p = (uint8_t *)pGC;
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()
{
# if defined(ESP8266) || defined(ESP32)
void eeprom_setup() {
EEPROM.begin(4096);
pGC = (struct _GLOBAL_CONFIG *)EEPROM.getDataPtr();
pGC = (struct _GLOBAL_CONFIG*)EEPROM.getDataPtr();
// if checksum bad init GC else use GC values
if (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);
@@ -90,15 +85,14 @@ void eeprom_setup()
EEPROM.commit();
}
}
#endif
# endif
RFM69 radio;
void setupRFM69(void)
{
#if defined(ESP8266) || defined(ESP32)
void setupRFM69(void) {
# if defined(ESP8266) || defined(ESP32)
eeprom_setup();
#endif
# endif
int freq;
static const char PROGMEM JSONtemplate[] =
R"({"msgType":"config","freq":%d,"rfm69hcw":%d,"netid":%d,"power":%d})";
@@ -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,141 +113,118 @@ void setupRFM69(void)
if (pGC->encryptkey[0] != '\0')
radio.encrypt(pGC->encryptkey);
switch (pGC->rfmfrequency)
{
case RF69_433MHZ:
freq = 433;
break;
case RF69_868MHZ:
freq = 868;
break;
case RF69_915MHZ:
freq = 915;
break;
case RF69_315MHZ:
freq = 315;
break;
default:
freq = -1;
break;
switch (pGC->rfmfrequency) {
case RF69_433MHZ:
freq = 433;
break;
case RF69_868MHZ:
freq = 868;
break;
case RF69_915MHZ:
freq = 915;
break;
case RF69_315MHZ:
freq = 315;
break;
default:
freq = -1;
break;
}
Log.notice(F("ZgatewayRFM69 Listening and transmitting at: %d" CR), freq);
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();
JsonObject& RFM69data = jsonBuffer.createObject();
uint8_t data[RF69_MAX_DATA_LEN + 1]; // For the null character
uint8_t SENDERID = radio.SENDERID;
uint8_t DATALEN = radio.DATALEN;
uint16_t RSSI = radio.RSSI;
//save packet because it may be overwritten
memcpy(data, (void *)radio.DATA, DATALEN);
memcpy(data, (void*)radio.DATA, DATALEN);
data[DATALEN] = '\0'; // Terminate the string
// 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);
Log.trace(F("Data received: %s" CR), (const char *)data);
Log.trace(F("Data received: %s" CR), (const char*)data);
char buff[sizeof(subjectRFM69toMQTT) + 4];
sprintf(buff, "%s/%d", subjectRFM69toMQTT, SENDERID);
RFM69data.set("data", (char *)data);
RFM69data.set("data", (char*)data);
RFM69data.set("rssi", (int)radio.RSSI);
RFM69data.set("senderid", (int)radio.SENDERID);
pub(buff, RFM69data);
return true;
}
else
{
} else {
return false;
}
}
#ifdef simpleReceiving
void MQTTtoRFM69(char *topicOri, char *datacallback)
{
if (cmpToMainTopic(topicOri, subjectMQTTtoRFM69))
{
# ifdef simpleReceiving
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);
memcpy(data, (void*)datacallback, RF69_MAX_DATA_LEN);
data[RF69_MAX_DATA_LEN] = '\0';
//We look into the subject to see if a special RF protocol is defined
String topic = topicOri;
int valueRCV = defaultRFM69ReceiverId; //default receiver id value
int pos = topic.lastIndexOf(RFM69receiverKey);
if (pos != -1)
{
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))
{
const char *data = RFM69data["data"];
# endif
# ifdef jsonReceiving
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));
}
}
}
#endif
# endif
#endif

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);
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,14 +98,13 @@ 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));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &SRFBdata = jsonBuffer.createObject();
SRFBdata.set("raw", (char *)buffer);
JsonObject& SRFBdata = jsonBuffer.createObject();
SRFBdata.set("raw", (char*)buffer);
char Tsyn[4] = {0};
extract_char(buffer, Tsyn, 0, 4, false, true);
@@ -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)
{
# ifdef simpleReceiving
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);
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);
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);
@@ -306,29 +269,22 @@ void MQTTtoSRFB(char *topicOri, char *datacallback)
pub(subjectGTWSRFBtoMQTT, datacallback); // we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}
#endif
#ifdef jsonReceiving
void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata)
{
# endif
# ifdef jsonReceiving
void MQTTtoSRFB(char* topicOri, JsonObject& SRFBdata) {
// RF DATA ANALYSIS
const char *raw = SRFBdata["raw"];
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"];
@@ -343,8 +299,8 @@ void MQTTtoSRFB(char *topicOri, JsonObject &SRFBdata)
if (valueSYNC == 0)
valueSYNC = 9500;
Log.notice(F("SRFB Repeat: %d" CR),valueRPT);
Log.notice(F("RF Mini Pulse Lgth: %d" CR),valueMiniPLSL);
Log.notice(F("SRFB Repeat: %d" CR), valueRPT);
Log.notice(F("RF Mini Pulse Lgth: %d" CR), valueMiniPLSL);
Log.notice(F("RF Maxi Pulse Lgth: %d" CR), valueMaxiPLSL);
Log.notice(F("RF sync: %d" CR), valueSYNC);
@@ -376,13 +332,11 @@ 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));
}
}
}
}
#endif
# endif
#endif

View File

@@ -26,42 +26,38 @@
#include "User_config.h"
#ifdef ZgatewayWeatherStation
#include <WeatherStationDataRx.h>
# include <WeatherStationDataRx.h>
WeatherStationDataRx wsdr(RF_WS_RECEIVER_PIN, true);
void PairedDeviceAdded(byte newID)
{
#if defined(ESP8266) || defined(ESP32)
Serial.printf("ZgatewayWeatherStation: New device paired %d\r\n", newID);
#else
Serial.print("ZgatewayWeatherStation: New device paired ");
Serial.println(newID, DEC);
#endif
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(2);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &RFdata = jsonBuffer.createObject();
RFdata.set("sensor", newID);
RFdata.set("action", "paired");
pub(subjectRFtoMQTT, RFdata);
wsdr.pair(NULL, PairedDeviceAdded);
void PairedDeviceAdded(byte newID) {
# if defined(ESP8266) || defined(ESP32)
Serial.printf("ZgatewayWeatherStation: New device paired %d\r\n", newID);
# else
Serial.print("ZgatewayWeatherStation: New device paired ");
Serial.println(newID, DEC);
# endif
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(2);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
RFdata.set("sensor", newID);
RFdata.set("action", "paired");
pub(subjectRFtoMQTT, RFdata);
wsdr.pair(NULL, PairedDeviceAdded);
}
void setupWeatherStation()
{
Log.notice(F("RF_WS_RECEIVER_PIN %d" CR),RF_WS_RECEIVER_PIN);
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();
JsonObject& RFdata = jsonBuffer.createObject();
RFdata.set("sensor", id);
RFdata.set("wind_speed", wind_speed);
RFdata.set("battery", bitRead(battery_status, 0) == 0 ? "OK" : "Low");
@@ -71,14 +67,12 @@ 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();
JsonObject& RFdata = jsonBuffer.createObject();
RFdata.set("sensor", id);
RFdata.set("rain_volume", rain_volume);
RFdata.set("battery", bitRead(battery_status, 1) == 0 ? "OK" : "Low");
@@ -88,14 +82,12 @@ 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();
JsonObject& RFdata = jsonBuffer.createObject();
RFdata.set("sensor", id);
RFdata.set("wind_direction", wind_direction);
RFdata.set("wind_gust", wind_gust);
@@ -106,14 +98,12 @@ 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();
JsonObject& RFdata = jsonBuffer.createObject();
RFdata.set("sensor", id);
RFdata.set("temperature", temperature);
RFdata.set("humidity", humidity);
@@ -121,38 +111,35 @@ void sendTemperatureData(byte id, float temperature, int humidity, byte battery_
pub(subjectRFtoMQTT, RFdata);
Log.trace(F("Store temp val: %lu" CR), MQTTvalue);
storeValue(MQTTvalue);
}
}
}
void ZgatewayWeatherStationtoMQTT()
{
void ZgatewayWeatherStationtoMQTT() {
char newData = wsdr.readData();
switch (newData)
{
case 'T':
Log.trace(F("Temperature" CR));
sendTemperatureData(wsdr.sensorID(), wsdr.readTemperature(), wsdr.readHumidity(), wsdr.batteryStatus());
break;
switch (newData) {
case 'T':
Log.trace(F("Temperature" CR));
sendTemperatureData(wsdr.sensorID(), wsdr.readTemperature(), wsdr.readHumidity(), wsdr.batteryStatus());
break;
case 'S':
Log.trace(F("Wind speed" CR));
sendWindSpeedData(wsdr.sensorID(), wsdr.readWindSpeed(), wsdr.batteryStatus());
break;
case 'S':
Log.trace(F("Wind speed" CR));
sendWindSpeedData(wsdr.sensorID(), wsdr.readWindSpeed(), wsdr.batteryStatus());
break;
case 'G':
Log.trace(F("Wind direction" CR));
sendWindData(wsdr.sensorID(), wsdr.readWindDirection(), wsdr.readWindGust(), wsdr.batteryStatus());
break;
case 'G':
Log.trace(F("Wind direction" CR));
sendWindData(wsdr.sensorID(), wsdr.readWindDirection(), wsdr.readWindGust(), wsdr.batteryStatus());
break;
case 'R':
Log.trace(F("Rain volume" CR));
sendRainData(wsdr.sensorID(), wsdr.readRainVolume(), wsdr.batteryStatus());
break;
case 'R':
Log.trace(F("Rain volume" CR));
sendRainData(wsdr.sensorID(), wsdr.readRainVolume(), wsdr.batteryStatus());
break;
default:
break;
default:
break;
}
}
#endif

View File

@@ -27,62 +27,57 @@
#ifdef ZmqttDiscovery
String getMacAddress()
{
String getMacAddress() {
uint8_t baseMac[6];
char baseMacChr[13] = {0};
#if defined(ESP8266)
# if defined(ESP8266)
WiFi.macAddress(baseMac);
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#elif defined(ESP32)
# elif defined(ESP32)
esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
#else
# else
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
#endif
# endif
return String(baseMacChr);
}
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++)
{
Log.trace(F("CreateDiscoverySensor %s" CR),sensorList[i][1]);
# ifdef ZgatewayBT
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];
createDiscovery(sensorList[i][0],
(char *)discovery_topic.c_str(), sensorList[i][1], (char *)unique_id.c_str(),
(char*)discovery_topic.c_str(), sensorList[i][1], (char*)unique_id.c_str(),
will_Topic, sensorList[i][3], sensorList[i][4],
sensorList[i][5], sensorList[i][6], sensorList[i][7],
0, "", "", false, "");
}
}
#endif
# endif
void createDiscovery(char *sensor_type,
char *st_topic, char *s_name, char *unique_id,
char *availability_topic, char *device_class, char *value_template,
char *payload_on, char *payload_off, char *unit_of_meas,
void createDiscovery(char* sensor_type,
char* st_topic, char* s_name, char* unique_id,
char* availability_topic, char* device_class, char* value_template,
char* payload_on, char* payload_off, char* unit_of_meas,
int off_delay,
char *payload_available, char *payload_not_avalaible, bool child_device, char *cmd_topic)
{
char* payload_available, char* payload_not_avalaible, bool child_device, char* cmd_topic) {
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(5) + JSON_ARRAY_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &sensor = jsonBuffer.createObject();
JsonObject& sensor = jsonBuffer.createObject();
char state_topic[mqtt_topic_max_size];
strcpy(state_topic, mqtt_topic);
strcat(state_topic, st_topic);
sensor.set("stat_t", state_topic); //state_topic
sensor.set("name", s_name); //name
sensor.set("name", s_name); //name
sensor.set("uniq_id", unique_id); //unique_id
if (device_class[0])
sensor.set("dev_cla", device_class); //device_class
@@ -101,58 +96,55 @@ 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();
JsonObject& device = jsonDeviceBuffer.createObject();
device.set("name", gateway_name);
device.set("manufacturer", DEVICEMANUFACTURER);
device.set("sw_version", OMG_VERSION);
JsonArray &identifiers = device.createNestedArray("identifiers");
JsonArray& identifiers = device.createNestedArray("identifiers");
identifiers.add(getMacAddress());
sensor.set("device", device); //device sensor is connected to
}
String topic = String(discovery_Topic) + "/" + String(sensor_type) + "/" + String(unique_id) + "/config";
pub_custom_topic((char *)topic.c_str(), sensor, true);
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
will_Topic, "connectivity", "", //set availability_topic,device_class,value_template,
Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas,
0, //set off_delay
Gateway_AnnouncementMsg, will_Message, false, "" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic
createDiscovery("binary_sensor", //set Type
will_Topic, Gateway_Name, (char*)getUniqueId("", "").c_str(), //set state_topic,name,uniqueId
will_Topic, "connectivity", "", //set availability_topic,device_class,value_template,
Gateway_AnnouncementMsg, will_Message, "", //set,payload_on,payload_off,unit_of_meas,
0, //set off_delay
Gateway_AnnouncementMsg, will_Message, false, "" //set,payload_avalaible,payload_not avalaible ,is a child device, command topic
);
createDiscovery("switch", //set Type
will_Topic, "restart OMG", (char *)getUniqueId("restart", "").c_str(), //set state_topic,name,uniqueId
will_Topic, "", "", //set availability_topic,device_class,value_template,
"{\"cmd\":\"restart\"}", "", "", //set,payload_on,payload_off,unit_of_meas,
0, //set off_delay
Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic
createDiscovery("switch", //set Type
will_Topic, "restart OMG", (char*)getUniqueId("restart", "").c_str(), //set state_topic,name,uniqueId
will_Topic, "", "", //set availability_topic,device_class,value_template,
"{\"cmd\":\"restart\"}", "", "", //set,payload_on,payload_off,unit_of_meas,
0, //set off_delay
Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic
);
createDiscovery("switch", //set Type
will_Topic, "erase OMG", (char *)getUniqueId("erase", "").c_str(), //set state_topic,name,uniqueId
will_Topic, "", "", //set availability_topic,device_class,value_template,
"{\"cmd\":\"erase\"}", "", "", //set,payload_on,payload_off,unit_of_meas,
0, //set off_delay
Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic
createDiscovery("switch", //set Type
will_Topic, "erase OMG", (char*)getUniqueId("erase", "").c_str(), //set state_topic,name,uniqueId
will_Topic, "", "", //set availability_topic,device_class,value_template,
"{\"cmd\":\"erase\"}", "", "", //set,payload_on,payload_off,unit_of_meas,
0, //set off_delay
Gateway_AnnouncementMsg, will_Message, true, subjectMQTTtoSYSset //set,payload_avalaible,payload_not avalaible ,is a child device, command topic
);
#ifdef ZsensorBME280
#define BMEparametersCount 6
# ifdef ZsensorBME280
# define BMEparametersCount 6
Log.trace(F("bme280Discovery" CR));
char *BMEsensor[BMEparametersCount][8] = {
char* BMEsensor[BMEparametersCount][8] = {
{"sensor", "tempc", "bme", "temperature", jsonTemp, "", "", "°C"},
{"sensor", "tempf", "bme", "temperature", jsonTempf, "", "", "°F"},
{"sensor", "pa", "bme", "", jsonPa, "", "", "hPa"},
@@ -162,320 +154,314 @@ 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],
BMETOPIC, BMEsensor[i][1], (char *)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(),
BMETOPIC, BMEsensor[i][1], (char*)getUniqueId(BMEsensor[i][1], BMEsensor[i][2]).c_str(),
will_Topic, BMEsensor[i][3], BMEsensor[i][4],
BMEsensor[i][5], BMEsensor[i][6], BMEsensor[i][7],
0, "", "", true, "");
}
#endif
# endif
#ifdef ZsensorHTU21
#define HTUparametersCount 3
# ifdef ZsensorHTU21
# define HTUparametersCount 3
Log.trace(F("htu21Discovery" CR));
char *HTUsensor[HTUparametersCount][8] = {
char* HTUsensor[HTUparametersCount][8] = {
{"sensor", "tempc", "htu", "temperature", jsonTemp, "", "", "°C"},
{"sensor", "tempf", "htu", "temperature", jsonTempf, "", "", "°F"},
{"sensor", "hum", "htu", "humidity", jsonHum, "", "", "%"}
//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],
HTUTOPIC, HTUsensor[i][1], (char *)getUniqueId(HTUsensor[i][1], HTUsensor[i][2]).c_str(),
HTUTOPIC, HTUsensor[i][1], (char*)getUniqueId(HTUsensor[i][1], HTUsensor[i][2]).c_str(),
will_Topic, HTUsensor[i][3], HTUsensor[i][4],
HTUsensor[i][5], HTUsensor[i][6], HTUsensor[i][7],
0, "", "", true, "");
}
#endif
# endif
#ifdef ZsensorDHT
#define DHTparametersCount 2
# ifdef ZsensorDHT
# define DHTparametersCount 2
Log.trace(F("DHTDiscovery" CR));
char *DHTsensor[DHTparametersCount][8] = {
char* DHTsensor[DHTparametersCount][8] = {
{"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],
DHTTOPIC, DHTsensor[i][1], (char *)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(),
DHTTOPIC, DHTsensor[i][1], (char*)getUniqueId(DHTsensor[i][1], DHTsensor[i][2]).c_str(),
will_Topic, DHTsensor[i][3], DHTsensor[i][4],
DHTsensor[i][5], DHTsensor[i][6], DHTsensor[i][7],
0, "", "", true, "");
}
#endif
# endif
#ifdef ZsensorADC
# ifdef ZsensorADC
Log.trace(F("ADCDiscovery" CR));
char *ADCsensor[8] = {"sensor", "adc", "", "", jsonAdc, "", "", ""};
char* ADCsensor[8] = {"sensor", "adc", "", "", jsonAdc, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(ADCsensor[1]);
createDiscovery(ADCsensor[0],
ADCTOPIC, ADCsensor[1], (char *)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(),
ADCTOPIC, ADCsensor[1], (char*)getUniqueId(ADCsensor[1], ADCsensor[2]).c_str(),
will_Topic, ADCsensor[3], ADCsensor[4],
ADCsensor[5], ADCsensor[6], ADCsensor[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZsensorBH1750
#define BH1750parametersCount 3
# ifdef ZsensorBH1750
# define BH1750parametersCount 3
Log.trace(F("BH1750Discovery" CR));
char *BH1750sensor[BH1750parametersCount][8] = {
char* BH1750sensor[BH1750parametersCount][8] = {
{"sensor", "lux", "BH1750", "illuminance", jsonLux, "", "", "lu"},
{"sensor", "ftCd", "BH1750", "", jsonFtcd, "", "", ""},
{"sensor", "wattsm2", "BH1750", "", jsonWm2, "", "", "wm²"}
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
};
for (int i = 0; i < BH1750parametersCount; i++)
{
for (int i = 0; i < BH1750parametersCount; i++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(BH1750sensor[i][1]);
createDiscovery(BH1750sensor[i][0],
subjectBH1750toMQTT, BH1750sensor[i][1], (char *)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(),
subjectBH1750toMQTT, BH1750sensor[i][1], (char*)getUniqueId(BH1750sensor[i][1], BH1750sensor[i][2]).c_str(),
will_Topic, BH1750sensor[i][3], BH1750sensor[i][4],
BH1750sensor[i][5], BH1750sensor[i][6], BH1750sensor[i][7],
0, "", "", true, "");
}
#endif
# endif
#ifdef ZsensorTSL2561
#define TSL2561parametersCount 3
# ifdef ZsensorTSL2561
# define TSL2561parametersCount 3
Log.trace(F("TSL2561Discovery" CR));
char *TSL2561sensor[TSL2561parametersCount][8] = {
char* TSL2561sensor[TSL2561parametersCount][8] = {
{"sensor", "lux", "TSL2561", "illuminance", jsonLux, "", "", "lu"},
{"sensor", "ftcd", "TSL2561", "", jsonFtcd, "", "", ""},
{"sensor", "wattsm2", "TSL2561", "", jsonWm2, "", "", "wm²"}
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
};
for (int i = 0; i < TSL2561parametersCount; i++)
{
for (int i = 0; i < TSL2561parametersCount; i++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(TSL2561sensor[i][1]);
createDiscovery(TSL2561sensor[i][0],
subjectTSL12561toMQTT, TSL2561sensor[i][1], (char *)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(),
subjectTSL12561toMQTT, TSL2561sensor[i][1], (char*)getUniqueId(TSL2561sensor[i][1], TSL2561sensor[i][2]).c_str(),
will_Topic, TSL2561sensor[i][3], TSL2561sensor[i][4],
TSL2561sensor[i][5], TSL2561sensor[i][6], TSL2561sensor[i][7],
0, "", "", true, "");
}
#endif
# endif
#ifdef ZsensorHCSR501
# ifdef ZsensorHCSR501
Log.trace(F("HCSR501Discovery" CR));
char *HCSR501sensor[8] = {"binary_sensor", "hcsr501", "", "", jsonPresence, "true", "false", ""};
char* HCSR501sensor[8] = {"binary_sensor", "hcsr501", "", "", jsonPresence, "true", "false", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(HCSR501sensor[1]);
createDiscovery(HCSR501sensor[0],
subjectHCSR501toMQTT, HCSR501sensor[1], (char *)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(),
subjectHCSR501toMQTT, HCSR501sensor[1], (char*)getUniqueId(HCSR501sensor[1], HCSR501sensor[2]).c_str(),
will_Topic, HCSR501sensor[3], HCSR501sensor[4],
HCSR501sensor[5], HCSR501sensor[6], HCSR501sensor[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZsensorGPIOInput
# ifdef ZsensorGPIOInput
Log.trace(F("GPIOInputDiscovery" CR));
char *GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "", "", jsonGpio, "HIGH", "LOW", ""};
char* GPIOInputsensor[8] = {"binary_sensor", "GPIOInput", "", "", jsonGpio, "HIGH", "LOW", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(GPIOInputsensor[1]);
createDiscovery(GPIOInputsensor[0],
subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char *)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(),
subjectGPIOInputtoMQTT, GPIOInputsensor[1], (char*)getUniqueId(GPIOInputsensor[1], GPIOInputsensor[2]).c_str(),
will_Topic, GPIOInputsensor[3], GPIOInputsensor[4],
GPIOInputsensor[5], GPIOInputsensor[6], GPIOInputsensor[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZsensorINA226
#define INA226parametersCount 3
# ifdef ZsensorINA226
# define INA226parametersCount 3
Log.trace(F("INA226Discovery" CR));
char *INA226sensor[INA226parametersCount][8] = {
char* INA226sensor[INA226parametersCount][8] = {
{"sensor", "volt", "INA226", "", jsonVolt, "", "", "V"},
{"sensor", "current", "INA226", "", jsonCurrent, "", "", "A"},
{"sensor", "power", "INA226", "", jsonPower, "", "", "W"}
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
};
for (int i = 0; i < INA226parametersCount; i++)
{
for (int i = 0; i < INA226parametersCount; i++) {
Log.trace(F("CreateDiscoverySensor" CR));
//trc(INA226sensor[i][1]);
createDiscovery(INA226sensor[i][0],
subjectINA226toMQTT, INA226sensor[i][1], (char *)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(),
subjectINA226toMQTT, INA226sensor[i][1], (char*)getUniqueId(INA226sensor[i][1], INA226sensor[i][2]).c_str(),
will_Topic, INA226sensor[i][3], INA226sensor[i][4],
INA226sensor[i][5], INA226sensor[i][6], INA226sensor[i][7],
0, "", "", true, "");
}
#endif
# endif
#ifdef ZsensorDS1820
# ifdef ZsensorDS1820
// Publish any DS1820 sensors found on the OneWire bus
pubOneWire_HADiscovery();
#endif
# endif
#ifdef ZactuatorONOFF
# ifdef ZactuatorONOFF
Log.trace(F("actuatorONOFFDiscovery" CR));
char *actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "", "", "{\"cmd\":1}", "{\"cmd\":0}", ""};
char* actuatorONOFF[8] = {"switch", "actuatorONOFF", "", "", "", "{\"cmd\":1}", "{\"cmd\":0}", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(actuatorONOFF[1]);
createDiscovery(actuatorONOFF[0],
subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char *)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(),
subjectGTWONOFFtoMQTT, actuatorONOFF[1], (char*)getUniqueId(actuatorONOFF[1], actuatorONOFF[2]).c_str(),
will_Topic, actuatorONOFF[3], actuatorONOFF[4],
actuatorONOFF[5], actuatorONOFF[6], actuatorONOFF[7],
0, "", "", true, subjectMQTTtoONOFF);
#endif
# endif
#ifdef ZgatewayRF
# ifdef ZgatewayRF
// Sensor to display RF received value
Log.trace(F("gatewayRFDiscovery" CR));
char *gatewayRF[8] = {"sensor", "gatewayRF", "", "", jsonVal, "", "", ""};
char* gatewayRF[8] = {"sensor", "gatewayRF", "", "", jsonVal, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayRF[1]);
createDiscovery(gatewayRF[0],
subjectRFtoMQTT, gatewayRF[1], (char *)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(),
subjectRFtoMQTT, gatewayRF[1], (char*)getUniqueId(gatewayRF[1], gatewayRF[2]).c_str(),
will_Topic, gatewayRF[3], gatewayRF[4],
gatewayRF[5], gatewayRF[6], gatewayRF[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewayRF2
# ifdef ZgatewayRF2
// Sensor to display RF received value
Log.trace(F("gatewayRF2Discovery" CR));
char *gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", jsonVal, "", "", ""};
char* gatewayRF2[8] = {"sensor", "gatewayRF2", "", "", jsonVal, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayRF2[1]);
createDiscovery(gatewayRF2[0],
subjectRF2toMQTT, gatewayRF2[1], (char *)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(),
subjectRF2toMQTT, gatewayRF2[1], (char*)getUniqueId(gatewayRF2[1], gatewayRF2[2]).c_str(),
will_Topic, gatewayRF2[3], gatewayRF2[4],
gatewayRF2[5], gatewayRF2[6], gatewayRF2[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewayRFM69
# ifdef ZgatewayRFM69
// Sensor to display RF received value
Log.trace(F("gatewayRFM69Discovery" CR));
char *gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", jsonVal, "", "", ""};
char* gatewayRFM69[8] = {"sensor", "gatewayRFM69", "", "", jsonVal, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayRFM69[1]);
createDiscovery(gatewayRFM69[0],
subjectRFM69toMQTT, gatewayRFM69[1], (char *)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(),
subjectRFM69toMQTT, gatewayRFM69[1], (char*)getUniqueId(gatewayRFM69[1], gatewayRFM69[2]).c_str(),
will_Topic, gatewayRFM69[3], gatewayRFM69[4],
gatewayRFM69[5], gatewayRFM69[6], gatewayRFM69[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewayLORA
# ifdef ZgatewayLORA
// Sensor to display RF received value
Log.trace(F("gatewayLORADiscovery" CR));
char *gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", jsonMsg, "", "", ""};
char* gatewayLORA[8] = {"sensor", "gatewayLORA", "", "", jsonMsg, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayLORA[1]);
createDiscovery(gatewayLORA[0],
subjectLORAtoMQTT, gatewayLORA[1], (char *)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(),
subjectLORAtoMQTT, gatewayLORA[1], (char*)getUniqueId(gatewayLORA[1], gatewayLORA[2]).c_str(),
will_Topic, gatewayLORA[3], gatewayLORA[4],
gatewayLORA[5], gatewayLORA[6], gatewayLORA[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewaySRFB
# ifdef ZgatewaySRFB
// Sensor to display RF received value
Log.trace(F("gatewaySRFBDiscovery" CR));
char *gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", jsonVal, "", "", ""};
char* gatewaySRFB[8] = {"sensor", "gatewaySRFB", "", "", jsonVal, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewaySRFB[1]);
createDiscovery(gatewaySRFB[0],
subjectSRFBtoMQTT, gatewaySRFB[1], (char *)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(),
subjectSRFBtoMQTT, gatewaySRFB[1], (char*)getUniqueId(gatewaySRFB[1], gatewaySRFB[2]).c_str(),
will_Topic, gatewaySRFB[3], gatewaySRFB[4],
gatewaySRFB[5], gatewaySRFB[6], gatewaySRFB[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewayPilight
# ifdef ZgatewayPilight
// Sensor to display RF received value
Log.trace(F("gatewayPilightDiscovery" CR));
char *gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", jsonMsg, "", "", ""};
char* gatewayPilight[8] = {"sensor", "gatewayPilight", "", "", jsonMsg, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayPilight[1]);
createDiscovery(gatewayPilight[0],
subjectPilighttoMQTT, gatewayPilight[1], (char *)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(),
subjectPilighttoMQTT, gatewayPilight[1], (char*)getUniqueId(gatewayPilight[1], gatewayPilight[2]).c_str(),
will_Topic, gatewayPilight[3], gatewayPilight[4],
gatewayPilight[5], gatewayPilight[6], gatewayPilight[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewayIR
# ifdef ZgatewayIR
// Sensor to display IR received value
Log.trace(F("gatewayIRDiscovery" CR));
char *gatewayIR[8] = {"sensor", "gatewayIR", "", "", jsonVal, "", "", ""};
char* gatewayIR[8] = {"sensor", "gatewayIR", "", "", jsonVal, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayIR[1]);
createDiscovery(gatewayIR[0],
subjectIRtoMQTT, gatewayIR[1], (char *)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(),
subjectIRtoMQTT, gatewayIR[1], (char*)getUniqueId(gatewayIR[1], gatewayIR[2]).c_str(),
will_Topic, gatewayIR[3], gatewayIR[4],
gatewayIR[5], gatewayIR[6], gatewayIR[7],
0, "", "", true, "");
#endif
# endif
#ifdef Zgateway2G
# ifdef Zgateway2G
// Sensor to display 2G received value
Log.trace(F("gateway2GDiscovery" CR));
char *gateway2G[8] = {"sensor", "gateway2G", "", "", jsonMsg, "", "", ""};
char* gateway2G[8] = {"sensor", "gateway2G", "", "", jsonMsg, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gateway2G[1]);
createDiscovery(gateway2G[0],
subject2GtoMQTT, gateway2G[1], (char *)getUniqueId(gateway2G[1], gateway2G[2]).c_str(),
subject2GtoMQTT, gateway2G[1], (char*)getUniqueId(gateway2G[1], gateway2G[2]).c_str(),
will_Topic, gateway2G[3], gateway2G[4],
gateway2G[5], gateway2G[6], gateway2G[7],
0, "", "", true, "");
#endif
# endif
#ifdef ZgatewayBT
# ifdef ZgatewayBT
// Sensor to display BT received value
Log.trace(F("gatewayBTDiscovery" CR));
char *gatewayBT[8] = {"sensor", "gatewayBT", "", "", jsonId, "", "", ""};
char* gatewayBT[8] = {"sensor", "gatewayBT", "", "", jsonId, "", "", ""};
//component type,name,availability topic,device class,value template,payload on, payload off, unit of measurement
Log.trace(F("CreateDiscoverySensor" CR));
//trc(gatewayBT[1]);
createDiscovery(gatewayBT[0],
subjectBTtoMQTT, gatewayBT[1], (char *)getUniqueId(gatewayBT[1], gatewayBT[2]).c_str(),
subjectBTtoMQTT, gatewayBT[1], (char*)getUniqueId(gatewayBT[1], gatewayBT[2]).c_str(),
will_Topic, gatewayBT[3], gatewayBT[4],
gatewayBT[5], gatewayBT[6], gatewayBT[7],
0, "", "", true, "");
#endif
# endif
}
#endif

View File

@@ -30,40 +30,33 @@
#ifdef ZsensorADC
#if defined(ESP8266)
# if defined(ESP8266)
ADC_MODE(ADC_TOUT);
#endif
# endif
//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
#if defined(ESP8266)
void MeasureADC() {
if (millis() > (timeadc + TimeBetweenReadingADC)) { //retrieving value of temperature and humidity of the box from DHT every xUL
# if defined(ESP8266)
yield();
#endif
# endif
timeadc = millis();
static int persistedadc;
int val = analogRead(ADC_PIN);
if (isnan(val))
{
if (isnan(val)) {
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;
JsonObject &ADCdata = jsonBuffer.createObject();
JsonObject& ADCdata = jsonBuffer.createObject();
ADCdata.set("adc", (int)val);
pub(ADCTOPIC, ADCdata);
persistedadc = val;

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 "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,14 +51,11 @@ 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();
JsonObject& BH1750data = jsonBuffer.createObject();
timebh1750 = millis();
unsigned int i = 0;
@@ -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)

View File

@@ -40,17 +40,17 @@
#include "User_config.h"
#ifdef ZsensorBME280
#include "Wire.h" // Library for communication with I2C / TWI devices
#include <stdint.h>
#include "SparkFunBME280.h"
# 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;
mySensor.settings.I2CAddress = BME280_i2c_addr;
Log.notice(F("Setup BME280 on adress: %H" CR), BME280_i2c_addr);
//***Operation settings*****************************//
@@ -101,15 +101,11 @@ void setupZsensorBME280()
mySensor.settings.humidOverSample = 1;
delay(10); // Gives the Sensor enough time to turn on (The BME280 requires 2ms to start up)
Log.notice(F("Bosch BME280 Initialized - Result of .begin(): 0x %h" CR),mySensor.begin());
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();
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)

View File

@@ -30,23 +30,20 @@
#include "User_config.h"
#ifdef ZsensorDHT
#include <DHT.h>
#include <DHT_U.h>
# include <DHT.h>
# include <DHT_U.h>
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)
{
JsonObject& DHTdata = jsonBuffer.createObject();
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)

View File

@@ -26,8 +26,8 @@
#include "User_config.h"
#ifdef ZsensorDS1820
#include <OneWire.h>
#include <DallasTemperature.h>
# include <DallasTemperature.h>
# include <OneWire.h>
OneWire owbus(DS1820_OWBUS_PIN);
DallasTemperature ds1820(&owbus);
@@ -38,10 +38,8 @@ static uint8_t ds1820_resolution[OW_MAX_SENSORS];
static String ds1820_type[OW_MAX_SENSORS];
static String ds1820_addr[OW_MAX_SENSORS];
void setupZsensorDS1820()
{
Log.trace(F("DS1820: configured pin: %d for 1-wire bus" CR), DS1820_OWBUS_PIN );
void setupZsensorDS1820() {
Log.trace(F("DS1820: configured pin: %d for 1-wire bus" CR), DS1820_OWBUS_PIN);
ds1820.begin();
// Search the OneWire bus for all devices
@@ -51,57 +49,46 @@ 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,
// 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)
{
ds1820_type[ds1820_count] = String("DS1820/DS18S20");
} 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);
}
}
ds1820_resolution[ds1820_count] = ds1820.getResolution(ds1820_address);
Log.trace(F("DS1820: Device %d, Type: %s, Address: %s, Resolution: %d" CR),
ds1820_count,
(char *)ds1820_type[ds1820_count].c_str(),
(char *)ds1820_addr[ds1820_count].c_str(),
ds1820_resolution[ds1820_count]);
ds1820_count,
(char*)ds1820_type[ds1820_count].c_str(),
(char*)ds1820_addr[ds1820_count].c_str(),
ds1820_resolution[ds1820_count]);
ds1820_count++;
}
}
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,103 +97,88 @@ 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
# ifdef ZmqttDiscovery
Log.notice(F("CreateDiscoverySensor - Found %d" CR), ds1820_count);
for (int index=0; index<ds1820_count; index++)
{
#if DS1820_FAHRENHEIT
createDiscovery("sensor",
(char *)(String(OW_TOPIC) + "/" + ds1820_addr[index]).c_str(),
(char *)String("DS12B20_" + String(index+1)).c_str(),
(char *)ds1820_addr[index].c_str(),
will_Topic,
"temperature",
jsonTempf,
"", "", "°F",
0, "", "", true, "");
#else
createDiscovery("sensor",
(char *)(String(OW_TOPIC) + "/" + ds1820_addr[index]).c_str(),
(char *)String("DS12B20_" + String(index+1)).c_str(),
(char *)ds1820_addr[index].c_str(),
will_Topic,
"temperature",
jsonTemp,
"", "", "°C",
0, "", "", true, "");
#endif
for (int index = 0; index < ds1820_count; index++) {
# if DS1820_FAHRENHEIT
createDiscovery("sensor",
(char*)(String(OW_TOPIC) + "/" + ds1820_addr[index]).c_str(),
(char*)String("DS12B20_" + String(index + 1)).c_str(),
(char*)ds1820_addr[index].c_str(),
will_Topic,
"temperature",
jsonTempf,
"", "", "°F",
0, "", "", true, "");
# else
createDiscovery("sensor",
(char*)(String(OW_TOPIC) + "/" + ds1820_addr[index]).c_str(),
(char*)String("DS12B20_" + String(index + 1)).c_str(),
(char*)ds1820_addr[index].c_str(),
will_Topic,
"temperature",
jsonTemp,
"", "", "°C",
0, "", "", true, "");
# endif
}
#endif
# endif
}
void MeasureDS1820Temp()
{
void MeasureDS1820Temp() {
static float persisted_temp[OW_MAX_SENSORS];
static unsigned long timeDS1820 = 0;
static boolean triggeredConversion = false;
float current_temp[OW_MAX_SENSORS];
// trigger temperature conversion some time before actually
// 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();
JsonObject& DS1820data = jsonBuffer.createObject();
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)
{
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])
{
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) {
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]) {
if (DS1820_FAHRENHEIT) {
Log.notice(F("DS1820: Temperature %s %d F" CR),
(char *)ds1820_addr[i].c_str(),
DallasTemperature::toFahrenheit(current_temp[i]));
Log.notice(F("DS1820: Temperature %s %d F" CR),
(char*)ds1820_addr[i].c_str(),
DallasTemperature::toFahrenheit(current_temp[i]));
DS1820data.set("temp", (float)DallasTemperature::toFahrenheit(current_temp[i]));
DS1820data.set("unit", "F");
} else {
Log.notice(F("DS1820: Temperature %s %d C" CR),
(char *)ds1820_addr[i].c_str(),
current_temp[i]);
Log.notice(F("DS1820: Temperature %s %d C" CR),
(char*)ds1820_addr[i].c_str(),
current_temp[i]);
DS1820data.set("temp", (float)DallasTemperature::toFahrenheit(current_temp[i]));
DS1820data.set("unit", "F");
DS1820data.set("temp", (float)current_temp[i]);
DS1820data.set("unit", "C");
}
if (DS1820_DETAILS) {
if (DS1820_DETAILS) {
DS1820data.set("type", ds1820_type[i]);
DS1820data.set("res", ds1820_resolution[i] + String("bit" CR));
DS1820data.set("addr", ds1820_addr[i]);
}
pub((char *)(String(OW_TOPIC) + "/" + ds1820_addr[i]).c_str(), DS1820data);
pub((char*)(String(OW_TOPIC) + "/" + ds1820_addr[i]).c_str(), DS1820data);
delay(10);
}
else
{
Log.trace(F("DS1820: Temperature for device %s didn't change, don't publish it." CR), (char *)ds1820_addr[i].c_str());
} 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];
}

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)
# if defined(ESP8266) || defined(ESP32)
yield();
#endif
# 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)
{
JsonObject& GPIOdata = jsonBuffer.createObject();
if (InputState == HIGH) {
GPIOdata.set("gpio", "HIGH");
}
if (InputState == LOW)
{
if (InputState == LOW) {
GPIOdata.set("gpio", "LOW");
}
if (GPIOdata.size() > 0)

View File

@@ -31,18 +31,15 @@ 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); //
pinMode(GPIOKeyCode_D2_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D0_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D1_PIN, INPUT_PULLUP); //
pinMode(GPIOKeyCode_D2_PIN, INPUT_PULLUP); //
//pinMode(GPIOKeyCode_D3_PIN, INPUT_PULLUP); //
}
void MeasureGPIOKeyCode()
{
void MeasureGPIOKeyCode() {
int latch = digitalRead(GPIOKeyCode_LATCH_PIN);
// check to see if you just pressed the button
@@ -52,12 +49,11 @@ void MeasureGPIOKeyCode()
{
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
#if defined(ESP8266) || defined(ESP32)
# if defined(ESP8266) || defined(ESP32)
yield();
#endif
# endif
// if the Input state has changed:
if (latch > 0 && lastLatchStateGPIOKeyCode != latch)
{
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)

View File

@@ -33,49 +33,38 @@
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
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;
JsonObject &HCSR04data = jsonBuffer.createObject();
JsonObject& HCSR04data = jsonBuffer.createObject();
digitalWrite(HCSR04_TRI_PIN, LOW);
delayMicroseconds(2);
digitalWrite(HCSR04_TRI_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(HCSR04_TRI_PIN, LOW);
unsigned long duration = pulseIn(HCSR04_ECH_PIN, HIGH);
if (isnan(duration))
{
if (isnan(duration)) {
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));
}

View File

@@ -30,37 +30,29 @@
#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();
JsonObject& HCSR501data = jsonBuffer.createObject();
static int pirState = LOW;
int PresenceValue = digitalRead(HCSR501_PIN);
#if defined(ESP8266) || defined(ESP32)
# if defined(ESP8266) || defined(ESP32)
yield();
#endif
if (PresenceValue == HIGH)
{
if (pirState == LOW)
{
# endif
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;

View File

@@ -38,10 +38,11 @@
#include "User_config.h"
#ifdef ZsensorHTU21
#include "Wire.h" // Library for communication with I2C / TWI devices
#include <stdint.h>
#include "SparkFunHTU21D.h"
#include "config_HTU21.h"
# 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
unsigned long timehtu21 = 0;
@@ -49,24 +50,20 @@ 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));
#if defined(ESP32)
# if defined(ESP32)
Wire.begin(I2C_SDA, I2C_SCL);
htuSensor.begin(Wire);
#else
# else
htuSensor.begin();
#endif
# 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();
JsonObject& HTU21data = jsonBuffer.createObject();
// Generate Temperature in degrees C
if (HtuTempC != persisted_htu_tempc || htu21_always)
{
float HtuTempF = (HtuTempC*1.8)+32;
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));
}

View File

@@ -35,40 +35,36 @@
#include "User_config.h"
#ifdef ZsensorINA226
#include <Wire.h>
# include <Wire.h>
float rShunt = 0.1; // Shunt Widerstand festlegen, hier 0.1 Ohm
float rShunt = 0.1; // Shunt Widerstand festlegen, hier 0.1 Ohm
const int INA226_ADDR = 0x40; // A0 und A1 auf GND > Adresse 40 Hex auf Seite 18 im Datenblatt
//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;
JsonObject &INA226data = jsonBuffer.createObject();
JsonObject& INA226data = jsonBuffer.createObject();
// Topic on which we will send data
Log.trace(F("Retrieving electrical data" CR));
// Bus Spannung, read-only, 16Bit, 0...40.96V max., LSB 1.25mV
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
shuntvolt += 1; // 1 dazuzählen
shuntvolt *= -1; // negativ machen
}
float current = shuntvolt * 0.0000025 / rShunt; // * LSB / R
float power = abs(volt * current);
@@ -79,15 +75,14 @@ void MeasureINA226()
dtostrf(volt, 6, 3, volt_c);
dtostrf(current, 6, 3, current_c);
dtostrf(power, 6, 3, power_c);
INA226data.set("volt", (char *)volt_c);
INA226data.set("current", (char *)current_c);
INA226data.set("power", (char *)power_c);
INA226data.set("volt", (char*)volt_c);
INA226data.set("current", (char*)current_c);
INA226data.set("power", (char*)power_c);
pub(subjectINA226toMQTT, INA226data);
}
}
static void writeRegister(byte reg, word value)
{
static void writeRegister(byte reg, word value) {
Wire.beginTransmission(INA226_ADDR);
Wire.write(reg);
Wire.write((value >> 8) & 0xFF);
@@ -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();
}

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 <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,24 +84,21 @@ void setupZsensorTSL2561()
displaySensorDetails();
}
void MeasureLightIntensityTSL2561()
{
if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561))
{
void MeasureLightIntensityTSL2561() {
if (millis() > (timetsl2561 + TimeBetweenReadingtsl2561)) {
static uint32_t persisted_lux;
timetsl2561 = millis();
Log.trace(F("Creating TSL2561 buffer" CR));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject &TSL2561data = jsonBuffer.createObject();
JsonObject& TSL2561data = jsonBuffer.createObject();
sensors_event_t event;
tsl.getEvent(&event);
if (event.light)
// if event.light == 0 the sensor is clipping, do not send
{
if (persisted_lux != event.light || tsl2561_always)
{
if (persisted_lux != event.light || tsl2561_always) {
persisted_lux = event.light;
TSL2561data.set("lux", (float)event.light);
@@ -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));
}
}

View File

@@ -28,34 +28,34 @@
extern void setup2G();
extern bool _2GtoMQTT();
extern void MQTTto2G(char *topicOri, char *datacallback);
extern void MQTTto2G(char *topicOri, JsonObject &SMSdata);
extern void MQTTto2G(char* topicOri, char* datacallback);
extern void MQTTto2G(char* topicOri, JsonObject& SMSdata);
/*-------------------2G topics & parameters----------------------*/
//433Mhz MQTT Subjects and keys
#define subjectMQTTto2G "/commands/MQTTto2G"
#define subject2GtoMQTT "/2GtoMQTT"
#define subjectMQTTto2G "/commands/MQTTto2G"
#define subject2GtoMQTT "/2GtoMQTT"
#define subjectGTW2GtoMQTT "/2GtoMQTT"
#define _2GPhoneKey "PHO_" // phone number define the phone number to send the SMS MQTT->2G
#define _2GPhoneKey "PHO_" // phone number define the phone number to send the SMS MQTT->2G
#define _2G_MODULE_BAUDRATE 9600
#define _2G_MIN_SIGNAL 30
#define _2G_MAX_SIGNAL 1000
#define _2G_MIN_SIGNAL 30
#define _2G_MAX_SIGNAL 1000
/*-------------------PIN DEFINITIONS----------------------*/
#if !defined(_2G_TX_PIN) || !defined(_2G_RX_PIN) || !defined(_2G_PWR_PIN)
#ifdef ESP8266
#define _2G_TX_PIN D6 //D6 to A6 RX,
#define _2G_RX_PIN D7 //D7 to A6 TX
#define _2G_PWR_PIN D5 // connect a MOSFET to power on and off your A6/7 module
#elif defined(ESP32)
#define _2G_TX_PIN 16 //D16 to A6 RX,
#define _2G_RX_PIN 17 //D17 to A6 TX
#define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module
#else
#define _2G_TX_PIN 6 //D6 to A6 RX,
#define _2G_RX_PIN 7 //D7 to A6 TX
#define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module
#endif
# ifdef ESP8266
# define _2G_TX_PIN D6 //D6 to A6 RX,
# define _2G_RX_PIN D7 //D7 to A6 TX
# define _2G_PWR_PIN D5 // connect a MOSFET to power on and off your A6/7 module
# elif defined(ESP32)
# define _2G_TX_PIN 16 //D16 to A6 RX,
# define _2G_RX_PIN 17 //D17 to A6 TX
# define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module
# else
# define _2G_TX_PIN 6 //D6 to A6 RX,
# define _2G_RX_PIN 7 //D7 to A6 TX
# define _2G_PWR_PIN 5 // connect a MOSFET to power on and off your A6/7 module
# endif
#endif
#endif
#endif

View File

@@ -30,19 +30,19 @@ extern void setupADC();
extern void ADCtoMQTT();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define ADCTOPIC "/ADCtoMQTT"
#define ADCTOPIC "/ADCtoMQTT"
#if !defined(TimeBetweenReadingADC) || (TimeBetweenReadingADC < 200)
#define TimeBetweenReadingADC 500 // time between 2 ADC readings, minimum 200 to let the time of the ESP to keep the connection
# define TimeBetweenReadingADC 500 // time between 2 ADC readings, minimum 200 to let the time of the ESP to keep the connection
#endif
#ifndef ThresholdReadingADC
#define ThresholdReadingADC 50 // following the comparison between the previous value and the current one +- the threshold the value will be published or not
# define ThresholdReadingADC 50 // following the comparison between the previous value and the current one +- the threshold the value will be published or not
#endif
/*-------------------PIN DEFINITIONS----------------------*/
#if defined(ESP8266) || !defined(ADC_PIN)
#define ADC_PIN A0 //on nodeMCU this is D3 GPIO0
# define ADC_PIN A0 //on nodeMCU this is D3 GPIO0
#endif
#endif
#endif

View File

@@ -41,14 +41,14 @@
extern void setupBH1750();
extern void BH1750toMQTT();
#define bh1750_always true // if false when the current value for light Level (Lux) is the same as previous one don't send it by MQTT
#define bh1750_always true // if false when the current value for light Level (Lux) is the same as previous one don't send it by MQTT
#define TimeBetweenReadingBH1750 30000
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectBH1750toMQTT "/BH1750toMQTT"
#define subjectBH1750toMQTT "/BH1750toMQTT"
//Time used to wait for an interval before resending measured values
unsigned long timebh1750 = 0;
int BH1750_i2c_addr = 0x23; // Light Sensor I2C Address
#endif
#endif

View File

@@ -41,12 +41,12 @@
extern void setupBME280();
extern void BME280toMQTT();
#define bme280_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT
#define bme280_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT
#define TimeBetweenReadingbme280 30000
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define BMETOPIC "/CLIMAtoMQTT/bme"
#define BMETOPIC "/CLIMAtoMQTT/bme"
//Time used to wait for an interval before resending measured values
unsigned long timebme280 = 0;

View File

@@ -27,38 +27,38 @@
#define config_BT_h
extern void setupBT();
extern bool BTtoMQTT();
extern void MQTTtoBT(char * topicOri, JsonObject& RFdata);
extern bool BTtoMQTT();
extern void MQTTtoBT(char* topicOri, JsonObject& RFdata);
/*----------------------BT topics & parameters-------------------------*/
#define subjectBTtoMQTT "/BTtoMQTT"
#define subjectMQTTtoBTset "/commands/MQTTtoBT/config"
#define MinimumRSSI -100 //default minimum rssi value, all the devices below -90 will not be reported
#define Scan_duration 10 //define the time for a scan --WARNING-- changing this value can lead to instability on ESP32
#define HM-10
#define HMSerialSpeed 9600 // Communication speed with the HM module, softwareserial doesn't support 115200
#define subjectBTtoMQTT "/BTtoMQTT"
#define subjectMQTTtoBTset "/commands/MQTTtoBT/config"
#define MinimumRSSI -100 //default minimum rssi value, all the devices below -90 will not be reported
#define Scan_duration 10 //define the time for a scan --WARNING-- changing this value can lead to instability on ESP32
#define HM -10
#define HMSerialSpeed 9600 // Communication speed with the HM module, softwareserial doesn't support 115200
//#define HM-11 // uncomment this line if you use HM-11 and comment the line above
//#define HM_BLUE_LED_STOP true //uncomment to stop the blue led light of HM1X
#define BLEdelimiter "4f4b2b444953413a" // OK+DISA:
#define BLEdelimiter "4f4b2b444953413a" // OK+DISA:
#define ServicedataMinLength 30
#ifndef TimeBtw_Read
#define TimeBtw_Read 55555 //define default time between 2 scans
# define TimeBtw_Read 55555 //define default time between 2 scans
#endif
#ifndef pubKnownBLEServiceData
#define pubKnownBLEServiceData false // define true if you want to publish service data belonging to recognised sensors
# define pubKnownBLEServiceData false // define true if you want to publish service data belonging to recognised sensors
#endif
#ifndef pubUnknownBLEServiceData
#define pubUnknownBLEServiceData true // define false if you don't want to publish service data to unrecognised sensors (in case you are having too heavy service data) https://github.com/1technophile/OpenMQTTGateway/issues/318#issuecomment-446064707
# define pubUnknownBLEServiceData true // define false if you don't want to publish service data to unrecognised sensors (in case you are having too heavy service data) https://github.com/1technophile/OpenMQTTGateway/issues/318#issuecomment-446064707
#endif
#ifndef pubBLEManufacturerData
#define pubBLEManufacturerData false // define true if you want to publish the manufacturer's data (sometimes contains characters that aren't valid with receiving client)
# define pubBLEManufacturerData false // define true if you want to publish the manufacturer's data (sometimes contains characters that aren't valid with receiving client)
#endif
#ifndef pubBLEServiceUUID
#define pubBLEServiceUUID false // define true if you want to publish the service UUID data
# define pubBLEServiceUUID false // define true if you want to publish the service UUID data
#endif
/*-------------------HOME ASSISTANT ROOM PRESENCE ----------------------*/
@@ -68,37 +68,37 @@ extern void MQTTtoBT(char * topicOri, JsonObject& RFdata);
unsigned int BLEinterval = TimeBtw_Read; //time between 2 scans
int Minrssi = MinimumRSSI; //minimum rssi value
struct BLEdevice{
struct BLEdevice {
char macAdr[13];
bool isDisc;
bool isWhtL;
bool isBlkL;
};
#define device_flags_isDisc 1 << 0
#define device_flags_isDisc 1 << 0
#define device_flags_isWhiteL 1 << 1
#define device_flags_isBlackL 1 << 2
struct decompose{
struct decompose {
char subject[4];
int start;
int len;
bool reverse;
char extract[60];
};
/*-------------------PIN DEFINITIONS----------------------*/
#if !defined(BT_RX) || !defined(BT_TX)
#ifdef ESP8266
#define BT_RX 13 //D7 ESP8266 RX connect HM-10 or 11 TX
#define BT_TX 12 //D6 ESP8266 TX connect HM-10 or 11 RX
#elif defined(ESP32)
#define BT_RX 18 // not tested
#define BT_TX 19 // not tested
#else
#define BT_RX 5 //arduino RX connect HM-10 or 11 TX
#define BT_TX 6 //arduino TX connect HM-10 or 11 RX
#endif
# ifdef ESP8266
# define BT_RX 13 //D7 ESP8266 RX connect HM-10 or 11 TX
# define BT_TX 12 //D6 ESP8266 TX connect HM-10 or 11 RX
# elif defined(ESP32)
# define BT_RX 18 // not tested
# define BT_TX 19 // not tested
# else
# define BT_RX 5 //arduino RX connect HM-10 or 11 TX
# define BT_TX 6 //arduino TX connect HM-10 or 11 RX
# endif
#endif
#endif
#endif

View File

@@ -30,8 +30,8 @@ extern void setupDHT();
extern void DHTtoMQTT();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define DHTTOPIC "/DHTtoMQTT/dht1"
#define dht_always true // if false when the current value for temp or hum is the same as previous one don't send it by MQTT
#define DHTTOPIC "/DHTtoMQTT/dht1"
#define dht_always true // if false when the current value for temp or hum is the same as previous one don't send it by MQTT
#define TimeBetweenReadingDHT 30000 // time between 2 DHT readings
/*-------------DHT SENSOR TYPE-------------*/
//#define DHT_SENSOR_TYPE DHT11 //uncomment for DHT11 Sensor
@@ -39,13 +39,13 @@ extern void DHTtoMQTT();
#define DHT_SENSOR_TYPE DHT22 //uncomment for DHT22 Sensor (default for backwards compatibility)
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef DHT_RECEIVER_PIN
#if defined(ESP8266)
#define DHT_RECEIVER_PIN 5 //5 = D1 you can put 14 = D5 if you don't use HCSR501 sensor and the RFM69
#elif defined(ESP32)
#define DHT_RECEIVER_PIN 16
#else
#define DHT_RECEIVER_PIN 8
#endif
# if defined(ESP8266)
# define DHT_RECEIVER_PIN 5 //5 = D1 you can put 14 = D5 if you don't use HCSR501 sensor and the RFM69
# elif defined(ESP32)
# define DHT_RECEIVER_PIN 16
# else
# define DHT_RECEIVER_PIN 8
# endif
#endif
#endif

View File

@@ -31,26 +31,26 @@ extern void DS1820toMQTT();
extern void pubOneWire_HADiscovery();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define OW_TOPIC "/OneWiretoMQTT/ds1820"
#define OW_MAX_SENSORS 8 // query max. sensors on 1-wire bus
#define DS1820_ALWAYS true // if false only published current temperature if has changed from previous reading
#define OW_TOPIC "/OneWiretoMQTT/ds1820"
#define OW_MAX_SENSORS 8 // query max. sensors on 1-wire bus
#define DS1820_ALWAYS true // if false only published current temperature if has changed from previous reading
#define DS1820_INTERVAL_SEC 60 // time between DS1820 readings (seconds)
#define DS1820_RESOLUTION 10 // conversion times: 9 bit (93.75 ms), 10 bit (187.5 ms), 11 bit (375 ms), 12 bit (750 ms)
#define DS1820_RESOLUTION 10 // conversion times: 9 bit (93.75 ms), 10 bit (187.5 ms), 11 bit (375 ms), 12 bit (750 ms)
#ifndef DS1820_FAHRENHEIT
#define DS1820_FAHRENHEIT false // defaults to Celcius
# define DS1820_FAHRENHEIT false // defaults to Celcius
#endif
#define DS1820_DETAILS true // publish extented info for each sensor (resolution, address, type)
#define DS1820_CONV_TIME 2000 // trigger conversion before requesting temperature readings (ms)
#define DS1820_DETAILS true // publish extented info for each sensor (resolution, address, type)
#define DS1820_CONV_TIME 2000 // trigger conversion before requesting temperature readings (ms)
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef DS1820_OWBUS_PIN
#if defined(ESP8266)
#define DS1820_OWBUS_PIN 2
#elif defined(ESP32)
#define DS1820_OWBUS_PIN 2
#else
#define DS1820_OWBUS_PIN 2
#endif
# if defined(ESP8266)
# define DS1820_OWBUS_PIN 2
# elif defined(ESP32)
# define DS1820_OWBUS_PIN 2
# else
# define DS1820_OWBUS_PIN 2
# endif
#endif
#endif

View File

@@ -26,11 +26,11 @@
/*-------------------FASTLED topics & parameters----------------------*/
//FASTLED MQTT Subjects
#define subjectMQTTtoFASTLED "/commands/MQTTtoFASTLED"
#define subjectMQTTtoFASTLEDsetled "/commands/MQTTtoFASTLED/setled" //set only one LED with JSON struct {"led":0-x,"hex":"#000000","blink":true/false}
#define subjectMQTTtoFASTLED "/commands/MQTTtoFASTLED"
#define subjectMQTTtoFASTLEDsetled "/commands/MQTTtoFASTLED/setled" //set only one LED with JSON struct {"led":0-x,"hex":"#000000","blink":true/false}
#define subjectMQTTtoFASTLEDsetbrightness "/commands/MQTTtoFASTLED/setbrightness" //set the brightness 0-255
#define subjectMQTTtoFASTLEDsetanimation "/commands/MQTTtoFASTLED/setanimation" //Animation Fire2012 by Mark Kriegsman
#define subjectGTWFASTLEDtoMQTT "/FASTLEDtoMQTT" //same color on all LEDs in #RRGGBB
#define subjectMQTTtoFASTLEDsetanimation "/commands/MQTTtoFASTLED/setanimation" //Animation Fire2012 by Mark Kriegsman
#define subjectGTWFASTLEDtoMQTT "/FASTLEDtoMQTT" //same color on all LEDs in #RRGGBB
// How many leds in your strip?
#define FASTLED_NUM_LEDS 16
@@ -72,15 +72,15 @@
#ifdef ESP8266
//#define FASTLED_ESP8266_RAW_PIN_ORDER
//#define FASTLED_ESP8266_NODEMCU_PIN_ORDER
#define FASTLED_ESP8266_D1_PIN_ORDER
#define FASTLED_DATA_PIN D2 // only D2 works by me
# define FASTLED_ESP8266_D1_PIN_ORDER
# define FASTLED_DATA_PIN D2 // only D2 works by me
//#define FASTLED_CLOCK_PIN 13
#elif ESP32
#define FASTLED_DATA_PIN 16
#define FASTLED_CLOCK_PIN 13
# define FASTLED_DATA_PIN 16
# define FASTLED_CLOCK_PIN 13
#else
#define FASTLED_DATA_PIN 10
#define FASTLED_CLOCK_PIN 13
# define FASTLED_DATA_PIN 10
# define FASTLED_CLOCK_PIN 13
#endif
#endif
#endif

View File

@@ -30,16 +30,16 @@ extern void setupGPIOInput();
extern void GPIOInputtoMQTT();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectGPIOInputtoMQTT "/GPIOInputtoMQTT"
#define subjectGPIOInputtoMQTT "/GPIOInputtoMQTT"
#define GPIOInputDebounceDelay 60 //debounce time, increase if there are issues
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef GPIOInput_PIN
#if defined(ESP8266) || defined(ESP32)
#define GPIOInput_PIN 13
#else
#define GPIOInput_PIN 7
#endif
# if defined(ESP8266) || defined(ESP32)
# define GPIOInput_PIN 13
# else
# define GPIOInput_PIN 7
# endif
#endif
#endif

View File

@@ -30,30 +30,30 @@ extern void setupGPIOKeyCode();
extern void GPIOKeyCodetoMQTT();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectGPIOKeyCodetoMQTT "/keycode"
#define subjectGPIOKeyCodetoMQTT "/keycode"
#define subjectGPIOKeyCodeStatetoMQTT subjectGPIOKeyCodetoMQTT "/status"
#define GPIOKeyCodeDebounceDelay 60 //debounce time, increase if there are issues
#define GPIOKeyCodeDebounceDelay 60 //debounce time, increase if there are issues
/*-------------------PIN DEFINITIONS----------------------*/
#if defined(ESP8266) || defined(ESP32)
#ifndef GPIOKeyCode_LATCH_PIN
#define GPIOKeyCode_LATCH_PIN 12 //D6
#endif
#ifndef GPIOKeyCode_D0_PIN
#define GPIOKeyCode_D0_PIN 14 //D5
#endif
#ifndef GPIOKeyCode_D1_PIN
#define GPIOKeyCode_D1_PIN 5 //D1
#endif
#ifndef GPIOKeyCode_D2_PIN
#define GPIOKeyCode_D2_PIN 13 //D7
#endif
#ifndef GPIOKeyCode_D3_PIN
#define GPIOKeyCode_D3_PIN XX //??
#endif
# ifndef GPIOKeyCode_LATCH_PIN
# define GPIOKeyCode_LATCH_PIN 12 //D6
# endif
# ifndef GPIOKeyCode_D0_PIN
# define GPIOKeyCode_D0_PIN 14 //D5
# endif
# ifndef GPIOKeyCode_D1_PIN
# define GPIOKeyCode_D1_PIN 5 //D1
# endif
# ifndef GPIOKeyCode_D2_PIN
# define GPIOKeyCode_D2_PIN 13 //D7
# endif
# ifndef GPIOKeyCode_D3_PIN
# define GPIOKeyCode_D3_PIN XX //??
# endif
#else
// must define !!!
// must define !!!
#endif
#endif

View File

@@ -40,23 +40,23 @@
extern void setupHCSR04();
extern void MeasureDistance();
#define HCSR04_always true // If false, the current value of the parameter is the same as previous one don't send it by MQTT
#define HCSR04_always true // If false, the current value of the parameter is the same as previous one don't send it by MQTT
#define TimeBetweenReadingHCSR04 5000
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectHCSR04 "/DISTtoMQTT/sr04"
#define subjectHCSR04 "/DISTtoMQTT/sr04"
/*-------------------PIN DEFINITIONS----------------------*/
#if defined(ESP8266)
#define HCSR04_TRI_PIN D6
#define HCSR04_ECH_PIN D7
# define HCSR04_TRI_PIN D6
# define HCSR04_ECH_PIN D7
#elif defined(ESP32)
#define HCSR04_TRI_PIN 16 // NOT TESTED
#define HCSR04_ECH_PIN 17 // NOT TESTED
# define HCSR04_TRI_PIN 16 // NOT TESTED
# define HCSR04_ECH_PIN 17 // NOT TESTED
#else
#define HCSR04_TRI_PIN 6 // NOT TESTED
#define HCSR04_ECH_PIN 5 // NOT TESTED
# define HCSR04_TRI_PIN 6 // NOT TESTED
# define HCSR04_ECH_PIN 5 // NOT TESTED
#endif
#endif

View File

@@ -30,21 +30,21 @@ extern void setupHCSR501();
extern void HCSR501toMQTT();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectHCSR501toMQTT "/HCSR501toMQTT"
#define subjectHCSR501toMQTT "/HCSR501toMQTT"
#ifndef TimeBeforeStartHCSR501
#define TimeBeforeStartHCSR501 60000 //define the time necessary for HC SR501 init
# define TimeBeforeStartHCSR501 60000 //define the time necessary for HC SR501 init
#endif
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef HCSR501_PIN
#if defined(ESP8266)
#define HCSR501_PIN D5
#elif defined(ESP32)
#define HCSR501_PIN 5
#else
#define HCSR501_PIN 7
#endif
# if defined(ESP8266)
# define HCSR501_PIN D5
# elif defined(ESP32)
# define HCSR501_PIN 5
# else
# define HCSR501_PIN 7
# endif
#endif
#endif

View File

@@ -41,18 +41,18 @@
extern void setupHTU21();
extern void HTU21toMQTT();
#define htu21_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT
#define htu21_always true // if false when the current value of the parameter is the same as previous one don't send it by MQTT
#define TimeBetweenReadinghtu21 30000
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define HTUTOPIC "/CLIMAtoMQTT/htu"
#define HTUTOPIC "/CLIMAtoMQTT/htu"
#if defined(ESP32)
#if !defined(I2C_SDA) || !defined(I2C_SCL)
#define I2C_SDA 16
#define I2C_SCL 0
#endif
# if !defined(I2C_SDA) || !defined(I2C_SCL)
# define I2C_SDA 16
# define I2C_SCL 0
# endif
#endif
#endif

View File

@@ -30,7 +30,7 @@ extern void setupINA226();
extern void INA226toMQTT();
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectINA226toMQTT "/INA226toMQTT"
#define subjectINA226toMQTT "/INA226toMQTT"
#define TimeBetweenReadingINA226 30000 // time between 2 INA226 readings
#endif
#endif

View File

@@ -27,146 +27,146 @@
#define config_IR_h
extern void setupIR();
extern void IRtoMQTT();
extern void MQTTtoIR(char * topicOri, char * datacallback);
extern void MQTTtoIR(char * topicOri, JsonObject& RFdata);
extern void IRtoMQTT();
extern void MQTTtoIR(char* topicOri, char* datacallback);
extern void MQTTtoIR(char* topicOri, JsonObject& RFdata);
/*-------------------IR topics & parameters----------------------*/
//IR MQTT Subjects
#define subjectGTWIRtoMQTT "/IRtoMQTT"
#define subjectIRtoMQTT "/IRtoMQTT"
#define subjectMQTTtoIR "/commands/MQTTtoIR"
#define subjectGTWIRtoMQTT "/IRtoMQTT"
#define subjectIRtoMQTT "/IRtoMQTT"
#define subjectMQTTtoIR "/commands/MQTTtoIR"
// subject monitored to listen traffic processed by other gateways to store data and avoid ntuple
#define subjectMultiGTWIR "+/+/IRtoMQTT"
#define IRbitsKey "IRBITS_" // bits will be defined if a subject contains IRbitsKey followed by a value of 2 digits
#define IRRptKey "RPT_" // repeats will be defined if a subject contains IRRptKey followed by a value of 1 digit
#define repeatIRwMQTT false // do we repeat a received signal by using mqtt
#define repeatIRwNumber 0 // default repeat of the signal
#define IRbitsKey "IRBITS_" // bits will be defined if a subject contains IRbitsKey followed by a value of 2 digits
#define IRRptKey "RPT_" // repeats will be defined if a subject contains IRRptKey followed by a value of 1 digit
#define repeatIRwMQTT false // do we repeat a received signal by using mqtt
#define repeatIRwNumber 0 // default repeat of the signal
//#define RawDirectForward false // direct repeat of IR signal with raw data
#define RawFrequency 38 // raw frequency sending
//#define DumpMode true // uncomment so as to see big dumps of IR codes
#define pubIRunknownPrtcl false // key to avoid mqtt publication of unknown IR protocol (set to true if you want to publish unknown protocol)
#define PanasonicAddress 0x4004 // Panasonic address (Pre data)
#define PanasonicAddress 0x4004 // Panasonic address (Pre data)
#if defined(ESP8266) || defined(ESP32) //IR supported protocols on ESP8266, all supported per default
#define IR_GC
#define IR_RAW
#define IR_COOLIX
#define IR_WHYNTER
#define IR_LG
#define IR_SONY
#define IR_DISH
#define IR_RC5
#define IR_RC6
#define IR_SHARP
#define IR_SAMSUNG
#define IR_PANASONIC
#define IR_RCMM
#define IR_MITSUBISHI
#define IR_GICABLE
#define IR_MITSUBISHI2
#define IR_LASERTAG
#define IR_CARRIER_AC
#define IR_MIDEA
#define IR_NIKAI
#define IR_SHERWOOD
#define IR_DENON
#define IR_AIWA_RC_T501
#define IR_JVC
#define IR_SANYO
#define IR_DAIKIN
#define IR_KELVINATOR
#define IR_MITSUBISHI_AC
#define IR_SANYO_LC7461
#define IR_GREE
#define IR_ARGO
#define IR_TROTEC
#define IR_TOSHIBA_AC
#define IR_FUJITSU_AC
#define IR_MAGIQUEST
#define IR_HAIER_AC
#define IR_HITACHI_AC
#define IR_HITACHI_AC1
#define IR_HITACHI_AC2
#define IR_GICABLE
#define IR_HAIER_AC_YRW02
#define IR_WHIRLPOOL_AC
#define IR_SAMSUNG_AC
#define IR_LUTRON
#define IR_ELECTRA_AC
#define IR_PANASONIC_AC
#define IR_PIONEER
#define IR_LG2
#define IR_MWM
#define IR_DAIKIN2
#define IR_VESTEL_AC
#define IR_SAMSUNG36
#define IR_TCL112AC
#define IR_TECO
#define IR_LEGOPF
#define IR_MITSUBISHI_HEAVY_88
#define IR_MITSUBISHI_HEAVY_152
#define IR_DAIKIN216
#define IR_SHARP_AC
#define IR_GOODWEATHER
#define IR_INAX
#define IR_DAIKIN160
#define IR_NEOCLIMA
#define IR_DAIKIN176
#define IR_DAIKIN128
#define IR_AMCOR
#define IR_DAIKIN152
#define IR_MITSUBISHI136
#define IR_MITSUBISHI112
#define IR_HITACHI_AC424
#if defined(ESP8266) || defined(ESP32) //IR supported protocols on ESP8266, all supported per default
# define IR_GC
# define IR_RAW
# define IR_COOLIX
# define IR_WHYNTER
# define IR_LG
# define IR_SONY
# define IR_DISH
# define IR_RC5
# define IR_RC6
# define IR_SHARP
# define IR_SAMSUNG
# define IR_PANASONIC
# define IR_RCMM
# define IR_MITSUBISHI
# define IR_GICABLE
# define IR_MITSUBISHI2
# define IR_LASERTAG
# define IR_CARRIER_AC
# define IR_MIDEA
# define IR_NIKAI
# define IR_SHERWOOD
# define IR_DENON
# define IR_AIWA_RC_T501
# define IR_JVC
# define IR_SANYO
# define IR_DAIKIN
# define IR_KELVINATOR
# define IR_MITSUBISHI_AC
# define IR_SANYO_LC7461
# define IR_GREE
# define IR_ARGO
# define IR_TROTEC
# define IR_TOSHIBA_AC
# define IR_FUJITSU_AC
# define IR_MAGIQUEST
# define IR_HAIER_AC
# define IR_HITACHI_AC
# define IR_HITACHI_AC1
# define IR_HITACHI_AC2
# define IR_GICABLE
# define IR_HAIER_AC_YRW02
# define IR_WHIRLPOOL_AC
# define IR_SAMSUNG_AC
# define IR_LUTRON
# define IR_ELECTRA_AC
# define IR_PANASONIC_AC
# define IR_PIONEER
# define IR_LG2
# define IR_MWM
# define IR_DAIKIN2
# define IR_VESTEL_AC
# define IR_SAMSUNG36
# define IR_TCL112AC
# define IR_TECO
# define IR_LEGOPF
# define IR_MITSUBISHI_HEAVY_88
# define IR_MITSUBISHI_HEAVY_152
# define IR_DAIKIN216
# define IR_SHARP_AC
# define IR_GOODWEATHER
# define IR_INAX
# define IR_DAIKIN160
# define IR_NEOCLIMA
# define IR_DAIKIN176
# define IR_DAIKIN128
# define IR_AMCOR
# define IR_DAIKIN152
# define IR_MITSUBISHI136
# define IR_MITSUBISHI112
# define IR_HITACHI_AC424
#elif __AVR_ATmega2560__
#define IR_COOLIX
#define IR_Whynter
#define IR_LG
#define IR_Sony
#define IR_DISH
#define IR_RC5
#define IR_Sharp
#define IR_SAMSUNG
#define IR_Raw
#define IR_PANASONIC
# define IR_COOLIX
# define IR_Whynter
# define IR_LG
# define IR_Sony
# define IR_DISH
# define IR_RC5
# define IR_Sharp
# define IR_SAMSUNG
# define IR_Raw
# define IR_PANASONIC
#else //IR supported protocols on arduino uncomment if you want to send with this protocol, NEC protocol is available per default
//#define IR_COOLIX
//#define IR_Whynter
//#define IR_LG
//#define IR_Sony
//#define IR_DISH
//#define IR_RC5
//#define IR_Sharp
//#define IR_SAMSUNG
//#define IR_Raw
//#define IR_PANASONIC
//#define IR_COOLIX
//#define IR_Whynter
//#define IR_LG
//#define IR_Sony
//#define IR_DISH
//#define IR_RC5
//#define IR_Sharp
//#define IR_SAMSUNG
//#define IR_Raw
//#define IR_PANASONIC
#endif
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef IR_RECEIVER_PIN
#ifdef ESP8266
#define IR_RECEIVER_PIN 2 //D4 /replace by 4 with sonoff rf bridge
#elif ESP32
#define IR_RECEIVER_PIN 26
#elif __AVR_ATmega2560__
#define IR_RECEIVER_PIN 2 // 2 = D2 on arduino mega
#else
#define IR_RECEIVER_PIN 0 // 0 = D2 on arduino UNO
#endif
# ifdef ESP8266
# define IR_RECEIVER_PIN 2 //D4 /replace by 4 with sonoff rf bridge
# elif ESP32
# define IR_RECEIVER_PIN 26
# elif __AVR_ATmega2560__
# define IR_RECEIVER_PIN 2 // 2 = D2 on arduino mega
# else
# define IR_RECEIVER_PIN 0 // 0 = D2 on arduino UNO
# endif
#endif
#ifndef IR_EMITTER_PIN
#ifdef ESP8266
#define IR_EMITTER_PIN 16 //D0/ replace by 0 (D3) if you use IR LOLIN controller shield /replace by 5 with sonoff rf bridge
#elif ESP32
#define IR_EMITTER_PIN 14
#elif __AVR_ATmega2560__
#define IR_EMITTER_PIN 9
#else
#define IR_EMITTER_PIN 9
#endif
# ifdef ESP8266
# define IR_EMITTER_PIN 16 //D0/ replace by 0 (D3) if you use IR LOLIN controller shield /replace by 5 with sonoff rf bridge
# elif ESP32
# define IR_EMITTER_PIN 14
# elif __AVR_ATmega2560__
# define IR_EMITTER_PIN 9
# else
# define IR_EMITTER_PIN 9
# endif
#endif
#endif
#endif

View File

@@ -27,13 +27,13 @@
#define config_LORA_h
extern void setupLORA();
extern void LORAtoMQTT();
extern void MQTTtoLORA(char * topicOri, char * datacallback);
extern void MQTTtoLORA(char * topicOri, JsonObject& RFdata);
extern void LORAtoMQTT();
extern void MQTTtoLORA(char* topicOri, char* datacallback);
extern void MQTTtoLORA(char* topicOri, JsonObject& RFdata);
/*----------------------LORA topics & parameters-------------------------*/
#define subjectLORAtoMQTT "/LORAtoMQTT"
#define subjectMQTTtoLORA "/commands/MQTTtoLORA"
#define subjectGTWLORAtoMQTT "/LORAtoMQTT"
#define subjectLORAtoMQTT "/LORAtoMQTT"
#define subjectMQTTtoLORA "/commands/MQTTtoLORA"
#define subjectGTWLORAtoMQTT "/LORAtoMQTT"
//Default parameters used when the parameters are not set in the json data
#define LORA_BAND 868E6
@@ -49,11 +49,11 @@ extern void MQTTtoLORA(char * topicOri, JsonObject& RFdata);
/*-------------------PIN DEFINITIONS----------------------*/
//TTGO LORA BOARD ESP32 PIN DEFINITION
#define LORA_SCK 5 // GPIO5 -- SX1278's SCK
#define LORA_MISO 19 // GPIO19 -- SX1278's MISO
#define LORA_MOSI 27 // GPIO27 -- SX1278's MOSI
#define LORA_SS 18 // GPIO18 -- SX1278's CS
#define LORA_RST 14 // GPIO14 -- SX1278's RESET
#define LORA_DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request)
#define LORA_SCK 5 // GPIO5 -- SX1278's SCK
#define LORA_MISO 19 // GPIO19 -- SX1278's MISO
#define LORA_MOSI 27 // GPIO27 -- SX1278's MOSI
#define LORA_SS 18 // GPIO18 -- SX1278's CS
#define LORA_RST 14 // GPIO14 -- SX1278's RESET
#define LORA_DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request)
#endif

View File

@@ -27,10 +27,10 @@
#define config_M5_h
#ifdef ZboardM5STICKC
#include <M5StickC.h>
# include <M5StickC.h>
#endif
#ifdef ZboardM5STACK
#include <M5Stack.h>
# include <M5Stack.h>
#endif
extern void setupM5();
@@ -38,15 +38,15 @@ extern void loopM5();
/*----------------------------USER PARAMETERS-----------------------------*/
/*---------------DEFINE SCREEN BRIGHTNESS------------------*/
#ifndef SLEEP_LCD_BRIGHTNESS
#define SLEEP_LCD_BRIGHTNESS 2 // 0 to 100
# define SLEEP_LCD_BRIGHTNESS 2 // 0 to 100
#endif
#ifndef NORMAL_LCD_BRIGHTNESS
#define NORMAL_LCD_BRIGHTNESS 100 // 0 to 100
# define NORMAL_LCD_BRIGHTNESS 100 // 0 to 100
#endif
/*-------------------DEFINE LOG LEVEL----------------------*/
#define LOG_LEVEL_LCD LOG_LEVEL_WARNING // if we go down below warning the size of the text to display can make the M5 restarting
#define LOG_TO_LCD true //set to false if you want to use serial monitor for the log per default instead of the M5 screen
#define LOG_TO_LCD true //set to false if you want to use serial monitor for the log per default instead of the M5 screen
/*-------------------DEFINE MQTT TOPIC FOR CONFIG----------------------*/
#define subjectMQTTtoM5set "/commands/MQTTtoM5/config"
#define subjectMQTTtoM5set "/commands/MQTTtoM5/config"
#endif

View File

@@ -27,26 +27,26 @@
#define config_ONOFF_h
extern void setupONOFF();
extern void MQTTtoONOFF(char * topicOri, char * datacallback);
extern void MQTTtoONOFF(char * topicOri, JsonObject& RFdata);
extern void MQTTtoONOFF(char* topicOri, char* datacallback);
extern void MQTTtoONOFF(char* topicOri, JsonObject& RFdata);
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectMQTTtoONOFF "/commands/MQTTtoONOFF"
#define subjectGTWONOFFtoMQTT "/ONOFFtoMQTT"
#define subjectMQTTtoONOFF "/commands/MQTTtoONOFF"
#define subjectGTWONOFFtoMQTT "/ONOFFtoMQTT"
#define ONKey "setON"
#define ONKey "setON"
#define OFFKey "setOFF"
/*-------------------PIN DEFINITIONS----------------------*/
// default pin, if not set into the MQTT json
#ifndef ACTUATOR_ONOFF_PIN
#ifdef ESP8266
#define ACTUATOR_ONOFF_PIN 15 //12 for sonoff basic relay
#elif ESP32
#define ACTUATOR_ONOFF_PIN 15
#else
#define ACTUATOR_ONOFF_PIN 13
#endif
# ifdef ESP8266
# define ACTUATOR_ONOFF_PIN 15 //12 for sonoff basic relay
# elif ESP32
# define ACTUATOR_ONOFF_PIN 15
# else
# define ACTUATOR_ONOFF_PIN 13
# endif
#endif
#endif
#endif

View File

@@ -32,29 +32,29 @@
#ifdef ZgatewayRF
extern void setupRF();
extern void RFtoMQTT();
extern void MQTTtoRF(char *topicOri, char *datacallback);
extern void MQTTtoRF(char *topicOri, JsonObject &RFdata);
extern void MQTTtoRF(char* topicOri, char* datacallback);
extern void MQTTtoRF(char* topicOri, JsonObject& RFdata);
#endif
#ifdef ZgatewayRF2
extern void setupRF2();
extern void RF2toMQTT();
extern void MQTTtoRF2(char *topicOri, char *datacallback);
extern void MQTTtoRF2(char *topicOri, JsonObject &RFdata);
extern void MQTTtoRF2(char* topicOri, char* datacallback);
extern void MQTTtoRF2(char* topicOri, JsonObject& RFdata);
#endif
#ifdef ZgatewayPilight
extern void setupPilight();
extern void PilighttoMQTT();
extern void MQTTtoPilight(char *topicOri, char *datacallback);
extern void MQTTtoPilight(char *topicOri, JsonObject &RFdata);
extern void MQTTtoPilight(char* topicOri, char* datacallback);
extern void MQTTtoPilight(char* topicOri, JsonObject& RFdata);
#endif
/*-------------------RF topics & parameters----------------------*/
//433Mhz MQTT Subjects and keys
#define subjectMQTTtoRF "/commands/MQTTto433"
#define subjectRFtoMQTT "/433toMQTT"
#define subjectMQTTtoRF "/commands/MQTTto433"
#define subjectRFtoMQTT "/433toMQTT"
#define subjectGTWRFtoMQTT "/433toMQTT"
#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit
#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits
#define repeatRFwMQTT false // do we repeat a received signal by using mqtt with RF gateway
#define RFprotocolKey "433_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit
#define RFbitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits
#define repeatRFwMQTT false // do we repeat a received signal by using mqtt with RF gateway
/*
RF supported protocols
@@ -73,52 +73,52 @@ RF supported protocols
/*-------------------RF2 topics & parameters----------------------*/
//433Mhz newremoteswitch MQTT Subjects and keys
#define subjectMQTTtoRF2 "/commands/MQTTtoRF2"
#define subjectRF2toMQTT "/RF2toMQTT"
#define subjectMQTTtoRF2 "/commands/MQTTtoRF2"
#define subjectRF2toMQTT "/RF2toMQTT"
#define subjectGTWRF2toMQTT "/433toMQTT"
#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits
#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits
#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits
#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit
#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits
#define RF2codeKey "ADDRESS_" // code will be defined if a subject contains RF2codeKey followed by a value of 7 digits
#define RF2periodKey "PERIOD_" // period will be defined if a subject contains RF2periodKey followed by a value of 3 digits
#define RF2unitKey "UNIT_" // number of your unit value will be defined if a subject contains RF2unitKey followed by a value of 1-2 digits
#define RF2groupKey "GROUP_" // number of your group value will be defined if a subject contains RF2groupKey followed by a value of 1 digit
#define RF2dimKey "DIM" // number of your dim value will be defined if a subject contains RF2dimKey and the payload contains the dim value as digits
/*-------------------ESPPiLight topics & parameters----------------------*/
//433Mhz Pilight MQTT Subjects and keys
#define subjectMQTTtoPilight "/commands/MQTTtoPilight"
#define subjectPilighttoMQTT "/PilighttoMQTT"
#define subjectMQTTtoPilight "/commands/MQTTtoPilight"
#define subjectPilighttoMQTT "/PilighttoMQTT"
#define subjectGTWPilighttoMQTT "/PilighttoMQTT"
#define PilightRAW "RAW"
#define repeatPilightwMQTT false // do we repeat a received signal by using mqtt with Pilight gateway
#define PilightRAW "RAW"
#define repeatPilightwMQTT false // do we repeat a received signal by using mqtt with Pilight gateway
/*-------------------CC1101 frequency----------------------*/
//Match frequency to the hardware version of the radio if ZradioCC1101 is used.
#define CC1101_FREQUENCY 433.92
//Match frequency to the hardware version of the radio if ZradioCC1101 is used.
#define CC1101_FREQUENCY 433.92
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef RF_RECEIVER_PIN
#ifdef ESP8266
#define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod
#elif ESP32
#define RF_RECEIVER_PIN 27 // D27 on DOIT ESP32
#elif __AVR_ATmega2560__
#define RF_RECEIVER_PIN 1 //1 = D3 on mega
#else
#define RF_RECEIVER_PIN 1 //1 = D3 on arduino
#endif
# ifdef ESP8266
# define RF_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod
# elif ESP32
# define RF_RECEIVER_PIN 27 // D27 on DOIT ESP32
# elif __AVR_ATmega2560__
# define RF_RECEIVER_PIN 1 //1 = D3 on mega
# else
# define RF_RECEIVER_PIN 1 //1 = D3 on arduino
# endif
#endif
#ifndef RF_EMITTER_PIN
#ifdef ESP8266
#define RF_EMITTER_PIN 3 // RX on nodemcu if it doesn't work with 3, try with 4 (D2) // put 5 with rf bridge direct mod
#elif ESP32
#define RF_EMITTER_PIN 12 // D12 on DOIT ESP32
#elif __AVR_ATmega2560__
#define RF_EMITTER_PIN 4
#else
//IMPORTANT NOTE: On arduino UNO connect IR emitter pin to D9 , comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library <library>IRremote/boarddefs.h so as to free pin D3 for RF RECEIVER PIN
//RF PIN definition
#define RF_EMITTER_PIN 4 //4 = D4 on arduino
#endif
# ifdef ESP8266
# define RF_EMITTER_PIN 3 // RX on nodemcu if it doesn't work with 3, try with 4 (D2) // put 5 with rf bridge direct mod
# elif ESP32
# define RF_EMITTER_PIN 12 // D12 on DOIT ESP32
# elif __AVR_ATmega2560__
# define RF_EMITTER_PIN 4
# else
//IMPORTANT NOTE: On arduino UNO connect IR emitter pin to D9 , comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library <library>IRremote/boarddefs.h so as to free pin D3 for RF RECEIVER PIN
//RF PIN definition
# define RF_EMITTER_PIN 4 //4 = D4 on arduino
# endif
#endif
#endif
#endif

View File

@@ -27,17 +27,17 @@
#define config_RFM69_h
extern void setupRFM69();
extern bool RFM69toMQTT();
extern void MQTTtoRFM69(char * topicOri, char * datacallback);
extern void MQTTtoRFM69(char * topicOri, JsonObject& RFdata);
extern bool RFM69toMQTT();
extern void MQTTtoRFM69(char* topicOri, char* datacallback);
extern void MQTTtoRFM69(char* topicOri, JsonObject& RFdata);
/*----------------------RFM69 topics & parameters -------------------------*/
// Topic where the message from RFM69 will be published by the gateway,
// appended with the nodeID of the sender
#define subjectRFM69toMQTT "/RFM69toMQTT"
#define subjectRFM69toMQTT "/RFM69toMQTT"
// Topic subscribed by the gateway. Messages received will be sent to RFM69
#define subjectMQTTtoRFM69 "/commands/MQTTtoRFM69"
#define RFM69receiverKey "RCV_" // receiver id will be defined if a subject contains RFM69receiverKey followed by a value of 3 digits
#define subjectMQTTtoRFM69 "/commands/MQTTtoRFM69"
#define RFM69receiverKey "RCV_" // receiver id will be defined if a subject contains RFM69receiverKey followed by a value of 3 digits
// On reception of an ack from RFM69, the message that has been sent is published here
#define subjectGTWRFM69toMQTT "/RFM69toMQTT/acked"
#define defaultRFM69ReceiverId 99
@@ -47,33 +47,33 @@ const char PROGMEM ENCRYPTKEY[] = "sampleEncryptKey";
const char PROGMEM MDNS_NAME[] = "rfm69gw1";
const char PROGMEM MQTT_BROKER[] = "raspi2";
const char PROGMEM RFM69AP_NAME[] = "RFM69-AP";
#define NETWORKID 200 //the same on all nodes that talk to each other
#define NODEID 10
#define NETWORKID 200 //the same on all nodes that talk to each other
#define NODEID 10
//Match frequency to the hardware version of the radio
#define FREQUENCY RF69_433MHZ
#define FREQUENCY RF69_433MHZ
//#define FREQUENCY RF69_868MHZ
//#define FREQUENCY RF69_915MHZ
#define IS_RFM69HCW true // set to 'true' if you are using an RFM69HCW module
#define POWER_LEVEL 31
#define IS_RFM69HCW true // set to 'true' if you are using an RFM69HCW module
#define POWER_LEVEL 31
/*-------------------PIN DEFINITIONS----------------------*/
#if defined(ESP8266)
#define RFM69_CS D1
#define RFM69_IRQ D8 // GPIO15/D8
#define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ)
#define RFM69_RST D4 // GPIO02/D4
# define RFM69_CS D1
# define RFM69_IRQ D8 // GPIO15/D8
# define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ)
# define RFM69_RST D4 // GPIO02/D4
#elif defined(ESP32)
#define RFM69_CS 1
#define RFM69_IRQ 8 // GPIO15/D8
#define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ)
#define RFM69_RST 4 // GPIO02/D4
# define RFM69_CS 1
# define RFM69_IRQ 8 // GPIO15/D8
# define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ)
# define RFM69_RST 4 // GPIO02/D4
#else
//RFM69 not tested with arduino
#define RFM69_CS 10
#define RFM69_IRQ 0
#define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ)
#define RFM69_RST 9
//RFM69 not tested with arduino
# define RFM69_CS 10
# define RFM69_IRQ 0
# define RFM69_IRQN digitalPinToInterrupt(RFM69_IRQ)
# define RFM69_RST 9
#endif
#endif
#endif

View File

@@ -28,19 +28,19 @@
#define config_SRFB_h
extern void setupSRFB();
extern bool SRFBtoMQTT();
extern void MQTTtoSRFB(char * topicOri, char * datacallback);
extern void MQTTtoSRFB(char * topicOri, JsonObject& RFdata);
extern bool SRFBtoMQTT();
extern void MQTTtoSRFB(char* topicOri, char* datacallback);
extern void MQTTtoSRFB(char* topicOri, JsonObject& RFdata);
/*-------------------RF topics & parameters----------------------*/
//433Mhz MQTT Subjects and keys
#define subjectMQTTtoSRFB "/commands/MQTTtoSRFB"
#define subjectMQTTtoSRFBRaw "/commands/MQTTtoSRFB/Raw"
#define subjectSRFBtoMQTT "/SRFBtoMQTT"
#define subjectGTWSRFBtoMQTT "/SRFBtoMQTT"
#define SRFBRptKey "RPT_"
#define subjectMQTTtoSRFB "/commands/MQTTtoSRFB"
#define subjectMQTTtoSRFBRaw "/commands/MQTTtoSRFB/Raw"
#define subjectSRFBtoMQTT "/SRFBtoMQTT"
#define subjectGTWSRFBtoMQTT "/SRFBtoMQTT"
#define SRFBRptKey "RPT_"
#define SRFBmaxipulselengthKey "Thigh_"
#define SRFBminipulselengthKey "Tlow_"
#define SRFBsyncKey "Tsyn_"
#define SRFBsyncKey "Tsyn_"
#define repeatSRFBwMQTT false // do we repeat a received signal by using mqtt with Sonoff RF Bridge
@@ -48,19 +48,19 @@ extern void MQTTtoSRFB(char * topicOri, JsonObject& RFdata);
// RFBRIDGE
// -----------------------------------------------------------------------------
#define RF_SEND_TIMES 4 // How many times to send the message
#define RF_SEND_DELAY 500 // Interval between sendings in ms
#define RF_RECEIVE_DELAY 500 // Interval between recieving in ms (avoid debouncing)
#define RF_SEND_TIMES 4 // How many times to send the message
#define RF_SEND_DELAY 500 // Interval between sendings in ms
#define RF_RECEIVE_DELAY 500 // Interval between recieving in ms (avoid debouncing)
// -----------------------------------------------------------------------------
// DEFINITIONS
// -----------------------------------------------------------------------------
#define RF_MESSAGE_SIZE 9
#define RF_CODE_START 0xAA
#define RF_CODE_ACK 0xA0
#define RF_CODE_RFIN 0xA4
#define RF_CODE_RFOUT 0xA5
#define RF_CODE_STOP 0x55
#define RF_MESSAGE_SIZE 9
#define RF_CODE_START 0xAA
#define RF_CODE_ACK 0xA0
#define RF_CODE_RFIN 0xA4
#define RF_CODE_RFOUT 0xA5
#define RF_CODE_STOP 0x55
#endif
#endif

View File

@@ -42,11 +42,11 @@
extern void setupTSL2561();
extern void TSL2561toMQTT();
#define tsl2561_always true // if false only send current value if it has changed
#define TimeBetweenReadingtsl2561 30000
#define tsl2561_always true // if false only send current value if it has changed
#define TimeBetweenReadingtsl2561 30000
/*----------------------------USER PARAMETERS-----------------------------*/
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectTSL12561toMQTT "/LIGHTtoMQTT"
#define subjectTSL12561toMQTT "/LIGHTtoMQTT"
//Time used to wait for an interval before resending measured values
unsigned long timetsl2561 = 0;

View File

@@ -35,18 +35,17 @@ extern void ZgatewayWeatherStationtoMQTT();
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
#define subjectRFtoMQTT "/433toMQTT"
/*-------------------PIN DEFINITIONS----------------------*/
#ifndef RF_WS_RECEIVER_PIN
#ifdef ESP8266
#define RF_WS_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod
#elif ESP32
#define RF_WS_RECEIVER_PIN 27 // D27 on DOIT ESP32
#elif __AVR_ATmega2560__
#define RF_WS_RECEIVER_PIN 1 //1 = D3 on mega
#else
#define RF_WS_RECEIVER_PIN 1 //1 = D3 on arduino
#endif
# ifdef ESP8266
# define RF_WS_RECEIVER_PIN 0 // D3 on nodemcu // put 4 with rf bridge direct mod
# elif ESP32
# define RF_WS_RECEIVER_PIN 27 // D27 on DOIT ESP32
# elif __AVR_ATmega2560__
# define RF_WS_RECEIVER_PIN 1 //1 = D3 on mega
# else
# define RF_WS_RECEIVER_PIN 1 //1 = D3 on arduino
# endif
#endif
#endif

View File

@@ -29,72 +29,72 @@
extern String getUniqueId(String name, String sufix);
extern void pubMqttDiscovery();
extern void createDiscoveryFromList(char *mac, char *sensorList[][8], int sensorCount);
extern void createDiscovery(char * sensor_type,
char * state_topic, char * s_name, char * unique_id,
char * availability_topic, char * device_class, char * value_template,
char * payload_on, char * payload_off, char * unit_of_meas,
int off_delay,
char * payload_available, char * payload_not_avalaible, bool child_device , char * command_topic);
extern void createDiscoveryFromList(char* mac, char* sensorList[][8], int sensorCount);
extern void createDiscovery(char* sensor_type,
char* state_topic, char* s_name, char* unique_id,
char* availability_topic, char* device_class, char* value_template,
char* payload_on, char* payload_off, char* unit_of_meas,
int off_delay,
char* payload_available, char* payload_not_avalaible, bool child_device, char* command_topic);
#define discovery_Topic "homeassistant"
#define DEVICEMANUFACTURER "OMG_community"
/*-------------- Auto discovery macros-----------------*/
// Set the line below to true so as to have autodiscovery working with OpenHAB
// Set the line below to true so as to have autodiscovery working with OpenHAB
#define OpenHABDiscovery false
#if OpenHABDiscovery // OpenHAB autodiscovery value key definition (is defined command is not supported by OpenHAB)
#define jsonBatt "{{ value_json.batt }}"
#define jsonLux "{{ value_json.lux }}"
#define jsonPres "{{ value_json.pres }}"
#define jsonFer "{{ value_json.fer }}"
#define jsonMoi "{{ value_json.moi }}"
#define jsonHum "{{ value_json.hum }}"
#define jsonTemp "{{ value_json.tem }}"
#define jsonStep "{{ value_json.steps }}"
#define jsonWeight "{{ value_json.weight }}"
#define jsonPresence "{{ value_json.presence }}"
#define jsonAltim "{{ value_json.altim }}"
#define jsonAltif "{{ value_json.altift }}"
#define jsonTempf "{{ value_json.tempf }}"
#define jsonMsg "{{ value_json.message }}"
#define jsonVal "{{ value_json.value }}"
#define jsonVolt "{{ value_json.volt }}"
#define jsonCurrent "{{ value_json.current }}"
#define jsonPower "{{ value_json.power }}"
#define jsonGpio "{{ value_json.gpio }}"
#define jsonFtcd "{{ value_json.ftcd }}"
#define jsonWm2 "{{ value_json.wattsm2 }}"
#define jsonAdc "{{ value_json.adc }}"
#define jsonPa "{{ float(value_json.pa) * 0.01 }}"
#define jsonId "{{ value_json.id }}"
# define jsonBatt "{{ value_json.batt }}"
# define jsonLux "{{ value_json.lux }}"
# define jsonPres "{{ value_json.pres }}"
# define jsonFer "{{ value_json.fer }}"
# define jsonMoi "{{ value_json.moi }}"
# define jsonHum "{{ value_json.hum }}"
# define jsonTemp "{{ value_json.tem }}"
# define jsonStep "{{ value_json.steps }}"
# define jsonWeight "{{ value_json.weight }}"
# define jsonPresence "{{ value_json.presence }}"
# define jsonAltim "{{ value_json.altim }}"
# define jsonAltif "{{ value_json.altift }}"
# define jsonTempf "{{ value_json.tempf }}"
# define jsonMsg "{{ value_json.message }}"
# define jsonVal "{{ value_json.value }}"
# define jsonVolt "{{ value_json.volt }}"
# define jsonCurrent "{{ value_json.current }}"
# define jsonPower "{{ value_json.power }}"
# define jsonGpio "{{ value_json.gpio }}"
# define jsonFtcd "{{ value_json.ftcd }}"
# define jsonWm2 "{{ value_json.wattsm2 }}"
# define jsonAdc "{{ value_json.adc }}"
# define jsonPa "{{ float(value_json.pa) * 0.01 }}"
# define jsonId "{{ value_json.id }}"
#else // Home assistant autodiscovery value key definition
#define jsonBatt "{{ value_json.batt | is_defined }}"
#define jsonLux "{{ value_json.lux | is_defined }}"
#define jsonPres "{{ value_json.pres | is_defined }}"
#define jsonFer "{{ value_json.fer | is_defined }}"
#define jsonMoi "{{ value_json.moi | is_defined }}"
#define jsonHum "{{ value_json.hum | is_defined }}"
#define jsonTemp "{{ value_json.tem | is_defined }}"
#define jsonStep "{{ value_json.steps | is_defined }}"
#define jsonWeight "{{ value_json.weight | is_defined }}"
#define jsonPresence "{{ value_json.presence | is_defined }}"
#define jsonAltim "{{ value_json.altim | is_defined }}"
#define jsonAltif "{{ value_json.altift | is_defined }}"
#define jsonTempf "{{ value_json.tempf | is_defined }}"
#define jsonMsg "{{ value_json.message | is_defined }}"
#define jsonVal "{{ value_json.value | is_defined }}"
#define jsonVolt "{{ value_json.volt | is_defined }}"
#define jsonCurrent "{{ value_json.current | is_defined }}"
#define jsonPower "{{ value_json.power | is_defined }}"
#define jsonGpio "{{ value_json.gpio | is_defined }}"
#define jsonFtcd "{{ value_json.ftcd | is_defined }}"
#define jsonWm2 "{{ value_json.wattsm2 | is_defined }}"
#define jsonAdc "{{ value_json.adc | is_defined }}"
#define jsonPa "{{ float(value_json.pa) * 0.01 | is_defined }}"
#define jsonId "{{ value_json.id | is_defined }}"
# define jsonBatt "{{ value_json.batt | is_defined }}"
# define jsonLux "{{ value_json.lux | is_defined }}"
# define jsonPres "{{ value_json.pres | is_defined }}"
# define jsonFer "{{ value_json.fer | is_defined }}"
# define jsonMoi "{{ value_json.moi | is_defined }}"
# define jsonHum "{{ value_json.hum | is_defined }}"
# define jsonTemp "{{ value_json.tem | is_defined }}"
# define jsonStep "{{ value_json.steps | is_defined }}"
# define jsonWeight "{{ value_json.weight | is_defined }}"
# define jsonPresence "{{ value_json.presence | is_defined }}"
# define jsonAltim "{{ value_json.altim | is_defined }}"
# define jsonAltif "{{ value_json.altift | is_defined }}"
# define jsonTempf "{{ value_json.tempf | is_defined }}"
# define jsonMsg "{{ value_json.message | is_defined }}"
# define jsonVal "{{ value_json.value | is_defined }}"
# define jsonVolt "{{ value_json.volt | is_defined }}"
# define jsonCurrent "{{ value_json.current | is_defined }}"
# define jsonPower "{{ value_json.power | is_defined }}"
# define jsonGpio "{{ value_json.gpio | is_defined }}"
# define jsonFtcd "{{ value_json.ftcd | is_defined }}"
# define jsonWm2 "{{ value_json.wattsm2 | is_defined }}"
# define jsonAdc "{{ value_json.adc | is_defined }}"
# define jsonPa "{{ float(value_json.pa) * 0.01 | is_defined }}"
# define jsonId "{{ value_json.id | is_defined }}"
#endif
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"scripts": {
"docs:dev": "vuepress dev docs",
"docs:build": "vuepress build docs"
}
}
"scripts": {
"docs:dev": "vuepress dev docs",
"docs:build": "vuepress build docs"
}
}

View File

@@ -51,7 +51,7 @@
*/
/*-------------DEFINE GATEWAY NAME BELOW IT CAN ALSO BE DEFINED IN platformio.ini----------------*/
#ifndef Gateway_Name
#define Gateway_Name "OpenMQTTGateway"
# define Gateway_Name "OpenMQTTGateway"
#endif
#define Base_Topic "home/"
@@ -59,29 +59,29 @@
/*-------------DEFINE YOUR NETWORK PARAMETERS BELOW----------------*/
//#define NetworkAdvancedSetup true //uncomment if you want to set advanced network parameters for arduino boards, not uncommented you can set the IP and mac only
#ifdef NetworkAdvancedSetup // for arduino boards advanced config
// these values are only used if no dhcp configuration is available
const byte ip[] = { 192, 168, 1, 99 }; //ip adress
const byte gateway[] = { 0, 0, 0, 0 }; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns
const byte Dns[] = { 0, 0, 0, 0 }; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns
const byte subnet[] = { 255, 255, 255, 0 }; //ip adress
// these values are only used if no dhcp configuration is available
const byte ip[] = {192, 168, 1, 99}; //ip adress
const byte gateway[] = {0, 0, 0, 0}; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns
const byte Dns[] = {0, 0, 0, 0}; //ip adress, if first value is different from 0 advanced config network will be used and you should fill gateway & dns
const byte subnet[] = {255, 255, 255, 0}; //ip adress
#endif
#if defined(ESP8266)||defined(ESP32) // for nodemcu, weemos and esp8266
//#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP
#if defined(ESP8266) || defined(ESP32) // for nodemcu, weemos and esp8266
//#define ESPWifiManualSetup true //uncomment you don't want to use wifimanager for your credential settings on ESP
#else // for arduino boards
const byte ip[] = { 192, 168, 1, 99 }; //ip adress
const byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95 }; //W5100 ethernet shield mac adress
const byte ip[] = {192, 168, 1, 99}; //ip adress
const byte mac[] = {0xDE, 0xED, 0xBA, 0xFE, 0x54, 0x95}; //W5100 ethernet shield mac adress
#endif
#if defined(ESPWifiManualSetup) // for nodemcu, weemos and esp8266
#define wifi_ssid "wifi ssid"
#define wifi_password "wifi password"
# define wifi_ssid "wifi ssid"
# define wifi_password "wifi password"
#endif
#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point
#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point
#define WifiManager_password "your_password" //this is going to be the WPA2-PSK password for the initial setup access point
#define WifiManager_ssid Gateway_Name //this is the network name of the initial setup access point
#define WifiManager_ConfigPortalTimeOut 120
#define WifiManager_TimeOut 5
#define WifiManager_TimeOut 5
//#define MDNS_SD //uncomment if you want to use mdns for discovering automatically your ip server, please note that MDNS with ESP32 can cause the BLE to not work
@@ -91,7 +91,7 @@
/*-------------DEFINE YOUR MQTT PARAMETERS BELOW----------------*/
//MQTT Parameters definition
//#define mqtt_server_name "www.mqtt_broker.com" // instead of defining the server by its IP you can define it by its name, uncomment this line and set the correct MQTT server host name
#define parameters_size 20
#define parameters_size 20
#define mqtt_topic_max_size 100
char mqtt_user[parameters_size] = "your_username"; // not compulsory only if your broker needs authentication
char mqtt_pass[parameters_size] = "your_password"; // not compulsory only if your broker needs authentication
@@ -100,11 +100,11 @@ char mqtt_port[6] = "1883";
char mqtt_topic[mqtt_topic_max_size] = Base_Topic;
char gateway_name[parameters_size * 2] = Gateway_Name;
#define version_Topic "/version"
#define will_Topic "/LWT"
#define will_QoS 0
#define will_Retain true
#define will_Message "Offline"
#define version_Topic "/version"
#define will_Topic "/LWT"
#define will_QoS 0
#define will_Retain true
#define will_Message "Offline"
#define Gateway_AnnouncementMsg "Online"
#define maxMQTTretry 4 //maximum MQTT connection attempts before going to wifi setup
@@ -112,52 +112,52 @@ char gateway_name[parameters_size * 2] = Gateway_Name;
/*-------------DEFINE YOUR OTA PARAMETERS BELOW----------------*/
#define ota_hostname "OTAHOSTNAME"
#define ota_password "OTAPASSWORD"
#define ota_port 8266
#define ota_port 8266
/*-------------DEFINE PINs FOR STATUS LEDs----------------*/
#ifdef ESP8266
#define led_receive 40
#define led_send 42
#define led_info 44
# define led_receive 40
# define led_send 42
# define led_info 44
#elif ESP32
#define led_receive 40
#define led_send 42
#define led_info 44
# define led_receive 40
# define led_send 42
# define led_info 44
#elif __AVR_ATmega2560__ //arduino mega
#define led_receive 40
#define led_send 42
#define led_info 44
# define led_receive 40
# define led_send 42
# define led_info 44
#else //arduino uno/nano
#define led_receive 40
#define led_send 42
#define led_info 44
# define led_receive 40
# define led_send 42
# define led_info 44
#endif
// VCC ------------D|-----------/\/\/\/\ ----------------- Arduino PIN
// LED Resistor 270-510R
#ifndef TRIGGER_PIN
#ifdef ESP8266
#define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s)
#elif ESP32
#define TRIGGER_PIN 0 // boot button as full reset button (long press >10s)
#endif
# ifdef ESP8266
# define TRIGGER_PIN 14 // pin D5 as full reset button (long press >10s)
# elif ESP32
# define TRIGGER_PIN 0 // boot button as full reset button (long press >10s)
# endif
#endif
/*----------------------------OTHER PARAMETERS-----------------------------*/
#ifdef ZgatewaySRFB
#define SERIAL_BAUD 19200
# define SERIAL_BAUD 19200
#else
#define SERIAL_BAUD 115200
# define SERIAL_BAUD 115200
#endif
/*-------------------CHANGING THEM IS NOT COMPULSORY-----------------------*/
/*--------------MQTT general topics-----------------*/
// global MQTT subject listened by the gateway to execute commands (send RF, IR or others)
#define subjectMQTTtoX "/commands/#"
#define subjectMultiGTWKey "toMQTT"
#define subjectGTWSendKey "MQTTto"
#define subjectMQTTtoX "/commands/#"
#define subjectMultiGTWKey "toMQTT"
#define subjectGTWSendKey "MQTTto"
// key used for launching commands to the gateway
#define restartCmd "restart"
#define eraseCmd "erase"
#define restartCmd "restart"
#define eraseCmd "erase"
// define if we concatenate the values into the topic
//#define valueAsASubject true
@@ -166,16 +166,16 @@ char gateway_name[parameters_size * 2] = Gateway_Name;
#define time_avoid_duplicate 3000 // if you want to avoid duplicate mqtt message received set this to > 0, the value is the time in milliseconds during which we don't publish duplicates
#ifdef ESP32
//#define multiCore //uncomment to use multicore function of ESP32 for BLE
//#define multiCore //uncomment to use multicore function of ESP32 for BLE
#endif
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
#define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
#define ARDUINOJSON_USE_LONG_LONG 1
# define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
# define ARDUINOJSON_USE_LONG_LONG 1
#else // boards with smaller memory
#define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
# define JSON_MSG_BUFFER 64 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
#endif
#define TimeBetweenReadingSYS 120000 // time between system readings (like memory)
#define subjectSYStoMQTT "/SYStoMQTT"
#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config"
#define subjectSYStoMQTT "/SYStoMQTT"
#define subjectMQTTtoSYSset "/commands/MQTTtoSYS/config"
#endif