Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions python/sbp/client/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,15 @@ def add_callback(self, callback, msg_type=None):
----------
callback : fn
Callback function
msg_type : int
msg_type : int | iterable
Message type to register callback against. Default `None` means global callback.
Iterable type adds the callback to all the message types.
"""
self.callbacks[msg_type].add(callback)
try:
for mt in iter(msg_type):
self.callbacks[mt].add(callback)
except TypeError:
self.callbacks[msg_type].add(callback)

def remove_callback(self, callback, msg_type=None):
"""
Expand All @@ -193,10 +198,15 @@ def remove_callback(self, callback, msg_type=None):
----------
callback : fn
Callback function
msg_type : int
msg_type : int | iterable
Message type to remove callback from. Default `None` means global callback.
Iterable type removes the callback from all the message types.
"""
self.callbacks[msg_type].remove(callback)
try:
for mt in iter(msg_type):
self.callbacks[mt].remove(callback)
except TypeError:
self.callbacks[msg_type].remove(callback)

def get_callbacks(self, msg_type):
"""
Expand Down
27 changes: 27 additions & 0 deletions python/tests/sbp/client/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,30 @@ def test_handler_callbacks():
assert global_counter2.value == 2
assert msg_type_counter1.value == 1
assert msg_type_counter2.value == 0
handler.remove_callback(global_counter1)
handler.remove_callback(global_counter2)
handler.remove_callback(msg_type_counter1, 0x55)
handler.remove_callback(msg_type_counter2, 0x66)
handler.call(SBP(0x11, None, None, None, None))
handler.call(SBP(0x55, None, None, None, None))
assert global_counter1.value == 2
assert global_counter2.value == 2
assert msg_type_counter1.value == 1
assert msg_type_counter2.value == 0

def test_multiple_handler_callbacks():
handler = Handler(None, None)
msg_type_counter1 = TestCallbackCounter()
msg_type_counter2 = TestCallbackCounter()
handler.add_callback(msg_type_counter1, [0x55, 0x66])
handler.add_callback(msg_type_counter2, [0x11, 0x55])
handler.call(SBP(0x11, None, None, None, None))
handler.call(SBP(0x55, None, None, None, None))
assert msg_type_counter1.value == 1
assert msg_type_counter2.value == 2
handler.remove_callback(msg_type_counter1, [0x55, 0x66])
handler.remove_callback(msg_type_counter2, [0x11, 0x55])
handler.call(SBP(0x11, None, None, None, None))
handler.call(SBP(0x55, None, None, None, None))
assert msg_type_counter1.value == 1
assert msg_type_counter2.value == 2