Periodic message plugin.
authorBenjamin Braatz <bb@bbraatz.eu>
Mon, 26 Jul 2021 21:45:46 +0000 (23:45 +0200)
committerBenjamin Braatz <bb@bbraatz.eu>
Mon, 26 Jul 2021 21:45:46 +0000 (23:45 +0200)
controlpi_plugins/wait.py

index be0c9e04e9d97ebfcdfb60e7dea2c094f2db602a..95c1008db1180da66ee184663196a798762a0ba3 100644 (file)
@@ -156,3 +156,48 @@ class GenericWait(BasePlugin):
     async def run(self) -> None:
         """Run no code proactively."""
         pass
+
+
+class Periodic(BasePlugin):
+    """Send message periodically.
+
+    The "seconds" configuration key is the period of the repetition:
+    receiving a "wait" command before sending the "finished" event:
+    >>> import controlpi
+    >>> asyncio.run(controlpi.test(
+    ...     {"Loop": {"plugin": "Periodic", "seconds": 0.01,
+    ...               "message": {"key": "value"}}},
+    ...     [], 0.025))
+    ... # doctest: +NORMALIZE_WHITESPACE
+    test(): {'sender': '', 'event': 'registered',
+             'client': 'Loop', 'plugin': 'Periodic',
+             'sends': [{'key': {'const': 'value'}}], 'receives': []}
+    test(): {'sender': 'Loop', 'key': 'value'}
+    test(): {'sender': 'Loop', 'key': 'value'}
+    """
+
+    CONF_SCHEMA = {'properties': {'seconds': {'type': 'number'},
+                                  'message': {'type': 'object'}},
+                   'required': ['seconds', 'message']}
+    """Schema for Wait plugin configuration.
+
+    Required configuration key:
+
+    - 'seconds': period of repetition in seconds.
+    - 'message': message to send periodically.
+    """
+
+    async def nop(self, message: Message) -> None:
+        """Do nothing."""
+        pass
+
+    def process_conf(self) -> None:
+        """Register plugin as bus client."""
+        sends = [MessageTemplate.from_message(self.conf['message'])]
+        self.bus.register(self.name, 'Periodic', sends, [], self.nop)
+
+    async def run(self) -> None:
+        """Run periodic loop."""
+        while True:
+            await asyncio.sleep(self.conf['seconds'])
+            await self.bus.send(Message(self.name, self.conf['message']))