Things/things/DeviceLed.h

101 lines
2.5 KiB
C
Raw Normal View History

#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;
}
2016-04-11 00:29:05 +02:00
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;
2016-04-11 00:22:29 +02:00
bool ledOnHandler(String value);
bool ledColorHandler(String message);
HomieNode ledNode{"led", "rgb"};
};
2016-04-11 00:29:05 +02:00
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;
}
2016-04-11 00:29:05 +02:00
void DeviceLed::deviceRegister() {
2016-04-10 00:20:50 +02:00
ledNode.subscribe("on", [this](String value) { return ledOnHandler(value); });
ledNode.subscribe("color", [this](String value) { return ledColorHandler(value); });
Homie.registerNode(ledNode);
}
2016-04-11 00:29:05 +02:00
void DeviceLed::deviceLoop() {
return;
}
#endif