-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYeeLight.h
361 lines (321 loc) · 9.05 KB
/
YeeLight.h
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#ifndef __yeelight_h__
#define __yeelight_h__
#include <string>
#include <memory>
#include <ESPAsyncTCP.h>
#include <ArduinoJson.h>
#include <IPAddress.h>
#include "task.h"
namespace yeelighttask_detail
{
static constexpr unsigned int heartbeat_interval = 5*1000;
static constexpr unsigned int timeout_ms = 10*1000;
static constexpr unsigned int connect_wait_interval = 5*1000;
enum
{
S_stop = 0,
S_disconnect,
S_connecting,
S_ready,
S_busy,
S_disconnecting,
S_max
};
const char *str_state(unsigned int state)
{
static const char *strtab[S_max] =
{
"stop",
"disconnect",
"connecting",
"ready",
"busy",
"disconnecting",
};
if (state >= S_max)
return "unknown";
return strtab[state];
}
typedef StaticJsonDocument<256> JsonDocumentType;
class YeeLightImpl : public TaskImpl
{
public:
YeeLightImpl()
{
// m_client.reset(new AsyncClient);
m_client.onConnect([this](void*, AsyncClient*){
on_connect();
}, nullptr);
m_client.onDisconnect([this](void*, AsyncClient*){
on_disconnect();
}, nullptr);
m_client.onError([this](void*, AsyncClient*, err_t error){
logi() << "onError: " << error << '(' << m_client.errorToString(error) << ')';
// on_disconnect();
}, nullptr);
m_client.onData([this](void*, AsyncClient*, void *data, size_t len){
on_data(data, len);
}, nullptr);
}
void set_remote(const IPAddress &remote)
{
m_remote = remote;
}
bool connected()
{
return m_state == S_ready || m_state == S_busy;
}
void power_toggle()
{
if (!connected())
return;
logi() << "power toggle";
JsonDocumentType request;
send_request("toggle", request, &YeeLightImpl::cb_donot_care);
}
void mode_toggle()
{
// set_power('on', 'smooth', 500, 5 or 1)
if (!connected())
return;
m_night_mode = !m_night_mode;
JsonDocumentType request;
request.createNestedArray("params");
request["params"][0] = "on";
request["params"][1] = "smooth";
request["params"][2] = 300;
request["params"][3] = m_night_mode ? 5 : 1;
logi() << "mode toggle: " << (m_night_mode ? "night" : "normal");
send_request("set_power", request, &YeeLightImpl::cb_donot_care);
}
protected:
void on_start() override
{
change_state(S_disconnect);
}
void on_loop() override
{
switch (m_state)
{
case S_disconnect:
{
if (!m_wait_connect_is_set)
{
m_wait_connect_is_set = true;
m_last_active = millis();
return;
}
if (millis() - m_last_active < connect_wait_interval)
return;
m_wait_connect_is_set = false;
logd() << "async connect to " << m_remote.toString();
if (m_client.connect(m_remote, 55443))
change_state(S_connecting);
break;
}
case S_ready:
{
if (millis() - m_last_active > heartbeat_interval) {
send_heartbeat();
}
}
case S_busy:
{
if (millis() - m_last_active > timeout_ms) {
close_connection();
}
}
}
}
void on_stop() override
{
m_client.close(true);
clear_connection();
change_state(S_stop);
}
const char* get_name() const override
{
return "YeeLight";
}
private:
typedef void (YeeLightImpl::*response_callback_type)(const JsonDocumentType& response);
void change_state(unsigned int state)
{
logv() << "state change from " << m_state << "(" << str_state(m_state) << ") to " << state << "(" << str_state(state) << ")";
m_state = state;
if (state == S_disconnect)
{
m_wait_connect_is_set = false;
}
}
void clear_connection()
{
m_resp_cb = nullptr;
m_recv_buf = std::string();
m_next_request.clear();
m_next_resp_cb = nullptr;
}
void close_connection()
{
common_panic_assert(m_state == S_ready || m_state == S_busy);
change_state(S_disconnecting);
m_client.close(true);
common_panic_assert(m_state == S_disconnect);
}
void send_request(const char *method, JsonDocumentType &request, response_callback_type cb)
{
common_panic_assert(cb != nullptr);
request["id"] = 2333;
request["method"] = method;
if (!request.containsKey("params"))
{
request.createNestedArray("params");
}
if (m_state == S_busy)
{
m_next_request = request;
m_next_resp_cb = cb;
return;
}
common_panic_assert(m_state == S_ready);
common_panic_assert(m_resp_cb == nullptr);
m_resp_cb = cb;
m_last_active = millis();
change_state(S_busy);
send_request_final(request);
}
void send_request_final(JsonDocument &request)
{
String data;
size_t len = 0;
serializeJson(request, data);
len += m_client.add(data.c_str(), data.length());
len += m_client.add("\r\n", 2);
common_panic_assert(len == data.length() + 2);
logd() << "send " << data;
if (!m_client.send()) {
logw() << "send fail, close socket";
close_connection();
}
}
void on_connect()
{
logi() << "connected to " << m_client.remoteIP();
common_panic_assert(m_state == S_connecting);
change_state(S_ready);
m_last_active = millis();
m_night_mode = false;
}
void on_disconnect()
{
logi() << "disconnected";
change_state(S_disconnect);
clear_connection();
}
void on_data(const void *data, size_t len)
{
logv() << __func__ << " call len: " << len;
common_panic_assert(m_state == S_ready || m_state == S_busy);
m_last_active = millis();
m_recv_buf += std::string(reinterpret_cast<const char*>(data), len);
size_t pos = 0, next;
while (1)
{
next = m_recv_buf.find('\r', pos);
if (next == m_recv_buf.npos)
break;
if (next == m_recv_buf.length() - 1)
break;
if (m_recv_buf[next+1] != '\n')
{
logw() << "protocol error: cannot found \\n";
close_connection();
break;
}
std::string frame = m_recv_buf.substr(pos, next - pos);
JsonDocumentType doc;
logd() << "recv " << frame.c_str();
if (deserializeJson(doc, frame.c_str()))
{
logw() << "parse fail: " << frame.c_str();
close_connection();
return;
}
else
{
on_data_json(doc); // be care of exception
}
pos = next + 2;
}
m_recv_buf = m_recv_buf.substr(pos);
}
void on_data_json(const JsonDocumentType& data)
{
if (data.containsKey("id"))
{
common_panic_assert(m_resp_cb != nullptr);
// common_panic_assert(data.containsKey("result") && data["result"].is<JsonArray>());
change_state(S_ready);
(this->*m_resp_cb)(data);
m_resp_cb = nullptr;
if (m_next_request.size())
{
m_resp_cb = m_next_resp_cb;
m_next_resp_cb = nullptr;
change_state(S_busy);
send_request_final(m_next_request);
m_next_request.clear();
}
}
}
void send_heartbeat()
{
JsonDocumentType request;
send_request("get_prop", request, &YeeLightImpl::cb_heartbeat);
}
void cb_heartbeat(const JsonDocumentType& response)
{
logd() << "got heartbeat";
}
void cb_donot_care(const JsonDocumentType& response)
{
logd() << "get response, don't care";
}
private:
bool m_wait_connect_is_set;
int m_state {S_stop};
unsigned long m_last_active;
bool m_night_mode;
AsyncClient m_client;
IPAddress m_remote;
std::string m_recv_buf;
JsonDocumentType m_next_request;
response_callback_type m_next_resp_cb;
response_callback_type m_resp_cb {nullptr};
};
}
class YeeLightTask : public Task
{
public:
YeeLightTask() : Task(&m_impl)
{}
void set_remote(const IPAddress& remote)
{
m_impl.set_remote(remote);
}
void bright_adjust(int val)
{}
void ct_adjust(int val)
{}
void power_toggle()
{
m_impl.power_toggle();
}
void mode_toggle()
{
m_impl.mode_toggle();
}
private:
yeelighttask_detail::YeeLightImpl m_impl;
};
#endif