17 Commits

21 changed files with 1069 additions and 36 deletions

1
.gitignore vendored
View File

@@ -3,3 +3,4 @@
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
.venv/

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "lib/state-machine"]
path = lib/state-machine
url = https://github.com/t-liu93/state-machine

View File

@@ -55,5 +55,6 @@
"thread": "cpp",
"cinttypes": "cpp",
"typeinfo": "cpp"
}
},
"idf.portWin": "COM4"
}

125
helper/remote-serial.py Normal file
View 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()

15
include/config.h Normal file
View File

@@ -0,0 +1,15 @@
#pragma once
#include <cstdint>
#include <string>
inline constexpr uint8_t ledPinR = 16;
inline constexpr uint8_t ledPinG = 17;
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";
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
View 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)...);
}
}
};

107
lib/communication/mqtt.cpp Normal file
View File

@@ -0,0 +1,107 @@
#include <PubSubClient.h>
#include <WiFiClient.h>
#include "debugutil.hpp"
#include "mqtt.h"
constexpr uint16_t BUFFER_SIZE = 2048;
static WiFiClient wifiClient = WiFiClient();
static PubSubClient mqttClient = PubSubClient(wifiClient);
std::string Mqtt::brokerIp;
uint16_t Mqtt::brokerPort;
std::string Mqtt::clientId;
std::string Mqtt::username;
std::string Mqtt::password;
std::map<std::string, MqttCallback> Mqtt::callbacks;
bool Mqtt::initialized = false;
bool Mqtt::isConnected = false;
void Mqtt::mqttCb(char* topic, uint8_t* payload, unsigned int length) {
std::string topicStr(topic);
if (callbacks.find(topicStr) != callbacks.end()) {
callbacks[topicStr](payload, length);
}
}
void Mqtt::subscribe(const std::string& topic, MqttCallback callback) {
if (mqttClient.connected()) {
if (mqttClient.subscribe(topic.c_str())) {
callbacks[topic] = callback;
Debug::printf("Subscribed to topic: %s\n", topic.c_str());
} else {
Debug::printf("Failed to subscribe to topic: %s\n", topic.c_str());
}
} else {
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);
}
}
void Mqtt::publish(const std::string& topic, const std::string& payload, bool retain) {
if (mqttClient.connected()) {
if (mqttClient.publish(topic.c_str(), payload.c_str(), retain)) {
} else {
Debug::printf("Failed to publish to topic: %s\n", topic.c_str(), payload.c_str());
}
} else {
Debug::println("MQTT client is not connected. Cannot publish.");
}
}
void Mqtt::poll() {
if (mqttClient.connected()) {
mqttClient.loop(); // Process incoming messages
} else {
Debug::println("MQTT client is not connected. Polling skipped.");
}
}
void Mqtt::checkConnection() {
if (!mqttClient.connected()) {
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())) {
Debug::println("Reconnected to MQTT broker successfully.");
for (const auto& callback : Mqtt::callbacks) {
mqttClient.subscribe(callback.first.c_str());
}
Mqtt::isConnected = true;
} else {
Debug::printf("Failed to reconnect to MQTT broker, rc=%d\n", mqttClient.state());
Mqtt::isConnected = false;
}
}
}
void Mqtt::connect(std::string brokerIp, uint16_t brokerPort, std::string clientId, std::string username, std::string password) {
Mqtt::brokerIp = brokerIp;
Mqtt::brokerPort = brokerPort;
Mqtt::clientId = clientId;
Mqtt::username = username;
Mqtt::password = password;
mqttClient.setServer(Mqtt::brokerIp.c_str(), Mqtt::brokerPort);
mqttClient.setKeepAlive(60);
mqttClient.setCallback(mqttCb);
mqttClient.setBufferSize(BUFFER_SIZE);
if (mqttClient.connect(Mqtt::clientId.c_str(), Mqtt::username.c_str(), Mqtt::password.c_str())) {
Debug::println("Connected to MQTT broker");
Mqtt::initialized = true;
Mqtt::isConnected = true;
} else {
Debug::printf("Failed to connect to MQTT broker, rc=%d\n", mqttClient.state());
}
}

