Jump to content

[TUTORIAL] Introduction to Lua tables (2nd edition)


Recommended Posts

Hi @AutoFrank, sorry to bother you..

 

I remember reading something on the forum about how to create a json table straight from the main loop of a VD when you press save the first time.

But I can't find it. Do you have a clue how to?

 

Thanks,

 

Jim

Link to post
Share on other sites
50 minutes ago, jimicr said:

Hi @AutoFrank, sorry to bother you..

 

I remember reading something on the forum about how to create a json table straight from the main loop of a VD when you press save the first time.

But I can't find it. Do you have a clue how to?

 

Thanks,

 

Jim

 

Hi

 

Now.. The question was obviously not directed to me, but...

 

I do that on several places in my DSC alarm to HC2 integration code. I also extend, modify and delete json tables in the main loop. You can look at my code here and maybe get some inspiration...

http://www.incedo.eu/~sjoholmp/Fibaro_Homecenter/LUA/VDs/HC2_DSCengine/

 

Just ask if you have some questions...

 

Regards

Peo

 

Link to post
Share on other sites
Just now, pos said:

 

Hi

 

Now.. The question was obviously not directed to me, but...

 

I do that on several places in my DSC alarm to HC2 integration code. I also extend, modify and delete json tables in the main loop. You can look at my code here and maybe get some inspiration...

http://www.incedo.eu/~sjoholmp/Fibaro_Homecenter/LUA/VDs/HC2_DSCengine/

 

Just ask if you have some questions...

 

Regards

Peo

 

Thanks, will look at it this weekend!

 

Jim

Link to post
Share on other sites
10 hours ago, jimicr said:

Hi @AutoFrank, sorry to bother you..

 

I remember reading something on the forum about how to create a json table straight from the main loop of a VD when you press save the first time.

But I can't find it. Do you have a clue how to?

 

Thanks,

 

Jim

Hi @jimicr

 

 No bother....

 

Could you expand a little ? 

Are you looking to create a table, json encode it and store it in a newly created global variable or an existing valiable or just create a table to be used local to the main loop?

 

Thanks

_f

Link to post
Share on other sites

Hi @AutoFrank & @pos,

 

I actually found where I read about it, it was in the beta test for @Sankotronic weather VD.

I pieced this together from the post of @petergebruers:

 

Mainloop of a VD:

-- Create if it doesn't exist
if fibaro:getGlobalValue("testTable") ~= nil then
  print("Variable already exists. No 'post' performend")
else
  api.post("/globalVariables",
    {
      name="testTable",
      value="Table", -- optional
    })
-- Modify existing variable to "predefined" style
api.put("/globalVariables/testTable",
  {
    name="testTable",
    value="Table", -- optional
    isEnum=true,
    enumValues=
    {
      "Table",    }
  })

print("Global Variable modified to predefined style")

jsonTest = {
  Test1={check=1},
  Test2={check=true},
  Test3={check=false},
  Test4={check="Hello"},
}

fibaro:setGlobal("testTable", json.encode(jsonTest)) -- store table in global 
  end

To test:

testT = json.decode(fibaro:getGlobalValue("testTable")) -- get the table from global
	local test1 = testT.Test1.check	
	local test2 = testT.Test2.check	
	local test3 = testT.Test3.check	
	local test4 = testT.Test4.check			
fibaro:debug(testT.Test1.check)
fibaro:debug(test1)		
fibaro:debug(testT.Test2.check)
fibaro:debug(test2)		
fibaro:debug(testT.Test3.check)
fibaro:debug(test3)		
fibaro:debug(testT.Test4.check)
fibaro:debug(test4)

And to change the values:

jsonTest = {
  Test1={check=2},
  Test2={check=true},
  Test3={check=false},
  Test4={check="Bye"},
}

fibaro:setGlobal("testTable", json.encode(jsonTest))

The thing I noticed is that as long as the code is in the main loop you can't delete the created Global from the panel.

 

Thanks all for your help!

 

Jim

Link to post
Share on other sites
8 minutes ago, jimicr said:

Hi @AutoFrank & @pos,

 

I actually found where I read about it, it was in the beta test for @Sankotronic weather VD.

I pieced this together from the post of @petergebruers:

 

Mainloop of a VD:

-- Create if it doesn't exist
if fibaro:getGlobalValue("testTable") ~= nil then
  print("Variable already exists. No 'post' performend")
else
  api.post("/globalVariables",
    {
      name="testTable",
      value="Table", -- optional
    })
