[quote=“kyb2012, post:8, topic:184933”]Since I bought the Wallyhome sensors, I thought that I might as well try my hand at writing a plugin or lua script to get the readings from these sensors. But I need a lot of help…
I’m hoping that someone can help me with calling the API and reading the JSON response.
When I call the API below with the appropriate and values from a REST API tool, I get a JSON response. But when I try the LUUP below, in the log, I only see the last logged statement “Wally finished”. I don’t see the “result” or “status” values. Am I adding the header in the right place?
local socket = require(“socket”)
local ltn12 = require(‘ltn12’)
local https = require(“ssl.https”)
https.METHOD = “GET”
local result = {}
https.headers = {
[“Authorization”] = “Bearer ”,
–[“content-length”] = string.len(data),
[“content-type”] = “application/json”
}
local url = “https://api.snsr.net/v2/places//sensors”
local result, status = https.request(url)
luup.log(“Wally result:”, result)
luup.log(“Wally status:”, status)
luup.log(‘Wally finished = !!!’);[/quote]
Your code is close… but is missing a few important parameters in the https call…
You need to specify the mode the request is to use, you need to specify the encryption protocol the request will use, and you need to specify what the https module will do to verify the remote host.
You also will need to use the generic form of the https.request meathod (In my experience the short form almost never works properly, or as expected)…
Provided below is a code snippet to help you out, taken from my Wink Hub plugin (and subtley modified to suit your situation…)… Not that the decode_json function is a generic (and small) json decoder that is embedded within my plugin… you can use any json decoder you desire…
local https = require("ssl.https")
local ltn12 = require("ltn12")
local respBody = {}
local client_id = "<client id>"
local req_url = "https://api.snsr.net/v2/places/"..client_id.."/sensors"
local jResp = ""
debug("Sending http request ["..req_url.."] ["..req_json.."].",2)
local rBody, rCode, rHeaders, rStatus = https.request(
{
method = "get",
url = req_url,
headers = { ["Authorization"] = "Bearer <token>",["Content-Type"] = "application/json", ["Content-Length"] = #req_json },
sink = ltn12.sink.table(respBody),
verify = "none",
mode = "client",
protocol = "tlsv1",
options = "all",
redirect = false
}
)
if (tonumber(rCode,10) == 200) then
local jResp = decode_json(table.concat(respBody))
-- the jResp now contains a keyed Lua table with your decoded json data
else
log("https request FAILED!",1)
end