27
lib/communication/mqtt.h Normal file
View File

@@ -0,0 +1,27 @@
#pragma once
#include <string>
#include <functional>
#include <map>
typedef std::function<void(uint8_t*, int)> MqttCallback;
class Mqtt {
public:
static void connect(std::string brokerIp, uint16_t brokerPort, std::string clientId, std::string username="mqtt", std::string password="mqtt");
static void poll();
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:
static std::string brokerIp;
static uint16_t brokerPort;
static std::string clientId;
static std::string username;
static std::string password;
static bool initialized;
static bool isConnected;
static std::map<std::string, MqttCallback> callbacks;
};

279
lib/light/light.cpp Normal file
View File

@@ -0,0 +1,279 @@
#include <ArduinoJson.h>
#include "debugutil.hpp"
#include "light.h"
#include "mqtt.h"
constexpr uint16_t configMsgSize = 1024;
constexpr uint16_t statusMsgSize = 128;
constexpr uint8_t minPwmValue = 0;
constexpr double gammaCorrection = 2.4;
constexpr uint32_t maxPwmUi = 255;
const struct {
String available = "online";
String notAvailable = "offline";
} Availability;
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;
notifyOnline();
}
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();
notifyOnline();
}
void Light::publishInitialState() {
// Publish the initial state of the light
JsonDocument configInfo;
JsonObject deviceInfo = configInfo["device"].to<JsonObject>();
deviceInfo["name"] = this->deviceInfo.name;
deviceInfo["model"] = this->deviceInfo.model;
JsonArray identifiers = deviceInfo["identifiers"].to<JsonArray>();
identifiers.add(this->lightInfo.uniqueId);
deviceInfo["sw_version"] = this->deviceInfo.swVersion;
deviceInfo["manufacturer"] = this->deviceInfo.manufacturer;
configInfo["unique_id"] = this->lightInfo.uniqueId;
configInfo["name"] = this->lightInfo.name;
configInfo["schema"] = "json";
configInfo["json_attributes_topic"] = this->lightInfo.jsonAttributesTopic;
configInfo["command_topic"] = this->lightInfo.commandTopic;
configInfo["color_temp_kelvin"] = true;
configInfo["max_kelvin"] = cwTempKelvin;
configInfo["min_kelvin"] = wwTempKelvin;
JsonArray availabilityInfo = configInfo["availability"].to<JsonArray>();
JsonObject availabilityItem = availabilityInfo.add<JsonObject>();
availabilityItem["topic"] = this->lightInfo.availabilityTopic;
availabilityItem["value_template"] = this->lightInfo.availabilityTemplate;
JsonArray supportedColorModes = configInfo["supported_color_modes"].to<JsonArray>();
if (lightType == LightType::rgb) {
supportedColorModes.add("rgb");
} else if (lightType == LightType::rgbw) {
supportedColorModes.add("rgbw");
} else if (lightType == LightType::rgbww) {
supportedColorModes.add("rgb");
supportedColorModes.add("color_temp");
} else if (lightType == LightType::colorTemperature) {
supportedColorModes.add("color_temp");
} else if (lightType == LightType::brightness) {
supportedColorModes.add("brightness");
} else {
supportedColorModes.add("onoff");
}
configInfo["state_topic"] = this->lightInfo.stateTopic;
std::string configJson;
serializeJson(configInfo, configJson);
Mqtt::publish(lightInfo.discoveryTopic, configJson);
std::string stateJson;
JsonDocument stateInfo;
stateInfo["state"] = "OFF";
stateInfo["brightness"] = maxPwmUi;
brightness = maxPwmUi;
JsonObject color = stateInfo["color"].to<JsonObject>();
color["r"] = 0;
r = 0;
color["g"] = 0;
g = 0;
color["b"] = 0;
b = 0;
serializeJson(stateInfo, stateJson);
std::string availabilityJson;
JsonDocument availabilityInfoDoc;
availabilityInfoDoc["availability"] = Availability.available;
serializeJson(availabilityInfoDoc, availabilityJson);
Mqtt::publish(lightInfo.stateTopic, stateJson);
Mqtt::publish(lightInfo.availabilityTopic, availabilityJson);
}
void Light::operatePin() {
auto clamp8 = [](int v)->uint8_t { return v < 0 ? 0 : (v > 255 ? 255 : v); };
if (!isOn) {
turnOff();
return;
}
uint8_t r8 = clamp8(r);
uint8_t g8 = clamp8(g);
uint8_t b8 = clamp8(b);
uint8_t cw8 = clamp8(cw);
uint8_t ww8 = clamp8(ww);
uint8_t br8 = clamp8(brightness);
uint32_t rGamma = correctGamma(r8);
uint32_t gGamma = correctGamma(g8);
uint32_t bGamma = correctGamma(b8);
uint32_t cwGamma = correctGamma(cw8);
uint32_t wwGamma = correctGamma(ww8);
uint32_t brGamma = correctGamma(br8);
auto mixHw = [this](uint32_t cG, uint32_t bG) -> uint32_t {
return static_cast<uint32_t>((static_cast<uint64_t>(cG) * bG + (maxPwm / 2)) / maxPwm);
};
uint32_t rSetpoint = mixHw(rGamma, brGamma);
uint32_t gSetpoint = mixHw(gGamma, brGamma);
uint32_t bSetpoint = mixHw(bGamma, brGamma);
uint32_t cwSetpoint = 0;
uint32_t wwSetpoint = 0;
if (activeMode == ActiveMode::modeCct) {
uint32_t peak = cwGamma > wwGamma ? cwGamma : wwGamma;
if (peak > 0) {
uint32_t cwGammaUp = static_cast<uint32_t>(
(static_cast<uint64_t>(cwGamma) * maxPwm + (peak / 2)) / peak
);
uint32_t wwGammaUp = static_cast<uint32_t>(
(static_cast<uint64_t>(wwGamma) * maxPwm + (peak / 2)) / peak
);
if (cwGammaUp > maxPwm) cwGammaUp = maxPwm;
if (wwGammaUp > maxPwm) wwGammaUp = maxPwm;
cwSetpoint = mixHw(cwGammaUp, brGamma);
wwSetpoint = mixHw(wwGammaUp, brGamma);
} else {
cwSetpoint = wwSetpoint = 0;
}
} else {
cwSetpoint = mixHw(cwGamma, brGamma);
wwSetpoint = mixHw(wwGamma, brGamma);
}
if (pinR) pinR->setLedLevel(rSetpoint);
if (pinG) pinG->setLedLevel(gSetpoint);
if (pinB) pinB->setLedLevel(bSetpoint);
if (pinCW) pinCW->setLedLevel(cwSetpoint);
if (pinWW) pinWW->setLedLevel(wwSetpoint);
}
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) {
Debug::println("Received command: " + String(command.c_str()));
JsonDocument commandJson;
deserializeJson(commandJson, command);
if (commandJson.isNull()) {
Debug::println("Invalid command JSON");
return;
}
if (commandJson["state"].is<String>()) {
std::string state = commandJson["state"].as<std::string>();
if (state == "ON") {
isOn = true;
} else if (state == "OFF") {
isOn = false;
}
}
if (commandJson["brightness"].is<int>()) {
brightness = commandJson["brightness"].as<int>();
}
if (commandJson["color"].is<JsonObject>()) {
JsonObject color = commandJson["color"];
r = color["r"] | maxPwmUi;
g = color["g"] | maxPwmUi;
b = color["b"] | maxPwmUi;
cw = 0;
ww = 0;
activeMode = ActiveMode::modeRgb;
}
if (commandJson["color_temp"].is<int>()) {
colorTemperature = commandJson["color_temp"].as<int>();
applyKelvin(colorTemperature);
}
if (lightType == LightType::rgb || lightType == LightType::rgbw || lightType == LightType::rgbww)
{
operatePin();
publishCurrentState();
}
}
void Light::turnOff() {
isOn = false;
if (pinR != nullptr) pinR->setLedLevel(0);
if (pinG != nullptr) pinG->setLedLevel(0);
if (pinB != nullptr) pinB->setLedLevel(0);
if (pinCW != nullptr) pinCW->setLedLevel(0);
if (pinWW != nullptr) pinWW->setLedLevel(0);
}
void Light::publishCurrentState() {
// Publish the current state of the light
JsonDocument stateInfo;
JsonDocument attributeInfo;
stateInfo["state"] = isOn ? "ON" : "OFF";
stateInfo["availability"] = Availability.available; // Current availability
stateInfo["brightness"] = brightness;
if (activeMode == ActiveMode::modeRgb) {
JsonObject color = stateInfo["color"].to<JsonObject>();
color["r"] = r;
color["g"] = g;
color["b"] = b;
stateInfo["color_mode"] = "rgb";
} else if (activeMode == ActiveMode::modeCct) {
stateInfo["color_temp"] = colorTemperature;
stateInfo["color_mode"] = "color_temp";
}
attributeInfo["pwmR"] = pinR->getLedLevel();
attributeInfo["pwmG"] = pinG->getLedLevel();
attributeInfo["pwmB"] = pinB->getLedLevel();
if (pinCW != nullptr)
attributeInfo["pwmCW"] = pinCW->getLedLevel();
if (pinWW != nullptr)
attributeInfo["pwmWW"] = pinWW->getLedLevel();
std::string stateJson;
serializeJson(stateInfo, stateJson);
Debug::println("Publishing current state: " + String(stateJson.c_str()));
Mqtt::publish(lightInfo.stateTopic, stateJson);
std::string attributeJson;
serializeJson(attributeInfo, attributeJson);
Debug::println("Publishing current attributes: " + String(attributeJson.c_str()));
Mqtt::publish(lightInfo.jsonAttributesTopic, attributeJson);
}
uint32_t Light::correctGamma(uint32_t originalPwm) {
double normalized = static_cast<double>(originalPwm) / maxPwmUi;
if (normalized <= 0.04045) {
return static_cast<uint32_t>((normalized / 12.92) * maxPwm);
} else {
return static_cast<uint32_t>(pow((normalized + 0.055) / 1.055, gammaCorrection) * maxPwm);
}
}
void Light::applyKelvin(uint32_t kelvin) {
if (kelvin > cwTempKelvin) kelvin = cwTempKelvin;
if (kelvin < wwTempKelvin) kelvin = wwTempKelvin;
double tLin = static_cast<double>(kelvin - wwTempKelvin) / static_cast<double>(cwTempKelvin - wwTempKelvin);
r = 0;
g = 0;
b = 0;
cw = static_cast<uint8_t>(tLin * maxPwmUi);
ww = static_cast<uint8_t>((1.0 - tLin) * maxPwmUi);
activeMode = ActiveMode::modeCct;
}

