Jump to content

Welcome to Smart Home Forum by FIBARO

Dear Guest,

 

as you can notice parts of Smart Home Forum by FIBARO is not available for you. You have to register in order to view all content and post in our community. Don't worry! Registration is a simple free process that requires minimal information for you to sign up. Become a part of of Smart Home Forum by FIBARO by creating an account.

 

As a member you can:

  •     Start new topics and reply to others
  •     Follow topics and users to get email updates
  •     Get your own profile page and make new friends
  •     Send personal messages
  •     ... and learn a lot about our system!

 

Regards,

Smart Home Forum by FIBARO Team


Search the Community

Showing results for tags 'LUA'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • FIBARO Community
    • FIBARO Portal and Forum policy
    • FIBARO
    • Say hello!
    • Off-topics
  • FIBARO Update
    • FIBARO System Update
    • FIBARO Mobile Update
  • FIBARO Community Support
    • Scenes and Interface
    • FIBARO Products
    • FIBARO Mobile
    • FIBARO HomeKit
    • FIBARO Assistant Integrations
    • Other Devices / Third-party devices
    • Tutorials and Guides
    • Home Automation
    • Suggestions
  • FIBARO Społeczność
    • FIBARO
    • Przywitaj się!
    • Off-topic
  • FIBARO Aktualizacja
    • FIBARO System Aktualizacja
    • FIBARO Mobile Aktualizacja
  • FIBARO Wsparcie Społeczności
    • Sceny i Interfejs
    • FIBARO Urządzenia
    • FIBARO Mobilnie
    • FIBARO HomeKit
    • Integracja z Amazon Alexa i Google Home
    • Urządzenia Firm Trzecich
    • Poradniki
    • Automatyka Domowa
    • Sugestie

Categories

  • Scenes
  • Virtual Devices
  • Quick Apps
  • Icons

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Facebook


Google+


Skype


Website URL


WhatsApp


Country


Gateway/s


Interests

  1. How do I create a Global Variable from LUA in HC3? I'm trying to create a light dimmer function for Philips HUE using a Logic Group Matrix ZDB5100 switch so when I hold the Button its starts dimming up or down. But to keep track if the button is released and pressed again I need to keep track of the direction from last time it was pressed. So I'm thinking of using an Enumerated global variable "dimDirection" that can be set to Up or Down. I want the code to create the variable if not present. My working code whiteout remembering dimDirection is here https://pastebin.pl/view/d74c93bb In HC2 i used this snippet of code. But how is it in HC3 ? local ProjectorStatus = {On="Tændt", Off="Slukket"}; -- in code you then declare predefined global variable using users mapped values: local varName = { ["Projector"] = { value = ProjectorStatus.On, isEnum = true, isTable = false, enumValue = {ProjectorStatus.On, ProjectorStatus.Off} }, } function checkGlobalVariable(varName) -- Check if variable exist for i , v in pairs(varName) do if fibaro:getGlobalValue(i) == nil then api.post("/globalVariables/", { name = i }); fibaro:sleep(400) api.put("/globalVariables/"..i, { name = i, value = v.value, isEnum = v.isEnum, enumValues = v.enumValue }) if v.isTable then ok, msg = pcall(function() wT = json.decode(fibaro:getGlobalValue(i)) if type(wT) ~= "table" then error() end end ) if not ok then fibaro:debug("ERROR - Creating table was unsuccessful, error code: "..msg) else fibaro:debug("Variable '"..i.."' created successfully."); end else if fibaro:getGlobalValue(i) ~= nil then fibaro:debug("Variable '"..i.."' created successfully."); else fibaro:debug("ERROR - Variable '"..i.."' was NOT created!") end end end -- update all predefined global variables in case user changed default values if v.isEnum then fibaro:debug("Variable '"..i.."' allready exists."); local value = fibaro:getGlobalValue(i) for i,m in pairs(v.enumValue) do if m == value then v.value = value end end if v.value == value then fibaro:debug("For variable '"..i.."' found current value ("..value..") and will keep it") else fibaro:debug("For variable '"..i.."' NOT found current value, will set default value ("..value..")") end api.put("/globalVariables/"..i, { name = i, value = v.value, isEnum = v.isEnum, enumValues = v.enumValue }) fibaro:sleep(400) end end updateVar = true end checkGlobalVariable(varName)
  2. Witam, Ciekaw jestem, czy można napisać scenę LUA, która da odpowiedź w formie debug lub wyśle rezultat na maila odnośnie wyszukania, w których scenach znajduje się, jest użyte dane ID urządzenia. Np. chcę poszukać, w których scenach jest załączane lub wyłączane światło przed domem o ID 1101. Wiem, że jak wejdę w urządzenie o ID 1101, to zobaczę wynik dla if lub then ale okazuje się, że nie są to wszystkie sceny... Pozdrawiam, Łukasz
  3. I have moved to the HC3 and trying to work out how the LUA programming works. The HC2 programming seemed a lot more logical and I am struggling to work out how to convert some of my old routines over. One of the first routines is remotes. Setting this up by blocks wouldn't work as it looks like I'd have to setup a scene for each button for each remote. Could someone help tell me how to convert this simple program into a HC3 computable version? --[[%% properties13 sceneActivation%% globals--]]local buttonPressed = fibaro:getValue(13, "sceneActivation")if ( tonumber(buttonPressed) == 1) thenfibaro:debug("MiniMote button 1 pressed")elseif ( tonumber(buttonPressed) == 2) thenfibaro:debug("MiniMote button 2 pressed")elseif ( tonumber(buttonPressed) == 3) thenfibaro:call(4, "turnOn")fibaro:debug("MiniMote button 3 pressed - Light ON")elseif ( tonumber(buttonPressed) == 4) thenfibaro:call(4, "turnOff")fibaro:debug("MiniMote button 4 pressed - Light OFF")elseif ( tonumber(buttonPressed) == 5) thenfibaro:debug("MiniMote button 5 pressed")elseif ( tonumber(buttonPressed) == 6) thenfibaro:debug("MiniMote button 6 pressed")elseif ( tonumber(buttonPressed) == 7) thenfibaro:debug("MiniMote button 7 pressed")elseif ( tonumber(buttonPressed) == ? thenfibaro:debug("MiniMote button 8 pressed")elsefibaro:debug("No response")end Thanks
  4. I'm using a ZRC-90EU and everything works fine but I don't like the way I need to assign a action to a button (function). As you can see in the picture, in the Advanced page of the device you can assign an action to each button but you have to start from scratch every time (I can not assign an existing scene to a button).... With a block scene it is possible as well but if you want to assign 1 function/scene to one button and you know that every button has 4 options (1x,released, held and 2x) than I have to create 32 scenes.... I am new and have a HC3 so I never had HC2, HCL .... but once I've seen a LUA script that contained all button options and in the script it was possible to assign a function/scene to every possible option per button within that script so you could assign existing scenes as well. I already tried some HC2 LUA scripts and they don't work in HC3 so copying the script from HC2 isn't an option (+ I can(t find it anymore ) Does someone have a solution so I can use a LUA script or a QA to assign functions/scenes to the buttons without creating a new scene per button .... ? Thank you
  5. Yes/no and run/cancel are the only options when using block scenes. Can I use LUA to make an interactive push notification that lets me choose between 2 or more scenes to run? If so, how?
  6. response, status = api.get("/scenes") fibaro:sleep(1000) if (status == 200) then fibaro:debug("Get Scenes Successful") created = true else fibaro:debug("Failed to get Scenes " ) end for _,s1 in ipairs(response) do local s2 = api.get("/scenes/"..s1.id) if s1.name == gSceneName then fibaro:debug("SceneName: " .. s1.name .. " Scene ID: " ..s1.id) print (s1.isLua) -- ** gets correctly print (s1.lua) -- <=== RETURNS a null --- HOW do I get this print (s1.roomID) -- ** gets correctly print (s1.iconID) -- ** gets correctly print (s1.sortOrder) -- ** gets correctly SceneID= s1.id fibaro:sleep(1000) Essentially I'm trying to get the Lua code from a scene so I jason encode it so I can then populate another scene with the same lua code. I'm trying to automatically update/create Lua scenes without having to go in and edit each one individually. I can populate the "lua " field with an API PUT ... But I can't read it back. The code above returns all the other fields but not the s1.lua Any help would be greatly appreciated - thanks.
  7. Hi everybody, I seem to be stuck in my search how to implement a (large) mobile popup, triggered in a LUA scene in HC3. I found this example for HC2: https://manuals.fibaro.com/knowledge-base-browse/how-to-create-mobile-pop-up/ This is actually what I want to create, a large popup with buttons and actions connected to it. But the example (obviously) does not work in HC3. I am using the following code and the fibaro.homeCenter.notificationService.publish function with type set to MobilePopupNotification as described in https://manuals.fibaro.com/home-center-3-lua-scenes/ local function popupMessage(message) local request = { type = "MobilePopupNotification", priority = "warning", data = { title = "Door(s) Open", text = message, } } local response, code = fibaro.homeCenter.notificationService.publish(request) fibaro.debug("Scene109", json.encode(response)) fibaro.debug("Scene109", code) end The debug responses are: for response: {"data":{"title":"Door(s) Open","buttons":[],"text":"Alarm in kelder en begane grond armed"},"created":1586512755,"type":"MobilePopupNotification","id":208,"priority":"warning","wasRead":false,"canBeDeleted":true} for code: 200 My Notification page in the web interface displays the warning as "Notification title" but no mobile notification is received. I also had this scene running with fibaro.alert() but that did not give me the desired large popup, only a smal one with limited text and not button options. BTW: I couldn't get the button functionality to work in any way. Tried arrays, objects, array of objects, object of objects etc but always got an error code 400 or simply a load error code ((load):34: unexpected symbol near '[') So, can anybody point me in the right direction, or tell me if what I want is possible in HC3? Thanks a lot
  8. Witam, Scena LUA utworzona ze sceny blokowej mi nie działa. Tak w danym moncie aktywna jest tylko jedna z dwóch scen. Scena blokowa: Utworzona z niej scena LUA: Ktoś ma pojęcie o co chodzi?
  9. Hi all Is there a fibaro killscene and startscene command similar to hc2? Thanks
  10. Dear All, I'm confused to run scene with or without "while true do" cycle to use scene all triggered command change. I have the following easy code without "while true do" to change the airfresh working status if the alarm system is on or off. Work without an problem, if the alarm system status ( thrue smart implant input ) is changed the wall plug of the airfresh also changed Here is the LUA code: --[[ %% autostart %% properties 34 value %% events %% globals --]] local alarm local airfreshId = 55; local airfreshStatus function airfresh() alarm = tonumber(fibaro:getValue(34, 'value')); airfreshStatus = tonumber(fibaro:getValue(airfreshId, 'value')); if ( alarm == 0 and airfreshStatus == 0 ) then fibaro:call(airfreshId, "turnOn"); elseif ( alarm == 1 and airfreshStatus == 1 ) then fibaro:call(airfreshId, "turnOff"); end; end; -- Main program airfresh(); And here is the similar LUA code when I need to switch on or off the bathroom electrical radiator heating. If I use this LUA code without "while true do" cycle and I change the termostat adjustment no any action happened. If I use the same code with "while true do" cycle this work perfect. --[[ %% autostart %% properties 28 value 29 value 281 value 272 value %% events %% globals --]] local thermostat -- id:28 radiator thermosztat local roomtemp -- id:29 room temperature local radiatorheatId = 54; -- id:54 radiator heating local heatingwater -- id:281 boiler heating water temp local heatingwaterpump -- id:272 heating water pump local tempswitch = true; function radiator() thermostat = tonumber(fibaro:getValue(28, 'value')); roomtemp = tonumber(fibaro:getValue(29, 'value')); heatingwater = tonumber(fibaro:getValue(281, "value")); heatingwaterpump = tonumber(fibaro:getValue(272, "value")); if ( (roomtemp - thermostat) >= 0 ) then tempswitch = false; else tempswitch = true; end; if ( ( tempswitch == true and heatingwater < 30 and heatingwaterpump == 0 ) ) then fibaro:call(radiatorheatId, "turnOn"); else fibaro:call(radiatorheatId, "turnOff"); end; end; -- Main program while true do radiator(); fibaro:sleep(60000); -- Wait 1 minute end; Can you please advise why I need to run while true do cycle in the 2nd program, if the 1st program run without this cycle perfect ? Thank you
  11. Hello, I'm interested to learn more about scripting to automate the home with HC3. Which "languages" would you recommend to learn? I know there is documentation about LUA on manuals.fibaro.com, but I don't have any "programming skills" yet. So that a step to far for me at the moment. I also found this app https://getmimo.com/ (not sponsored content), maybe this is something easy to understand the basics. Let me know if you have any other suggestion!
  12. knuth

    HC3 LUA vs HC2

    In making the transfer from HC2 to HC3 based on a cloud backup (update 4.581 Beta) it is stated that "scenes will not be moved and need to be created again". That's OK, but it would be helpful when planning the transfer to know what the differences are (in syntax and available functions) between the two LUA versions. I know that the new LUA editor is documented in https://manuals.fibaro.com/home-center-3-lua-scenes/ . What I would hope to see in addition, is a side by side comparison of all the crucial differences, to enable a pre-edit of the old LUA scenes before entering them into the new editor. Something like this: If you used this in HC2 LUA: You need to do this in HC3 LUA: fibaro.debug("txt") fibaro.debug("tag", "txt") os.time() ??? etc. If we all contribute to such a table as we identify all the differences, we may be able to help each other prepare for HC3. Not all differences can easily be summarized in the simple two-column format above, however. For the new definition of conditions and triggers, it seems it would be more appropriate to give a few examples of old codes (with triggers) converted to new codes. PS: I haven't even decided to buy the HC3 yet! But getting a feel for the amount of re-programming needed to convert my scene is an important factor in making that decision. The suggested table is now shown in a pdf file attached to this post, see below. It is regularly updated as new contributions are posted. LUA HC2 vs HC3.pdf
  13. fibaroapiHC3.lua Note, I currently only support my new emulator, TQAE, and have moved all my development to that - please check it out... It's a rewrite with the learnings I have made coding fibaroapiHC3.lua... (Note: The new version of the emulator has gone through extensive rewrite and is stabilising (0.300). The old version of the emulator is here fibaroapiHC3_classic.lua.) This is a thread for the fibaroapiHC3.lua sdk that is under development (keeping it separate from the HC3 QuickApps coding - tips and tricks thread) I've started to run and test HC3 QuickApps offline and have made a fibaroapi.lua file that can be included to emulate the fibaro calls and call out to the HC3. This means that a whole QA can be developed offline, debugged and verified before deploying to the HC3. Something that significantly reduces the development process. It's an emulation so it's not 100% but it will cater for 99.99% of the needs to catch bugs, get decent error messages when things doesn't work (like timers). Be able to set breakpoints and inspect states etc. It's complete enough to run the most demanding QuickApps that I have found on the forum so far... If it runs in the emulator and it doesn't run on the HC3 or vice versa I will prioritise to fix it. Latest version here fibaroapiHC3.lua (v0.311) The code is updated weekly so please make sure you have the latest... It was inspired by the old fibaroapi for the HC2 in a thread started by @riemers but has evolved with more extensive support to create a better debugging and "offline experience"... in fact, it's really an HC3 emulator now. The video is an earlier version of the emulator but the principles are more or less the same. Note the nice tooltip and autocompletion of fibaro commands we get with the fibaroapiHC3plugin for ZBS. Enable English subtitles to see instructions... Some benefits: Use a modern development environment such as ZeroBrane Studio (free for Mac/PC/Linux, HC3 plugin here) on your laptop/PC to develop and debug QuickApps and Scenes. Here is a good introduction to Lua (using ZeroBrane) Step through code, inspect Lua variables, set break-points etc - all that is possible in a good IDE. Faster to pin-point errors as the error messages are better than on the HC3 - stack-traces etc. Advanced timer info (setTimeout) warning of late timers and from where the offending function was called if a timer function crashes. Info from where an eronous json.encode was called from in your code so you can easily find the error (instead of seeing a line from deep inside the json encoder) Use the whole Fibaro API fibaro.call etc and net.HTTPClient(), setTimeout(), json.ecode/decode, QuickApp self:functions like self:getVariable, self:updateView Support for MQTT client and QuickApp child devices Both QuickApps and Scenes are supported. Scenes support most conditions and are triggered by real triggers from the HC3 or simulated triggers. Speed up clock to run faster than real time, to watch a Scene or QuickApp over days/weeks/months in seconds. Start at any given time and date - test if your scene behaves on week-ends ? Automatically create a proxy QuickApp on the HC3 that sends UI clicks back to the code your are running and displays self:updateView updates. This way you can test the QuickApp UI (buttons etc) and still debug the main code on your PC. Develop and run multi-file QuickApps, allowing you to build up a library of common code to share between your QAs. Run completely disconnected from the HC3 simulating devices and other resources (now you can take your coding with you on your vacation ) There is a possibility to download resource definitions from the HC3 and use them (devices, globals etc) while running disconnected. Load multiple QAs/Scenes into the emulator at the same time to debug interaction patterns between QAs (or just run all your QAs offline and use the HC3 as a wave GW ) Telnet into the running emulator to capture logs or issue Lua commands like turning on/off devices at runtime to test you QA/Scene. Move the code as-is over to the HC3 when it runs in the emulator - and it will most likely run on the HC3. Scenes needs to be moved to conditions/actions part on the HC3 - may automat that in the future. Oh, and an emulated Web GUI for the quickApp so you can try out button/slider clicks without connecting to the HC3. And lastly, it makes it fun to develop code for the HC3 To get going download the fibaroapiHC3.lua and put in in the working directory where you code your QA(s) If you run ZerobraneStudio (recommended) paste this and run if dofile and not hc3_emulator then dofile("fibaroapiHC3.lua") end--hc3 hc3_emulator.downloadPlugin() hc3_emulator.downloadAssets() Please note the 'end--hc3' that ends the 'if dofile and not hc3_emulator then' statement. It requires the '--end' comment so I can recognise it. Also, you need to set the Lua interpreter to version 5.3 (In ZBS, Menu ; Project -> Lua Interpreter -> Lua 5.3) It will install the. ZBS plugin in ~/.zbstudio/packages and some code templates in ~/.zbstudio/hc3emu/ (Restart ZBS for the plugin to. be installed) Create a Lua file and create a header + QA/scene code. An example of a minimal QA can look like if dofile and not hc3_emulator then hc3_emulator = { name = "My QA", poll=1000, -- Poll for triggers from the HC3 every 1s credentials = {ip="192.168.1.X", user="<user>", pwd="<password>"} } dofile("fibaroapiHC3.lua") end--hc3 function QuickApp:onInit() fibaro.call(88,"turnOn") -- turns on device 88 on your HC3 end We wrap the emulator specific stuff inside "if dofile and not hc3_emulator then .... end" as the symbol 'dofile' is not defined on the HC3 and will thus be false and not include the code - This means that we can take the code as-is and paste it into the HC3 and it works. Note the credentials that contains the IP, username and password so that the emulator can access the HC3 box. If you use ZBS and the plugin there is an Edit-HC3 SDK templates-> menu that will insert a standard QA and Scene header + code in the current buffer. Most of the functions are there and will be improved over time. There are support for net.HTTPClient() and setTimeout/clearTimeout and api.* There are support for getting triggers and events from the HC3 Support for auto-creating a QuickApp proxy with UI elements that sends events back to the code being debugged. There are support for both QuickApps and Scenes (with conditions) Currently supported (v 0.300) fibaro.debug(type,str) fibaro.warning(type,str) fibaro.trace(type,str) fibaro.error(type,str) fibaro.call(deviceID, actionName, ...) fibaro.getType(deviceID) fibaro.getValue(deviceID, propertyName) fibaro.getName(deviceID) fibaro.get(deviceID,propertyName) fibaro.getGlobalVariable(varName) fibaro.setGlobalVariable(varName ,value) fibaro.getRoomName(roomID) fibaro.getRoomID(deviceID) fibaro.getRoomNameByDeviceID(deviceID) fibaro.getSectionID(deviceID) fibaro.getIds(devices) fibaro.getAllDeviceIds() fibaro.getDevicesID(filter) fibaro.scene(action, sceneIDs) fibaro.profile(profile_id, action) fibaro.callGroupAction(action,args) fibaro.alert(alert_type, user_ids, notification_content) fibaro.alarm(partition_id, action) fibaro.setTimeout(ms, func) fibaro.clearTimeout(ref) fibaro.setInterval(ms, func) fibaro.clearInterval(ref) fibaro.emitCustomEvent(name) fibaro.wakeUpDeadDevice(deviceID) fibaro.sleep(ms) net.HTTPClient() net.TCPSocket() net.UDPSocket() net.WebSocketClient() -- needs extra download net.WebSocketClientTLS() -- needs extra download api.get(call) api.put(call <, data>) api.post(call <, data>) api.delete(call <, data>) setTimeout(func, ms) clearTimeout(ref) setInterval(func, ms) clearInterval(ref) mqtt.Client.connect(uri, options) -- needs extra download <mqttclient>:addEventListener(message,handler) <mqttclient>:subscribe(topic, options) <mqttclient>:unsubscribe(topics, options) <mqttclient>:publish(topic, payload, options) <mqttclient>::disconnect(options) plugin.mainDeviceId plugin.deleteDevice(deviceId) plugin.restart(deviceId) plugin.getProperty(id,prop) plugin.getChildDevices(id) plugin.createChildDevice(prop) class QuickAppBase class QuickApp class QuickAppChild json.encode(expr) json.decode(string) QuickApp:onInit() -- called at startup if defined QuickApp - self:setVariable(name,value) QuickApp - self:getVariable(name) QuickApp - self:debug(...) QuickApp - self:updateView(elm,type,value) QuickApp - self:updateProperty() QuickApp - self:createChildDevice(props,device) QuickApp - self:initChildDevices(table) sourceTrigger - scene trigger Supported scene events: {type='alarm', id=<id>, property='armed', value=<value>} {type='alarm', id=<id>, property='breached', value=<value>} {type='alarm', property='homeArmed', value=<value>} {type='alarm', property='homeBreached', value=<value>} {type='weather', property=<prop>, value=<value>, old=<value>} {type='global-variable', property=<name>, value=<value>, old=<value>} {type='device', id=<id>, property=<property>, value=<value>, old=<value>} {type='device', id=<id>, property='centralSceneEvent', value={keyId=<value>, keyAttribute=<value>}} {type='device', id=<id>, property='accessControlEvent', value=<value>} {type='device', id=<id>, property='sceneActivationEvent', value=<value>} {type='profile', property='activeProfile', value=<value>, old=<value>} {type='location', id=<uid>,property=<locationId>, value=<geofenceAction>, timestamp=<timestamp>} {type='custom-event', name=<name>} {type='UpdateReadyEvent', value=_} {type='onlineEvent', value=<bool>} Some of the parameters that affect the behaviour of the emulator and can be set in the header are: hc3_emulator.name=<string> -- Name of QuickApp, default "QuickApp" hc3_emulator.id=<QuickApp ID> -- ID of QuickApp. Normally let emulator asign ID. (usually 999 for non-proxy QA) hc3_emulator.poll=<poll interval> -- Time in ms to poll the HC3 for triggers. default false hc3_emulator.type=<type> -- default "com.fibaro.binarySwitch" hc3_emulator.speed=<speedtime> -- If not false, time in hours the emulator should speed. default false hc3_emulator.proxy=<boolean> -- If true create HC3 procy. default false hc3_emulator.UI=<UI table> -- Table defining buttons/sliders/labels. default {} hc3_emulator.quickVars=<table> -- Table with values to assign quickAppVariables. default {}, hc3_emulator.offline=<boolean> -- If true run offline with simulated devices. default false hc3_emulator.autocreate=<boolean> -- Autocreate local resources hc3_emulator.apiHTTPS=<boolean> -- If true use https to call HC3 REST apis. default false hc3_emulator.deploy=<boolean>, -- If true deploy code to HC3 instead of running it. default false hc3_emulator.assetDirectory=<string> -- Directory where assets shoud be downloaded (ZBS). Default ~/.zbstudio/hc3emu hc3_emulator.resourceFile=<string> -- When doing a resource download, use this file as default. hc3_emulator.db=<boolean/string>, -- If true load a "resource download" from hc3_emulator.resourceFile or string hc3_emulator.htmlDebug=<boolean> -- Try to convert html tags to ZBS console cmds (i.e. colors) hc3_emulator.terminalPort=<boolean> -- Port used for socket/telnet interface hc3_emulator.webPort=<number> -- Port used for web UI and events from HC3 hc3_emulator.HC3_logmessages=<boolean> -- Defult false. If true will push log messages to the HC3 also. hc3_emulator.supressTrigger -- Make the emulator ignore certain events from the HC3, like = PluginChangedViewEvent hc3_emulator.negativeTimeout=<boolean> -- Allow specification of negative timeout for setTimeout (will fire immediatly) hc3_emulator.strictClass=<boolean> -- Strict class semantics, requiring initializers hc3_emulator.consoleColors=<table> -- Maps fibaro.debug/self:debug etc to color (debug.color enables color debugging) hc3_emulator.sysConsoleColors=<table> -- Maps colors used for system logs hc3_emulator.userdataType=<boolean> -- If true intercepts type(...) to return 'userdata' for our Lua classes. Some apps checks this... Some useful emulator functions: hc3_emulator.setOffline(<boolean>,<boolean>) -- hc3_emulator.getIPaddress() -- Return HC3 IP address hc3_emulator.prettyJsonFormat(<table>) -- Return json formatted string of Lua table hc3_emulator.postTrigger(<event>,[<time ms>]) -- Posts a trigger to the emulator... hc3_emulator.loadScene(...) -- Load scene from file or HC3... hc3_emulator.loadQA(...) -- Load QA from file or HC3... hc3_emulator.downloadPlugin() -- (ZBS). Default ~/.zbstudio/packages hc3_emulator.downloadAssets() -- (ZBS). Default ~/.zbstudio/hc3emu hc3_emulator.downloadResources([<filename>]) -- Downloads a "backup" of HC3 resources hc3_emulator.loadResources([<filename>]) -- ...that can be loaded as "local" resources for the emulator. Some debug flags that can be set with hc3_emulator.debug.<flag>=<value> fibaro=false, -- Logs calls to fibaro api trigger=true, -- Logs incoming triggers from HC3 or internal emulator timers=nil, -- Logs low level info on timers being called, very noisy. refreshloop=false, -- Logs evertime refreshloop receives events mqtt=true, -- Logs mqtt message and callbacks http=false, -- Logs all net.HTTPClient():request. ALso includes the time the request took api=false, -- Logs all api request to the HC3 onAction=true, -- Logs call to onAction (incoming fibaro.calls etc UIEvent=true, -- Logs incoming UIEvents, from GUI elements zbsplug=true, -- Logs call from ZBS plugin calls webServer=false, -- Logs requests to /web/ including headers webServerReq=false, -- Logs requests to /web/ excluding headers files=false, -- Logs files loaded and run color=true, -- Logs in console using ANSI colors (see hc3_emulator.consoleColors for mapping) locl=true, -- Log creation of local devices breakOnInit=<boolean> -- Tries to set breakpoint on QuickApp:onInit (mobdebug) breakOnLoad=<boolean> -- Tries to set breakpoint on first line in loaded file (mobdebug) breakOnError=<boolean> -- Tries to break after error (makes it easier to look at call stack etc) ctx=false, -- Logs Lua context switches timersSched=false, -- Logs when timers are scheduled timersWarn=0.500, -- Logs when timers are called late or setTimeout with time < 0 timersExtra=true, -- Adds extra info to timers, like from where it's called and definition of function (small time penalty) In the example in the beginning, the HC3 credentials are listed in the header. If you don't want that (it's easy to forget it and share the code with your passwords in plain sights<9 you can create a credentials.lua file with your secret stuff and it will be automatically included by the SDK. The format should be return { ip="2912.168.77", user="admin", pwd="admin", mySecret="hgskjfhgjhgkdfh" } It returns a Lua table with the relevant keys. ip, user,and pwd is used to log into the HC3. We have added another key here to 'mySecret'. Assume that you want you QA to have a defined quickAppVariable with the value of mySecret. It could be the password to log into an external services. Then you can do like this if dofile and not hc3_emulator then hc3_emulator = { name="My QA", quickVars = {["password"]="$CREDS.mySecret"}, This define a quickAppVariable with the name 'password' and it fetches the key 'mySecret' from the credentials table and uses that as the value. When you QA starts up you can do self:getVarible('password') and it will return the credential. This is useful as not to litter your code with visible credentials. NOTE. Be aware that if you deploy the real QA with hc3_emulator.deploy=true or using the menu commands with the plugin, the deployed QA will have the quickAppVariable defined and if you upload that for sharing people will see your credential. If someone wants to try this in another IDE than Zerobrane that I use (like Visual Studio) the only thing that could be an issue is to have access to the Lua libraries require("socket") -- LuaSocket require("socket.url") -- LuaSocket require("socket.headers") -- LuaSocket require("ltn12") -- LuaSocket require("mime") -- LuaSocket require("lfs") -- LuaFileSystem They are pretty standard lua libraries - based on LuaSocket. @10der has managed to run it under Visual Studio on Windows. Here is an updated library/project map to work with the latest version of the emulator vscode_fibaro_bin.zip. Note that you should update the fibaroapiHC3.lua file provided i the archive when new are released as I will not update this archive for every new release. @petergebruers also have some tips. Any improvements are happily received (in code) and credits will be due granted. Links to notable post Here is a description of the various way to use the emulator when developing code (high-level) Some in-depth posts Running "Offline" (TBD) Running in "Mix mode". Mixing real devices and locally emulated devices (TBD) Running with a "Proxy QA" (TBD) Using real QA as "Proxy" (TBD) Downloading HC3 resources to file and emulate them locally (TBD) Running standard Lua with access to HC3 functions (developing management scripts etc) (TBD) Loading multiple QAs/Scenes and run them in parallel in the emulator (also getting QAs/Scenes from the HC3 and install them in emulator on the fly...) (TBD) Running faster than real-time and manipulating start dates (TBD) A ZeroBrane plugin to make life easier while debugging A post introducing the SDK with QuickApps. A post introducing the SDK with Scenes. Scene support is not complete. Creating and debugging multi-file QuickApps The debug flags that can be set are described The new dynamic load functions to run multiple QAs/Scenes in the emulator are described Telneting into the emulator to capture logs and issuing Lua calls <here> (nice way to test your code) Using the Web GUI Debugging setTimeout code and tracking timers. MQTT support. Another post with running a scene completly without being connected to the HC3. Some notes on the implementation of the SDK - if you would like to hack on it A collection of QA's I developed with the SDK - which means that they can be run offline ChildrenOfHue. A QA that creates QA children devices for your Hue devices (It's the Hue QA I use myself these day) iOSLocator. An iOS geopresence QA. iCal (iOS,Google) QA Telegram QA. Event watcher QA. Helper QA to get/subscribe on event triggers Vonage/Nexmo SMS service. Send SMS. Changelog: v 0.67 - numerous bug fixes caused by the restructuring. hc3_emulator.start{startTime="07:00 4/5/2000"} - will start the simulation at the given time. v 0.68 - fibaro.debug behaves more like original. v 0.70 - better offline support and speeding. v 0.72 - More offline and support for downloading HC3 resources to be used while running disconnected from the HC3 v 0.73 - Various speed-time related bugs v 0.75 - Better http sync behaviour. Set hc3_emulator.asyncHTTP=true to get some pseudo asynchronous behaviour v 0.77 - Support for 5.030.45. Initial support for childDevices and fixes for the changed handling of UI events v 0.78 - UI fix. Name of callbacks defaults to button.."Clicked", unless you have a onReleased=name or onChanged=name in the UI table struct. v 0.80 - Fixed bug in self:getVariable and self:setVariable v 0.81 - Better quickVariables handling for proxies, and self.childDevices list updated when children are deleted. v 0.83 - self:getVariable returns the empty string "" if the variable does not exists according to the latest behaviour on the HC3... 'class' is not redefined if available from Luabind... However, I've not had a chance to test if it's 100% compatible yet... v 0.84 - Initial support for mqtt. You need to have installed https://github.com/xHasKx/luamqtt so that require("mqtt") works from fibaroapiHC3.lua. I have tried to mimic the HC3 mqtt api but I have not really used mqtt that much so if someone uses it with fibaroapiHC3.lua and discovers if stuff is not compatible with the HC3 implementation please let me know and we fix it. v 0.85 - Compatibility fix for function 'class' to adhere more closely to the HC3/luabind version v 0.90 - Cleanup of code, Better handling of children and QuickApps, ZBS color output with ansi escapes; hc3_emulator.colorDebug=true v 0.93 - New model for QuickApp proxies. Better child device compatibility. v 0.95 - Various bug fixes - log prints more in line with HC3 log console. fibaro.emitCustomEvent bug fix. v 0.98 - First support for backup/download/upload with the ZeroBrane plugin (another post here) v 0.99 - Better trigger handling and new way to include SDK in your QA/scene code. No hc3_emulator.start at the end. v 0.100 - Web GUI emulator for QuickApps. New format for using credentials.lua. Bug fixes... v 0.102 - Better handling of children and their quickAppVariables v 0.104 - Rewrite of offline mode. Better web UI support. v 0.105 - Support for new QA file format (proxies work again) v 0.106 - Added support for net.UDPSocket() v 0.109 - UDPSocket bug fix. ( @10der), property() support for class() - much harder than it looks... v 0.110 - Oops, serious bug in 'class' affecting ...everything. Hopefully fixed. v 0.111 - Removed unnecessary os.exit(). urlencode api calls ( @10der) v 0.112 - UDP fixes. ( @10der) v 0.114 - Bug fix (global 'self' escaped) v 0.115 - Bug in url encode for api calls. UDPSocket :bind(ip,port) function added. v 0.116 - :bind(ip,port) really fixed.... v 0.117 - startup fix v 0.119 - "Softer os.exit()" - better compatibility with Visual Studio (thanks @10der) v 0.120 - Debugger friendly QuickApp class (no __index). First version of file/backup v 0.121 - api.get bug fix. Faster proxy/deploy. v 0.123 - QuickApp:setVariable bug (thanks @10der) v 0.124 - fibaro.clearTimeout added, MQTT fixes. v 0.125 - fibaro.alarm() was buggy - fixed. Set self.USERPIN to pincode to allow fibaro.alarm("disarm") to be allowed from emulator. v 0.126 - fix __fibaro_get_device() ( @10der) v 0.128 - fix sort order of triggers. Default room in offline mode ( @10der) v 0.130 - fix UI handling ( @rangee. More UI options. v 0.131 - fix uiCallbacks not always updating when updating proxy v 0.135 - fixes... v 0.137 - TCPSocket fixes v 0.138 - setTimeout for negative times are inserted in the queue.... i.e. will execute as soon as possible. v 0.140 - fixed bug with setInterval (clearInterval within a setInterval function didn't work...) v 0.141 - fix bug in net.TCPClient() v 0.145 - bug in printout of sockets... stricter class constructor requirements v 0.148 - MQTT event format bug ( @jayrock) v 0.150 - Initial websocket support. Need to download wsLua_ER.lua from my github and put in project directory. v 0.152 - support fibaroapiHC3plug.lua v0.4 v 0.155 - bugfixes. v 0.156 - html color bugfix v 0.198 - New version of emulator with better support for everything. Thanks to @petrkl12 that has been a guinea pig and helped in debugging the code. v 0.200 - Fixed bug in speedTime. plugin.restart() now restarts the QA in a correct way. v 0.299 - Major rewrite of the HC3 API - cleaner architecture and prepared for being split into sub-files (I'm approaching 10k lines now). Note 'end--hc3' required to end header. v 0.300 - Bugfixes from v0.299 v 0.301 - Better/simpler class definition - easier to debug/step into classes (avoiding __index unless class uses property() )
  14. Hi guys I ask for Lua scene to control the lights automatically into star's by motion detection bt problem not for that The problem is I want that scene work between 6 pm to 7am and if motion detection don't detect any move then turn off light after 20 minutes Any one hare can help my to do that And Thanks for every one
  15. I use the following code and it gives me nicely a table of devices when applied in a scene, however when I apply it in Main of a VD, it returns null. Anyone a suggestion ? local data = { args = { 1 }, filters = { { filter = "hasProperty", value = { "power" } } } } local devices = fibaro:callGroupAction("deviceID", data)
  16. can someone help me? I am trying to create a scene that checks to see if a variable changes. if variable x=1 don't check variable (do nothing) but if variable x=0 then continuously search to see if a variable x changes from 0 to 1 then the loop stops until variable x changes to 0 again. *yes there is another scene that will change it from 0 to 1. *Edit, I figured this out.
  17. I have a scene that gets the sunrise and sunset for the day. I recently noticed that both sunrise and sunset times are not correct. They are about 30min - 1 hour off from what they should be. has anyone else seen this issue? Does anyone know if fibaro is going to fix it? @T.Konopka
  18. Hi Everyone, Since a couple of weeks im trying to learn a bit about Lua programming. At the moment im struggling to find an answer to my problem. To switch floor heating pump i used a power plug on my central heating boiler to measure the power usage to turn on the power of the floor heating pump (also a power plug). First i made a simple block scene which worked fine at first but now i found out that also when im using tap water the central heating boiler is using a significant amount of power. so the idea is to use the living room temp. sensor and the power measurement of the central heating boiler to switch the floor heating pump. Since the margin is very small im trying to do a double check so check if the conditions match, sleep for 3 minutes and check the conditions again before powering off. This is a bit of the code i used but get a error. if (PowerCV <'1') and (PompStatus >'1') then fibaro:debug('wacht 3 min voor uitschakelen') fibaro:sleep(10000) fibaro:debug(' 3 min later') and (PowerCV <'1') and (PompStatus >'1') then fibaro:call(191, "turnOff") fibaro:debug('Pomp staat nu uit') end it seems like im not able to check another set of conditions after the "sleep". is there a way to do this? all help is appreciated. thank!
  19. I have come across several Fibaro LUA functions that do not seem to be documented in the available Fibaro LUA manual. Here are a few examples: fibaro:getName(id) fibaro:getRoomNameByDeviceID(id) The use of formatting codes in fibaro:debug("text") And fibaro:call(id, "sendPush", "text..") and similar commands for e-mail etc. I have successfully used all of these and probably more. I am sure there are still more functions/calls out there which are only known from scenes published on the forum. Is there a more complete documentation available? Has anyone collected these semi-secret functions into a private document that may be shared?
  20. Guys, i simple need to send this command using a VD: Button1: PUT http://admin:[email protected]/ISAPI/ContentMgmt/record/control/manual/start/tracks/101 Button2:PUT http://admin:[email protected]/ISAPI/ContentMgmt/record/control/manual/stop/tracks/101 How can i do? Do u have some example? There ia also a way to check the status of the command? Regards Gianluca
  21. The documentation on Fibaro LUA states that the call fibaro:get(deviceID, property) "gets the latest data (value and time of last modification) of the device properties". The similar call fibaro:getValue(deviceID, property) is said to "get the current value of the device (deviceID) property". Apart from the difference that the first call may also retrieve the time of last modification, they seem to do identical jobs. I have seen, however, (I forget where) that the wording latest and current is significant. Am I right that the fibaro:get call retrieves its value from the latest value stored in the HC2, while the fibaro:getValue call retrieves it directly by a call to the device? If so, it is worth knowing when making a choice between the two, and the documentation could have been clearer. My specific reason for asking, is that I have a Fibaro door/window sensor, where the temperature measurement has been unchanged for several days, which is unlikely. In a small test script I used both the get and the getValue calls, and they returned identical values. The call used was simply fibaro:getValue(520, "value") and similarly for get. Time of last modification confirms that the value has not been changed for 215 000 seconds (60 hours). If communication had been lost with this device, would it not refuse to return a value from the getValue call? Or does it use the stored value if the device is unresponsive?
  22. Tried to combine two converted blok scenes to one, but now it wont trigger... Any suggestions ? ------------------------------------------------------------------------------------------------------------------------- --[[ %% autostart %% properties %% weather %% events %% globals --]] local sourceTrigger = fibaro:getSourceTrigger(); local currentDate = os.date("*t"); local startSource = fibaro:getSourceTrigger(); if ( ( ((currentDate.wday == 1 or currentDate.wday == 2 or currentDate.wday == 3 or currentDate.wday == 4 or currentDate.wday == 5 or currentDate.wday == 6 or currentDate.wday == 7) and string.format("%02d", currentDate.hour) .. ":" .. string.format("%02d", currentDate.min) == "04:00") ) or ( ((currentDate.wday == 1 or currentDate.wday == 2 or currentDate.wday == 3 or currentDate.wday == 4 or currentDate.wday == 5 or currentDate.wday == 6 or currentDate.wday == 7) and string.format("%02d", currentDate.hour) .. ":" .. string.format("%02d", currentDate.min) == "15:00") ) ) then fibaro:setGlobal("reclameverl", "1"); fibaro:debug("var reclverl set to 1") fibaro:sleep(60*1000) elseif ( ( ((currentDate.wday == 1 or currentDate.wday == 2 or currentDate.wday == 3 or currentDate.wday == 4 or currentDate.wday == 5 or currentDate.wday == 6 or currentDate.wday == 7) and string.format("%02d", currentDate.hour) .. ":" .. string.format("%02d", currentDate.min) == "09:00") ) or ( ((currentDate.wday == 1 or currentDate.wday == 2 or currentDate.wday == 3 or currentDate.wday == 4 or currentDate.wday == 5 or currentDate.wday == 6 or currentDate.wday == 7) and string.format("%02d", currentDate.hour) .. ":" .. string.format("%02d", currentDate.min) == "18:00") ) ) then fibaro:setGlobal("reclameverl", "0"); fibaro:debug("var reclverl set to 0") fibaro:sleep(60*1000) end ---------------------------------------------------------------------------------------------------------------------------------------------------- I,m hoping someone can give me a hint.... Gary set var reclverl.lua
  23. Hi could some explain to me what kind of variable or syntax this command needs fibaro:call(ID_RGB_CONTROLLER, "setColor", "0", "255", "0", "0") If i define local R_value = 255 fibaro:call(ID_RGB_CONTROLLER, "setColor", R_value, "255", "0", "0") "R_value" is not defined. The command fails. I tried character and single numeric, global and local etc. or do i have to use a table for all of the 4 values? I didn't find an example. Thanks Gerhard
  24. Hi could some explain to me what kind of variable or syntax this command needs fibaro:call(ID_RGB_CONTROLLER, "setColor", "0", "255", "0", "0") If i define local R_value = 255 fibaro:call(ID_RGB_CONTROLLER, "setColor", R_value, "255", "0", "0") "R_value" is not defined. The command fails. I tried character and single numeric, global and local etc. or do i have to use a table for all of the 4 values? I didn't find an example. Thanks Gerhard
  25. Cześć wszystkim! Jestem nowy na forum i nowy w temacie LUA. Walczę i szukam po forum od dłuższego czasu. Wiele problemów już rozwiązałem, ale ten zalazł mi konkretnie za skórę i potrzebuję pomocy ? Mam scenę, która ma działać zależnie od obecności w biurze. 3 czujniki po naruszeniu zaczynają odliczać czas i jeśli zostaną naruszone ponownie, odliczają od początku. Jeśli odliczą do zera to wyłączają światła i inne rzeczy. Oznacza to, że nikogo w biurze już nie ma. Kolejne naruszenie któregoś z czujnika wywołuje efekt odwrotny, czyli wszystko się włącza. Jest jednak jeden wyjątek, którym jest jeden z laptopów, którego nie obejmuje żaden czujnik. Jest on podpięty przez wallpluga i daje informację o zużyciu energii ~10W. Niestety nie umiem ustawić, aby po wyłączeniu laptopa scena zaczynała odliczać czas. Cały czas, bez względu na to czy jest on włączony czy nie, licznik stoi na maksymalnej wartości i nie zaczyna odliczania w dół. Zaczyna to odliczanie dopiero gdy zmieniłem wartość z "power" na "value" i dałem > 0 czyli włączony wallplug. Na ten moment działa to w ten sposób, czyli wnioskuję, że pozostałe elementy sceny są poprawne. Mimo wszystko nie zadowala rozwiązanie, w którym trzeba wyłączyć wallplug, żeby licznik zaczynał odliczać obecność w biurze. Pomocy, kod poniżej --[[ %% autostart %% properties 70 value 657 value 694 value 775 value %% events %% globals --]] --funkcje local czujnikbiuro = (tonumber(fibaro:getValue(70, "value")) > 0); local czujnikwejscie = (tonumber(fibaro:getValue(657, "value")) > 0); local czujnikmagazyn = (tonumber(fibaro:getValue(694, "value")) > 0); local delay = 600 --włączanie zmiennej PRACA = ON if czujnikbiuro or czujnikwejscie or czujnikmagazyn then fibaro:setGlobal("PRACA", "ON"); fibaro:debug("Witaj w salonie Fibaro"); end --uruchamianie pracy if fibaro:getGlobalValue("PRACA") == "ON" then fibaro:call(46, "open"); fibaro:debug("Zasłona została otwarta"); fibaro:startScene(349); fibaro:debug("Muzyka gra przez głośnik Sonos"); fibaro:startScene(530); fibaro:debug("Automatyczne działanie ekspozycji LED włączone"); fibaro:call(16, "turnOn"); fibaro:call(15, "turnOn"); fibaro:call(17, "turnOn"); fibaro:debug("Profile LED nad stołem zostały włączone"); fibaro:call(376, "setValue", "70"); fibaro:debug("AmstLED ustawiony na 70 procent"); fibaro:call(177, "turnOn"); fibaro:debug("Telewizor włączony"); fibaro:call(420, "turnOn"); fibaro:debug("Lampa nad TV włączona"); end --utrzymywanie stanu włączonego przez 10min bezruchu if fibaro:getGlobalValue("PRACA") == "ON" then local turnOffTime = os.time() + delay while turnOffTime > os.time() do if (tonumber(fibaro:getValue(657, "value"))) > 0 or (tonumber(fibaro:getValue(694, "value"))) > 0 or (tonumber(fibaro:getValue(70, "value"))) > 0 or (tonumber(fibaro:getValue(775, "value"))) > 0 then turnOffTime = os.time() + delay end fibaro:debug("zwłoka: "..tostring(turnOffTime - os.time())) fibaro:sleep(5000) end end --wyłączanie pracy po 10min bezruchu fibaro:call(46, "close"); fibaro:call(16, "turnOff"); fibaro:call(15, "turnOff"); fibaro:call(17, "turnOff"); fibaro:call(681, "turnOff"); fibaro:call(376, "turnOff"); fibaro:call(177, "turnOff"); fibaro:startScene(352); fibaro:debug("Do widzenia");
×
×
  • Create New...