-
Notifications
You must be signed in to change notification settings - Fork 1
/
cec-server.js
89 lines (81 loc) · 2.05 KB
/
cec-server.js
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
var http = require('http');
const log4js = require('log4js');
const exec = require('child_process').execSync;
log4js.configure(
{
appenders: {
file: {
type: 'file',
filename: './log/hdmicec.log',
maxLogSize: 1 * 1024 * 1024, // = 1Mb
numBackups: 3, // keep three backup files
}
},
categories: {
default: { appenders: ['file'], level: 'info' }
}
}
);
const logger = log4js.getLogger('tv');
const PORT = 7476;
var server = http.createServer(onRequest);
server.listen(PORT);
logger.info("The HDMI CEC controller has started");
function onRequest(request, response) {
var command = request.headers['cec-command'];
var msg = '';
switch(command) {
case "on":
msg = 'echo "on 0" | cec-client RPI -s -d 1';
execmd(msg);
response.end(msg);
break;
case "off":
msg = 'echo "standby 0" | cec-client RPI -s -d 1';
execmd(msg);
response.end(msg);
break;
case "1":
case "2":
case "3":
msg = 'echo "tx 1F:82:'.concat(command, '0:00" | cec-client RPI -s -d 1');
execmd(msg);
response.end(msg);
break;
case "status":
msg = 'echo "pow 0" | cec-client RPI -s -d 1';
var state = getStatus(msg);
response.setHeader("tv-status", state);
response.end(msg);
break;
default:
msg = 'unsupported command: '.concat(command);
logger.error(msg);
response.end(msg);
break;
}
}
function execmd(command) {
var stdout = systemSync(command);
if (stdout) {
logger.info(`stdout: ${stdout}`);
}
}
function getStatus(command) {
var stdout = systemSync(command);
if (stdout == null) return "off";
logger.info(`stdout: ${stdout}`);
var arrayOfLines = stdout.match(/[^\r\n]+/g);
if (arrayOfLines.length != 2) return "off";
if (arrayOfLines[1] == 'power status: on') return "on";
return "off";
}
function systemSync(command) {
logger.info("executing cmd: ".concat(command));
try {
return exec(command).toString();
}
catch (error) {
logger.error(error.message);
}
}