Some memory optimization for Arduino UNO following this thread:

https://community.openmqttgateway.com/t/arduino-uno-ethernet-shield-reboots-on-receiving-rf-signal-on-v-0-9/346/22
Rework led management to avoid use of global variables
and specify special JSON_MSG_BUFFER for arduino UNO
led can now be used for all the boards

generalize use of F macro
for memory optimization
change jsonbuffer calculation method
reduce pubsubclient max packet size for uno and nano
This commit is contained in:
Florian committed 2019-03-09 17:28:54 +01:00
1 parent a34d476f04
commit da859cc6ae
22 files changed
+166 -131

No files matched your search

+50 -54
View File
@@ -179,11 +179,6 @@ PubSubClient client(eClient);
//MQTT last attemps reconnection date
unsigned long lastReconnectAttempt = 0;
//timers for LED indicators
unsigned long timer_led_receive = 0;
unsigned long timer_led_send = 0;
unsigned long timer_led_error = 0;
boolean reconnect() {
// Loop until we're reconnected
@@ -313,20 +308,17 @@ void setup()
//Launch serial for debugging purposes
Serial.begin(SERIAL_BAUD);
//Begining ethernet connection in case of Arduino + W5100
setup_ethernet();
//setup LED status, turn all ON for short amount then leave only the RED LED ON
pinMode(led_receive, OUTPUT);
pinMode(led_send, OUTPUT);
pinMode(led_error, OUTPUT);
digitalWrite(led_receive, LOW);
digitalWrite(led_send, LOW);
digitalWrite(led_error, LOW);
delay(500);
digitalWrite(led_receive, HIGH);
digitalWrite(led_send, HIGH);
setup_ethernet();
#endif
//setup LED status
pinMode(led_receive, OUTPUT);
pinMode(led_send, OUTPUT);
pinMode(led_info, OUTPUT);
digitalWrite(led_receive, LOW);
digitalWrite(led_send, LOW);
digitalWrite(led_info, LOW);
#if defined(MDNS_SD) && defined(ESP8266)
trc(F("Connecting to MQTT by mDNS without mqtt hostname"));
connectMQTTmdns();
@@ -410,8 +402,6 @@ void setup()
trc(F("MQTT_MAX_PACKET_SIZE"));
trc(MQTT_MAX_PACKET_SIZE);
trc(F("JSON_MSG_BUFFER"));
trc(JSON_MSG_BUFFER);
trc(F("Setup OpenMQTTGateway end"));
}
@@ -448,7 +438,7 @@ bool shouldSaveConfig = true;
//callback notifying us of the need to save config
void saveConfigCallback () {
trc("Should save config");
trc(F("Should save config"));
shouldSaveConfig = true;
}
@@ -456,16 +446,16 @@ void setup_wifimanager(boolean reset_settings){
if(reset_settings) SPIFFS.format();
//read configuration from FS json
trc("mounting FS...");
trc(F("mounting FS..."));
if (SPIFFS.begin()) {
trc("mounted file system");
trc(F("mounted file system"));
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
trc("reading config file");
trc(F("reading config file"));
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
trc("opened config file");
trc(F("opened config file"));
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
@@ -475,7 +465,7 @@ void setup_wifimanager(boolean reset_settings){
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
trc("\nparsed json");
trc(F("\nparsed json"));
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
@@ -483,12 +473,12 @@ void setup_wifimanager(boolean reset_settings){
strcpy(mqtt_pass, json["mqtt_pass"]);
} else {
trc("failed to load json config");
trc(F("failed to load json config"));
}
}
}
} else {
trc("failed to mount FS");
trc(F("failed to mount FS"));
}
// The extra parameters to be configured (can be either global or just in the setup)
@@ -525,7 +515,7 @@ void setup_wifimanager(boolean reset_settings){
//if it does not connect it starts an access point with the specified name
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect(WifiManager_ssid, WifiManager_password)) {
trc("failed to connect and hit timeout");
trc(F("failed to connect and hit timeout"));
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
@@ -533,7 +523,7 @@ void setup_wifimanager(boolean reset_settings){
}
//if you get here you have connected to the WiFi
trc("connected...yeey :)");
trc(F("connected...yeey :)"));
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
@@ -543,7 +533,7 @@ void setup_wifimanager(boolean reset_settings){
//save the custom parameters to FS
if (shouldSaveConfig) {
trc("saving config");
trc(F("saving config"));
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
@@ -553,7 +543,7 @@ void setup_wifimanager(boolean reset_settings){
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
trc("failed to open config file for writing");
trc(F("failed to open config file for writing"));
}
json.printTo(Serial);
@@ -594,7 +584,7 @@ void setup_ethernet() {
trc(F("no services found"));
}else {
trc(n);
trc(" service(s) found");
trc(F(" service(s) found"));
for (int i=0; i < n; ++i) {
// Print details for each service found
trc(i + 1);
@@ -614,13 +604,14 @@ void setup_ethernet() {
void loop()
{
unsigned long now = millis();
digitalWrite(led_receive, LOW);
digitalWrite(led_info, LOW);
digitalWrite(led_send, LOW);
unsigned long now = millis();
//MQTT client connexion management
if (!client.connected()) { // not connected
//RED ON
digitalWrite(led_error, LOW);
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
@@ -630,12 +621,6 @@ void loop()
}
} else { //connected
// MQTT loop
//RED OFF
if (now - timer_led_receive > 300) {
timer_led_receive = now;
digitalWrite(led_receive, HIGH);
}
digitalWrite(led_error, HIGH);
connectedOnce = true;
client.loop();
@@ -717,28 +702,29 @@ void stateMeasures(){
unsigned long now = millis();
if (now > (timer_sys_measures + TimeBetweenReadingSYS)) {//retriving value of memory ram every TimeBetweenReadingSYS
timer_sys_measures = millis();
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& SYSdata = jsonBuffer.createObject();
trc("Uptime (s)");
trc(F("Uptime (s)"));
unsigned long uptime = millis()/1000;
trc(uptime);
SYSdata["uptime"] = uptime;
#if defined(ESP8266) || defined(ESP32)
trc("Remaining memory");
trc(F("Remaining memory"));
uint32_t freeMem;
freeMem = ESP.getFreeHeap();
SYSdata["freeMem"] = freeMem;
trc(freeMem);
trc("RSSI");
trc(F("RSSI"));
long rssi = WiFi.RSSI();
SYSdata["rssi"] = rssi;
trc(rssi);
trc("SSID");
trc(F("SSID"));
String SSID = WiFi.SSID();
SYSdata["SSID"] = SSID;
trc(SSID);
#endif
trc("Activated modules");
trc(F("Activated modules"));
String modules = "";
#ifdef ZgatewayRF
modules = modules + ZgatewayRF;
@@ -859,10 +845,10 @@ return false;
void receivingMQTT(char * topicOri, char * datacallback) {
if (strstr(topicOri, subjectMultiGTWKey) != NULL) // storing received value so as to avoid publishing this value if it has been already sent by this or another OpenMQTTGateway
{
trc(F("Storing signal"));
trc(F("Store signal"));
unsigned long data = 0;
#ifdef jsonPublishing
trc(F("Creating Json buffer"));
trc(F("Json buf."));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& jsondata = jsonBuffer.parseObject(datacallback);
if (jsondata.success()) data = jsondata["value"];
@@ -874,11 +860,9 @@ void receivingMQTT(char * topicOri, char * datacallback) {
if (data != 0) {
storeValue(data);
trc(F("Data from JSON stored"));
trc(F("Data JSON stored"));
}
}
//YELLOW ON
digitalWrite(led_send, LOW);
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
JsonObject& jsondata = jsonBuffer.parseObject(datacallback);
@@ -916,6 +900,7 @@ void receivingMQTT(char * topicOri, char * datacallback) {
#ifdef ZactuatorONOFF // outside the jsonpublishing macro due to the fact that we need to use simplepublishing with HA discovery
MQTTtoONOFF(topicOri, jsondata);
#endif
digitalWrite(led_send, HIGH);
} else { // not a json object --> simple decoding
#ifdef simpleReceiving
#ifdef ZgatewayLORA
@@ -946,6 +931,7 @@ void receivingMQTT(char * topicOri, char * datacallback) {
#ifdef ZactuatorONOFF
MQTTtoONOFF(topicOri, datacallback);
#endif
digitalWrite(led_send, HIGH);
}
//YELLOW OFF
digitalWrite(led_send, HIGH);
@@ -997,6 +983,7 @@ bool to_bool(String const& s) { // thanks Chris Jester-Young from stackoverflow
void trc(String msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1006,6 +993,7 @@ void trc(String msg){
void trc(int msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1015,6 +1003,7 @@ void trc(int msg){
void trc(unsigned int msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1024,6 +1013,7 @@ void trc(unsigned int msg){
void trc(long msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1033,6 +1023,7 @@ void trc(long msg){
void trc(unsigned long msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1042,6 +1033,7 @@ void trc(unsigned long msg){
void trc(double msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1051,6 +1043,7 @@ void trc(double msg){
void trc(float msg){
#ifdef TRACE
Serial.println(msg);
digitalWrite(led_info, HIGH);
#endif
#ifdef subjectTRACEtoMQTT
pub(subjectTRACEtoMQTT,msg);
@@ -1062,7 +1055,9 @@ void pub(char * topic, char * payload, boolean retainFlag){
}
void pub(char * topicori, JsonObject& data){
digitalWrite(led_receive, HIGH);
String topic = topicori;
#ifdef valueAsASubject
unsigned long value = data["value"];
@@ -1110,6 +1105,7 @@ void pub(char * topicori, JsonObject& data){
}
}
#endif
}
void pub(char * topic, char * payload){
+23 -5
View File
@@ -26,7 +26,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*-------------------VERSION----------------------*/
#define OMG_VERSION "0.9"
#define OMG_VERSION "0.9.1beta"
/*-------------CONFIGURE WIFIMANAGER-------------(only ESP8266 & SONOFF RFBridge)*/
/*
@@ -137,9 +137,23 @@ const byte subnet[] = { 255, 255, 255, 0 }; //ip adress
#define ota_port 8266
/*-------------DEFINE PINs FOR STATUS LEDs----------------*/
#define led_receive 40
#define led_send 42
#define led_error 44
#ifdef ESP8266
#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
#elif __AVR_ATmega2560__ //arduino mega
#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
#endif
// VCC ------------D|-----------/\/\/\/\ ----------------- Arduino PIN
// LED Resistor 270-510R
@@ -166,7 +180,11 @@ const byte subnet[] = { 255, 255, 255, 0 }; //ip adress
#define multiCore //comment to don't use multicore function of ESP32 for BLE
#endif
#define JSON_MSG_BUFFER 512 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
#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
#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
#endif
#define TimeBetweenReadingSYS 120000 // time between system readings (like memory)
#define subjectSYStoMQTT Base_Topic Gateway_Name "/SYStoMQTT"
+14 -13
View File
@@ -47,22 +47,22 @@ void setup2G(){
}
void setupGSM(boolean deleteSMS){
trc("Init 2G module: ");
trc(F("Init 2G module: "));
trc(_2G_PWR_PIN);
delay(1000);
// Power-cycle the module to reset it.
A6l.powerCycle(_2G_PWR_PIN);
trc("waiting for network connection");
trc(F("waiting for network connection"));
A6l.blockUntilReady(_2G_MODULE_BAUDRATE);
trc("A6/A7 gsm ready");
trc(F("A6/A7 gsm ready"));
signalStrengthAnalysis();
delay(1000);
// deleting all sms
if (deleteSMS){
if (A6l.deleteSMS(1,4) == A6_OK ) {
trc("delete SMS OK");
trc(F("delete SMS OK"));
}else{
trc("delete SMS KO");
trc(F("delete SMS KO"));
}
}
}
@@ -70,10 +70,10 @@ void setupGSM(boolean deleteSMS){
void signalStrengthAnalysis(){
int signalStrength = 0;
signalStrength = A6l.getSignalStrength();
trc("Signal strength: ");
trc(F("Signal strength: "));
trc(signalStrength);
if (signalStrength < _2G_MIN_SIGNAL || signalStrength > _2G_MAX_SIGNAL ) {
trc("Signal too low restart the module");
trc(F("Signal too low restart the module"));
setupGSM(false); // if we are below or above a threshold signal we relaunch the setup of GSM module
}
}
@@ -82,10 +82,11 @@ boolean _2GtoMQTT(){
// Get the memory locations of unread SMS messages.
unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 512);
trc(F("Creating SMS buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& SMSdata = jsonBuffer.createObject();
for (int i = 0; i < unreadSMSNum; i++) {
trc("New message at index: ");
trc(F("New message at index: "));
trc(unreadSMSNum);
sms = A6l.readSMS(unreadSMSLocs[i]);
SMSdata.set("message", (char *)sms.message.c_str());
@@ -117,11 +118,11 @@ boolean _2GtoMQTT(){
trc(F("MQTTto2G sms"));
trc(data);
if (A6l.sendSMS(phone_number,data) == A6_OK ) {
trc("SMS OK");
trc(F("SMS OK"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, 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
}else{
trc("SMS KO");
trc(F("SMS KO"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, "SMS KO");// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
@@ -143,11 +144,11 @@ boolean _2GtoMQTT(){
trc(F("MQTTto2G sms & phone ok"));
trc(sms);
if (A6l.sendSMS(String(phone),String(sms)) == A6_OK ) {
trc("SMS OK");
trc(F("SMS OK"));
// Acknowledgement to the GTW2G topic
pub(subjectGTW2GtoMQTT, SMSdata);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}else{
trc("SMS KO");
trc(F("SMS KO"));
pub(subjectGTW2GtoMQTT, "SMS KO");// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also
}
}else{
+4 -2
View File
@@ -53,7 +53,8 @@ Thanks to wolass https://github.com/wolass for suggesting me HM 10 and dinosd ht
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
trc(F("Creating BLE buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(6);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& BLEdata = jsonBuffer.createObject();
String mac_adress = advertisedDevice.getAddress().toString().c_str();
BLEdata.set("id", (char *)mac_adress.c_str());
@@ -247,7 +248,8 @@ Thanks to wolass https://github.com/wolass for suggesting me HM 10 and dinosd ht
if((strlen(d[0].extract)) == 12) // if a mac adress is detected we publish it
{
trc(F("Creating BLE buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& BLEdata = jsonBuffer.createObject();
#ifdef subjectHomePresence
String HomePresenceId;
+8 -11
View File
@@ -94,7 +94,8 @@ void IRtoMQTT(){
if (irrecv.decode(&results)){
trc(F("Creating IR buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& IRdata = jsonBuffer.createObject();
trc(F("Rcv. IR"));
@@ -106,10 +107,6 @@ void IRtoMQTT(){
IRdata.set("value", (unsigned long)(results.value));
IRdata.set("protocol", (int)(results.decode_type));
IRdata.set("bits",(int)(results.bits));
trc(F("LED MNG"));
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
String rawCode = "";
// Dump data
@@ -179,7 +176,7 @@ void IRtoMQTT(){
}
#ifdef IR_GC
else if(strstr(topicOri, "IR_GC") != NULL){ // sending GC data from https://irdb.globalcache.com
trc("IR_GC");
trc(F("IR_GC"));
//buffer allocation from char datacallback
uint16_t GC[count+1];
String value = "";
@@ -202,7 +199,7 @@ void IRtoMQTT(){
#endif
#ifdef IR_Raw
else if(strstr(topicOri, "IR_Raw") != NULL){ // sending Raw data
trc("IR_Raw");
trc(F("IR_Raw"));
//buffer allocation from char datacallback
#ifdef ESP8266
uint16_t Raw[count+1];
@@ -279,9 +276,9 @@ void IRtoMQTT(){
if (data != 0||raw) {
trc(F("MQTTtoIR data || raw ok"));
boolean signalSent = false;
trc("value");
trc(F("value"));
trc(data);
trc("raw");
trc(F("raw"));
trc(raw);
const char * protocol_name = IRdata["protocol_name"];
unsigned int valueBITS = IRdata["bits"];
@@ -299,7 +296,7 @@ void IRtoMQTT(){
}
#ifdef IR_GC
if(strstr(protocol_name, "IR_GC") != NULL){ // sending GC data from https://irdb.globalcache.com
trc("IR_GC");
trc(F("IR_GC"));
//buffer allocation from char datacallback
uint16_t GC[count+1];
String value = "";
@@ -322,7 +319,7 @@ void IRtoMQTT(){
#endif
#ifdef IR_Raw
if(strstr(protocol_name, "IR_Raw") != NULL){ // sending Raw data
trc("IR_Raw");
trc(F("IR_Raw"));
//buffer allocation from char datacallback
#ifdef ESP8266
uint16_t Raw[count+1];
+3 -2
View File
@@ -36,7 +36,7 @@ void setupLORA() {
LoRa.setPins(LORA_SS,LORA_RST,LORA_DI0);
if (!LoRa.begin(LORA_BAND)) {
trc("ZgatewayLORA setup failed!");
trc(F("ZgatewayLORA setup failed!"));
while (1);
}
LoRa.receive();
@@ -59,7 +59,8 @@ void setupLORA() {
void LORAtoMQTT(){
int packetSize = LoRa.parsePacket();
if (packetSize) {
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(5);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& LORAdata = jsonBuffer.createObject();
trc(F("Rcv. LORA"));
#ifdef ESP32
+2 -5
View File
@@ -47,7 +47,8 @@ void setupRF(){
void RFtoMQTT(){
if (mySwitch.available()){
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFdata = jsonBuffer.createObject();
trc(F("Rcv. RF"));
#ifdef ESP32
@@ -61,10 +62,6 @@ void RFtoMQTT(){
RFdata.set("delay", (int)mySwitch.getReceivedDelay());
mySwitch.resetAvailable();
trc(F("LED MNG"));
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
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
+2 -5
View File
@@ -68,7 +68,8 @@ void RF2toMQTT(){
if(rf2rd.hasNewData){
trc(F("Creating RF2 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RF2data = jsonBuffer.createObject();
rf2rd.hasNewData = false;
@@ -80,10 +81,6 @@ void RF2toMQTT(){
RF2data.set("address", (unsigned long)rf2rd.address);
RF2data.set("switchType", (int)rf2rd.switchType);
trc(F("LED MNG"));
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
trc(F("Adv data RF2toMQTT"));
pub(subjectRF2toMQTT,RF2data);
}
+2 -5
View File
@@ -47,7 +47,8 @@ void setupRF315(){
boolean RF315toMQTT(){
if (mySwitch315.available()){
trc(F("Creating RF315 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RF315data = jsonBuffer.createObject();
trc(F("Rcv. RF315"));
#ifdef ESP32
@@ -61,10 +62,6 @@ boolean RF315toMQTT(){
RF315data.set("delay", (int)mySwitch315.getReceivedDelay());
mySwitch315.resetAvailable();
trc(F("LED MNG"));
digitalWrite(led_receive, LOW);
timer_led_receive = millis();
unsigned long MQTTvalue = RF315data.get<unsigned long>("value");
if (!isAduplicate(MQTTvalue) && MQTTvalue!=0) {// conditions to avoid duplications of RF -->MQTT
trc(F("Adv data RF315toMQTT"));
+4 -3
View File
@@ -71,7 +71,7 @@ void eeprom_setup() {
pGC = (struct _GLOBAL_CONFIG *)EEPROM.getDataPtr();
// if checksum bad init GC else use GC values
if (gc_checksum() != pGC->checksum) {
trc("Factory reset");
trc(F("Factory reset"));
memset(pGC, 0, sizeof(*pGC));
strcpy_P(pGC->encryptkey, ENCRYPTKEY);
strcpy_P(pGC->rfmapname, RFM69AP_NAME);
@@ -134,7 +134,7 @@ void setupRFM69(void) {
size_t len = snprintf_P(RadioConfig, sizeof(RadioConfig), JSONtemplate,
freq, GC_IS_RFM69HCW, pGC->networkid, GC_POWER_LEVEL);
if (len >= sizeof(RadioConfig)) {
trc("\n\n*** RFM69 config truncated ***\n");
trc(F("\n\n*** RFM69 config truncated ***\n"));
}
}
@@ -143,7 +143,8 @@ boolean RFM69toMQTT(void) {
if (radio.receiveDone())
{
trc(F("Creating RFM69 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& RFM69data = jsonBuffer.createObject();
uint8_t data[RF69_MAX_DATA_LEN+1]; // For the null character
uint8_t SENDERID = radio.SENDERID;
+4 -3
View File
@@ -55,7 +55,7 @@ void _rfbSend(byte * message, int times) {
char buffer[RF_MESSAGE_SIZE];
_rfbToChar(message, buffer);
trc("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n");
trc(F("[RFBRIDGE] Sending MESSAGE '%s' %d time(s)\n"));
for (int i=0; i<times; i++) {
if (i>0) {
@@ -103,7 +103,8 @@ void _rfbDecode() {
_rfbToChar(&_uartbuf[1], buffer);
trc(F("Creating SRFB buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& SRFBdata = jsonBuffer.createObject();
SRFBdata.set("raw", (char *)buffer);
@@ -139,7 +140,7 @@ void _rfbDecode() {
}
void _rfbAck() {
trc("[RFBRIDGE] Sending ACK\n");
trc(F("[RFBRIDGE] Sending ACK\n"));
Serial.println();
Serial.write(RF_CODE_START);
Serial.write(RF_CODE_ACK);
+4 -2
View File
@@ -358,7 +358,8 @@ void createDiscovery(char * sensor_type,
bool optimistic, bool retain, int off_delay,
char * payload_available, char * payload_not_avalaible, boolean child_device , char * command_topic)
{
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(14) + JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject &sensor = jsonBuffer.createObject();
sensor.set("stat_t", state_topic); //state_topic
sensor.set("name", s_name); //name
@@ -385,7 +386,8 @@ void createDiscovery(char * sensor_type,
if (child_device){
StaticJsonBuffer<JSON_MSG_BUFFER> jsonDeviceBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4) + JSON_ARRAY_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonDeviceBuffer;
JsonObject &device = jsonDeviceBuffer.createObject();
device.set("name", Gateway_Name);
device.set("manufacturer", DEVICEMANUFACTURER);
+2 -1
View File
@@ -48,7 +48,8 @@ void MeasureADC(){
}else{
if(val >= persistedadc + ThresholdReadingADC || val <= persistedadc - ThresholdReadingADC){
trc(F("Creating ADC buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& ADCdata = jsonBuffer.createObject();
ADCdata.set("adc", (int)val);
pub(ADCTOPIC,ADCdata);
+2 -1
View File
@@ -55,7 +55,8 @@ void MeasureLightIntensity()
{
if (millis() > (timebh1750 + TimeBetweenReadingBH1750)) {//retriving value of Lux, FtCd and Wattsm2 from BH1750
trc(F("Creating BH1750 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& BH1750data = jsonBuffer.createObject();
timebh1750 = millis();
+2 -1
View File
@@ -129,7 +129,8 @@ void MeasureTempHumAndPressure()
trc(F("Failed to read from Weather Sensor BME280!"));
}else{
trc(F("Creating BME280 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(6);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& BME280data = jsonBuffer.createObject();
// Generate Temperature in degrees C
if(BmeTempC != persisted_bme_tempc || bme280_always){
+2 -1
View File
@@ -49,7 +49,8 @@ void MeasureTempAndHum(){
trc(F("Failed to read from DHT sensor!"));
}else{
trc(F("Creating DHT buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(2);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& DHTdata = jsonBuffer.createObject();
if(h != persistedh || dht_always){
DHTdata.set("hum", (float)h);
+2 -1
View File
@@ -61,7 +61,8 @@ void MeasureGPIOInput(){
if (reading != InputState) {
InputState = reading;
trc(F("Creating GPIOInput buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& GPIOdata = jsonBuffer.createObject();
if (InputState == HIGH) {
trc(F("GPIO HIGH"));
+2 -1
View File
@@ -35,7 +35,8 @@ void setupHCSR501() {
void MeasureHCSR501(){
if (millis() > TimeBeforeStartHCSR501) {//let time to init the PIR sensor
trc(F("Creating HCSR501 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(1);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& HCSR501data = jsonBuffer.createObject();
static int pirState = LOW;
int PresenceValue = digitalRead(HCSR501_PIN);
+2 -1
View File
@@ -52,7 +52,8 @@ void MeasureINA226(){
if (millis() > (timeINA226 + TimeBetweenReadingINA226)) {//retriving value of temperature and humidity of the box from DHT every xUL
timeINA226 = millis();
trc(F("Creating INA226 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(3);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& INA226data = jsonBuffer.createObject();
// Topic on which we will send data
trc(F("Retrieving electrical data"));
+9 -8
View File
@@ -50,15 +50,15 @@ void displaySensorDetails(void)
{
sensor_t sensor;
tsl.getSensor(&sensor);
trc("------------------------------------");
trc(F("------------------------------------"));
trc("Sensor: " + String(sensor.name));
trc("Driver Ver: " + String(sensor.version));
trc("Unique ID: " + String(sensor.sensor_id));
trc("Max Value: " + String(sensor.max_value) + " lux");
trc("Min Value: " + String(sensor.min_value) + " lux");
trc("Resolution: " + String(sensor.resolution) + " lux");
trc("------------------------------------");
trc("");
trc(F("------------------------------------"));
trc(F(""));
delay(500);
}
@@ -69,7 +69,7 @@ void setupZsensorTSL2561()
if (!tsl.begin())
{
trc("No TSL2561 detected");
trc(F("No TSL2561 detected"));
}
// enable auto ranging
@@ -81,7 +81,7 @@ void setupZsensorTSL2561()
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);
trc("TSL2561 Initialized. Printing detials now.");
trc(F("TSL2561 Initialized. Printing detials now."));
displaySensorDetails();
}
@@ -92,7 +92,8 @@ void MeasureLightIntensityTSL2561()
timetsl2561 = millis();
trc(F("Creating TSL2561 buffer"));
StaticJsonBuffer<JSON_MSG_BUFFER> jsonBuffer;
const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4);
StaticJsonBuffer<JSON_MSG_CALC_BUFFER> jsonBuffer;
JsonObject& TSL2561data = jsonBuffer.createObject();
sensors_event_t event;
@@ -109,10 +110,10 @@ void MeasureLightIntensityTSL2561()
pub(subjectTSL12561toMQTT,TSL2561data);
} else {
trc("Same lux value, do not send");
trc(F("Same lux value, do not send"));
}
} else {
trc("Failed to read from TSL2561");
trc(F("Failed to read from TSL2561"));
}
}
}
+1 -1
View File
@@ -26,7 +26,7 @@
#if defined(ESP8266) || defined(ESP32) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)
#define MQTT_MAX_PACKET_SIZE 1024
#else // boards with smaller memory
#define MQTT_MAX_PACKET_SIZE 256
#define MQTT_MAX_PACKET_SIZE 128
#endif
#endif
+22 -5
View File
@@ -100,9 +100,23 @@ const byte subnet[] = { 255, 255, 255, 0 }; //ip adress
#define ota_password "OTAPASSWORD"
#define ota_port 8266
/*-------------DEFINE PINs FOR STATUS LEDs----------------*/
#define led_receive 40
#define led_send 42
#define led_error 44
#ifdef ESP8266
#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
#elif __AVR_ATmega2560__ //arduino mega
#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
#endif
// VCC ------------D|-----------/\/\/\/\ ----------------- Arduino PIN
// LED Resistor 270-510R
@@ -220,8 +234,11 @@ const byte subnet[] = { 255, 255, 255, 0 }; //ip adress
#ifdef ESP32
//#define multiCore //uncomment to use multicore function of ESP32 for BLE
#endif
#define JSON_MSG_BUFFER 256 // Json message max buffer size, don't put 1024 or higher it is causing unexpected behaviour on ESP8266
#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
#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
#endif
#define TimeBetweenReadingSYS 30000 // time between system readings (like memory)
#define subjectSYStoMQTT Base_Topic Gateway_Name "/SYStoMQTT"
/*-------------------ACTIVATE TRACES----------------------*/