netatmo.lua
#!/usr/bin/env lua
package.path = "./?/init.lua;"..package.path
local copas = require "copas"
local socket = require "socket"
local pretty = require("pl.pretty").write
local Netatmo = require "netatmo"
Netatmo.https = copas.http
local host = "127.0.0.1"
local port = "54321"
copas(function()
local config = require "config" local na = Netatmo.new {
client_id = config.auth_data.client_id,
client_secret = config.auth_data.client_secret,
callback_url = "http://"..host..":"..port.."/some/path",
}
local callback_result
local server_sock = assert(socket.bind(host, port))
local server_ip, server_port = assert(server_sock:getsockname())
local socket_handler = function(sock)
local request = {}
while true do
local line = assert(sock:receive("*l"))
if line == "" then break end
request[#request+1] = line
end
callback_result = request
sock:send("HTTP/1.1 200 OK\r\n\r\nOAuth2 access approved, please close this browser window.\r\n")
sock:close()
copas.removeserver(server_sock)
server_sock = nil
end
copas.addserver(server_sock, copas.handler(socket_handler))
print("if a webbrowser is not started automatically, please visit: ",na:get_authorization_url())
os.execute("open '"..na:get_authorization_url().."'")
print()
print("Listening on "..server_ip..":"..server_port)
local endtime = socket.gettime()+60 while socket.gettime() < endtime and callback_result == nil do
copas.sleep(0.1)
end
if not callback_result then
copas.removeserver(server_sock)
server_sock = nil
print("timeout waiting for callback")
os.exit(1)
end
assert(na:authorize(callback_result[1]))
print("Authorized successfully!")
local data, err = na:get_stations_data()
na:logout()
if not data then
print("Error: ", err)
os.exit(1)
end
print(pretty(data))
end)