-
Notifications
You must be signed in to change notification settings - Fork 0
/
tv_serial.h
514 lines (480 loc) · 15.4 KB
/
tv_serial.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// serial control for TV (LG_TV)
#pragma once
#include "scheduler.h"
#include "home_assistant.h"
namespace ustd {
// Protocol defintion for TVs that can be controlled via serial
class TvSerialProtocol {
public:
enum TvInput {
UNDEFINED,
DIGITALTV,
ANALOGTV,
VIDEO1,
VIDEO2,
COMPONENT1,
COMPONENT2,
RGBDTV,
RGBPC,
HDMI1,
HDMI2
};
virtual ~TvSerialProtocol(){}; // Otherwise destructor of derived classes
// is never called!
virtual bool begin() {
return false;
}
virtual bool setOn() {
return false;
}
virtual bool setOff() {
return false;
}
virtual bool setState(bool state) {
return false;
}
virtual bool setInput(TvInput input) {
return false;
}
virtual bool getState() {
return false;
}
virtual TvInput getInput() {
return TvInput::UNDEFINED;
}
virtual bool asyncCheckState() {
return false;
}
virtual bool asyncCheckInput() {
return false;
}
virtual bool asyncReceive(Scheduler *, String) {
return false;
}
virtual bool asyncSend(Scheduler *, String) {
return false;
}
};
// TvSerialProtocol implementation for LG-TV
class TVSerialLG : TvSerialProtocol {
private:
const uint8_t recBufLen = 32;
uint8_t recBuf[32];
enum recStateType { none, started };
recStateType recState = recStateType::none;
uint8_t recBufPtr = 0;
int curState = -1;
int curInput = -1;
unsigned long lastSend = 0;
unsigned long minSendIntervall = 150;
ustd::queue<uint8_t *> asyncSendQueue = ustd::queue<uint8_t *>(16);
// this send function makes sure that there are at least
// minSendIntervall ms between different packets, otherwise
// the TV protocol parser might implode...
// Packets are queued and sent asynchronously, if necessary.
void _sendTV(const char *pData, uint8_t dataLen = 0) {
if (timeDiff(lastSend, millis()) < minSendIntervall) {
uint8_t *buf = (uint8_t *)malloc(dataLen + 1);
if (buf) {
memset(buf, 0, dataLen + 1);
memcpy(buf, pData, dataLen);
if (!asyncSendQueue.push(buf)) {
free(buf);
}
}
return;
}
pSer->write((const uint8_t *)pData, dataLen);
pSer->write('\n');
lastSend = millis();
}
public:
HardwareSerial *pSer;
TVSerialLG(HardwareSerial *pSer) : pSer(pSer) {
}
// Check if packets are in the async queue, and sent
// at appropriate time.
virtual bool asyncSend(Scheduler *pSched, String name) override {
if (timeDiff(lastSend, millis()) >= minSendIntervall) {
if (!asyncSendQueue.isEmpty()) {
char *buf = (char *)asyncSendQueue.pop();
if (buf) {
// pSched->publish(name+"/debug",buf);
// char bufdbg[256];
// char bufbt[32];
// strcpy(bufdbg,"Async: ");
// for (unsigned int i=0; i<strlen(buf); i++) {
// sprintf(bufbt," 0x%02x [%c] |",buf[i],buf[i]);
// strcat(bufdbg,bufbt);
//}
// pSched->publish(name+"/debug",bufdbg);
_sendTV(buf, strlen(buf));
free(buf);
}
}
}
return true;
}
virtual bool begin() override {
pSer->begin(9600);
lastSend = millis() + 500;
asyncCheckState(); // Current TV state (on/off)
asyncCheckInput(); // Check current input (only works, if TV is on)
return true;
}
virtual bool setOn() override {
const char *cmd = "ka 01 01";
_sendTV(cmd, strlen(cmd));
return true;
}
virtual bool setOff() override {
const char *cmd = "ka 01 00";
_sendTV(cmd, strlen(cmd));
return true;
}
virtual bool setState(bool state) override {
if (state)
return setOn();
else
return setOff();
}
virtual bool getState() {
if (curState == 1)
return true;
else
return false;
}
/*
"00" => "digitalTV",
"01" => "analogueTV",
"02" => "video1",
"03" => "video2",
"04" => "component1",
"05" => "component2",
"06" => "rgbDTV",
"07" => "rgbPC",
"08" => "hdmi1",
"09" => "hdmi2"
*/
virtual bool setInput(TvInput chan) {
const char *cmd;
switch (chan) {
case TvInput::DIGITALTV:
cmd = "kb 01 00";
_sendTV(cmd, strlen(cmd));
return true;
case TvInput::ANALOGTV:
cmd = "kb 01 01";
_sendTV(cmd, strlen(cmd));
return true;
break;
case TvInput::VIDEO1:
cmd = "kb 01 02";
_sendTV(cmd, strlen(cmd));
return true;
break;
case TvInput::VIDEO2:
cmd = "kb 01 03";
_sendTV(cmd, strlen(cmd));
return true;
break;
case TvInput::HDMI1:
cmd = "kb 01 08";
_sendTV(cmd, strlen(cmd));
return true;
break;
case TvInput::HDMI2:
cmd = "kb 01 09";
_sendTV(cmd, strlen(cmd));
return true;
break;
default:
return false;
break;
}
}
// request current state (on/off)
virtual bool asyncCheckState() {
const char *cmd = "ka 01 ff";
_sendTV(cmd, strlen(cmd));
return true;
}
// request current input
virtual bool asyncCheckInput() {
if (curState == 1) {
const char *cmd = "kb 01 ff";
_sendTV(cmd, strlen(cmd));
return true;
} else {
return false; // Can't check input channel, if TV off.
}
}
// Parse a complete message from TV
void parseRecBuf(Scheduler *pSched, String topic) {
bool known = false;
if (recBufPtr == 9) {
switch (recBuf[0]) {
case 'a': // on/off state
uint8_t state;
state = recBuf[8] - '0';
switch (state) {
case 0:
if (state != curState)
pSched->publish(topic + "/switch/state", "off");
curState = state;
known = true;
break;
case 1:
if (state != curState)
pSched->publish(topic + "/switch/state", "on");
curState = state;
known = true;
break;
default:
char msg[32];
sprintf(msg, "UNKNOWN STATE 0x%02x", state);
pSched->publish(topic + "/switch/state", msg);
break;
}
break;
case 'b': // tv input
uint8_t input;
TvInput newInput;
const char *sval;
input = recBuf[8] - '0';
switch (input) {
case 0:
sval = "digitaltv";
newInput = TvInput::DIGITALTV;
known = true;
break;
case 1:
sval = "analogtv";
newInput = TvInput::ANALOGTV;
known = true;
break;
case 2:
sval = "video1";
newInput = TvInput::VIDEO1;
known = true;
break;
case 3:
sval = "video2";
newInput = TvInput::VIDEO2;
known = true;
break;
case 8:
sval = "hdmi1";
newInput = TvInput::HDMI1;
known = true;
break;
case 9:
sval = "hdmi2";
newInput = TvInput::HDMI2;
known = true;
break;
}
if (known) {
if (curInput != newInput)
pSched->publish(topic + "/tv/input", sval);
curInput = newInput;
} else {
char msg[32];
sprintf(msg, "UNKNOWN TV INPUT 0x%02x, TV off?", input);
pSched->publish(topic + "/tv/input", msg);
curInput = TvInput::UNDEFINED;
}
break;
}
}
if (!known) {
char scratch[256];
char part[10];
strcpy(scratch, "");
for (int i = 0; i < recBufPtr; i++) {
sprintf(part, " 0x%02x", recBuf[i]);
strcat(scratch, part);
}
pSched->publish(topic + "/tv/xmessage", scratch);
}
}
// Check, if serial data is available and assemble a complete packet for
// parser
virtual bool asyncReceive(Scheduler *pSched, String topic) override {
while (pSer->available() > 0) {
uint8_t b = pSer->read();
// char dbg[42];
// sprintf(dbg,"RECEIVE [%02d] 0x%02x %c",recBufPtr,b,(char)b);
// pSched->publish(topic+"/debug",dbg);
switch (recState) {
case recStateType::none:
if (b == 'a' || b == 'b') { // Answer to state ('a') or input ('b')
recBufPtr = 0;
recBuf[recBufPtr] = b;
++recBufPtr;
recState = recStateType::started;
} else {
recBufPtr = 0;
}
continue;
break;
case recStateType::started:
if (b == 'x') {
parseRecBuf(pSched, topic);
recBufPtr = 0;
recState = recStateType::none;
} else {
recBuf[recBufPtr] = b;
++recBufPtr;
if (recBufPtr >= recBufLen) {
recBufPtr = 0;
recState = recStateType::none;
}
}
continue;
break;
default:
recBufPtr = 0;
recState = recStateType::none;
continue;
break;
}
}
return true;
}
};
// Main mupplet
class TvSerial {
private:
Scheduler *pSched;
int tID;
public:
String TVSERIAL_VERSION = "0.1.0";
TvSerialProtocol *tvProt;
enum TV_SERIAL_TYPE { LG_TV }; // currently support serial TV types
String name;
HardwareSerial *pSerial;
TV_SERIAL_TYPE tvSerialType;
bool pollActive = true;
#ifdef __ESP__
HomeAssistant *pHA;
#endif
TvSerial(String name, HardwareSerial *pSerial,
TV_SERIAL_TYPE tvSerialType = TV_SERIAL_TYPE::LG_TV)
: name(name), pSerial(pSerial), tvSerialType(tvSerialType) {
// Instantiate the appropriate TvSerialProtocol:
switch (tvSerialType) {
case TV_SERIAL_TYPE::LG_TV:
tvProt = (TvSerialProtocol *)new TVSerialLG(pSerial);
break;
default:
tvProt = nullptr;
break;
}
}
~TvSerial() {
}
void begin(Scheduler *_pSched) {
pSched = _pSched;
tvProt->begin();
auto ft = [=]() { this->loop(); };
// Loop 50ms: check async send/receive every 50ms,
// (and request TV status every 1sec):
tID = pSched->add(ft, name, 50000); // call loop() every 50ms
auto fnall = [=](String topic, String msg, String originator) {
this->subsMsg(topic, msg, originator);
};
pSched->subscribe(tID, name + "/#", fnall);
}
// This registers the TV as switch in home assistant and automatically
// syncs information.
#ifdef __ESP__
void registerHomeAssistant(String homeAssistantFriendlyName, String projectName = "",
String homeAssistantDiscoveryPrefix = "homeassistant") {
pHA = new HomeAssistant(name, tID, homeAssistantFriendlyName, projectName, TVSERIAL_VERSION,
homeAssistantDiscoveryPrefix);
pHA->addSwitch("mdi:television-classic");
pHA->begin(pSched);
}
#endif
bool setOn() {
if (tvProt->setOn()) {
return tvProt->setInput(TvSerialProtocol::TvInput::HDMI1);
} else
return false;
}
bool setOff() {
return tvProt->setOff();
}
bool setState(bool state) {
if (!tvProt->setState(state))
return false;
if (state) {
return tvProt->setInput(TvSerialProtocol::TvInput::HDMI1);
}
}
bool setInput(TvSerialProtocol::TvInput input) {
return tvProt->setInput(input);
}
bool asyncCheckState() {
return tvProt->asyncCheckState();
}
bool syncCheckInput() {
return tvProt->asyncCheckInput();
}
private:
int checker = 0;
void loop() {
if (pollActive) {
++checker;
if (checker > 20) { // 20*50ms = 1sec, request TV status to make sure it's
// in sync, if user manually switch TV.
checker = 0;
tvProt->asyncCheckState();
tvProt->asyncCheckInput();
}
tvProt->asyncReceive(pSched, name); // serial receive
tvProt->asyncSend(pSched, name); // serial send
}
}
// MQTT message subscriptions, also used by Home Assistant
void subsMsg(String topic, String msg, String originator) {
if (topic == name + "/switch/set") {
if (msg == "on" || msg == "true") {
tvProt->setOn();
}
if (msg == "off" || msg == "false") {
tvProt->setOff();
}
}
if (topic == name + "/switch/state/get") {
char buf[32];
if (tvProt->getState())
sprintf(buf, "on");
else
sprintf(buf, "off");
pSched->publish(name + "/switch/state", buf);
}
if (topic == name + "/tv/input/set") {
if (msg == "digitaltv") {
tvProt->setInput(TvSerialProtocol::TvInput::DIGITALTV);
}
if (msg == "analogtv") {
tvProt->setInput(TvSerialProtocol::TvInput::ANALOGTV);
}
if (msg == "video1") {
tvProt->setInput(TvSerialProtocol::TvInput::VIDEO1);
}
if (msg == "video2") {
tvProt->setInput(TvSerialProtocol::TvInput::VIDEO2);
}
if (msg == "hdmi1") {
tvProt->setInput(TvSerialProtocol::TvInput::HDMI1);
}
if (msg == "hdmi2") {
tvProt->setInput(TvSerialProtocol::TvInput::HDMI2);
}
}
};
}; // TvSerial
} // namespace ustd