(Last Updated: May 6, 2020)

Lua Function in openLuup Startup Lua to send async command to Home Assistant API



  • function POSTHA(path, payload, token)
        local async = require "http_async"
        local ltn12 = require("ltn12")
        local resp = {}
        async.request(
        {
        url = path,
        method = "POST",
        headers = 
            {["Content-Type"] = "application/json",
            ["Content-Length"] = payload:len(),
            ["Authorization"] = token,
            },
        source = ltn12.source.string(payload),
        sink = ltn12.sink.table(resp)
        }, function() end)
    end
    

    example of usage:
    define the token obtained from home assistant in the scene lua or startup lua:

    local hass_token = "*********"
    local path = "http://hass_ip:8123/api/services/vacuum/turn_off"
    local payload = [[{"entity_id": "vacuum.upstairs_roomba"}]]
    
    POSTHA(path, payload, hass_token)
    


  • I believe that you mean to write

    local ok, err = async.request

    Although that’s largely wasted since you don’t use those two variables.

    You might as well write simply

    async.request



  • Nope, doesn't work that way. It disables the function. I have been running this way for a few years...
    What you say makes sense now that I know more about lua but somehow... I believe I got the original code from you as well since I had to make changes with the async implementation.



  • This can’t be true. Lua doesn’t care about line breaks, so

    local ok, err async.request(...

    Is syntactically the same as

    local ok, err
    async.request(...

    Which simply shows that ok and err are unassigned and unused.

    So your code works, but the two variables are not needed.



  • I agree with you and I don't know why but the first time I tested it, it broke the function.
    I just ran another test and it seems to be ok. Not sure why.


Log in to reply