dzVents OpenURL json to LUA how to read  [Solved]

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

snuiter
Posts: 67
Joined: Saturday 17 June 2017 12:30
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

dzVents OpenURL json to LUA how to read

Post by snuiter »

Hi,
I am trying to get the weatherdetails from the KNMI API via

http://weerlive.nl/api/json-data-10min. ... ,5.1124231

The result from the openurl is in the following format
Spoiler: show
{ "liveweer": [{"plaats": "None", "temp": "0", "gtemp": "0", "samenv": "Gebruik een plaatsnaam of lat/lon-paar om het weerbericht op te vragen", "lv": "0", "windr": "0", "windms": "0", "winds": "0", "windk": "0", "windkmh": "0", "luchtd": "0", "ldmmhg": "0", "dauwp": "0", "zicht": "0", "verw": "0", "sup": "0", "sunder": "0", "image": "0", "d0weer": "0", "d0tmax": "0", "d0tmin": "0", "d0windk": "0", "d0windknp": "0", "d0windms": "0", "d0windkmh": "0", "d0windr": "0", "d0neerslag": "0", "d0zon": "0", "d1weer": "0", "d1tmax": "0", "d1tmin": "0", "d1windk": "0", "d1windknp": "0", "d1windms": "0", "d1windkmh": "0", "d1windr": "0", "d1neerslag": "0", "d1zon": "0", "d2weer": "0", "d2tmax": "0", "d2tmin": "0", "d2windk": "0", "d2windknp": "0", "d2windms": "0", "d2windkmh": "0", "d2windr": "0", "d2neerslag": "0", "d2zon": "0", "alarm": "0", "alarmtxt": "0"}]}
Now I am trying to retrieve the specific values from the output, I convert the JSON to a LUA table. Looking in the forum, internet and the dzVents wiki but not getting any value out of it.

Any ideas, this is the if loop in the script I am using? I have tried many formats but no luck, never any value in my output apart from the '-'

Appreciate your suggestions or hints in the right direction :D
Spoiler: show

Code: Select all

		if (item.isHTTPResponse) then
		    if (item.statusCode == 200) and (item.isJSON) then
                          domoticz.log('JSON was detected',domoticz.LOG_FORCE)
		          print("-----------------------------")
	         	  -- print(item.data)
            	          print("-")
               	          print("-")
               	          print("-")
                          local a = domoticz.utils.fromJSON(item.data)
                          print(a)
            	          print(a[3].value)
                          print("-")
                          print(a.liveweer.plaats)
                          for i,line in ipairs(a) do
                               print(line)
                          end
                          print("-")
    			   print("-----------------------------")
				-- 	domoticz.devices('testweer').updateText(someValue) 					-- update some device in Domoticz
			else
				domoticz.log('There was a problem handling the request', domoticz.LOG_ERROR)
				domoticz.log(item, domoticz.LOG_ERROR)
	        end
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

snuiter wrote: Saturday 02 March 2019 21:37 Hi, I am trying to get the weatherdetails from the KNMI API. Appreciate your suggestions or hints in the right direction :D
Have a look at this one

Code: Select all

-- knmi.lua

return { 
            on = {   timer  =   { "every minute" },},
       
        logging    =    {   
                            level       =  domoticz.LOG_DEBUG,   
                            marker      =  "KNMI" 
                        },    

    execute = function(dz)
        local function logWrite(str,level)             -- Support function for shorthand debug log statements
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        local testData = '{ "liveweer": [{"plaats": "None", "temp": "0", "gtemp": "0", "samenv": "Gebruik een plaatsnaam of lat/lon-paar om het weerbericht op te vragen", "lv": "0", "windr": "0", "windms": "0", "winds": "0", "windk": "0", "windkmh": "0", "luchtd": "0", "ldmmhg": "0", "dauwp": "0", "zicht": "0", "verw": "0", "sup": "0", "sunder": "0", "image": "0", "d0weer": "0", "d0tmax": "0", "d0tmin": "0", "d0windk": "0", "d0windknp": "0", "d0windms": "0", "d0windkmh": "0", "d0windr": "0", "d0neerslag": "0", "d0zon": "0", "d1weer": "0", "d1tmax": "0", "d1tmin": "0", "d1windk": "0", "d1windknp": "0", "d1windms": "0", "d1windkmh": "0", "d1windr": "0", "d1neerslag": "0", "d1zon": "0", "d2weer": "0", "d2tmax": "0", "d2tmin": "0", "d2windk": "0", "d2windknp": "0", "d2windms": "0", "d2windkmh": "0", "d2windr": "0", "d2neerslag": "0", "d2zon": "0", "alarm": "0", "alarmtxt": "0"}]}'

        local rt        = dz.utils.fromJSON(testData)        -- convert complete json to table
        local weer      = rt.liveweer[1]                     -- liveweer is a key in table (or "associative array") rt and contains one or more subtables. You want the first one
        for key, value in pairs(weer) do
            logWrite(key .. ": " .. tostring(value))
        end
    end
}
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
snuiter
Posts: 67
Joined: Saturday 17 June 2017 12:30
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by snuiter »

