Compare commits
7 Commits
ff442f5650
...
bugfix/lig
| Author | SHA1 | Date | |
|---|---|---|---|
| 214f4647a0 | |||
| 2dec989294 | |||
| 3c1ddb52a2 | |||
| d8943c00ab | |||
| f5fff82fad | |||
| 8a0c502dae | |||
| d80a58f72c |
60
.vscode/settings.json
vendored
Normal file
60
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
{
|
||||||
|
"files.associations": {
|
||||||
|
"array": "cpp",
|
||||||
|
"atomic": "cpp",
|
||||||
|
"bitset": "cpp",
|
||||||
|
"cctype": "cpp",
|
||||||
|
"chrono": "cpp",
|
||||||
|
"clocale": "cpp",
|
||||||
|
"cmath": "cpp",
|
||||||
|
"condition_variable": "cpp",
|
||||||
|
"cstdarg": "cpp",
|
||||||
|
"cstddef": "cpp",
|
||||||
|
"cstdint": "cpp",
|
||||||
|
"cstdio": "cpp",
|
||||||
|
"cstdlib": "cpp",
|
||||||
|
"cstring": "cpp",
|
||||||
|
"ctime": "cpp",
|
||||||
|
"cwchar": "cpp",
|
||||||
|
"cwctype": "cpp",
|
||||||
|
"deque": "cpp",
|
||||||
|
"list": "cpp",
|
||||||
|
"unordered_map": "cpp",
|
||||||
|
"unordered_set": "cpp",
|
||||||
|
"vector": "cpp",
|
||||||
|
"exception": "cpp",
|
||||||
|
"algorithm": "cpp",
|
||||||
|
"functional": "cpp",
|
||||||
|
"iterator": "cpp",
|
||||||
|
"map": "cpp",
|
||||||
|
"memory": "cpp",
|
||||||
|
"memory_resource": "cpp",
|
||||||
|
"numeric": "cpp",
|
||||||
|
"optional": "cpp",
|
||||||
|
"random": "cpp",
|
||||||
|
"ratio": "cpp",
|
||||||
|
"regex": "cpp",
|
||||||
|
"string": "cpp",
|
||||||
|
"string_view": "cpp",
|
||||||
|
"system_error": "cpp",
|
||||||
|
"tuple": "cpp",
|
||||||
|
"type_traits": "cpp",
|
||||||
|
"utility": "cpp",
|
||||||
|
"fstream": "cpp",
|
||||||
|
"initializer_list": "cpp",
|
||||||
|
"iomanip": "cpp",
|
||||||
|
"iosfwd": "cpp",
|
||||||
|
"istream": "cpp",
|
||||||
|
"limits": "cpp",
|
||||||
|
"mutex": "cpp",
|
||||||
|
"new": "cpp",
|
||||||
|
"ostream": "cpp",
|
||||||
|
"sstream": "cpp",
|
||||||
|
"stdexcept": "cpp",
|
||||||
|
"streambuf": "cpp",
|
||||||
|
"thread": "cpp",
|
||||||
|
"cinttypes": "cpp",
|
||||||
|
"typeinfo": "cpp"
|
||||||
|
},
|
||||||
|
"idf.portWin": "COM4"
|
||||||
|
}
|
||||||
91
lib/communication/mqtt.cpp
Normal file
91
lib/communication/mqtt.cpp
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
#include <PubSubClient.h>
|
||||||
|
#include <WiFiClient.h>
|
||||||
|
#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;
|
||||||
|
Serial.printf("Subscribed to topic: %s\n", topic.c_str());
|
||||||
|
} else {
|
||||||
|
Serial.printf("Failed to subscribe to topic: %s\n", topic.c_str());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Serial.println("MQTT client is not connected. Cannot subscribe.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
Serial.printf("Failed to publish to topic: %s\n", topic.c_str(), payload.c_str());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Serial.println("MQTT client is not connected. Cannot publish.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Mqtt::poll() {
|
||||||
|
if (mqttClient.connected()) {
|
||||||
|
mqttClient.loop(); // Process incoming messages
|
||||||
|
} else {
|
||||||
|
Serial.println("MQTT client is not connected. Polling skipped.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Mqtt::checkConnection() {
|
||||||
|
if (!mqttClient.connected()) {
|
||||||
|
Serial.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.");
|
||||||
|
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());
|
||||||
|
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())) {
|
||||||
|
Serial.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());
|
||||||
|
}
|
||||||
|
}
|
||||||
26
lib/communication/mqtt.h
Normal file
26
lib/communication/mqtt.h
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#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 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;
|
||||||
|
};
|
||||||
270
lib/light/light.cpp
Normal file
270
lib/light/light.cpp
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
#include <ArduinoJson.h>
|
||||||
|
#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 = uniqueId;
|
||||||
|
lightType = LightType::rgb;
|
||||||
|
uint8_t bits = pinR->getLedResolutionBits();
|
||||||
|
maxPwm = (bits >= 1 && bits <= 31) ? ((1u << bits) - 1u) : 255u;
|
||||||
|
publishInitialState();
|
||||||
|
subscribeToMqttTopics();
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = uniqueId;
|
||||||
|
lightType = LightType::rgbww;
|
||||||
|
uint8_t bits = pinR->getLedResolutionBits();
|
||||||
|
maxPwm = (bits >= 1 && bits <= 31) ? ((1u << bits) - 1u) : 255u;
|
||||||
|
publishInitialState();
|
||||||
|
subscribeToMqttTopics();
|
||||||
|
}
|
||||||
|
|
||||||
|
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->deviceInfo.identifier + 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::subscribeToMqttTopics() {
|
||||||
|
Mqtt::subscribe(lightInfo.commandTopic, [this](uint8_t* payload, int length) {
|
||||||
|
std::string command(reinterpret_cast<char*>(payload), length);
|
||||||
|
handleCommand(command);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void Light::handleCommand(const std::string& command) {
|
||||||
|
Serial.println("Received command: " + String(command.c_str()));
|
||||||
|
JsonDocument commandJson;
|
||||||
|
deserializeJson(commandJson, command);
|
||||||
|
if (commandJson.isNull()) {
|
||||||
|
Serial.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);
|
||||||
|
Serial.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()));
|
||||||
|
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;
|
||||||
|
}
|
||||||
103
lib/light/light.h
Normal file
103
lib/light/light.h
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include "pin.h"
|
||||||
|
|
||||||
|
struct LightInfo {
|
||||||
|
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 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 subscribeToMqttTopics();
|
||||||
|
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;
|
||||||
|
};
|
||||||
0
lib/light/lightinfo.h
Normal file
0
lib/light/lightinfo.h
Normal file
38
lib/network/network.cpp
Normal file
38
lib/network/network.cpp
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
|
||||||
|
#include <ESPmDNS.h>
|
||||||
|
#include "network.h"
|
||||||
|
|
||||||
|
WIFIMANAGER Network::WifiManager;
|
||||||
|
AsyncWebServer Network::webServer(80);
|
||||||
|
|
||||||
|
Network::Network(std::string hostname, std::string apSsid) : hostname(hostname), apSsid(apSsid) {
|
||||||
|
setHostname(hostname);
|
||||||
|
WifiManager.startBackgroundTask(apSsid.c_str(), "");
|
||||||
|
WifiManager.fallbackToSoftAp(true);
|
||||||
|
WifiManager.attachWebServer(&webServer);
|
||||||
|
WifiManager.attachUI();
|
||||||
|
webServer.on("/", HTTP_GET, [this](AsyncWebServerRequest *request) {
|
||||||
|
request->send(200, "text/html", this->defaultHomepage.c_str());
|
||||||
|
});
|
||||||
|
webServer.begin();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Network::isConnected() const {
|
||||||
|
return WiFi.status() == WL_CONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Network::getHostname() const {
|
||||||
|
return WiFi.getHostname();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Network::setHostname(const std::string &hostname) {
|
||||||
|
return WiFi.setHostname(hostname.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Network::registerMDNS() {
|
||||||
|
if (!MDNS.begin(hostname.c_str())) {
|
||||||
|
Serial.println("Error setting up MDNS responder!");
|
||||||
|
} else {
|
||||||
|
Serial.printf("mDNS responder started with hostname: %s\n", hostname.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
30
lib/network/network.h
Normal file
30
lib/network/network.h
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
#include "wifimanager.h"
|
||||||
|
|
||||||
|
class Network {
|
||||||
|
public:
|
||||||
|
Network(std::string hostname, std::string apSsid = "Smart RGB");
|
||||||
|
bool isConnected() const;
|
||||||
|
std::string getHostname() const;
|
||||||
|
bool setHostname(const std::string &hostname);
|
||||||
|
void registerMDNS();
|
||||||
|
private:
|
||||||
|
static WIFIMANAGER WifiManager;
|
||||||
|
static AsyncWebServer webServer;
|
||||||
|
const std::string defaultHomepage = R"html(
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html><head><title>Wifi Manager</title></head>
|
||||||
|
<body style="font-family: Arial, sans-serif; margin: 40px;">
|
||||||
|
<h1>Wifi Manager</h1>
|
||||||
|
<ul>
|
||||||
|
<li><a href="/wifi">WiFi Configuration Panel</a></li>
|
||||||
|
<li><a href="/api/wifi/status">WiFi Status (JSON API)</a></li>
|
||||||
|
<li><a href="/api/wifi/configlist">Saved Networks (JSON API)</a></li>
|
||||||
|
</ul>
|
||||||
|
<hr>
|
||||||
|
<p><small>ESP32 WiFi Manager (c) 2022-2025 by Martin Verges</small></p>
|
||||||
|
</body></html>
|
||||||
|
)html";
|
||||||
|
std::string hostname;
|
||||||
|
std::string apSsid; // SSID for the fallback AP
|
||||||
|
};
|
||||||
34
lib/ota/ota.cpp
Normal file
34
lib/ota/ota.cpp
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
#include <ArduinoOTA.h>
|
||||||
|
#include "ota.h"
|
||||||
|
|
||||||
|
OTAHandler::OTAHandler(std::string hostname) {
|
||||||
|
ArduinoOTA.setHostname(hostname.c_str());
|
||||||
|
ArduinoOTA.onStart([]() {
|
||||||
|
Serial.println("OTA Start");
|
||||||
|
});
|
||||||
|
ArduinoOTA.onEnd([]() {
|
||||||
|
Serial.println("OTA End");
|
||||||
|
});
|
||||||
|
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
|
||||||
|
Serial.printf("OTA Progress: %u%%\n", (progress / (total / 100)));
|
||||||
|
});
|
||||||
|
ArduinoOTA.onError([](ota_error_t error) {
|
||||||
|
Serial.printf("OTA Error[%u]: ", error);
|
||||||
|
if (error == OTA_AUTH_ERROR) {
|
||||||
|
Serial.println("Auth Failed");
|
||||||
|
} else if (error == OTA_BEGIN_ERROR) {
|
||||||
|
Serial.println("Begin Failed");
|
||||||
|
} else if (error == OTA_CONNECT_ERROR) {
|
||||||
|
Serial.println("Connect Failed");
|
||||||
|
} else if (error == OTA_RECEIVE_ERROR) {
|
||||||
|
Serial.println("Receive Failed");
|
||||||
|
} else if (error == OTA_END_ERROR) {
|
||||||
|
Serial.println("End Failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ArduinoOTA.begin();
|
||||||
|
}
|
||||||
|
|
||||||
|
void OTAHandler::poll() {
|
||||||
|
ArduinoOTA.handle();
|
||||||
|
}
|
||||||
9
lib/ota/ota.h
Normal file
9
lib/ota/ota.h
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class OTAHandler {
|
||||||
|
public:
|
||||||
|
OTAHandler(std::string hostname);
|
||||||
|
|
||||||
|
void poll();
|
||||||
|
};
|
||||||
53
lib/pin/pin.cpp
Normal file
53
lib/pin/pin.cpp
Normal 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
22
lib/pin/pin.h
Normal 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
|
||||||
|
};
|
||||||
@@ -8,7 +8,20 @@
|
|||||||
; Please visit documentation for the other options and examples
|
; Please visit documentation for the other options and examples
|
||||||
; https://docs.platformio.org/page/projectconf.html
|
; https://docs.platformio.org/page/projectconf.html
|
||||||
|
|
||||||
[env:esp32dev]
|
[env]
|
||||||
platform = espressif32
|
platform = espressif32
|
||||||
board = esp32dev
|
board = esp32dev
|
||||||
framework = arduino
|
framework = arduino
|
||||||
|
monitor_speed = 115200
|
||||||
|
lib_deps =
|
||||||
|
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]
|
||||||
|
|
||||||
|
[env:esp32dev-ota]
|
||||||
|
upload_protocol = espota
|
||||||
|
upload_port = smart-rgb.local
|
||||||
|
|||||||
62
src/main.cpp
62
src/main.cpp
@@ -1,18 +1,64 @@
|
|||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
#include "light.h"
|
||||||
|
#include "mqtt.h"
|
||||||
|
#include "network.h"
|
||||||
|
#include "ota.h"
|
||||||
|
#include "pin.h"
|
||||||
|
#include "TaskScheduler.h"
|
||||||
|
#include "wifimanager.h"
|
||||||
|
|
||||||
// put function declarations here:
|
Network* network = nullptr;
|
||||||
int myFunction(int, int);
|
OTAHandler* otaHandler = nullptr;
|
||||||
|
Mqtt* mqttClient = nullptr;
|
||||||
|
Light *light = nullptr;
|
||||||
|
|
||||||
|
Task *updateTask = nullptr;
|
||||||
|
Task *mqttTickTask = nullptr;
|
||||||
|
Task *mqttCheckConnectionTask = nullptr;
|
||||||
|
|
||||||
|
Pin *pinR = new Pin(16, true, true, 5000, 0); // Example pin numbers, adjust as needed
|
||||||
|
Pin *pinG = new Pin(17, true, true, 5000, 1);
|
||||||
|
Pin *pinB = new Pin(18, true, true, 5000, 2);
|
||||||
|
Pin *pinCW = new Pin(19, true, true, 5000, 3);
|
||||||
|
Pin *pinWW = new Pin(21, true, true, 5000, 4);
|
||||||
|
|
||||||
|
Scheduler *scheduler;
|
||||||
|
|
||||||
|
void initializeScheduler();
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
// put your setup code here, to run once:
|
// put your setup code here, to run once:
|
||||||
int result = myFunction(2, 3);
|
Serial.begin(115200);
|
||||||
|
Serial.println("Starting Smart RGB ESP32...");
|
||||||
|
pinR->setLedLevel(0);
|
||||||
|
pinG->setLedLevel(0);
|
||||||
|
pinB->setLedLevel(0);
|
||||||
|
pinCW->setLedLevel(0);
|
||||||
|
pinWW->setLedLevel(0);
|
||||||
|
network = new Network("smart-rgb");
|
||||||
|
otaHandler = new OTAHandler("smart-rgb-ota");
|
||||||
|
network->registerMDNS();
|
||||||
|
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, "smart_rgb_light");
|
||||||
|
initializeScheduler();
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// put your main code here, to run repeatedly:
|
scheduler->execute(); // Execute the scheduler to run tasks
|
||||||
|
yield(); // Yield to allow other tasks to run
|
||||||
}
|
}
|
||||||
|
|
||||||
// put function definitions here:
|
void initializeScheduler() {
|
||||||
int myFunction(int x, int y) {
|
scheduler = new Scheduler();
|
||||||
return x + y;
|
updateTask = new Task(TASK_SECOND, TASK_FOREVER, []() {
|
||||||
|
otaHandler->poll(); // Poll for OTA updates
|
||||||
|
|
||||||
|
}, 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);
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user