98
lib/light/light.h Normal file
View File

@@ -0,0 +1,98 @@
#pragma once
#include <cstdint>
#include "pin.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 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 }}";
};
struct DeviceInfo {
std::string name = "Smart RGB Light";
std::string model = "smart_rgb_light";
std::string identifier = "smart_rgb_light_";
std::string swVersion = "1.0"; // TODO: version will be generated.
std::string manufacturer = "Studio TJ";
};
enum LightType {
onOff,
brightness,
colorTemperature,
rgb,
rgbw,
rgbww,
};
enum ActiveMode {
modeRgb,
modeCct
};
class Light {
public:
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);
void setColorTemperature(uint16_t temperature);
void setBrightness(uint8_t brightness);
void turnOff();
private:
void handleCommand(const std::string& command);
void operatePin();
uint32_t correctGamma(uint32_t originalPwm);
void applyKelvin(uint32_t kelvin);
uint8_t r = 0; // Default to white
uint8_t g = 0; // Default to white
uint8_t b = 0; // Default to white
uint8_t cw = 255; // Default to white
uint8_t ww = 255; // Default to white
const uint32_t cwTempKelvin = 6000;
const uint32_t wwTempKelvin = 3000;
uint16_t colorTemperature;
uint8_t brightness;
uint32_t maxPwm;
bool isOn = false;
Pin* pinR;
Pin* pinG;
Pin* pinB;
Pin* pinCW;
Pin* pinWW;
LightInfo lightInfo;
DeviceInfo deviceInfo;
LightType lightType = onOff; // Default light type
ActiveMode activeMode = modeRgb;
};

