Skip to content

Commit ebeb575

Browse files
author
Brendan Whitfield
committed
allow for multiple callbacks per command
1 parent 98423d2 commit ebeb575

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

obd/async.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class Async(obd.OBD):
4343
def __init__(self, portstr=None):
4444
super(Async, self).__init__(portstr)
4545
self.commands = {} # key = OBDCommand, value = Response
46-
self.callbacks = {} # key = OBDCommand, value = Callback
46+
self.callbacks = {} # key = OBDCommand, value = list of Functions
4747
self.thread = None
4848
self.running = False
4949

@@ -84,31 +84,43 @@ def watch(self, c, callback=None, force=False):
8484
if self.running:
8585
self.stop()
8686

87-
# store the command
87+
# new command being watched, store the command
8888
if not self.commands.has_key(c):
8989
debug("Watching command: %s" % str(c))
9090
self.commands[c] = Response() # give it an initial value
91+
self.callbacks[c] = [] # create an empty list
9192

92-
# store the callback
93-
if hasattr(callback, "__call__") and (not self.callbacks.has_key(c)):
93+
# if a callback was given, push it
94+
if hasattr(callback, "__call__") and (callback not in self.callbacks[c]):
9495
debug("subscribing callback for command: %s" % str(c))
95-
self.callbacks[c] = callback
96+
self.callbacks[c].append(callback)
9697

9798
# start if neccessary
9899
if was_running:
99100
self.start()
100101

101102

102-
def unwatch(self, c):
103+
def unwatch(self, c, callback=None):
103104

104105
# if running, the daemon thread must be stopped before altering the command dict
105106
was_running = self.running
106107
if self.running:
107108
self.stop()
108109

109110
debug("Unwatching command: %s" % str(c))
110-
self.commands.pop(c, None)
111-
self.callbacks.pop(c, None)
111+
112+
# if a callback was specified, only remove the callback
113+
if hasattr(callback, "__call__") and (callback in self.callbacks[c]):
114+
self.callbacks[c].remove(callback)
115+
116+
# if no more callbacks are left, remove the command entirely
117+
if len(self.callbacks[c]) === 0:
118+
self.commands.pop(c, None)
119+
else:
120+
# no callback was specified, pop everything
121+
self.callbacks.pop(c, None)
122+
self.commands.pop(c, None)
123+
112124

113125
# start if neccessary
114126
if was_running:

0 commit comments

Comments
 (0)