From: Benjamin Braatz Date: Mon, 26 Jul 2021 21:45:46 +0000 (+0200) Subject: Periodic message plugin. X-Git-Tag: v0.3.0~33 X-Git-Url: http://git.graph-it.com/?a=commitdiff_plain;h=09964b3c67994cd90adf0688daa0523ae53a71a1;p=graphit%2Fcontrolpi.git Periodic message plugin. --- diff --git a/controlpi_plugins/wait.py b/controlpi_plugins/wait.py index be0c9e0..95c1008 100644 --- a/controlpi_plugins/wait.py +++ b/controlpi_plugins/wait.py @@ -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']))