-- Modify existing variable to "predefined" style
api.put("/globalVariables/testTable",
  {
    name="testTable",
    value="Table", -- optional
    isEnum=true,
    enumValues=
    {
      "Table",    }
  })

print("Global Variable modified to predefined style")

jsonTest = {
  Test1={check=1},
  Test2={check=true},
  Test3={check=false},
  Test4={check="Hello"},
}

fibaro:setGlobal("testTable", json.encode(jsonTest)) -- store table in global 
  end

To test:

testT = json.decode(fibaro:getGlobalValue("testTable")) -- get the table from global
	local test1 = testT.Test1.check	
	local test2 = testT.Test2.check	
	local test3 = testT.Test3.check	
	local test4 = testT.Test4.check			
fibaro:debug(testT.Test1.check)
fibaro:debug(test1)		
fibaro:debug(testT.Test2.check)
fibaro:debug(test2)		
fibaro:debug(testT.Test3.check)
fibaro:debug(test3)		
fibaro:debug(testT.Test4.check)
fibaro:debug(test4)

And to change the values:

jsonTest = {
  Test1={check=2},
  Test2={check=true},
  Test3={check=false},
  Test4={check="Bye"},
}

fibaro:setGlobal("testTable", json.encode(jsonTest))

The thing I noticed is that as long as the code is in the main loop you can't delete the created Global from the panel.

 

Thanks all for your help!

 

Jim

 

Glad you got it sorted @jimicr

 

Link to post
Share on other sites

Looks like I cheered to soon,

I have to do some more tests, creating or trying to delete the Global presses the save button and destroys all the vars...

 

Okay, found out what messed with the Globals: If the creation code exists in the mainloop of a vd and you try to delete it destroys the Globals

Edited by jimicr
Link to post
Share on other sites
22 minutes ago, jimicr said:

Looks like I cheered to soon,

I have to do some more tests, creating or trying to delete the Global presses the save button and destroys all the vars...

 

Okay, found out what messed with the Globals: If the creation code exists in the mainloop of a vd and you try to delete it destroys the Globals

 

Hi @jimicr

 

Is you press save on the global variable page the value stored get corrupt

Try and avoid this if you can.

 

The code to create a global generally had a check to see if it exists before trying to create so if you run it in a main loop then it should only try and create once.

When I am developing code that will run in main loop I first develop it in a button so I can control when it get executed.. might be an approach worth considering for what you're working on ....

 

 

Link to post
Share on other sites
6 minutes ago, AutoFrank said:

 

Hi @jimicr

 

Is you press save on the global variable page the value stored get corrupt

Try and avoid this if you can.

 

The code to create a global generally had a check to see if it exists before trying to create so if you run it in a main loop then it should only try and create once.

When I am developing code that will run in main loop I first develop it in a button so I can control when it get executed.. might be an approach worth considering for what you're working on ....

 

 

I didn't press the save button, that's the weird part.

I had it all working and try to remove the testTable var I created and then all went into a downward spiral :)

Link to post
Share on other sites
1 hour ago, jimicr said:

I didn't press the save button, that's the weird part.

I had it all working and try to remove the testTable var I created and then all went into a downward spiral :)

 

@jimicr

That doesn't make sense...

Did you get it back working ?

Link to post
Share on other sites
1 hour ago, AutoFrank said:

 

@jimicr

That doesn't make sense...

Did you get it back working ?

First (I think) the lua engine crashed all scenes where throwing an error something like :line 35 :T don't remember. Then I noticed that all globals that can be affected turned to the NaN.  

 

Rebooted removed my test vd removed the created global restored all the globals and am back. 

 

Will raise this as an issue later. 

 

Thanks for asking 

Link to post
Share on other sites
  • 1 year later...
  • 2 months later...

Hi all, 

 

I have a request which I expect that can be solved/simplified using JSON and global variables.

 

What am I looking for;

When I arm my alarm I would like to store the value of several lights in house.

After values are stored ( in the enable alarm scene) , I would like to automatically switch all lights off .

 

When the alarm is armed and breached, I want all lights to be set to 100%.

 

When the alarm is disarmed I want to restore the lights to the value at the moment the alarm was enabled.

 

How can I do this without the need for each light to have its own global variable? (I guess JSON table could help).

I'm not a code expert so help is needed.

 

Thanks in advance for help!

 

Regards,

Jules

 

 

 

 

 

Link to post
Share on other sites

Hi

 

You could read all values and write it to a single global var. But that is probably not optimal. You could also write ids and values as pairs in a single predefined variable. Probably better, but still not optimal. I guess JSON in a global variable is not wrong here...

 

Just some thoughts...

