forked from michaelarnauts/cec-mqtt-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bridge.py
executable file
·301 lines (238 loc) · 8.88 KB
/
bridge.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import subprocess
import time
import re
import configparser as ConfigParser
import threading
import os
import ssl
# Default configuration
config = {
'mqtt': {
'broker': os.environ.get('MQTT_HOST'),
'port': 8883,
'ssl': 1,
'prefix': 'media',
'user': os.environ.get('MQTT_USER'),
'password': os.environ.get('MQTT_PASSWORD'),
},
'cec': {
'enabled': 1,
'id': 1,
'port': 'Linux',
'devices': '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15',
},
'ir': {
'enabled': 0,
}
}
def mqtt_on_connect(client, userdata, flags, rc):
"""@type client: paho.mqtt.client """
print("Connection returned result: " + str(rc))
# Subscribe to CEC commands
if int(config['cec']['enabled']) == 1:
client.subscribe([
(config['mqtt']['prefix'] + '/cec/cmd', 0),
(config['mqtt']['prefix'] + '/cec/+/cmd', 0),
(config['mqtt']['prefix'] + '/cec/tx', 0)
])
# Subscribe to IR commands
if int(config['ir']['enabled']) == 1:
client.subscribe([
(config['mqtt']['prefix'] + '/ir/+/tx', 0)
])
def mqtt_on_message(client, userdata, message):
"""@type client: paho.mqtt.client """
try:
# Decode topic
cmd = message.topic.replace(config['mqtt']['prefix'], '').strip('/')
print("Command received: %s (%s)" % (cmd, message.payload))
split = cmd.split('/')
if split[0] == 'cec':
if split[1] == 'cmd':
action = message.payload.decode()
if action == 'mute':
cec_client.AudioMute()
return
if action == 'unmute':
cec_client.AudioUnmute()
return
if action == 'voldown':
cec_client.VolumeDown()
return
if action == 'volup':
cec_client.VolumeUp()
return
raise Exception("Unknown command (%s)" % action)
if split[1] == 'tx':
commands = message.payload.decode().split(',')
for command in commands:
print(" Sending raw: %s" % command)
cec_send(command)
return
if split[2] == 'cmd':
action = message.payload.decode()
if action == 'on':
id = int(split[1])
cec_send('44:6D', id=id)
mqtt_send(config['mqtt']['prefix'] + '/cec/' + str(id), 'on', True)
return
if action == 'off':
id = int(split[1])
cec_send('36', id=id)
mqtt_send(config['mqtt']['prefix'] + '/cec/' + str(id), 'off', True)
return
raise Exception("Unknown command (%s)" % action)
if split[0] == 'ir':
if split[2] == 'tx':
remote = split[1]
key = message.payload.decode()
ir_send(remote, key)
return
except Exception as e:
print("Error during processing of message: ", message.topic, message.payload, str(e))
def mqtt_send(topic, value, retain=False):
mqtt_client.publish(topic, value, retain=retain)
def cec_on_message(level, time, message):
if level == cec.CEC_LOG_TRAFFIC:
# Send raw command to mqtt
m = re.search('>> ([0-9a-f:]+)', message)
if m:
mqtt_send(config['mqtt']['prefix'] + '/cec/rx', m.group(1))
# Report Power Status
m = re.search('>> ([0-9a-f])[0-9a-f]:90:([0-9a-f]{2})', message)
if m:
id = int(m.group(1), 16)
# power = cec_client.PowerStatusToString(int(m.group(2)))
if (m.group(2) == '00') or (m.group(2) == '02'):
power = 'on'
else:
power = 'off'
mqtt_send(config['mqtt']['prefix'] + '/cec/' + str(id), power, True)
return
# Device Vendor ID
m = re.search('>> ([0-9a-f])[0-9a-f]:87', message)
if m:
id = int(m.group(1), 16)
power = 'on'
mqtt_send(config['mqtt']['prefix'] + '/cec/' + str(id), power, True)
return
# Report Physical Address
m = re.search('>> ([0-9a-f])[0-9a-f]:84', message)
if m:
id = int(m.group(1), 16)
power = 'on'
mqtt_send(config['mqtt']['prefix'] + '/cec/' + str(id), power, True)
return
def cec_send(cmd, id=None):
if id is None:
cec_client.Transmit(cec_client.CommandFromString(cmd))
else:
cec_client.Transmit(cec_client.CommandFromString('1%s:%s' % (hex(id)[2:], cmd)))
def ir_listen_thread():
try:
while True:
try:
code = lirc.nextcode()
except lirc.NextCodeError:
code = None
if code:
code = code[0].split(",", maxsplit=1)
if len(code) == 1:
mqtt_send(config['mqtt']['prefix'] + '/ir/rx', code[0].strip())
elif len(code) == 2:
remote = code[0].strip()
code = code[1].strip()
mqtt_send(config['mqtt']['prefix'] + '/ir/' + remote + '/rx', code)
else:
time.sleep(0.2)
except:
return
def ir_send(remote, key):
subprocess.call(["irsend", "SEND_ONCE", remote, key])
def cec_refresh():
try:
for id in config['cec']['devices'].split(','):
cec_send('8F', id=int(id))
except Exception as e:
print("Error during refreshing: ", str(e))
def cleanup():
mqtt_client.loop_stop()
mqtt_client.disconnect()
if int(config['ir']['enabled']) == 1:
lirc.deinit()
try:
### Parse config ###
try:
Config = ConfigParser.SafeConfigParser()
if Config.read("config.ini"):
# Load all sections and overwrite default configuration
for section in Config.sections():
config[section].update(dict(Config.items(section)))
# Environment variables
for section in config:
for key, value in config[section].items():
env = os.getenv(section.upper() + '_' + key.upper());
if env:
config[section][key] = type(value)(env)
# Do some checks
if (not int(config['cec']['enabled']) == 1) and \
(not int(config['ir']['enabled']) == 1):
raise Exception('IR and CEC are both disabled. Can\'t continue.')
except Exception as e:
print("ERROR: Could not configure:", str(e))
exit(1)
### Setup CEC ###
if int(config['cec']['enabled']) == 1:
print("Initialising CEC...")
try:
import cec
cec_config = cec.libcec_configuration()
cec_config.strDeviceName = "cec-ir-mqtt"
cec_config.bActivateSource = 0
cec_config.deviceTypes.Add(cec.CEC_DEVICE_TYPE_RECORDING_DEVICE)
cec_config.clientVersion = cec.LIBCEC_VERSION_CURRENT
cec_config.SetLogCallback(cec_on_message)
cec_client = cec.ICECAdapter.Create(cec_config)
if not cec_client.Open(config['cec']['port']):
raise Exception("Could not connect to cec adapter")
except Exception as e:
print("ERROR: Could not initialise CEC:", str(e))
exit(1)
### Setup IR ###
if int(config['ir']['enabled']) == 1:
print("Initialising IR...")
try:
import lirc
lirc.init("cec-ir-mqtt", "lircrc", blocking=False)
lirc_thread = threading.Thread(target=ir_listen_thread)
lirc_thread.start()
except Exception as e:
print("ERROR: Could not initialise IR:", str(e))
exit(1)
### Setup MQTT ###
print("Initialising MQTT...")
mqtt_client = mqtt.Client("cec-ir-mqtt")
mqtt_client.on_connect = mqtt_on_connect
mqtt_client.on_message = mqtt_on_message
if config['mqtt']['user']:
mqtt_client.username_pw_set(config['mqtt']['user'], password=config['mqtt']['password']);
if config['mqtt']['ssl']:
mqtt_client.tls_set(
ca_certs='/etc/ssl/cert.pem',
tls_version=ssl.PROTOCOL_TLSv1_2,
ciphers='ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384',
)
mqtt_client.connect(config['mqtt']['broker'], int(config['mqtt']['port']), 60)
mqtt_client.loop_start()
print("Starting main loop...")
while True:
if int(config['cec']['enabled']) == 1:
cec_refresh()
time.sleep(10)
except KeyboardInterrupt:
cleanup()
except RuntimeError:
cleanup()