-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
79 lines (62 loc) · 2.12 KB
/
controller.py
File metadata and controls
79 lines (62 loc) · 2.12 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
import threading
# Thread with stop
class Thread(threading.Thread):
def __init__(self, *args, **kwargs):
super(Thread, self).__init__(*args, **kwargs)
self._stopper = threading.Event()
self._wait = threading.Event()
def stop(self):
self._stopper.set()
def stopped(self):
return self._stopper.isSet()
def wait(self):
self._wait.set()
def cont(self):
self._wait.clear()
def waiting(self):
return self._wait.isSet()
class Controller:
def __init__(self):
# 1 thread for each pin (RGB), + log for dynamic logging?
# Maybe log should be a separate thing with its own thread
self.threads = dict()
def get_thread(self, name):
return self.threads[name]
def add(self, name, func, *args):
thread = Thread(target=func, args=args)
if name not in ('r', 'g', 'b', 'log'):
raise Exception(f"unsupported thread name: {name}")
self.threads[name] = thread
def start(self, name):
if not name in self.threads:
raise Exception(f"no thread '{name}' found")
self.threads[name].start()
def start_all(self):
for n, t in self.threads.items():
if t.is_alive():
raise Warning(f"thread '{n}' is already running")
t.start()
def stop(self, name):
if not name in self.threads:
raise Exception(f"no thread '{name}' found")
self.threads[name].stop()
def stop_all(self):
for t in self.threads.values():
t.stop()
t.join()
def waiting(self, name):
return self.threads[name].waiting()
def cont_all(self):
for t in self.threads.values():
t.cont()
def all_waiting(self):
return all([t.waiting() == True for t in self.threads.values()])
# True if at least one thread is alive
def alive(self):
for n, t in self.threads.items():
# FIXME: log should be somewhere else
if n == 'log':
continue
if not t.stopped():
return True
return False