Aller au contenu

jang

Membres confirmés
  • Compteur de contenus

    206
  • Inscription

  • Dernière visite

  • Jours gagnés

    41

Tout ce qui a été posté par jang

  1. jang

    setTimeout seule solution?

    Try to install this QA TriggerQA.fqa v1.21 and then create another QA: function QuickApp:subscribeTrigger(event) local s = self:getVariable('TRIGGER_SUB') if s == nil or s == "" then s = {} end s[#s+1]=event self:setVariable('TRIGGER_SUB',s) end function QuickApp:sourceTrigger(tr) self:debug(json.encode(tr)) end function QuickApp:onInit() self:debug("onInit") self:subscribeTrigger({type='device'}) end This will call QuickApp: sourceTrigger with the trigger as soon as it happens. You can be more specific and do self:subscribeTrigger({type='device', id=88}) self:subscribeTrigger({type='device', id=99}) to only get triggers from deviceId 88 and 99 etc. Inside QuickApp: sourceTrigger you need to look at the trigger to see what trigger it is if you subscribe to different triggers. If you don't need super optimized trigger handling (then you run your own / refreshStates loop) then the TriggerQA is a simple helper that makes it easy for other QAs to receive sourceTrigger with very little overhead - similar to how scenes gets them - and it scales very well.
  2. jang

    setTimeout seule solution?

    It's not the setTimeout - it's what you do inside the setTimeouts... Here I start 1 million setTimeouts in parallell. local t = os.time() for i=1,1000000 do -- Start a million setTimeouts fibaro.setTimeout(1,function() end) end fibaro.setTimeout(30,function() print("OK2") print(os.time()-t) end) The last setTimeout with 30ms timer will not be allowed to run until all the 1 million have completed (that's how we time it). It takes 41s on the HC3 [27.05.2021] [12:07:13] [DEBUG] [SCENE24]: OK2 [27.05.2021] [12:07:13] [DEBUG] [SCENE24]: 41 That's actually quite ok. The trick with polling for state changes is not to do it with a setTimeout loop doing fibaro.getValue. It's to do http:requests to the /refreshStates api as the http request will hang if there are no events and not consume any cpu during that time. When an event is available the http request will return immediately. Granted is that you will get all kinds of events and need an efficient way to filter for events that you look for (devices changing state or globals changing value) - but that is easy to do with a table lookup. I have a ready made library 'fibaroExtra.lua' that implements an event/sourceTrigger callback function that is as efficient as it gets.
  3. So the example becomes local function condition1(self) return true end local function condition2(self) return math.random(1,3) > 1 end local function condition3(self) return false end local function action1(self) fibaro.call(...) end local function action2(self) fibaro.call(...) end local rules = { {condition=condition1,action=action1}, {condition=condition2,action=action2}, {condition=condition3,action=action2} } function mainCode(self) for _,r in ipairs(rules) do -- Test conditions and run actions if true if r.condition(self) then r.action(self) end end end with the "passing around self' style.
  4. Well, all QuickApp functions declared are callable from other QAs or through the web interface as has been discussed in other posts previously. Functions that are local to the QA I believe should be declared as just local functions. The problem is that you don't have access to 'self' in local functions, for calling ex. self:updateProperty() self:debug() etc. However, there is a global Lua variable that fibaro sets for us 'quickApp' that gets the value of 'self' - or the QuickApp object. The problem with 'quickApp' is that it's not set until we exit the QuickApp:onInit() function. So I use something like this. local function foo() quickApp:debug("Foo") end function QuickApp:onInit() quickApp = self foo() end The reason they set 'quickApp' after we exit :onInit() is that the object is not considered initialised until :onInit() has run. So just be careful that you don't access self variables that you initialise in :onInit() from, in this case, 'foo'. A purist would say we shouldn't use global variables like 'quickApp' but pass around the self value - however it tends to be a bit tedious if we only have one QuickApp object. However, there is an exception (or rule). If you have QuickAppChild objects too in your QA, then you in effect have several 'QuickApps' and need to pass around the right self to your local functions. local function foo(self) self:debug("Foo") end class 'Child'(QuickAppChild) function Child:onInit() foo(self) -- Child's self end function QuickApp:onInit() foo(self) -- QuickApp's self end Remember to declare 'local foo' before it's referenced in the Child:onInit() function.
  5. The type of the QA defines a lot of the available key-values of the QA device structure. Changing the type of the QA would require some migration of values. For some types the property.value is a boolean for others a float etc. It would be messy. For children you need to update the mother QAs, as children can't migrate to another mother QA (one could experiment with changing the .parentId but my guess it could create havoc...) I have a Hue QA that I have updated the mother QA for a year now and users have been able to keep their children and more important the children deviceId's. I have my own version of the QuickAppChild class called QuickerAppChild that manages the children and reloads them with the correct class and it works well. I have also an 'UpdaterQA' that allow people to upgrade (and downgrade) my EventRunner and ChildrenOfHue's QAs.
  6. I guess it's something like if (conditions1) then self:actions1() end ? You could make your conditions into self:condition1() too. if self:condition1() then self:action1() end The important thing is that your conditions need to return true/false. Then you could put them into an list function QuickApp:condition1() return true end function QuickApp:condition2() return math.random(1,3) > 1 end function QuickApp:condition3() return false end function QuickApp:action1() fibaro.call(...) end function QuickApp:action2() fibaro.call(...) end local rules = { {condition='condition1',action='action1'}, {condition='condition2',action='action2'}, {condition='condition3',action='action2'} } function mainCode(self) for _,r in ipairs(rules) do -- Test conditions and run actions if true if self[r.condition](self) then self[r.action](self) end end end Then you run the mainCode every 30s and rename your QA to GEA ;-) P.S I probably wouldn't declare conditions/actions as QuickApp methods.
  7. jang

    Récupérer valeur dans un API

    _ is a variable like all others... _ = 42 for _,_ in ipairs(({ 6,5,4,3 })) do print(_) end print(_G['_']) A_B, _A, _ are all valid variable names. However, as @Leisure points out it's a convention to name a temporary (local) variable that you don't need '_' as a signal to other that reads the code. Ex. code checking programs (LuaLint, Luacheck) also don't warn for "unused variables" if the variable is named '_'.
  8. jang

    Slider

    I think your analysis is justified. Fibaro is not always consistent in how they define their APIs....
  9. https://forum.fibaro.com/topic/54915-quickapp-slider-minimum-and-maximum-range/
  10. The general advice to declare your variables in the beginning of the code/functions is usually a very good advice. Actually, the QA is "executed" when the code is loaded. It's just that fibaro helps us by collecting a lot of nice-to-have functions in the QuickApp class and when the code is loaded is creates a QuickApp object and calls its :onInit() function as an "entry point" for our code. If fibaro had not done that we could have achieved the same thing by creating the QuickApp object ourselves at the end of our code. function QuickApp:onInit() self:debug("foo") end quickApp = QuickApp() -- create object from class quickApp:onInit() -- call our "entry point" However, we don't need an :onInit() in our QA. If there is no :onInit(), fibaro will not call it. setInterval(function() fibaro.call(88,"turnOff") end,60*60*1000) is a perfectly valid QA that will turn off device 88 every hour.
  11. is still valid. When Lua loads your file the statements are executed top-to-bottom. Your first example: sets local test to "foo" defines function function QuickApp:onInit(). When onInit() is defined (compiled) the variable 'test' is determined to be a local variable as it has been defined previously (step 1). When the file is loaded no one has called QuickApp:onInit() yet. However after the QA is loaded, fibaro calls your QuickApp:onInit() to "start" your QA. The QA prints "foo". Your second example. defines function function QuickApp:onInit(). When onInit() is defined (compiled) the variable 'test' is determined to be a global variable as it has not been seen previously. sets local test to "foo" fibaro calls your QuickApp:onInit() functions that tries to print the global variable 'test' that has the value nil. In my previous post I talked about "forward" declaring variables. This would solve it. local test function QuickApp : onInit () self : debug ( "onInit" ) print ( test ) end test = "foo" declares local variable test defines function function QuickApp:onInit(). When onInit() is defined (compiled) the variable 'test' is determined to be a local variable as it has been defined previously (step 1). local test is set to "foo" fibaro calls your QuickApp:onInit() functions that prints the global variable 'test' that has the value "foo"
  12. You can also just do local clim = 120 function QuickApp:updateClima() self:updateView("label1", "text", tostring(fibaro.getValue(clim, "power")).."W") end function QuickApp:onInit() self:debug(self.clima) setInterval(function() self:updateClima() end,10*1000) end but you probably would like to have some "smoothing" of the value...
  13. It's not that straight forward.... However, you can leverage a library I have for that. Add fibaroExtra.lua to your QA https://forum.fibaro.com/topic/54538-fibaroextra/ Then in your QA main: local clim = 120 function QuickApp:updateClima() self:updateView("label1", "text", tostring(fibaro.getValue(clim, "power")).."W") end function QuickApp:onInit() self:debug(self.clima) self:updateClima() self:event({type='device', id=clima, property='power'}, function(env) self:updateClima() end ) end
  14. Well, the local variables just shadow each other - it will work with same name - I choose different ones just for clarity. ...and clarity is good! Here you have 3 versions. Parallell - all request run and handled in parallell. Sequential - one request after another, handled in sequence. Parallell_join - The request run in parallell and the response collected in a common result that is sent to the callback when all results are ready. The advantage of sequential with the performance of parallell :-) function httpGet(self, url, callback) self.http:request(url, { success = function(response) if response.status < 400 then callback(true, url, response.data) else callback(false, url, response.status) end end, error = function(err) callback(false, url, err) end }) end local urls2call = { "https://www.apple.com", "https://www.google.com", "https://www.amazon.com", "https://www.facebook.com", } function parallell(self, urls ,handler) -- call all urls in parallell, handle asynchronous for _,url in ipairs(urls) do httpGet(self, url, handler) end end function sequential(self, urls, handler) -- call all urls in sequence local i = 1 local function callback(success, url, result) handler(success, url, result) i=i+1 if i <= #urls then httpGet(self,urls[i], callback) end end httpGet(self, urls[i], callback) end function parallell_join(self, urls, handler) -- call all urls in parallel, call join local result = {n=0,responses={}} for _,url in ipairs(urls) do httpGet(self, url, function(success, url, response) result.responses[#result.responses+1]={url=url,success=success,response=response} result.n = result.n+1 if result.n == #urls then handler(true, nil, result.responses) end end) end end function QuickApp:onInit() self.http = net.HTTPClient() -- parallell(self,urls2call, -- function(success, url, result) self:debug("Success "..tostring(success).." "..url) end -- ) -- sequential(self,urls2call, -- function(success, url, result) self:debug("Success "..tostring(success).." "..url) end -- ) parallell_join(self,urls2call, function(success, url, result) for _,r in ipairs(result) do self:debug("Success "..tostring(r.success).." "..r.url) end end ) end
  15. Ahh, you want to run them in parallell?
  16. ...and you see that currentData(...) becomes a generic http get function... function httpGet(self, url, callback) self.http:request(url, { success = function(response) if response.status == 200 then self:debug("Success: status = "..tostring(response.status)) local jsonTable = json.decode(response.data) callback(true, jsonTable) else self:warning("Error: status = " ..tostring(response.status)) end end, error = function(err) callback(false, err) self:warning("Error: " ..err) end }) end function mainCode(self) httpGet(self,"http://worldtimeapi.org/api/timezone/Europe/Stockholm", function(success1, datajsonTable1) if success1 then self:debug("1",datajsonTable1.datetime) httpGet(self,"http://worldtimeapi.org/api/timezone/America/New_York", function(success2, datajsonTable2) if success2 then self:debug("2",datajsonTable2.datetime) else self:error("ça ne s'est pas bien passé :", datajsonTable2) end end) else self:error("ça ne s'est pas bien passé :", datajsonTable1) end end ) end function QuickApp:onInit() self.http = net.HTTPClient() mainCode(self) end
  17. function currentData(self, callback) self.http:request("http://worldtimeapi.org/api/timezone/Europe/Stockholm", { success = function(response) if response.status == 200 then self:debug("Success: status = "..tostring(response.status)) local jsonTable = json.decode(response.data) callback(true, jsonTable) else self:warning("Error: status = " ..tostring(response.status)) end end, error = function(err) callback(false, err) self:warning("Error: " ..err) end }) end function mainCode(self) currentData(self, function(success1, datajsonTable1) if success1 then self:debug("1",datajsonTable1.datetime) currentData(self,function(success2, datajsonTable2) if success2 then self:debug("2",datajsonTable2.datetime) else self:error("ça ne s'est pas bien passé :", datajsonTable2) end end) else self:error("ça ne s'est pas bien passé :", datajsonTable1) end end ) end function QuickApp:onInit() self.http = net.HTTPClient() mainCode(self) end
  18. setView("Humidity is %s%%",50) %% -> %
  19. In the first version I missed some % directives. It should be fixed in the last edit of the post. Yes
  20. In Lua, all strings created, in code and that are read in, are "interned" which means that there are only one version of the same string stored. This makes comparing if two strings are equal as fast as comparing if 2 integers are equal. The drawback is that it takes a little longer to create strings as they need to be interned (usually put in an efficient hash table and references replaced by the hash value). Java, Lisp and many other languages use the same concept. This is the reason why it's much more efficient to add strings to a table and then do table.concat, or often better to do a string.format than multiple ... concats that creates intermediate strings. It's also a reason why Lua's table lookup is so fast, all strings have a pre-computed hash-value already associated with them.
  21. There was some missing fields in the setView call, fixed. What's missing is to check the user provided quickAppVariables that they are valid and warn if not.
  22. ...and the reason it's pretty quick to run your original QA, step through it, understand what it's doing and then modifying it, is that it runs very well in my new little offline emulator.
  23. Sitting in a long meeting and being a bit bored I did some hacking on your code... I guess it's a matter of taste but there are no globals anymore :-) Your original version may make more sense to you, so just see it as an example of alternative way of coding. function QuickApp:onInit() local key_id = self:getVariable("key_id") local lati = tostring(api.get("/settings/location").latitude) self:setVariable("latitude", string.format("%.2f", lati)) local long = tostring(api.get("/settings/location").longitude) self:setVariable("longitude", string.format("%.2f", long)) self.url = "https://api.weatherbit.io/v2.0/forecast/daily?lat="..lati.."&lon="..long.."&days=5&lang=fr&key="..key_id self.icons = {} for i=1,11 do self.icons[i]=tonumber(self:getVariable("id_icon"..i)) end self:loop() end ----- function QuickApp:loop() local http = net.HTTPClient() http:request(self.url, { options = { method = 'GET' }, success = function(response) if response.status == 200 then if response.data and response.data ~= "" then local jsonTable = json.decode(response.data) local gfx = jsonTable.data[1].weather.code local city = jsonTable.city_name local citycode = jsonTable.country_code ------------------------------------------------------------------------------ ----------------------------- CHOIX DE L'ICON -------------------------------- ------------------------------------------------------------------------------ local codeicon,icon = tonumber(gfx),1 if codeicon == 610 then icon=1 end if codeicon >= 803 and codeicon <= 804 then icon=2 end if codeicon >= 700 and codeicon <= 751 then icon=3 end if codeicon >= 500 and codeicon <= 522 then icon=4 end if codeicon >= 601 and codeicon <= 623 then icon=5 end if codeicon == 600 then icon=6 end if codeicon == 800 then icon=7 end if codeicon >= 801 and codeicon <= 802 then icon=8 end if codeicon >= 300 and codeicon <= 302 then icon=9 end if codeicon >= 230 and codeicon <= 233 then icon=10 end if codeicon >= 200 and codeicon <= 202 then icon=11 end self:updateProperty("deviceIcon", self.icons[icon]) local Var_Heure = os.date("%d.%m.%Y à %Hh%M") ------------------------------------------------------------------------------ -------------------------- CONSTRUCTION DES TABLES --------------------------- ------------------------------------------------------------------------------ local week = {[0] = "DIMANCHE", [1] = "LUNDI", [2] = "MARDI", [3] = "MERCREDI", [4] = "JEUDI", [5] = "VENDREDI", [6] = "SAMEDI"} local month = {"JANVIER", "FEVRIER", "MARS", "AVRIL", "MAI", "JUIN", "JUILLET", "AOUT", "SEPTEMBRE", "OCTOBRE", "NOVEMBRE", "DECEMBRE"} local day = os.date("%w")-1 local data = {} ------------------ ----- JOUR ----- ------------------ for i=1,5 do data[i]={} local m = data[i] m.precipday = jsonTable.data[i].precip m.dayweather = jsonTable.data[i].weather.description m.snowday = jsonTable.data[i].snow m.lowtempday = jsonTable.data[i].low_temp m.maxtempday = jsonTable.data[i].max_temp m.windspeed = jsonTable.data[i].wind_spd m.winddir = jsonTable.data[i].wind_cdir m.m,m.j = jsonTable.data[i].datetime:match("%d+%-(%d+)%-(%d+)") m.j,m.m = tonumber(m.j),tonumber(m.m) m.day = (tonumber(day)+i) % 7 end ------------------------------------------------------------------------------ --------------------------- CONSTRUCTION DES LABELS -------------------------- ------------------------------------------------------------------------------ local function setView(elm,fmt,...) self:updateView(elm,"text",string.format(fmt,...)) end for i=1,5 do local m = data[i] setView( "labelday"..i, "%s %s %s\r%s\rT° mini : %s °c - T° maxi : %s°c\r%.1f mm de pluie | %.1f mm de neige\rVent %.1f km/h (%s)", week[m.day],m.j,month[m.m],m.dayweather,m.lowtempday,m.maxtempday,m.precipday,m.snowday,m.windspeed* 3.6,m.winddir ) end setView("labelMAJ", "Station de %s (%s) - MAJ le %s",city,citycode,Var_Heure) ----------------------------- local precipitation_arrosage = string.format("%.2f", data[1].precipday + data[2].precipday) fibaro.setGlobalVariable("prevision_pluie", tostring(precipitation_arrosage)) ---------- else self:error("empty response data") end else self:error("status=" .. tostring(response.status)) end end, error = function(err) self:error(err) end }) fibaro.setTimeout(1000 * 60 * 60 * 2, function() self:loop() end) end
  24. jang

    QA Moyenne Glissante

    Not exactly a moving average but still "smoothing" out the value can be achieved by subtracting the average... no buffer needed. function smoothFilter(size) local sum,n,average=0,0 return function(x) sum,n=sum+x,n+1 average = sum/n if n >= size then sum,n=sum-average,n-1 end return average end end local filter = smoothFilter(40) for i=1,10000 do print(filter(math.random(1,500))) end
  25. No it only seems to affect fibaro.call(self.id,"...",...) There was complaints that the QuickApp hung for ~5s when doing that (QAs are single-threaded so it blocked itself) so they added __fibaroUseAsyncHandler(bool) and set it to true by default. I assume they check if it's the same QA and in that case call it in another setTimeout thread. I'm not sure how really useful that was, as one should call your own QA methods with self:... I would have preferred that they fixed the whole fibaro.call mechanism as it causes hard to detect bugs in people's code - and we got fibaro.calls that could return values .... as outlined here https://forum.fibaro.com/topic/49113-hc3-quickapps-coding-tips-and-tricks/?do=findComment&amp;comment=233772
×
×
  • Créer...