101 lines
2.5 KiB
C++
101 lines
2.5 KiB
C++
#ifndef DEVICELED_H
|
|
#define DEVICELED_H
|
|
|
|
#include "Device.h"
|
|
#include <Homie.h>
|
|
|
|
class DeviceLed : public Device {
|
|
public:
|
|
inline DeviceLed(byte ledRed, byte ledGreen, byte ledBlue) {
|
|
pinRed = ledRed;
|
|
pinGreen = ledGreen;
|
|
pinBlue = ledBlue;
|
|
}
|
|
virtual void deviceSetup();
|
|
virtual void deviceRegister();
|
|
virtual void deviceLoop();
|
|
private:
|
|
byte pinRed;
|
|
byte pinGreen;
|
|
byte pinBlue;
|
|
int led_red = 0;
|
|
int led_green = 0;
|
|
int led_blue = 0;
|
|
bool ledOnHandler(String value);
|
|
bool ledColorHandler(String message);
|
|
HomieNode ledNode{"led", "rgb"};
|
|
};
|
|
|
|
void DeviceLed::deviceSetup() {
|
|
pinMode(pinRed, OUTPUT);
|
|
pinMode(pinGreen, OUTPUT);
|
|
pinMode(pinBlue, OUTPUT);
|
|
analogWrite(pinRed, led_red);
|
|
analogWrite(pinGreen, led_green);
|
|
analogWrite(pinBlue, led_blue);
|
|
}
|
|
|
|
bool DeviceLed::ledOnHandler(String value) {
|
|
if (value == "true") {
|
|
analogWrite(pinRed, led_red);
|
|
analogWrite(pinGreen, led_green);
|
|
analogWrite(pinBlue, led_blue);
|
|
Homie.setNodeProperty(ledNode, "on", "true");
|
|
Serial.println("led is on");
|
|
} else if (value == "false") {
|
|
analogWrite(pinRed, 0);
|
|
analogWrite(pinGreen, 0);
|
|
analogWrite(pinBlue, 0);
|
|
Homie.setNodeProperty(ledNode, "on", "false");
|
|
Serial.println("led is off");
|
|
} else {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool DeviceLed::ledColorHandler(String message) {
|
|
DynamicJsonBuffer json_inBuffer;
|
|
JsonObject& json_in = json_inBuffer.parseObject(message);
|
|
if (json_in.success()) {
|
|
if (json_in.containsKey("red")) {
|
|
led_red = json_in["red"];
|
|
analogWrite(pinRed, led_red);
|
|
}
|
|
if (json_in.containsKey("green")) {
|
|
led_green = json_in["green"];
|
|
analogWrite(pinGreen, led_green);
|
|
}
|
|
if (json_in.containsKey("blue")) {
|
|
led_blue = json_in["blue"];
|
|
analogWrite(pinBlue, led_blue);
|
|
}
|
|
} else {
|
|
Serial.println("parsing of JSON failed");
|
|
}
|
|
|
|
DynamicJsonBuffer json_outBuffer;
|
|
JsonObject& json_out = json_outBuffer.createObject();
|
|
json_out["red"] = led_red;
|
|
json_out["green"] = led_green;
|
|
json_out["blue"] = led_blue;
|
|
String response;
|
|
json_out.printTo(response);
|
|
Serial.print("led state: ");
|
|
Serial.println(response);
|
|
Homie.setNodeProperty(ledNode, "color", response);
|
|
return true;
|
|
}
|
|
|
|
void DeviceLed::deviceRegister() {
|
|
ledNode.subscribe("on", [this](String value) { return ledOnHandler(value); });
|
|
ledNode.subscribe("color", [this](String value) { return ledColorHandler(value); });
|
|
Homie.registerNode(ledNode);
|
|
}
|
|
|
|
void DeviceLed::deviceLoop() {
|
|
return;
|
|
}
|
|
|
|
#endif
|