-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdvi_matrix_control.py
375 lines (336 loc) · 13.1 KB
/
dvi_matrix_control.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
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
#!/usr/bin/env python
"""
Simple command-line based controller application for Lightware and Extron
DVI or HDMI crossbar video switches. Supports up to 10 macros.
"""
from __future__ import print_function
import sys, os, time, threading, socket
DEFAULT_CONFIGFILE = "dvi_matrix_control.conf"
MAX_CONNECT_TIMEOUT = 1.0
MAX_COMMAND_TIMEOUT = 0.1
POLL_INTERVAL = 0.05
try: # Python 2/3 compatibility
input = raw_input
except:
pass
###############################################################################
class ProtocolBase(object):
default_ip = [192, 168, 254, 254]
default_port = 0
default_baud = 9600
default_bits = 801
def __init__(self): self.result = None
def connect(self): pass
def receive(self, line): pass
def switch_single(self, pin, pout): pass
def switch_multi(self, ties):
for pin, pout in ties:
self.switch_single(pin, pout)
def notify_success(self): self.result = True
def notify_error(self): self.result = False
def clear_status(self): self.result = None
class LightwareProtocol(ProtocolBase):
"Lightware LW1 Protocol"
default_port = 10001
def connect(self):
self.notify_success()
def receive(self, line):
if line.startswith(b'(') and line.endswith(b')'):
self.notify_success()
def switch_single(self, pin, pout):
return b'{%d@%d}\r\n' % (pin, pout)
class ExtronProtocol(ProtocolBase):
"Extron DXP SIS Protocol"
default_port = 23
def connect(self):
self.notify_success()
def receive(self, line):
if line.lower().startswith((b"login ", b"qik", b"out")):
self.notify_success()
def switch_single(self, pin, pout):
return b'%d*%d!' % (pin, pout)
def switch_multi(self, ties):
return b'\x1b+Q' + b''.join(b'%d*%d!' % (pin, pout) for pin, pout in ties) + b'\r\n'
Protocols = {
1: LightwareProtocol,
2: ExtronProtocol,
}
###############################################################################
class UnsuitableConnectionParameters(ValueError):
pass
class ConnectionBase(object):
def __init__(self, proto_id):
try:
proto = Protocols[proto_id]
except KeyError:
raise UnsuitableConnectionParameters("invalid protocol")
self.proto = proto()
self.conn = None
self.receiver = None
self.cancel = False
def receiver_thread(self):
buf = b''
while not self.cancel:
try:
buf += self.do_receive(self.conn).replace(b'\r', b'\n')
except EnvironmentError:
pass
while b'\n' in buf:
line, buf = buf.split(b'\n', 1)
if line:
self.proto.receive(line)
def connect(self):
if self.conn:
return
t1 = time.time() + MAX_CONNECT_TIMEOUT
try:
self.conn = self.do_connect(MAX_CONNECT_TIMEOUT)
except EnvironmentError:
self.conn = None
return
self.cancel = False
self.receiver = threading.Thread(target=self.receiver_thread, name="Receiver")
self.receiver.daemon = True
self.receiver.start()
self.proto.clear_status()
self.proto.connect()
while (self.proto.result is None) and (time.time() < t1):
time.sleep(POLL_INTERVAL)
return self.proto.result
def disconnect(self):
if not self.conn:
return
self.cancel = True
self.do_disconnect(self.conn)
self.receiver.join(MAX_CONNECT_TIMEOUT)
self.receiver = None
self.conn = None
def send(self, data, allow_reconnect=True, wait=True):
if not(self.conn):
res = self.connect()
if self.conn and not res:
print("! reconnect didn't succeed, trying to send anyway")
if not self.conn:
print("! reconnect attempt failed, can't send command")
return
self.proto.clear_status()
try:
part = data
while part:
n = self.do_send(self.conn, part)
part = part[n:]
self.do_flush(self.conn)
except EnvironmentError:
if allow_reconnect:
print("! connection lost, reconnecting and retrying")
self.disconnect()
return self.send(data, allow_reconnect=False, wait=wait)
if wait:
t1 = time.time() + MAX_COMMAND_TIMEOUT
while (self.proto.result is None) and (time.time() < t1):
time.sleep(POLL_INTERVAL)
if self.proto.result is None:
print("! no reaction from device, reconnecting and retrying")
self.disconnect()
return self.send(data, allow_reconnect=False, wait=wait)
if not self.proto.result:
print("! device reports error")
def do_flush(self, conn):
pass
class TCPConnection(ConnectionBase):
"[192.168.x.y[,port]] - TCP connection"
def __init__(self, proto, *params):
ConnectionBase.__init__(self, proto)
if not(len(params) in (0, 4, 5)) \
or ((len(params) >= 4) and not(all(0 <= p < 256 for p in params[:4]))) \
or ((len(params) == 5) and not(0 < params[4] < 65536)):
raise UnsuitableConnectionParameters()
self.ip = '.'.join(map(str, (self.proto.default_ip if (len(params) < 4) else tuple(params[:4]))))
self.port = self.proto.default_port if (len(params) < 5) else params[4]
print("* connecting to {}:{}".format(self.ip, self.port))
def do_connect(self, timeout):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
s.settimeout(timeout)
s.connect((self.ip, self.port))
return s
def do_disconnect(self, s):
try:
s.shutdown(socket.SHUT_RDWR)
except EnvironmentError as e:
pass
s.close()
def do_receive(self, s):
return s.recv(1024)
def do_send(self, s, data):
return s.send(data)
class SerialConnection(ConnectionBase):
"port[,baud[,<bits><parity><stop>]] - serial connection"
def __init__(self, proto, *params):
ConnectionBase.__init__(self, proto)
if not(len(params) in (1, 2, 3, 5)) \
or ((len(params) >= 2) and (params[1] < 300)) \
or ((len(params) == 3) and not(700 < params[2] < 822)) \
or ((len(params) > 3) and not(7 <= params[2] <= 8)) \
or ((len(params) > 3) and not(0 <= params[3] <= 2)) \
or ((len(params) > 3) and not(0 <= params[4] <= 2)):
raise UnsuitableConnectionParameters()
self.port = params[0]
self.baud = self.proto.default_baud if (len(params) < 2) else params[1]
if len(params) > 3:
self.bits, self.parity, self.stop = params[2:5]
else:
bits = self.proto.default_bits if (len(params) < 3) else params[2]
self.bits = (bits / 100) % 10
self.parity = (bits / 10) % 10
self.stop = bits % 10
Connections = [TCPConnection]
try:
import serial
Connections.append(SerialConnection)
except ImportError:
pass
###############################################################################
class DVIMatrixController(object):
def __init__(self, configfile=None):
self.configfile = configfile or DEFAULT_CONFIGFILE
self.macros = {}
self.connection_config = []
self.config_lock = False
self.conn = None
def save_config(self):
if self.config_lock:
return
try:
with open(self.configfile, "w") as f:
print("//" + '.'.join(map(str, self.connection_config)), file=f)
for k in sorted(self.macros):
print("*{}*{}".format(k, ','.join(self.macros[k])), file=f)
except EnvironmentError as e:
print("error: failed to write configuration file '{}':".format(self.configfile, e))
def load_config(self):
self.config_lock = True
try:
with open(self.configfile) as f:
print("----- loading and executing configuration file ('{}') -----".format(self.configfile))
for cmd in f:
self.handle_cmd(cmd, echo="+ ", verbose=False)
print("----- configuration file loaded -----")
except EnvironmentError as e:
pass # no error if config file doesn't exist
self.config_lock = False
def handle_cmd(self, cmd, echo=None, verbose=True):
cmd = cmd.split('#', 1)[0].strip().replace(',', '.').lower()
if not cmd:
return
if echo:
print(echo + cmd)
if False:
pass # elif chain follows
# handle assignment command
elif cmd.replace('.', '').isalnum():
# step 1: resolve macros
subcmds = []
for subcmd in cmd.split('.'):
subcmd = subcmd
if subcmd in self.macros:
subcmds.extend(self.macros[subcmd])
else:
subcmds.append(subcmd)
# step 2: resolve output assignments
assign = {}
for subcmd in subcmds:
if len(subcmd) < 2:
print("warning: ignoring incomplete subcommand '{}'".format(subcmd))
continue
subcmd = [int(c, 36) for c in subcmd]
for out in subcmd[1:]:
assign[out] = subcmd[0]
assign = [(i,o) for o,i in assign.items()]
# step 3: send command
if self.conn and assign:
if len(assign) > 1:
self.conn.send(self.conn.proto.switch_multi(assign))
else:
self.conn.send(self.conn.proto.switch_single(*assign[0]))
# handle "store macro" command, e.g. *1*34,56
elif (len(cmd) > 2) \
and (cmd[0] == '*') \
and cmd[1].isalnum() \
and (cmd[2] == '*') \
and ((len(cmd) <= 3) or cmd[3:].replace('.', '').isalnum()):
name = cmd[1]
value = cmd[3:].split('.')
if value and value[0]:
self.macros[name] = value
if verbose: print("stored macro '{}':".format(name), ','.join(value))
elif name in self.macros:
del self.macros[name]
if verbose: print("deleted macro '{}'".format(name))
else:
if verbose: print("macro '{}' is not defined".format(name))
self.save_config()
# handle "set connection" command, e.g. //192.168.1.2.10001 or //0.9600.801
elif cmd.startswith('//') \
and ((len(cmd) < 3) or cmd[2:].replace('.', '').isdigit()):
params = cmd[2:].split('.')
if params and params[0]:
params = list(map(int, params))
else:
params = []
if params:
self.connection_config = params
self.save_config()
if self.conn:
self.conn.disconnect()
self.conn = None
for c in Connections:
try:
self.conn = c(*params)
except UnsuitableConnectionParameters:
pass
need_help = not(self.conn)
if self.conn:
res = self.conn.connect()
if res:
print("! connection established")
else:
print("! connection failed")
else:
need_help = True
if need_help:
print("connection types:")
for c in Connections:
print(" - //proto," + c.__doc__)
print("protocols:")
for k in sorted(Protocols):
print(" -", k, "-", Protocols[k].__doc__)
# invalid command
else:
print("invalid command", repr(cmd))
def interactive(self):
print("----- entering interactive command mode -----")
print("""
Quick tutorial:
- 12 = tie input 1 to output 2
- 345 = tie input 3 to outputs 4 and 5
- 12,345 = do both above commands at once
- *7*12,345 = store these commands as macro '7'
- 7 = recall macro '7'
- // = show help about connect command
- //2,10.0.1.2 = connect to Extron switch at IP 10.0.1.2 (default port)
Hints:
- dots ('.') and commas (',') can be used interchangeably, even in IP addrs.
- config file is saved after every "store macro" and "connect" command
""".strip())
while True:
try:
self.handle_cmd(input("> "))
except (IOError, EOFError, KeyboardInterrupt) as e:
print(type(e).__name__)
print("----- leaving interactive command mode -----")
return
###############################################################################
if __name__ == "__main__":
ctl = DVIMatrixController()
ctl.load_config()
ctl.interactive()