I do the opposite to what you do. When I arm my alarm and leave, an "away lights" scene starts. That have both fixed times and times related to sunrise and sunset. I automate lights in the house when away to make potential burglars believe someone is at home. If it is dark, a burglar knows for sure you are away. When I get home and disarm, the scene stops. The scene however leaves the lights in the current state they had at disarm time. Thats me :)

 

Peo

Link to post
Share on other sites
  • 1 year later...

i was trying to go through this turorial. Especially the saving and reading of tables to global variables interests me.

So i copyed the code into a scene. My code looks like this:

Table = {
    group = {
        option1=1560,option2=1507,option3=881        
    },
  }

jTable = json.encode(table)
fibaro:setGlobal("StateTable", jTable)

local jT = json.decode(fibaro:getGlobalValue("Table"))

fibaro:debug(jT.group.option1)

when i run this scene as described in the turorial i get the following error:

[ fatal] Unknown exception: /usr/share/lua/5.2/json/encode.lua:93: Failed to encode value, encoders for function deny encoding

 

apparently the initial variable is called "Table" instead of "table". After correcting this error, my code looks like this:

Table = {
    group = {
        option1=1560,option2=1507,option3=881        
    },
  }

jTable = json.encode(Table)
fibaro:setGlobal("StateTable", jTable)

local jT = json.decode(fibaro:getGlobalValue("Table"))

fibaro:debug(jT.group.option1)

 running the scene now results in:

 

[ fatal] Unknown exception: /usr/share/lua/5.2/json/decode.lua:74: bad argument #1 to 'match' (string expected, got nil)

 

I was also wondering why setGlobal refers to "StateTable" whereas getGlobal refers to "Table".

After correcting this error, my code looks like this:

Table = {
    group = {
        option1=1560,option2=1507,option3=881        
    },
  }

jTable = json.encode(Table)
fibaro:setGlobal("StateTable", jTable)

local jT = json.decode(fibaro:getGlobalValue("StateTable"))

fibaro:debug(jT.group.option1)

 

running the scene now results in:

[ fatal] Unknown exception: /usr/share/lua/5.2/json/decode.lua:74: bad argument #1 to 'match' (string expected, got nil)

 

Has anyone any idea why this isn`t working as described in the tutorial?

 

Link to post
Share on other sites

In your browser go to Panels, Variables Panels and create "StateTable". It isn't created automatically for you. I have tested your scene, after creating that global variable, your last scene prints "1560" as expected.

  • Like 1
Link to post
Share on other sites

Thanks petergebruers 

i indeed didn`t know that i have to create the global variable in the variables panel beforehand.

 

maybe the creator of this post could fix the 2 issues with the tutorial`s code.

Also Thanks to the author of this post for the great tutorial.

much appreciated!

 

Link to post
Share on other sites
  • 8 months later...

Hello , i read inthe forum up and down, but i can't find a solution for my proplem. I make an http request on a virtual device and become this output:

-- Setze Verbindungsdaten
-- hole ip adresse aus virtuellem modul
local selfId = fibaro:getSelfId()
local IP = fibaro:get(selfId, "IPAddress")
local Port = fibaro:get(selfId, "TCPPort")
local versuche = 3
-- setze variable MOWER aus IP und Logindaten
DG = Net.FHttp(IP)

--check Onlinestatus
local function _ping(retry)
        fibaro:sleep(500)
    retry = retry or 0
    local tcpSocket = Net.FTcpSocket(IP, Port)
    tcpSocket:setReadTimeout(250)
    --fibaro:debug('Suche..., versuche #' .. retry .. ' bitte warten...')
    fibaro:sleep(250)
    local bytes, errorCode = tcpSocket:write('ping')

    if errorCode == 0 then
        return true
    else
        if retry < versuche then
        --fibaro:debug('Nicht gefunden, erneut versuchen, bitte warten...')
        fibaro:sleep(500);
    return _ping(retry + 1)
end
    return false
end
end

local f, result = pcall(_ping)

if (f) then
    if (result == true)

    then
    --xy
 else
        fibaro:sleep(300000)
    end

else
    fibaro:debug('Error: ' .. f)
end

 
-- geting info about specific device
  response = DG:GET("/info.jsn")
 fibaro:debug(response)
-- decoding json string to table
 extractedjson = json.encode(response)

fibaro:debug(extractedjson)

 

output:

grafik.png.b71a3d0eaf5f2cfa2cdf15db192e1b20.png

 

I think there is an easy solution to separate specific value and transfer it to a global variable. But i can't find it. I try with several variants of table or string entrys - no result. Have anybody a solution statement?

Thanks in advance.

 

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...