Need help with appdaemon 4 and async

Hi all.
I upgraded to appdaemon 4 because I wanted async for a project where I sleep alot.
Anywho, I’m not that well versed in python async, and can’t get it to work. I made a simple example that I figured would work, but ‘turn_on’ fails. What am I doing wrong?

import adbase as ad
class Simple(ad.ADBase):

    async def toggle(self, light):
        state= await self.hass.get_state(light, attribute='state')
        if state == 'off':
            self.hass.turn_on(light)
        else:
            self.hass.turn_off(light)

    def initialize(self):
        self.adbase = self.get_ad_api()
        self.hass = self.get_plugin_api("HASS")
        self.adbase.create_task(self.toggle('light.reserv'))

Log:

2020-01-16 17:45:59.511886 WARNING simple: Coroutine (<coroutine object Plugins.get_plugin_object at 0xb45b3e88>) took too long (10 seconds), cancelling the task...
2020-01-16 17:45:59.513011 WARNING simple: non_existent namespace (default) specified in call to turn_off

Hi, I am also working on changing one of my apps with async and I found out that turn_on and turn_off is not working well with async, what I did is change to a call_service, so you can replace the turn_on for:

self.call_service("homeassistant/turn_on", entity_id=light)

Try this:

import hassapi as hass
class Simple(hass.hass):
    async def toggle(self, light):
        state= await self.hass.get_state(light, attribute='state')
        if state == 'off':
            self.hass.turn_on(light)
        else:
            self.hass.turn_off(light)


And the initialize function also need to change, give me a minute.

@tjntomas I started out that way, could not get it working so I switched to the ‘new’ way hoping it would work. Maybe I made some error.

@xaviml Great tip, thanks.

And for the initialize function try:

    def initialize(self):
        self.toggle('light.reserv')

Thanks guys!
This works:

import appdaemon.plugins.hass.hassapi as hass

class Simple(hass.Hass):


    async def toggle(self, light):
        state= await self.get_state(light, attribute='state')
        if state == 'off':
            self.call_service("homeassistant/turn_on", entity_id=light)
        else:
            self.call_service("homeassistant/turn_off", entity_id=light)

    def initialize(self):

        self.create_task(self.toggle('light.reserv'))
1 Like

If you don’t mind, I will take your example to create an issue on appdaemon repository.

Sure, great that you bother.

Done. https://github.com/home-assistant/appdaemon/issues/848