You would need to register a Luup request handler using luup.register_handler()
. The handler itself is a function that receives certain parameters. This is usually done in a plugin but you can do it in startup Lua.
function RoomMeHandler( req, params, outputfmt )
end
luup.register_handler( 'RoomMeHandler', 'RoomMe' )
I haven’t provided any function implementation yet, and I’ll go into a bit of that in a moment, but let’s look at what’s here, starting at the bottom. The luup.register_handler()
call registers a request handler for making Luup requests (which are HTTP requests). The first argument is the name of the function to handle the requests, which must be a global function. The second argument is the name/ID of the handler.
Once this registration has happened, a request to http://your-vera-ip:3480/data_request?id=lr_RoomMe
will cause the named handler function to be called. Notice that the id
parameter of this request/URL has lr_
(lowercase-L lowercase-R underscore) prepended to the ID we gave in the handler call. This is how the request is connected to the handler.
The handler is called when Luup’s internal web server receives a GET or POST request at the above URL. Within the function (your implementation), the most important part is the params
argument, where you will receive the values of all parameters passed on the request as a Lua table. If the URL parameters were ?id=lr_RoomMe&room=Dining
then we would expect to have params.room
with a value of Dining
. You can ignore the req
and outputfmt
arguments for this purpose.
On a POST request, the post body (in your case, the JSON payload) will be in params.post_data
, and it will be a string that you have to parse, so you’ll need to load a JSON library. Once you have that, you can start processing the request.
function RoomMeHandler( req, params, outputfmt )
local json = require( 'dkjson' ) -- typical/default JSON parser for Veras
-- Parse the JSON data
local data, pos, err = json.decode( params.post_data )
if err then
-- Signal requester there was a problem and log the error message and data received.
luup.log( "RoomMeHandler invalid JSON data at " .. tostring(pos) .. ": " .. tostring(err), 1 )
luup.log( data, 1 )
return "Invalid request data", "text/plain"
end
if "RoomEntry" == data.event then
-- Add your code here to handle a RoomEntry event
elseif "RoomExit" == data.event then
-- Add your code here to handle a RoomExit event
else
-- Unhandled event type (use of tostring() is defensive/guard nil)
luup.log( "Ignoring unhandled event " .. toString( data.event ), 2 )
return "Ignored unhandled event", "text/plain"
end
return "OK", "text/plain"
end
This skeleton should be filled in with your implementation. Note that the request handler function here also returns two values from every exit point – it must do this every time, success or error. The first value is a string, and the second value is the MIME type of the data in the string. In this case, I’ve just used simple plain text responses.