Compare commits
10 Commits
83d589a3ec
...
feature/ad
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c018ebba5 | |||
| 14041120cd | |||
| fdff1d369c | |||
| 8a76e869cb | |||
| d630a7ea5f | |||
| b2ee44dd60 | |||
| c18836f0cf | |||
| 214f4647a0 | |||
| eeb317c108 | |||
| 936d1dba20 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -3,3 +3,4 @@
|
||||
.vscode/c_cpp_properties.json
|
||||
.vscode/launch.json
|
||||
.vscode/ipch
|
||||
.venv/
|
||||
125
helper/remote-serial.py
Normal file
125
helper/remote-serial.py
Normal file
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Telnet-only tool to toggle DTR/RTS via ser2net admin console.
|
||||
|
||||
New sequences (physical levels):
|
||||
- restart: RTS HI -> DTR LO -> DTR HI
|
||||
- download: RTS LO -> DTR LO -> DTR HI -> RTS HI
|
||||
|
||||
Timing parameters tunable via args (ms). Use admin host/port and connection name (con).
|
||||
Example:
|
||||
python3 helper/remote-serial.py --host 192.168.1.100 --admin-port 7373 --con con1 --action restart -v
|
||||
"""
|
||||
import argparse
|
||||
import socket
|
||||
import errno
|
||||
import time
|
||||
import sys
|
||||
|
||||
def send_admin_cmd(host, port, cmd, timeout=1.0, verbose=False):
|
||||
if verbose:
|
||||
print(f"> {cmd}")
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=timeout) as s:
|
||||
s.settimeout(timeout)
|
||||
try:
|
||||
s.sendall(cmd.encode('ascii') + b"\n")
|
||||
except Exception as e:
|
||||
print(f"ERROR sending command: {e}", file=sys.stderr)
|
||||
return None
|
||||
# small pause to let server respond
|
||||
time.sleep(0.05)
|
||||
chunks = []
|
||||
while True:
|
||||
try:
|
||||
data = s.recv(4096)
|
||||
if not data:
|
||||
break
|
||||
chunks.append(data)
|
||||
# short sleep to allow more data to arrive
|
||||
time.sleep(0.01)
|
||||
except socket.timeout:
|
||||
break
|
||||
except OSError as e:
|
||||
if getattr(e, 'errno', None) == errno.EWOULDBLOCK:
|
||||
break
|
||||
break
|
||||
resp = b"".join(chunks)
|
||||
if resp:
|
||||
try:
|
||||
txt = resp.decode(errors="ignore")
|
||||
except Exception:
|
||||
txt = str(resp)
|
||||
if verbose:
|
||||
print(txt.strip())
|
||||
return txt
|
||||
return ""
|
||||
except Exception as e:
|
||||
print(f"ERROR: cannot connect to {host}:{port} -> {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
def set_port_control(host, admin_port, con, line, hi_or_lo, timeout, verbose):
|
||||
# hi_or_lo must be 'HI' or 'LO'
|
||||
cmd = f"setportcontrol {con} {line}{hi_or_lo}"
|
||||
return send_admin_cmd(host, admin_port, cmd, timeout=timeout, verbose=verbose)
|
||||
|
||||
def run_sequence(host, admin_port, con, seq, timeout, verbose):
|
||||
# seq: list of (line, state, sleep_seconds)
|
||||
for line, state, sleep_s in seq:
|
||||
if verbose:
|
||||
print(f"-> {line}{state} (wait {sleep_s:.3f}s)")
|
||||
res = set_port_control(host, admin_port, con, line, state, timeout, verbose)
|
||||
# continue even if response is None; user sees errors in stderr
|
||||
if sleep_s and sleep_s > 0:
|
||||
time.sleep(sleep_s)
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="ser2net admin: restart / download sequences (explicit HI/LO)")
|
||||
p.add_argument("--host", required=True, help="ser2net admin host/ip")
|
||||
p.add_argument("--admin-port", type=int, required=True, help="ser2net admin port")
|
||||
p.add_argument("--con", required=True, help="ser2net connection name (e.g. con1)")
|
||||
p.add_argument("--action", choices=["restart", "download", "bootloader"], default="restart",
|
||||
help="restart or download (bootloader alias)")
|
||||
p.add_argument("--pulse-ms", type=float, default=100.0, help="DTR pulse length in milliseconds")
|
||||
p.add_argument("--step-delay-ms", type=float, default=20.0, help="short delay between steps in milliseconds")
|
||||
p.add_argument("--tail-delay-ms", type=float, default=50.0, help="extra delay after sequence in milliseconds")
|
||||
p.add_argument("--timeout", type=float, default=1.0, help="telnet connect/read timeout seconds")
|
||||
p.add_argument("-v", "--verbose", action="store_true")
|
||||
args = p.parse_args()
|
||||
|
||||
pulse_s = max(0.001, args.pulse_ms / 1000.0)
|
||||
step_delay_s = max(0.0, args.step_delay_ms / 1000.0)
|
||||
tail_delay_s = max(0.0, args.tail_delay_ms / 1000.0)
|
||||
|
||||
if args.verbose:
|
||||
print(f"Admin {args.host}:{args.admin_port} con={args.con} action={args.action}")
|
||||
|
||||
# sequences use explicit physical HI/LO as requested
|
||||
if args.action == "restart":
|
||||
seq = [
|
||||
("RTS", "HI", step_delay_s), # RTS HI
|
||||
("DTR", "LO", pulse_s), # DTR LO (pulse start)
|
||||
("DTR", "HI", tail_delay_s), # DTR HI (pulse end), then tail delay
|
||||
]
|
||||
else: # download / bootloader
|
||||
# Ensure known starting state (RESET released), then enter download:
|
||||
# 1) ensure DTR=HI (reset released)
|
||||
# 2) RTS=LO (IO0 low)
|
||||
# 3) DTR=LO -> wait pulse_ms
|
||||
# 4) DTR=HI -> small delay
|
||||
# 5) RTS=HI -> release IO0 (enter bootloader)
|
||||
seq = [
|
||||
("DTR", "HI", step_delay_s), # ensure reset released
|
||||
("RTS", "LO", step_delay_s), # RTS LO (IO0 low)
|
||||
("DTR", "LO", pulse_s), # DTR LO (reset asserted)
|
||||
("DTR", "HI", step_delay_s), # DTR HI (reset released)
|
||||
("RTS", "HI", tail_delay_s), # RTS HI (release IO0)
|
||||
]
|
||||
|
||||
run_sequence(args.host, args.admin_port, args.con, seq, args.timeout, args.verbose)
|
||||
|
||||
if args.verbose:
|
||||
print("Sequence finished.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -8,8 +8,8 @@ inline constexpr uint8_t ledPinB = 18;
|
||||
inline constexpr uint8_t ledPinCW = 19;
|
||||
inline constexpr uint8_t ledPinWW = 21;
|
||||
|
||||
inline constexpr std::string_view hostName = "smart-rgb-dev";
|
||||
inline constexpr std::string_view friendlyName = "Smart RGB Dev";
|
||||
inline constexpr std::string_view hostName = "smart-rgb";
|
||||
inline constexpr std::string_view friendlyName = "Smart RGB";
|
||||
inline constexpr uint32_t maxNumberOfStates = 10;
|
||||
|
||||
inline constexpr std::string_view mqttBroker = "10.238.75.81";
|
||||
30
include/debugutil.hpp
Normal file
30
include/debugutil.hpp
Normal file
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
#ifndef ENABLE_SERIAL_DEBUG
|
||||
#define ENABLE_SERIAL_DEBUG 0
|
||||
#endif
|
||||
|
||||
struct Debug {
|
||||
static constexpr bool enabled = static_cast<bool>(ENABLE_SERIAL_DEBUG);
|
||||
static inline void begin(unsigned long baud) {
|
||||
if constexpr (enabled) Serial.begin(baud);
|
||||
}
|
||||
template<typename... Args>
|
||||
static inline void print(Args&&... args) {
|
||||
if constexpr (enabled) { (Serial.print(std::forward<Args>(args)), ...); }
|
||||
}
|
||||
template<typename... Args>
|
||||
static inline void println(Args&&... args) {
|
||||
if constexpr (enabled) {
|
||||
(Serial.print(std::forward<Args>(args)), ...);
|
||||
Serial.println();
|
||||
}
|
||||
}
|
||||
template<typename... Args>
|
||||
static inline void printf(const char *fmt, Args&&... args) {
|
||||
if constexpr (enabled) {
|
||||
Serial.printf(fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
#include <PubSubClient.h>
|
||||
#include <WiFiClient.h>
|
||||
#include "debugutil.hpp"
|
||||
#include "mqtt.h"
|
||||
|
||||
constexpr uint16_t BUFFER_SIZE = 2048;
|
||||
@@ -26,12 +27,27 @@ void Mqtt::subscribe(const std::string& topic, MqttCallback callback) {
|
||||
if (mqttClient.connected()) {
|
||||
if (mqttClient.subscribe(topic.c_str())) {
|
||||
callbacks[topic] = callback;
|
||||
Serial.printf("Subscribed to topic: %s\n", topic.c_str());
|
||||
Debug::printf("Subscribed to topic: %s\n", topic.c_str());
|
||||
} else {
|
||||
Serial.printf("Failed to subscribe to topic: %s\n", topic.c_str());
|
||||
Debug::printf("Failed to subscribe to topic: %s\n", topic.c_str());
|
||||
}
|
||||
} else {
|
||||
Serial.println("MQTT client is not connected. Cannot subscribe.");
|
||||
Debug::println("MQTT client is not connected. Cannot subscribe.");
|
||||
}
|
||||
}
|
||||
|
||||
void Mqtt::unsubscribe(const std::string& topic) {
|
||||
if (mqttClient.connected()) {
|
||||
if (mqttClient.unsubscribe(topic.c_str())) {
|
||||
Debug::printf("Unsubscribed from topic: %s\n", topic.c_str());
|
||||
} else {
|
||||
Debug::printf("Failed to unsubscribe from topic: %s\n", topic.c_str());
|
||||
}
|
||||
} else {
|
||||
Debug::println("MQTT client is not connected. Unsubscribe skipped.");
|
||||
}
|
||||
if (callbacks.find(topic) != callbacks.end()) {
|
||||
callbacks.erase(topic);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,10 +55,10 @@ void Mqtt::publish(const std::string& topic, const std::string& payload, bool re
|
||||
if (mqttClient.connected()) {
|
||||
if (mqttClient.publish(topic.c_str(), payload.c_str(), retain)) {
|
||||
} else {
|
||||
Serial.printf("Failed to publish to topic: %s\n", topic.c_str(), payload.c_str());
|
||||
Debug::printf("Failed to publish to topic: %s\n", topic.c_str(), payload.c_str());
|
||||
}
|
||||
} else {
|
||||
Serial.println("MQTT client is not connected. Cannot publish.");
|
||||
Debug::println("MQTT client is not connected. Cannot publish.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,21 +66,21 @@ void Mqtt::poll() {
|
||||
if (mqttClient.connected()) {
|
||||
mqttClient.loop(); // Process incoming messages
|
||||
} else {
|
||||
Serial.println("MQTT client is not connected. Polling skipped.");
|
||||
Debug::println("MQTT client is not connected. Polling skipped.");
|
||||
}
|
||||
}
|
||||
|
||||
void Mqtt::checkConnection() {
|
||||
if (!mqttClient.connected()) {
|
||||
Serial.println("MQTT client is not connected. Attempting to reconnect...");
|
||||
Debug::println("MQTT client is not connected. Attempting to reconnect...");
|
||||
if (mqttClient.connect(Mqtt::clientId.c_str(), Mqtt::username.c_str(), Mqtt::password.c_str())) {
|
||||
Serial.println("Reconnected to MQTT broker successfully.");
|
||||
Debug::println("Reconnected to MQTT broker successfully.");
|
||||
for (const auto& callback : Mqtt::callbacks) {
|
||||
mqttClient.subscribe(callback.first.c_str());
|
||||
}
|
||||
Mqtt::isConnected = true;
|
||||
} else {
|
||||
Serial.printf("Failed to reconnect to MQTT broker, rc=%d\n", mqttClient.state());
|
||||
Debug::printf("Failed to reconnect to MQTT broker, rc=%d\n", mqttClient.state());
|
||||
Mqtt::isConnected = false;
|
||||
}
|
||||
}
|
||||
@@ -82,10 +98,10 @@ void Mqtt::connect(std::string brokerIp, uint16_t brokerPort, std::string client
|
||||
mqttClient.setBufferSize(BUFFER_SIZE);
|
||||
|
||||
if (mqttClient.connect(Mqtt::clientId.c_str(), Mqtt::username.c_str(), Mqtt::password.c_str())) {
|
||||
Serial.println("Connected to MQTT broker");
|
||||
Debug::println("Connected to MQTT broker");
|
||||
Mqtt::initialized = true;
|
||||
Mqtt::isConnected = true;
|
||||
} else {
|
||||
Serial.printf("Failed to connect to MQTT broker, rc=%d\n", mqttClient.state());
|
||||
Debug::printf("Failed to connect to MQTT broker, rc=%d\n", mqttClient.state());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ public:
|
||||
static void checkConnection();
|
||||
static void publish(const std::string& topic, const std::string& payload, bool retain = false);
|
||||
static void subscribe(const std::string& topic, MqttCallback callback);
|
||||
static void unsubscribe(const std::string& topic);
|
||||
static void mqttCb(char* topic, uint8_t* payload, unsigned int length);
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <ArduinoJson.h>
|
||||
#include "debugutil.hpp"
|
||||
#include "light.h"
|
||||
#include "mqtt.h"
|
||||
|
||||
@@ -14,24 +15,22 @@ const struct {
|
||||
} Availability;
|
||||
|
||||
|
||||
Light::Light(Pin* pinR, Pin* pinG, Pin* pinB, Mqtt* mqttClient, std::string uniqueId)
|
||||
: pinR(pinR), pinG(pinG), pinB(pinB), pinCW(nullptr), pinWW(nullptr), mqttClient(mqttClient) {
|
||||
lightInfo.uniqueId = uniqueId;
|
||||
Light::Light(Pin* pinR, Pin* pinG, Pin* pinB, std::string uniqueId)
|
||||
: pinR(pinR), pinG(pinG), pinB(pinB), pinCW(nullptr), pinWW(nullptr), lightInfo(uniqueId) {
|
||||
|
||||
lightType = LightType::rgb;
|
||||
uint8_t bits = pinR->getLedResolutionBits();
|
||||
maxPwm = (bits >= 1 && bits <= 31) ? ((1u << bits) - 1u) : 255u;
|
||||
publishInitialState();
|
||||
subscribeToMqttTopics();
|
||||
notifyOnline();
|
||||
}
|
||||
|
||||
Light::Light(Pin* pinR, Pin* pinG, Pin* pinB, Pin* pinCW, Pin* pinWW, Mqtt* mqttClient, std::string uniqueId)
|
||||
: pinR(pinR), pinG(pinG), pinB(pinB), pinCW(pinCW), pinWW(pinWW), mqttClient(mqttClient) {
|
||||
lightInfo.uniqueId = uniqueId;
|
||||
Light::Light(Pin* pinR, Pin* pinG, Pin* pinB, Pin* pinCW, Pin* pinWW, std::string uniqueId)
|
||||
: pinR(pinR), pinG(pinG), pinB(pinB), pinCW(pinCW), pinWW(pinWW), lightInfo(uniqueId) {
|
||||
lightType = LightType::rgbww;
|
||||
uint8_t bits = pinR->getLedResolutionBits();
|
||||
maxPwm = (bits >= 1 && bits <= 31) ? ((1u << bits) - 1u) : 255u;
|
||||
publishInitialState();
|
||||
subscribeToMqttTopics();
|
||||
notifyOnline();
|
||||
}
|
||||
|
||||
void Light::publishInitialState() {
|
||||
@@ -41,7 +40,7 @@ void Light::publishInitialState() {
|
||||
deviceInfo["name"] = this->deviceInfo.name;
|
||||
deviceInfo["model"] = this->deviceInfo.model;
|
||||
JsonArray identifiers = deviceInfo["identifiers"].to<JsonArray>();
|
||||
identifiers.add(this->deviceInfo.identifier + this->lightInfo.uniqueId);
|
||||
identifiers.add(this->lightInfo.uniqueId);
|
||||
deviceInfo["sw_version"] = this->deviceInfo.swVersion;
|
||||
deviceInfo["manufacturer"] = this->deviceInfo.manufacturer;
|
||||
|
||||
@@ -76,7 +75,7 @@ void Light::publishInitialState() {
|
||||
|
||||
std::string configJson;
|
||||
serializeJson(configInfo, configJson);
|
||||
mqttClient->publish(lightInfo.discoveryTopic, configJson);
|
||||
Mqtt::publish(lightInfo.discoveryTopic, configJson);
|
||||
|
||||
std::string stateJson;
|
||||
JsonDocument stateInfo;
|
||||
@@ -95,8 +94,8 @@ void Light::publishInitialState() {
|
||||
JsonDocument availabilityInfoDoc;
|
||||
availabilityInfoDoc["availability"] = Availability.available;
|
||||
serializeJson(availabilityInfoDoc, availabilityJson);
|
||||
mqttClient->publish(lightInfo.stateTopic, stateJson);
|
||||
mqttClient->publish(lightInfo.availabilityTopic, availabilityJson);
|
||||
Mqtt::publish(lightInfo.stateTopic, stateJson);
|
||||
Mqtt::publish(lightInfo.availabilityTopic, availabilityJson);
|
||||
}
|
||||
|
||||
void Light::operatePin() {
|
||||
@@ -158,19 +157,29 @@ void Light::operatePin() {
|
||||
if (pinWW) pinWW->setLedLevel(wwSetpoint);
|
||||
}
|
||||
|
||||
void Light::subscribeToMqttTopics() {
|
||||
mqttClient->subscribe(lightInfo.commandTopic, [this](uint8_t* payload, int length) {
|
||||
void Light::notifyOnline() {
|
||||
Mqtt::subscribe(lightInfo.commandTopic, [this](uint8_t* payload, int length) {
|
||||
std::string command(reinterpret_cast<char*>(payload), length);
|
||||
handleCommand(command);
|
||||
});
|
||||
publishInitialState();
|
||||
}
|
||||
|
||||
void Light::notifyOffline() {
|
||||
Mqtt::unsubscribe(lightInfo.commandTopic);
|
||||
JsonDocument availabilityDoc;
|
||||
availabilityDoc["availability"] = Availability.notAvailable;
|
||||
std::string availabilityJson;
|
||||
serializeJson(availabilityDoc, availabilityJson);
|
||||
Mqtt::publish(lightInfo.availabilityTopic, availabilityJson);
|
||||
}
|
||||
|
||||
void Light::handleCommand(const std::string& command) {
|
||||
Serial.println("Received command: " + String(command.c_str()));
|
||||
Debug::println("Received command: " + String(command.c_str()));
|
||||
JsonDocument commandJson;
|
||||
deserializeJson(commandJson, command);
|
||||
if (commandJson.isNull()) {
|
||||
Serial.println("Invalid command JSON");
|
||||
Debug::println("Invalid command JSON");
|
||||
return;
|
||||
}
|
||||
if (commandJson["state"].is<String>()) {
|
||||
@@ -240,12 +249,12 @@ void Light::publishCurrentState() {
|
||||
|
||||
std::string stateJson;
|
||||
serializeJson(stateInfo, stateJson);
|
||||
Serial.println("Publishing current state: " + String(stateJson.c_str()));
|
||||
mqttClient->publish(lightInfo.stateTopic, stateJson);
|
||||
Debug::println("Publishing current state: " + String(stateJson.c_str()));
|
||||
Mqtt::publish(lightInfo.stateTopic, stateJson);
|
||||
std::string attributeJson;
|
||||
serializeJson(attributeInfo, attributeJson);
|
||||
Serial.println("Publishing current attributes: " + String(attributeJson.c_str()));
|
||||
mqttClient->publish(lightInfo.jsonAttributesTopic, attributeJson);
|
||||
Debug::println("Publishing current attributes: " + String(attributeJson.c_str()));
|
||||
Mqtt::publish(lightInfo.jsonAttributesTopic, attributeJson);
|
||||
}
|
||||
|
||||
uint32_t Light::correctGamma(uint32_t originalPwm) {
|
||||
|
||||
@@ -2,41 +2,34 @@
|
||||
|
||||
#include <cstdint>
|
||||
#include "pin.h"
|
||||
#include "mqtt.h"
|
||||
|
||||
struct LightInfo {
|
||||
LightInfo() = default;
|
||||
LightInfo(const std::string& id) {
|
||||
uniqueId = id;
|
||||
updateTopics();
|
||||
}
|
||||
void setUniqueId(const std::string& id) {
|
||||
uniqueId = id;
|
||||
updateTopics();
|
||||
}
|
||||
void updateTopics() {
|
||||
discoveryTopic = discoveryTopicBase + uniqueId + "/config";
|
||||
availabilityTopic = topicBase + uniqueId + "/availability";
|
||||
stateTopic = topicBase + uniqueId + "/state";
|
||||
jsonAttributesTopic = topicBase + uniqueId + "/attributes";
|
||||
commandTopic = topicBase + uniqueId + "/state/set";
|
||||
}
|
||||
std::string uniqueId;
|
||||
const std::string name = "Smart RGB Light";
|
||||
const std::string discoveryTopic = "homeassistant/light/smart_rgb_light/light/config";
|
||||
const std::string baseTopic = "studiotj/smart-rgb/light";
|
||||
const std::string availabilityTopic = "studiotj/smart-rgb/light/status";
|
||||
const std::string stateTopic = "studiotj/smart-rgb/light/state";
|
||||
const std::string jsonAttributesTopic = "studiotj/smart-rgb/light/attributes";
|
||||
const std::string stateValueTemplate = "{{ value_json.state }}";
|
||||
const std::string commandTopic = "studiotj/smart-rgb/light/state/set";
|
||||
const std::string brightnessCommandTopic = "studiotj/smart-rgb/light/brightness/set";
|
||||
const std::string brightnessValueTemplate = "{{ value_json.brightness }}";
|
||||
const std::string colorTempCommandTopic = "studiotj/smart-rgb/light/color_temp/set";
|
||||
const std::string colorTempKelvinTopic = "studiotj/smart-rgb/light/color_temp_kelvin/set";
|
||||
const std::string colorTempStateTopic = "studiotj/smart-rgb/light/color_temp/state";
|
||||
const std::string colorTempValueTemplate = "{{ value_json.color_temp }}";
|
||||
const std::string hsCommandTopic = "studiotj/smart-rgb/light/hs/set";
|
||||
const std::string hsCommandTemplate = "{{ value_json.hs_cmd }}";
|
||||
const std::string hsStateTopic = "studiotj/smart-rgb/light/hs/state";
|
||||
const std::string hsValueTemplate = " {{ value_json.hs_value }}";
|
||||
const std::string rgbCommandTopic = "studiotj/smart-rgb/light/rgb/set";
|
||||
const std::string rgbCommandTemplate = "{{ {'rgb': [red, green, blue]} | to_json }}";
|
||||
const std::string rgbStateTopic = "studiotj/smart-rgb/light/rgb/state";
|
||||
const std::string rgbValueTemplate = "{{ value_json.rgb | join(',') }}";
|
||||
const std::string rgbwCommandTopic = "studiotj/smart-rgb/light/rgbw/set";
|
||||
const std::string rgbwCommandTemplate = "{{ value_json.rgbw_cmd }}";
|
||||
const std::string rgbwStateTopic = "studiotj/smart-rgb/light/rgbw/state";
|
||||
const std::string rgbwValueTemplate = "{{ value_json.rgbw_value }}";
|
||||
const std::string rgbwwCommandTopic = "studiotj/smart-rgb/light/rgbww/set";
|
||||
const std::string rgbwwCommandTemplate = "{{ value_json.rgbww_cmd }}";
|
||||
const std::string rgbwwStateTopic = "studiotj/smart-rgb/light/rgbww/state";
|
||||
const std::string rgbwwValueTemplate = "{{ value_json.rgbww_value }}";
|
||||
const std::string supportedColorModesTopic = "studiotj/smart-rgb/light/supported_color_modes";
|
||||
const std::string discoveryTopicBase = "homeassistant/light/";
|
||||
std::string discoveryTopic = discoveryTopicBase + uniqueId + "/config";
|
||||
const std::string topicBase = "studiotj/";
|
||||
std::string availabilityTopic = topicBase + uniqueId + "/availability";
|
||||
std::string stateTopic = topicBase + uniqueId + "/state";
|
||||
std::string jsonAttributesTopic = topicBase + uniqueId + "/attributes";
|
||||
std::string stateValueTemplate = "{{ value_json.state }}";
|
||||
std::string commandTopic = topicBase + uniqueId + "/state/set";
|
||||
const std::string supportedColorModesValue = "['rgb', 'brightness']";
|
||||
const std::string availabilityTemplate = "{{ value_json.availability }}";
|
||||
};
|
||||
@@ -65,10 +58,11 @@ enum ActiveMode {
|
||||
|
||||
class Light {
|
||||
public:
|
||||
Light(Pin* pinR, Pin* pinG, Pin* pinB, Mqtt* mqttClient, std::string uniqueId);
|
||||
Light(Pin* pinR, Pin* pinG, Pin* pinB, Pin* pinCW, Mqtt* mqttClient, std::string uniqueId);
|
||||
Light(Pin* pinR, Pin* pinG, Pin* pinB, Pin* pinCW, Pin* pinWW, Mqtt* mqttClient, std::string uniqueId);
|
||||
void subscribeToMqttTopics();
|
||||
Light(Pin* pinR, Pin* pinG, Pin* pinB, std::string uniqueId);
|
||||
Light(Pin* pinR, Pin* pinG, Pin* pinB, Pin* pinCW, std::string uniqueId);
|
||||
Light(Pin* pinR, Pin* pinG, Pin* pinB, Pin* pinCW, Pin* pinWW, std::string uniqueId);
|
||||
void notifyOnline();
|
||||
void notifyOffline();
|
||||
void publishInitialState();
|
||||
void publishCurrentState();
|
||||
void setHsl(uint8_t h, uint8_t s, uint8_t l);
|
||||
@@ -97,7 +91,6 @@ private:
|
||||
Pin* pinB;
|
||||
Pin* pinCW;
|
||||
Pin* pinWW;
|
||||
Mqtt* mqttClient;
|
||||
LightInfo lightInfo;
|
||||
DeviceInfo deviceInfo;
|
||||
LightType lightType = onOff; // Default light type
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
WIFIMANAGER Network::WifiManager;
|
||||
AsyncWebServer Network::webServer(80);
|
||||
|
||||
Network::Network(std::string_view hostname, std::string_view apSsid) : hostname(hostname), apSsid(apSsid) {
|
||||
Network::Network(std::string_view hostname, std::string_view apSsid) {
|
||||
this->hostname = std::string(hostname);
|
||||
this->apSsid = std::string(apSsid);
|
||||
setHostname(hostname);
|
||||
WifiManager.startBackgroundTask(apSsid.data(), "");
|
||||
WifiManager.fallbackToSoftAp(true);
|
||||
@@ -17,6 +19,17 @@ Network::Network(std::string_view hostname, std::string_view apSsid) : hostname(
|
||||
webServer.begin();
|
||||
}
|
||||
|
||||
Network::~Network() {
|
||||
webServer.end();
|
||||
WifiManager.detachUI();
|
||||
WifiManager.detachWebServer();
|
||||
}
|
||||
|
||||
void Network::reconnect() {
|
||||
WifiManager.stopWifi(true);
|
||||
WifiManager.startBackgroundTask(apSsid.data(), "");
|
||||
}
|
||||
|
||||
bool Network::isConnected() const {
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
@@ -25,14 +38,26 @@ std::string Network::getHostname() const {
|
||||
return WiFi.getHostname();
|
||||
}
|
||||
|
||||
const std::string Network::getMacAddress() const {
|
||||
std::string mac = WiFi.macAddress().c_str(); // format: "AA:BB:CC:DD:EE:FF"
|
||||
std::string hexMac = "0x";
|
||||
for (size_t i = 0; i < mac.size(); ++i) {
|
||||
if (mac[i] != ':') {
|
||||
hexMac += mac[i];
|
||||
}
|
||||
}
|
||||
return hexMac;
|
||||
}
|
||||
|
||||
bool Network::setHostname(const std::string_view &hostname) {
|
||||
return WiFi.setHostname(hostname.data());
|
||||
this->hostname = std::string(hostname);
|
||||
return WiFi.setHostname(this->hostname.c_str());
|
||||
}
|
||||
|
||||
void Network::registerMDNS() {
|
||||
if (!MDNS.begin(hostname.data())) {
|
||||
if (!MDNS.begin(this->hostname.c_str())) {
|
||||
Serial.println("Error setting up MDNS responder!");
|
||||
} else {
|
||||
Serial.printf("mDNS responder started with hostname: %s\n", hostname.data());
|
||||
Serial.printf("mDNS responder started with hostname: %s\n", this->hostname.c_str());
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@
|
||||
class Network {
|
||||
public:
|
||||
Network(std::string_view hostname, std::string_view apSsid = "Smart RGB");
|
||||
~Network();
|
||||
void reconnect();
|
||||
bool isConnected() const;
|
||||
std::string getHostname() const;
|
||||
const std::string getMacAddress() const;
|
||||
bool setHostname(const std::string_view &hostname);
|
||||
void registerMDNS();
|
||||
private:
|
||||
@@ -26,6 +29,6 @@ private:
|
||||
<p><small>ESP32 WiFi Manager (c) 2022-2025 by Martin Verges</small></p>
|
||||
</body></html>
|
||||
)html";
|
||||
std::string_view hostname;
|
||||
std::string_view apSsid; // SSID for the fallback AP
|
||||
std::string hostname;
|
||||
std::string apSsid; // SSID for the fallback AP
|
||||
};
|
||||
@@ -1,29 +1,30 @@
|
||||
#include <ArduinoOTA.h>
|
||||
#include "debugutil.hpp"
|
||||
#include "ota.h"
|
||||
|
||||
OTAHandler::OTAHandler(std::string_view hostname) {
|
||||
ArduinoOTA.setHostname(hostname.data());
|
||||
ArduinoOTA.onStart([]() {
|
||||
Serial.println("OTA Start");
|
||||
Debug::println("OTA Start");
|
||||
});
|
||||
ArduinoOTA.onEnd([]() {
|
||||
Serial.println("OTA End");
|
||||
Debug::println("OTA End");
|
||||
});
|
||||
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
|
||||
Serial.printf("OTA Progress: %u%%\n", (progress / (total / 100)));
|
||||
Debug::printf("OTA Progress: %u%%\n", (progress / (total / 100)));
|
||||
});
|
||||
ArduinoOTA.onError([](ota_error_t error) {
|
||||
Serial.printf("OTA Error[%u]: ", error);
|
||||
Debug::printf("OTA Error[%u]: ", error);
|
||||
if (error == OTA_AUTH_ERROR) {
|
||||
Serial.println("Auth Failed");
|
||||
Debug::println("Auth Failed");
|
||||
} else if (error == OTA_BEGIN_ERROR) {
|
||||
Serial.println("Begin Failed");
|
||||
Debug::println("Begin Failed");
|
||||
} else if (error == OTA_CONNECT_ERROR) {
|
||||
Serial.println("Connect Failed");
|
||||
Debug::println("Connect Failed");
|
||||
} else if (error == OTA_RECEIVE_ERROR) {
|
||||
Serial.println("Receive Failed");
|
||||
Debug::println("Receive Failed");
|
||||
} else if (error == OTA_END_ERROR) {
|
||||
Serial.println("End Failed");
|
||||
Debug::println("End Failed");
|
||||
}
|
||||
});
|
||||
ArduinoOTA.begin();
|
||||
|
||||
@@ -15,8 +15,8 @@ framework = arduino
|
||||
monitor_speed = 115200
|
||||
build_unflags = -std=gnu++11
|
||||
build_flags =
|
||||
-std=c++17
|
||||
-std=gnu++17
|
||||
-I include
|
||||
lib_deps =
|
||||
martinverges/ESP32 Wifi Manager@^1.5.0
|
||||
esp32async/ESPAsyncWebServer@^3.7.10
|
||||
@@ -25,7 +25,17 @@ lib_deps =
|
||||
arkhipenko/TaskScheduler@^3.8.5
|
||||
|
||||
[env:esp32dev-serial]
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-D ENABLE_SERIAL_DEBUG=1
|
||||
|
||||
[env:esp32dev-serial-tcp]
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-D ENABLE_SERIAL_DEBUG=1
|
||||
monitor_port = rfc2217://10.238.75.163:6000
|
||||
upload_port = rfc2217://10.238.75.163:6000
|
||||
|
||||
[env:esp32dev-ota]
|
||||
upload_protocol = espota
|
||||
upload_port = smart-rgb-dev.local
|
||||
upload_port = smart-rgb.local
|
||||
|
||||
12
src/main.cpp
12
src/main.cpp
@@ -1,6 +1,7 @@
|
||||
#include <Arduino.h>
|
||||
#include "appcontext.hpp"
|
||||
#include "config.h"
|
||||
#include "debugutil.hpp"
|
||||
#include "light.h"
|
||||
#include "mqtt.h"
|
||||
#include "network.h"
|
||||
@@ -41,11 +42,10 @@ Scheduler *scheduler = nullptr;
|
||||
void initializeScheduler();
|
||||
|
||||
void setup() {
|
||||
// put your setup code here, to run once:
|
||||
Serial.begin(115200);
|
||||
Serial.println("Starting Smart RGB ESP32...");
|
||||
initializeScheduler();
|
||||
Debug::begin(115200);
|
||||
Debug::println("Starting Smart RGB ESP32...");
|
||||
stateMachine = new StateMachine<maxNumberOfStates>();
|
||||
initializeScheduler();
|
||||
appContext->pinR = pinR;
|
||||
appContext->pinG = pinG;
|
||||
appContext->pinB = pinB;
|
||||
@@ -56,10 +56,8 @@ void setup() {
|
||||
stateMachine->addTransition(StateId::StartState, EventId::PinInitialized, StateId::NetworkInitializeState);
|
||||
stateMachine->addStateRaw(runningState);
|
||||
stateMachine->addTransition(StateId::NetworkInitializeState, EventId::WifiConnected, StateId::RunningState);
|
||||
stateMachine->addTransition(StateId::RunningState, EventId::WifiDisconnected, StateId::NetworkInitializeState);
|
||||
stateMachine->setInitialState(StateId::StartState);
|
||||
|
||||
// Mqtt::connect("10.238.75.81", 1883, "smart_rgb_client", "mqtt", "mqtt");
|
||||
// delay(1000); // Wait for MQTT connection to stabilize
|
||||
// light = new Light(pinR, pinG, pinB, pinCW, pinWW, mqttClient, "smart_rgb_light");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <Arduino.h>
|
||||
#include "appcontext.hpp"
|
||||
#include "config.h"
|
||||
#include "debugutil.hpp"
|
||||
#include "mqtt.h"
|
||||
#include "pin.h"
|
||||
#include "statemachine.hpp"
|
||||
@@ -15,7 +16,8 @@ enum class StateId
|
||||
enum class EventId
|
||||
{
|
||||
PinInitialized,
|
||||
WifiConnected
|
||||
WifiConnected,
|
||||
WifiDisconnected
|
||||
};
|
||||
|
||||
class StartState : public State
|
||||
@@ -50,17 +52,22 @@ public:
|
||||
NetworkInitializeState(AppContext *appContext) : State("NetworkInitializeState", StateId::NetworkInitializeState), appContext(appContext) {}
|
||||
|
||||
void onEnter(StateMachineBase &stateMachine) override {
|
||||
if (appContext) {
|
||||
Debug::println("Entering NetworkInitializeState");
|
||||
if (appContext && !appContext->network) {
|
||||
appContext->network = new Network(hostName, friendlyName);
|
||||
} else if (appContext && appContext->network) {
|
||||
appContext->network->reconnect();
|
||||
}
|
||||
}
|
||||
|
||||
void onExit(StateMachineBase &stateMachine) override {
|
||||
if (appContext && appContext->network) {
|
||||
appContext->network->registerMDNS();
|
||||
if (!appContext->otaHandler) {
|
||||
appContext->otaHandler = new OTAHandler(hostName);
|
||||
}
|
||||
Mqtt::connect(mqttBroker.data(), 1883, "smart_rgb_dev", "mqtt", "mqtt");
|
||||
}
|
||||
Mqtt::connect(mqttBroker.data(), 1883, hostName.data(), "mqtt", "mqtt");
|
||||
}
|
||||
|
||||
void onUpdate(StateMachineBase &stateMachine) override {
|
||||
@@ -78,12 +85,25 @@ class RunningState : public State
|
||||
public:
|
||||
RunningState(AppContext *appContext) : State("RunningState", StateId::RunningState), appContext(appContext) {}
|
||||
void onEnter(StateMachineBase &stateMachine) override {
|
||||
Debug::println("Entering RunningState");
|
||||
if (appContext) {
|
||||
if (!appContext->light) {
|
||||
appContext->light = new Light(appContext->pinR, appContext->pinG, appContext->pinB, appContext->pinCW, appContext->pinWW, appContext->network->getMacAddress());
|
||||
} else {
|
||||
appContext->light->notifyOnline();
|
||||
}
|
||||
}
|
||||
lastOtaPollMs = millis();
|
||||
lastMqttPollMs = millis();
|
||||
lastMqttCheckConnectionPollSecond = millis() / 1000;
|
||||
lastNetworkCheckPollMs = millis();
|
||||
}
|
||||
|
||||
void onExit(StateMachineBase &stateMachine) override {
|
||||
Debug::println("Exiting RunningState");
|
||||
if (appContext && appContext->light) {
|
||||
appContext->light->notifyOffline();
|
||||
}
|
||||
}
|
||||
|
||||
void onUpdate(StateMachineBase &stateMachine) override {
|
||||
@@ -101,12 +121,20 @@ public:
|
||||
lastMqttCheckConnectionPollSecond = millis() / 1000;
|
||||
Mqtt::checkConnection();
|
||||
}
|
||||
if ((millis() - lastNetworkCheckPollMs) >= networkCheckPollInterval) {
|
||||
lastNetworkCheckPollMs = millis();
|
||||
if (appContext && appContext->network && !appContext->network->isConnected()) {
|
||||
stateMachine.postEvent(EventId::WifiDisconnected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
AppContext *appContext = nullptr;
|
||||
uint32_t lastOtaPollMs = 0;
|
||||
static constexpr uint32_t otaPollInterval = 1000; // Poll every second
|
||||
uint32_t lastNetworkCheckPollMs = 0;
|
||||
static constexpr uint32_t networkCheckPollInterval = 5000; // Poll every 5 seconds
|
||||
uint32_t lastMqttPollMs = 0;
|
||||
static constexpr uint32_t mqttPollInterval = 100; // Poll every 100 milliseconds
|
||||
uint32_t lastMqttCheckConnectionPollSecond = 0;
|
||||
|
||||
Reference in New Issue
Block a user