21.07.2023, 06:44
I use this code
Code:
require 'ltn12'
require 'socket.http'
json = require("json")
https = require 'ssl.https'
socket.http.TIMEOUT = 5
netatmo_debug = false
client_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
refresh_token_org = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -- get this token from the netatmo dev page, generate first auth and refresh_token
request_token_url = "https://api.netatmo.net/oauth2/token"
request_url = "https://api.netatmo.net/api"
response_body = { }
if (netatmo_debug) then
log("netatmo start")
end
-- get auth token from refresh token
-- https://github.com/akbooer/Netatmo/blob/master/L_Netatmo.lua#L430
function refresh_token()
refresh = storage.get('netatmo_refresh_1', refresh_token_org)
local request_body = "grant_type=refresh_token&client_id=" .. client_id .."&client_secret=" .. client_secret .. "&refresh_token=" .. refresh
local body, code, hdrs, stat = https.request
{
url = request_token_url;
method = "POST";
headers =
{
["Content-Type"] = "application/x-www-form-urlencoded";
["Content-Length"] = #request_body;
};
source = ltn12.source.string(request_body);
sink = ltn12.sink.table(response_body);
}
if (code ~= 200) then
if (netatmo_debug) then
log("netatmo auth error: "..tostring(code)..", "..tostring(body))
end
return
end
local response_decode = json.decode(table.concat(response_body))
local access_token = response_decode.access_token
if response_decode.refresh_token then
storage.set('netatmo_refresh_1', response_decode.refresh_token)
end
if (netatmo_debug) then
log(response_body)
log("netatmo token %s",access_token)
end
return "access_token=" .. access_token
end
-- init
if not init then
if (netatmo_debug) then
log("netatmo init")
end
request_body = refresh_token()
init = true
end
if not request_body and netatmo_debug then
log("netatmo token error")
end
function get_stationdata()
if not request_body then return end
--to limit to only one device : -- local request_body = "access_token=" .. access_token .. "&device_id=" .. device_id
--https://dev.netatmo.com/dev/resources/technical/reference/weatherstation/getstationsdata
local response_body = { }
local body, code, hdrs, stat = https.request
{
url = request_url..'/getstationsdata';
method = "POST";
headers =
{
["Content-Type"] = "application/x-www-form-urlencoded";
["Content-Length"] = #request_body;
};
source = ltn12.source.string(request_body);
sink = ltn12.sink.table(response_body);
}
if (code ~= 200) then
if (netatmo_debug) then
log("netatmo devicelist error: "..tostring(code)..", "..tostring(body)..", "..tostring(hdrs)..", "..tostring(stat))
end
return
end
local response_decode = json.decode(table.concat(response_body))
if (netatmo_debug) then
log(response_decode)
end
end
if (netatmo_debug) then
log("netatmo end")
end
Code:
require('user.nit_netatmo')
get_stationdata()