(26.06.2024, 11:05) admin Wrote: Similar integration: https://forum.logicmachine.net/showthrea...4#pid31274
In case someone needs it, below is a scheduled script that runs every 5 minutes to retrieve temp data from some sensors and write them into LM5 groups. (I'm pretty sure that it could be improved)
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
local https =
require (
'ssl.https' )
local json =
require (
'json' )
local ltn12 =
require (
'ltn12' )
local tokenEndpoint =
'https://accounts-api.airthings.com/v1/token'
local clientId =
'xx'
local clientSecret =
'xx'
local devices = {
{
serialNumber =
'xx' ,
location =
'7east' },
{
serialNumber =
'xx' ,
location =
'7west' },
{
serialNumber =
'xx' ,
location =
'7mid' }
}
local accessToken
function getAccessToken ()
local requestBody =
'grant_type=client_credentials'
..
'&client_id=' ..
clientId
..
'&client_secret=' ..
clientSecret
..
'&scope=read:device'
local response_body = {}
local _ ,
code ,
headers ,
status =
https.request {
url =
tokenEndpoint ,
method =
'POST' ,
headers = {
[
'Content-Type' ] =
'application/x-www-form-urlencoded' ,
[
'Content-Length' ] = #
requestBody
},
source =
ltn12.source.string (
requestBody ),
sink =
ltn12.sink.table (
response_body )
}
local response =
table.concat (
response_body )
if code ==
200 then
local jsonResponse =
json.decode (
response )
accessToken =
jsonResponse.access_token
log (
"INFO" ,
'Access token received: ' ..
accessToken )
else
log (
"ERROR" ,
'Error fetching access token: ' ..
tostring (
code ) ..
' ' ..
tostring (
status ))
end
end
function getDeviceData (
serialNumber )
local deviceDataEndpoint =
'https://ext-api.airthings.com/v1/devices/' ..
serialNumber ..
'/latest-samples'
local response_body = {}
local _ ,
code ,
headers ,
status =
https.request {
url =
deviceDataEndpoint ,
method =
'GET' ,
headers = {
[
'Authorization' ] =
'Bearer ' ..
accessToken
},
sink =
ltn12.sink.table (
response_body )
}
local response =
table.concat (
response_body )
if code ==
200 then
local jsonResponse =
json.decode (
response )
return jsonResponse
else
return nil
end
end
getAccessToken ()
getAccessToken ()
if accessToken then
i =
1
for _ ,
device in ipairs (
devices )
do
i =
i +
1
local data =
getDeviceData (
device.serialNumber )
if data then
local temperature =
tostring (
data.data.temp )
log (
"INFO" ,
"Temperature " ..
device.location ..
" == " ..
temperature )
grp.checkwrite (
"32/1/" ..
i ,
temperature )
end
end
end