-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathledcontrol.hpp
89 lines (74 loc) · 1.72 KB
/
ledcontrol.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <string>
#include <stdio.h>
#define ARDUINOJSON_ENABLE_STD_STRING 1
#include <ArduinoJson.h>
namespace ledcontrol {
struct Parameters {
Parameters() {}
Parameters(int on)
: valid(true)
, onpower(on)
{
}
bool valid = false;
int onpower = 0; // [0->255]
int offpower = 0; // [0->255]
int period = -1; //
};
Parameters parse(const std::string &in) {
// Boolean
const bool on = in == "true";
const bool off = in == "false";
if (on) {
Parameters p(255);
return p;
}
if (off) {
Parameters p(0);
return p;
}
Parameters params;
StaticJsonBuffer<200> jsonBuffer; // fails if smaller than 200
JsonVariant root = jsonBuffer.parse(in);
if (!root.success()) {
return Parameters {};
}
// Plain number
if (root.is<int>() ) {
params.valid = true;
params.onpower = root.as<int>();
return params;
}
// On/off animation
JsonObject &anim = root.as<JsonObject>();
if (anim.containsKey("animate")) {
params.onpower = anim["on"];
params.offpower = anim["off"];
params.period = anim["period"];
params.valid = true;
return params;
}
// Failed
return Parameters {};
}
struct State {
long nextSwitch = 0;
bool isOn = false;
};
int next(State &s, Parameters p, long currentTime) {
if (!p.valid) {
return -1;
}
if (p.period < 0) {
return p.onpower;
} else {
// on-off animation
if (currentTime >= s.nextSwitch) {
s.nextSwitch += p.period/2;
s.isOn = !s.isOn;
return s.isOn ? p.onpower : p.offpower;
}
}
return -1;
}
}