View File

@@ -5,18 +5,31 @@
WIFIMANAGER Network::WifiManager;
AsyncWebServer Network::webServer(80);
Network::Network(std::string hostname, std::string 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.c_str(), "");
WifiManager.startBackgroundTask(apSsid.data(), "");
WifiManager.fallbackToSoftAp(true);
WifiManager.attachWebServer(&webServer);
WifiManager.attachUI();
webServer.on("/", HTTP_GET, [this](AsyncWebServerRequest *request) {
request->send(200, "text/html", this->defaultHomepage.c_str());
request->send(200, "text/html", this->defaultHomepage.data());
});
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();
}
bool Network::setHostname(const std::string &hostname) {
return WiFi.setHostname(hostname.c_str());
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) {
this->hostname = std::string(hostname);
return WiFi.setHostname(this->hostname.c_str());
}
void Network::registerMDNS() {
if (!MDNS.begin(hostname.c_str())) {
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.c_str());
Serial.printf("mDNS responder started with hostname: %s\n", this->hostname.c_str());
}
}

View File

@@ -1,12 +1,16 @@
#include <Arduino.h>
#include <string_view>
#include "wifimanager.h"
class Network {
public:
Network(std::string hostname, std::string apSsid = "Smart RGB");
Network(std::string_view hostname, std::string_view apSsid = "Smart RGB");
~Network();
void reconnect();
bool isConnected() const;
std::string getHostname() const;
bool setHostname(const std::string &hostname);
const std::string getMacAddress() const;
bool setHostname(const std::string_view &hostname);
void registerMDNS();
private:
static WIFIMANAGER WifiManager;

View File

@@ -1,29 +1,30 @@
#include <ArduinoOTA.h>
#include "debugutil.hpp"
#include "ota.h"
OTAHandler::OTAHandler(std::string hostname) {
ArduinoOTA.setHostname(hostname.c_str());
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();

View File

@@ -1,9 +1,9 @@
#pragma once
#include <string>
#include <string_view>
class OTAHandler {
public:
OTAHandler(std::string hostname);
OTAHandler(std::string_view hostname);
void poll();
};

53
lib/pin/pin.cpp Normal file
View File

@@ -0,0 +1,53 @@
#include <Arduino.h>
#include "pin.h"
Pin::Pin(int pinNumber, bool isOutput, bool isLed, uint32_t ledFrequency, uint8_t ledChannel)
: pinNumber(pinNumber), output(isOutput), isLed(isLed), ledChannel(ledChannel) {
pinMode(pinNumber, isOutput ? OUTPUT : INPUT);
if (isLed) {
ledcSetup(ledChannel, ledFrequency, ledResolutionBits); // Setup LEDC for PWM with 8-bit resolution
ledcAttachPin(pinNumber, ledChannel); // Attach the pin to the LEDC channel
}
}
const uint8_t Pin::getLedResolutionBits() const {
return ledResolutionBits;
}
void Pin::setHigh() {
if (output) {
digitalWrite(pinNumber, HIGH);
}
}
void Pin::setLow() {
if (output) {
digitalWrite(pinNumber, LOW);
}
}
void Pin::setLedLevel(uint32_t level) {
if (output && isLed) {
ledcWrite(ledChannel, level);
ledLevel = level;
}
}
uint32_t Pin::getLedLevel() const {
return ledLevel;
}
bool Pin::read() {
if (!output) {
return digitalRead(pinNumber);
}
return false;
}
int Pin::getPinNumber() const {
return pinNumber;
}
bool Pin::isOutput() const {
return output;
}

22
lib/pin/pin.h Normal file
View File

@@ -0,0 +1,22 @@
#pragma once
class Pin {
public:
Pin(int pinNumber, bool isOutput = true, bool isLed = false, uint32_t ledFrequency = 5000, uint8_t ledChannel = 0);
void setHigh();
void setLow();
void setLedLevel(uint32_t level);
uint32_t getLedLevel() const;
const uint8_t getLedResolutionBits() const;
bool read();
int getPinNumber() const;
bool isOutput() const;
private:
uint8_t ledChannel = 0; // LED channel for PWM
uint8_t pinNumber;
uint32_t ledLevel = 0;
const uint8_t ledResolutionBits = 12;
bool output;
bool isLed = false; // Flag to indicate if this pin is used for LED control
};

1
lib/state-machine Submodule

Submodule lib/state-machine added at fc7d0d9706

View File

@@ -13,13 +13,28 @@ platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
build_unflags = -std=gnu++11
build_flags =
-std=gnu++17
-I include
lib_deps =
martinverges/ESP32 Wifi Manager@^1.5.0
esp32async/ESPAsyncWebServer@^3.7.10
bblanchon/ArduinoJson@^7.4.2
martinverges/ESP32 Wifi Manager@^1.5.0
esp32async/ESPAsyncWebServer@^3.7.10
bblanchon/ArduinoJson@^7.4.2
knolleary/PubSubClient@^2.8
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

24
src/appcontext.hpp Normal file
View File

@@ -0,0 +1,24 @@
#pragma once
class Pin;
template <uint32_t MAX_NUMBER_OF_STATES, uint32_t MAX_NUMBER_OF_TRANSITIONS>
class StateMachine;
class OTAHandler;
class Mqtt;
class Light;
class Network;
class Scheduler;
struct AppContext {
Pin *pinR = nullptr;
Pin *pinG = nullptr;
Pin *pinB = nullptr;
Pin *pinCW = nullptr;
Pin *pinWW = nullptr;
Network *network = nullptr;
Light *light = nullptr;
Mqtt *mqtt = nullptr;
OTAHandler *otaHandler = nullptr;
Scheduler *scheduler = nullptr;
};

View File

@@ -1,22 +1,82 @@
#include <Arduino.h>
#include "appcontext.hpp"
#include "config.h"
#include "debugutil.hpp"
#include "light.h"
#include "mqtt.h"
#include "network.h"
#include "ota.h"
#include "pin.h"
#include "statemachine.hpp"
#include "states.hpp"
#include "TaskScheduler.h"
#include "wifimanager.h"
Network* network = nullptr;
OTAHandler* otaHandler = nullptr;
// Network* network = nullptr;
// OTAHandler* otaHandler = nullptr;
// Mqtt* mqttClient = nullptr;
// Light *light = nullptr;
// Task *updateTask = nullptr;
// Task *mqttTickTask = nullptr;
// Task *mqttCheckConnectionTask = nullptr;
Task *appStateMachineUpdateTask = nullptr;
Pin *pinR = new Pin(ledPinR, true, true, 5000, 0);
Pin *pinG = new Pin(ledPinG, true, true, 5000, 1);
Pin *pinB = new Pin(ledPinB, true, true, 5000, 2);
Pin *pinCW = new Pin(ledPinCW, true, true, 5000, 3);
Pin *pinWW = new Pin(ledPinWW, true, true, 5000, 4);
AppContext *appContext = new AppContext();
StartState *startState = new StartState(appContext);
NetworkInitializeState *networkInitializeState = new NetworkInitializeState(appContext);
RunningState *runningState = new RunningState(appContext);
StateMachine<maxNumberOfStates> *stateMachine = nullptr;
Scheduler *scheduler = nullptr;
void initializeScheduler();
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Starting Smart RGB ESP32...");
network = new Network("smart-rgb");
otaHandler = new OTAHandler("smart-rgb-ota");
network->registerMDNS();
Debug::begin(115200);
Debug::println("Starting Smart RGB ESP32...");
stateMachine = new StateMachine<maxNumberOfStates>();
initializeScheduler();
appContext->pinR = pinR;
appContext->pinG = pinG;
appContext->pinB = pinB;
appContext->pinCW = pinCW;
appContext->pinWW = pinWW;
stateMachine->addStateRaw(startState);
stateMachine->addStateRaw(networkInitializeState);
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);
// light = new Light(pinR, pinG, pinB, pinCW, pinWW, mqttClient, "smart_rgb_light");
}
void loop() {
otaHandler->poll(); // Handle OTA updates
delay(500);
scheduler->execute(); // Execute the scheduler to run tasks
yield(); // Yield to allow other tasks to run
}
void initializeScheduler() {
scheduler = new Scheduler();
appStateMachineUpdateTask = new Task(TASK_MILLISECOND, TASK_FOREVER, []() {
if (stateMachine) {
stateMachine->update();
}
}, scheduler, true, nullptr, nullptr);
// mqttTickTask = new Task(TASK_MILLISECOND * 100, TASK_FOREVER, []() {
// Mqtt::poll(); // Poll MQTT client for messages
// }, scheduler, true, nullptr, nullptr);
// mqttCheckConnectionTask = new Task(TASK_SECOND * 30, TASK_FOREVER, []() {
// Mqtt::checkConnection(); // Check MQTT connection status
// }, scheduler, true, nullptr, nullptr);
}

