From f8355cfb7b5815e1dd6b560b51056ed8af1f8c09 Mon Sep 17 00:00:00 2001 From: livello Date: Sun, 1 Jul 2018 01:56:16 +0300 Subject: [PATCH 1/6] Encoder. need to change irq function --- lighthub/inputs.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++- lighthub/inputs.h | 5 +++++ platformio.ini | 4 ++-- 3 files changed, 56 insertions(+), 3 deletions(-) diff --git a/lighthub/inputs.cpp b/lighthub/inputs.cpp index 9a512af..ea0cc01 100644 --- a/lighthub/inputs.cpp +++ b/lighthub/inputs.cpp @@ -90,7 +90,9 @@ int Input::poll() { if (!isValid()) return -1; if (inType & IN_DHT22) dht22Poll(); -/* example +else if(inType & IN_ENCODER) + encoderPoll(); + /* example else if (inType & IN_ANALOG) analogPoll(); */ else @@ -98,6 +100,48 @@ int Input::poll() { return 0; } +void Input::encoderPoll() { + if (store->nextPollMillis > millis()) + return; + if (store->logicState == 0) { + short real_pin; +#if defined(__AVR__) +#define interrupt_number pin + if (interrupt_number >= 0 && interrupt_number < 6) { + short mega_interrupt_array[6] = {2, 3, 21, 20, 19, 18}; + real_pin = mega_interrupt_array[interrupt_number]; + pinMode(real_pin, INPUT); + attachInterrupt(interrupt_number, onEncoderChanged, RISING); + } else { + Serial.print(F("IRQ:")); + Serial.print(pin); + Serial.print(F(" Encoder type. INCORRECT Interrupt number!!!")); + return; + } +#endif + +#if defined(__SAM3X8E__) + pinMode(pin, INPUT); + attachInterrupt(pin, onEncoderChanged, RISING); +#endif + store->logicState = 1; + return; + } + aJsonObject *emit = aJson.getObjectItem(inputObj, "emit"); + Serial.print(F("IN:"));Serial.print(pin);Serial.print(F(" Encoder type. val="));Serial.print(store->aslong); + if (emit) { + char valstr[10]; + char addrstr[100] = ""; + strcat(addrstr, emit->valuestring); + sprintf(valstr, "%d", store->aslong); + mqttClient.publish(addrstr, valstr); + store->nextPollMillis = millis() + DHT_POLL_DELAY_DEFAULT; + Serial.print(F(" NextPollMillis="));Serial.println(store->nextPollMillis); + } + else + Serial.print(F(" No emit data!")); +} + void Input::dht22Poll() { #ifndef DHT_DISABLE if (store->nextPollMillis > millis()) @@ -204,3 +248,7 @@ void Input::onContactChanged(int val) } } } + +static void Input::onEncoderChanged() { + store->aslong++; +} diff --git a/lighthub/inputs.h b/lighthub/inputs.h index 6055503..843f28b 100644 --- a/lighthub/inputs.h +++ b/lighthub/inputs.h @@ -27,6 +27,7 @@ e-mail anklimov@gmail.com #define IN_PUSH_ON 0 // PUSH - ON, Release - OFF (ovverrided by pcmd/rcmd) - DEFAULT #define IN_PUSH_TOGGLE 1 // Every physicall push toggle logical switch on/off #define IN_DHT22 4 +#define IN_ENCODER 8 #define SAME_STATE_ATTEMPTS 3 @@ -100,4 +101,8 @@ class Input void printFloatValueToStr(float temp, char *valstr); + + void encoderPoll(); + + void onEncoderChanged(); }; diff --git a/platformio.ini b/platformio.ini index 679d3d3..19eee9e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,8 +10,8 @@ [platformio] src_dir = lighthub env_default = - - megaatmega2560-net + megaatmega2560 +; megaatmega2560-net ; due ; esp8266 ; megaatmega2560-5500 From ec4f4784a287dadb0dd1de7331bb30152605566f Mon Sep 17 00:00:00 2001 From: livello Date: Sun, 1 Jul 2018 12:54:59 +0300 Subject: [PATCH 2/6] Encoder support --- lighthub/inputs.cpp | 116 +++++++++++++++++++++++++++++++++++++++----- lighthub/inputs.h | 48 ++++++++++-------- 2 files changed, 134 insertions(+), 30 deletions(-) diff --git a/lighthub/inputs.cpp b/lighthub/inputs.cpp index ea0cc01..b073710 100644 --- a/lighthub/inputs.cpp +++ b/lighthub/inputs.cpp @@ -29,6 +29,16 @@ e-mail anklimov@gmail.com extern PubSubClient mqttClient; //DHT dht(); +#if defined(__AVR__) +static volatile long encoder_value[6]; +#endif + +#if defined(__SAM3X8E__) +static short encoder_irq_map[54]; + static long encoder_value[54]; + static int encoders_count; +#endif + Input::Input(char * name) //Constructor { if (name) @@ -104,14 +114,12 @@ void Input::encoderPoll() { if (store->nextPollMillis > millis()) return; if (store->logicState == 0) { - short real_pin; #if defined(__AVR__) #define interrupt_number pin if (interrupt_number >= 0 && interrupt_number < 6) { - short mega_interrupt_array[6] = {2, 3, 21, 20, 19, 18}; - real_pin = mega_interrupt_array[interrupt_number]; - pinMode(real_pin, INPUT); - attachInterrupt(interrupt_number, onEncoderChanged, RISING); + const short mega_interrupt_array[6] = {2, 3, 21, 20, 19, 18}; + short real_pin = mega_interrupt_array[interrupt_number]; + attachInterruptPinIrq(real_pin,interrupt_number); } else { Serial.print(F("IRQ:")); Serial.print(pin); @@ -121,19 +129,22 @@ void Input::encoderPoll() { #endif #if defined(__SAM3X8E__) - pinMode(pin, INPUT); - attachInterrupt(pin, onEncoderChanged, RISING); + attachInterruptPinIrq(pin,encoders_count); + encoder_irq_map[encoders_count]=pin; + encoders_count++; #endif store->logicState = 1; return; } + long encoderValue = encoder_value[pin]; + Serial.print(F("IN:"));Serial.print(pin);Serial.print(F(" Encoder type. val="));Serial.print(encoderValue); + aJsonObject *emit = aJson.getObjectItem(inputObj, "emit"); - Serial.print(F("IN:"));Serial.print(pin);Serial.print(F(" Encoder type. val="));Serial.print(store->aslong); if (emit) { char valstr[10]; char addrstr[100] = ""; strcat(addrstr, emit->valuestring); - sprintf(valstr, "%d", store->aslong); + sprintf(valstr, "%d", encoderValue); mqttClient.publish(addrstr, valstr); store->nextPollMillis = millis() + DHT_POLL_DELAY_DEFAULT; Serial.print(F(" NextPollMillis="));Serial.println(store->nextPollMillis); @@ -142,6 +153,33 @@ void Input::encoderPoll() { Serial.print(F(" No emit data!")); } +void Input::attachInterruptPinIrq(int realPin, int irq) { + pinMode(realPin, INPUT); + switch(irq){ + case 0: + attachInterrupt(realPin, onEncoderChanged0, RISING); + break; + case 1: + attachInterrupt(realPin, onEncoderChanged1, RISING); + break; + case 2: + attachInterrupt(realPin, onEncoderChanged2, RISING); + break; + case 3: + attachInterrupt(realPin, onEncoderChanged3, RISING); + break; + case 4: + attachInterrupt(realPin, onEncoderChanged4, RISING); + break; + case 5: + attachInterrupt(realPin, onEncoderChanged5, RISING); + break; + default: + Serial.print(F("Incorrect irq:"));Serial.println(irq); + break; + } +} + void Input::dht22Poll() { #ifndef DHT_DISABLE if (store->nextPollMillis > millis()) @@ -249,6 +287,62 @@ void Input::onContactChanged(int val) } } -static void Input::onEncoderChanged() { - store->aslong++; +void Input::onEncoderChanged0() { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[0]]++; +#endif + +#if defined(__AVR__) + encoder_value[0]++; +#endif +} + +void Input::onEncoderChanged1() { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[1]]++; +#endif + +#if defined(__AVR__) + encoder_value[1]++; +#endif +} + +void Input::onEncoderChanged2() { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[2]]++; +#endif + +#if defined(__AVR__) + encoder_value[2]++; +#endif +} + +void Input::onEncoderChanged3() { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[3]]++; +#endif + +#if defined(__AVR__) + encoder_value[3]++; +#endif +} + +void Input::onEncoderChanged4() { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[4]]++; +#endif + +#if defined(__AVR__) + encoder_value[4]++; +#endif +} + +void Input::onEncoderChanged5() { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[5]]++; +#endif + +#if defined(__AVR__) + encoder_value[5]++; +#endif } diff --git a/lighthub/inputs.h b/lighthub/inputs.h index 843f28b..3cd9aaa 100644 --- a/lighthub/inputs.h +++ b/lighthub/inputs.h @@ -64,8 +64,7 @@ e-mail anklimov@gmail.com extern aJsonObject *inputs; -typedef union -{ +typedef union { long int aslong; struct { int8_t reserve; @@ -76,33 +75,44 @@ typedef union unsigned long nextPollMillis; } inStore; -class Input -{ - public: - aJsonObject *inputObj; - uint8_t inType; - uint8_t pin; - inStore * store; +class Input { +public: + aJsonObject *inputObj; + uint8_t inType; + uint8_t pin; + inStore *store; - Input(int pin); - Input(aJsonObject * obj); - Input(char * name); + Input(int pin); - boolean isValid (); - void onContactChanged(int val); + Input(aJsonObject *obj); - int poll(); - protected: - void Parse(); + Input(char *name); + + boolean isValid(); + + void onContactChanged(int val); + + int poll(); + + static void onEncoderChanged0(); + static void onEncoderChanged1(); + static void onEncoderChanged2(); + static void onEncoderChanged3(); + static void onEncoderChanged4(); + static void onEncoderChanged5(); + + + +protected: + void Parse(); void contactPoll(); void dht22Poll(); - void printFloatValueToStr(float temp, char *valstr); void encoderPoll(); - void onEncoderChanged(); + void attachInterruptPinIrq(int realPin, int irq); }; From 797ce5d4cee32d762fd91799dedca38663fc3b20 Mon Sep 17 00:00:00 2001 From: livello Date: Sun, 1 Jul 2018 13:35:53 +0300 Subject: [PATCH 3/6] Encoder support --- lighthub/inputs.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/lighthub/inputs.cpp b/lighthub/inputs.cpp index b073710..a27c46c 100644 --- a/lighthub/inputs.cpp +++ b/lighthub/inputs.cpp @@ -155,24 +155,31 @@ void Input::encoderPoll() { void Input::attachInterruptPinIrq(int realPin, int irq) { pinMode(realPin, INPUT); + int real_irq; +#if defined(__AVR__) + real_irq = irq; +#endif +#if defined(__SAM3X8E__) + real_irq = realPin; +#endif switch(irq){ case 0: - attachInterrupt(realPin, onEncoderChanged0, RISING); + attachInterrupt(real_irq, onEncoderChanged0, RISING); break; case 1: - attachInterrupt(realPin, onEncoderChanged1, RISING); + attachInterrupt(real_irq, onEncoderChanged1, RISING); break; case 2: - attachInterrupt(realPin, onEncoderChanged2, RISING); + attachInterrupt(real_irq, onEncoderChanged2, RISING); break; case 3: - attachInterrupt(realPin, onEncoderChanged3, RISING); + attachInterrupt(real_irq, onEncoderChanged3, RISING); break; case 4: - attachInterrupt(realPin, onEncoderChanged4, RISING); + attachInterrupt(real_irq, onEncoderChanged4, RISING); break; case 5: - attachInterrupt(realPin, onEncoderChanged5, RISING); + attachInterrupt(real_irq, onEncoderChanged5, RISING); break; default: Serial.print(F("Incorrect irq:"));Serial.println(irq); From 09726be883afd8657b23719a531c291da4067006 Mon Sep 17 00:00:00 2001 From: livello Date: Wed, 4 Jul 2018 01:22:00 +0300 Subject: [PATCH 4/6] esp32 support, build_flags_{ENVNAME}.sh now can be used and edited in IDE! --- build_flags_template.sh | 46 +++++++++++++---------------- lighthub/dmx.cpp | 4 +-- lighthub/dmx.h | 2 +- lighthub/inputs.cpp | 10 ++++++- lighthub/item.cpp | 4 ++- lighthub/main.cpp | 62 ++++++++++++++++++++++++++++++--------- lighthub/main.h | 26 +++++++++++------ lighthub/options.h | 6 +--- lighthub/utils.cpp | 2 +- my_build_flags.py | 32 -------------------- platformio.ini | 65 ++++++++++++++++++++++++++++++++++------- prepareDue.sh | 2 ++ 12 files changed, 161 insertions(+), 100 deletions(-) delete mode 100644 my_build_flags.py create mode 100755 prepareDue.sh diff --git a/build_flags_template.sh b/build_flags_template.sh index f8d841b..d8ed177 100644 --- a/build_flags_template.sh +++ b/build_flags_template.sh @@ -1,32 +1,28 @@ #! /bin/bash # usage: # first make your own copy of template -# cp build_flags_template.sh my_build_flags.sh +# cp build_flags_template.sh build_flags_{ENVNAME}.sh # then edit, change or comment something -# nano my_build_flags.sh -# and source it -# source my_build_flags.sh - echo "==============================================Custom build flags are:=====================================================" export FLAGS="-DMY_CONFIG_SERVER=lazyhome.ru" - export FLAGS="$FLAGS -DWATCH_DOG_TICKER_DISABLE" - export FLAGS="$FLAGS -DUSE_1W_PIN=12" - export FLAGS="$FLAGS -DSD_CARD_INSERTED" + #export FLAGS="$FLAGS -DWATCH_DOG_TICKER_DISABLE" + #export FLAGS="$FLAGS -DUSE_1W_PIN=12" + #export FLAGS="$FLAGS -DSD_CARD_INSERTED" export FLAGS="$FLAGS -DSERIAL_BAUD=115200" - export FLAGS="$FLAGS -DWiz5500" - export FLAGS="$FLAGS -DDISABLE_FREERAM_PRINT" + #export FLAGS="$FLAGS -DWiz5500" + #export FLAGS="$FLAGS -DDISABLE_FREERAM_PRINT" export FLAGS="$FLAGS -DCUSTOM_FIRMWARE_MAC=de:ad:be:ef:fe:00" - export FLAGS="$FLAGS -DDMX_DISABLE" - export FLAGS="$FLAGS -DMODBUS_DISABLE" - export FLAGS="$FLAGS -DOWIRE_DISABLE" - export FLAGS="$FLAGS -DAVR_DMXOUT_PIN=18" - export FLAGS="$FLAGS -DLAN_INIT_DELAY=2000" - export FLAGS="$FLAGS -DCONTROLLINO" - export FLAGS="$FLAGS -DESP_WIFI_AP=MYAP" - export FLAGS="$FLAGS -DESP_WIFI_PWD=MYPWD" - export FLAGS="$FLAGS -DDHT_DISABLE" - export FLAGS="$FLAGS -DRESET_PIN=5" - export FLAGS="$FLAGS -DDHCP_RETRY_INTERVAL=60000" - export PLATFORMIO_BUILD_FLAGS="$FLAGS" - echo PLATFORMIO_BUILD_FLAGS=$PLATFORMIO_BUILD_FLAGS - echo "==============================================Custom build flags END=====================================================" - unset FLAGS \ No newline at end of file +# export FLAGS="$FLAGS -DDMX_DISABLE" +# export FLAGS="$FLAGS -DMODBUS_DISABLE" +# export FLAGS="$FLAGS -DOWIRE_DISABLE" +# export FLAGS="$FLAGS -DAVR_DMXOUT_PIN=18" +# export FLAGS="$FLAGS -DLAN_INIT_DELAY=2000" +# export FLAGS="$FLAGS -DCONTROLLINO" +# export FLAGS="$FLAGS -DESP_WIFI_AP=MYAP" +# export FLAGS="$FLAGS -DESP_WIFI_PWD=MYPWD" +# export FLAGS="$FLAGS -DWIFI_MANAGER_DISABLE" +# export FLAGS="$FLAGS -DDHT_DISABLE" +# export FLAGS="$FLAGS -DRESET_PIN=5" +# export FLAGS="$FLAGS -DDHCP_RETRY_INTERVAL=60000" +# export FLAGS="$FLAGS -DRESTART_LAN_ON_MQTT_ERRORS" + export FLAGS="$FLAGS -DPIO_SRC_REV="$(git log --pretty=format:%h_%ad -1 --date=short) + echo $FLAGS \ No newline at end of file diff --git a/lighthub/dmx.cpp b/lighthub/dmx.cpp index e46d283..d604985 100644 --- a/lighthub/dmx.cpp +++ b/lighthub/dmx.cpp @@ -28,7 +28,7 @@ e-mail anklimov@gmail.com #endif #endif -#if defined(__ESP__) +#if defined(ESP8266) #ifndef DMX_DISABLE DMXESPSerial dmxout; #endif @@ -236,7 +236,7 @@ void DMXoutSetup(int channels) #endif -#if defined(__ESP__) +#if defined(ESP8266) dmxout.init(channels); #endif diff --git a/lighthub/dmx.h b/lighthub/dmx.h index f78ddb7..f879b16 100644 --- a/lighthub/dmx.h +++ b/lighthub/dmx.h @@ -38,7 +38,7 @@ e-mail anklimov@gmail.com #define DmxWrite DmxSimple.write #endif -#if defined(__ESP__) +#if defined(ESP8266) #include extern DMXESPSerial dmxout; #define DmxWrite dmxout.write diff --git a/lighthub/inputs.cpp b/lighthub/inputs.cpp index a27c46c..e274706 100644 --- a/lighthub/inputs.cpp +++ b/lighthub/inputs.cpp @@ -33,6 +33,14 @@ extern PubSubClient mqttClient; static volatile long encoder_value[6]; #endif +#if defined(ESP8266) +static volatile long encoder_value[6]; +#endif + +#if defined(ARDUINO_ARCH_ESP32) +static volatile long encoder_value[6]; +#endif + #if defined(__SAM3X8E__) static short encoder_irq_map[54]; static long encoder_value[54]; @@ -216,7 +224,7 @@ void Input::dht22Poll() { } void Input::printFloatValueToStr(float temp, char *valstr) { - #if defined(__ESP__) + #if defined(ESP8266) sprintf(valstr, "%2.1f", temp); #endif #if defined(__AVR__) diff --git a/lighthub/item.cpp b/lighthub/item.cpp index 1e6b135..f43ab1c 100644 --- a/lighthub/item.cpp +++ b/lighthub/item.cpp @@ -186,7 +186,7 @@ void Item::copyPar (aJsonObject *itemV) } */ -#ifdef ESP32 +#if defined(ARDUINO_ARCH_ESP32) void analogWrite(int pin, int val) { //TBD @@ -218,6 +218,7 @@ int Item::Ctrl(char * payload, boolean send){ case -1: //Not known command case -2: //JSON input (not implemented yet break; +#if not defined(ARDUINO_ARCH_ESP32) and not defined(ESP8266) case -3: //RGB color in #RRGGBB notation { CRGB rgb; @@ -231,6 +232,7 @@ int Item::Ctrl(char * payload, boolean send){ } break; } +#endif case CMD_ON: // if (item.getEnableCMD(500) || lanStatus == 4) diff --git a/lighthub/main.cpp b/lighthub/main.cpp index 41dc504..310a640 100644 --- a/lighthub/main.cpp +++ b/lighthub/main.cpp @@ -77,12 +77,20 @@ EthernetClient ethClient; EthernetClient ethClient; #endif -#ifdef __ESP__ +#ifdef ESP8266 #include #include WiFiClient ethClient; #endif +#ifdef ARDUINO_ARCH_ESP32 +#include +#include +#include +#include +WiFiClient ethClient; +#endif + lan_status lanStatus = INITIAL_STATE; const char outprefix[] PROGMEM = OUTTOPIC; @@ -270,7 +278,7 @@ lan_status lanLoop() { { -#ifndef __ESP__ +#if defined(__AVR__) || defined(__SAM3X8E__) wdt_dis(); if (lanStatus > 0) switch (Ethernet.maintain()) { @@ -395,8 +403,7 @@ void ip_ready_config_loaded_connecting_to_broker() { } void onInitialStateInitLAN() { -#ifdef __ESP__ -#ifdef WIFI_MANAGER_DISABLE +#if defined(ESP8266) and defined(WIFI_MANAGER_DISABLE) if(!wifiInitialized) { WiFi.mode(WIFI_STA); Serial.print(F("WIFI AP/Password:")); @@ -408,15 +415,40 @@ void onInitialStateInitLAN() { wifiInitialized = true; } #endif - if (WiFi.status() == WL_CONNECTED) { - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - lanStatus=HAVE_IP_ADDRESS;//1; - } + +#ifdef ARDUINO_ARCH_ESP32 + if(!wifiInitialized) { + WiFi.mode(WIFI_STA); + WiFi.disconnect(); + Serial.print(F("WIFI AP/Password:")); + Serial.print(QUOTE(ESP_WIFI_AP)); + Serial.print(F("/")); + Serial.println(QUOTE(ESP_WIFI_PWD)); + WiFi.begin(QUOTE(ESP_WIFI_AP), QUOTE(ESP_WIFI_PWD)); + + int wifi_connection_wait = 10000; + while (WiFi.status() != WL_CONNECTED && wifi_connection_wait > 0) { + delay(500); + wifi_connection_wait -= 500; + Serial.print("."); + } + wifiInitialized = true; + } #endif -#if not defined(__ESP__) +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP8266) + if (WiFi.status() == WL_CONNECTED) { + Serial.print(F("WiFi connected. IP address: ")); + Serial.println(WiFi.localIP()); + lanStatus = HAVE_IP_ADDRESS;//1; + } else + { + Serial.println(F("Problem with WiFi connected")); + nextLanCheckTime = millis() + DHCP_RETRY_INTERVAL/5; + } +#endif + + #if defined(__AVR__) || defined(__SAM3X8E__) IPAddress ip, dns, gw, mask; int res = 1; Serial.println(F("Starting lan")); @@ -956,7 +988,7 @@ lan_status getConfig(int arg_cnt, char **args) return READ_RE_CONFIG;//-11; //Load from NVRAM } #endif -#if defined(__ESP__) +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP8266) HTTPClient httpClient; String fullURI = "http://"; fullURI+=configServer; @@ -1047,7 +1079,7 @@ void setup_main() { ArtnetSetup(); #endif -#if defined(__ESP__) and not defined(WIFI_MANAGER_DISABLE) +#if defined(ESP8266) and not defined(WIFI_MANAGER_DISABLE) WiFiManager wifiManager; #if defined(ESP_WIFI_AP) and defined(ESP_WIFI_PWD) wifiManager.autoConnect(QUOTE(ESP_WIFI_AP), QUOTE(ESP_WIFI_PWD)); @@ -1060,6 +1092,10 @@ void setup_main() { //TODO: checkForRemoteSketchUpdate(); } +#ifdef MMMMMM +errro!!! +#endif + void printFirmwareVersionAndBuildOptions() { Serial.print(F("\nLazyhome.ru LightHub controller ")); Serial.println(F(QUOTE(PIO_SRC_REV))); diff --git a/lighthub/main.h b/lighthub/main.h index 67088d1..ec5e129 100644 --- a/lighthub/main.h +++ b/lighthub/main.h @@ -14,18 +14,24 @@ #define DHCP_RETRY_INTERVAL 60000 #endif -#if defined(__AVR__) +#if defined(ESP8266) #define wdt_en() wdt_enable(WDTO_8S) #define wdt_dis() wdt_disable() #define wdt_res() wdt_reset() #endif -#if defined(__ESP__) +#ifdef ARDUINO_ARCH_ESP32 #define wdt_res() #define wdt_en() #define wdt_dis() #endif +//#if defined(ESP8266) +//#define wdt_res() +//#define wdt_en() +//#define wdt_dis() +//#endif + #if defined(WATCH_DOG_TICKER_DISABLE) && defined(__AVR__) #define wdt_en() wdt_disable() #define wdt_dis() wdt_disable() @@ -63,16 +69,13 @@ #include #endif -#if defined(__ESP__) +#if defined(ESP8266) #include //this needs to be first, or it all crashes and burns... #include #include - -#ifndef WIFI_MANAGER_DISABLE #include #include #include -#endif #endif @@ -88,11 +91,19 @@ #endif +#if defined(__AVR__) || defined(__SAM3X8E__) || defined(ESP8266) #ifdef Wiz5500 #include #else #include #endif +#endif + +#ifdef ARDUINO_ARCH_ESP32 +#include +#include +#endif + #ifdef _artnet #include @@ -122,12 +133,9 @@ enum lan_status { void mqttCallback(char *topic, byte *payload, unsigned int length); -//#ifndef __ESP__ void printIPAddress(IPAddress ipAddress); -//#endif - void printMACAddress(); void restoreState(); diff --git a/lighthub/options.h b/lighthub/options.h index 0509d12..a3fb25b 100644 --- a/lighthub/options.h +++ b/lighthub/options.h @@ -95,10 +95,6 @@ #define LAN_INIT_DELAY 500 #endif -#if defined(ESP8266) -#define __ESP__ -#endif - #if defined(__AVR__) //All options available #ifdef CONTROLLINO @@ -116,7 +112,7 @@ #define dmxin DmxDue1 #endif -#if defined(__ESP__) +#if defined(ESP8266) #undef _dmxin #undef _modbus #ifndef DMX_DISABLE diff --git a/lighthub/utils.cpp b/lighthub/utils.cpp index 0509cf0..5a771c9 100644 --- a/lighthub/utils.cpp +++ b/lighthub/utils.cpp @@ -80,7 +80,7 @@ int getInt(char **chan) { } -#if defined(ESP8266) +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP8266) unsigned long freeRam () {return system_get_free_heap_size();} #endif diff --git a/my_build_flags.py b/my_build_flags.py deleted file mode 100644 index 43992c8..0000000 --- a/my_build_flags.py +++ /dev/null @@ -1,32 +0,0 @@ -# from time import time -# -# from SCons.Script import DefaultEnvironment -# -# print("==============================================Custom build flags are:=====================================================") -# #FLAGS="-MY_CONFIG_SERVER=192.168.10.110" -# #FLAGS+=" -WATCH_DOG_TICKER_DISABLE" -# #FLAGS+=" -USE_1W_PIN=12" -# #FLAGS+=" -SD_CARD_INSERTED" -# #FLAGS+=" -SERIAL_BAUD=115200" -# #FLAGS+=" -Wiz5500" -# #FLAGS+=" -DISABLE_FREERAM_PRINT" -# #FLAGS+=" -CUSTOM_FIRMWARE_MAC=C4:3E:1f:03:1B:1B" -# #FLAGS+=" -DMX_DISABLE" -# FLAGS="MODBUS_DISABLE" -# #FLAGS+=" -OWIRE_DISABLE" -# #FLAGS+=" -ARTNET_ENABLE" -# #FLAGS+=" -CONTROLLINO" -# #FLAGS+=" -AVR_DMXOUT_PIN=18" -# -# print(FLAGS) -# print("==============================================Custom build flags END=====================================================") -# -# env = DefaultEnvironment() -# env.Append(CPPDEFINES=['MODBUS_DISABLE=1']) - -from time import time - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() -env.Append(CPPDEFINES=['BUILD_TIMESTAMP=%d' % time()]) diff --git a/platformio.ini b/platformio.ini index 19eee9e..75db53e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -14,19 +14,68 @@ env_default = ; megaatmega2560-net ; due ; esp8266 +; esp32 ; megaatmega2560-5500 ; due-5500 ; controllino +; stm32f407 + build_dir = /tmp/pioenvs libdeps_dir = /tmp/piolibdeps +[env:esp32] +platform = espressif32 +framework = arduino +board = pico32 +lib_ldf_mode = chain+ +build_flags = !sh build_flags_esp32.sh +lib_deps = + https://github.com/anklimov/Arduino-Temperature-Control-Library.git + https://github.com/anklimov/DS2482_OneWire + ESP8266HTTPClient + Ethernet3 + https://github.com/anklimov/aJson + https://github.com/anklimov/CmdArduino + https://github.com/anklimov/ModbusMaster + https://github.com/knolleary/pubsubclient.git + https://github.com/anklimov/Artnet.git + FastLED + Adafruit Unified Sensor + DHT sensor library for ESPx + DHT sensor library + +[env:stm32f407] +platform = ststm32 +framework = arduino +board = genericSTM32F407VET6 +;lib_ldf_mode = chain+ +build_flags = !sh build_flags_stm32f407.sh +lib_deps = + https://github.com/sebnil/DueFlashStorage + https://github.com/anklimov/Arduino-Temperature-Control-Library.git + https://github.com/anklimov/DS2482_OneWire + https://github.com/anklimov/DmxDue + https://github.com/anklimov/ArduinoHttpClient + https://github.com/anklimov/aJson + https://github.com/anklimov/CmdArduino + https://github.com/anklimov/ModbusMaster + https://github.com/anklimov/Ethernet + https://github.com/anklimov/Ethernet2 + https://github.com/knolleary/pubsubclient.git + https://github.com/anklimov/Artnet.git +; FastLED + SD + SdFat + Adafruit Unified Sensor + DHT sensor library + + [env:due] platform = atmelsam framework = arduino board = due lib_ldf_mode = chain+ -extra_scripts = pre:my_build_flags.py -build_flags = !echo -n "-DPIO_SRC_REV="$(git log --pretty=format:%h_%ad -1 --date=short) +build_flags = !sh build_flags_due.sh lib_deps = https://github.com/sebnil/DueFlashStorage https://github.com/anklimov/Arduino-Temperature-Control-Library.git @@ -52,7 +101,7 @@ platform = atmelavr board = megaatmega2560 framework = arduino ;lib_ldf_mode = chain+ -build_flags = !echo -n "-DPIO_SRC_REV="$(git log --pretty=format:%h_%ad -1 --date=short) +build_flags = !sh build_flags_mega2560.sh lib_deps = https://github.com/anklimov/Arduino-Temperature-Control-Library.git https://github.com/anklimov/DS2482_OneWire @@ -77,8 +126,7 @@ platform = espressif8266 framework = arduino board = nodemcuv2 lib_ldf_mode = chain+ -build_flags = !echo -n "-DMODBUS_DISABLE -DPIO_SRC_REV="$(git log --pretty=format:%h_%ad -1 --date=short) -;extra_scripts = pre:my_build_flags.py +build_flags = !sh build_flags_esp8266.sh lib_deps = https://github.com/anklimov/Arduino-Temperature-Control-Library.git https://github.com/anklimov/DS2482_OneWire @@ -95,14 +143,13 @@ lib_deps = DHT sensor library WifiManager - [env:megaatmega2560-net] platform = atmelavr board = megaatmega2560 framework = arduino upload_port = net:192.168.88.2:23000 +build_flags = !sh build_flags_mega2560-net.sh ;lib_ldf_mode = chain+ -build_flags = !echo -n "-DPIO_SRC_REV="$(git rev-parse --short HEAD) lib_deps = https://github.com/anklimov/Arduino-Temperature-Control-Library.git https://github.com/anklimov/DS2482_OneWire @@ -124,9 +171,7 @@ lib_deps = platform = atmelsam framework = arduino board = due -lib_ldf_mode = chain+ -extra_scripts = pre:my_build_flags.py -build_flags = !echo -n "-DPIO_SRC_REV="$(git log --pretty=format:%h_%ad -1 --date=short) +;lib_ldf_mode = chain+ build_flags = -D Wiz5500 -D ARTNET_ENABLE lib_deps = https://github.com/sebnil/DueFlashStorage diff --git a/prepareDue.sh b/prepareDue.sh new file mode 100755 index 0000000..6be6e61 --- /dev/null +++ b/prepareDue.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +sed -i -- 's/void USART0_Handler(void)/void USART0_Handler(void ) __attribute__((weak));\nvoid USART0_Handler(void )/g' ~/.platformio/packages/framework-arduinosam/variants/arduino_due_x/variant.cpp From 40479ba2c85604b59b7477a7016471f7f24a9be9 Mon Sep 17 00:00:00 2001 From: livello Date: Thu, 19 Jul 2018 05:44:27 +0300 Subject: [PATCH 5/6] stm32f1 suppport. changes --- build_flags_template.sh | 2 +- lighthub/inputs.cpp | 75 +++---- lighthub/inputs.h | 2 + lighthub/item.cpp | 2 +- lighthub/main.cpp | 421 +++++++++++++++++++++------------------- lighthub/main.h | 8 + lighthub/options.h | 14 +- lighthub/owTerm.cpp | 7 +- lighthub/owTerm.h | 3 + lighthub/utils.cpp | 22 ++- lighthub/utils.h | 3 + platformio.ini | 26 +-- 12 files changed, 315 insertions(+), 270 deletions(-) diff --git a/build_flags_template.sh b/build_flags_template.sh index d8ed177..8c1c2ab 100644 --- a/build_flags_template.sh +++ b/build_flags_template.sh @@ -1,7 +1,7 @@ #! /bin/bash # usage: # first make your own copy of template -# cp build_flags_template.sh build_flags_{ENVNAME}.sh +# cp build_flags_template.sh build_flags_ENVNAME.sh # then edit, change or comment something export FLAGS="-DMY_CONFIG_SERVER=lazyhome.ru" #export FLAGS="$FLAGS -DWATCH_DOG_TICKER_DISABLE" diff --git a/lighthub/inputs.cpp b/lighthub/inputs.cpp index e274706..88af542 100644 --- a/lighthub/inputs.cpp +++ b/lighthub/inputs.cpp @@ -41,7 +41,7 @@ static volatile long encoder_value[6]; static volatile long encoder_value[6]; #endif -#if defined(__SAM3X8E__) +#if defined(__SAM3X8E__) || defined(ARDUINO_ARCH_STM32F1) static short encoder_irq_map[54]; static long encoder_value[54]; static int encoders_count; @@ -242,7 +242,14 @@ void Input::printFloatValueToStr(float temp, char *valstr) { void Input::contactPoll() { boolean currentInputState; - uint8_t inputPinMode, inputOnLevel; +#if defined(ARDUINO_ARCH_STM32F1) + WiringPinMode inputPinMode; +#endif +#if defined(__SAM3X8E__)||defined(__AVR__)||defined(ESP8266) + uint32_t inputPinMode; +#endif + + uint8_t inputOnLevel; if (inType & IN_ACTIVE_HIGH) { inputOnLevel = HIGH; inputPinMode = INPUT; @@ -302,62 +309,32 @@ void Input::onContactChanged(int val) } } +void Input::onEncoderChanged(int i) { +#if defined(__SAM3X8E__) + encoder_value[encoder_irq_map[i]]++; +#endif + +#if defined(__AVR__) + encoder_value[i]++; +#endif +} + void Input::onEncoderChanged0() { -#if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[0]]++; -#endif - -#if defined(__AVR__) - encoder_value[0]++; -#endif + onEncoderChanged(0); } - void Input::onEncoderChanged1() { -#if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[1]]++; -#endif - -#if defined(__AVR__) - encoder_value[1]++; -#endif + onEncoderChanged(1); } - void Input::onEncoderChanged2() { -#if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[2]]++; -#endif - -#if defined(__AVR__) - encoder_value[2]++; -#endif + onEncoderChanged(2); } - void Input::onEncoderChanged3() { -#if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[3]]++; -#endif - -#if defined(__AVR__) - encoder_value[3]++; -#endif + onEncoderChanged(3); } - void Input::onEncoderChanged4() { -#if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[4]]++; -#endif - -#if defined(__AVR__) - encoder_value[4]++; -#endif + onEncoderChanged(4); } - void Input::onEncoderChanged5() { -#if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[5]]++; -#endif - -#if defined(__AVR__) - encoder_value[5]++; -#endif + onEncoderChanged(5); } + diff --git a/lighthub/inputs.h b/lighthub/inputs.h index 3cd9aaa..281c97c 100644 --- a/lighthub/inputs.h +++ b/lighthub/inputs.h @@ -94,6 +94,7 @@ public: int poll(); + static void inline onEncoderChanged(int i); static void onEncoderChanged0(); static void onEncoderChanged1(); static void onEncoderChanged2(); @@ -115,4 +116,5 @@ protected: void encoderPoll(); void attachInterruptPinIrq(int realPin, int irq); + }; diff --git a/lighthub/item.cpp b/lighthub/item.cpp index f43ab1c..3abbd2a 100644 --- a/lighthub/item.cpp +++ b/lighthub/item.cpp @@ -218,7 +218,7 @@ int Item::Ctrl(char * payload, boolean send){ case -1: //Not known command case -2: //JSON input (not implemented yet break; -#if not defined(ARDUINO_ARCH_ESP32) and not defined(ESP8266) +#if not defined(ARDUINO_ARCH_ESP32) and not defined(ESP8266) and not defined(ARDUINO_ARCH_STM32F1) case -3: //RGB color in #RRGGBB notation { CRGB rgb; diff --git a/lighthub/main.cpp b/lighthub/main.cpp index 310a640..e8ea09d 100644 --- a/lighthub/main.cpp +++ b/lighthub/main.cpp @@ -91,6 +91,20 @@ WiFiClient ethClient; WiFiClient ethClient; #endif +#ifdef ARDUINO_ARCH_STM32F1 +//#include +//#include "UIPEthernet.h" +//#include "UIPUdp.h" +#include +#include +#include "HttpClient.h" +#include "Dns.h" +//#include "utility/logging.h" +#include + +EthernetClient ethClient; +#endif + lan_status lanStatus = INITIAL_STATE; const char outprefix[] PROGMEM = OUTTOPIC; @@ -131,7 +145,7 @@ int mqttErrorRate; void watchdogSetup(void) { //Serial.begin(115200); -//Serial.println("Watchdog armed."); +//debugSerial.println("Watchdog armed."); } //Do not remove - strong re-definition WDT Init for DUE @@ -140,22 +154,22 @@ void watchdogSetup(void) { void mqttCallback(char *topic, byte *payload, unsigned int length) { - Serial.print(F("\n[")); - Serial.print(topic); - Serial.print(F("] ")); + debugSerial.print(F("\n[")); + debugSerial.print(topic); + debugSerial.print(F("] ")); if (!payload) return; payload[length] = 0; int fr = freeRam(); if (fr < 250) { - Serial.println(F("OOM!")); + debugSerial.println(F("OOM!")); return; } for (int i = 0; i < length; i++) { - Serial.print((char) payload[i]); + debugSerial.print((char) payload[i]); } - Serial.println(); + debugSerial.println(); if(!strcmp(topic,CMDTOPIC)) { cmd_parse((char *)payload); @@ -168,11 +182,12 @@ void mqttCallback(char *topic, byte *payload, unsigned int length) { { char buf[MQTT_TOPIC_LENGTH + 1]; strncpy_P(buf, inprefix, sizeof(buf)); + intopic = strncmp(topic, buf, strlen(inprefix)); } // in Retaining status - trying to restore previous state from retained output topic. Retained input topics are not relevant. if (retaining && !intopic) { - Serial.println(F("Skipping..")); + debugSerial.println(F("Skipping..")); return; } char subtopic[MQTT_SUBJECT_LENGTH] = ""; @@ -191,19 +206,19 @@ void mqttCallback(char *topic, byte *payload, unsigned int length) { void printIPAddress(IPAddress ipAddress) { for (byte thisByte = 0; thisByte < 4; thisByte++) { - Serial.print(ipAddress[thisByte], DEC); + debugSerial.print(ipAddress[thisByte], DEC); if (thisByte < 3) - Serial.print(F(".")); + debugSerial.print(F(".")); } } void printMACAddress() { - Serial.print(F("Configured MAC:")); + debugSerial.print(F("Configured MAC:")); for (byte thisByte = 0; thisByte < 6; thisByte++) { - Serial.print(mac[thisByte], HEX); - Serial.print(F(":")); + debugSerial.print(mac[thisByte], HEX); + debugSerial.print(F(":")); } - Serial.println(); + debugSerial.println(); } void restoreState() { @@ -246,7 +261,7 @@ lan_status lanLoop() { mqttClient.unsubscribe(buf); lanStatus = OPERATION;//3; - Serial.println(F("Accepting commands...")); + debugSerial.println(F("Accepting commands...")); break; } @@ -283,32 +298,32 @@ lan_status lanLoop() { if (lanStatus > 0) switch (Ethernet.maintain()) { case NO_LINK: - Serial.println(F("No link")); + debugSerial.println(F("No link")); if (mqttClient.connected()) mqttClient.disconnect(); nextLanCheckTime = millis() + 30000; lanStatus = AWAITING_ADDRESS;//-10; break; case DHCP_CHECK_RENEW_FAIL: - Serial.println(F("Error: renewed fail")); + debugSerial.println(F("Error: renewed fail")); if (mqttClient.connected()) mqttClient.disconnect(); nextLanCheckTime = millis() + 1000; lanStatus = AWAITING_ADDRESS;//-10; break; case DHCP_CHECK_RENEW_OK: - Serial.println(F("Renewed success. IP address:")); + debugSerial.println(F("Renewed success. IP address:")); printIPAddress(Ethernet.localIP()); break; case DHCP_CHECK_REBIND_FAIL: - Serial.println(F("Error: rebind fail")); + debugSerial.println(F("Error: rebind fail")); if (mqttClient.connected()) mqttClient.disconnect(); nextLanCheckTime = millis() + 1000; lanStatus = AWAITING_ADDRESS;//-10; break; case DHCP_CHECK_REBIND_OK: - Serial.println(F("Rebind success. IP address:")); + debugSerial.println(F("Rebind success. IP address:")); printIPAddress(Ethernet.localIP()); break; @@ -341,25 +356,25 @@ void ip_ready_config_loaded_connecting_to_broker() { if (n >= 4) user = aJson.getArrayItem(mqttArr, 3)->valuestring; if (!loadFlash(OFFSET_MQTT_PWD, passwordBuf, sizeof(passwordBuf)) && (n >= 5)) { password = aJson.getArrayItem(mqttArr, 4)->valuestring; - Serial.println(F("Using MQTT password from config")); + debugSerial.println(F("Using MQTT password from config")); } mqttClient.setServer(servername, port); mqttClient.setCallback(mqttCallback); - Serial.print(F("Attempting MQTT connection to ")); - Serial.print(servername); - Serial.print(F(":")); - Serial.print(port); - Serial.print(F(" user:")); - Serial.print(user); - Serial.print(F(" ...")); + debugSerial.print(F("Attempting MQTT connection to ")); + debugSerial.print(servername); + debugSerial.print(F(":")); + debugSerial.print(port); + debugSerial.print(F(" user:")); + debugSerial.print(user); + debugSerial.print(F(" ...")); wdt_dis(); //potential unsafe for ethernetIdle(), but needed to avoid cyclic reboot if mosquitto out of order if (mqttClient.connect(client_id, user, password)) { mqttErrorRate = 0; - Serial.print(F("connected as ")); - Serial.println(client_id); + debugSerial.print(F("connected as ")); + debugSerial.println(client_id); wdt_en(); configOk = true; // ... Temporary subscribe to status topic @@ -378,16 +393,16 @@ void ip_ready_config_loaded_connecting_to_broker() { // if (_once) {DMXput(); _once=0;} lanStatus = RETAINING_COLLECTING;//4; nextLanCheckTime = millis() + 5000; - Serial.println(F("Awaiting for retained topics")); + debugSerial.println(F("Awaiting for retained topics")); } else { - Serial.print(F("failed, rc=")); - Serial.print(mqttClient.state()); - Serial.println(F(" try again in 5 seconds")); + debugSerial.print(F("failed, rc=")); + debugSerial.print(mqttClient.state()); + debugSerial.println(F(" try again in 5 seconds")); nextLanCheckTime = millis() + 5000; #ifdef RESTART_LAN_ON_MQTT_ERRORS mqttErrorRate++; if(mqttErrorRate>50){ - Serial.print(F("Too many MQTT connection errors. Restart LAN")); + debugSerial.print(F("Too many MQTT connection errors. Restart LAN")); mqttErrorRate=0; #ifdef RESET_PIN resetHard(); @@ -406,10 +421,10 @@ void onInitialStateInitLAN() { #if defined(ESP8266) and defined(WIFI_MANAGER_DISABLE) if(!wifiInitialized) { WiFi.mode(WIFI_STA); - Serial.print(F("WIFI AP/Password:")); - Serial.print(QUOTE(ESP_WIFI_AP)); - Serial.print(F("/")); - Serial.println(QUOTE(ESP_WIFI_PWD)); + debugSerial.print(F("WIFI AP/Password:")); + debugSerial.print(QUOTE(ESP_WIFI_AP)); + debugSerial.print(F("/")); + debugSerial.println(QUOTE(ESP_WIFI_PWD)); wifi_set_macaddr(STATION_IF,mac); WiFi.begin(QUOTE(ESP_WIFI_AP), QUOTE(ESP_WIFI_PWD)); wifiInitialized = true; @@ -420,17 +435,17 @@ void onInitialStateInitLAN() { if(!wifiInitialized) { WiFi.mode(WIFI_STA); WiFi.disconnect(); - Serial.print(F("WIFI AP/Password:")); - Serial.print(QUOTE(ESP_WIFI_AP)); - Serial.print(F("/")); - Serial.println(QUOTE(ESP_WIFI_PWD)); + debugSerial.print(F("WIFI AP/Password:")); + debugSerial.print(QUOTE(ESP_WIFI_AP)); + debugSerial.print(F("/")); + debugSerial.println(QUOTE(ESP_WIFI_PWD)); WiFi.begin(QUOTE(ESP_WIFI_AP), QUOTE(ESP_WIFI_PWD)); int wifi_connection_wait = 10000; while (WiFi.status() != WL_CONNECTED && wifi_connection_wait > 0) { delay(500); wifi_connection_wait -= 500; - Serial.print("."); + debugSerial.print("."); } wifiInitialized = true; } @@ -438,31 +453,31 @@ void onInitialStateInitLAN() { #if defined(ARDUINO_ARCH_ESP32) || defined(ESP8266) if (WiFi.status() == WL_CONNECTED) { - Serial.print(F("WiFi connected. IP address: ")); - Serial.println(WiFi.localIP()); + debugSerial.print(F("WiFi connected. IP address: ")); + debugSerial.println(WiFi.localIP()); lanStatus = HAVE_IP_ADDRESS;//1; } else { - Serial.println(F("Problem with WiFi connected")); + debugSerial.println(F("Problem with WiFi connected")); nextLanCheckTime = millis() + DHCP_RETRY_INTERVAL/5; } #endif - #if defined(__AVR__) || defined(__SAM3X8E__) + #if defined(__AVR__) || defined(__SAM3X8E__)||defined(ARDUINO_ARCH_STM32F1) IPAddress ip, dns, gw, mask; int res = 1; - Serial.println(F("Starting lan")); + debugSerial.println(F("Starting lan")); if (ipLoadFromFlash(OFFSET_IP, ip)) { - Serial.print("Loaded from flash IP:"); + debugSerial.print("Loaded from flash IP:"); printIPAddress(ip); if (ipLoadFromFlash(OFFSET_DNS, dns)) { - Serial.print(" DNS:"); + debugSerial.print(" DNS:"); printIPAddress(dns); if (ipLoadFromFlash(OFFSET_GW, gw)) { - Serial.print(" GW:"); + debugSerial.print(" GW:"); printIPAddress(gw); if (ipLoadFromFlash(OFFSET_MASK, mask)) { - Serial.print(" MASK:"); + debugSerial.print(" MASK:"); printIPAddress(mask); Ethernet.begin(mac, ip, dns, gw, mask); } else Ethernet.begin(mac, ip, dns, gw); @@ -470,44 +485,62 @@ void onInitialStateInitLAN() { } else Ethernet.begin(mac, ip); } else { - Serial.println("No IP data found in flash"); + debugSerial.println("No IP data found in flash"); wdt_dis(); +#if defined(__AVR__) || defined(__SAM3X8E__) res = Ethernet.begin(mac, 12000); +#endif +#if defined(ARDUINO_ARCH_STM32F1) + res = Ethernet.begin(mac); +#endif wdt_en(); wdt_res(); } if (res == 0) { - Serial.println(F("Failed to configure Ethernet using DHCP. You can set ip manually!")); - Serial.print(F("'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n")); + debugSerial.println(F("Failed to configure Ethernet using DHCP. You can set ip manually!")); + debugSerial.print(F("'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n")); lanStatus = AWAITING_ADDRESS;//-10; nextLanCheckTime = millis() + DHCP_RETRY_INTERVAL; #ifdef RESET_PIN resetHard(); #endif } else { - Serial.print(F("Got IP address:")); + debugSerial.print(F("Got IP address:")); printIPAddress(Ethernet.localIP()); lanStatus = HAVE_IP_ADDRESS;//1; } - - #endif } +#ifdef ARDUINO_ARCH_STM32F1 +void softRebootFunc() { + nvic_sys_reset(); +} +#endif + +#if defined(__AVR__) || defined(__SAM3X8E__) void (*softRebootFunc)(void) = 0; +#endif + +#if defined(ESP8266) || defined(ARDUINO_ARCH_ESP32) +void softRebootFunc(){ + debugSerial.print(F("ESP.restart();")); + ESP.restart(); +} +#endif void resetHard() { #ifdef RESET_PIN - Serial.print(F("Reset Arduino with digital pin ")); - Serial.println(QUOTE(RESET_PIN)); + debugSerial.print(F("Reset Arduino with digital pin ")); + debugSerial.println(QUOTE(RESET_PIN)); delay(500); pinMode(RESET_PIN, OUTPUT); digitalWrite(RESET_PIN,LOW); delay(500); digitalWrite(RESET_PIN,HIGH); delay(500); -#endif +#endif } #ifdef _owire @@ -527,12 +560,12 @@ void Changed(int i, DeviceAddress addr, int val) { owEmit = aJson.getObjectItem(owObj, "emit")->valuestring; if (owEmit) { strncpy(addrbuf, owEmit, sizeof(addrbuf)); - Serial.print(owEmit); - Serial.print(F("=")); - Serial.println(val); + debugSerial.print(owEmit); + debugSerial.print(F("=")); + debugSerial.println(val); } owItem = aJson.getObjectItem(owObj, "item")->valuestring; - } else Serial.println(F("1w-item not found in config")); + } else debugSerial.println(F("1w-item not found in config")); if ((val == -127) || (val == 85) || (val == 0)) { //ToDo: 1-w short circuit mapped to "0" celsium return; @@ -554,7 +587,8 @@ void cmdFunctionHelp(int arg_cnt, char **args) //(char* tokens) { printFirmwareVersionAndBuildOptions(); - Serial.println(F("Use the commands: 'help' - this text\n" + debugSerial.print(F(" free RAM: "));debugSerial.print(freeRam()); + debugSerial.println(F(" Use the commands: 'help' - this text\n" "'mac de:ad:be:ef:fe:00' set and store MAC-address in EEPROM\n" "'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n" "'save' - save config in NVRAM\n" @@ -569,12 +603,12 @@ void cmdFunctionHelp(int arg_cnt, char **args) void cmdFunctionKill(int arg_cnt, char **args) { for (short i = 1; i < 20; i++) { delay(1000); - Serial.println(i); + debugSerial.println(i); }; } void cmdFunctionReboot(int arg_cnt, char **args) { - Serial.println(F("Soft rebooting...")); + debugSerial.println(F("Soft rebooting...")); softRebootFunc(); } @@ -586,8 +620,8 @@ void applyConfig() { dmxArr = aJson.getObjectItem(root, "dmxin"); if (dmxArr && (itemsCount = aJson.getArraySize(dmxArr))) { DMXinSetup(itemsCount * 4); - Serial.print(F("DMX in started. Channels:")); - Serial.println(itemsCount * 4); + debugSerial.print(F("DMX in started. Channels:")); + debugSerial.println(itemsCount * 4); } #endif #ifdef _dmxout @@ -596,8 +630,8 @@ void applyConfig() { if (dmxoutArr && aJson.getArraySize(dmxoutArr) >=1 ) { DMXoutSetup(maxChannels = aJson.getArrayItem(dmxoutArr, 1)->valueint); //,aJson.getArrayItem(dmxoutArr, 0)->valueint); - Serial.print(F("DMX out started. Channels: ")); - Serial.println(maxChannels); + debugSerial.print(F("DMX out started. Channels: ")); + debugSerial.println(maxChannels); } #endif #ifdef _modbus @@ -609,12 +643,12 @@ void applyConfig() { if (owArr && !owReady) { aJsonObject *item = owArr->child; owReady = owSetup(&Changed); - if (owReady) Serial.println(F("One wire Ready")); + if (owReady) debugSerial.println(F("One wire Ready")); t_count = 0; while (item && owReady) { if ((item->type == aJson_Object)) { DeviceAddress addr; - //Serial.print(F("Add:")),Serial.println(item->name); + //debugSerial.print(F("Add:")),debugSerial.println(item->name); SetAddr(item->name, addr); owAdd(addr); } @@ -642,10 +676,10 @@ while (items && item) int k; pinMode(pin, OUTPUT); digitalWrite(pin, k = ((cmd == CMD_ON) ? HIGH : LOW)); - Serial.print(F("Pin:")); - Serial.print(pin); - Serial.print(F("=")); - Serial.println(k); + debugSerial.print(F("Pin:")); + debugSerial.print(pin); + debugSerial.print(F("=")); + debugSerial.println(k); } break; } //switch @@ -660,16 +694,16 @@ while (items && item) } void printConfigSummary() { - Serial.println(F("Configured:")); - Serial.print(F("items ")); + debugSerial.println(F("Configured:")); + debugSerial.print(F("items ")); printBool(items); - Serial.print(F("inputs ")); + debugSerial.print(F("inputs ")); printBool(inputs); - Serial.print(F("modbus ")); + debugSerial.print(F("modbus ")); printBool(modbusArr); - Serial.print(F("mqtt ")); + debugSerial.print(F("mqtt ")); printBool(mqttArr); - Serial.print(F("1-wire ")); + debugSerial.print(F("1-wire ")); printBool(owArr); } @@ -682,24 +716,24 @@ int loadConfigFromEEPROM(int arg_cnt, char **args) //(char* tokens) { char ch; - Serial.println(F("loading Config")); + debugSerial.println(F("loading Config")); ch = EEPROM.read(EEPROM_offset); if (ch == '{') { aJsonEEPROMStream as = aJsonEEPROMStream(EEPROM_offset); aJson.deleteItem(root); root = aJson.parse(&as); - Serial.println(); + debugSerial.println(); if (!root) { - Serial.println(F("load failed")); + debugSerial.println(F("load failed")); return 0; } - Serial.println(F("Loaded")); + debugSerial.println(F("Loaded")); applyConfig(); ethClient.stop(); //Refresh MQTT connect to get retained info return 1; } else { - Serial.println(F("No stored config")); + debugSerial.println(F("No stored config")); return 0; } @@ -715,33 +749,33 @@ int mqttConfigRequest(int arg_cnt, char **args) //(char* tokens) { char buf[25] = "/"; - Serial.println(F("request MQTT Config")); + debugSerial.println(F("request MQTT Config")); SetBytes((uint8_t *) mac, 6, buf + 1); buf[13] = 0; strncat(buf, "/resp/#", 25); - Serial.println(buf); + debugSerial.println(buf); mqttClient.subscribe(buf); buf[13] = 0; strncat(buf, "/req/conf", 25); - Serial.println(buf); + debugSerial.println(buf); mqttClient.publish(buf, "1"); } int mqttConfigResp(char *as) { - Serial.println(F("got MQTT Config")); + debugSerial.println(F("got MQTT Config")); //aJsonEEPROMStream as=aJsonEEPROMStream(EEPROM_offset); //aJson.deleteItem(root); root = aJson.parse(as); - Serial.println(); + debugSerial.println(); if (!root) { - Serial.println(F("load failed")); + debugSerial.println(F("load failed")); return 0; } - Serial.println(F("Loaded")); + debugSerial.println(F("Loaded")); applyConfig(); return 1; } @@ -750,10 +784,10 @@ void cmdFunctionSave(int arg_cnt, char **args) //(char* tokens) { aJsonEEPROMStream jsonEEPROMStream = aJsonEEPROMStream(EEPROM_offset); - Serial.println(F("Saving config to EEPROM..")); + debugSerial.println(F("Saving config to EEPROM..")); aJson.print(root, &jsonEEPROMStream); jsonEEPROMStream.putEOF(); - Serial.println(F("Saved to EEPROM")); + debugSerial.println(F("Saved to EEPROM")); } void cmdFunctionIp(int arg_cnt, char **args) @@ -785,24 +819,24 @@ void cmdFunctionIp(int arg_cnt, char **args) saveFlash(OFFSET_MASK, current_mask); saveFlash(OFFSET_GW, current_gw); saveFlash(OFFSET_DNS, current_dns); - Serial.print(F("Saved current config(ip,dns,gw,subnet):")); + debugSerial.print(F("Saved current config(ip,dns,gw,subnet):")); printIPAddress(current_ip); - Serial.print(F(" ,")); + debugSerial.print(F(" ,")); printIPAddress(current_dns); - Serial.print(F(" ,")); + debugSerial.print(F(" ,")); printIPAddress(current_gw); - Serial.print(F(" ,")); + debugSerial.print(F(" ,")); printIPAddress(current_mask); - Serial.println(F(";")); + debugSerial.println(F(";")); } - Serial.println(F("Saved")); + debugSerial.println(F("Saved")); } void cmdFunctionClearEEPROM(int arg_cnt, char **args){ for (int i = 0; i < 512; i++) EEPROM.write(i, 0); - Serial.println(F("EEPROM cleared")); + debugSerial.println(F("EEPROM cleared")); } @@ -812,13 +846,13 @@ void cmdFunctionPwd(int arg_cnt, char **args) if (arg_cnt) saveFlash(OFFSET_MQTT_PWD,args[1]); else saveFlash(OFFSET_MQTT_PWD,empty); - Serial.println(F("Password updated")); + debugSerial.println(F("Password updated")); } void cmdFunctionSetMac(int arg_cnt, char **args) { - //Serial.print("Got:"); - //Serial.println(args[1]); + //debugSerial.print("Got:"); + //debugSerial.println(args[1]); if (sscanf(args[1], "%x:%x:%x:%x:%x:%x%с", &mac[0], &mac[1], @@ -826,13 +860,13 @@ void cmdFunctionSetMac(int arg_cnt, char **args) { &mac[3], &mac[4], &mac[5]) < 6) { - Serial.print(F("could not parse: ")); - Serial.println(args[1]); + debugSerial.print(F("could not parse: ")); + debugSerial.println(args[1]); return; } printMACAddress(); for (short i = 0; i < 6; i++) { EEPROM.write(i, mac[i]); } - Serial.println(F("Updated")); + debugSerial.println(F("Updated")); } void cmdFunctionGet(int arg_cnt, char **args) { @@ -841,7 +875,7 @@ void cmdFunctionGet(int arg_cnt, char **args) { //restoreState(); } -void printBool(bool arg) { (arg) ? Serial.println(F("on")) : Serial.println(F("off")); } +void printBool(bool arg) { (arg) ? debugSerial.println(F("on")) : debugSerial.println(F("off")); } void saveFlash(short n, char *str) { @@ -885,9 +919,9 @@ lan_status getConfig(int arg_cnt, char **args) snprintf(URI, sizeof(URI), "/%02x-%02x-%02x-%02x-%02x-%02x.config.json", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - Serial.print(F("Config URI: http://")); - Serial.print(configServer); - Serial.println(URI); + debugSerial.print(F("Config URI: http://")); + debugSerial.print(configServer); + debugSerial.println(URI); #if defined(__AVR__) FILE *configStream; @@ -903,52 +937,52 @@ lan_status getConfig(int arg_cnt, char **args) if (configStream != NULL) { if (responseStatusCode == 200) { - Serial.println(F("got Config")); + debugSerial.println(F("got Config")); char c; aJsonFileStream as = aJsonFileStream(configStream); noInterrupts(); aJson.deleteItem(root); root = aJson.parse(&as); interrupts(); - // Serial.println(F("Parsed.")); + // debugSerial.println(F("Parsed.")); hclient.closeStream(configStream); // this is very important -- be sure to close the STREAM if (!root) { - Serial.println(F("Config parsing failed")); + debugSerial.println(F("Config parsing failed")); nextLanCheckTime = millis() + 15000; return READ_RE_CONFIG;//-11; } else { // char *outstr = aJson.print(root); - // Serial.println(outstr); + // debugSerial.println(outstr); // free(outstr); - Serial.println(F("Applying.")); + debugSerial.println(F("Applying.")); applyConfig(); } } else { - Serial.print(F("ERROR: Server returned ")); - Serial.println(responseStatusCode); + debugSerial.print(F("ERROR: Server returned ")); + debugSerial.println(responseStatusCode); nextLanCheckTime = millis() + 5000; return READ_RE_CONFIG;//-11; } } else { - Serial.println(F("failed to connect")); - Serial.println(F(" try again in 5 seconds")); + debugSerial.println(F("failed to connect")); + debugSerial.println(F(" try again in 5 seconds")); nextLanCheckTime = millis() + 5000; return READ_RE_CONFIG;//-11; } #endif -#if defined(__SAM3X8E__) +#if defined(__SAM3X8E__) || defined(ARDUINO_ARCH_STM32F1) String response; EthernetClient configEthClient; HttpClient htclient = HttpClient(configEthClient, configServer, 80); //htclient.stop(); //_socket =MAX htclient.setHttpResponseTimeout(4000); wdt_res(); - //Serial.println("making GET request");get + //debugSerial.println("making GET request");get htclient.beginRequest(); htclient.get(URI); htclient.endRequest(); @@ -959,31 +993,31 @@ lan_status getConfig(int arg_cnt, char **args) response = htclient.responseBody(); htclient.stop(); wdt_res(); - Serial.print(F("HTTP Status code: ")); - Serial.println(responseStatusCode); - //Serial.print("GET Response: "); + debugSerial.print(F("HTTP Status code: ")); + debugSerial.println(responseStatusCode); + //debugSerial.print("GET Response: "); if (responseStatusCode == 200) { aJson.deleteItem(root); root = aJson.parse((char *) response.c_str()); if (!root) { - Serial.println(F("Config parsing failed")); + debugSerial.println(F("Config parsing failed")); // nextLanCheckTime=millis()+15000; return READ_RE_CONFIG;//-11; //Load from NVRAM } else { /* char * outstr=aJson.print(root); - Serial.println(outstr); + debugSerial.println(outstr); free (outstr); */ - Serial.println(response); + debugSerial.println(response); applyConfig(); } } else { - Serial.println(F("Config retrieving failed")); + debugSerial.println(F("Config retrieving failed")); //nextLanCheckTime=millis()+15000; return READ_RE_CONFIG;//-11; //Load from NVRAM } @@ -997,23 +1031,23 @@ lan_status getConfig(int arg_cnt, char **args) int httpResponseCode = httpClient.GET(); if (httpResponseCode > 0) { // HTTP header has been send and Server response header has been handled - Serial.printf("[HTTP] GET... code: %d\n", httpResponseCode); + debugSerial.printf("[HTTP] GET... code: %d\n", httpResponseCode); // file found at server if (httpResponseCode == HTTP_CODE_OK) { String response = httpClient.getString(); - Serial.println(response); + debugSerial.println(response); aJson.deleteItem(root); root = aJson.parse((char *) response.c_str()); if (!root) { - Serial.println(F("Config parsing failed")); + debugSerial.println(F("Config parsing failed")); return READ_RE_CONFIG;//-11; //Load from NVRAM } else { - Serial.println(F("Config OK, Applying")); + debugSerial.println(F("Config OK, Applying")); applyConfig(); } } } else { - Serial.printf("[HTTP] GET... failed, error: %s\n", httpClient.errorToString(httpResponseCode).c_str()); + debugSerial.printf("[HTTP] GET... failed, error: %s\n", httpClient.errorToString(httpResponseCode).c_str()); httpClient.end(); return READ_RE_CONFIG;//-11; //Load from NVRAM } @@ -1092,84 +1126,76 @@ void setup_main() { //TODO: checkForRemoteSketchUpdate(); } -#ifdef MMMMMM -errro!!! -#endif - void printFirmwareVersionAndBuildOptions() { - Serial.print(F("\nLazyhome.ru LightHub controller ")); - Serial.println(F(QUOTE(PIO_SRC_REV))); + debugSerial.print(F("\nLazyhome.ru LightHub controller ")); + debugSerial.println(F(QUOTE(PIO_SRC_REV))); #ifdef CONTROLLINO - Serial.println(F("(+)CONTROLLINO")); + debugSerial.println(F("(+)CONTROLLINO")); #endif #ifdef WATCH_DOG_TICKER_DISABLE - Serial.println(F("(-)WATCHDOG")); + debugSerial.println(F("(-)WATCHDOG")); #else - Serial.println(F("(+)WATCHDOG")); + debugSerial.println(F("(+)WATCHDOG")); #endif - Serial.print(F("Config server:")); - Serial.println(F(CONFIG_SERVER)); - Serial.print(F("Firmware MAC Address ")); - Serial.println(F(QUOTE(CUSTOM_FIRMWARE_MAC))); //Q Macros didn't working with 6 args + debugSerial.print(F("Config server:")); + debugSerial.println(F(CONFIG_SERVER)); + debugSerial.print(F("Firmware MAC Address ")); + debugSerial.println(F(QUOTE(CUSTOM_FIRMWARE_MAC))); //Q Macros didn't working with 6 args #ifdef DISABLE_FREERAM_PRINT - Serial.println(F("(-)FreeRam printing")); + debugSerial.println(F("(-)FreeRam printing")); #else - Serial.println(F("(+)FreeRam printing")); + debugSerial.println(F("(+)FreeRam printing")); #endif #ifdef USE_1W_PIN - Serial.print(F("(-)DS2482-100 USE_1W_PIN=")); - Serial.println(QUOTE(USE_1W_PIN)); + debugSerial.print(F("(-)DS2482-100 USE_1W_PIN=")); + debugSerial.println(QUOTE(USE_1W_PIN)); #else - Serial.println(F("(+)DS2482-100")); + debugSerial.println(F("(+)DS2482-100")); #endif #ifdef Wiz5500 - Serial.println(F("(+)WizNet5500")); + debugSerial.println(F("(+)WizNet5500")); #endif #ifdef DMX_DISABLE - Serial.println(F("(-)DMX")); + debugSerial.println(F("(-)DMX")); #else - Serial.println(F("(+)DMX")); + debugSerial.println(F("(+)DMX")); #endif #ifdef MODBUS_DISABLE - Serial.println(F("(-)MODBUS")); + debugSerial.println(F("(-)MODBUS")); #else - Serial.println(F("(+)MODBUS")); + debugSerial.println(F("(+)MODBUS")); #endif #ifdef OWIRE_DISABLE - Serial.println(F("(-)OWIRE")); + debugSerial.println(F("(-)OWIRE")); #else - Serial.println(F("(+)OWIRE")); + debugSerial.println(F("(+)OWIRE")); #endif #ifndef DHT_DISABLE - Serial.println(F("(+)DHT")); + debugSerial.println(F("(+)DHT")); #else - Serial.println(F("(-)DHT")); -#endif - -#ifdef Wiz5500 - Serial.println(F("(+)Wiz5500")); + debugSerial.println(F("(-)DHT")); #endif #ifdef SD_CARD_INSERTED - Serial.println(F("(+)SDCARD")); + debugSerial.println(F("(+)SDCARD")); #endif #ifdef RESET_PIN - Serial.print(F("(+)HARDRESET on pin=")); - Serial.println(F(QUOTE(RESET_PIN))); + debugSerial.print(F("(+)HARDRESET on pin=")); + debugSerial.println(F(QUOTE(RESET_PIN))); #else - Serial.println("(-)HARDRESET, using soft"); + debugSerial.println("(-)HARDRESET, using soft"); #endif #ifdef RESTART_LAN_ON_MQTT_ERRORS - Serial.println(F("(+)RESTART_LAN_ON_MQTT_ERRORS")); + debugSerial.println(F("(+)RESTART_LAN_ON_MQTT_ERRORS")); #else - Serial.println("(-)RESTART_LAN_ON_MQTT_ERRORS"); + debugSerial.println("(-)RESTART_LAN_ON_MQTT_ERRORS"); #endif } @@ -1191,7 +1217,7 @@ void setupMacAddress() { if (mac[i] != 0 && mac[i] != 0xff) isMacValid = true; } if (!isMacValid) { - Serial.println(F("Invalid MAC: set firmware's MAC")); + debugSerial.println(F("Invalid MAC: set firmware's MAC")); memcpy(mac, firmwareMacAddress, 6); } printMACAddress(); @@ -1199,7 +1225,7 @@ void setupMacAddress() { void setupCmdArduino() { cmdInit(uint32_t(SERIAL_BAUD)); - Serial.println(F(">>>")); + debugSerial.println(F(">>>")); cmdAdd("help", cmdFunctionHelp); cmdAdd("save", cmdFunctionSave); cmdAdd("load", cmdFunctionLoad); @@ -1231,7 +1257,7 @@ void loop_main() { // unsigned long lastpacket = DMXSerial.noDataSince(); DMXCheck(); #endif - // if (lastpacket && (lastpacket%10==0)) Serial.println(lastpacket); + // if (lastpacket && (lastpacket%10==0)) debugSerial.println(lastpacket); if (items) { #ifndef MODBUS_DISABLE @@ -1257,7 +1283,7 @@ void owIdle(void) { wdt_res(); return; //TODO: unreached code - Serial.print(F("o")); + debugSerial.print(F("o")); if (lanLoop() == 1) mqttClient.loop(); //if (owReady) owLoop(); @@ -1272,7 +1298,7 @@ void owIdle(void) { void ethernetIdle(void){ wdt_res(); inputLoop(); -// Serial.print("."); +// debugSerial.print("."); }; void modbusIdle(void) { @@ -1357,8 +1383,8 @@ void thermoLoop(void) { int curTemp = aJson.getArrayItem(thermoExtensionArray, IET_TEMP)->valueint; if (!aJson.getArrayItem(thermoExtensionArray, IET_ATTEMPTS)->valueint) { - Serial.print(thermoItem->name); - Serial.println(F(" Expired")); + debugSerial.print(thermoItem->name); + debugSerial.println(F(" Expired")); } else { if (!(--aJson.getArrayItem(thermoExtensionArray, IET_ATTEMPTS)->valueint)) @@ -1368,27 +1394,27 @@ void thermoLoop(void) { if (curTemp > THERMO_OVERHEAT_CELSIUS) mqttClient.publish("/alarm/ovrht", thermoItem->name); - Serial.print(thermoItem->name); - Serial.print(F(" Set:")); - Serial.print(thermoSetting); - Serial.print(F(" Cur:")); - Serial.print(curTemp); - Serial.print(F(" cmd:")); - Serial.print(thermoStateCommand); + debugSerial.print(thermoItem->name); + debugSerial.print(F(" Set:")); + debugSerial.print(thermoSetting); + debugSerial.print(F(" Cur:")); + debugSerial.print(curTemp); + debugSerial.print(F(" cmd:")); + debugSerial.print(thermoStateCommand); pinMode(thermoPin, OUTPUT); if (thermoDisabledOrDisconnected(thermoExtensionArray, thermoStateCommand)) { digitalWrite(thermoPin, LOW); - Serial.println(F(" OFF")); + debugSerial.println(F(" OFF")); } else { if (curTemp < thermoSetting - THERMO_GIST_CELSIUS) { digitalWrite(thermoPin, HIGH); - Serial.println(F(" ON")); + debugSerial.println(F(" ON")); } //too cold else if (curTemp >= thermoSetting) { digitalWrite(thermoPin, LOW); - Serial.println(F(" OFF")); + debugSerial.println(F(" OFF")); } //Reached settings - else Serial.println(F(" -target zone-")); // Nothing to do + else debugSerial.println(F(" -target zone-")); // Nothing to do } thermostatCheckPrinted = true; } @@ -1398,9 +1424,9 @@ void thermoLoop(void) { nextThermostatCheck = millis() + THERMOSTAT_CHECK_PERIOD; #ifndef DISABLE_FREERAM_PRINT - (thermostatCheckPrinted) ? Serial.print(F("\nfree:")) : Serial.print(F(" ")); - Serial.print(freeRam()); - Serial.print(" "); + (thermostatCheckPrinted) ? debugSerial.print(F("\nfree:")) : debugSerial.print(F(" ")); + debugSerial.print(freeRam()); + debugSerial.print(" "); #endif } @@ -1431,4 +1457,3 @@ short thermoSetCurTemp(char *name, short t) { } } - diff --git a/lighthub/main.h b/lighthub/main.h index ec5e129..3784c8a 100644 --- a/lighthub/main.h +++ b/lighthub/main.h @@ -10,6 +10,12 @@ #define wdt_dis() #endif +#if defined(ARDUINO_ARCH_STM32F1) +#define wdt_res() +#define wdt_en() +#define wdt_dis() +#endif + #ifndef DHCP_RETRY_INTERVAL #define DHCP_RETRY_INTERVAL 60000 #endif @@ -50,7 +56,9 @@ #include "stdarg.h" #include "item.h" #include "inputs.h" +#ifndef ARDUINO_ARCH_STM32F1 #include "FastLED.h" +#endif #include "Dns.h" //#include "hsv2rgb.h" diff --git a/lighthub/options.h b/lighthub/options.h index a3fb25b..7fc1afe 100644 --- a/lighthub/options.h +++ b/lighthub/options.h @@ -135,4 +135,16 @@ #endif #endif -#define DHT_POLL_DELAY_DEFAULT 15000 \ No newline at end of file +#define DHT_POLL_DELAY_DEFAULT 15000 + +#ifdef ARDUINO_ARCH_STM32F1 +#define strncpy_P strncpy +#endif + +#ifndef debugSerial +#define debugSerial Serial1 +#endif + +#ifndef Wiz5500 +#define W5100_ETHERNET_SHIELD +#endif \ No newline at end of file diff --git a/lighthub/owTerm.cpp b/lighthub/owTerm.cpp index f965f31..dd4f101 100644 --- a/lighthub/owTerm.cpp +++ b/lighthub/owTerm.cpp @@ -41,6 +41,7 @@ unsigned long owTimer = 0; owChangedType owChanged; int owUpdate() { +#ifndef OWIRE_DISABLE unsigned long finish = millis() + OW_UPDATE_INTERVAL; short sr; @@ -80,11 +81,12 @@ int owUpdate() { Serial.print(F("1-wire count: ")); Serial.println(t_count); - +#endif } int owSetup(owChangedType owCh) { +#ifndef OWIRE_DISABLE //// todo - move memory allocation to here if (net) return true; // Already initialized #ifdef DS2482_100_I2C_TO_1W_BRIDGE @@ -138,6 +140,7 @@ net = new OneWire (USE_1W_PIN); delay(500); +#endif } @@ -182,6 +185,7 @@ int owFind(DeviceAddress addr) { } void owAdd(DeviceAddress addr) { +#ifndef OWIRE_DISABLE if (t_count>=t_max) return; wstat[t_count] = SW_FIND; //Newly detected memcpy(term[t_count], addr, 8); @@ -198,4 +202,5 @@ void owAdd(DeviceAddress addr) { // sensors.requestTemperaturesByAddress(term[t_count]); } t_count++; +#endif } diff --git a/lighthub/owTerm.h b/lighthub/owTerm.h index 18cf543..951bc32 100644 --- a/lighthub/owTerm.h +++ b/lighthub/owTerm.h @@ -50,7 +50,10 @@ e-mail anklimov@gmail.com #define t_max 20 //Maximum number of 1w devices #define TEMPERATURE_PRECISION 9 +#ifndef ARDUINO_ARCH_STM32F1 #include +#endif + #include #include "aJSON.h" diff --git a/lighthub/utils.cpp b/lighthub/utils.cpp index 5a771c9..ac5357e 100644 --- a/lighthub/utils.cpp +++ b/lighthub/utils.cpp @@ -20,7 +20,7 @@ e-mail anklimov@gmail.com #include "utils.h" -#if defined(__SAM3X8E__) +#if defined(__SAM3X8E__) || defined(ARDUINO_ARCH_STM32F1) #include #endif @@ -53,7 +53,7 @@ void SetBytes(uint8_t *addr, uint8_t count, char *out) { byte HEX2DEC(char i) { - byte v; + byte v=0; if ('a' <= i && i <= 'f') { v = i - 97 + 10; } else if ('A' <= i && i <= 'F') { v = i - 65 + 10; } else if ('0' <= i && i <= '9') { v = i - 48; } @@ -94,6 +94,20 @@ unsigned long freeRam () } #endif +#if defined(ARDUINO_ARCH_STM32F1) +extern char _end; +extern "C" char *sbrk(int i); + +unsigned long freeRam() { + char *heapend = sbrk(0); + register char *stack_ptr asm( "sp" ); + struct mallinfo mi = mallinfo(); + + return stack_ptr - heapend + mi.fordblks; +} + +#endif + #if defined(__SAM3X8E__) extern char _end; extern "C" char *sbrk(int i); @@ -119,4 +133,6 @@ void parseBytes(const char *str, char separator, byte *bytes, int maxBytes, int } str++; // Point to next character after separator } -} \ No newline at end of file +} +#pragma message(VAR_NAME_VALUE(debugSerial)) +#pragma message(VAR_NAME_VALUE(SERIAL_BAUD)) \ No newline at end of file diff --git a/lighthub/utils.h b/lighthub/utils.h index f0cb845..1725b59 100644 --- a/lighthub/utils.h +++ b/lighthub/utils.h @@ -19,6 +19,9 @@ e-mail anklimov@gmail.com */ #define Q(x) #x #define QUOTE(x) Q(x) +#define VALUE_TO_STRING(x) #x +#define VALUE(x) VALUE_TO_STRING(x) +#define VAR_NAME_VALUE(var) #var "=" VALUE(var) #include diff --git a/platformio.ini b/platformio.ini index 75db53e..dc5bdcf 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,7 +10,7 @@ [platformio] src_dir = lighthub env_default = - megaatmega2560 +; megaatmega2560 ; megaatmega2560-net ; due ; esp8266 @@ -18,7 +18,7 @@ env_default = ; megaatmega2560-5500 ; due-5500 ; controllino -; stm32f407 + stm32 build_dir = /tmp/pioenvs libdeps_dir = /tmp/piolibdeps @@ -44,28 +44,22 @@ lib_deps = DHT sensor library for ESPx DHT sensor library -[env:stm32f407] +[env:stm32] platform = ststm32 framework = arduino -board = genericSTM32F407VET6 +board = nucleo_f103rb +upload_protocol = st-link ;lib_ldf_mode = chain+ -build_flags = !sh build_flags_stm32f407.sh +build_flags = !sh build_flags_stm32.sh lib_deps = - https://github.com/sebnil/DueFlashStorage - https://github.com/anklimov/Arduino-Temperature-Control-Library.git - https://github.com/anklimov/DS2482_OneWire - https://github.com/anklimov/DmxDue - https://github.com/anklimov/ArduinoHttpClient + DallasTemperature https://github.com/anklimov/aJson https://github.com/anklimov/CmdArduino + ArduinoHttpClient https://github.com/anklimov/ModbusMaster - https://github.com/anklimov/Ethernet - https://github.com/anklimov/Ethernet2 +; https://github.com/Serasidis/Ethernet_STM.git +; https://github.com/livello/Ethernet_STM.git https://github.com/knolleary/pubsubclient.git - https://github.com/anklimov/Artnet.git -; FastLED - SD - SdFat Adafruit Unified Sensor DHT sensor library From f38dfc185164981e6bbe960d85847d0cb6e42d2b Mon Sep 17 00:00:00 2001 From: livello Date: Sun, 9 Sep 2018 01:16:07 +0300 Subject: [PATCH 6/6] from IS-STM32Duino --- .idea/markdown-exported-files.xml | 8 + lighthub/inputs.cpp | 198 +++++++++++++------- lighthub/inputs.h | 30 +-- lighthub/main.cpp | 295 +++++++++++++++++------------- lighthub/main.h | 2 +- lighthub/options.h | 3 +- platformio.ini | 44 +++-- pre_stm32.sh | 4 + 8 files changed, 362 insertions(+), 222 deletions(-) create mode 100644 .idea/markdown-exported-files.xml create mode 100644 pre_stm32.sh diff --git a/.idea/markdown-exported-files.xml b/.idea/markdown-exported-files.xml new file mode 100644 index 0000000..5d1f129 --- /dev/null +++ b/.idea/markdown-exported-files.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/lighthub/inputs.cpp b/lighthub/inputs.cpp index 88af542..365e7df 100644 --- a/lighthub/inputs.cpp +++ b/lighthub/inputs.cpp @@ -23,30 +23,35 @@ e-mail anklimov@gmail.com #include #ifndef DHT_DISABLE +#if defined(ESP8266) || defined(ARDUINO_ARCH_ESP32) +#include +#else #include "DHT.h" #endif +#endif extern PubSubClient mqttClient; -//DHT dht(); + +static volatile unsigned long nextPollMillisValue[5]; +static volatile int nextPollMillisPin[5] = {0,0,0,0,0}; #if defined(__AVR__) -static volatile long encoder_value[6]; +static volatile long counter_value[6]; #endif #if defined(ESP8266) -static volatile long encoder_value[6]; +static volatile long counter_value[6]; #endif #if defined(ARDUINO_ARCH_ESP32) -static volatile long encoder_value[6]; +static volatile long counter_value[6]; #endif #if defined(__SAM3X8E__) || defined(ARDUINO_ARCH_STM32F1) -static short encoder_irq_map[54]; - static long encoder_value[54]; - static int encoders_count; +static short counter_irq_map[54]; + static long counter_value[54]; + static int counters_count; #endif - Input::Input(char * name) //Constructor { if (name) @@ -57,13 +62,13 @@ Input::Input(char * name) //Constructor } -Input::Input(int pin) //Constructor +Input::Input(int pin) { // TODO } - Input::Input(aJsonObject * obj) //Constructor + Input::Input(aJsonObject * obj) { inputObj= obj; Parse(); @@ -86,9 +91,9 @@ void Input::Parse() aJsonObject *s; s = aJson.getObjectItem(inputObj, "T"); - if (s) inType = s->valueint; + if (s) inType = static_cast(s->valueint); - pin = atoi(inputObj->name); + pin = static_cast(atoi(inputObj->name)); s = aJson.getObjectItem(inputObj, "S"); if (!s) { @@ -108,18 +113,17 @@ int Input::poll() { if (!isValid()) return -1; if (inType & IN_DHT22) dht22Poll(); -else if(inType & IN_ENCODER) - encoderPoll(); - /* example - else if (inType & IN_ANALOG) - analogPoll(); */ + else if (inType & IN_COUNTER) + counterPoll(); + else if (inType & IN_UPTIME) + uptimePoll(); else contactPoll(); return 0; } -void Input::encoderPoll() { - if (store->nextPollMillis > millis()) +void Input::counterPoll() { + if(nextPollTime()>millis()) return; if (store->logicState == 0) { #if defined(__AVR__) @@ -131,31 +135,31 @@ void Input::encoderPoll() { } else { Serial.print(F("IRQ:")); Serial.print(pin); - Serial.print(F(" Encoder type. INCORRECT Interrupt number!!!")); + Serial.print(F(" Counter type. INCORRECT Interrupt number!!!")); return; } #endif #if defined(__SAM3X8E__) - attachInterruptPinIrq(pin,encoders_count); - encoder_irq_map[encoders_count]=pin; - encoders_count++; + attachInterruptPinIrq(pin,counters_count); + counter_irq_map[counters_count]=pin; + counters_count++; #endif store->logicState = 1; return; } - long encoderValue = encoder_value[pin]; - Serial.print(F("IN:"));Serial.print(pin);Serial.print(F(" Encoder type. val="));Serial.print(encoderValue); + long counterValue = counter_value[pin]; + Serial.print(F("IN:"));Serial.print(pin);Serial.print(F(" Counter type. val="));Serial.print(counterValue); aJsonObject *emit = aJson.getObjectItem(inputObj, "emit"); if (emit) { char valstr[10]; char addrstr[100] = ""; strcat(addrstr, emit->valuestring); - sprintf(valstr, "%d", encoderValue); + sprintf(valstr, "%d", counterValue); mqttClient.publish(addrstr, valstr); - store->nextPollMillis = millis() + DHT_POLL_DELAY_DEFAULT; - Serial.print(F(" NextPollMillis="));Serial.println(store->nextPollMillis); + setNextPollTime(millis() + DHT_POLL_DELAY_DEFAULT); + Serial.print(F(" NextPollMillis="));Serial.println(nextPollTime()); } else Serial.print(F(" No emit data!")); @@ -172,22 +176,22 @@ void Input::attachInterruptPinIrq(int realPin, int irq) { #endif switch(irq){ case 0: - attachInterrupt(real_irq, onEncoderChanged0, RISING); + attachInterrupt(real_irq, onCounterChanged0, RISING); break; case 1: - attachInterrupt(real_irq, onEncoderChanged1, RISING); + attachInterrupt(real_irq, onCounterChanged1, RISING); break; case 2: - attachInterrupt(real_irq, onEncoderChanged2, RISING); + attachInterrupt(real_irq, onCounterChanged2, RISING); break; case 3: - attachInterrupt(real_irq, onEncoderChanged3, RISING); + attachInterrupt(real_irq, onCounterChanged3, RISING); break; case 4: - attachInterrupt(real_irq, onEncoderChanged4, RISING); + attachInterrupt(real_irq, onCounterChanged4, RISING); break; case 5: - attachInterrupt(real_irq, onEncoderChanged5, RISING); + attachInterrupt(real_irq, onCounterChanged5, RISING); break; default: Serial.print(F("Incorrect irq:"));Serial.println(irq); @@ -197,14 +201,27 @@ void Input::attachInterruptPinIrq(int realPin, int irq) { void Input::dht22Poll() { #ifndef DHT_DISABLE - if (store->nextPollMillis > millis()) + if(nextPollTime()>millis()) return; +#if defined(ESP8266) || defined(ARDUINO_ARCH_ESP32) + DHTesp dhtSensor; + dhtSensor.setup(pin, DHTesp::DHT22); + TempAndHumidity dhtSensorData = dhtSensor.getTempAndHumidity(); + float temp = dhtSensorData.temperature; + float humidity = dhtSensorData.humidity; +#else DHT dht(pin, DHT22); float temp = dht.readTemperature(); float humidity = dht.readHumidity(); +#endif aJsonObject *emit = aJson.getObjectItem(inputObj, "emit"); - Serial.print(F("IN:"));Serial.print(pin);Serial.print(F(" DHT22 type. T="));Serial.print(temp); - Serial.print(F("°C H="));Serial.print(humidity);Serial.print(F("%")); + Serial.print(F("IN:")); + Serial.print(pin); + Serial.print(F(" DHT22 type. T=")); + Serial.print(temp); + Serial.print(F("°C H=")); + Serial.print(humidity); + Serial.print(F("%")); if (emit && temp && humidity && temp == temp && humidity == humidity) { char valstr[10]; char addrstr[100] = ""; @@ -215,28 +232,53 @@ void Input::dht22Poll() { addrstr[strlen(addrstr) - 1] = 'H'; printFloatValueToStr(humidity, valstr); mqttClient.publish(addrstr, valstr); - store->nextPollMillis = millis() + DHT_POLL_DELAY_DEFAULT; - Serial.print(" NextPollMillis=");Serial.println(store->nextPollMillis); - } - else - store->nextPollMillis = millis() + DHT_POLL_DELAY_DEFAULT/3; + setNextPollTime(millis() + DHT_POLL_DELAY_DEFAULT); + Serial.print(" NextPollMillis="); + Serial.println(nextPollTime()); + } else + setNextPollTime(millis() + DHT_POLL_DELAY_DEFAULT / 3); #endif } -void Input::printFloatValueToStr(float temp, char *valstr) { - #if defined(ESP8266) - sprintf(valstr, "%2.1f", temp); +unsigned long Input::nextPollTime() const { + for(int i=0;i<5;i++){ + if(nextPollMillisPin[i]==pin) + return nextPollMillisValue[i]; + else if(nextPollMillisPin[i]==0) { + nextPollMillisPin[i]=pin; + return nextPollMillisValue[i] = 0; + } + } + return 0; +} + +void Input::setNextPollTime(unsigned long pollTime) { + for (int i = 0; i < 5; i++) { + if (nextPollMillisPin[i] == pin) { + nextPollMillisValue[i] = pollTime; + return; + } else if (nextPollMillisPin[i] == 0) { + nextPollMillisPin[i] == pin; + nextPollMillisValue[i] = pollTime; + return; + } + } +} + +void Input::printFloatValueToStr(float value, char *valstr) { + #if defined(ESP8266) || defined(ARDUINO_ARCH_ESP32) + sprintf(valstr, "%2.1f", value); #endif #if defined(__AVR__) - sprintf(valstr, "%d", (int)temp); - int fractional = 10.0*((float)abs(temp)-(float)abs((int)temp)); + sprintf(valstr, "%d", (int)value); + int fractional = 10.0*((float)abs(value)-(float)abs((int)value)); int val_len =strlen(valstr); valstr[val_len]='.'; valstr[val_len+1]='0'+fractional; valstr[val_len+2]='\0'; #endif #if defined(__SAM3X8E__) - sprintf(valstr, "%2.1f", temp); + sprintf(valstr, "%2.1f",value); #endif } @@ -245,7 +287,7 @@ void Input::contactPoll() { #if defined(ARDUINO_ARCH_STM32F1) WiringPinMode inputPinMode; #endif -#if defined(__SAM3X8E__)||defined(__AVR__)||defined(ESP8266) +#if defined(__SAM3X8E__)||defined(__AVR__)||defined(ESP8266)||defined(ARDUINO_ARCH_ESP32) uint32_t inputPinMode; #endif @@ -271,6 +313,19 @@ void Input::contactPoll() { store->bounce = SAME_STATE_ATTEMPTS; } +void Input::uptimePoll() { + if(nextPollTime()>millis()) + return; + aJsonObject *emit = aJson.getObjectItem(inputObj, "emit"); + if (emit) { + char valstr[11]; +// printUlongValueToStr(valstr,millis()); + printUlongValueToStr(valstr,millis()); + mqttClient.publish(emit->valuestring, valstr); + } + setNextPollTime(millis() +UPTIME_POLL_DELAY_DEFAULT); +} + void Input::onContactChanged(int val) { Serial.print(F("IN:")); Serial.print(pin);Serial.print(F("="));Serial.println(val); @@ -309,32 +364,47 @@ void Input::onContactChanged(int val) } } -void Input::onEncoderChanged(int i) { +void Input::onCounterChanged(int i) { #if defined(__SAM3X8E__) - encoder_value[encoder_irq_map[i]]++; + counter_value[counter_irq_map[i]]++; #endif #if defined(__AVR__) - encoder_value[i]++; + counter_value[i]++; #endif } -void Input::onEncoderChanged0() { - onEncoderChanged(0); +void Input::onCounterChanged0() { + onCounterChanged(0); } -void Input::onEncoderChanged1() { - onEncoderChanged(1); +void Input::onCounterChanged1() { + onCounterChanged(1); } -void Input::onEncoderChanged2() { - onEncoderChanged(2); +void Input::onCounterChanged2() { + onCounterChanged(2); } -void Input::onEncoderChanged3() { - onEncoderChanged(3); +void Input::onCounterChanged3() { + onCounterChanged(3); } -void Input::onEncoderChanged4() { - onEncoderChanged(4); +void Input::onCounterChanged4() { + onCounterChanged(4); } -void Input::onEncoderChanged5() { - onEncoderChanged(5); +void Input::onCounterChanged5() { + onCounterChanged(5); +} + +void Input::printUlongValueToStr(char *valstr, unsigned long value) { + char buf[11]; + int i=0; + for(;value>0;i++){ + unsigned long mod = value - ((unsigned long)(value/10))*10; + buf[i]=mod+48; + value = (unsigned long)(value/10); + } + + for(int n=0;n<=i;n++){ + valstr[n]=buf[i-n-1]; + } + valstr[i]='\0'; } diff --git a/lighthub/inputs.h b/lighthub/inputs.h index 281c97c..4895b51 100644 --- a/lighthub/inputs.h +++ b/lighthub/inputs.h @@ -27,7 +27,8 @@ e-mail anklimov@gmail.com #define IN_PUSH_ON 0 // PUSH - ON, Release - OFF (ovverrided by pcmd/rcmd) - DEFAULT #define IN_PUSH_TOGGLE 1 // Every physicall push toggle logical switch on/off #define IN_DHT22 4 -#define IN_ENCODER 8 +#define IN_COUNTER 8 +#define IN_UPTIME 16 #define SAME_STATE_ATTEMPTS 3 @@ -72,7 +73,7 @@ typedef union { int8_t bounce; int8_t currentValue; }; - unsigned long nextPollMillis; + } inStore; class Input { @@ -94,13 +95,13 @@ public: int poll(); - static void inline onEncoderChanged(int i); - static void onEncoderChanged0(); - static void onEncoderChanged1(); - static void onEncoderChanged2(); - static void onEncoderChanged3(); - static void onEncoderChanged4(); - static void onEncoderChanged5(); + static void inline onCounterChanged(int i); + static void onCounterChanged0(); + static void onCounterChanged1(); + static void onCounterChanged2(); + static void onCounterChanged3(); + static void onCounterChanged4(); + static void onCounterChanged5(); @@ -111,10 +112,17 @@ protected: void dht22Poll(); - void printFloatValueToStr(float temp, char *valstr); + void printFloatValueToStr(float value, char *valstr); - void encoderPoll(); + void counterPoll(); void attachInterruptPinIrq(int realPin, int irq); + unsigned long nextPollTime() const; + void setNextPollTime(unsigned long pollTime); + + + void uptimePoll(); + + void printUlongValueToStr(char *valstr, unsigned long value); }; diff --git a/lighthub/main.cpp b/lighthub/main.cpp index e8ea09d..a1c5da3 100644 --- a/lighthub/main.cpp +++ b/lighthub/main.cpp @@ -88,6 +88,7 @@ WiFiClient ethClient; #include #include #include +#include "Ethernet3.h" WiFiClient ethClient; #endif @@ -105,6 +106,14 @@ WiFiClient ethClient; EthernetClient ethClient; #endif +#ifndef SYSLOG_DISABLE +#include +#include +EthernetUDP udpSyslogClient; +Syslog udpSyslog(udpSyslogClient, SYSLOG_PROTO_IETF); +unsigned long nextSyslogPingTime; +#endif + lan_status lanStatus = INITIAL_STATE; const char outprefix[] PROGMEM = OUTTOPIC; @@ -120,6 +129,7 @@ aJsonObject *mqttArr = NULL; aJsonObject *modbusArr = NULL; aJsonObject *owArr = NULL; aJsonObject *dmxArr = NULL; +aJsonObject *udpSyslogArr = NULL; unsigned long nextPollingCheck = 0; unsigned long nextInputCheck = 0; @@ -158,7 +168,7 @@ void mqttCallback(char *topic, byte *payload, unsigned int length) { debugSerial.print(topic); debugSerial.print(F("] ")); if (!payload) return; - payload[length] = 0; + payload[length] = 0; int fr = freeRam(); if (fr < 250) { @@ -172,8 +182,8 @@ void mqttCallback(char *topic, byte *payload, unsigned int length) { debugSerial.println(); if(!strcmp(topic,CMDTOPIC)) { - cmd_parse((char *)payload); - return; + cmd_parse((char *)payload); + return; } boolean retaining = (lanStatus == RETAINING_COLLECTING); @@ -191,17 +201,17 @@ void mqttCallback(char *topic, byte *payload, unsigned int length) { return; } char subtopic[MQTT_SUBJECT_LENGTH] = ""; - // int cmd = 0; + // int cmd = 0; //cmd = txt2cmd((char *) payload); char *t; if (t = strrchr(topic, '/')) strncpy(subtopic, t + 1, MQTT_SUBJECT_LENGTH - 1); - Item item(subtopic); - if (item.isValid()) { - if (item.itemType == CH_GROUP && retaining) - return; //Do not restore group channels - they consist not relevant data + Item item(subtopic); + if (item.isValid()) { + if (item.itemType == CH_GROUP && retaining) + return; //Do not restore group channels - they consist not relevant data item.Ctrl((char *)payload, !retaining); - } //valid item + } //valid item } void printIPAddress(IPAddress ipAddress) { @@ -230,7 +240,7 @@ lan_status lanLoop() { #ifdef NOETHER lanStatus=DO_NOTHING;//-14; -#endif + #endif switch (lanStatus) { case INITIAL_STATE: @@ -347,60 +357,77 @@ void ip_ready_config_loaded_connecting_to_broker() { char *user = ∅ char passwordBuf[16] = ""; char *password = passwordBuf; - +#ifndef SYSLOG_DISABLE + debugSerial.println("debugSerial:"); + delay(100); + char *syslogServer = aJson.getArrayItem(udpSyslogArr, 0)->valuestring; + int syslogPort = aJson.getArrayItem(udpSyslogArr, 1)->valueint; + char *syslogDeviceHostname = aJson.getArrayItem(udpSyslogArr, 2)->valuestring; + char *syslogAppname = aJson.getArrayItem(udpSyslogArr, 3)->valuestring; + debugSerial.println("debugSerial:"); + debugSerial.println(syslogServer); + debugSerial.println(syslogPort); + debugSerial.println(syslogDeviceHostname); + debugSerial.println(syslogAppname); + udpSyslog.server(syslogServer, syslogPort); + udpSyslog.deviceHostname(syslogDeviceHostname); + udpSyslog.appName(syslogAppname); + udpSyslog.defaultPriority(LOG_KERN); + udpSyslog.log(LOG_INFO, "UDP Syslog initialized!"); +#endif if (!mqttClient.connected() && mqttArr && ((n = aJson.getArraySize(mqttArr)) > 1)) { - char *client_id = aJson.getArrayItem(mqttArr, 0)->valuestring; - char *servername = aJson.getArrayItem(mqttArr, 1)->valuestring; - if (n >= 3) port = aJson.getArrayItem(mqttArr, 2)->valueint; - if (n >= 4) user = aJson.getArrayItem(mqttArr, 3)->valuestring; - if (!loadFlash(OFFSET_MQTT_PWD, passwordBuf, sizeof(passwordBuf)) && (n >= 5)) { - password = aJson.getArrayItem(mqttArr, 4)->valuestring; - debugSerial.println(F("Using MQTT password from config")); - } + char *client_id = aJson.getArrayItem(mqttArr, 0)->valuestring; + char *servername = aJson.getArrayItem(mqttArr, 1)->valuestring; + if (n >= 3) port = aJson.getArrayItem(mqttArr, 2)->valueint; + if (n >= 4) user = aJson.getArrayItem(mqttArr, 3)->valuestring; + if (!loadFlash(OFFSET_MQTT_PWD, passwordBuf, sizeof(passwordBuf)) && (n >= 5)) { + password = aJson.getArrayItem(mqttArr, 4)->valuestring; + debugSerial.println(F("Using MQTT password from config")); + } - mqttClient.setServer(servername, port); - mqttClient.setCallback(mqttCallback); + mqttClient.setServer(servername, port); + mqttClient.setCallback(mqttCallback); - debugSerial.print(F("Attempting MQTT connection to ")); - debugSerial.print(servername); - debugSerial.print(F(":")); - debugSerial.print(port); - debugSerial.print(F(" user:")); - debugSerial.print(user); - debugSerial.print(F(" ...")); + debugSerial.print(F("Attempting MQTT connection to ")); + debugSerial.print(servername); + debugSerial.print(F(":")); + debugSerial.print(port); + debugSerial.print(F(" user:")); + debugSerial.print(user); + debugSerial.print(F(" ...")); - wdt_dis(); //potential unsafe for ethernetIdle(), but needed to avoid cyclic reboot if mosquitto out of order - if (mqttClient.connect(client_id, user, password)) { - mqttErrorRate = 0; - debugSerial.print(F("connected as ")); - debugSerial.println(client_id); - wdt_en(); - configOk = true; - // ... Temporary subscribe to status topic - char buf[MQTT_TOPIC_LENGTH]; + wdt_dis(); //potential unsafe for ethernetIdle(), but needed to avoid cyclic reboot if mosquitto out of order + if (mqttClient.connect(client_id, user, password)) { + mqttErrorRate = 0; + debugSerial.print(F("connected as ")); + debugSerial.println(client_id); + wdt_en(); + configOk = true; + // ... Temporary subscribe to status topic + char buf[MQTT_TOPIC_LENGTH]; - strncpy_P(buf, outprefix, sizeof(buf)); - strncat(buf, "#", sizeof(buf)); - mqttClient.subscribe(buf); + strncpy_P(buf, outprefix, sizeof(buf)); + strncat(buf, "#", sizeof(buf)); + mqttClient.subscribe(buf); - //Subscribing for command topics - strncpy_P(buf, inprefix, sizeof(buf)); - strncat(buf, "#", sizeof(buf)); - mqttClient.subscribe(buf); + //Subscribing for command topics + strncpy_P(buf, inprefix, sizeof(buf)); + strncat(buf, "#", sizeof(buf)); + mqttClient.subscribe(buf); - //restoreState(); - // if (_once) {DMXput(); _once=0;} - lanStatus = RETAINING_COLLECTING;//4; - nextLanCheckTime = millis() + 5000; - debugSerial.println(F("Awaiting for retained topics")); - } else { - debugSerial.print(F("failed, rc=")); - debugSerial.print(mqttClient.state()); - debugSerial.println(F(" try again in 5 seconds")); - nextLanCheckTime = millis() + 5000; + //restoreState(); + // if (_once) {DMXput(); _once=0;} + lanStatus = RETAINING_COLLECTING;//4; + nextLanCheckTime = millis() + 5000; + debugSerial.println(F("Awaiting for retained topics")); + } else { + debugSerial.print(F("failed, rc=")); + debugSerial.print(mqttClient.state()); + debugSerial.println(F(" try again in 5 seconds")); + nextLanCheckTime = millis() + 5000; #ifdef RESTART_LAN_ON_MQTT_ERRORS - mqttErrorRate++; + mqttErrorRate++; if(mqttErrorRate>50){ debugSerial.print(F("Too many MQTT connection errors. Restart LAN")); mqttErrorRate=0; @@ -412,9 +439,9 @@ void ip_ready_config_loaded_connecting_to_broker() { } #endif - lanStatus = RECONNECT;//12; - } - } + lanStatus = RECONNECT;//12; + } + } } void onInitialStateInitLAN() { @@ -484,7 +511,7 @@ void onInitialStateInitLAN() { } else Ethernet.begin(mac, ip, dns); } else Ethernet.begin(mac, ip); } - else { + else { debugSerial.println("No IP data found in flash"); wdt_dis(); #if defined(__AVR__) || defined(__SAM3X8E__) @@ -510,7 +537,7 @@ void onInitialStateInitLAN() { printIPAddress(Ethernet.localIP()); lanStatus = HAVE_IP_ADDRESS;//1; } -#endif + #endif } #ifdef ARDUINO_ARCH_STM32F1 @@ -587,17 +614,20 @@ void cmdFunctionHelp(int arg_cnt, char **args) //(char* tokens) { printFirmwareVersionAndBuildOptions(); + #ifndef SYSLOG_DISABLE +// udpSyslog.logf(LOG_INFO, "free RAM: %d",freeRam()); + #endif debugSerial.print(F(" free RAM: "));debugSerial.print(freeRam()); debugSerial.println(F(" Use the commands: 'help' - this text\n" - "'mac de:ad:be:ef:fe:00' set and store MAC-address in EEPROM\n" - "'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n" - "'save' - save config in NVRAM\n" - "'get' [config addr]' - get config from pre-configured URL and store addr\n" - "'load' - load config from NVRAM\n" - "'pwd' - define MQTT password\n" - "'kill' - test watchdog\n" - "'clear' - clear EEPROM\n" - "'reboot' - reboot controller")); + "'mac de:ad:be:ef:fe:00' set and store MAC-address in EEPROM\n" + "'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n" + "'save' - save config in NVRAM\n" + "'get' [config addr]' - get config from pre-configured URL and store addr\n" + "'load' - load config from NVRAM\n" + "'pwd' - define MQTT password\n" + "'kill' - test watchdog\n" + "'clear' - clear EEPROM\n" + "'reboot' - reboot controller")); } void cmdFunctionKill(int arg_cnt, char **args) { @@ -613,7 +643,7 @@ void cmdFunctionReboot(int arg_cnt, char **args) { } void applyConfig() { - if (!root) return; + if (!root) return; #ifdef _dmxin int itemsCount; @@ -659,37 +689,38 @@ void applyConfig() { items = aJson.getObjectItem(root, "items"); // Digital output related Items initialization -pollingItem=NULL; -if (items) { -aJsonObject * item = items->child; -while (items && item) - if (item->type == aJson_Array && aJson.getArraySize(item)>1) { - Item it(item); - if (it.isValid()) { - int pin=it.getArg(); - int cmd = it.getCmd(); - switch (it.itemType) { - case CH_THERMO: - if (cmd<1) it.setCmd(CMD_OFF); - case CH_RELAY: - { - int k; - pinMode(pin, OUTPUT); - digitalWrite(pin, k = ((cmd == CMD_ON) ? HIGH : LOW)); - debugSerial.print(F("Pin:")); - debugSerial.print(pin); - debugSerial.print(F("=")); - debugSerial.println(k); - } - break; - } //switch - } //isValid - item = item->next; - } //if - pollingItem = items->child; -} + pollingItem=NULL; + if (items) { + aJsonObject * item = items->child; + while (items && item) + if (item->type == aJson_Array && aJson.getArraySize(item)>1) { + Item it(item); + if (it.isValid()) { + int pin=it.getArg(); + int cmd = it.getCmd(); + switch (it.itemType) { + case CH_THERMO: + if (cmd<1) it.setCmd(CMD_OFF); + case CH_RELAY: + { + int k; + pinMode(pin, OUTPUT); + digitalWrite(pin, k = ((cmd == CMD_ON) ? HIGH : LOW)); + debugSerial.print(F("Pin:")); + debugSerial.print(pin); + debugSerial.print(F("=")); + debugSerial.println(k); + } + break; + } //switch + } //isValid + item = item->next; + } //if + pollingItem = items->child; + } inputs = aJson.getObjectItem(root, "in"); mqttArr = aJson.getObjectItem(root, "mqtt"); + udpSyslogArr = aJson.getObjectItem(root, "syslog"); printConfigSummary(); } @@ -705,6 +736,8 @@ void printConfigSummary() { printBool(mqttArr); debugSerial.print(F("1-wire ")); printBool(owArr); + debugSerial.print(F("udp syslog ")); + printBool(udpSyslogArr); } void cmdFunctionLoad(int arg_cnt, char **args) { @@ -843,11 +876,11 @@ void cmdFunctionClearEEPROM(int arg_cnt, char **args){ void cmdFunctionPwd(int arg_cnt, char **args) //(char* tokens) { char empty[]=""; - if (arg_cnt) - saveFlash(OFFSET_MQTT_PWD,args[1]); - else saveFlash(OFFSET_MQTT_PWD,empty); - debugSerial.println(F("Password updated")); - } + if (arg_cnt) + saveFlash(OFFSET_MQTT_PWD,args[1]); + else saveFlash(OFFSET_MQTT_PWD,empty); + debugSerial.println(F("Password updated")); +} void cmdFunctionSetMac(int arg_cnt, char **args) { @@ -879,30 +912,30 @@ void printBool(bool arg) { (arg) ? debugSerial.println(F("on")) : debugSerial.pr void saveFlash(short n, char *str) { - short i; - short len=strlen(str); - if (len>31) len=31; - for(int i=0;i31) len=31; + for(int i=0;iread(); #endif - inputLoop(); + inputLoop(); } diff --git a/lighthub/main.h b/lighthub/main.h index 3784c8a..dc16718 100644 --- a/lighthub/main.h +++ b/lighthub/main.h @@ -109,7 +109,7 @@ #ifdef ARDUINO_ARCH_ESP32 #include -#include +//#include #endif diff --git a/lighthub/options.h b/lighthub/options.h index 7fc1afe..3eef817 100644 --- a/lighthub/options.h +++ b/lighthub/options.h @@ -136,13 +136,14 @@ #endif #define DHT_POLL_DELAY_DEFAULT 15000 +#define UPTIME_POLL_DELAY_DEFAULT 30000 #ifdef ARDUINO_ARCH_STM32F1 #define strncpy_P strncpy #endif #ifndef debugSerial -#define debugSerial Serial1 +#define debugSerial Serial #endif #ifndef Wiz5500 diff --git a/platformio.ini b/platformio.ini index dc5bdcf..6c1b13f 100644 --- a/platformio.ini +++ b/platformio.ini @@ -18,7 +18,7 @@ env_default = ; megaatmega2560-5500 ; due-5500 ; controllino - stm32 +; stm32 build_dir = /tmp/pioenvs libdeps_dir = /tmp/piolibdeps @@ -48,7 +48,9 @@ lib_deps = platform = ststm32 framework = arduino board = nucleo_f103rb -upload_protocol = st-link +upload_protocol = stlink +debug_tool = stlink +extra_scripts = pre:!pre_stm32.sh ;lib_ldf_mode = chain+ build_flags = !sh build_flags_stm32.sh lib_deps = @@ -62,7 +64,11 @@ lib_deps = https://github.com/knolleary/pubsubclient.git Adafruit Unified Sensor DHT sensor library - +; https://github.com/anklimov/DMXSerial +; Syslog +; https://github.com/No3x/Syslog.git + https://github.com/arcao/Syslog.git +; UIPEthernet [env:due] platform = atmelsam @@ -88,6 +94,7 @@ lib_deps = SdFat Adafruit Unified Sensor DHT sensor library + https://github.com/arcao/Syslog.git [env:megaatmega2560] @@ -136,6 +143,7 @@ lib_deps = DHT sensor library for ESPx DHT sensor library WifiManager + https://github.com/arcao/Syslog.git [env:megaatmega2560-net] platform = atmelavr @@ -145,21 +153,21 @@ upload_port = net:192.168.88.2:23000 build_flags = !sh build_flags_mega2560-net.sh ;lib_ldf_mode = chain+ lib_deps = - https://github.com/anklimov/Arduino-Temperature-Control-Library.git - https://github.com/anklimov/DS2482_OneWire - https://github.com/anklimov/DmxSimple - https://github.com/anklimov/httpClient - https://github.com/anklimov/aJson - https://github.com/anklimov/CmdArduino - https://github.com/anklimov/ModbusMaster - https://github.com/anklimov/DMXSerial - https://github.com/anklimov/Ethernet - https://github.com/PaulStoffregen/SPI.git - https://github.com/knolleary/pubsubclient.git - https://github.com/anklimov/Artnet.git - FastLED - Adafruit Unified Sensor - DHT sensor library + https://github.com/anklimov/Arduino-Temperature-Control-Library.git + https://github.com/anklimov/DS2482_OneWire + https://github.com/anklimov/DmxSimple + https://github.com/anklimov/httpClient + https://github.com/anklimov/aJson + https://github.com/anklimov/CmdArduino + https://github.com/anklimov/ModbusMaster + https://github.com/anklimov/DMXSerial + https://github.com/anklimov/Ethernet + https://github.com/PaulStoffregen/SPI.git + https://github.com/knolleary/pubsubclient.git + https://github.com/anklimov/Artnet.git + FastLED + Adafruit Unified Sensor + DHT sensor library [env:due-5500] platform = atmelsam diff --git a/pre_stm32.sh b/pre_stm32.sh new file mode 100644 index 0000000..d544c4f --- /dev/null +++ b/pre_stm32.sh @@ -0,0 +1,4 @@ +#! /bin/bash +rm /tmp/piolibdeps -Rf +mkdir /tmp/piolibdeps_stm32 +ln -s /tmp/piolibdeps_stm32 /tmp/piolibdeps