Accessing Home Assistant from Xojo on a Mac

I have Home Assistant running on a Raspberry Pi 4 and wanted an app on my Mac desktop on the same local network to be able to command lights to turn on and off etc. You can give Home Assistant instructions with curl calls to the REST API - see the documentation here: REST API | Home Assistant Developer Docs

Once I had succeeded in making some curl calls work in the Terminal I wrote a simple method to do this from within Xojo:

HA_Action(device as string, action as string)

dim sh as new shell, HA_Header as string, DQUOTE, SQUOTE as string

DQUOTE=chr(34)

SQUOTE=chr(39)

HA_Header=“-H “+DQUOTE+“Authorization: Bearer ”+DQUOTE+” -H “+DQUOTE+“Content-Type: application/json”+DQUOTE
sh.Execute (“curl “+HA_Header+” -d “+SQUOTE+”{”+DQUOTE+“entity_id”+DQUOTE+”: “+DQUOTE+device+DQUOTE+”}”+SQUOTE+" http://homeassistant.local:8123/api/"+action)

You get from the Home Assistant web interface. See here: Authentication API | Home Assistant Developer Docs

So the call

HA_Action(“switch.plug”,“services/switch/turn_on”)

switches on the Zigbee plug called ‘plug’

For me it seems to work very quickly and reliably.

1 Like

Also - the call to curl responds with a JSON string, so you can access this through sh.result

Sorry I see the system has removed something I had in angle brackets, here it is in square brackets:

HA_Action(device as string, action as string)

dim sh as new shell, HA_Header as string, DQUOTE, SQUOTE as string

DQUOTE=chr(34)

SQUOTE=chr(39)

HA_Header=“-H “+DQUOTE+“Authorization: Bearer [TOKEN]”+DQUOTE+” -H “+DQUOTE+“Content-Type: application/json”+DQUOTE
sh.Execute (“curl “+HA_Header+” -d “+SQUOTE+”{”+DQUOTE+“entity_id”+DQUOTE+”: “+DQUOTE+device+DQUOTE+”}”+SQUOTE+" http://homeassistant.local:8123/api/"+action)

You get a long-term [TOKEN] from the Home Assistant web interface. See here: Authentication API | Home Assistant Developer Docs

Use the URLConnection class for this. It’s more integrated into xojo

Thanks Derk, I’ll take a look at that.