142
src/states.hpp Normal file
View File

@@ -0,0 +1,142 @@
#include <Arduino.h>
#include "appcontext.hpp"
#include "config.h"
#include "debugutil.hpp"
#include "mqtt.h"
#include "pin.h"
#include "statemachine.hpp"
enum class StateId
{
StartState,
NetworkInitializeState,
RunningState
};
enum class EventId
{
PinInitialized,
WifiConnected,
WifiDisconnected
};
class StartState : public State
{
public:
StartState(AppContext *appContext) : State("StartState", StateId::StartState), appContext(appContext) {}
void onEnter(StateMachineBase &stateMachine) override {
if (appContext) {
appContext->pinR->setLedLevel(0);
appContext->pinG->setLedLevel(0);
appContext->pinB->setLedLevel(0);
appContext->pinCW->setLedLevel(0);
appContext->pinWW->setLedLevel(0);
}
stateMachine.postEvent(EventId::PinInitialized);
}
void onExit(StateMachineBase &stateMachine) override {
}
void onUpdate(StateMachineBase &stateMachine) override {
}
private:
AppContext *appContext = nullptr;
};
class NetworkInitializeState : public State
{
public:
NetworkInitializeState(AppContext *appContext) : State("NetworkInitializeState", StateId::NetworkInitializeState), appContext(appContext) {}
void onEnter(StateMachineBase &stateMachine) override {
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, hostName.data(), "mqtt", "mqtt");
}
void onUpdate(StateMachineBase &stateMachine) override {
if (appContext && appContext->network && appContext->network->isConnected()) {
stateMachine.postEvent(EventId::WifiConnected);
}
}
private:
AppContext *appContext = nullptr;
};
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 {
if ((millis() - lastOtaPollMs) >= otaPollInterval) {
lastOtaPollMs = millis();
if (appContext && appContext->otaHandler) {
appContext->otaHandler->poll();
}
}
if ((millis() - lastMqttPollMs) >= mqttPollInterval) {
lastMqttPollMs = millis();
Mqtt::poll();
}
if ((millis() - lastMqttCheckConnectionPollSecond) >= mqttCheckConnectionPollIntervalSecond * 1000) {
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;
static constexpr uint32_t mqttCheckConnectionPollIntervalSecond = 30; // Poll every 30 seconds
};