From 4bdc98bd7bd2b37b0a99cce1b4bca070a1b08d18 Mon Sep 17 00:00:00 2001 From: Svante Kaiser Date: Thu, 2 Nov 2023 16:04:15 +0300 Subject: [PATCH] refactoring --- src/config/config.h | 22 ++++ src/{ => domain}/stateMachine.cpp | 48 ++++++--- src/{ => domain}/stateMachine.h | 10 -- src/infra/eth.cpp | 118 +++++++++++++++++++++ src/infra/eth.h | 32 ++++++ src/infra/mqtt.cpp | 51 +++++++-- src/infra/mqtt.h | 13 ++- src/main.cpp | 171 ++---------------------------- src/utils/print.cpp | 58 ---------- src/utils/print.h | 49 ++++++--- 10 files changed, 302 insertions(+), 270 deletions(-) rename src/{ => domain}/stateMachine.cpp (71%) rename src/{ => domain}/stateMachine.h (66%) create mode 100644 src/infra/eth.cpp create mode 100644 src/infra/eth.h diff --git a/src/config/config.h b/src/config/config.h index e69de29..3f5e9d1 100644 --- a/src/config/config.h +++ b/src/config/config.h @@ -0,0 +1,22 @@ +#pragma once + +#define MQTT_HOST IPAddress(192, 168, 1, 173) +#define MQTT_PORT 1883 + +#define SERIAL_NUMBER "4823" + +#define MAC_ADDRESS_MQTT_TOPIC "/digitum/intercom_bridge4823/out/mac" +#define IP_ADDRESS_MQTT_TOPIC "/digitum/intercom_bridge4823/out/ip" +#define SERIAL_NUMBER_MQTT_TOPIC "/digitum/intercom_bridge4823/out/sn" + +#define FLAT_NUMBER_MQTT_TOPIC "/digitum/intercom_bridge4823/out/flat_number" +#define STATE_MQTT_TOPIC "/digitum/intercom_bridge4823/out/state" + +#define LEDS_PIN 32 +#define DRY_CONT_PIN 15 +#define DOOR_SENS_PIN 114 + +#define DATA_PIN 12 +#define DATA_PERIOD 240 // microseconds + +#define PRINT_RAW_SIGNAL_FLAG 0 \ No newline at end of file diff --git a/src/stateMachine.cpp b/src/domain/stateMachine.cpp similarity index 71% rename from src/stateMachine.cpp rename to src/domain/stateMachine.cpp index 406f571..c8d79d8 100644 --- a/src/stateMachine.cpp +++ b/src/domain/stateMachine.cpp @@ -1,4 +1,29 @@ -#include "stateMachine.h" +#include "utils/print.h" +#include "config/config.h" +#include "infra/mqtt.h" +#include "domain/stateMachine.h" + +State currentState = NOT_CONNECTED; +int countZeros = 0; +int countOnes = 0; + +int previousData = 0; +int dataLength = 0; +int signalDuration = 0; + +void resetCounters() { + countZeros = 0; + countOnes = 0; + + previousData = 0; + dataLength = 0; + signalDuration = 0; +} + +void writeState(char* message) { + println(message); + publishToMQTT(STATE_MQTT_TOPIC, message); +} void updateStateMachine(int data) { switch (currentState) { @@ -7,7 +32,7 @@ void updateStateMachine(int data) { // Stay in the NOT_CONNECTED state } else if (data == 1) { currentState = CONNECTED; - println("connected"); + writeState("connected"); } break; @@ -16,13 +41,13 @@ void updateStateMachine(int data) { countZeros++; if (countZeros >= NOT_CONNECTED_THRESHOLD) { currentState = NOT_CONNECTED; - println("not connected"); + writeState("not connected"); resetCounters(); } } else if (data == 1) { if (countZeros >= INITIALIZING_CALL_THRESHOLD) { currentState = RECEIVING_DATA; - println("receiving data"); + writeState("receiving data"); resetCounters(); } } @@ -44,10 +69,9 @@ void updateStateMachine(int data) { if (countZeros >= DATA_RECEIVED_THESHOLD) { println("| data length: ", dataLength); println("| flat: ", dataLength/2); - //sendDataToMQTT(dataLength/2); - + publishToMQTT(FLAT_NUMBER_MQTT_TOPIC, dataLength/2); + currentState = DATA_RECEIVED; - println("data received"); resetCounters(); } } else if (data == 1) { @@ -55,7 +79,7 @@ void updateStateMachine(int data) { countOnes++; if (countOnes >= CONNECTED_THRESHOLD) { currentState = CONNECTED; - println("connected"); + writeState("connected"); resetCounters(); } } @@ -66,14 +90,14 @@ void updateStateMachine(int data) { countZeros++; if (countZeros >= CALL_ENDED_THRESHOLD) { currentState = CALL_ENDED; - println("call ended"); + writeState("call ended"); resetCounters(); } } else if (data == 1) { countOnes++; if (countOnes >= CONNECTED_THRESHOLD) { currentState = CONNECTED; - println("connected"); + writeState("connected"); resetCounters(); } break; @@ -84,14 +108,14 @@ void updateStateMachine(int data) { countZeros++; if (countZeros >= NOT_CONNECTED_THRESHOLD) { currentState = NOT_CONNECTED; - println("not connected"); + writeState("not connected"); resetCounters(); } } else if (data == 1) { countOnes++; if (countOnes >= CONNECTED_THRESHOLD) { currentState = CONNECTED; - println("connected"); + writeState("connected"); resetCounters(); } break; diff --git a/src/stateMachine.h b/src/domain/stateMachine.h similarity index 66% rename from src/stateMachine.h rename to src/domain/stateMachine.h index 88f632e..515af33 100644 --- a/src/stateMachine.h +++ b/src/domain/stateMachine.h @@ -2,7 +2,6 @@ #define STATE_MACHINE_H #include -#include "utils/print.cpp" #define CONNECTED_THRESHOLD 50000 #define NOT_CONNECTED_THRESHOLD 50000 @@ -18,15 +17,6 @@ enum State { CALL_ENDED }; -int data = 0; -State currentState = NOT_CONNECTED; -int countZeros = 0; -int countOnes = 0; - -int previousData = 0; -int dataLength = 0; -int signalDuration = 0; - void resetCounters(); void updateStateMachine(int data); diff --git a/src/infra/eth.cpp b/src/infra/eth.cpp new file mode 100644 index 0000000..0a60fd6 --- /dev/null +++ b/src/infra/eth.cpp @@ -0,0 +1,118 @@ +#include "infra/eth.h" +#include "infra/mqtt.h" + +extern bool eth_connected; +TimerHandle_t ethReconnectTimer; + +void WiFiEvent(WiFiEvent_t event) +{ +#if ESP_IDF_VERSION_MAJOR > 3 + switch (event) { + case ARDUINO_EVENT_ETH_START: + Serial.println("ETH Started"); + // set eth hostname here + ETH.setHostname("esp32-ethernet"); + break; + case ARDUINO_EVENT_ETH_CONNECTED: + Serial.println("ETH Connected"); + break; + case ARDUINO_EVENT_ETH_GOT_IP: + Serial.print("ETH MAC: "); + Serial.print(ETH.macAddress()); + Serial.print(", IPv4: "); + Serial.print(ETH.localIP()); + if (ETH.fullDuplex()) { + Serial.print(", FULL_DUPLEX"); + } + Serial.print(", "); + Serial.print(ETH.linkSpeed()); + Serial.println("Mbps"); + eth_connected = true; + connectToMqtt(); + break; + case ARDUINO_EVENT_ETH_DISCONNECTED: + Serial.println("ETH Disconnected"); + eth_connected = false; + break; + case ARDUINO_EVENT_ETH_STOP: + Serial.println("ETH Stopped"); + eth_connected = false; + break; + default: + break; + } +#elif + switch (event) { + case SYSTEM_EVENT_ETH_START: + Serial.println("ETH Started"); + // set eth hostname here + ETH.setHostname("esp32-ethernet"); + break; + case SYSTEM_EVENT_ETH_CONNECTED: + Serial.println("ETH Connected"); + break; + case SYSTEM_EVENT_ETH_GOT_IP: + Serial.print("ETH MAC: "); + Serial.print(ETH.macAddress()); + Serial.print(", IPv4: "); + Serial.print(ETH.localIP()); + if (ETH.fullDuplex()) { + Serial.print(", FULL_DUPLEX"); + } + Serial.print(", "); + Serial.print(ETH.linkSpeed()); + Serial.println("Mbps"); + eth_connected = true; + break; + case SYSTEM_EVENT_ETH_DISCONNECTED: + Serial.println("ETH Disconnected"); + eth_connected = false; + break; + case SYSTEM_EVENT_ETH_STOP: + Serial.println("ETH Stopped"); + eth_connected = false; + break; + default: + break; + } +#endif +} + +void connectEth() { + pinMode(NRST, OUTPUT); + digitalWrite(NRST, 0); + delay(200); + digitalWrite(NRST, 1); + delay(200); + digitalWrite(NRST, 0); + delay(200); + digitalWrite(NRST, 1); + delay(200); + + ETH.begin(ETH_ADDR, + ETH_POWER_PIN, + ETH_MDC_PIN, + ETH_MDIO_PIN, + ETH_TYPE, + ETH_CLK_MODE); +} + +void testClient(const char * host, uint16_t port) +{ + Serial.print("\nconnecting to "); + Serial.println(host); + + WiFiClient client; + if (!client.connect(host, port)) { + Serial.println("connection failed"); + return; + } + client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host); + while (client.connected() && !client.available()); + while (client.available()) { + Serial.write(client.read()); + } + + Serial.println("closing connection\n"); + client.stop(); +} \ No newline at end of file diff --git a/src/infra/eth.h b/src/infra/eth.h new file mode 100644 index 0000000..e33d419 --- /dev/null +++ b/src/infra/eth.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +/* + * ETH_CLOCK_GPIO0_IN - default: external clock from crystal oscillator + * ETH_CLOCK_GPIO0_OUT - 50MHz clock from internal APLL output on GPIO0 - possibly an inverter is needed for LAN8720 + * ETH_CLOCK_GPIO16_OUT - 50MHz clock from internal APLL output on GPIO16 - possibly an inverter is needed for LAN8720 + * ETH_CLOCK_GPIO17_OUT - 50MHz clock from internal APLL inverted output on GPIO17 - tested with LAN8720 +*/ +#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT + +// Pin# of the enable signal for the external crystal oscillator (-1 to disable for internal APLL source) +#define ETH_POWER_PIN 16 + +// Type of the Ethernet PHY (LAN8720 or TLK110) +#define ETH_TYPE ETH_PHY_LAN8720 + +// I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110) +#define ETH_ADDR 1 + +// Pin# of the I²C clock signal for the Ethernet PHY +#define ETH_MDC_PIN 23 + +// Pin# of the I²C IO signal for the Ethernet PHY +#define ETH_MDIO_PIN 18 + +#define NRST 5 + +void WiFiEvent(WiFiEvent_t event); +void connectEth(); +void testClient(const char * host, uint16_t port); \ No newline at end of file diff --git a/src/infra/mqtt.cpp b/src/infra/mqtt.cpp index a93c777..acd2f65 100644 --- a/src/infra/mqtt.cpp +++ b/src/infra/mqtt.cpp @@ -1,19 +1,50 @@ #include +#include + +#include "config/config.h" #include "infra/mqtt.h" +AsyncMqttClient mqttClient; +TimerHandle_t mqttReconnectTimer; + void connectToMqtt() { Serial.println("Connecting to MQTT..."); mqttClient.connect(); } +void publishToMQTT(const char* topic, const char* message) { + mqttClient.publish(topic, 2, true, message); +} + +void publishToMQTT(const char* topic, int message) { + char num_char[10]; + sprintf(num_char, "%d", message); + mqttClient.publish(topic, 2, true, num_char); +} + +void publishToMQTT(const char* topic, float message) { + char num_char[10]; + dtostrf(message, 1, 2, num_char); // Convert float to string + mqttClient.publish(topic, 2, true, num_char); +} + +void publishToMQTT(const char* topic, bool message) { + const char* bool_str = message ? "true" : "false"; + mqttClient.publish(topic, 2, true, bool_str); +} + void onMqttConnect(bool sessionPresent) { Serial.println("Connected to MQTT."); Serial.print("Session present: "); Serial.println(sessionPresent); - uint16_t packetIdSub = mqttClient.subscribe("esp32/led", 0); - Serial.print("Subscribing at QoS 0, packetId: "); - Serial.println(packetIdSub); + publishToMQTT(MAC_ADDRESS_MQTT_TOPIC, ETH.macAddress().c_str()); + publishToMQTT(IP_ADDRESS_MQTT_TOPIC, ETH.localIP().toString().c_str()); + publishToMQTT(SERIAL_NUMBER_MQTT_TOPIC, SERIAL_NUMBER); + + //uint16_t packetIdSub = mqttClient.subscribe("esp32/led", 0); + //Serial.print("Subscribing at QoS 0, packetId: "); + //Serial.println(packetIdSub); } void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { @@ -43,8 +74,14 @@ void onMqttPublish(uint16_t packetId) { Serial.println(packetId); } -void sendDataToMQTT(int flatNumber) { - char num_char[3]; - sprintf(num_char, "%d", flatNumber); - mqttClient.publish("/digitum/out/flat_number", 2, true, num_char); +void initMQTT() { + mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + //mqttClient.onMessage(onMqttMessage); + //mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(MQTT_HOST, MQTT_PORT); } \ No newline at end of file diff --git a/src/infra/mqtt.h b/src/infra/mqtt.h index 6401e39..8cb84eb 100644 --- a/src/infra/mqtt.h +++ b/src/infra/mqtt.h @@ -1,12 +1,8 @@ -#ifndef INFRA_MQTT_H -#define INFRA_MQTT_H +#pragma once #include #include -AsyncMqttClient mqttClient; -TimerHandle_t mqttReconnectTimer; - void connectToMqtt(); void onMqttConnect(bool sessionPresent); void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); @@ -14,5 +10,8 @@ void onMqttSubscribe(uint16_t packetId, uint8_t qos); void onMqttUnsubscribe(uint16_t packetId); void onMqttPublish(uint16_t packetId); void sendDataToMQTT(int flatNumber); - -#endif // INFRA_MQTT_H \ No newline at end of file +void publishToMQTT(const char* topic, const char* message); +void publishToMQTT(const char* topic, int message); +void publishToMQTT(const char* topic, float message); +void publishToMQTT(const char* topic, bool message); +void initMQTT(); \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index f34224e..7173026 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,166 +6,18 @@ #include #include -#include "infra/mqtt.h" #include "utils/print.h" -#include "stateMachine.h" - -#define LEDS_PIN 32 -#define DRY_CONT_PIN 15 -#define DOOR_SENS_PIN 114 - -#define DATA_PIN 12 -#define DATA_PERIOD 240 // microseconds - -#define PRINT_RAW_SIGNAL_FLAG 0 - -/* - * ETH_CLOCK_GPIO0_IN - default: external clock from crystal oscillator - * ETH_CLOCK_GPIO0_OUT - 50MHz clock from internal APLL output on GPIO0 - possibly an inverter is needed for LAN8720 - * ETH_CLOCK_GPIO16_OUT - 50MHz clock from internal APLL output on GPIO16 - possibly an inverter is needed for LAN8720 - * ETH_CLOCK_GPIO17_OUT - 50MHz clock from internal APLL inverted output on GPIO17 - tested with LAN8720 -*/ -#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT - -// Pin# of the enable signal for the external crystal oscillator (-1 to disable for internal APLL source) -#define ETH_POWER_PIN 16 - -// Type of the Ethernet PHY (LAN8720 or TLK110) -#define ETH_TYPE ETH_PHY_LAN8720 - -// I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110) -#define ETH_ADDR 1 - -// Pin# of the I²C clock signal for the Ethernet PHY -#define ETH_MDC_PIN 23 - -// Pin# of the I²C IO signal for the Ethernet PHY -#define ETH_MDIO_PIN 18 - -#define NRST 5 - -#define MQTT_HOST IPAddress(192, 168, 1, 173) -#define MQTT_PORT 1883 +#include "config/config.h" +#include "infra/eth.h" +#include "infra/mqtt.h" +#include "domain/stateMachine.h" uint32_t lastMillis; uint64_t lastMicros; -static bool eth_connected = false; +bool eth_connected = false; -TimerHandle_t ethReconnectTimer; - -void WiFiEvent(WiFiEvent_t event) -{ -#if ESP_IDF_VERSION_MAJOR > 3 - switch (event) { - case ARDUINO_EVENT_ETH_START: - Serial.println("ETH Started"); - // set eth hostname here - ETH.setHostname("esp32-ethernet"); - break; - case ARDUINO_EVENT_ETH_CONNECTED: - Serial.println("ETH Connected"); - break; - case ARDUINO_EVENT_ETH_GOT_IP: - Serial.print("ETH MAC: "); - Serial.print(ETH.macAddress()); - Serial.print(", IPv4: "); - Serial.print(ETH.localIP()); - if (ETH.fullDuplex()) { - Serial.print(", FULL_DUPLEX"); - } - Serial.print(", "); - Serial.print(ETH.linkSpeed()); - Serial.println("Mbps"); - eth_connected = true; - connectToMqtt(); - break; - case ARDUINO_EVENT_ETH_DISCONNECTED: - Serial.println("ETH Disconnected"); - eth_connected = false; - break; - case ARDUINO_EVENT_ETH_STOP: - Serial.println("ETH Stopped"); - eth_connected = false; - break; - default: - break; - } -#elif - switch (event) { - case SYSTEM_EVENT_ETH_START: - Serial.println("ETH Started"); - // set eth hostname here - ETH.setHostname("esp32-ethernet"); - break; - case SYSTEM_EVENT_ETH_CONNECTED: - Serial.println("ETH Connected"); - break; - case SYSTEM_EVENT_ETH_GOT_IP: - Serial.print("ETH MAC: "); - Serial.print(ETH.macAddress()); - Serial.print(", IPv4: "); - Serial.print(ETH.localIP()); - if (ETH.fullDuplex()) { - Serial.print(", FULL_DUPLEX"); - } - Serial.print(", "); - Serial.print(ETH.linkSpeed()); - Serial.println("Mbps"); - eth_connected = true; - break; - case SYSTEM_EVENT_ETH_DISCONNECTED: - Serial.println("ETH Disconnected"); - eth_connected = false; - break; - case SYSTEM_EVENT_ETH_STOP: - Serial.println("ETH Stopped"); - eth_connected = false; - break; - default: - break; - } -#endif -} - -void connectEth() { - pinMode(NRST, OUTPUT); - digitalWrite(NRST, 0); - delay(200); - digitalWrite(NRST, 1); - delay(200); - digitalWrite(NRST, 0); - delay(200); - digitalWrite(NRST, 1); - delay(200); - - ETH.begin(ETH_ADDR, - ETH_POWER_PIN, - ETH_MDC_PIN, - ETH_MDIO_PIN, - ETH_TYPE, - ETH_CLK_MODE); -} - -void testClient(const char * host, uint16_t port) -{ - Serial.print("\nconnecting to "); - Serial.println(host); - - WiFiClient client; - if (!client.connect(host, port)) { - Serial.println("connection failed"); - return; - } - client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host); - while (client.connected() && !client.available()); - while (client.available()) { - Serial.write(client.read()); - } - - Serial.println("closing connection\n"); - client.stop(); -} +int data = 0; void setup() { Serial.begin(115200); @@ -173,16 +25,7 @@ void setup() { WiFi.onEvent(WiFiEvent); connectEth(); - - mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); - - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.onSubscribe(onMqttSubscribe); - mqttClient.onUnsubscribe(onMqttUnsubscribe); - //mqttClient.onMessage(onMqttMessage); - mqttClient.onPublish(onMqttPublish); - mqttClient.setServer(MQTT_HOST, MQTT_PORT); + initMQTT(); pinMode(DATA_PIN, INPUT); diff --git a/src/utils/print.cpp b/src/utils/print.cpp index 70c3ffc..e325563 100644 --- a/src/utils/print.cpp +++ b/src/utils/print.cpp @@ -1,77 +1,19 @@ #include -#include "utils/print.h" void print() { // Empty function to terminate recursion } -// Overloaded function to print a single value -template -void print(T value) { - Serial.print(value); -} - -// Recursive function to print multiple values -template -void print(T value, Args... args) { - Serial.print(value); - print(args...); // Recursively call print for the remaining arguments -} - // Function to print a newline void println() { Serial.println(); } -// Overloaded function to print a single value and a newline -template -void println(T value) { - Serial.println(value); -} - -// Recursive function to print multiple values and a newline -template -void println(T value, Args... args) { - Serial.print(value); - println(args...); // Recursively call println for the remaining arguments -} - -// Convenience functions for easy usage -template -void print(Args... args) { - print(args...); -} - -template -void println(Args... args) { - println(args...); -} - String fstring(const char* format) { String result = format; return result; } -template -String fstring(const char* format, Args... args) { - String result = ""; - while (*format) { - if (*format == '{' && *(format + 1) == '}' && sizeof...(args) > 0) { - result += String(args...); - format += 2; // Skip the "{}" in the format string - } else { - result += *format; - format++; - } - } - return result; -} - void printf(const char* format) { Serial.print(fstring(format)); -} - -template -void printf(const char* format, Args... args) { - Serial.print(fstring(format, args...)); } \ No newline at end of file diff --git a/src/utils/print.h b/src/utils/print.h index a207ca8..15c6cf2 100644 --- a/src/utils/print.h +++ b/src/utils/print.h @@ -1,5 +1,4 @@ -#ifndef UTILS_PRINT_H -#define UTILS_PRINT_H +#pragma once #include @@ -7,38 +6,64 @@ void print(); // Overloaded function to print a single value template -void print(T value); +void print(T value) { + Serial.print(value); +} // Recursive function to print multiple values template -void print(T value, Args... args); +void print(T value, Args... args) { + Serial.print(value); + print(args...); // Recursively call print for the remaining arguments +} // Function to print a newline void println(); // Overloaded function to print a single value and a newline template -void println(T value); +void println(T value) { + Serial.println(value); +} // Recursive function to print multiple values and a newline template -void println(T value, Args... args); +void println(T value, Args... args) { + Serial.print(value); + println(args...); // Recursively call println for the remaining arguments +} // Convenience functions for easy usage template -void print(Args... args); +void print(Args... args) { + print(args...); +} template -void println(Args... args); +void println(Args... args) { + println(args...); +} String fstring(const char* format); template -String fstring(const char* format, Args... args); +String fstring(const char* format, Args... args) { + String result = ""; + while (*format) { + if (*format == '{' && *(format + 1) == '}' && sizeof...(args) > 0) { + result += String(args...); + format += 2; // Skip the "{}" in the format string + } else { + result += *format; + format++; + } + } + return result; +} void printf(const char* format); template -void printf(const char* format, Args... args); - -#endif // UTILS_PRINT_H \ No newline at end of file +void printf(const char* format, Args... args) { + Serial.print(fstring(format, args...)); +} \ No newline at end of file