-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmind.py
More file actions
184 lines (141 loc) 路 5.57 KB
/
Copy pathmind.py
File metadata and controls
184 lines (141 loc) 路 5.57 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
from devstreamlog import DevStreamLogger
import threading
import traceback
import queue
import evdev
log = DevStreamLogger(filename="mind.log")
class Topic:
def __init__(self, name):
self.last_event = None
self.listeners = []
self.name = name
def add(self, callback):
self.listeners.append(callback)
def remove(self, callback):
if callback in self.listeners:
self.listeners.remove(callback)
class Job:
def __init__(self, id, callback, priority, args):
self.callback = callback
self.priority = priority
self.args = args
self.id = id
def __lt__(self, other):
if other.priority is None:
return False
elif self.priority != other.priority:
return self.priority < other.priority
else:
return self.id < other.id
class Executor:
def __init__(self):
self.thread = threading.Thread(target=self._run, daemon=True)
self.priority_queue = queue.PriorityQueue()
self.lock = threading.Lock()
self.lock.acquire()
self.next_job_id = 0
self.done = False
self.thread.start()
def _run(self):
while not self.done:
job:Job = self.priority_queue.get()
if job.callback is None:
break
try:
job.callback(*job.args)
except Exception as err: # pylint: disable=W0718
log.error("Something happened when processing a Mind's callback event:", err)
traceback.print_exc()
self.lock.release()
def submit(self, callback, priority, *args):
job = Job(self.next_job_id, callback, priority, args)
self.priority_queue.put(job)
self.next_job_id += 1
def terminate(self):
self.done = True
self.priority_queue.put(Job(self.next_job_id, None, None, None))
self.next_job_id += 1
def wait(self):
self.lock.acquire()
self.lock.release()
class Mind:
def __init__(self, name=None):
self.devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
self.name = type(self).__name__ if name is None else name
self.device_names = {dev.name for dev in self.devices}
self.topics:dict[str,Topic] = {}
self.required_devices = set()
self.executor = Executor()
self.shadows = {}
log.info("Initializing mind")
def require_device(self, device_name):
log.debug(f"Requiring device_name=\"{device_name}\"")
if isinstance(device_name, (set,list)):
self.required_devices.update(device_name)
else:
self.required_devices.add(device_name)
def add_shadow(self, shadow):
assert not shadow.name in self.shadows, "A shadow with the same name already exists in the mind"
self.shadows[shadow.name] = shadow
shadow.attach(self)
shadow.activate()
return shadow
def remove_shadow(self, name):
shadow = self.shadows.get(name)
if shadow is not None:
del self.shadows[name]
shadow.deactivate()
shadow.dettach()
def add_listener(self, topic_names, callback):
log.debug(f"Adding listener for topic_names=\"{topic_names}\"")
if not isinstance(topic_names, list):
topic_names = [topic_names]
for topic_name in topic_names:
if topic_name in self.topics:
topic = self.topics[topic_name]
topic.add(callback)
if topic.last_event is not None:
self._emit_one(callback, topic_name, topic.last_event)
else:
topic = Topic(topic_name)
topic.add(callback)
self.topics[topic_name] = topic
def remove_listener(self, topic_names, callback):
if not isinstance(topic_names, list):
topic_names = [topic_names]
for topic_name in topic_names:
if topic_name in self.topics:
self.topics[topic_name].remove(callback)
def emit(self, topic_name, event, priority=100):
try:
self.executor.submit(self._emit_all, priority, topic_name, event)
except RuntimeError as e:
log.warn(f"Could not emit event, maybe we are shutting down. Error=\"{e}\"")
def run(self):
try:
self.executor.wait()
except:
log.debug("\nTerminating...")
def _emit_all(self, topic_name, event):
if topic_name in self.topics:
topic:Topic = self.topics[topic_name]
topic.last_event = event
else:
topic = Topic(topic_name)
topic.last_event = event
self.topics[topic_name] = topic
if topic_name == "DeviceReader:Logitech MX Master 3S":
log.debug(f"Topic has {len(topic.listeners)} listeners")
for callback in topic.listeners:
try:
# print("Event.topic_name=" + topic_name)
callback(topic_name, event)
except Exception as e:
traceback.print_exc()
log.error(f"Error during event processing for topic_name=\"{topic_name}\", error=\"{e}\"")
def _emit_one(self, callback, topic_name, event):
try:
callback(topic_name, event)
except Exception as e:
traceback.print_exc()
log.error(f"Error during event processing for topic_name=\"{topic_name}\", error=\"{e}\"")