Thank you !! got it figured out now, and then it becomes so simple to use.... :roll:

waaren wrote: Saturday 02 March 2019 22:37 Have a look at this one

Code: Select all

-- knmi.lua

return { 
            on = {   timer  =   { "every minute" },},
       
        logging    =    {   
                            level       =  domoticz.LOG_DEBUG,   
                            marker      =  "KNMI" 
                        },    

    execute = function(dz)
        local function logWrite(str,level)             -- Support function for shorthand debug log statements
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        local testData = '{ "liveweer": [{"plaats": "None", "temp": "0", "gtemp": "0", "samenv": "Gebruik een plaatsnaam of lat/lon-paar om het weerbericht op te vragen", "lv": "0", "windr": "0", "windms": "0", "winds": "0", "windk": "0", "windkmh": "0", "luchtd": "0", "ldmmhg": "0", "dauwp": "0", "zicht": "0", "verw": "0", "sup": "0", "sunder": "0", "image": "0", "d0weer": "0", "d0tmax": "0", "d0tmin": "0", "d0windk": "0", "d0windknp": "0", "d0windms": "0", "d0windkmh": "0", "d0windr": "0", "d0neerslag": "0", "d0zon": "0", "d1weer": "0", "d1tmax": "0", "d1tmin": "0", "d1windk": "0", "d1windknp": "0", "d1windms": "0", "d1windkmh": "0", "d1windr": "0", "d1neerslag": "0", "d1zon": "0", "d2weer": "0", "d2tmax": "0", "d2tmin": "0", "d2windk": "0", "d2windknp": "0", "d2windms": "0", "d2windkmh": "0", "d2windr": "0", "d2neerslag": "0", "d2zon": "0", "alarm": "0", "alarmtxt": "0"}]}'

        local rt        = dz.utils.fromJSON(testData)        -- convert complete json to table
        local weer      = rt.liveweer[1]                     -- liveweer is a key in table (or "associative array") rt and contains one or more subtables. You want the first one
        for key, value in pairs(weer) do
            logWrite(key .. ": " .. tostring(value))
        end
    end
}
pvklink
Posts: 822
Joined: Wednesday 12 November 2014 15:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest b
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by pvklink »

Hi @waaren, need your help again!
Wunderground has changed its ratings and i want to get rid of it. I use the temperature for managing a livingboat like a told before.
I just made an account with http://weerlive.nl/api/json-data-10min. ... =Amsterdam and i can use it every 5 minutes for free!
Do you also have a dzvents version of the lua script ?
Raspberry (raspbian on rpi 3) , Domoticz Beta, dzVents , RFXtrx433e, P1, Hue, Yeelight, Zwave+, X10, ESP(easy), MQTT,Weather Underground, System Alive Checker, Domoticz Remote Server to RPI with Google Assistant,
Jablotron connection, Ikea
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

pvklink wrote: Saturday 09 March 2019 9:57 Hi @waaren, need your help again!
Wunderground has changed its ratings and i want to get rid of it. I use the temperature for managing a livingboat like a told before.
I just made an account with http://weerlive.nl/api/json-data-10min. ... =Amsterdam and i can use it every 5 minutes for free!
Do you also have a dzvents version of the lua script ?
Something like this ?

Code: Select all

local response = "KNMI_response"

return {
    on =        {       timer           =   { "every 10 minutes" },
                        httpResponses   =   {  response } },                         
              
    logging =   {       level   =   domoticz.LOG_DEBUG,      -- change to LOG_ERROR when script runs without problems                                  
                        marker  =   "getTemperatures" },                                           

    execute = function(dz, item)
        local apikey        = "xxxxxxxxx" 
        local latitude      = dz.settings.location.latitude   -- replace with your latitude when not yet on dzVents V2.4.14
        local longitude     = dz.settings.location.longitude  -- replace with your longitude when not yet on dzVents V2.4.14

        local currentTemp   = dz.devices(nnn)   -- define as virtual sensor type Temperature or comment this line if not needed  
        local maxTemp       = dz.devices(nnn)    -- define as virtual sensor type Temperature or comment this line if not needed    
        local minTemp       = dz.devices(nnn)    -- define as virtual sensor type Temperature or comment this line if not needed 
        local windChill     = dz.devices(nnn)   -- define as virtual sensor type Temperature or comment this line if not needed 
                
        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        if item.isHTTPResponse then
            local weer  = {}
            weer        = item.json.liveweer[1]
            logWrite("Temperaturen voor    : " .. weer.plaats    )
            logWrite("---------------------------------------------------")
            logWrite("Huidige temperatuur  : " .. weer.temp      )
            logWrite("Gevoels temperatuur  : " .. weer.gtemp     )
            logWrite("Max temperatuur      : " .. weer.d0tmax    )
            logWrite("Min temperatuur      : " .. weer.d0tmin    )
            if maxTemp       then maxTemp.updateTemperature(weer.d0tmax)    end
            if minTemp       then minTemp.updateTemperature(weer.d0tmin)    end
            if currentTemp   then currentTemp.updateTemperature(weer.temp)  end
            if windChill     then windChill.updateTemperature(weer.gtemp)   end
        else

            local url = "http://weerlive.nl/api/json-data-10min.php?key=" .. apikey .. "&locatie=" .. 
                        latitude .. "," ..
                        longitude 
                                        
            dz.openURL({
                  url = url,
                        method = "GET",
                        callback = response})
        end
    end
}

Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
pvklink
Posts: 822
Joined: Wednesday 12 November 2014 15:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest b
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by pvklink »

@waaren, thank you very much!
It works GREAAATTTT
now killing my wunderground.....
Raspberry (raspbian on rpi 3) , Domoticz Beta, dzVents , RFXtrx433e, P1, Hue, Yeelight, Zwave+, X10, ESP(easy), MQTT,Weather Underground, System Alive Checker, Domoticz Remote Server to RPI with Google Assistant,
Jablotron connection, Ikea
pvklink
Posts: 822
Joined: Wednesday 12 November 2014 15:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest b
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by pvklink »

Hi, i added value "alarmtxt" and that wend well when there is an alarm.
But for now there isn't an alarm, and in that case the variable isnt even there in the list, instead of "alarmtxt": ""
Where do i put the check if the variable alarmtxt is available?

Code: Select all

-- { "liveweer": [{"plaats": "Amsterdam", "temp": "8.6", "gtemp": "4.3", "samenv": "Geheel bewolkt", "lv": "74", "windr": "ZW", "windms": "10", "winds": "5", "windk": "19.4", "windkmh": "36", 
--"luchtd": "1008.5", "ldmmhg": "756", "dauwp": "4", "zicht": "16", "verw": "Kans op zware windstoten. Vanmiddag buien.", "sup": "07:06", "sunder": "18:36", "image": "bewolkt", "d0weer": "bewolkt", 
-- "d0tmax": "9", "d0tmin": "5", "d0windk": "4", "d0windknp": "16", "d0windms": "8", "d0windkmh": "30", "d0windr": "W", "d0neerslag": "8", "d0zon": "0", "d1weer": "regen", "d1tmax": "5", "d1tmin": "5", 
-- "d1windk": "3", "d1windknp": "8", "d1windms": "4", "d1windkmh": "15", "d1windr": "W", "d1neerslag": "90", "d1zon": "10", "d2weer": "regen", "d2tmax": "7", "d2tmin": "2", "d2windk": "3", "d2windknp": "10", 
-- "d2windms": "5", "d2windkmh": "19", "d2windr": "W", "d2neerslag": "70", "d2zon": "30", "alarm": "1", 
-- "alarmtxt": "Aan het einde van de ochtend en in de middag is er vooral bij buien kans op zware windstoten van 75-90 km/uur uit westelijke richtingen.  
-- In de loop van de middag en vanavond neemt de wind van het westen uit af."}]}
-- http://weerlive.nl/api/json-data-10min.php?key=xxxxxxf&locatie=xxxxx,xxxxxx

local response = "KNMI_response"

return {
    on =        {       timer           =   { "every 10 minutes" },
                        httpResponses   =   {  response } },                         
              
    logging =   {       level   =   domoticz.LOG_ERROR,      -- change to LOG_ERROR when script runs without problems otherwise LOG_DEBUG                             
                        marker  =   "getTemperatures" },                                           

    execute = function(dz, item)
        local apikey        = "xxxxxxx"
        local latitude      = dz.settings.location.latitude  
        local longitude     = dz.settings.location.longitude  

        local currentTemp   = dz.devices('Strijp_temp')   -- define as virtual sensor type Temperature or comment this line if not needed  
        local currentalarm  = dz.devices('Weeralarm')   -- define as virtual sensor type Temperature or comment this line if not needed  

        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        if item.isHTTPResponse then
            local weer  = {}
            weer        = item.json.liveweer[1]
            logWrite("Temperaturen voor    : " .. weer.plaats    )
            logWrite("---------------------------------------------------")
            logWrite("Huidige temperatuur  : " .. weer.temp      )
            logWrite("Alarm                : " .. weer.alarmtxt  )

            if currentTemp   then currentTemp.updateTemperature(weer.temp)  end
            if currentalarm  then currentalarm.updateText(weer.alarmtxt)    end
        
        else

            local url = "http://weerlive.nl/api/json-data-10min.php?key=" .. apikey .. "&locatie=" .. 
                        latitude .. "," ..
                        longitude 
                                        
            dz.openURL({
                  url = url,
                        method = "GET",
                        callback = response})
        end
    end
}
Raspberry (raspbian on rpi 3) , Domoticz Beta, dzVents , RFXtrx433e, P1, Hue, Yeelight, Zwave+, X10, ESP(easy), MQTT,Weather Underground, System Alive Checker, Domoticz Remote Server to RPI with Google Assistant,
Jablotron connection, Ikea
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

pvklink wrote: Monday 11 March 2019 19:25 Hi, i added value "alarmtxt" and that wend well when there is an alarm.
But for now there isn't an alarm, and in that case the variable isnt even there in the list, instead of "alarmtxt": ""
Where do i put the check if the variable alarmtxt is available?
changing line

Code: Select all

if currentalarm  then currentalarm.updateText(weer.alarmtxt)    end
to

Code: Select all

if currentalarm  then currentalarm.updateText(weer.alarmtxt or "Geen alarm" )    end
should do it.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
pvklink
Posts: 822
Joined: Wednesday 12 November 2014 15:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest b
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by pvklink »

Hi,
remarkable that you can set n or statement in a place where a value is expected!
i was trying with:
if weer.alarmtxt ~= nil then
if currentalarm then currentalarm.updateText(weer.alarmtxt) end
end
but your solution is much better!
Raspberry (raspbian on rpi 3) , Domoticz Beta, dzVents , RFXtrx433e, P1, Hue, Yeelight, Zwave+, X10, ESP(easy), MQTT,Weather Underground, System Alive Checker, Domoticz Remote Server to RPI with Google Assistant,
Jablotron connection, Ikea
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

pvklink wrote: Monday 11 March 2019 20:26 remarkable that you can set an or statement in a place where a value is expected!
That is the way the "or" syntax works in most languages. Only if the left part of an "or" statement evaluates to false / nil; the right part is evaluated. If the left part evaluaties to anything else; the right part is ignored.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
pvklink
Posts: 822
Joined: Wednesday 12 November 2014 15:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest b
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by pvklink »

2019-03-11 20:50:01.643 Status: dzVents: Error (2.4.15): getTemperatures: An error occured when calling event handler DZ_weer
2019-03-11 20:50:01.643 Status: dzVents: Error (2.4.15): getTemperatures: ...i/domoticz/scripts/dzVents/generated_scripts/DZ_weer.lua:38: attempt to concatenate field 'alarmtxt' (a nil value)


i will try this :
if weer.alarmtxt ~= nil then
logWrite("Alarm : " .. weer.alarmtxt )
end

@update: this works! and now i also have a fine message when there is no warning, so thanks again!
Last edited by pvklink on Monday 11 March 2019 21:12, edited 1 time in total.
Raspberry (raspbian on rpi 3) , Domoticz Beta, dzVents , RFXtrx433e, P1, Hue, Yeelight, Zwave+, X10, ESP(easy), MQTT,Weather Underground, System Alive Checker, Domoticz Remote Server to RPI with Google Assistant,
Jablotron connection, Ikea
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

pvklink wrote: Monday 11 March 2019 20:53 2019-03-11 20:50:01.643 Status: dzVents: Error (2.4.15): getTemperatures: ...i/domoticz/scripts/dzVents/generated_scripts/DZ_weer.lua:38: attempt to concatenate field 'alarmtxt' (a nil value)
you can do something similar there. Try

Code: Select all

logWrite("Alarm                : " .. (weer.alarmtxt or "Geen weeralarm actief") )
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
pvklink
Posts: 822
Joined: Wednesday 12 November 2014 15:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest b
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by pvklink »

oh, does that or also works in that place, i will change it!
Raspberry (raspbian on rpi 3) , Domoticz Beta, dzVents , RFXtrx433e, P1, Hue, Yeelight, Zwave+, X10, ESP(easy), MQTT,Weather Underground, System Alive Checker, Domoticz Remote Server to RPI with Google Assistant,
Jablotron connection, Ikea
Bitterbal
Posts: 3
Joined: Thursday 02 January 2020 18:14
Target OS: -
Domoticz version:
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by Bitterbal »

Hi all,

I started today with Domoticz so newbie question here.
I used the code from Waaren shown below, filled in my api key and saved it as .lua file in de Domoticz folder.
What I expected was an automatic update in my devices list with the weather information.
Nothing is happening. Do I need to add a dummy hardware device or something?
Still figuring out all the options of Domoticz.

Furthermore, the information I also wanted to get from the api is sun set and sun rise. How to include those?
Edit: I was looking for these parameters: https://weerlive.nl/delen.php
sun set and sun rise is added to the code using the parameters mentioned in the link.
waaren wrote: Saturday 09 March 2019 10:57 Something like this ?

Code: Select all

local response = "KNMI_response"

return {
    on =        {       timer           =   { "every 10 minutes" },
                        httpResponses   =   {  response } },                         
              
    logging =   {       level   =   domoticz.LOG_DEBUG,      -- change to LOG_ERROR when script runs without problems                                  
                        marker  =   "getTemperatures" },                                           

    execute = function(dz, item)
        local apikey        = "xxxxxxxxx" 
        local latitude      = dz.settings.location.latitude   -- replace with your latitude when not yet on dzVents V2.4.14
        local longitude     = dz.settings.location.longitude  -- replace with your longitude when not yet on dzVents V2.4.14

        local currentTemp   = dz.devices(nnn)   -- define as virtual sensor type Temperature or comment this line if not needed  
        local maxTemp       = dz.devices(nnn)    -- define as virtual sensor type Temperature or comment this line if not needed    
        local minTemp       = dz.devices(nnn)    -- define as virtual sensor type Temperature or comment this line if not needed 
        local windChill     = dz.devices(nnn)   -- define as virtual sensor type Temperature or comment this line if not needed 
                
        local function logWrite(str,level)
            dz.log(tostring(str),level or dz.LOG_DEBUG)
        end
        
        if item.isHTTPResponse then
            local weer  = {}
            weer        = item.json.liveweer[1]
            logWrite("Temperaturen voor    : " .. weer.plaats    )
            logWrite("---------------------------------------------------")
            logWrite("Huidige temperatuur  : " .. weer.temp      )
            logWrite("Gevoels temperatuur  : " .. weer.gtemp     )
            logWrite("Max temperatuur      : " .. weer.d0tmax    )
            logWrite("Min temperatuur      : " .. weer.d0tmin    )
            if maxTemp       then maxTemp.updateTemperature(weer.d0tmax)    end
            if minTemp       then minTemp.updateTemperature(weer.d0tmin)    end
            if currentTemp   then currentTemp.updateTemperature(weer.temp)  end
            if windChill     then windChill.updateTemperature(weer.gtemp)   end
        else

            local url = "http://weerlive.nl/api/json-data-10min.php?key=" .. apikey .. "&locatie=" .. 
                        latitude .. "," ..
                        longitude 
                                        
            dz.openURL({
                  url = url,
                        method = "GET",
                        callback = response})
        end
    end
}

User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

Bitterbal wrote: Thursday 02 January 2020 18:22 I started today with Domoticz so newbie question here.
When not yet familiar with dzVents please start with reading Get started Before implementing (~ 5 minutes). 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.
I used the code from Waaren shown below, filled in my api key and saved it as .lua file in de Domoticz folder.
What I expected was an automatic update in my devices list with the weather information.
Nothing is happening. Do I need to add a dummy hardware device or something?
Yes you need to define dummy hardware with hardwareType: "Dummy (Does nothing, use for virtual switches only)" first and then create some virtual sensors as described in the script using the button on this hardware (on the hardware tab)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Bitterbal
Posts: 3
Joined: Thursday 02 January 2020 18:14
Target OS: -
Domoticz version:
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by Bitterbal »

Thanks waaren for the link. I already set the settings you mentioned, but I made a mistake by placing the lua file in Domoticz\scripts instead of Domoticz\scripts\dzVents\scripts. I got it working now :)
jake
Posts: 744
Joined: Saturday 30 May 2015 22:40
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by jake »

@waaren : I managed in the past succesfully to work with a json in my dzvents script. With the next one, I don't get it to work, even after digging around on the internet for help. I assume I don't have a 100% understanding of json <> lua tables.

When I put this in the browser: http://user:[email protected]:8080/json ... :{booleans:[Player.HasAudio]},id:1}

than the response is: {"id":1,"jsonrpc":"2.0","result":{"Player.HasAudio":false}}


My code snippet is:

Code: Select all

if (device == testButton) then
   domoticz.openURL({
      url = 'http://user:[email protected]:8080/jsonrpc?request={jsonrpc:2.0,method:XBMC.GetInfoBooleans,params:{booleans:[Player.HasAudio]},id:1}',
      method = 'GET',
      callback = 'kodiIdleTimer'
   })
   elseif (device.isHTTPResponse and device.ok) then
      -- we know it is json but dzVents cannot detect this
      -- convert to Lua
      local json = domoticz.utils.fromJSON(device.data)
      -- json is now a Lua table
      
            print("The result true or false from the request is ".. json.result.Player.HasAudio)
elseif (device.isHTTPResponse and device.ok == false) then
  print("Response was not OK)
end
When I flip my testButton, the response in de domoticz log is:

attempt to index a nil value (field 'result')

I guess I have to do something with the Player.HasAudio, because it is on 1 level, but the 'dot' makes it look like the 'next level down'?
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

jake wrote: Sunday 30 August 2020 23:54 When I flip my testButton, the response in de domoticz log is: attempt to index a nil value (field 'result')
What do you see with this code snippet?

Code: Select all

if (device == testButton) then
   domoticz.openURL({
      url = 'http://user:[email protected]:8080/jsonrpc?request={jsonrpc:2.0,method:XBMC.GetInfoBooleans,params:{booleans:[Player.HasAudio]},id:1}',
      method = 'GET',
      callback = 'kodiIdleTimer'
   })
   elseif (device.isHTTPResponse and device.ok) then
      -- we know it is json but dzVents cannot detect this
      -- convert to Lua
      local json = domoticz.utils.fromJSON(device.data)
      -- json is now a Lua table
      
	 domoticz.log(device.data,domoticz.LOG_FORCE)
         domoticz.utils.dumpTable(json)
      
      print("The result true or false from the request is ".. json[1].result['Player.HasAudio'])
elseif (device.isHTTPResponse and device.ok == false) then
  print("Response was not OK)
end
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
jake
Posts: 744
Joined: Saturday 30 May 2015 22:40
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by jake »

waaren wrote:
jake wrote: Sunday 30 August 2020 23:54 When I flip my testButton, the response in de domoticz log is: attempt to index a nil value (field 'result')
What do you see with this code snippet?

Code: Select all

if (device == testButton) then
   domoticz.openURL({
      url = 'http://user:[email protected]:8080/jsonrpc?request={jsonrpc:2.0,method:XBMC.GetInfoBooleans,params:{booleans:[Player.HasAudio]},id:1}',
      method = 'GET',
      callback = 'kodiIdleTimer'
   })
   elseif (device.isHTTPResponse and device.ok) then
      -- we know it is json but dzVents cannot detect this
      -- convert to Lua
      local json = domoticz.utils.fromJSON(device.data)
      -- json is now a Lua table
      
	 domoticz.log(device.data,domoticz.LOG_FORCE)
         domoticz.utils.dumpTable(json)
      
      print("The result true or false from the request is ".. json[1].result['Player.HasAudio'])
elseif (device.isHTTPResponse and device.ok == false) then
  print("Response was not OK)
end
The force log learned me stuff:

Code: Select all

2020-08-31 18:14:57.112 Status: dzVents: !Info: {"error":{"code":-32700,"message":"Parse error."},"id":null,"jsonrpc":"2.0"}
2020-08-31 18:14:57.112 Status: dzVents: > jsonrpc: 2.0
2020-08-31 18:14:57.112 Status: dzVents: > error:
2020-08-31 18:14:57.112 Status: dzVents: > code: -32700
2020-08-31 18:14:57.112 Status: dzVents: > message: Parse error.
The result showed id:"null", while in the browser it is displayed as id: 1
This triggered me to put the " " back in the url: {"jsonrpc":"2.0","method":"XBMC.GetInfoBooleans","params":{"booleans":["Player.HasAudio"]},"id":1}

This improved the results in the log:

Code: Select all

2020-08-31 18:56:51.571 Status: dzVents: !Info: {"id":1,"jsonrpc":"2.0","result":{"Player.HasAudio":false}}
2020-08-31 18:56:51.571 Status: dzVents: > jsonrpc: 2.0
2020-08-31 18:56:51.571 Status: dzVents: > id: 1
2020-08-31 18:56:51.571 Status: dzVents: > result:
2020-08-31 18:56:51.571 Status: dzVents: > Player.HasAudio: false
2020-08-31 18:56:51.980 Status: EventSystem: Script event triggered: /home/pi/domoticz/dzVents/runtime/dzVents.lua
2020-08-31 18:56:51.571 Error: dzVents: Error: (2.5.7) An error occurred when calling event handler kodi3
2020-08-31 18:56:51.571 Error: dzVents: Error: (2.5.7) /home/pi/domoticz/scripts/dzVents/scripts/kodi3.lua:192: attempt to index a nil value (field '?')
Line 192 is:

Code: Select all

print("The result true or false from the request is ".. json[1].result['Player.HasAudio'])
UPDATE: well, well, I finally got it: I first 'tried' to change line 192 to json.result['Player.HasAudio']. This gave me the clue in the log:

Code: Select all

Error: (2.5.7) /home/pi/domoticz/scripts/dzVents/scripts/kodi3.lua:192: attempt to concatenate a boolean value (field 'Player.HasAudio
So i tried a different line of code on line 192 and finally with success:
if json.result['Player.HasAudio'] == false then print ("No audio is playing") end:

Code: Select all

2020-08-31 19:14:54.734 Status: dzVents: No audio is playing 
2020-08-31 19:14:54.734 Status: dzVents: !Info: {"id":1,"jsonrpc":"2.0","result":{"Player.HasAudio":false}}
2020-08-31 19:14:54.734 Status: dzVents: > jsonrpc: 2.0
2020-08-31 19:14:54.734 Status: dzVents: > id: 1
2020-08-31 19:14:54.734 Status: dzVents: > result:
2020-08-31 19:14:54.734 Status: dzVents: > Player.HasAudio: false
Thanks for pointing me in the right direction

Although I can now continue my script, I would like to know out of curiosity how I could still show the 'false' in a log line, instead of domoticz failing with 'attempt to concatenate a boolean value'



User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: dzVents OpenURL json to LUA how to read

Post by waaren »

jake wrote: Monday 31 August 2020 18:59 Although I can now continue my script, I would like to know out of curiosity how I could still show the 'false' in a log line, instead of domoticz failing with 'attempt to concatenate a boolean value'
You can with

Code: Select all

print("The result true or false from the request is ".. tostring(json.result['Player.HasAudio']))
or

Code: Select all

domoticz.log("The result true or false from the request is ".. tostring(json.result['Player.HasAudio']), domoticz.LOG_FORCE)
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest