From 40479ba2c85604b59b7477a7016471f7f24a9be9 Mon Sep 17 00:00:00 2001 From: livello Date: Thu, 19 Jul 2018 05:44:27 +0300 Subject: [PATCH] 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