-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
executable file
·1093 lines (881 loc) · 34.4 KB
/
controller.py
File metadata and controls
executable file
·1093 lines (881 loc) · 34.4 KB
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import requests
import asyncio
import configargparse
from flask import Flask, send_file
from hnapi import HnApi
import html
import json
import logging
import os
from pathlib import Path
import random
import socket
import stat
import subprocess
from subprocess import Popen
import signal
import sys
import time
import threading
sys.path.append(os.path.abspath("/usr/local/src/python-wayland"))
import draw as view
import wayland.protocol
from wayland.client import MakeDisplay
from wayland.utils import AnonymousFile
from zeroconf import IPVersion, ServiceInfo, Zeroconf
wserver = Flask(__name__)
dependencies = []
stream_sources = ["static-images", "v4l2", "vnc-browser"]
cmds = {"clock" : "humanbeans_clock",
"image_viewer" : "imv",
"media_player" : "mpv",
"screenshot" : "grim"}
@wserver.route("/")
def info():
return True
# Readiness
@wserver.route('/healthy')
def healthy():
return "OK"
# Liveness
@wserver.route('/healthz')
def healthz():
return probe_liveness()
@wserver.route("/display")
def display():
data = {}
data["name"] = "display-0"
data["os_release"] = "iss-display"
data['listen_address'] = display.address
data['listen_port'] = display.port
data['res_x'] = display.res_x
data['res_y'] = display.res_y
data['playlist'] = playlist.playlist
data['uris'] = playlist.uris
data['streams'] = stream.streams
#data['uptime'] = System.uptime()
json_data = json.dumps(data)
return json_data
def probe_liveness():
return "OK"
@wserver.route("/screenshot")
def display_screenshot():
fn = display.screenshot()
if not os.path.isfile(fn):
logging.error("screenshot: File {} does not exist".format(fn))
#return False
return send_file(fn, mimetype='image/png')
def which(cmd):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None
def download_file(url, path):
logging.info("Downloading: " + url)
cmd = ['curl', '-LO', '--create-dirs', '--output-dir', path, url]
Popen(cmd,
env=env,
start_new_session=True,
close_fds=True,
encoding='utf8')
return True
class System:
def list_processes(limit=0):
if limit > 0:
cmd = ['ps', 'ux', '--ppid', '2', '-p', '2', '--deselect', '|', 'head', '-n', limit]
else:
cmd = ['ps', 'ux', '--ppid', '2', '-p', '2', '--deselect']
# Processes without kernel threads
ps = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
encoding="utf8").communicate()[0]
return ps
def net_local_iface_address(probe_ip):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((probe_ip, 80))
return s.getsockname()[0]
def uptime():
#return time.time() - psutil.boot_time()
return False
class Zeroconf_service:
def __init__(self,
name_prefix,
service_type,
hostname,
listen_address,
listen_port,
properties):
ip_version = IPVersion.V6Only
self.service_type = service_type
self.service_name = name_prefix + "-" + \
hostname + "." + \
self.service_type
# The zeroconf service data to publish on the network
self.zc_service = ServiceInfo(
self.service_type,
self.service_name,
addresses=[socket.inet_pton(socket.AF_INET,
listen_address)],
port=int(listen_port),
properties=properties,
server=hostname + ".local.",
)
self.zc = Zeroconf(ip_version=ip_version)
def zc_register_service(self):
self.zc.register_service(self.zc_service)
return True
def zc_unregister_service(self):
self.zc.unregister_service(self.zc_service)
zc.close()
return True
class Theme:
def __init__(self, name="default"):
self.name = name
self.img_bg = "background.jpg"
self.font = ""
self.font_face = "Monospace"
class Playlist:
def __init__(self, uris, default_play_time_s, theme, location=None):
self.download_path = "/tmp/"
self.location = location
self.default_play_time_s = default_play_time_s
self.news = None
self.theme = theme
self.img_bg = "themes/" + theme.name + "/background.jpg"
self.playlist = list()
self.playlist = self.create(uris)
self.uris = self.get_uris()
def create(self, uris):
n = 0
playlist = list()
for uri in uris:
item = {}
n += 1
if uri.endswith(".m3u8"):
item["num"] = n
item["uri"] = uri
item["player"] = "mediaplayer"
item["play_time_s"] = self.default_play_time_s
elif uri.startswith("https://"):
item["num"] = n
item["uri"] = uri
item["player"] = "browser"
item["play_time_s"] = self.default_play_time_s
elif uri.startswith("iss-clock://"):
item["num"] = n
item["uri"] = uri
item["player"] = "clock"
item["play_time_s"] = self.default_play_time_s
elif uri.startswith("iss-news://"):
self.news = News()
item["num"] = n
item["uri"] = uri
item["player"] = "news"
item["play_time_s"] = self.default_play_time_s
elif uri.startswith("iss-system://"):
item["num"] = n
item["uri"] = uri
item["player"] = "system"
item["play_time_s"] = self.default_play_time_s
elif uri.startswith("iss-weather://"):
self.weather = Weather(self.location)
item["num"] = n
item["uri"] = uri
item["player"] = "weather"
item["play_time_s"] = self.default_play_time_s
elif uri.endswith(".svg"):
download_file(uri.strip(), self.download_path)
file = uri.split("/")
item["num"] = n
item["uri"] = "file:///" + self.download_path + file[-1]
item["player"] = "imageviewer"
item["play_time_s"] = self.default_play_time_s
elif uri.endswith(".jpg"):
item["num"] = n
item["uri"] = uri
item["player"] = "imageviewer"
item["play_time_s"] = self.default_play_time_s
# Append if we found a valid playlist item
if "num" in item:
playlist.append(item)
return playlist
def get_uris(self):
for item in self.playlist:
uris.append(item["uri"])
return uris
def start_player(self):
threads = list()
for item in self.playlist:
if item["player"] == "browser":
# start_browser() wants a list
# but we want to start an instance for each URL
urls = list()
urls.append(item["uri"])
x = threading.Thread(target=self.start_browser, args=(urls,))
elif item["player"] == "clock":
x = threading.Thread(target=self.start_clock, args=())
elif item["player"] == "imageviewer":
x = threading.Thread(target=self.start_image_view, args=(item["uri"],))
elif item["player"] == "news":
x = threading.Thread(target=self.start_news_view, args=(self.news, self.img_bg))
elif item["player"] == "system":
x = threading.Thread(target=self.start_system_view, args=())
elif item["player"] == "weather":
x = threading.Thread(target=self.start_weather_view, args=(self.weather, self.img_bg))
x.start()
if not x.is_alive():
logging.error("Failed to start {}".format(item["player"]))
else:
threads.append(x)
return threads
def start_browser(self, urls):
cmd = ['webdriver_util.py']
for url in urls:
cmd.append("--url")
cmd.append(url)
Popen(cmd,
env=env,
start_new_session=True,
close_fds=True,
encoding='utf8')
return True
def start_clock(self):
logging.info("Starting clock")
cmd = [cmds["clock"]]
p = Popen(cmd,
env=env,
start_new_session=True,
close_fds=True)
if p.communicate()[0] != 0:
return False
return True
def start_image_viewer(self, file):
logging.info("Starting image viewer with file: " + file)
cmd = [cmds["image_viewer"], file]
Popen(cmd,
env=env,
start_new_session=True,
close_fds=True,
encoding='utf8')
return True
def start_mediaplayer(self, url):
logging.info("Starting media player with stream: " + url)
cmd = [cmds["media_player"], url]
Popen(cmd,
env=env,
start_new_session=True,
close_fds=True,
encoding='utf8')
return True
def start_sys_view(self):
texts = list()
texts.append(System.list_processes(23))
view = Wayland_view(display.res_x, display.res_y, len(texts), theme)
view.s_objects[0]["font_size"] = 14
view.s_objects[0]["alignment"] = "left"
view.show_text(texts)
def start_weather_view(self, weather, img_bg):
texts = list()
data = weather.current_weather()
texts.append(data["current_condition"][0]["temp_C"] + "°C")
texts.append(data["current_condition"][0]["weatherDesc"][0]["value"] + " " + \
data["current_condition"][0]["windspeedKmph"] + " km/h")
texts.append(data["nearest_area"][0]["areaName"][0]["value"])
view = Wayland_view(display.res_x, display.res_y, len(texts), theme)
view.s_objects[0]["font_size"] = 80
view.s_objects[0]["alignment"] = "left"
view.s_objects[1]["font_size"] = 40
view.s_objects[1]["alignment"] = "left"
view.s_objects[2]["font_size"] = 20
view.s_objects[2]["alignment"] = "left"
view.show_text(texts, img_bg)
def start_news_view(self, news, img_bg):
texts = list()
item = news.news_item()
texts.append("[HN]")
texts.append(item["title"])
texts.append(item["url"])
logging.info("News: " + item["url"])
view = Wayland_view(display.res_x, display.res_y, len(texts), theme)
view.s_objects[0]["font_size"] = 30
view.s_objects[1]["font_size"] = 60
view.s_objects[2]["font_size"] = 30
view.show_text(texts, img_bg)
def start_image_view(self, file):
view = Wayland_view(display.res_x, display.res_y, 1, theme)
view.show_image(file)
class Stream():
def __init__(self, stream_source):
self.streams = list()
if stream_source == "v4l2":
# Start streaming
logging.info("Setting up source")
self.stream_create_v4l2_src(stream_source_device)
logging.info("Setting up stream")
time.sleep(3)
self.stream_v4l2_ffmpeg()
#gst = self.stream_setup_gstreamer(stream_source,
# stream_source_device,
# local_ip,
# listen_port)
#gst.stdin.close()
#gst.wait()
elif stream_source == "static-images":
gst = self.stream_setup_gstreamer(stream_source,
stream_source_device,
local_ip,
listen_port)
self.gst_stream_images(gst, img_path)
gst.stdin.close()
gst.wait()
def stream_setup_gstreamer(self, stream_source, source_device, ip, port):
if stream_source == "static-images":
gstreamer = subprocess.Popen([
'gst-launch-1.0', '-v', '-e',
'fdsrc',
'!', 'pngdec',
'!', 'videoconvert',
'!', 'videorate',
'!', 'video/x-raw,framerate=25/2',
'!', 'theoraenc',
'!', 'oggmux',
'!', 'tcpserversink', 'host=' + ip + '', 'port=' + str(port) + ''
], stdin=subprocess.PIPE)
elif stream_source == "v4l2":
gstreamer = subprocess.Popen([
'gst-launch-1.0', '-v', '-e',
'v4l2src', 'device=' + source_device,
'!', 'videorate',
'!', 'video/x-raw,framerate=25/2',
'!', 'queue',
'!', 'tcpserversink', 'host=' + ip + '', 'port=' + str(port) + ''
], stdin=subprocess.PIPE)
return gstreamer
def gst_stream_images(self, gstreamer, img_path, debug=False):
t0 = int(round(time.time() * 1000))
n = -1
while True:
#filename = img_path + '/image_' + str(0).zfill(4) + '.png'
filename = '/tmp/screenshot.png'
t1 = int(round(time.time() * 1000))
logging.debug(filename + ": " + str(t1 - t0) + " ms")
t0 = t1
f = Path(filename)
if not f.is_file():
logging.info("Startup: No file yet to stream")
logging.info("Startup: Waiting..")
time.sleep(3)
else:
if -1 == n:
logging.info("Found first file, starting stream")
n = 0
with open(filename, 'rb') as f:
content = f.read()
gstreamer.stdin.write(content)
time.sleep(0.1)
if 10 == n:
n = 0
else:
n += 1
def stream_create_v4l2_src(self, device):
# Check if device is an existing character device
if not stat.S_ISCHR(os.lstat(device)[stat.ST_MODE]):
logging.error(device + " does not exist, aborting..")
sys.exit(1)
# Create v4l2 recording of screen
logging.info("Creating v4l2 stream with device: " + device)
p = subprocess.Popen([
'wf-recorder',
'--muxer=v4l2',
'--file=' + device,
],
stdin=subprocess.PIPE,
start_new_session=True,
close_fds=False,
encoding='utf8')
# Handle wf-recorder prompt for overwriting the file
p.stdin.write('Y\n')
p.stdin.flush()
return True
def stream_v4l2_ffmpeg(self):
ffmpeg = subprocess.Popen([
'ffmpeg', '-f', 'v4l2', '-i', '/dev/video0',
'-codec', 'copy',
'-f', 'mpegts', 'udp:0.0.0.0:6000'
])
class News:
def __init__(self):
self.news = []
self.fetch_top_news(10)
def fetch_top_news(self, nitems):
n = 0
logging.info("Fetching News")
con = HnApi()
top = con.get_top()
for tnews in top:
if n == nitems:
break
self.news.append(con.get_item(tnews))
n += 1
# news_item returns a single news text
# from the previously fetched ones
def news_item(self):
n = {"title": "",
"url": ""}
n["title"] = self.news[0].get('title')
n["url"] = self.news[0].get('url')
self.news.pop(0)
return n
class Weather:
def __init__(self, location):
self.location = location
self.weather = self.fetch_weather()
def fetch_weather(self):
url = "https://wttr.in/{}?format=j1".format(self.location)
logging.info("Fetching weather for {} at {}"\
.format(self.location, url))
cmd = ['curl ' + url]
p = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf8")
#data = p.communicate()[0]
try:
data = requests.get(url, timeout=10)
data = data.content
except ReadTimeout as e:
logging.error("weather: Timeout for request")
if not data:
logging.error("Failed to fetch weather data")
try:
data = json.loads(data)
except ValueError as e:
logging.error("weather: Failed to decode data")
logging.error(e)
data = {}
sys.exit(1)
return data
def current_weather(self):
return self.weather
class Wayland_view:
def __init__(self, res_x, res_y, num_objects, theme):
# Load the main Wayland protocol.
wp_base = wayland.protocol.Protocol("/usr/share/wayland/wayland.xml")
wp_xdg_shell = wayland.protocol.Protocol("/usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml")
try:
self.conn = view.WaylandConnection(wp_base, wp_xdg_shell)
except FileNotFoundError as e:
if e.errno == 2:
print("Unable to connect to the compositor - "
"is one running?")
sys.exit(1)
raise
self.window = {}
self.window["res_x"] = res_x
self.window["res_y"] = res_y
self.window["title"] = "News"
s_object = {"alignment": "center",
"offset_x": 10,
"offset_y": 10,
"bg_alpha": 1,
"bg_colour_r": 7,
"bg_colour_g": 59,
"bg_colour_b": 76,
"font": theme.font,
"font_face": theme.font_face,
"font_size": 60,
"font_colour_r": 0,
"font_colour_g": 0,
"font_colour_b": 0,
"file": "",
"text": list()}
self.s_objects = list()
for n in range(0, num_objects):
logging.info("view: Appending drawing object")
self.s_objects.append(s_object.copy())
def create_window(self, w):
view.eventloop()
w.close()
self.conn.display.roundtrip()
self.conn.disconnect()
logging.info("Exiting wayland view: {}".format(view.shutdowncode))
def show_text(self, texts, img_bg=False, fullscreen=False):
if img_bg:
self.s_objects[0]["file"] = img_bg
logging.info("view: Have {} text blocks".format(len(texts)))
n = 0
for text in texts:
logging.debug(text)
self.s_objects[n]["text"] = html.escape(text)
n += 1
w = view.Window(self.conn,
self.window,
self.s_objects,
redraw=view.draw_img_with_text,
fullscreen=fullscreen,
class_="iss-view")
self.create_window(w)
def show_image(self, img_file, fullscreen=False):
self.s_objects[0]["file"] = file
self.s_objects[0]["bg_alpha"] = 0
w = view.Window(self.conn,
self.window,
self.s_objects,
redraw=view.draw_img_with_text,
fullscreen=fullscreen,
class_="iss-view")
self.create_window(w)
class Display:
def __init__(self, address, port, res_x=1280, res_y=1024):
self.address = address
self.port = port
logging.info("Resolution: {}x{}".format(res_x, res_y))
self.res_x = res_x
self.res_y = res_y
self.start_time = time.time()
self.switching_windows = list()
self.window_blacklist = list()
self.screenshot_path = "/tmp"
self.screenshot_file = "screenshot.png"
self.socket_path = self.get_socket_path()
logging.info("Resolution: {} x {}"
.format(self.res_x, self.res_y))
# We do not want to handle existing windows,
# so we put their IDs on a blacklist
existing_windows = self.get_windows()
for win in existing_windows:
self.window_blacklist.append(win["id"])
logging.info("Blacklisted {} windows".format(len(self.window_blacklist)))
self.x = threading.Thread(target=self.focus_next_window, args=(3,))
self.x.start()
def get_socket_path(self):
cmd = ['/usr/bin/sway', '--get-socketpath']
p = subprocess.Popen(cmd,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf8")
path = p.communicate()
path = path[0].rstrip()
#path = "/tmp/sway.sock"
return path
def get_windows_whitelist(self):
windows = self.get_windows(self.window_blacklist)
logging.info("display: {} windows in whitelist".format(len(windows)))
return windows
def get_windows(self, blacklist=None):
cmd="swaymsg -s {} -t get_tree".format(self.socket_path)
windows = []
p = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
data = json.loads(p.communicate()[0])
for output in data['nodes']:
if output.get('type') == 'output':
workspaces = output.get('nodes')
for ws in workspaces:
if ws.get('type') == 'workspace':
windows += self.workspace_nodes(ws)
if blacklist:
windows_whitelist = windows.copy()
for win in windows:
if win["id"] in blacklist:
windows_whitelist.pop()
return windows_whitelist
return windows
# Extracts all windows from sway workspace json
def workspace_nodes(self, workspace):
windows = []
floating_nodes = workspace.get('floating_nodes')
for floating_node in floating_nodes:
windows.append(floating_node)
nodes = workspace.get('nodes')
for node in nodes:
# Leaf node
if len(node.get('nodes')) == 0:
windows.append(node)
# Nested node
else:
for inner_node in node.get('nodes'):
nodes.append(inner_node)
return windows
def active_window():
cmd = 'swaymsg -s {} -t get_tree) | jq ".. | select(.type?) | select(.focused==true).id"'.format(self.socket_path)
def focus_next_window(self, t_focus_s):
while True:
time.sleep(t_focus_s)
if len(self.switching_windows) == 0:
self.switching_windows = self.get_windows_whitelist()
if len(self.switching_windows) == 0:
logging.warning("display: Expected windows to display but there is none")
continue
next_window = self.switching_windows.pop()
logging.info("display: Switching focus to: ".format(next_window["id"]))
cmd = "swaymsg -s {} [con_id={}] focus".format(self.socket_path, next_window["id"])
p = subprocess.Popen(cmd, shell=True)
p.communicate()[0]
async def fullscreen_next_window(self):
await asyncio.sleep(random.random() * 3)
t = round(time.time() - self.start_time, 1)
logging.info("Finished task: {}".format(t))
if len(self.switching_windows) == 0:
self.switching_windows = self.get_windows_whitelist()
if len(self.switching_windows) == 0:
logging.warning("display: Expected windows to display but there is none")
return
next_window = self.switching_windows.pop()
logging.info("display: Switching focus to: ".format(next_window["id"]))
cmd = "swaymsg -s {} [con_id={}] fullscreen".format(self.socket_path, next_window["id"])
p = subprocess.Popen(cmd,
shell=True)
p.communicate()[0]
async def task_scheduler(self, interval_s, interval_function):
while True:
logging.info("Starting periodic function: {}"\
.format(round(time.time() - self.start_time, 1)))
await asyncio.gather(
asyncio.sleep(interval_s),
interval_function(),
)
def switch_workspace(self):
cmd = "swaymsg -s {} workspace {}".format(self.socket_path, next_ws)
p = subprocess.Popen(cmd,
shell=True,
encoding="utf8")
res = p.communicate()[0]
def screenshot(self):
fn = self.screenshot_path + "/" + self.screenshot_file
logging.info("Saving screenshot to {}".format(fn))
cmd = [cmds["screenshot"],
fn]
p = Popen(cmd,
env=env,
start_new_session=True,
close_fds=True)
return fn
class Iss:
def __init__(self, threads):
self.threads = threads
if __name__ == "__main__":
parser = configargparse.ArgParser(description="")
parser.add_argument('--debug',
dest='debug',
env_var='DEBUG',
help="Show debug output",
type=bool,
default=False)
parser.add_argument('--uri',
dest='uris',
env_var='URI',
help="The URIs to open, can be supplied multiple times",
type=str,
action='append',
required=True)
parser.add_argument('--stream_source',
dest='stream_source',
env_var='STREAM_SOURCE',
help="The source of the stream",
type=str,
default="")
parser.add_argument('--stream-source-device',
dest='stream_source_device',
env_var='STREAM_SOURCE_DEVICE',
help="The source device to stream from",
type=str,
default="/dev/video0")
parser.add_argument('--listen-address',
dest='listen_address',
env_var='LISTEN_ADDRESS',
help="The address to listen on",
type=str,
default="0.0.0.0")
parser.add_argument('--listen-port',
dest='listen_port',
env_var='LISTEN_PORT',
help="The port to listen on",
type=int,
default=6000)
parser.add_argument('--img-path',
dest='img_path',
env_var='IMAGES_PATH',
help="Path to image files",
type=str,
default="/tmp/screenshots/")
parser.add_argument('--location',
dest='location',
env_var='LOCATION',
help="The location to gather data like weather for",
type=str,
default="Berlin")
parser.add_argument('--logfile',
dest='logfile',
env_var='LOGFILE',
help="Path to optional logfile",
type=str)
parser.add_argument('--loglevel',
dest='loglevel',
env_var='LOGLEVEL',
help="Loglevel, default: INFO",
type=str,
default='INFO')
parser.add_argument('--probe-ip',
dest='probe_ip',
env_var='PROBE_IP',
help="The address to probe for",
type=str,
default="9.9.9.9")
parser.add_argument('--theme',
dest='theme_name',
env_var='THEME',
help="The theme to use",
type=str,
default="default")
parser.add_argument('--zeroconf-publish-service',
dest='zeroconf_publish_service',
env_var='ZEROCONF_PUBLISH',
help="Publish service via mDNS",
type=bool,
default=False)
parser.add_argument('--zeroconf-service-name-prefix',
dest='zeroconf_service_name_prefix',
env_var='ZEROCONF_PREFIX',
help="The name prefix of the service",
type=str,
default="controller")
parser.add_argument('--zeroconf-service-type',
dest='zeroconf_service_type',
env_var='ZEROCONF_TYPE',
help="The type of service",
type=str,
default="_http._tcp.local.")
args = parser.parse_args()
# workaround: Make url a new list if first element contains a '|'
# since we can specify --uri multiple times but not URI as
# an env var. We use pipe: | as seperator since it is not allowed in URIs
if args.uris[0].find("|") != -1:
args.uris = args.uris[0].split("|")
debug = args.debug
uris = args.uris
stream_source = args.stream_source
stream_source_device = args.stream_source_device
img_path = args.img_path
listen_address = args.listen_address
listen_port = args.listen_port
location = args.location
probe_ip = args.probe_ip
theme_name = args.theme_name
zeroconf_publish_service = args.zeroconf_publish_service
zc_service_name_prefix = args.zeroconf_service_name_prefix
zc_service_type = args.zeroconf_service_type
logfile = args.logfile
loglevel = args.loglevel
log_format = '[%(asctime)s] \
{%(filename)s:%(lineno)d} %(levelname)s - %(message)s'
del locals()['args']
# Optional File Logging
if logfile:
tlog = logfile.rsplit('/', 1)
logpath = tlog[0]
logfile = tlog[1]
if not os.access(logpath, os.W_OK):
# Our logger is not set up yet, so we use print here
print("Logging: Can not write to directory. Skipping file handler")
else:
fn = logpath + '/' + logfile
file_handler = logging.FileHandler(filename=fn)
# Our logger is not set up yet, so we use print here
print("Logging: Logging to " + fn)
stdout_handler = logging.StreamHandler(sys.stdout)
if 'file_handler' in locals():
handlers = [file_handler, stdout_handler]
else:
handlers = [stdout_handler]
logging.basicConfig(
level=logging.INFO,
format=log_format,
handlers=handlers
)
logger = logging.getLogger(__name__)
level = logging.getLevelName(loglevel)
logger.setLevel(level)
for dep in dependencies:
if which(dep) is None: