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!



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


  • 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


  • Scenes
  • Virtual Devices
  • Quick Apps
  • Icons

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start






Website URL





  1. Tiny QuickApp Emulator (TQAE) started out as a simple modular QuickApp emulator but have evolved into a pretty good development environment. (Great intro to TQAE <here> from @Joep - thanks!) /TQAE.lua v0.56 -- Main emulator, loads other modules /modules/sync.lua -- timers with fake asynchronous IO /modules/async.lua -- timers with asynchronous IO based on copas /modules/copas.lua -- copas.* functions /modules/net.lua -- net.* functions /modules/api.lua -- api.* and web api /modules/json.lua -- json library /modules/fibaro.lua -- fibaro.* functions /modules/class.lua -- class function /modules/files.lua -- support for loading files, *.lua and *.fqa files /modules/QuickApp.lua -- QuickApp classes /modules/devices.json -- device templates /modules/webserver.lua -- web server for remote calls (ex. from proxy) /modules/proxy.lua -- creates QA proxy on the HC3 for funnelling back onAction and UIevents /modules/ui.lua -- Local Web UI for QA /modules/time.lua -- Time manipulation - changing start time... /modules/refreshStates.lua -- /refreshStates support /modules/Scene.lua -- Initial support /modules/offline.lua -- Support for local shadowing resources. Currently /globalVariables /modules/stdQA.lua -- Standard (simulated) devices /web/main.html -- Web - Main emulator page /web/qa.html -- Web - QuickApp info /web/ui.html -- Web - QuickApp UI /web/timers.html -- Web - list of active timers /web/settings.html -- Web - editor for configuration file examples/MyQuickApp.lua -- Simple QuickApp examples/Hue.lua -- Hue QuickApp with QuickAppChildren examples/Scheduler.lua -- Simple minute based scheduler examples/Ping.lua -- Ping QuickApp that loads Pong QuickApp and exchanges fibaro.calls... examples/Pong.lua examples/TestScene.lua -- Test scene examples/TestSceneCron.lua -- Test scene with Date condition examples/Backup.lua -- Non-QA code that backs up QuickApps from the HC3 to the local filesystem as *.fqa files examples/SamsunWebSocket.lua -- WebSocket example controlling my Samsung TV examples/TestTCPSocket.lua -- TCPSocket example with emulated responses setup/TQAEplugin.lua -- ZBS plugin to give editor help and fibaro command completion. TQAE.gz -- Every file in one archive Installation First time download the archive, TQAE.tar.gz and unpack it in a suitable directory on your PC/Mac/Linux. On Linux: >tar xvf TQAE.tar.gz On PC/Mac use suitable archive program to unpack the archive. ../TQAE.lua ../TQAE_QA.lua ../modules/* ../examples/* Alternatively clone the GitHub repository >git clone https://github.com/jangabrielsson/TQAE I will do my best to keep the repository clean. This way it's easy to keep up with updates of the code. Download ZeroBrane studio <link> Open ZBS and open the TQAE_QA.lua file Set project directory in ZBS to the current file, TQAE_QA.lua (Project->Project Directory->Set From Current File) Also set Lua interpreter to Lua 5.3 (Project->Lua Interpreter->Lua 5.3) Now, run TQAE_QA.lua (F5 in ZBS). The output will look something like: ---------------- Tiny QuickAppEmulator (TQAE) v0.30 ------------- [11.10.2021] [08:33:23] | SYS|: No connection to HC3 [11.10.2021] [08:33:23] | SYS|: Created WebAPI at [11.10.2021] [08:33:23] | SYS|: sunrise 07:43, sunset 19:50 Note first that there is no connection to the HC3 - we are missing user, password, and IP for the HC3. Secondly, note the WebAPI address. is my machine, your IP address may be different. The port is 8976. While TQAE_QA.lua is running open in your browser. (the Web UI only works while the emulator is running) Goto [Settings] in the web page menu (upper right). Fill in User ID, Password, and IP address for the HC3. Click "Save" Hopefully there is now a TQAEconfigs.lua file with the HC3 credentials that the emulator can use. Go back to ZBS and stop the program (Shift-F5) and run it again: ---------------- Tiny QuickAppEmulator (TQAE) v0.30 ------------- [11.10.2021] [09:13:43] | SYS|: Using config file TQAEconfigs.lua [11.10.2021] [09:13:43] | SYS|: Created WebAPI at [11.10.2021] [09:13:43] | SYS|: sunrise 07:14, sunset 17:52 It loads the config file and doesn't complain that there is no connection to the HC3 anymore. If you run ZBS I strongly encourage you to download the copy the TQAE/setup/TQAEplugin.lua file to your home directory ~/.zbstudio/packages/TQAEplugin.lua Also create directory ~/.zbstudio/tqae and move the files TQAE/setup/codeTemplates.lua and TQAE/setup/fileDownloads.lua to that directory. It will give you tooltips for the fibaro lua functions and some shortcuts to download updates to TQAE. Restart ZBS after installing the files. Great we are up and running! Supported functions (v0.33) 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() net.WebSocketClientTLS() mqtt.Client.connect(uri, options) <mqttclient>:addEventListener(message,handler) <mqttclient>:subscribe(topic, options) <mqttclient>:unsubscribe(topics, options) <mqttclient>:publish(topic, payload, options) <mqttclient>::disconnect(options) 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) json.encode(expr) json.decode(string) plugin.mainDeviceId plugin.deleteDevice(deviceId) plugin.restart(deviceId) plugin.getProperty(id,prop) plugin.getChildDevices(id) plugin.createChildDevice(prop) class QuickAppBase class QuickApp class QuickAppChild QuickApp:onInit() -- called at startup if defined QuickApp - self:setVariable(name,value) QuickApp - self:getVariable(name) QuickApp - self:debug(...) QuickApp - self:trace(...) QuickApp - self:warning(...) QuickApp - self:error(...) QuickApp - self:updateView(elm,type,value) QuickApp - self:updateProperty(name,value) QuickApp - self:createChildDevice(props,device) QuickApp - self:initChildDevices(table) The idea and reason that I implement an offline emulator for the HC3 is that it is generally speaking a pain to debug a moderately complex QuickApp on the HC3. You are left to using debug statements and it slow you down as you can not set breakpoint and step through the code to understand what logic it is following. With an offline emulator running on a PC/Mac you can use a modern IDE like ZeroBrane or VisualStudio to develop your QA. You can quickly put together 99.9% of your QA and the speed/productivity tripples. When it works in the emulator you can move the code to the HC3 and it will work. No need to develop on the HC3 and accidentally crash the whole box and make your family upset. Here is a video showing a typical workflow. (Note that the Web UI now has a button "Upload" that uploads the QuickApp when it's ready to the HC3) Writing HC3 (HC2) emulators seems to be a hobby for me - but what better thing to do on a vacation? So far I have HC2 Scene emulator - quite ok and feature complete, not actively developed anymore but still works well (not much has happened to the HC2 scene framework lately) HC3 emulator (fibaroapiHC3.lua) - gazillion of features, 9.5k lines - haven't come across any QA it can't run. Also some basic Scene support HC3 micro emulator - ~70 lines of Lua that can run QAs in parallel but have a very limited function support. Developed to prove that we could enhance the call model of QAs without much work Well, the micro emulator got my interest and I have evolved it to a more full featured emulator - Tiny QuickApp Emulator (TQAE). Runs multiple QAs in parallel - can test fibaro.calls between them Supports net.HTTPClient, setTimeout, clearTimeout, setInterval, clearInterval, json.*, class, property Supports QuickApp methods - self:setVariable, self.getVariable, self:updateProperty, self:updateView Supports fibaro.* functions Supports QuickAppChild devices Supports simple web UI to test QuickApp buttons/sliders Supports proxy QA on the HC3 to make to emulated QA interact with QAs running on the HC3 - Real HC3 QAs can call the QA you are running in the emulator. (and you get a real UI too) The main idea is that the emulator could be used as a light weight playground for testing out QAs The main logic is still under 1000 lines with current modules but stuff like json support and the whole fibaro.* sdk requires quite some code so it tends to swell - in any case it's modular. Dependencies on luasocket. (I recommend the free ZeroBrane Studio as it comes with the necessary libraries and is a specialised development environment for Lua) local http = require("socket.http") local socket = require("socket") local ltn12 = require("ltn12") It has an easy structure (I think). There are very few differences between TQAE and fibaroapiHC3.lua so I mainly work with TQAE these days. Advantages compared to fibaroapiHC3.lua. Easier to debug as code is not as asynchronous as it is in the fibaroapiHC3 scheduler (possibility to use a sync scheduler). Uses a vanilla fibaro.* implementation only leveraging api.* and __fibaro_* calls, so it should be easy to upgrade if we get new fibaro.* calls. Module structure makes it easy to add new libraries etc. It's modular. Include it in your QA code _=loadfile and loadfile("TQAE.lua"){ user="admin", pwd="admin", host="" } --%%name='Test' --%%id=99 --%%quickVars={x=88,y=99} function QuickApp:onInit() self:debug(self.name,self.id) self:debug("y=",self:getVariable("y")) local n = 5 setInterval(function() n=n-1 if n <= 0 then os.exit() end self:debug("PING") end,1000) end The loadfile at the top loads in the emulator and run your QA. The { ... } table after loadfile("TQAE.lua") is a table with configuration options to the emulator. The emulator needs ip, user and password to access the HC3. If you don't want to type that you can store a config file for TQAE with you standard settings. The default name for the file is "TQAEconfigs.lua" and it can look like return { user="admin", pwd="admin", host="", verbose=false, modPath = "TQAEmodules/", temp = "temp/" --localModules = {"myModule.lua"} --globalModules = {"UDP.lua"} } However, you still need to call loadfile("TQAE.lua"){} with and empty table. If you would like to have another name of the file you can specify that loadfile("TQAE.lua"){ config = "myTQAEconfigfile.lua" } The config is parameters for the emulator. Then you can also set "parameters" for the individual QAs that you run using --%% directives The --%% directives in your QA code are collected into a Lua table. In the case above { name='Test', id=99, quickVars = { x=88, y=99 } } and if present will be used to add fields to the QA. This is the way to tell what name, id and type you want your QA to have. A special field is quickVars that will be inserted as quickAppVariables of the QA at startup. Note that each field can only be one line. It's easy to startup another QA from within your code _=loadfile and loadfile("TQAE.lua"){ user="admin", pwd="admin", host="" } --%%name='Test' --%%id=99 hc3_emulator.installQA{id=444,file='MyOtherQA.lua'} -- Load in another QA and set id to 444 function QuickApp:onInit() self:debug(self.name,self.id) fibaro.call(444,"test",5,6) -- call other QA end If the other file is open in the IDE you can set breakpoints in it and jump between the QAs. In fact, hc3_emulator.installQA{id=444,file='MyThirdQA.fqa'} will load in a .fqa file directly. In that case temporary files are stored for each of the files in the .fqa. This means we can do trick like this, downloading a QA from the HC3 and run it in the emulator with one line of code _=loadfile and loadfile("TQAE.lua"){ user="admin", pwd="admin", host="" } hc3_emulator.installQA{id=700,code=api.get("/quickApp/export/700")} -- Load in QA 700 from HC3 and run it function QuickApp:onInit() self:debug(self.name,self.id) fibaro.call(700,"test",5,6) -- call QA 700 end Another useful directive is --FILE:<filename>,<name>; that allow us to include extra files in our QA. A QA can consist of several files but it must have a 'main' file. The QA code you run in the emulator will always be the main, and then you can include extra files that will be added to the QA as "files". Ex. _=loadfile and loadfile("TQAE.lua"){ user="admin", pwd="admin", host="" } --FILE:myUtilities.lua,utilities; function QuickApp:onInit() self:debug(self.name,self.id) LOG("This is a test") -- Using global LOG function defined in myUtilities.lua end Running and logs When running there will be output of two types. Standard logging that the QA does with fibaro.debug, self:debug etc,. System debugs, that are the emulators way to inform on what is ongoing. How much the system logs depends on the configuration parameter .logLevel. ---------------- Tiny QuickAppEmulator (TQAE) v0.5 ------------- [29.07.2021] [11:17:34] |SYS |: Loading QA:TestQA1 - ID:1001 Start [29.07.2021] [11:17:34] |SYS |: Starting QA:TestQA1 - ID:1001 [29.07.2021] [11:17:34] [DEBUG] [QUICKAPP1001]: TestQA1 - 1001 Here we se the system log (|SYS |) that the QA is loading and then the log that it's running. The first is when the QA code is loaded and all functions are defined. Also if you do something on top-level, outside functions it will run here. In the example the QA does a print("Start") on top-level of the QA so that is executed when loading. Then, if the QA is successfully loaded, it will be "started, meaning that the function QuickApp:onInit() will be called if it's defined. That's the second SYS log. It's good to pay notice to this. If you get an error before Loading it typically means that you have a syntactic error in the QA code - non-valid Lua code. If you get an error after Loading but before Starting it's something on top-level that is run, outside of function QuickApp:onInit() If you get an error after Starting, well, then it's just something wrong with your code when it runs. A run-time error will look like: [29.07.2021] [12:27:47] [ERROR] [QUICKAPP1002]: [string "temp/main_16546.lua"]:5: attempt to call a nil value (global 'foo') This tells us that the error was in the QA with id 1002 (unless you have changed __TAG) The QA file is 'main'. A QA can consist of many files and this gives us the clue in what file the error was. If you only have one file, its name is 'main'. Then it tells us that is was line 5 where the error occurred ([string "temp/main_16546.lua"]:5:) and then that we tried to call a global variable 'foo' that didn't have a value (a function) So, in the main file look for a foo() call on line 5 - that's the error... Turning up logLevel will also log modules loaded etc. It also sets a Lua global in the QA, LOGLEVEL to the level, so that variable can be used by you to also allow your code to log more or less. Other features The Web UI allows the file to be saved as a *.fqa file that can be uploaded manually to the HC3. It you have included multiple files with the --FILE: directive they will also be included. A simple way to code and create multi-file QAs. The Web UI can also upload the QA directly to the HC3. The directive 'interfaces' Ex. --%%interfaces={"power"} will add the interfaces as the initialInterfaces property of the .fqa. An easy way to include and extra interface in the ready .fqa. Emulator options: (set in the header _=loadfile and loadfile("TQAE.lua"){...} ) user=<user> Account used to interact with the HC3 via REST api pwd=<Password> Password for account used to interact with the HC3 via REST api host=<IP address> IP address of HC3 configFile = <filename> File used to load in emulator options instead of specifying them in the QA file. Great place to keep credentials instead of listing them in the QA code, and forget to remove them when uploading codeto forums... Default "TQAEconfigs.lua" debug={ traceFibaro=<boolean> -- default false QA=<boolean>, --default true module=<boolean>, --defaul false module2=<boolean>, --defaul false lock=<boolean>, --default false child=<boolean>, --default true device=<boolean>, --default true refreshStates=<boolean> -- default false } modPath = <path>, Path to TQAE modules. Default "TQAEmodules/" temp = <path> Path to temp directory. Default "temp/" startTime=<time string> Start date for the emulator. Ex. "12/24/2024-07:00" to start emulator at X-mas morning 07:00 2024. Default, current local time. htmlDebug=<boolean>. If false will strip html formatting from the log output. Default true colorDebug=<boolean>. If true will log in ZBS console with color. Default true copas=<boolean> If true will use the copas scheduler. Default true. noweb=<boolean> If true will not start up local web interface. Default false lateTimers=<seconds> If set to a value will be used to notify if timers are late to execute. Default false timerVerbose=<boolean> If true prints timer reference with extended information (expiration time etc) QuickApp options: (set with --%% directive n file) --%%name=<name> --%%id=<number> --%%type=<com.fibaro.XYZ> --%%properties={<table of initial properties>} --%%interfaces={<array of interfaces>} --%%quickVars={<table of initial quickAppVariables>} --%%proxy=<boolean> --%%save=<boolean> Documentation Emulator parameters and QA parameters Web UI - and QA UI Some implementation notes Notes and ToDos Mostly developed as a playground for my own coding and it fits my workflow. I may add features/fix bugs if others are using it - but no more than 500 lines of code
  2. I am trying to push a certain button from a different device, if the door is closed, but I cant locate how to let FIBARO know that the door is closed. How can I do that in scenes? Thanks in advance.
  3. I am very conversant with the HC2 stuff. For the HC3, the last time I looked at this a year ago, the offerings were rather disappointing with a steep learning curve. Could some one recommend A decent example of a lua scene. I am fine with the language change - I have just grepped and done global modifications on my 30 odd lua scenes. I am looking for a better explanation of the new trigger mechanism. A decent example of the new VD and any gotchas. Before I could just save the lua as a text file on pc with versioning. How are people saving the new scenes, as they come in two parts ?
  4. I am trying to start a boiler and a heater from an URL that has a lot of prices and timestamps. I am using Home Center 2. I have no idea where to start from, I understand I need VD (Virtual Devices) and Scenes, but anything I have tried hasn't worked sadly. How can I start a boiler and a heater during the lowest prices with JSON timestamp values from an URL? If required, I can post the URL here. Can anyone help me?
  5. Introduction to API and http requests Like the other 'Introduction to' posts I'm h0ping this may help some of the people begining their HC2 and lua journey Corrections and suggestions to improve always welcome. What is an API An API can be used to execute commands but the majority are used to request a response or status. Most API’s are interrogated through a http or https request. Some API’s require authentication in the form of a username or a password or an API key. There are public API’s and private API’s. There are a number of API types and the one of the most widely used is a called RESTAPI. This type of API is supported by the HC2 but there are others such MQTT, SOAP, etc The following are API’s that you may have come across in this forum and there are many others Home Center 2 : http://<hc2-ip>/docs (where hc2-ip is the ipaddress of your hc2 192.168.x.x OWN : open weather map ( https://openweathermap.org/api ) Sonos-http-api : ( https://github.com/jishi/node-sonos-http-api ) AWS Polly: used for TTS (http://docs.aws.amazon.com/polly/latest/dg/API_Reference.html ) VoiceRSS : used for TTS (http://www.voicerss.org/api/documentation.aspx ) Some organisations like AWS or Google have multiple API’s that are used for different purposes Structure All API’s has a set of web methods with a set structure. An API call or request can be either a GET, DELETE, POST, PUT and for this introduction we will focus on the GET This means that the data format is predictable and as such is easy to traverse and extract responses. Most RESTAPI responses have a format that conforms to json standard. Json is a way to store information in an organized, easy-to-access manner. It gives us a human-readable collection of data that we can access in a really logical manner. All public API’s are documented like the ones outlined above so a under will know what to expect when they issue a http request. A simple json example would be something like local jStr = {"age" : "24", “hometown" : "Missoula, MT", "gender" : "male" }; A slightly more complicated json string could be be {"coord":{"lon":15.98,"lat":45.81},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main" :{"temp":10.86,"pressure":1018.82, "humidity":66,"temp_min":10.86,"temp_max":10.86,"sea_level":1035.43,"grnd_level":1018.82},"wind":{"speed":1.06,"deg":281.501},"clouds":{"all":32},"dt":1487346966,"sys":{"message":0.0038,"country":"HR","sunrise":1487310847,"sunset":1487348795},"id":6618983,"name":"Zagreb - Centar","cod":200} This could also be referreed to as a tbale because of it's structured format. Fortunately there are websites like http://jsonprettyprint.com/ that make these json strings easier to read { "coord": { "lon": 15.98, "lat": 45.81 }, "weather": [ { "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03d" } ], "base": "stations", "main": { "temp": 10.86, "pressure": 1018.82, "humidity": 66, "temp_min": 10.86, "temp_max": 10.86, "sea_level": 1035.43, "grnd_level": 1018.82 }, "wind": { "speed": 1.06, "deg": 281.501 }, "clouds": { "all": 32 }, "dt": 1487346966, "sys": { "message": 0.0038, "country": "HR", "sunrise": 1487310847, "sunset": 1487348795 }, "id": 6618983, "name": "Zagreb - Centar", "cod": 200 } To access an api you need 2 things ip address, port, etc to make the http/https request Structure/format of the response so you know how to traverse it and extract what you want The easiest way to explain and learn is by example. As it is highly likely that everybody reading this will have a HC2 we can use to demonstrate the principles. The HC2 RESTAPI is documented on the Fibaro developer site at https://developer.fibaro.com/docs/fghc-restapi The one we will look at is devices. This the first one under the General category at the developers website above. The developer website shows the various parameters that are returned with this call. The API can be used to request information or complete an action. We will look at the request for information If you go to http://,hc2-ip./docs you will see the interactive or inline documentation for web API Go to the section on devices and select deviceid enter a device number ( I selected device 176 which is a dimmer module ) and click Try It. You will see the json formatted or encoded response for that API call. You will also see the full url for the call. If you copy the url and paste it into a browser you will get the same thing (except as one long string) {"id":176,"name":"kitchenPendant","roomID":7,"type":"com.fibaro.multilevelSwitch","baseType":"com.fibaro.binarySwitch","enabled":true,"visible":true,"isPlugin":false,"parentId":175,"remoteGatewayId":0,"interfaces":["deviceGrouping","fibaroFirmwareUpdate","levelChange","light","power","zwave","zwaveConfiguration","zwaveSceneActivation"],"properties":{"parameters":[{"id":1,"lastReportedValue":255,"lastSetValue":255,"size":1,"value":255},{"id":6,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":7,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":8,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":9,"lastReportedValue":5,"lastSetValue":5,"size":1,"value":5},{"id":10,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":11,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":12,"lastReportedValue":99,"lastSetValue":99,"size":1,"value":99},{"id":13,"lastReportedValue":2,"lastSetValue":2,"size":1,"value":2},{"id":14,"lastReportedValue":2,"lastSetValue":2,"size":1,"value":2},{"id":15,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":16,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":17,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":18,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":19,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":20,"lastReportedValue":110,"lastSetValue":110,"size":1,"value":110},{"id":30,"lastReportedValue":3,"lastSetValue":3,"size":1,"value":3},{"id":39,"lastReportedValue":600,"lastSetValue":600,"size":2,"value":600},{"id":41,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0}],"pollingTimeSec":0,"zwaveCompany":"Fibargroup","zwaveInfo":"3,3,52","zwaveVersion":"2.2","configured":"true","dead":"false","deviceControlType":"23","deviceGroup":"[]","deviceGroupMaster":"0","deviceIcon":"15","emailNotificationID":"0","emailNotificationType":"0","endPointId":"0","firmwareUpdate":"{\"info\":\"\",\"progress\":0,\"status\":\"UpToDate\",\"updateVersion\":\"2.2\"}","isLight":"true","liliOffCommand":"","liliOnCommand":"","log":"","logTemp":"","manufacturer":"","markAsDead":"false","model":"","nodeId":"49","parametersTemplate":"235","power":"0.00","powerConsumption":"42","productInfo":"1,15,1,0,16,10,2,2","pushNotificationID":"0","pushNotificationType":"0","remoteGatewayId":"0","saveLogs":"true","sceneActivation":"0","serialNumber":"","showEnergy":"true","smsNotificationID":"0","smsNotificationType":"0","updateVersion":"","useTemplate":"true","userDescription":"","value":"0"},"actions":{"associationGet":1,"associationSet":2,"getParameter":1,"reconfigure":0,"setParameter":2,"setValue":1,"startLevelDecrease":0,"startLevelIncrease":0,"stopLevelChange":0,"turnOff":0,"turnOn":0,"updateFirmware":1},"created":1486747960,"modified":1486747960,"sortOrder":13} EXAMPLE - API Call from a Virtual Device The following is a http request to the HC2 api. Copy the following in a button or main loop in a virtual device local device = fibaro:getSelfId() localhost = '' local port = 11111 diag = Net.FHttp(localhost, port); response = diag:GET("/api/devices/176") result = json.decode(response); fibaro:debug("name: "..result.name) fibaro:debug("properties.value: "..result.properties.value) run the vd and open the debug window You’ll see the name and value of the device you selected. If you look through the json response from further up in the tutorial you’ll see the correlation between the results and the json There are some examples of how to iterate through an array in another one of the tutorials I posted. Please see my signature… One last one in case you have difficulty sleeping and the if the above was too simple This function iterates through all the virtual devices on your HC2 and looks for one called 'LAN Network 2.0' The 'LAN Network 2.0' virtual device has multiple labels The function iterates through the virtual device and counts all the labels ( in the json for the virtual device these are called rows) For each row above it looks for an element type ‘Label’ It then iterates through all the labels checking that they match the default format of Label1, Lable2, etc. string.match(jT[i].properties.rows[r].elements[e].name, "Label")) == "Label" The result is a loop inside a loop inside another loop, iterating and checking at each step full code for function to pick through when you have some time. function labelCheck() fibaro:log("vdCheck mode enabled") local device, localhost, port = fibaro:getSelfId(), '', 11111; diag = Net.FHttp(localhost, port); response = diag:GET("/api/virtualDevices") jT = json.decode(response); for i = 1, #jT do if jT[i].name == "LAN Monitor 2.0" then if #jT[i].properties.rows == #jN then labelCount = "true" else labelCount = "false" end for r = 1, #jT[i].properties.rows do for e = 1, #jT[i].properties.rows[r].elements do if (string.match(jT[i].properties.rows[r].elements[e].name, "Label")) == "Label" then labelMatch = labelMatch else labelMatch = "false" end end end end end if labelCount == "true" and labelMatch ~= "false" then fibaro:debug("Quantity and format of labels is correct") else if labelCount == "false" then fibaro:debug("Quantity of labels incorrect") fibaro:log("Quantity of labels incorrect") end fibaro:sleep(3000) if labelMatch == "false" then fibaro:debug("Label format is incorrect") fibaro:log("Label format is incorrect") end end end Happy coding and suggestions to improve/correct always welcome -f
  6. Hello. I have written a code in LUA 5.4 which gives me a list of prices and timestamps through a URL, and on FIBARO HC2 it wont work. I understand that FIBARO HC2 uses Lua 5.1 or something like that. I am trying to start a boiler and a heater using HC2, but I have no idea how to start with that. How can I start the boiler and a heater at the time when prices are low on HC2 using a website URL? If required, I will provide more information in the comments. Thanks in advance.
  7. Is it possible to change the range of a slider, I mean, instead of going from 0% to 100%, can I make it go from 15ºC to 30ºC somehow, if not, can I remove the percentage tag of the slider completely? Thx
  8. Quick question: How can I update the value of a slider? I've tried self:updateProperty, self:updateView, fibaro:call, etc, and none of them seem to work.
  9. Hi, I would like to set a device parameter thru either a virtual device (preferred) or a scene In my example, I have a doorlock (IDLock 101) and would like to set parameter number 1 (autolock mode) The parameter can set the lock to autolock(arm or not armed) or manual (arm or not armed) https://idlock.no/wp-content/uploads/2018/03/IDL-Operational-Manual-EN-v1.3.pdf Is it possible thru LUA or do I need to set it another way? Regards
  10. There is supposed to be only three types of controls: buttons, sliders and labels, but if I create a Quick App with a template (thermostat auto for instance), I has other controls, like combo boxes. How can I add those custom controls or create them myself. And why can I not delete the controls of the templates, I mean, if I use a template, I can only delete the controls that I add on top of the default ones, in fact, those templates controls don't even show up in the preview window. whut ?¿?¿
  11. I need to send commands to a Modbus router to turn on a thermostat. I've heard that the commands need to be sent in hexadecimal format, as shown in this example I found online: function QuickApp:turnOn() comand = string.char(0x00,0x01,0x00,0x00,0x00,0x06,0x01,0x06,0x00,0x64,0x00,0x01); self:send(comand) -- sending data to the device. In a normal implementation it will be a code with an appropriate command. self:updateProperty("value", true) end But how can I know how to encript the commands I want in this format, I mean, how many characters it needs to be, in what order, etc. I can't find any info online so any help is appreciated. Thx.
  12. I have some device connected to z-wave plugs that can measure the energy consumption and aeon labs plugs are used. Now I would like every month a report how many kWh, all summary of consumption. Best would be to get that report by email. Is something like this possible in the HC3 lite with LUA? Can anybody help me to get started: - how to get all consumption summary - how to send an email - how to run the script only once per month Thanks
  13. Hi Everyone Smart Message Hub v1.2 (SMsgH v1.2) is now available. This release includes fixes tor three bugs that had various impacts and support for international characters. Thanks to @Sankotronic and @szmyk for locating the faults and extra feature for international characters "FIRST TIME USERS" - Please read below and follow the instructions laid out for first time users UPGRADING FROM 1.1b to 1.2 - Please use this Post - if you are a current user and may wish to consider avail of the fixes or extra feature This scene enables a user to send a message from either a scene or a virtual device to a number of notification and TTS services with a startScene call fibaro:startScene(682, {message, target}) -- Using ID of scene fibaro:startScene(SMsgH, {message, target}) -- Using HomeTable reference The scene also enables messages to be re-routed or queued depending on whether the house is set to Away mode, Sleep mode or if internet is not available. (See below for more details) A demo VD {v1.1} is also available to help demonstrate the scene features. SCENE FEATURES Smart Configuration options include the ability to re-route and/or queue all messages under certain conditions. (Internet unavailability , home occupancy mode presentState = Away) Messages with international characters are also supported Notification messages can be redirected to Home Center 2 Popup notification service if the internet is offline or unavailable Notification messages can be queued if the internet is offline or unavailable. All Messages in the queue will be released as one combined message once the internet come s back online. All TTS messages can be redirected to Home Center 2 Popup notification service if the internet is unavailable or offline or if the sonosAPI is offline if this solution is being leveraged All TTS messages can be queued if presentsState = Away. All TTS messages in the queue will be announced once presentsState = Home Simplified the message invocation method to startScene Invoked via startScene(SMsgHid, {message string} (SMsgHid is the id of the SMsgH scene when it is saved to your system ) See below for examples messageHub global no longer required (please delete when you have migrated all your scenes to using 1.1) Added support for sleepState (no TTS messages if set to Sleep) Additional support for HC2 popup notifications Types (Critical, Successs, Info, Warning) Images (use full url) Buttons (represented as a table) - See @Sankotronic [TUTORIAL] on popup notifications to see how to format Added ability to delay unloading of TTS messages by predefined time in seconds Added support for custom language in for TTS and Notify redirects default Popup title and subtitle Minor bug fixing and code cleaning Configuration options also include a default message notification target, title, subtitle and volume but all these can also be specified as part of the message invocation. There are three levels of debug verbosity. In normal mode there is a minimal amount of information displayed as the scene is triggered. The two other modes allow for much more expressive displaying of scene variables as well as configuration settings if enabled deBgVar is enabled in the scene so you can see the interactions- it can be disabled in normal running mode SCENE MESSAGING OPTIONS The supported services in this release include the following (supported in 1.0 & 1.1) Pushover Notifications -------------------------------------------------------> [TUTORIAL] on creating Pushover account and set up allinone ( jompa68 scene) Telegram messages hc2email (Home Center 2 email service) hc2push (Home Center 2 push notification service) hc2popup (Home Center 2 Popup Notification service) -------------------> [TUTORIAL} Popup Noification and Custom Inages Sonos-api based TTS --------------------------------------------------------> [TUTORIAL] Setting up and using Alternative Sonos VD using node-sonos-api Sonos VD Remote based TTS -----------------------------------------------> Discussion on Sonos Remote V1.0.0 beta I have also included a Companion Demo VD. The virtual device will allow the user to demonstrate the scenes queuing/unloading capabilities. CAUTION: The companion VD in demo mode can adjust the presentState and sleepState globals and will cause any other scene you may have with this as a trigger to execute A simplified version of the LAN Monitor VD called the WWWAPI Monitor will monitor just the sonos-api if desired and does not any in-built notification options like the LAN Monitor VD 2.5.Smart Message Hub users should use either the WWWAPI Monitor or LAN Monitor 2.6 Special thanks extended to @Sankotronic @petergebruers, @jompa68 and @szmyk for their contributions leading to 1.2 Once the scene configuration is complete I would recommend running the demonstration virtual device. This will give you a better understanding of the options and features as well providing some sample messages that you can run. Ideas for subsequent revisions are always welcome _f RELEASE CHANGELOG v1.0 - First release (march 4th 2017) v1.1 - Second release (march 17th 2017) v1.2 - Third Release (june 24th 2017) ================================================ FIRST TIME USERS - INSTALLATION & CONFIGURATION ================================================ The code is available in both lua and txt format below Paste code into scene and run - All global variables will be automatically created (Please do not adjust global triggers in scene header) Configure options as required at top of scene (line 100 onwards) Configure enable smart redirects Configure HC2 email settings, HC2 push settings and TTS services Configure default message titles, subtitles and volume Configuration notification settings, tokens, etc Enable/Disable increased debug and config verbosity for troubleshooting MESSAGE INVOCATION This message hub can be called from either a scene or a virtual device using a startScene call. The following is an example Sample invocations are included below Please see the section on Message Invocation lower down in this post of you wish to send messages with international characters local message = "Warning: Utility room freezer temperature is 10 degrees" local target = "hc2popup" local volume = "25" -- (can be left as "" if not TTS message) local title = "new alert title" local subtitle = "new subtitle" local popType = "Critcal" local popImg = "" local popButtons = "" fibaro:startScene(IDofSMsgHscene, {message, target, volume, title, subtitle, popType, popImg, popButtons}) Note: Replace IDofSMsgHscene with HomeTable reference of numerical ID of the SMsgH scene when it is installed on your system You need to include all parameters up to last one you populate. For example, if you want to specify a subtitle, you need to include message, target, volume and title as well. You CANNOT leave out a parameter in the call. Leave as "" if not used/required and default will be invoked. **USER CONFIGURATIONS & SETTINGS** OPTIONS FOR SMART RE-ROUTING OF MESSAGES The following four options can be set to true or false depending on what features you wish to enable. local tts2popup = "true" Set to true to enables re-routing of sonos TTS messages from either the Sonos VD or the sonos-api solution to HC2 notification Popup if the sonos-http-api or Internet is unavailable/offline to your local LAN local tts2queue = "true" Enable to Silence TTS announcement in sleepState, TTS announcements are NOT queued, they are simply discarded local tts2sleep = "true" Enable a Delay before TTS announcements are unloaded (seconds). Leave as "" for no delay local ttsUnloadDelay = "" -- seconds Set to true to enable Sonos TTS messages to queue when presentState = 'Away'. When presentState is set to Home it triggers the scene to automatically unload all the messages in the TTS queue to the default player that has been named in the configuration section local notify2popup = "true" Set to true to enable all notifications to re-route to HC2Popup notifications if the internet is unavailable/offline to your local LAN local notify2queue = "true" Set to true to enable all notifications to queue when presentState= 'Away'. When presentState is set to Home it triggers the scene automatically and unloads the message in the notifications queue to the default notification service that has been named in the configuration section below The scene as provided has all these 4 options set to true and this is the recommended setup if you wish to leverage full functionality and the demo OPTIONS TO MONITOR THE INTERNET STATUS To achieve the most benefit from this scene the internet and sonos-api should be dynamically monitored. Dynamically monitoring the internet will enable messages (TTS and notifications) to be queued while the internet if offline. Queued message can also be sent as hc2 pop notifications on the local LAN. The preferred monitoring option is named here. The example below is setup to use the LAN Monitor VD 2.5 local ipMonitor = "networkTable" There are 3 options available: Select 'manual' if you wish internet and sonos-api to be permanently set to online. Please note that this option does NOT enable queuing of notification messages. Select 'networkTable' to leverage the LAN Monitor VD 2.5, Select 'wwwapiTable' to leverage the new simplified WWWAPI Monitor 1.0 HC2 EMAIL CONFIGURATION hc2emailUsers = {["su"]="2", ["frank"]="1564", ["sylvia"]="1565"} List all users that you want to be able send messages to. The user id's are located from the HC2. Select Configuration, then Access Control to see the current users. HC2 PUSH CONFIGURATION hc2pushUsers = {["DadiPh"]="563", ["MumiPh"]="155", ["DogiPa"]="175"} List all users that you want to be able send push messages to. The mobile devices ID can be found by going to http://<HC_IP>/docs/ and looking under iosDevices section. local defhc2pushUser = "563" -- identify default hc2push user Select a default user from this list and this is used if there is no user specified as part of the message invocation. TTS PREFERENCES Select your TTS preference. If you use the sonos-http-api solution please enter API. If you use the Sonos VD Remote solution please enter REM. local ttsMethod = "API" Default volume for TTS announcements local defTTSvolume = "12" This allows you to select a default volume and this aplies to both the API and REM sonos solutions. This volume can be changed by including a different volume in the message invocation SONOS-API PREFERENCES Configure this section if you have selected API in the above section. APIplayers = {"hallway","kitchen","bed5_office","landing"} List all the sonos players you want to send TTS messages to. The zone/player names must match exactly what is on your sonos native application local defAPIzone = "bed5_office" The default player/zone selected is used to unload the TTS message when presentState = Home. The default player must be included in the overall players list above local APIipaddress = "" local APIport = "5005" The ip address and port are of the device that is hosting the sonos-api local defAPIlanguage = "Amy" The final item here is the language or voice code for the respective TTS service. Thisoculd be something like en-gb for google or Amy for AWS Polly SONOS REMOTE VD PREFERENCES Configure this section if you have selected REM in the above section. REMplayers = { ["kitchen"] = {vd="295", btn="28"}, ["hall"] = {vd="765", btn="27"}, } List all the sonos player virtual devices you want to send TTS messages to. The virtual device id's and process button id’s much match exactly what is on your HC2 for each virtual device. Please note the process button may differ if you have modified the standard virtual device. local defREMvd = "hall" -- Id of player vd for unloading queue The default player/zone is user to unload the TTS message when presentState = Home. This zone must be included in the overall REMplayers table and the name must match exactly. local defREMlanguage = "en-gb" The final item in this section is the language or voice code for the respective TTS service DEFAULT TITLES AND SUBTITLES This scene has default titles and subtitles and these are used if no title or subtitle is included in the message invocation. local defTitle = "Alert Title" local defSubtitle = "Alert Subtitle" Adjust the default titles and subtitles as you require. Note: Subtitles are only used for PopUp Notifications NOTIFICATION SERVICES There is a broad range of notification services available to use. Some are native to the home center and others are third party services provided by external vendors. local defmessageSvc = "pushover" Select the default notification service that you wish to use. This default service will be used if no service is invoked in the message and is also used as the service to unload the queued messages when presentState = Home PUSHOVER CONFIGURATION This service is provided by pushover.org. You will need to register with them and obtain a token and user key. local POtkn = "" local POusr = "" Once registered you will need to select the devices that you wish to send the pushover notifications to. Once they are added to your pushover account you will need to add their details below. Currently there is only one setting for device which means that all messages to pushover will be send to the devices named in this list. Priority can be set at ) like I have below local POdevice = "Dad_Ph, Kit_iPad, Landing iPad" local POpriority = "0" TELEGRAM CONFIGURATION This service is provided by telegram.org. You will need to register with them and obtain a token and a chat ID local TGtoken = "" local TGchatID = "" DEBUG VERBOSITY OPTIONS This allows a number of levels of debug verbosity. There is a minimal amount of debug window responses running in normal mode but these two capabilities allow the user to observe extra information in the debug window when the scene is running. local deBugVar = true -- deBugVar will display the scene variables local deBugCfg = false -- deBugCfg will display the scene configaution that you have set OCCUPANCY/PRESENCE STATE I am also supporting the presentState as it is defined by Sankotronic and others. -- "PresentState" is predefined global value that determines if you are at home -- or away. This variable value is set by other scene or VD. Enter name of your -- global variable between "" if called different or leave as it is local presentState = "PresentState"; -- Enter corresponding values that you use for presence in your language. Change -- the one in quotes or leave as it is local presentStateMapping = {Home="Home", Away="Away"}; HOMETABLE There is also support for the hometable solution. Hometable is a approach to storing all device ID in a global variable. Please Uncomment the following line if you wish to use Hometable data in scene -- local jT = json.decode(fibaro:getGlobalValue("HomeTable")); POPUP MESSAGE TYPES Default popup message type, possible values: Success, Info, Warning, Critical. Please define popup message default popup type, button caption and buttons if you wish These defaults can be left as is or modified/translated into your own language local defPopType = "Info" local defPopCaption = "OK" local defPopButton = { { caption = defPopCaption, sceneId = 0 }} Please refer to Sankotronic Tutorial "Popup Notifications and Custom Images" for format and examples POPUP REDIRECT TITLES AND SUBTITLES Please amend the text sent to PopUp Notification when Internet or TTS is offline to your own language if you wish. Both Title and subtitle can be modified local TTSofflineTitle = "Announcement" local TTSofflineSubtitle = "TTS is offline, TTS announcement sent as popup notification" local WWWofflineSubtitle = "Internet is offline, TTS announcement sent as popup notification" SAMPLE MESSAGE INVOCATIONS The message function can be invoked with as little as one parameter or as many as five parameters. The following examples will provide a good understanding. Send message to default notification service, with default titles/subtitles fibaro:startScene(682, {message}) -- Replace 682 with id of your SMsgH v1.1 scene or a hometable reference Send message to specific notification service (The notification service must match exactly what is contained in the notifySve table in the variables section) fibaro:startScene(682, {message, target}) (The hc2user in the message invocation must match exactly what is contained in the hc2emailUsers table in the user configuration section) fibaro:startScene(682, {message, "hc2email"}) - send to superuser fibaro:startScene(682, {message, "hc2email frank"}) - send to user frank fibaro:startScene(682, {message, "hc2email frank su"}) - send to user frank and superuser (The hc2push device in the message invocation must match exactly what is contained in the hc2emailUsers table in the user configuration section) fibaro:startScene(682, {message, "hc2push DadiPhone"}) - send to superuser fibaro:startScene(682, {message, "hc2push MumiPhone SarahiPhone"}) - send to mumphone and sarah phone (The sonos player name in the message invocation must match exactly what is contained in either the APIplayers or REMplayers table in the user configuration section) The target can also specify sonos player or VD id for TTS with options fibaro:startScene(682, {message, "kitchen"}) -send TTS to kitchen, default volume fibaro:startScene(682, {message, "hallway", "10"}) -send TTS to kicthen, volume=10 Custom titles and subtitles can also be specified. These will overwrite the default titles and subtitles. Subtitles are only available for HC2 Popup notifications. They can be used with or with a target notification. If the target is omitted it will send to the default notification service that has been named in the configuration section local message = "what ever the message is" fibaro:startScene(682, {message, "", "", "Alert !!", "The wine fridge temp is rising"}) Finally an example of a Message to popup with specified popup type local message = "kitchen window has been breached" fibaro:startScene(682, {message, "hc2popup", "", "Alarm", "House Breach", "Critical"}) MESSAGE WITH INTERNATIONAL CHARACTERS If you want to send message with special characters just use urlencode function: fibaro:startScene(682, {"message", "hc2email", "", "title"}) -- without special chars fibaro:startScene(682, {urlencode("message ąść"), "hc2email", "", "title"}) -- with special chars fibaro:startScene(682, {urlencode("message ąść"), "hc2email", "", urlencode("title ČčĆ抚ĐđŽžáäéè")}) -- with special chars COMPANION DEMONSTRATION VD INSTRUCTIONS (1.1) A number of sample notification and TTS messages can be activated giving the user an understanding of the message invocation format and options Demonstration mode enabled the toggling of 'Internet online/offline', presentState Home/Away, sleepState Sleep/Awake modes. This capability allows the used to observe the queuing and unloading of queued notification messages and TTS messages in action. Import the VD into your home center 2. Review the messages and adjust based on your own implementation of Smart Message Hub Send messages and TTS as required To demonstrate the queuing and unload of queue’s Set demo mode to ON. Send messages and TTS and observe in selected notification services and apps, Set internet to offline, sent messages and observe queuing, Set internet to online, observer unloading of queue. Set presetState to Away, send messages and observe queuing. Set presentState to Home and observe unloading of queue. Set sleepState to Sleep and observe TTS are silenced. For normal operation - set Demo mode to OFF FILES [Smart Message Hub SCENE] SMsgH 1.2.lua (lua file) WWWAPI Monitor Virtual Device [VIRTUAL DEVICE] WWWAPI_Monitor_1.0.vfib Companion Virtual Device [VIRTUAL DEVICE] SMsgH_Demo_1.1.vfib
  14. 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.) I'm currently working on a new emulator, TQAE, that I recommend you to check out... It's a rewrite with the learnings I have made coding fibaroapiHC3.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() )
  15. (I'm a n00b. Using a Home Center 2) I have a space where I want any one of three (motion) sensors to be able to switch lights on, and when not more activity has been sense for some time, switch them off. I'd like to extend it such that the lights only come on between sunset and sunrise. I have created 4x scenes, 3x Turn On, 1x Turn Off. The logic I am using is: I created a Global Variable (called LastOnTime) to track the last activation/on time. All of the motion sensors trigger a scene that turn the lights on; and set the LastOnTime to os.time() - I have three copies of that scene. I created one more scene that is triggered off a timer; then if [os.time() - LastOnTime] > 600 turn the lights off. The scripts are below. Questions I have are: is this a good way of doing it? is there a better way? the timer is not working (the scenes are not triggered). I found this 'hack' somewhere in this forum. how do I put something here to check os.time() > [sunset] ? ---------- The On scenes look like: --[[ %% properties 58 value %% weather %% events %% globals --]] local minLight = 100 local motionSensorName = 'F438944-Motion' local motionSensorId = 58 local luxSensorId = 60 fibaro:debug('Lights On - ' .. motionSensorName .. ' (' .. motionSensorId .. ')') local startSource = fibaro:getSourceTrigger() local currentTime = os.time() local deviceStatus = tonumber(fibaro:getValue(motionSensorId, "value")) local currentLux = tonumber(fibaro:getValue(luxSensorId, "value")) fibaro:debug('Device Status: ' .. deviceStatus ) fibaro:debug('currentTime: ' .. currentTime ) fibaro:debug('Lux: ' .. currentLux ) if ( (deviceStatus >= 0) and (currentLux < minLight) ) then fibaro:debug('Turn On Lights') fibaro:call(20, "turnOn") fibaro:call(24, "turnOn") fibaro:debug('Set Global Variable (LightsOnTime) to ' .. currentTime) fibaro:setGlobal("LightsOnTime", currentTime) end fibaro:debug('Complete') The Off script looks like: --[[ %% properties %% events %% globals %% time log *00:01 zoneAlights --]] local currentTime = os.time() fibaro:debug('currentTime: ' .. currentTime ) local lastOnTime = fibaro:getGlobal("LightsOnTime") fibaro:debug('lastOnTime: ' .. lastOnTime ) local delta = tonumber(currentTime) - tonumber(lastOnTime) fibaro:debug('delta: ' .. delta ) if delta > 600 then fibaro:debug('Turn Off Lights') fibaro:call(20, "turnOff") fibaro:call(24, "turnOff") end
  16. 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)
  17. Hi all!! Thank you all for this forum and all nice people that helping eachother out. Now its my turn to ask a question regarding LUA scripting, a script that makes my system to stall within 24h What the script basicaly does is that it checks if doors, windows, motionsencors etc is open or closed and then send it to a QA but also to a global value from a standard LUA scene. I am running the QA on diffrent screens in my home to so i get a nice view of what´s going on. The global value i pick up then i am arming the house and sending it to a a TTS-script. Always nice to hear a voice that tells me that a window is open etc... when i am leaving. But i think something is draining resources, i have tried to only activate the script via Conditions and Triggers, but also via a loop with diffrent sleep times. It does not say in Diagnostics that i am out of recourses se my sample below short version (The script works fine but after aprox 24h HC3 stalls or not working as expected ). How can i do it better ? ::BEGIN:: local var = {}; local debug = 1; ----------------WINDOWS------------ local Windows = ""; local WindowsAlarm = ""; local WindowsLiving = ""; local WindowsLivingAlarm = ""; local WLiving = fibaro.getValue(249, "value"); --...and 6 more sencors ----------------DOORS------------ local Doors = ""; local DoorsAlarm = ""; local Freezer = "" ; local FreezerAlarm = "" ; local DFreezer = fibaro.getValue(355, "value") ; --...and 10 more sencors ----------------MOTION---------- local Motion = ""; local MotionAlarm = ""; local Kitchen = ""; local KitchenAlarm = ""; local MKitchen = fibaro.getValue(21, "value"); --...and 7 more sencors ----------------Switches 1st and 2nd floor---- --...About 30 switches ----------------TEMPS---------------------- --... collecting temps round house ----------------Secure-------------------- local SecureFrontdoor = " " local Parm = " " -- ...Checking if frontdoor is locked and if it is armed etc... ----------------Garage-------------------- -- ... same with garage local Garage = "Garage : " ..IR ..Outlet ..Mainlight ..Port ----------------Setting Variable--------- if WLiving == true then WindowsLiving = "Livingroom" WindowsLivingAlarm = "Vardagsrums fönster, " end; if DFreezer == true then Freezer= "Frys, " FreezerAlarm = "Frysdörr. " end ; if MKitchen == true then Kitchen = "Köket, " KitchenAlarm = "Rörelse i köket, " end; if fibaro.getValue(30, "value") == true then sink = fibaro.getName(30)..", " end; -------------CONSOLIDATE --------------- Windows = "Fönster: " ..WindowsLiving .." " .. Bathroom; -- for screens QA var.WindowsAlarm = WindowsLivingAlarm ..BathroomAlarm; Doors = "Dörrar: " ..Refrigerator .." "..StoreTrash ; -- for screens QA var.DoorsAlarm = RefrigeratorAlarm ..StoreTrashAlarm ; Motion = "Rörelse:" ..Kitchen .." "..Shower ; -- for screens QA var.MotionAlarm = KitchenAlarm ..ShowerAlarm ; -- .. and some more... -------------SEND UPDATES---------------------------------------------------------------------- fibaro.call(103,"updateView","windows","text", Windows); fibaro.call(103,"updateView","doors","text", Doors) fibaro.call(103,"updateView","detectors","text", Motion); fibaro.call(103,"updateView","avgtemp","text", avgtemp) ; fibaro.call(103,"updateView","secure","text", SecureFrontdoor .." " ..Parm ); fibaro.call(103,"updateView","garage","text", Garage) ; fibaro.call(103,"updateView","first","text",first) ; fibaro.call(103,"updateView","second","text",second) ; fibaro.setGlobalVariable('Status',json.encode(var)) -------------DEBUG-------------- ------Loop Me ------------------ fibaro.sleep(5*1000); goto BEGIN
  18. Hallo Ich habe versucht, eine verschachtelte Tabelle zu sortieren und zu drucken. Leider bekomme ich einen Tisch zurück aber mit json nicht darstellen. Ich bitte um Hilfe.
  19. Hi, I have been working with the pushover service recently as an alternative the native notification service within the HC2. I think it is worth exploring if you are looking for another option. Since it is fresh in my mind I thought I'd document it and share to hopefully help others This draws on previous work from @SDeath and @sj3fk3 and others so all credit goes to them. STEP 1 – SIGN UP AND GET USER KEY 1. Sign up at pushover.net, usual stuff. You can use a trial account for 7 days and after that you'll need to purchase a license per platform (ie iOS, Android, etc) irrespective of how many devices you have with each platform. The licenses per platform are approx €5 each so they shouldn't break the bank 2. Open confirmation email and verify account 3. Log back into pushover and make note of your User Key which will be something like ubp44xxxxxxxxxxxxxx8497aihkq and this is your User Key 4. Copy this out as you will need this in the scenes in HC2 Note: There is also a pushover email address under your user key should you need this for another project but you don't need it for what we are doing here STEP 2 - REGISTER YOU APPLICATION 1. Scroll down to the bottom of the dashboard and click (Register Application/Create an API Token) 2. Give it a Name (we call our HC2 domino so I named it domino) This will appear in your client device where you receive your messages 3. Type = Application 4. Description/URL and icon all optional. (I added an icon as it appears on the alerts that you receive on your client devices (72px x 72px, png) and attached is the one I used) 5. Check the box and Click Create Application 6. This is the second Token Key, it’s something like aphmpbezxxxxxxxxxerqjwsg. Copy is out as you will need this in the scenes in HC2 STEP 3 – ADD CLIENT DEVICES (TO RECEIVE ALERTS ON ) 1. Android/iOS - Download the app from the appropriate store playstore or appstore 2. Log in to the app using your username and password that you got when you opened your pushover.net account 3. Give your device a name and click Register Device (I think it's better to avoid spaces and special characters if possible) 4. Go back to pushover.com and on your dashboard you'll see this new device added with the name you gave it. (Clicking the Pushover icon on the top left gets you back to your dashboard should you navigate off to another page) Repeat all part of STEP 3 for all other client devices. If you have multiple you'll end up with something like following You will see an Alert in your pushover app for each device that is added Within the pushover dashboard you can set up quiet times, groups and aliases but you don't need any of this to get started. STEP 4 – HC2 SETUP 1. Create a variable called pushoverBody in the top part of the variables panel 2. Create a new scene called pushoverSend and copy the following code into it ( this is the 'engine' that will call the pushover api and send the alert) 3. You will need to add your own user key and token key to line 14 -- SCENE THAT SAVES THE DATA TO THE GLOBAL VARIABLE 'pushoverBody' AND SENDS TO API --[[ %% events %% properties %% globals pushoverBody --]] -- Stops the scene if gv not populated if (tonumber(fibaro:getGlobalValue("pushoverBody")) == 0) then fibaro:abort(); end local selfhttp = net.HTTPClient({timeout=2000}) local tkn, usr = "a51eryn9t2qcg5bvoubzhqs29z2yc6", "u2n4tb99eckm6qw3hz365ts9r5z6r8" local msg = fibaro:getGlobalValue("pushoverBody") local requestBody = 'token=' ..tkn ..'&user=' ..usr ..msg selfhttp:request('https://api.pushover.net/1/messages.json', { options={ headers = selfhttp.controlHeaders, data = requestBody, method = 'POST', timeout = 5000 }, success = function(status) local result = json.decode(status.data); if result.status == 1 then fibaro:debug("Success: " ..result.request); else fibaro:debug("Failed: " ..status.data); end end, error = function(error) fibaro:debug("Success: " ..error); end }) --Reset the gv to 0 for next message fibaro:setGlobal("pushoverBody", "0") 4. Create another scene and call the pushover Test 5. Copy the following code to run a test (Change line 11 & 12 to the names of your device(s) that you wish to send the alert to. I have included 2 devices on my sample code) Change the Alert/Message Text as required -- CODE THAT SENDS THE DATA TO 'pushoverBody' GLOBAL VARIABLE -- THIS IS THE PART THAT YOU INCLUDE IN A SCENE TO SEND THE ALERT --[[ %% events %% properties %% globals pushoverBody --]] local dvc, prio = "Dad_Phone,Kitchen_iPad", "0" local ttl, msg = "Home Alert! - Panic", "Panic activated from Home." local requestBody = '&device='..dvc ..'&priority=' ..prio ..'&title=' ..ttl ..'&message=' ..msg fibaro:setGlobal("pushoverBody", requestBody) 6. Confirm that you should see an alert on the devices that you specified This is the code that you can put into any scene that you wish to send an alert from, making the necessary adjustments to receiving devices, message and priority should you wish Full details of the API can be found at https://pushover.net/api After 7 days it will stop working and you will need to purchase the required licenses at ~ €5 each .. and that it !! -f
  20. Version 1.1.0


    Hello Everyone, I 've tried Konnected alarm panel in parallel with my old alarm system, and it is working great. (Konnected) My task that was assigned to myself was to integrate Konnected directly to my HC2. So with a little LUA magic we have ready the Konnected Virtual Device for HC2. You can find the Virtual Device Repository here. Enjoy!
  21. Hi I have to understand the Quick app HC2 code to make the same app to HC3. This Quick App control Multiroom AMCP MR4.50-XT - 4 Zones with Itach RS232 Serial Interface. I do not understand where in the LUA Code call function like above: local ID_VD = fibaro:getSelfId() fibaro:call(ID_VD, "pressButton", "6") fibaro:sleep(600) fibaro:call(ID_VD, "pressButton", "16") fibaro:sleep(600) fibaro:call(ID_VD, "pressButton", "26") fibaro:sleep(600) fibaro:call(ID_VD, "pressButton", "36") fibaro:sleep(300) Where I need to looking for some information about this code? MULTIROOM.vfib
  22. Hi. I'm an experienced programmer, but a novice in LUA. 1. I have some qubino smart meters, and would like (of course) to read all the parameters they can provide. It seems to me that every single parameter in them get an ID in HC2. When I want one of the values, i use fibaro:getValue(63,'value'); But: For some of the parameters there are no ID's! So how can I get their values? Examples of missing parameters are 143: Reactive power total and 144: Power factor total How can I get to those? 2. Is there a way to get parameters based on the device parameter numbers? I'd like to use some function v=fibaro:getParameter(main id,parameter number); Is this possible? 3. Where can I find a list of legal parameter values to the getValue call? Helgemor
  23. Hello Forum members, I am a Newbie on Fibaro HC2 / LUA and struggling with my next project: I have a Hydrawise Irrigation Controller (sister company of Hunter). This controller is already smart and adjusting the irrigation schedule based on weather data via WUnderground. My plan is to track the status of each zone in HC2 and switch the pump (wall plug) on and off. API key is available and the connection is working on browser and in LUA code. I can run and stop specific irrigation zones via code but I do not know how to get the datastring into HC2 variables. start relay 485761 / zone 3 for 600 seconds: local http = net.HTTPClient() http:request('https://api.hydrawise.com/api/v1/setzone.php?action=run&api_key=XXXXXX&period_id=999&relay_id=485761&custom=600') stop same relay: http:request('https://api.hydrawise.com/api/v1/setzone.php?action=stop&api_key=XXXXXXX&relay_id=485761') Both is working and I can see the effect on the Hydrawise controller. code for the statusschedule: https://api.hydrawise.com/api/v1/statusschedule.php?api_key=XXXXXXXXX I receive following string in the browser: {"time":1613911956,"nextpoll":60,"message":"","simRelays":1,"options":17,"master":12,"master_timer":0,"master_post_timer":0,"expanders":[],"sensors":[{"input":0,"type":1,"mode":1,"timer":0,"offtimer":0, "relays":[{"id":485761},{"id":488979},{"id":488980},{"id":488981}]}], "relays":[{"relay_id":488979,"time":1576800000,"type":110,"run":0,"relay":1,"name":"Rasen Terrasse","period":259200,"timestr":""}, {"relay_id":488980,"time":1576800000,"type":110,"run":0,"relay":2,"name":"Beete Eingang","period":259200,"timestr":""}, {"relay_id":485761,"time":1576800000,"type":110,"run":0,"relay":3,"name":"Rasen Erker","period":259200,"timestr":""}, {"relay_id":488981,"time":1576800000,"type":110,"run":0,"relay":4,"name":"Hochbeet","period":259200,"timestr":""}] Hopefully somebody can support in this topic. Hydrawise REST API.pdf
  24. Möchte gerne, wenn ich den KeyFob Taste 1 drücke das, eine Push Nachricht geschickt wird, wenn das Garagentor offen ist. Und wenn ich wieder drücke , das eine Push Nachricht geschickt wird, wenn das Garagentor geschlossen ist. Kann mir jemand dabei helfen ? LUA ist für mich sehr neu. Vielen Dank für eure Hilfe. Trigger: { conditions = { { id = 97, isTrigger = true, operator = „==“, property = „centralSceneEvent“, type = „device“, value = { keyAttribute = „Pressed“, keyId = 1 } }, { id = 100, isTrigger = true, operator = „==“, property = „value“, type = „device“, value = true }, { id = 100, isTrigger = true, operator = „==“, property = „value“, type = „device“, value = false } }, operator = „all“ } AKTION: local Taste = json.encode(sourceTrigger.value.keyId) – Betätigte Taste local Aktion = json.encode(sourceTrigger.value.keyAttribute) – Anzahl Betätigungen if Taste == „1“ and Aktion == ‚„Pressed“‘ then fibaro.call(90, ‚toggle‘) print(„Garagentor“) end fibaro.alert(‚simplePush‘, {[1] = 98, }, 'Garagentor ist offen’false) print(„Garagentor ist offen“) end fibaro.alert(‚simplePush‘, {[1] = 98, }, ‚Garagentor ist geschlossen‘, false) print(„Garagentor ist geschlossen“) end
  25. 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
  • Create New...