-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
472 lines (371 loc) · 15.3 KB
/
main.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
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
from dataclasses import dataclass
import sys
import tkinter as tk
from threading import Thread, Lock, get_ident
import time
import alsaaudio # apt install python-alsaaudio, libasound2-dev ; pip3 pyalsaaudio
from random import randrange
from serial import Serial # pyserial
import mouse
import argparse
import subprocess
# https://stackoverflow.com/questions/57974532/why-cant-run-both-tkinter-mainloop-and-cefpython3-messageloop
# TODO slack notification with random room names?
# https://medium.com/@harvitronix/using-python-slack-for-quick-and-easy-mobile-push-notifications-5e5ff2b80aad
def bit_not(n, numbits=8):
return (1 << numbits) - 1 - n
@dataclass
class Config(object):
startfullscreen: bool
username: str
roomname: str
server: str
serialbaud: int
serialdevice: str
cache_path: str
useragent :str
ignoreserial: bool
serialretry: bool
@classmethod
def default(cls):
return cls(startfullscreen=False,
username='User_'+str(randrange(1000)),
roomname='tv_room'+str(randrange(1000)),
server='https://meet.jit.si/', # https://meet.scheible.it/
serialbaud=9600,
serialdevice='/dev/arduino_nano_clone', # HINT: set udev rule for device to be connected to same name every time
cache_path='cache',
useragent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36',
ignoreserial=True,
serialretry=True)
def get_jitsi_url(cfg: Config):
url = '%s%s' % (cfg.server, cfg.roomname)
print('URL: '+url)
params = '#userInfo.displayName="%s"&config.startWithAudioMuted=false&config.startWithVideoMuted=false' % (cfg.username)
return url+params
def _window_id_from_pid(pid):
# 'wmctrl - lp | grep 7678 | cut - d" " - f1'
proc_wmctrl = subprocess.Popen(['wmctrl', '-lp'], stdout=subprocess.PIPE)
proc_grep = subprocess.run(['grep', f'{pid}'], stdin=proc_wmctrl.stdout, stdout=subprocess.PIPE)
proc_wmctrl.stdout.close()
return proc_grep.stdout.decode('utf-8').split(' ')[0]
#return subprocess.run(['ls ', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
def _set_window_always_on_top(hex_wid,top):
if top:
subprocess.run(['wmctrl', '-ir',f'{hex_wid}','-b','add,above'])
else:
subprocess.run(['wmctrl', '-ir',f'{hex_wid}','-b','remove,above'])
class ComObj(object):
BUTTON_COUNT = 5
def __init__(self, cfg: Config):
self._iolock = Lock()
self._cfg = cfg
self._lights: int = 0
self._buttons: int = 0
self.signals = {'exit': False}
try:
self._ser = Serial(self._cfg.serialdevice, self._cfg.serialbaud, timeout=1)
except Exception as e:
if cfg.serialretry:
pass
else:
raise e
self._comthread = Thread(target=self._com_loop)
self._comthread.start()
self._echo_negated = True
def __del__(self):
try:
self.stop()
except:
pass
def _com_loop(self):
# incoming button states should have their left bits set to 110
# 110xxxxx
ex = None
# outgoing light states should have their left bits set to 101
# 101xxxxx
print('com_loop_start', get_ident())
while not self.signals['exit']:
#rx
try:
if self._ser.in_waiting:
rx_bytes = self._ser.read_all() # last
#print(rx_byte)
rx = rx_bytes[-1] # int.from_bytes(rx_byte, 'big')
if (rx & 0b11000000) == 0b11000000: # header?
self._iolock.acquire()
try:
self._buttons = rx & 0b00011111 # remove header
#tx only on rx:
tx = self._lights
if self._echo_negated:
tx = self._buttons ^ 0b11111111
#header
tx &= 0b00011111 # header-zero
tx |= 0b10100000 # header-value
tx_byte = tx.to_bytes(1, 'big')
self._ser.write(tx_byte)
finally:
self._iolock.release()
time.sleep(0.01) # @ 100Hz
except Exception as e:
if self._cfg.serialretry:
self._ser = None
print("No connection to buttons. Trying to connect ...")
count = 0
while (not self._ser) and (not self.signals['exit']):
count +=1
if count % 5 == 0: # retry every 5 seconds
try:
self._ser = Serial(self._cfg.serialdevice, self._cfg.serialbaud, timeout=1)
except:
pass
time.sleep(1) # @ 1Hz
else:
ex = e
break
try:
self._ser.write(b'/ff')
except:
pass
time.sleep(0.2)
print('com_loop_end')
if ex:
raise ex
def get_buttons(self):
res = 0
self._iolock.acquire()
try:
state_int = self._buttons
res = state_int
finally:
self._iolock.release()
return res
def set_lights(self, buttonlights_bitfield):
self._echo_negated = False # stop mirror tests
self._iolock.acquire()
try:
lights_int = buttonlights_bitfield
self._lights = lights_int
finally:
self._iolock.release()
def stop(self):
self.signals['exit'] = True
self._comthread.join()
class Fullscreen_Window:
def __init__(self, cfg: Config, comm_obj: ComObj):
self.comm_obj = comm_obj
self.cfg = cfg
self._last_hw_buttons = 0
self._mixer = alsaaudio.Mixer()
self.tk = tk.Tk()
self.tk.protocol('WM_DELETE_WINDOW', self.on_closing)
w, h = self.tk.winfo_screenwidth(), self.tk.winfo_screenheight()
self.tk.attributes('-zoomed', True) # This just maximizes it so we can see the window. It's nothing to do with fullscreen.
self.mainframe = tk.Frame(self.tk, height=h, width=w, bg='black')
self.frame2 = tk.Frame(self.tk, bg='black', height=100, width=w)
self.mainframe.pack(side='top', expand=True, fill='both')
self.frame2.pack(side='top', expand=False, fill='x')
photo = tk.PhotoImage(file="media/main.png")
photo_label = tk.Label(self.mainframe, image=photo, anchor="center")
photo_label.grid()
photo_label.image = photo
self.browser = None
self.browser_thread_signals = {"have_browser": False, "exit": False}
self.bt1 = tk.Button(self.frame2, text="VIDEO [F5]", command=lambda: self.button_handler(0), bg='green')
self.bt1.grid(row=0, column=4, sticky='news')
self.bt2 = tk.Button(self.frame2, text="STOP [F4]", command=lambda: self.button_handler(1), bg='red')
self.bt2.grid(row=0, column=3, sticky='news')
self.bt3 = tk.Button(self.frame2, text="LEISER(video) [F3]", command=lambda: self.button_handler(2), bg='yellow')
self.bt3.grid(row=0, column=2, sticky='news')
self.bt4 = tk.Button(self.frame2, text="LAUTER(video) [F2]", command=lambda: self.button_handler(3), bg='white')
self.bt4.grid(row=0, column=1, sticky='news')
self.bt5 = tk.Button(self.frame2, text="[BLAU] [F1]", command=lambda: self.button_handler(4), bg='blue', fg='white')
self.bt5.grid(row=0, column=0, sticky='news')
self.bt5 = tk.Button(self.frame2, text="Beenden [F10]", command=lambda: self.button_handler(10), bg='grey', fg='white')
self.bt5.grid(row=0, column=6, sticky='news')
self.lbl_vol = tk.Label(self.frame2, text="Lautstärke ...")
self.lbl_vol.grid(row=0, column=5, sticky='news')
self.lbl_room = tk.Label(self.frame2, text=" SERVER: %s RAUM: %s " % (cfg.server, cfg.roomname))
self.lbl_room.grid(row=0, column=7, sticky='news')
self.fullscreen_state = False
self.tk.bind("<F11>", self.toggle_fullscreen)
self.tk.bind("<Escape>", self.end_fullscreen)
self.tk.bind("<F1>", self._onF)
self.tk.bind("<F2>", self._onF)
self.tk.bind("<F3>", self._onF)
self.tk.bind("<F4>", self._onF)
self.tk.bind("<F5>", self._onF)
self.tk.bind("<F10>", self._onF)
if cfg.startfullscreen:
self.toggle_fullscreen()
#self._attach_cef_thread()
self._attach_ext_browser_thread()
self.tk.after(10, self._process) # @100Hz
def __del__(self):
try:
self.on_closing()
except:
pass
def on_closing(self):
self.browser_thread_signals["exit"] = True
self.browserthread.join()
self.tk.destroy()
print("exit")
def _onF(self, event=None):
if event:
k = event.keysym
if k == "F5":
self.button_handler(0)
if k == "F4":
self.button_handler(1)
if k == "F3":
self.button_handler(2)
if k == "F2":
self.button_handler(3)
if k == "F1":
self.button_handler(4)
if k == "F10":
self.button_handler(10)
def _attach_ext_browser_thread(self):
self.browserthread = Thread(target=self._ext_app_thread_loop)
self.browserthread.start()
def _process(self):
# process io and such, called @ ~100Hz
# TODO button texts according to app-state, instruction image when in base state
# check hw buttons:
hwbts_state = self._check_hw_buttons_and_trigger()
#update gui
self.lbl_vol['text'] = "Lautstärke: %s %%" % (str(self._mixer.getvolume()[0]))
# set lights
self._light_hw_buttons(hwbts_state)
#give us focus
self.frame2.focus_force() # keys only work if also the mouse is not in the browser .... :/
#repeat
self.tk.after(10, self._process) # @~100Hz
def _check_hw_buttons_and_trigger(self):
if not self.comm_obj:
return 0
hw_bts = self.comm_obj.get_buttons()
hw_trigger = 0
# check if newly pressed, then trigger
# trigger once on rising (e.g. onpress)
hw_trigger = bit_not(self._last_hw_buttons) & hw_bts
# TODO special behaviour when multiple pressed (for longer)?
# restart? update? reboot?
for i in range(self.comm_obj.BUTTON_COUNT):
if hw_trigger & (1 << i):
self.button_handler(i)
self._last_hw_buttons = hw_bts
return hw_bts # current state
def _light_hw_buttons(self, light_these_anyway):
if not self.comm_obj:
return
state_light = 0
# todo define states together with button functions and visuals
# green light when 'in calls'
# for now:
if self.browser:
state_light |= 1 << 0 # 0-> green
# and additionally:
state_light |= light_these_anyway
self.comm_obj.set_lights(state_light)
def button_handler(self, button_id):
# print(button_id)
# TODO group with current state the app is in rather than buttons
if button_id == 0: # green
self.browser_thread_signals["have_browser"] = True
if button_id == 1: # red
self.browser_thread_signals["have_browser"] = False
if button_id == 2: # yellow (-)
if self.browser:
v = self._mixer.getvolume()[0]
v -= 10
v = max(v, 0)
self._mixer.setvolume(v)
if button_id == 3: # white (+)
if self.browser:
v = self._mixer.getvolume()[0]
v += 10
v = min(v, 100)
self._mixer.setvolume(v)
if button_id == 10: # grey,exit,nonphysical
self.on_closing()
def _ext_app_thread_loop(self):
print("ext_loop ", get_ident())
while not self.browser_thread_signals["exit"]:
if self.browser_thread_signals["have_browser"]:
if not self.browser:
# setup
browser = "chromium-browser"
app = f"--app={get_jitsi_url(self.cfg)}"
size = f"--window-size={self.mainframe.winfo_width()},{self.mainframe.winfo_height()}"
pos = f"--window-position=0,0"
self.browser = subprocess.Popen([browser, app, size, pos])
print("browser_start")
# bring to top
_set_window_always_on_top(_window_id_from_pid(self.browser.pid), True) # this does not work a few times after starting the browser until there is a window
time.sleep(0.1) # @10Hz otherwise will take 100% cpu. also there is basically nothing to do here anymore after chrome runs in its own process
else:
if self.browser:
# tear down
self.browser.terminate()
self.browser = None
print("browser_end")
time.sleep(0.1) # @10Hz otherwise will take 100% cpu
if self.browser:
# tear down
self.browser.terminate()
self.browser = None
print("browser_end")
def toggle_fullscreen(self, event=None):
self.fullscreen_state = not self.fullscreen_state # Just toggling the boolean
self.tk.attributes("-fullscreen", self.fullscreen_state)
return "break"
def end_fullscreen(self, event=None):
self.fullscreen_state = False
self.tk.attributes("-fullscreen", False)
return "break"
def setup_window(cfg: Config, com: ComObj):
window = Fullscreen_Window(cfg, com)
return window
def main():
# TODO more params / write/load config file
cfg = Config.default()
cfg.startfullscreen = False
parser = argparse.ArgumentParser(description="TV-Video-Call-Interface")
parser.add_argument("--server", help="Use this server", type=str, default="")
parser.add_argument("--room", help="Use this room", type=str, default="")
parser.add_argument("--user", help="Use this username", type=str, default="")
args = None
try:
args = parser.parse_args()
except:
parser.print_help()
exit(0)
print("-------------------------------------------")
print("main ", get_ident())
if args.server:
cfg.server = args.server
if args.room:
cfg.roomname = args.room
if args.user:
cfg.username = args.user
com = None
try:
com = ComObj(cfg)
except Exception as e:
print("Cannot connect to serial buttons @ %s" % (cfg.serialdevice))
if cfg.ignoreserial:
com = None
else:
print(e)
exit(-1)
#move mouse to bottom right corner (e.g. far away)
mouse.move(10000, 10000)
w = setup_window(cfg, com)
w.tk.mainloop()
if com:
com.stop()
if __name__ == '__main__':
main()