]> ToastFreeware Gitweb - gregoa/zavai.git/blobdiff - zavai/registry.py
Notes about remotising devices
[gregoa/zavai.git] / zavai / registry.py
index 285045f507ac3165f3e85221e0c4fe7041330fcf..4fc210143ecb8568f3ad692328dbea2665db80d1 100644 (file)
@@ -161,12 +161,19 @@ class Resource(object):
 
 class Service(Resource):
     "Service that is activated only when someone is listening"
-    def __init__(self):
+    def __init__(self, types = []):
+        """
+        Initialise a service that can emit signals for the given event types
+        """
         super(Service, self).__init__()
-        self.callbacks = set()
+        self.callbacks = dict()
+        for t in types:
+            self.callbacks[t] = set()
+        self.started = False
 
     def shutdown(self):
-        self.stop()
+        if self.started:
+            self.stop()
 
     def start(self):
         "Activate the service"
@@ -176,21 +183,28 @@ class Service(Resource):
         "Deactivate the service"
         pass
 
-    def notify(self, *args, **kw):
+    def notify(self, type, *args, **kw):
         "Call all callbacks with the given parameters"
-        for cb in self.callbacks:
+        for cb in self.callbacks[type]:
             cb(*args, **kw)
 
-    def connect(self, callback):
+    def has_callbacks(self):
+        for i in self.callbacks.values():
+            if i: return True
+        return False
+
+    def connect(self, type, callback):
         "Connect a callback to this resource, activating it if needed"
-        do_start = not self.callbacks
-        self.callbacks.add(callback)
+        do_start = not self.has_callbacks()
+        self.callbacks[type].add(callback)
         if do_start:
             self.start()
+            self.started = True
 
-    def disconnect(self, callback):
+    def disconnect(self, type, callback):
         "Disconnect a callback to this resource, activating it if needed"
-        if not self.callbacks: return
-        self.callbacks.discard(callback)
-        if not self.callbacks:
+        if not self.has_callbacks(): return
+        self.callbacks[type].discard(callback)
+        if not self.has_callbacks():
             self.stop()
+            self.started = False