Created
August 24, 2019 18:06
-
-
Save dlashua/c532064a2d0c7550f674f68f7bba7a7d to your computer and use it in GitHub Desktop.
coros in AppDaemon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import appdaemon.plugins.hass.hassapi as hass | |
import asyncio | |
class Test(hass.Hass): | |
def terminate(self): | |
# clean up after ourselves | |
for f in self.futures: | |
f.cancel() | |
def initialize(self): | |
self.interval = 1 | |
self.count = 0 | |
self.futures = [] | |
self.run_in(self.do_this, self.interval) | |
def do_this(self, kwargs): | |
self.count += 1 | |
self.log(f"count {self.count}") | |
# we don't care about the return value | |
self.run_coroutine( | |
self.log_thing(self.count)) | |
# we do care about the return value | |
self.run_coroutine( | |
self.return_thing(self.count), | |
self.return_thing_cb, | |
testarg="got it") | |
# repeat until puke | |
self.run_in(self.do_this, self.interval) | |
def return_thing_cb(self, result, kwargs): | |
# this exception raises up | |
# d = 2 / 0 | |
if "testarg" in kwargs: | |
self.log(f"testarg seen {kwargs['testarg']}") | |
self.log(f"{result} return thing cb") | |
def run_coroutine(self, coro, callback=None, **kwargs): | |
def coro_callback(f): | |
if f.cancelled(): | |
# Do Nothing? | |
self.log('CANCELLED') | |
return | |
# we call this even if there is | |
# no callback so the exception will raise | |
r = f.result() | |
if callback is not None: | |
callback(r, kwargs) | |
f = asyncio.run_coroutine_threadsafe(coro, loop=self.AD.loop) | |
f.add_done_callback(coro_callback) | |
# save it for later | |
self.futures.append(f) | |
# keep the list small | |
for f in self.futures: | |
if f.done() or f.cancelled(): | |
self.futures.remove(f) | |
async def log_thing(self, value): | |
# this exception raises up | |
# d = 2 / 0 | |
await asyncio.sleep(5) | |
self.log(f"{value} log thing") | |
async def return_thing(self, value): | |
# this exception raises up | |
# d = 2 / 0 | |
await asyncio.sleep(5) | |
return f"{value} return thing" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment