-- ~/domoticz/scripts/lua/script_device_increaselight.lua
-- On pressing a single button, script reads current light level
--  and increases by 1 dimming level


function dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end

function os.capture(cmd, raw)
  local f = assert(io.popen(cmd, 'r'))
  local s = assert(f:read('*a'))
  f:close()
  if raw then return s end
  s = string.gsub(s, '^%s+', '')
  s = string.gsub(s, '%s+$', '')
  s = string.gsub(s, '[\n\r]+', ' ')
  return s
end
decodeurjson = (loadfile "/home/souti/domoticz/scripts/lua/JSON.lua")()

commandArray = {}
-- Path to curl
local curl = '/usr/bin/curl'
-- Device ID
local idx = '493'
--serveur domoticz
dz = "192.168.1.3:81"

local cmd = curl .. ' "http://'..dz..'/json.htm?type=devices&rid='..idx..'"'
local json = os.capture(cmd , false)
donneesJson = decodeurjson:decode(json)
print(dump(donneesJson))
level = donneesJson['result']
print(dump(level))
print('json: ' .. donneesJson['result'][1]["Level"])



commandArray = {}
-- No of dimming steps of device
MaxDimLevel = 100
step = 100.0 / MaxDimLevel
increment = 10
button = 'dimmapp'
light = 'Appliques'
if (devicechanged[button]) then
    -- Need to test for not "Off" rather than "On", as when light
    --   on svalue can be "On" or "Set Level"
    if ('Off' ~= string.len(otherdevices_svalues[light])) then
       local Level = tonumber(Level)
       if (Level < MaxDimLevel) then
          Level = step * Level
          newlevel =  mat.ceil(level + (increment * step))
          print('Increase ' .. light .. ' from ' .. math.ceil(Level) .. '% to ' .. newlevel .. '%')
          commandArray[light]='Set Level ' .. newlevel
       end
    end
end

return commandArray


