Get online airquality data  [SOLVED]

Moderator: leecollings

User avatar
EdwinK
Posts: 1820
Joined: Sunday 22 January 2017 21:46
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Rhoon
Contact:

Re: Get online airquality data

Post by EdwinK »

At least PM10 (and PM25) and amonia. We have some heave industry over here, so I want to know as much as possible about airquality.
Running latest BETA on a Pi-3 | Toon® Thermostat (rooted) | Hue | Tuya | IKEA tradfri | Dashticz V3 on Lenovo Huawei Tablet | Conbee
elmortero
Posts: 247
Joined: Sunday 29 November 2015 20:46
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.9639
Location: Spain
Contact:

Re: Get online airquality data

Post by elmortero »

WIth the last code I posted, you can replicate all parts for PM25 (I don't know if that is needed, as PM25 is smaller than PM 10)
As for amonia, waqi does not offer that value
User avatar
capman
Posts: 153
Joined: Friday 12 July 2013 20:48
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Belgium
Contact:

Re: Get online airquality data

Post by capman »

My script so far. It's not updating now because the values are stable. But there are no errors in the log.

Code: Select all

return {
	on = {
		timer = { 'every 10 minutes' },
		httpResponses = { 'waqi' } -- matches callback string below
	},
	
	execute = function(domoticz, triggerItem)
local lat = 'xxxxxxxx'
local long = 'yyyyyyyy'
local apikey = 'my api key'

    local PM10sensor = domoticz.devices('Fijn stof') 		-- virtual sensor of the type "Custom sensor"
    local prevPM10 = PM10sensor.rawData[1]			-- get the current value of the Alert
    local pmalert = domoticz.devices('Fijn stof alarm') 	-- virtual sensor of the type "Alert"
    local AirC = domoticz.devices('Luchtkwaliteit') 	   	-- virtual sensor of the type "Air Quality"

		if (triggerItem.isTimer) then
			domoticz.openURL({
				url = 'http://api.waqi.info/feed/geo:'..lat..';'..long..'/?token='..apikey,
				method = 'GET',
				callback = 'waqi'
			})
		elseif (triggerItem.isHTTPResponse) then

	local response = triggerItem
		if (response.ok and response.isJSON) then
		local pm10 = tonumber(response.json.data.iaqi.pm10.v)
		local aqius = tonumber(response.json.data.aqi)		-- combined air quality	
 
        if pm10 ~= nil and pm10 ~= prevPM10 then 
		 PM10sensor.updateCustomSensor(pm10)
        end

        if aqius ~= nil then  --and aqius ~= prevAirC
		 AirC.updateAirQuality(aqius)
        end

		if pm10 ~= prevpm10 then			-- before updating the sensor check if the value has changed (in order to avoid unneeded updating, 
				if pm10 <= 100 then level = domoticz.ALERTLEVEL_GREEN; nfo = "Good"
				elseif pm10 > 100 and pm10 <= 200 then level = domoticz.ALERTLEVEL_YELLOW; nfo = "Polluted"
				elseif pm10 > 200 and pm10 <= 300 then level = domoticz.ALERTLEVEL_ORANGE; nfo = "Very Polluted"
				elseif pm10 > 300 then level =  domoticz.ALERTLEVEL_RED; nfo = "Alarming"
				end
			pmalert.updateAlertSensor(level, pm10)	-- if you want just on sensor with alert level and value (as text) replace nfo with pm10
		end

			else
				print('**PM10failed to fetch info')
			end
		end
	end
}
Just wonder how to get the right allert values ? For Europe.
warning.JPG
warning.JPG (36.43 KiB) Viewed 4168 times
So should it not begin with a value of <50 , >50 and <=90 , and so on ? This is only for pm10 value.
User avatar
EdwinK
Posts: 1820
Joined: Sunday 22 January 2017 21:46
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Rhoon
Contact:

Re: Get online airquality data

Post by EdwinK »

elmortero wrote: Saturday 28 July 2018 13:31 WIth the last code I posted, you can replicate all parts for PM25 (I don't know if that is needed, as PM25 is smaller than PM 10)
As for amonia, waqi does not offer that value
Maybe it has another name, or code. Not sure Need to check that from another, now no longer, working script.
Running latest BETA on a Pi-3 | Toon® Thermostat (rooted) | Hue | Tuya | IKEA tradfri | Dashticz V3 on Lenovo Huawei Tablet | Conbee
User avatar
capman
Posts: 153
Joined: Friday 12 July 2013 20:48
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Belgium
Contact:

Re: Get online airquality data

Post by capman »

My final working script. Hope it's okee now.

Code: Select all

return {
	on = {
		timer = { 'every 6 minutes' },
		httpResponses = { 'waqi' } -- matches callback string below
	},
	
	execute = function(domoticz, triggerItem)

	local lat = 'xxxxxxx'
	local long = 'yyyyyy'
	local apikey = 'zzzzzzzzzzz'

    	local PM10sensor = domoticz.devices('Fijn stof PM10') 	-- virtual sensor of the type "Custom sensor"
    	local prevPM10 = PM10sensor.rawData[1]				-- get the current value of the Alert
    	local PM25sensor = domoticz.devices('Fijn stof PM2.5') 	-- virtual sensor of the type "Custom sensor"  
    	local prevPM25 = PM25sensor.rawData[1]				-- get the current value of the 	Alert
	local pmalert = domoticz.devices('Fijn stof alarm')     	-- virtual sensor of the type "Alert"
    	local AirC = domoticz.devices('Luchtkwaliteit buiten') 	-- virtual sensor of the type "Air Quality"

		if (triggerItem.isTimer) then
			domoticz.openURL({
				url = 'http://api.waqi.info/feed/geo:'..lat..';'..long..'/?token='..apikey,
				method = 'GET',
				callback = 'waqi'
			})
		elseif (triggerItem.isHTTPResponse) then

	local response = triggerItem
		if (response.ok and response.isJSON) then
		local pm10 = tonumber(response.json.data.iaqi.pm10.v)	-- respirable particulate matter
		local aqius = tonumber(response.json.data.aqi)			-- combined air quality	
	        local pm25 = tonumber(response.json.data.iaqi.pm25.v)	-- partical matter of particles < 2.5µm
 
        if pm10 ~= nil and pm10 ~= prevPM10 then 
		 PM10sensor.updateCustomSensor(pm10)
        end

        if pm25 ~= nil and pm25 ~= prevPM25 then 
		 PM25sensor.updateCustomSensor(pm25)
        end

        if aqius ~= nil then
		 AirC.updateAirQuality(aqius)
        end

		if pm25 ~= prevpm25 then			-- before updating the sensor check if the value has changed (in order to avoid unneeded updating, 
				if pm25 <= 100 then level = domoticz.ALERTLEVEL_GREEN; nfo = "Zuiver"
				elseif pm25 > 100 and pm25 <= 200 then level = domoticz.ALERTLEVEL_YELLOW; nfo = "Vervuild"
				elseif pm25 > 200 and pm25 <= 300 then level = domoticz.ALERTLEVEL_ORANGE; nfo = "Zeer vervuild"
				elseif pm25 > 300 then level =  domoticz.ALERTLEVEL_RED; nfo = "Alarmerend"
				end
			pmalert.updateAlertSensor(level, pm25)	-- if you want just on sensor with alert level and value (as text) replace nfo with pm10
		end

			else
				print('**PM25failed to fetch info')
			end
		end
	end
}
Thanks to all for helping my out , especially Elmortero for the original script.
User avatar
EdwinK
Posts: 1820
Joined: Sunday 22 January 2017 21:46
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Rhoon
Contact:

Re: Get online airquality data

Post by EdwinK »

Just noticed, I don't get any data at all :(
Running latest BETA on a Pi-3 | Toon® Thermostat (rooted) | Hue | Tuya | IKEA tradfri | Dashticz V3 on Lenovo Huawei Tablet | Conbee
elmortero
Posts: 247
Joined: Sunday 29 November 2015 20:46
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.9639
Location: Spain
Contact:

Re: Get online airquality data

Post by elmortero »

Just no data? Or errors in log?
Maybe write the acquired data to the log so you can see if it gets a nil value
User avatar
EdwinK
Posts: 1820
Joined: Sunday 22 January 2017 21:46
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Rhoon
Contact:

Re: Get online airquality data

Post by EdwinK »

This is what I have as devices
Screen Shot 2018-08-03 at 10.26.42.png
Screen Shot 2018-08-03 at 10.26.42.png (85.58 KiB) Viewed 4098 times
And an error.

dzVents: Error (2.4.7): An error occured when calling event handler AirQuality
2018-08-03 10:24:04.331 Status: dzVents: Error (2.4.7): ...omoticz/scripts/dzVents/generated_scripts/AirQuality.lua:32: attempt to index field 'pm25' (a nil value)
2018-08-03 10:24:04.331 Status: dzVents: Info: ------ Finished AirQuality

I'm using the latest (adapted) script from Capman.
Running latest BETA on a Pi-3 | Toon® Thermostat (rooted) | Hue | Tuya | IKEA tradfri | Dashticz V3 on Lenovo Huawei Tablet | Conbee
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Get online airquality data

Post by waaren »

EdwinK wrote: Friday 03 August 2018 10:30
dzVents: Error (2.4.7): An error occured when calling event handler AirQuality
2018-08-03 10:24:04.331 Status: dzVents: Error (2.4.7): ...omoticz/scripts/dzVents/generated_scripts/AirQuality.lua:32: attempt to index field 'pm25' (a nil value)
2018-08-03 10:24:04.331 Status: dzVents: Info: ------ Finished AirQuality

I'm using the latest (adapted) script from Capman.
I saw this behaviour also too many times. It looks like some of the locations do not return any data on the first call. Not sure why but most of the times a second call with the exact same content is successful.
That is why I modified the script to handle these exceptions. If you are interested...

Code: Select all

--[[
data from http://waqi.info/
An API key is required and can be aquired here ==> http://aqicn.org/data-platform/token/

Based on the original idea and script from @elmortero

http://api.waqi.info/feed/geo:51.852062;4.507676/?token=Your_apikey = Zwartewaalstraat, Rotterdam Zuid
http://api.waqi.info/feed/geo:51.986119;4.934413/?token=Your_apikey = Lopik (co)
http://api.waqi.info/feed/geo:51.867238,4.354981/?token=Your_apikey = Leemkuil (so2)
]]--

return {
    on =    {  
                timer           = { "every 15 minutes" },
                httpResponses   = { "waqi*" }                            -- matches callback wildcard 
            },
        
        data    =   {   
                        safedMessage = { history = true, maxItems = 100 , maxHours = 168 }
                    },
        
        logging =   {   level   =   domoticz.LOG_DEBUG,
                        marker  =   "Waqi" },
    
    execute = function(dz, triggerItem)
        
        local apiKey            = "Your_apikey"
        local defaultLocation   = "51.852062;4.507676"
        local sensorType
        
        if dz.data.safedMessage.get(1) == nil then
            dz.data.safedMessage.add("Init") 
        end
        
        local geo   = { nearby  = defaultLocation,        -- to get station closest to your home 
                        SO2     = "51.867238;4.354981",   -- if value for this item cannot be obtained from "nearby"
                        CO      = "51.986119;4.934413",   -- else keep this as an empty string
                        PM25    = "",
                        PM10    = "",
                        O3      = "",
                        NO2     = "",
                        AQI     = "",
                      }  
                      
        local sensors = {   SO2     = { sensor = 1003,  alert = 1002 },   -- enter device index Numbers or 0 for sensor and alert "
                            CO      = { sensor = 1004,  alert = 0     },
                            PM25    = { sensor = 1008,  alert = 1009  },
                            PM10    = { sensor = 1011,  alert = 1010  },
                            O3      = { sensor = 1005,  alert = 0     },
                            NO2     = { sensor = 0,     alert = 0     },
                            AQI     = { sensor = 1007,  alert = 1006  , aqiSensor = 1000},      -- additional Air Quality sensor
                        }
       
        local sensorTypes = { alert = "Alert", aqi = "Air Quality", custom = "Custom Sensor" } 
        
        local function responseType(str)   -- strip waqi_ from string
            return str:gsub("waqi_","")
        end
       
        local function errorMessage(message,notify)   -- Add entry to log and notify to all subsystems
            dz.log(message,dz.LOG_ERROR)
            if notify then 
                dz.notify(message)
            end
        end    
        
        local function callPollutionURL(location,callback,delay)
            local delay = delay or 1
            local url   = "http://api.waqi.info/feed/geo:".. location .. "/?token=" .. apiKey
            dz.openURL({    url         = url,
                            method      = "GET",
                            callback    = callback
                       }).afterSec(delay)
        end
        
        local function getAirQualityData()
            local delay = 1
            for callType, location in pairs(geo) do
                if location ~= "" then
                    callPollutionURL(location,"waqi_" .. callType,delay) 
                    delay = delay + 30                    
                end    
            end
        end
        
        local function alertLevelAQI(value)
            if value < 50 then return dz.ALERTLEVEL_GREEN,"Excellent" end
            if value < 100 then return dz.ALERTLEVEL_YELLOW,"Poor" end
            if value < 150 then return dz.ALERTLEVEL_ORANGE,"Polluted" end
            return dz.ALERTLEVEL_RED,"Dangerous"
        end
        
        function deviceType(device)
            if device ~= nil then
                if dz.devices(device).deviceType:upper() == "GENERAL" then
                    return dz.devices(device).deviceSubType
                else
                    return dz.devices(device).deviceType
                end
            else
                return nil
            end
        end
        
        
        local function setSensor(sensor,value)
            if sensor ~= 0 and value ~= nil then
               
                if deviceType(sensor) == sensorTypes.custom then 
                    dz.devices(sensor).updateCustomSensor(value)
                elseif deviceType(sensor) == sensorTypes.aqi then
                    dz.devices(sensor).updateAirQuality(value)
                else
                    local alertLevel, alertText = alertLevelAQI(value)
                    local alertString = alertText .. "(" .. tostring(value) .. ")"   
                    if dz.devices(sensor).text ~= alertString then
                        dz.devices(sensor).updateAlertSensor(alertLevel, alertString)
                    end
                end 
            end
        end
        
        local function handleResponse(type)
            local rt = triggerItem.json                        -- rt is just a reference to the data no actual copy is done
            if triggerItem.json ~= nil and rt.data ~= nil and tonumber(rt.data.aqi) then
                if type == "nearby" then
                    rt.data.iaqi["aqi"] = {}; rt.data.iaqi["aqi"].v = rt.data.aqi    -- handle exception in iaqi as aqi is stored elsewhere
                    
                    for nearbyType, location in pairs(geo) do
                        if nearbyType ~= "nearby" and location == "" then               -- No other location for this type 
                            handleResponse(nearbyType)    
                        end    
                    end
                else
                    for setDevice, idx in pairs(sensors[type]) do
                        setSensor(idx,rt.data.iaqi[type:lower()].v)
                    end
                end
            else
                errorMessage("This should not happen")   -- aqi should always be there and set
                if dz.data.safedMessage.get(1).time.secondsAgo > 30 then
                    errorMessage("I will call url again")   -- aqi should always be there and set
                    callPollutionURL(geo[responseType(triggerItem.trigger)],triggerItem.trigger,1)
                    dz.data.safedMessage.add("Extra call to openURL for " .. triggerItem.trigger)
                end    
            end
        end
        
        if triggerItem.isHTTPResponse then
           if triggerItem.ok and triggerItem.isJSON then 
               handleResponse(responseType(triggerItem.trigger))
           else
               errorMessage("Problem with response from waqi",true)  
           end
        else
            getAirQualityData()
        end    
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
User avatar
EdwinK
Posts: 1820
Joined: Sunday 22 January 2017 21:46
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Rhoon
Contact:

Re: Get online airquality data

Post by EdwinK »

Going to try this ;)

Now i see data getting into the sensors. Thanks everyone.
Running latest BETA on a Pi-3 | Toon® Thermostat (rooted) | Hue | Tuya | IKEA tradfri | Dashticz V3 on Lenovo Huawei Tablet | Conbee
krommetje3108
Posts: 12
Joined: Saturday 05 November 2016 7:52
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.5877
Location: netherlands
Contact:

Re: Get online airquality data

Post by krommetje3108 »

I am using this code...

Code: Select all

--[[
data from http://waqi.info/
An API key is required and can be aquired here ==> http://aqicn.org/data-platform/token/

Based on the original idea and script from @elmortero

http://api.waqi.info/feed/geo:51.468096;5.631230/?token=TOKEN REMOVED = Helmond
http://api.waqi.info/feed/geo:51.544365;5.867349/?token=TOKEN REMOVED = Vedepeel (co)
http://api.waqi.info/feed/geo:51.544365;5.867349/?token=TOKEN REMOVED = Vedepeel (so2)
]]--

return {
    on =    {  
                timer           = { "every 15 minutes" },
                httpResponses   = { "waqi*" }                            -- matches callback wildcard 
            },
        
        data    =   {   
                        safedMessage = { history = true, maxItems = 100 , maxHours = 168 }
                    },
        
        logging =   {   level   =   domoticz.LOG_DEBUG,
                        marker  =   "Waqi" },
    
    execute = function(dz, triggerItem)
        
        local apiKey            = "TOKEN REMOVED"
        local defaultLocation   = "51.468096;5.631230"
        local sensorType
        
        if dz.data.safedMessage.get(1) == nil then
            dz.data.safedMessage.add("Init") 
        end
        
        local geo   = { nearby  = defaultLocation,        -- to get station closest to your home 
                        SO2     = "",   -- if value for this item cannot be obtained from "nearby"
                        CO      = "",   -- else keep this as an empty string
                        PM25    = "",
                        PM10    = "",
                        O3      = "",
                        NO2     = "",
                        AQI     = "",
                      }  
                      
        local sensors = {   SO2     = { sensor = 203,  alert = 0},   -- enter device index Numbers or 0 for sensor and alert "
                            CO      = { sensor = 204,  alert = 0},
                            PM25    = { sensor = 205,  alert = 0},
                            PM10    = { sensor = 206,  alert = 0},
                            O3      = { sensor = 207,  alert = 0},
                            NO2     = { sensor = 208,  alert = 0},
                                                    }
       
        local sensorTypes = { alert = "Alert", aqi = "Air Quality", custom = "Custom Sensor" } 
        
        local function responseType(str)   -- strip waqi_ from string
            return str:gsub("waqi_","")
        end
       
        local function errorMessage(message,notify)   -- Add entry to log and notify to all subsystems
            dz.log(message,dz.LOG_ERROR)
            if notify then 
                dz.notify(message)
            end
        end    
        
        local function callPollutionURL(location,callback,delay)
            local delay = delay or 1
            local url   = "http://api.waqi.info/feed/geo:".. location .. "/?token=" .. apiKey
            dz.openURL({    url         = url,
                            method      = "GET",
                            callback    = callback
                       }).afterSec(delay)
        end
        
        local function getAirQualityData()
            local delay = 1
            for callType, location in pairs(geo) do
                if location ~= "" then
                    callPollutionURL(location,"waqi_" .. callType,delay) 
                    delay = delay + 30                    
                end    
            end
        end
        
        local function alertLevelAQI(value)
            if value < 50 then return dz.ALERTLEVEL_GREEN,"Excellent" end
            if value < 100 then return dz.ALERTLEVEL_YELLOW,"Poor" end
            if value < 150 then return dz.ALERTLEVEL_ORANGE,"Polluted" end
            return dz.ALERTLEVEL_RED,"Dangerous"
        end
        
        function deviceType(device)
            if device ~= nil then
                if dz.devices(device).deviceType:upper() == "GENERAL" then
                    return dz.devices(device).deviceSubType
                else
                    return dz.devices(device).deviceType
                end
            else
                return nil
            end
        end
        
        
        local function setSensor(sensor,value)
            if sensor ~= 0 and value ~= nil then
               
                if deviceType(sensor) == sensorTypes.custom then 
                    dz.devices(sensor).updateCustomSensor(value)
                elseif deviceType(sensor) == sensorTypes.aqi then
                    dz.devices(sensor).updateAirQuality(value)
                else
                    local alertLevel, alertText = alertLevelAQI(value)
                    local alertString = alertText .. "(" .. tostring(value) .. ")"   
                    if dz.devices(sensor).text ~= alertString then
                        dz.devices(sensor).updateAlertSensor(alertLevel, alertString)
                    end
                end 
            end
        end
        
        local function handleResponse(type)
            local rt = triggerItem.json                        -- rt is just a reference to the data no actual copy is done
            if triggerItem.json ~= nil and rt.data ~= nil and tonumber(rt.data.aqi) then
                if type == "nearby" then
                    rt.data.iaqi["aqi"] = {}; rt.data.iaqi["aqi"].v = rt.data.aqi    -- handle exception in iaqi as aqi is stored elsewhere
                    
                    for nearbyType, location in pairs(geo) do
                        if nearbyType ~= "nearby" and location == "" then               -- No other location for this type 
                            handleResponse(nearbyType)    
                        end    
                    end
                else
                    for setDevice, idx in pairs(sensors[type]) do
                        setSensor(idx,rt.data.iaqi[type:lower()].v)
                    end
                end
            else
                errorMessage("This should not happen")   -- aqi should always be there and set
                if dz.data.safedMessage.get(1).time.secondsAgo > 30 then
                    errorMessage("I will call url again")   -- aqi should always be there and set
                    callPollutionURL(geo[responseType(triggerItem.trigger)],triggerItem.trigger,1)
                    dz.data.safedMessage.add("Extra call to openURL for " .. triggerItem.trigger)
                end    
            end
        end
        
        if triggerItem.isHTTPResponse then
           if triggerItem.ok and triggerItem.isJSON then 
               handleResponse(responseType(triggerItem.trigger))
           else
               errorMessage("Problem with response from waqi",true)  
           end
        else
            getAirQualityData()
        end    
    end
}
but stil get this error:
2019-06-08 09:48:12.521 Error: EventSystem: in Waqi: [string "--[[ ..."]:22: attempt to index global 'domoticz' (a nil value)

Any thoughts on how to make it work?
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Get online airquality data

Post by waaren »

krommetje3108 wrote: Saturday 08 June 2019 10:01 I am using this code...
Any thoughts on how to make it work?
Yes. You most likely saved it as a Lua script. It should be saved as a dzVents script.

When not yet familiar with dzVents please start with reading Get started Before implementing. Special attention please for
"In Domoticz go to Setup > Settings > Other and in the section EventSystem make sure the checkbox 'dzVents disabled' is not checked. Also make sure that in the Security section in the settings you allow 127.0.0.1 to not need a password. dzVents uses that port to send certain commands to Domoticz. Finally make sure you have set your current location in Setup > Settings > System > Location, otherwise there is no way to determine nighttime/daytime state."
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
krommetje3108
Posts: 12
Joined: Saturday 05 November 2016 7:52
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.5877
Location: netherlands
Contact:

Re: Get online airquality data

Post by krommetje3108 »

> Yes. You most likely saved it as a Lua script. It should be saved as a dzVents script.

Oops, do I feel a little bit .... (well you know)

For Nitrous Oxide, values are there ;-) but....,
Update 10:48: I've put the station's Lat/Long in the script, now I've got Ozone PM2.5 and PM10 as well....Carbon Monide and SO2 still nothing
Perhaps this staion does not send them...

Here part of my Log:

Code: Select all

2019-06-08 10:30:03.295 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.468096;5.631230/?token=TOKEN REMOVED
2019-06-08 10:30:03.295 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-08 10:30:03.295 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-08 10:30:03.295 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-08 10:30:03.296 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_nearby
2019-06-08 10:30:03.297 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-08 10:30:03.298 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-08 10:30:05.039 Status: dzVents: Info: Handling httpResponse-events for: "waqi_nearby
2019-06-08 10:30:05.039 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_nearby"
2019-06-08 10:30:05.117 Status: dzVents: Debug: Waqi: Processing device-adapter for Lachgasgehalte: Custom sensor device adapter
2019-06-08 10:30:05.117 Status: dzVents: Error (2.4.22): Waqi: An error occured when calling event handler Waqi_1
2019-06-08 10:30:05.118 Status: dzVents: Error (2.4.22): Waqi: ...pi/domoticz/scripts/dzVents/generated_scripts/Waqi_1.lua:135: attempt to index field '?' (a nil value)
2019-06-08 10:30:05.118 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-08 10:30:05.118 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Get online airquality data

Post by waaren »

krommetje3108 wrote: Saturday 08 June 2019 10:36 > Yes. You most likely saved it as a Lua script. It should be saved as a dzVents script.

Oops, do I feel a little bit .... (well you know)

For Nitrous Oxide, values are there ;-) but....,
Update 10:48: I've put the station's Lat/Long in the script, now I've got Ozone PM2.5 and PM10 as well....Carbon Monide and SO2 still nothing
Perhaps this station does not send them...
Can you replace in your script the function handleResponse with

Code: Select all

        local function handleResponse(type)
            local rt = triggerItem.json                        -- rt is just a reference to the data no actual copy is done
			dz.log(triggerItem.data,dz.LOG_DEBUG)
            if triggerItem.json ~= nil and rt.data ~= nil and tonumber(rt.data.aqi) then
                if type == "nearby" then
                    rt.data.iaqi["aqi"] = {}; rt.data.iaqi["aqi"].v = rt.data.aqi    -- handle exception in iaqi as aqi is stored elsewhere
                    
                    for nearbyType, location in pairs(geo) do
                        if nearbyType ~= "nearby" and location == "" then               -- No other location for this type 
                            handleResponse(nearbyType)    
                        end    
                    end
                else
                    for setDevice, idx in pairs(sensors[type]) do
						dz.log("setDevice" .. setDevice, dz.log_DEBUG)
						dz.log("idx" .. idx, dz.log_DEBUG)
						dz.log("sensors[Type]" .. tostring(sensors[Type]), dz.log_DEBUG)
						dz.log("rt" .. tostring(rt), dz.log_DEBUG)
						dz.log("rt.data" .. tostring(rt.data), dz.log_DEBUG)
						dz.log("rt.data.iaqi" .. tostring(rt.data.iaqi), dz.log_DEBUG)
						dz.log("rt.data.iaqi[type]" .. tostring(rt.data.iaqi[type]), dz.log_DEBUG)
                        setSensor(idx,rt.data.iaqi[type:lower()].v)
                    end
                end
            else
                errorMessage("This should not happen")   -- aqi should always be there and set
                if dz.data.safedMessage.get(1).time.secondsAgo > 30 then
                    errorMessage("I will call url again")   -- aqi should always be there and set
                    callPollutionURL(geo[responseType(triggerItem.trigger)],triggerItem.trigger,1)
                    dz.data.safedMessage.add("Extra call to openURL for " .. triggerItem.trigger)
                end    
            end
        end
This will only add some extra debug logging
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
User avatar
FireWizard
Posts: 1770
Joined: Tuesday 25 December 2018 12:11
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: Voorthuizen (NL)
Contact:

Re: Get online airquality data

Post by FireWizard »

Hi,

Do you know that a Domoticz plugin for air quality exists?

See: https://openaq.org
Plugin: https://github.com/Xorfor/Domoticz-OpenAQ-Plugin

It's easier than inventing the wheel twice.
If you are in The Netherlands you can also use the script in this thread:
https://www.domoticz.com/forum/viewtopic.php?t=17334

Regards.
krommetje3108
Posts: 12
Joined: Saturday 05 November 2016 7:52
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.5877
Location: netherlands
Contact:

Re: Get online airquality data

Post by krommetje3108 »

FireWizard wrote: Saturday 08 June 2019 22:23 Hi,

Do you know that a Domoticz plugin for air quality exists?

See: https://openaq.org
Plugin: https://github.com/Xorfor/Domoticz-OpenAQ-Plugin

It's easier than inventing the wheel twice.
If you are in The Netherlands you can also use the script in this thread:
https://www.domoticz.com/forum/viewtopic.php?t=17334

Regards.
I am going to look into this..., thnks
krommetje3108
Posts: 12
Joined: Saturday 05 November 2016 7:52
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.5877
Location: netherlands
Contact:

Re: Get online airquality data

Post by krommetje3108 »

Can you replace in your script the function handleResponse with

...........
This will only add some extra debug logging

Code: Select all

2019-06-09 07:46:02.042 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 07:46:31.996 Status: dzVents: Info: Handling httpResponse-events for: "waqi_nearby
2019-06-09 07:46:31.996 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_nearby"
2019-06-09 07:46:32.016 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:47:02.016 Status: dzVents: Info: Handling httpResponse-events for: "waqi_PM10
2019-06-09 07:47:02.016 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_PM10"
2019-06-09 07:47:02.094 Status: dzVents: Debug: Waqi: Processing device-adapter for Adembare grootfijnstof: Custom sensor device adapter
2019-06-09 07:47:02.096 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:47:02.096 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 07:45:32.056 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:45:32.057 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 07:46:01.962 Status: dzVents: Info: Handling httpResponse-events for: "waqi_CO
2019-06-09 07:46:01.962 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_CO"
2019-06-09 07:46:02.040 Status: dzVents: Debug: Waqi: Processing device-adapter for Koolmonoxide Buiten: Custom sensor device adapter
2019-06-09 07:46:02.042 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:46:02.042 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 07:46:31.996 Status: dzVents: Info: Handling httpResponse-events for: "waqi_nearby
2019-06-09 07:46:31.996 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_nearby"
2019-06-09 07:46:32.016 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:47:02.016 Status: dzVents: Info: Handling httpResponse-events for: "waqi_PM10
2019-06-09 07:47:02.016 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_PM10"
2019-06-09 07:47:02.094 Status: dzVents: Debug: Waqi: Processing device-adapter for Adembare grootfijnstof: Custom sensor device adapter
2019-06-09 07:47:02.096 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:47:02.096 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 07:47:32.004 Status: dzVents: Info: Handling httpResponse-events for: "waqi_O3
2019-06-09 07:47:32.005 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_O3"
2019-06-09 07:47:32.082 Status: dzVents: Debug: Waqi: Processing device-adapter for Ozongehalte: Custom sensor device adapter
2019-06-09 07:47:32.084 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 07:47:32.084 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 07:48:01.991 Status: dzVents: Info: Handling httpResponse-events for: "waqi_SO2
2019-06-09 07:48:01.991 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_SO2"
2019-06-09 07:48:02.010 Status: dzVents: Error (2.4.22): Waqi: An error occured when calling event handler Waqi_1
2019-06-09 07:48:02.010 Status: dzVents: Error (2.4.22): Waqi: ...pi/domoticz/scripts/dzVents/generated_scripts/Waqi_1.lua:134: attempt to index field '?' (a nil value)
2019-06-09 07:48:02.010 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:00:01.990 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1:, trigger: every 15 minutes
2019-06-09 08:00:01.992 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.544365;5.867349/?token=token_removed
2019-06-09 08:00:01.993 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.993 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.993 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.993 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_SO2
2019-06-09 08:00:01.994 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.544365;5.867349/?token=token_removed
2019-06-09 08:00:01.994 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.994 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.994 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.994 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_PM25
2019-06-09 08:00:01.994 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.841338;5.857758/?token=token_removed
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_CO
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.544365;5.867349/?token=token_removed
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.995 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.996 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_O3
2019-06-09 08:00:01.996 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.468096;5.631230/?token=token_removed
2019-06-09 08:00:01.996 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.996 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.996 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.996 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_nearby
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.544365;5.867349/?token=token_removed
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_NO2
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: url = http://api.waqi.info/feed/geo:51.544365;5.867349/?token=token_removed
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: method = GET
2019-06-09 08:00:01.997 Status: dzVents: Debug: Waqi: OpenURL: post data = nil
2019-06-09 08:00:01.998 Status: dzVents: Debug: Waqi: OpenURL: headers = nil
2019-06-09 08:00:01.998 Status: dzVents: Debug: Waqi: OpenURL: callback = waqi_PM10
2019-06-09 08:00:01.999 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:00:02.002 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 08:00:03.739 Status: dzVents: Info: Handling httpResponse-events for: "waqi_SO2
2019-06-09 08:00:03.739 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_SO2"
2019-06-09 08:00:03.758 Status: dzVents: Error (2.4.22): Waqi: An error occured when calling event handler Waqi_1
2019-06-09 08:00:03.758 Status: dzVents: Error (2.4.22): Waqi: ...pi/domoticz/scripts/dzVents/generated_scripts/Waqi_1.lua:134: attempt to index field '?' (a nil value)
2019-06-09 08:00:03.759 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:00:33.797 Status: dzVents: Info: Handling httpResponse-events for: "waqi_PM25
2019-06-09 08:00:33.797 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_PM25"
2019-06-09 08:00:33.876 Status: dzVents: Debug: Waqi: Processing device-adapter for Fijnstof: Custom sensor device adapter
2019-06-09 08:00:33.878 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:00:33.879 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 08:01:03.779 Status: dzVents: Info: Handling httpResponse-events for: "waqi_CO
2019-06-09 08:01:03.779 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_CO"
2019-06-09 08:01:03.862 Status: dzVents: Debug: Waqi: Processing device-adapter for Koolmonoxide Buiten: Custom sensor device adapter
2019-06-09 08:01:03.865 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:01:03.865 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 08:01:33.880 Status: dzVents: Info: Handling httpResponse-events for: "waqi_O3
2019-06-09 08:01:33.881 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_O3"
2019-06-09 08:01:33.907 Status: dzVents: Debug: Waqi: Processing device-adapter for Ozongehalte: Custom sensor device adapter
2019-06-09 08:01:33.909 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:01:33.910 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 08:02:03.764 Status: dzVents: Info: Handling httpResponse-events for: "waqi_nearby
2019-06-09 08:02:03.765 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_nearby"
2019-06-09 08:02:03.786 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:02:33.770 Status: dzVents: Info: Handling httpResponse-events for: "waqi_NO2
2019-06-09 08:02:33.770 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_NO2"
2019-06-09 08:02:33.852 Status: dzVents: Debug: Waqi: Processing device-adapter for Lachgasgehalte: Custom sensor device adapter
2019-06-09 08:02:33.854 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
2019-06-09 08:02:33.854 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2019-06-09 08:03:03.756 Status: dzVents: Info: Handling httpResponse-events for: "waqi_PM10
2019-06-09 08:03:03.757 Status: dzVents: Info: Waqi: ------ Start internal script: Waqi_1: HTTPResponse: "waqi_PM10"
2019-06-09 08:03:03.840 Status: dzVents: Debug: Waqi: Processing device-adapter for Adembare grootfijnstof: Custom sensor device adapter
2019-06-09 08:03:03.842 Status: dzVents: Info: Waqi: ------ Finished Waqi_1
as far As I can tell the script wortks fine so I think the sensordata for Idx203 mis not sent by waqi.info...
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Get online airquality data

Post by waaren »

krommetje3108 wrote: Sunday 09 June 2019 8:15 as far As I can tell the script works fine so I think the sensordata for Idx203 mis not sent by waqi.info...
The station eibergen-lintveldseweg (52.1;6.65) seems to be the station nearest to you that does report so2 data
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
krommetje3108
Posts: 12
Joined: Saturday 05 November 2016 7:52
Target OS: Raspberry Pi / ODroid
Domoticz version: 3.5877
Location: netherlands
Contact:

Re: Get online airquality data

Post by krommetje3108 »

Everthing works now!!! Thanx All
mojso
Posts: 92
Joined: Friday 08 November 2019 23:07
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Get online airquality data

Post by mojso »

i use this script

Code: Select all


--[[
data from http://waqi.info/
An API key is required and can be aquired here ==> http://aqicn.org/data-platform/token/

Based on the original idea and script from @elmortero

http://api.waqi.info/feed/geo:51.852062;4.507676/?token=Your_apikey = Zwartewaalstraat, Rotterdam Zuid
http://api.waqi.info/feed/geo:51.986119;4.934413/?token=Your_apikey = Lopik (co)
http://api.waqi.info/feed/geo:51.867238,4.354981/?token=Your_apikey = Leemkuil (so2)
]]--

return {
    on =    {  
                timer           = { "every 5 minutes" },
                httpResponses   = { "waqi*" }                            -- matches callback wildcard 
            },
        
        data    =   {   
                        safedMessage = { history = true, maxItems = 100 , maxHours = 168 }
                    },
        
        logging =   {   level   =   domoticz.LOG_DEBUG,
                        marker  =   "Waqi" },
    
    execute = function(dz, triggerItem)
        
        local apiKey            = "REMOVED"
        local defaultLocation   = "42.00997;20.97114"
        local sensorType
        
        if dz.data.safedMessage.get(1) == nil then
            dz.data.safedMessage.add("Init") 
        end
        
        local geo   = { nearby  = defaultLocation,        -- to get station closest to your home 
                        so2     = "",   -- if value for this item cannot be obtained from "nearby"
                        co      = "",   -- else keep this as an empty string
                        pm25    = "",
                        pm10    = "",
                        o3      = "",
                        no2     = "",
                        aqi     = "",
                      }  
                      
        local sensors = {   so2     = { sensor = 62,  alert = 63 },   -- enter device index Numbers or 0 for sensor and alert "
                            co      = { sensor = 64,  alert = 65    },
                            pm25    = { sensor = 66,  alert = 67  },
                            pm10    = { sensor = 68,  alert = 69  },
                            o3      = { sensor = 70,  alert = 71     },
                            no2     = { sensor = 72,     alert = 73     },
                            aqi     = { sensor = 76,  alert = 75  , aqiSensor = 74},      -- additional Air Quality sensor
                        }
       
        local sensorTypes = { alert = "Alert", aqi = "Air Quality", custom = "Custom Sensor" } 
        
        local function responseType(str)   -- strip waqi_ from string
            return str:gsub("waqi_","")
        end
       
        local function errorMessage(message,notify)   -- Add entry to log and notify to all subsystems
            dz.log(message,dz.LOG_ERROR)
            if notify then 
                dz.notify(message)
            end
        end    
        
        local function callPollutionURL(location,callback,delay)
            local delay = delay or 1
            local url   = "http://api.waqi.info/feed/geo:".. location .. "/?token=" .. apiKey
            dz.openURL({    url         = url,
                            method      = "GET",
                            callback    = callback
                       }).afterSec(delay)
        end
        
        local function getAirQualityData()
            local delay = 1
            for callType, location in pairs(geo) do
                if location ~= "" then
                    callPollutionURL(location,"waqi_" .. callType,delay) 
                    delay = delay + 30                    
                end    
            end
        end
        
        local function alertLevelAQI(value)
            if value < 50 then return dz.ALERTLEVEL_GREEN,"Excellent" end
            if value < 100 then return dz.ALERTLEVEL_YELLOW,"Poor" end
            if value < 150 then return dz.ALERTLEVEL_ORANGE,"Polluted" end
            return dz.ALERTLEVEL_RED,"Dangerous"
        end
        
        function deviceType(device)
            if device ~= nil then
                if dz.devices(device).deviceType:upper() == "GENERAL" then
                    return dz.devices(device).deviceSubType
                else
                    return dz.devices(device).deviceType
                end
            else
                return nil
            end
        end
        
        
        local function setSensor(sensor,value)
            if sensor ~= 0 and value ~= nil then
               
                if deviceType(sensor) == sensorTypes.custom then 
                    dz.devices(sensor).updateCustomSensor(value)
                elseif deviceType(sensor) == sensorTypes.aqi then
                    dz.devices(sensor).updateAirQuality(value)
                else
                    local alertLevel, alertText = alertLevelAQI(value)
                    local alertString = alertText .. "(" .. tostring(value) .. ")"   
                    if dz.devices(sensor).text ~= alertString then
                        dz.devices(sensor).updateAlertSensor(alertLevel, alertString)
                    end
                end 
            end
        end
        
                local function handleResponse(type)
            local rt = triggerItem.json                        -- rt is just a reference to the data no actual copy is done
			dz.log(triggerItem.data,dz.LOG_DEBUG)
            if triggerItem.json ~= nil and rt.data ~= nil and tonumber(rt.data.aqi) then
                if type == "nearby" then
                    rt.data.iaqi["aqi"] = {}; rt.data.iaqi["aqi"].v = rt.data.aqi    -- handle exception in iaqi as aqi is stored elsewhere
                    
                    for nearbyType, location in pairs(geo) do
                        if nearbyType ~= "nearby" and location == "" then               -- No other location for this type 
                            handleResponse(nearbyType)    
                        end    
                    end
                else
                    for setDevice, idx in pairs(sensors[type]) do
						dz.log("setDevice" .. setDevice, dz.log_DEBUG)
						dz.log("idx" .. idx, dz.log_DEBUG)
						dz.log("sensors[Type]" .. tostring(sensors[Type]), dz.log_DEBUG)
						dz.log("rt" .. tostring(rt), dz.log_DEBUG)
						dz.log("rt.data" .. tostring(rt.data), dz.log_DEBUG)
						dz.log("rt.data.iaqi" .. tostring(rt.data.iaqi), dz.log_DEBUG)
						dz.log("rt.data.iaqi[type]" .. tostring(rt.data.iaqi[type]), dz.log_DEBUG)
                        setSensor(idx,rt.data.iaqi[type:lower()].v)
                    end
                end
            else
                errorMessage("This should not happen")   -- aqi should always be there and set
                if dz.data.safedMessage.get(1).time.secondsAgo > 30 then
                    errorMessage("I will call url again")   -- aqi should always be there and set
                    callPollutionURL(geo[responseType(triggerItem.trigger)],triggerItem.trigger,1)
                    dz.data.safedMessage.add("Extra call to openURL for " .. triggerItem.trigger)
                end    
            end
        end
        
        if triggerItem.isHTTPResponse then
           if triggerItem.ok and triggerItem.isJSON then 
               handleResponse(responseType(triggerItem.trigger))
           else
               errorMessage("Problem with response from waqi",true)  
           end
        else
            getAirQualityData()
        end    
    end
}
i get all the values ​​but i get this error

2019-11-11 15:30:00.835 Error: dzVents: Error: (2.5.0) Waqi: An error occurred when calling event handler AirQ4
2019-11-11 15:30:00.835 Error: dzVents: Error: (2.5.0) Waqi: .../pi/domoticz/scripts/dzVents/generated_scripts/AirQ4.lua:136: bad argument #1 to 'for iterator' (table expected, got nil)
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests