Welcome to Smart Home Forum by FIBARO
Dear Guest,
as you can notice parts of Smart Home Forum by FIBARO is not available for you. You have to register in order to view all content and post in our community. Don't worry! Registration is a simple free process that requires minimal information for you to sign up. Become a part of of Smart Home Forum by FIBARO by creating an account.
As a member you can:
- Start new topics and reply to others
- Follow topics and users to get email updates
- Get your own profile page and make new friends
- Send personal messages
- ... and learn a lot about our system!
Regards,
Smart Home Forum by FIBARO Team
Search the Community
Showing results for tags 'development'.
-
This setup is designed for QA development using Visual Studio Code (VSCode). It includes an emulator, allowing you to run and debug QAs directly in VSCode. This setup is compatible with HC3, offering features such as code completion, syntax highlighting, and workflow tasks for downloading, editing, packaging, and uploading QAs to/from HC3. Tested on Windows 11 and MacOS, this setup should also work on Linux. You can download the repository from here. Documentation, still in progress, is available here. Additionally, there's a video tutorial on installing this setup on Windows 11. The setup in VSCode looks as shown in the image. This configuration allows you to develop and run a QuickApp (QA) offline on your PC, Mac, or Linux system, and interact with the HC3 in a controlled manner. There's also a simple Web user interface for interacting with the QAs and monitoring events (available at http://127.0.0.1:5004/frontend) To get started: Install Python 3 on your machine. NOTE! Only Python v3.11 and 3.12 is supported. in settings.json set "fibpython":".venv/bin/python", fibpython should point to your executable python. In the example it points to a python venv in the workspace, but it could point anywhere you have installed python. There is a settings.templ provided as a base for your own settings.json (should be in the .vscode directory) To test if the installation is ok , in the vscode terminal window, type what you set the fibpython path to. ex: .venv/bin/python and see if it works. Install the required Python libraries from requirements.txt using >pip install -r requirements.txt. Make sure they install for the python interpreter that is pointed out by fibpython. Create a config.json file with credentials to access the HC3, based on the config.json.example. Install the VSCode extension "Local Lua Debugger" by Tom Blind. Create a QA file in the directory, choose the launcher "Fibenv QA file (remote)," and start debugging with F5. For more examples, refer to the files in the examples/ directory. The included .gitignore file excludes the ./dev and ./test subdirectories, allowing you to test your own code without affecting the rest of the repository. For installing Python libraries, it's recommended to create a virtual environment in the folder first. This setup includes a Python wrapper for the Lua runtime (Lupa), addressing dependencies on luasocket and others, eliminating the need for Lua installation on your machine. To instruct the emulator about the type of QA, directives similar to TQAE can be used in the QA file, but with slight differences, as shown in the example. Ex. --%%name=MyQA --%%type=com.fibaro.binarySwitch --%%file=qa3_1.lua,extra; --%%remote=devices:788,790 --%%remote=globalVariables:myVar,anotherVar --%%debug=libraryfiles:false,userfilefiles:false function QuickApp:onInit() self:debug(self.name,self.type,self.id) fibaro.call(788,"turnOn") end Note the --%%remote directive It instructs the emulator that it's ok to call device 788,789 o the HC3. As a default, the emulator treats all resources as local (we can read from HC3 but then treat them as local copies) and we enable resources we want to interact with on the HC3 as 'remote'. This goes for other resources also like 'globalVariables'. The setup integrates with the Lua debugger, allowing for breakpoint setting and more. Note that this project is still in progress, and updates will be provided as improvements are made. The emulator UI can be accessed at http://127.0.0.1:5004/, with a Swagger page for implemented APIs at http://127.0.0.1:5004/docs. The port (5004) can be changed as needed. Supported APIs include various fibaro and net functions, along with api calls and plugin functions. The setup also includes classes for QuickApp development and management. Supported APIs fibaro.debug(tag,str) fibaro.warning(tag,str) fibaro.trace(tag,str) fibaro.error(tag,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) ...and corresponding hub.* functions net.HTTPClient() net.TCPSocket() net.UDPSocket() net.WebSocketClient() net.WebSocketClientTLS() --mqtt.Client.connect(uri, options) --no yet --<mqttclient>:addEventListener(message,handler) --no yet --<mqttclient>:subscribe(topic, options) --no yet --<mqttclient>:unsubscribe(topics, options) --no yet --<mqttclient>:publish(topic, payload, options) --no yet --<mqttclient>::disconnect(options) --no yet 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) --not yet plugin.restart(deviceId) plugin.getProperty(id,prop) plugin.getChildDevices(id) plugin.createChildDevice(prop) class QuickAppBase class QuickApp class QuickAppChild class RefreshStateSubscriber class <name> property(get,set) 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:removeChildDevice(id) QuickApp - self:initChildDevices(table) QuickApp - self:isTypeOf(typ) QuickApp - self:callAction(name, ...) QuickApp - self:setName(name) QuickApp - self:setEnabled(bool) QuickApp - self:setVisible(bool) getHierarchy() For your own QA development have the repo 'fibemu' downloaded in a separate directory. Then create your own vscode development directory, and initialise that as a git repo if you want. With that open, do File->Add Folder to Workspace, and add the fibemu folder. This is what Vscode calls a "multi-root" workspace and it. Create a lua (QuickApp file) in your directory. First line in your QuickApp file should be the offset to your directory --%%root=../<name of your dir>/ So if you have a multi-root workspace now that looks like o fibemu o myDirectory You set the root to ../myDirectory/ Then press F5 to start to debug. The launch commands and other will be taken from the fibemu folder. This way you can pull down new version of fibemu without messing up your own directory and development. Also, don't forget to setup your config.json with credentials (copy from fibemu/config.json.example) Here is a link to the multi-project setup instructions (may include a video in the future) Implementation Some implementation notes. Supported REST APIs. Workflow There are some defined vscode Tasks that help in remotely uploading and updating the QA on the HC3 from within the vscode environment "QA, download fqa" downloads an QA from the HC3 and saves it as a .fqa file. The task will prompt for deviceID and path where to store. The path/dir needs to exist "QA, download and unpack" downloads an QA from the HC3 and saves all QA files as .lua files. It also adds fibemu headers in the main file so it can be opened and run with the emulator . The task will prompt for deviceId and path where to store. The path/dir needs to exist "QA, upload" will upload the QA to the HC3. It will prompt for QA file. If '.' is given as argument it will upload the current opened file. This will create a new QA, with a new deviceId on the HC3. "QA, update" will try to update QA files, viewLayout, uiCallbacks, and quickAppVariables of an existing QA on the HC3. If '.' is given as argument the file must have set the fibemu header --%%id=<ID> so it knows what QA to update. One can also give the deviceId of the QA on the HC3 that should be updated. This is convenient when developing and avoiding new IDs being "consumed". Sometimes when you update a QA you would not like to update the quickAppVariables. In that case give '-' instead '.' for the current opened file, or -deviceId for an exiting QA on the HC3. Scripts An advantage with the emulator is that we have access to more lua functions than on the HC3 which allow us to write some maintenance scripts QA backup. Backs up QAs from the HC3 to a local directory, keeping the 3 last versions QA distribution. Packs a development file to a .fqa, initialises some quickAppVariables, adds readme.txt file and zips it to an archive. Known issues While the QA is running, break-points can't be added. This is a limitation of the debugger used. Just add the break-point and restart the QA. When the emulator crashes, it may leave a process open that keeps the port 5004 in use. The emulator will complain at restart that the port is already bound. You may need to manually kill the process. On Mac: >kill -9 $(lsof -ti:5004)
- 362 replies
-
- 7
-
- visual studio code
- quickapp
-
(and 3 more)
Tagged with:
-
Note. The first ~2000 posts of this thread is mainly about EventRunner3 that is for the HC2. EventRunner3 is not developed further, but bugs are fixed as they are reported. For HC3, the version is EventRunner4, and is a QuickApp,. Here is a post introducing EventRunner4. Its EventRunner5, link <here> Most of the 'Event Script" syntax and commands are still valid and old posts can be of use for new HC3 owners. Link to EventRunner3.lua for the HC2 There is a QA that is used to download and install the EventRunner4 QA to your HC3 (and update to new versions) Here is an example of how to code in a "single instance / event" style. A style I'm using today for all of my scenes. The idea is that instead of having to deal with a new instance being spawned with every scene trigger, all triggers are dealt with from within a single scene instance that is continuously running. It becomes something close to a traditional event loop model found in most modern GUI frameworks. The advantages with coding scenes in this style are: Scene can keep state in local lua variables between scene invocations/triggers Easy to keep different rules/logic in the same scene without causing conflicts, e.g. combining continuous running loops/schedules with immediate reaction on incoming triggers Easy to distribute different rules/logic between different scenes and allow them to communicate Easy to schedule actions to do in the future - that can be easily cancelled if new information is gained. Because the scene is continuously running it doesn't matter if there is a heavy initialisation when the scene starts up (parsing HomeTables etc.) as it is only done once... The framework has extensive support to run and debug the scene offline on a PC/Mac to get things right before deploying the scene on the HC2 (uses HC2 emulator). Offline it is easy to simulate trigger/events to understand if the logic is correct, something that is not always easy to detect in a asynchronous environment. It has publish/subscribe mechanism allowing scenes to exchange events without having to know each other's names or IDs or rely on global variables. It has proven to be easy to integrate with external event/msg based systems like Node-red, where scenes can both send and receive events to node-red and thus extend functionality with Alexa, Google home, Hue etc etc. The framework is available in two version, a 'light' version and a full blow version with a lot of bells and whistles. The latter also supports writing rules in EventScript, a "simple", but very flexible and efficient approach to writing rules that need to trigger things at various times of the day, or trigger on sensors or switches changing states. The implementation of EventScript is built on-top of the single instance framework and the event model and would have been impossible to do in a traditional scene model. Ex of EventScript rules. --[[ %% properties 54 value 55 value 56 value 57 value 66 value 77 value 78 sceneActivation 88 ui.Slider1.value 88 ui.Label1.value %% events 100 CentralSceneEvent 120 AccessControlEvent %% globals Home %% autostart --]] myLightSensor1 = 54 -- do not declare local, script will not find them(!) myLightSensor2 = 55 myMotionSensor1 = 56 myMotionSensor2 = 57 myLight1 = 66 myLight2 = 67 myDoorSensor = 77 mySwitch = 78 myVD=88 myKeyFob = 100 myLock = 120 function main() -- Trigger rules Rule.eval("myLightSensor1:lux > 200 => myLight1:on") -- Turn on light1 if lux value goes above 200 Rule.eval("myLight1:isOn => myLight2:on") -- Turn on light2 if light1 is turned on Rule.eval("myDoorSensor:breached => myLight1:on") -- Turn on light1 if door sensor is breached Rule.eval("mySwitch:scene == S2.click => myLight1:on") -- Turn on light1 if S2 is clicked once Rule.eval("slider(myVD,'Slider1') == 50 => myLight1:on") -- Turn on light1 if slider is set to 50 Rule.eval("label(myVD,'Label1') == 'ON' => myLight1:on") -- Turn on light1 if label is set to 'ON' Rule.eval("myKeyFob:central.keyId==4 => myLight1:on") -- Turn on light1 if key 4 is pressed on keyFob Rule.eval("myLock:access.status=='Unlock' => log('Door unlocked by %s',myLock:access.name)") -- Door unlocked Rule.eval("$Home == 'AWAY' => myLight1:on") -- Turn on light1 if fibaro global variable 'Home' is set to 'AWAY' Rule.eval("#AccessControlEvent{data={name='$name',slotId='$slot',status='Unlock',id=myLock}} => log('Door unlocked by %s',name)") -- more rules -- Turn on lamp at 15min before sunset Rule.eval("@sunset-00:15 => myLight1:on") -- Turn on 2 lamps 15min past sunrise on weekdays Rule.eval("@sunrise+00:15 & wday('mon-fri') => {myLight1,myLight2}:on") -- Turn on lamp if sensor breached Rule.eval("myMotionSensor1:breached => myLight1:on") -- Turn off lamp if sensor safe for 5min Rule.eval("trueFor(00:05,myMotionSensor1:safe) => myLight1:off") -- Turn on lamp if doubleclick on switch S2 Rule.eval("mySwitch:scene==S2.double => myLight1:on") -- Toggle lamp if key '1' pressed on keyfob Rule.eval("myKeyfob:central.keyId=='1' => myLight1:toggle") -- Turn on lamp if average lux is less than 200 Rule.eval("sum({myLightSensor1,myLightSensor2}:lux)/2<200 => myLight1:on") -- Turn on lamp if any of motion sensor myMotionSensor1,myMotionSensor2 are breached Rule.eval("{myMotionSensor1,myMotionSensor2}:breached => lamp:on") -- ..and turn off lamp all motion sensors are safe for 10min Rule.eval("trueFor(00:10,{myMotionSensor1,myMotionSensor2}:safe) => lamp:off") -- Turn on lamp if any of motion sensor myMotionSensor1,myMotionSensor2 is breached -- but not if it's daytime, and only at dimmed level during night Rule.eval([[{myMotionSensor1,myMotionSensor2}:breached => || 24:00..sunrise >> myLight1:value=30 || sunset-00:30..24:00 >> myLight1:on ]]) end More on EventScript and the full blown version is available in the posts listed below: Here is a post on setting up the framework (works for EventRunnerLite too) Here is a post on the EventRunnerLite version - a bare bone version of the framework Here is a post on writing schedulers using EventScript. Here is a post on writing trigger rules using EventScript. Here is a post on EventScript syntax and rules (here is a new version under development) Here is a post on writing Lua event handlers Here is a post on debugging the framework Here is a post on the publish/subscribe mechanism Here is a post on enabling Hue support - mapping of Hue devices to standards z-wave/fibaro:* calls Here is a post on integrating the event model with Node-red - sending/receiving events from node-red, with extendable, example flow. Gives support for Sonos TTS and Alexa input...Updated flow <here>. (and here is another thread, 1,2,.) Here is a thread on the HC2 emulator used to debug EventRunner offline Here is a post on creating VDs from an ER scene and handle the VD logic with EventScript rules (and a calculator example) There will also be some services based on the EventFramework posted iOSLocator - a service that checks with iClod for people at places and sends events to other EventFramework services iCalendar - a service that fetches evens from Apple's iCloud calendar or Google calendar and post them to scenes. (latest iCalendar) Logger service - part of Supervisor Alarm service - TBD CronRunner - a UNIX like crontab service other scenes can register call-backs with Supervisor - A scene that pings EventRunner scenes and makes sure they stay alive. Best practices rules - TBD Implementation notes Notes on the basic EventRunner framework Notes on the EventScript implementation - TBD ChangeLog for the EventRunner framework. The lastest version of the code is kept in my GitHub. The background of this framework and a thread discussing it can be found here, however the code has evolved a bit from when originally posted there. If you are new to EventRunner I don't encourage you to read the posts in the thread chronological, as it contains a lot of outdated information. Instead, the best way to get an understanding of the capabilities of EventRunner is to browse the links in the list above.
- 4,679 replies
-
- 11
-
- events
- rule engine
- (and 8 more)
-
fibaroapiHC3.lua Note, I currently only support my new emulator, TQAE, and have moved all my development to that - please check it out... It's a rewrite with the learnings I have made coding fibaroapiHC3.lua... (Note: The new version of the emulator has gone through extensive rewrite and is stabilising (0.300). The old version of the emulator is here fibaroapiHC3_classic.lua.) This is a thread for the fibaroapiHC3.lua sdk that is under development (keeping it separate from the HC3 QuickApps coding - tips and tricks thread) I've started to run and test HC3 QuickApps offline and have made a fibaroapi.lua file that can be included to emulate the fibaro calls and call out to the HC3. This means that a whole QA can be developed offline, debugged and verified before deploying to the HC3. Something that significantly reduces the development process. It's an emulation so it's not 100% but it will cater for 99.99% of the needs to catch bugs, get decent error messages when things doesn't work (like timers). Be able to set breakpoints and inspect states etc. It's complete enough to run the most demanding QuickApps that I have found on the forum so far... If it runs in the emulator and it doesn't run on the HC3 or vice versa I will prioritise to fix it. Latest version here fibaroapiHC3.lua (v0.311) The code is updated weekly so please make sure you have the latest... It was inspired by the old fibaroapi for the HC2 in a thread started by @riemers but has evolved with more extensive support to create a better debugging and "offline experience"... in fact, it's really an HC3 emulator now. The video is an earlier version of the emulator but the principles are more or less the same. Note the nice tooltip and autocompletion of fibaro commands we get with the fibaroapiHC3plugin for ZBS. Enable English subtitles to see instructions... Some benefits: Use a modern development environment such as ZeroBrane Studio (free for Mac/PC/Linux, HC3 plugin here) on your laptop/PC to develop and debug QuickApps and Scenes. Here is a good introduction to Lua (using ZeroBrane) Step through code, inspect Lua variables, set break-points etc - all that is possible in a good IDE. Faster to pin-point errors as the error messages are better than on the HC3 - stack-traces etc. Advanced timer info (setTimeout) warning of late timers and from where the offending function was called if a timer function crashes. Info from where an eronous json.encode was called from in your code so you can easily find the error (instead of seeing a line from deep inside the json encoder) Use the whole Fibaro API fibaro.call etc and net.HTTPClient(), setTimeout(), json.ecode/decode, QuickApp self:functions like self:getVariable, self:updateView Support for MQTT client and QuickApp child devices Both QuickApps and Scenes are supported. Scenes support most conditions and are triggered by real triggers from the HC3 or simulated triggers. Speed up clock to run faster than real time, to watch a Scene or QuickApp over days/weeks/months in seconds. Start at any given time and date - test if your scene behaves on week-ends ? Automatically create a proxy QuickApp on the HC3 that sends UI clicks back to the code your are running and displays self:updateView updates. This way you can test the QuickApp UI (buttons etc) and still debug the main code on your PC. Develop and run multi-file QuickApps, allowing you to build up a library of common code to share between your QAs. Run completely disconnected from the HC3 simulating devices and other resources (now you can take your coding with you on your vacation ) There is a possibility to download resource definitions from the HC3 and use them (devices, globals etc) while running disconnected. Load multiple QAs/Scenes into the emulator at the same time to debug interaction patterns between QAs (or just run all your QAs offline and use the HC3 as a wave GW ) Telnet into the running emulator to capture logs or issue Lua commands like turning on/off devices at runtime to test you QA/Scene. Move the code as-is over to the HC3 when it runs in the emulator - and it will most likely run on the HC3. Scenes needs to be moved to conditions/actions part on the HC3 - may automat that in the future. Oh, and an emulated Web GUI for the quickApp so you can try out button/slider clicks without connecting to the HC3. And lastly, it makes it fun to develop code for the HC3 To get going download the fibaroapiHC3.lua and put in in the working directory where you code your QA(s) If you run ZerobraneStudio (recommended) paste this and run if dofile and not hc3_emulator then dofile("fibaroapiHC3.lua") end--hc3 hc3_emulator.downloadPlugin() hc3_emulator.downloadAssets() Please note the 'end--hc3' that ends the 'if dofile and not hc3_emulator then' statement. It requires the '--end' comment so I can recognise it. Also, you need to set the Lua interpreter to version 5.3 (In ZBS, Menu ; Project -> Lua Interpreter -> Lua 5.3) It will install the. ZBS plugin in ~/.zbstudio/packages and some code templates in ~/.zbstudio/hc3emu/ (Restart ZBS for the plugin to. be installed) Create a Lua file and create a header + QA/scene code. An example of a minimal QA can look like if dofile and not hc3_emulator then hc3_emulator = { name = "My QA", poll=1000, -- Poll for triggers from the HC3 every 1s credentials = {ip="192.168.1.X", user="<user>", pwd="<password>"} } dofile("fibaroapiHC3.lua") end--hc3 function QuickApp:onInit() fibaro.call(88,"turnOn") -- turns on device 88 on your HC3 end We wrap the emulator specific stuff inside "if dofile and not hc3_emulator then .... end" as the symbol 'dofile' is not defined on the HC3 and will thus be false and not include the code - This means that we can take the code as-is and paste it into the HC3 and it works. Note the credentials that contains the IP, username and password so that the emulator can access the HC3 box. If you use ZBS and the plugin there is an Edit-HC3 SDK templates-> menu that will insert a standard QA and Scene header + code in the current buffer. Most of the functions are there and will be improved over time. There are support for net.HTTPClient() and setTimeout/clearTimeout and api.* There are support for getting triggers and events from the HC3 Support for auto-creating a QuickApp proxy with UI elements that sends events back to the code being debugged. There are support for both QuickApps and Scenes (with conditions) Currently supported (v 0.300) fibaro.debug(type,str) fibaro.warning(type,str) fibaro.trace(type,str) fibaro.error(type,str) fibaro.call(deviceID, actionName, ...) fibaro.getType(deviceID) fibaro.getValue(deviceID, propertyName) fibaro.getName(deviceID) fibaro.get(deviceID,propertyName) fibaro.getGlobalVariable(varName) fibaro.setGlobalVariable(varName ,value) fibaro.getRoomName(roomID) fibaro.getRoomID(deviceID) fibaro.getRoomNameByDeviceID(deviceID) fibaro.getSectionID(deviceID) fibaro.getIds(devices) fibaro.getAllDeviceIds() fibaro.getDevicesID(filter) fibaro.scene(action, sceneIDs) fibaro.profile(profile_id, action) fibaro.callGroupAction(action,args) fibaro.alert(alert_type, user_ids, notification_content) fibaro.alarm(partition_id, action) fibaro.setTimeout(ms, func) fibaro.clearTimeout(ref) fibaro.setInterval(ms, func) fibaro.clearInterval(ref) fibaro.emitCustomEvent(name) fibaro.wakeUpDeadDevice(deviceID) fibaro.sleep(ms) net.HTTPClient() net.TCPSocket() net.UDPSocket() net.WebSocketClient() -- needs extra download net.WebSocketClientTLS() -- needs extra download api.get(call) api.put(call <, data>) api.post(call <, data>) api.delete(call <, data>) setTimeout(func, ms) clearTimeout(ref) setInterval(func, ms) clearInterval(ref) mqtt.Client.connect(uri, options) -- needs extra download <mqttclient>:addEventListener(message,handler) <mqttclient>:subscribe(topic, options) <mqttclient>:unsubscribe(topics, options) <mqttclient>:publish(topic, payload, options) <mqttclient>::disconnect(options) plugin.mainDeviceId plugin.deleteDevice(deviceId) plugin.restart(deviceId) plugin.getProperty(id,prop) plugin.getChildDevices(id) plugin.createChildDevice(prop) class QuickAppBase class QuickApp class QuickAppChild json.encode(expr) json.decode(string) QuickApp:onInit() -- called at startup if defined QuickApp - self:setVariable(name,value) QuickApp - self:getVariable(name) QuickApp - self:debug(...) QuickApp - self:updateView(elm,type,value) QuickApp - self:updateProperty() QuickApp - self:createChildDevice(props,device) QuickApp - self:initChildDevices(table) sourceTrigger - scene trigger Supported scene events: {type='alarm', id=<id>, property='armed', value=<value>} {type='alarm', id=<id>, property='breached', value=<value>} {type='alarm', property='homeArmed', value=<value>} {type='alarm', property='homeBreached', value=<value>} {type='weather', property=<prop>, value=<value>, old=<value>} {type='global-variable', property=<name>, value=<value>, old=<value>} {type='device', id=<id>, property=<property>, value=<value>, old=<value>} {type='device', id=<id>, property='centralSceneEvent', value={keyId=<value>, keyAttribute=<value>}} {type='device', id=<id>, property='accessControlEvent', value=<value>} {type='device', id=<id>, property='sceneActivationEvent', value=<value>} {type='profile', property='activeProfile', value=<value>, old=<value>} {type='location', id=<uid>,property=<locationId>, value=<geofenceAction>, timestamp=<timestamp>} {type='custom-event', name=<name>} {type='UpdateReadyEvent', value=_} {type='onlineEvent', value=<bool>} Some of the parameters that affect the behaviour of the emulator and can be set in the header are: hc3_emulator.name=<string> -- Name of QuickApp, default "QuickApp" hc3_emulator.id=<QuickApp ID> -- ID of QuickApp. Normally let emulator asign ID. (usually 999 for non-proxy QA) hc3_emulator.poll=<poll interval> -- Time in ms to poll the HC3 for triggers. default false hc3_emulator.type=<type> -- default "com.fibaro.binarySwitch" hc3_emulator.speed=<speedtime> -- If not false, time in hours the emulator should speed. default false hc3_emulator.proxy=<boolean> -- If true create HC3 procy. default false hc3_emulator.UI=<UI table> -- Table defining buttons/sliders/labels. default {} hc3_emulator.quickVars=<table> -- Table with values to assign quickAppVariables. default {}, hc3_emulator.offline=<boolean> -- If true run offline with simulated devices. default false hc3_emulator.autocreate=<boolean> -- Autocreate local resources hc3_emulator.apiHTTPS=<boolean> -- If true use https to call HC3 REST apis. default false hc3_emulator.deploy=<boolean>, -- If true deploy code to HC3 instead of running it. default false hc3_emulator.assetDirectory=<string> -- Directory where assets shoud be downloaded (ZBS). Default ~/.zbstudio/hc3emu hc3_emulator.resourceFile=<string> -- When doing a resource download, use this file as default. hc3_emulator.db=<boolean/string>, -- If true load a "resource download" from hc3_emulator.resourceFile or string hc3_emulator.htmlDebug=<boolean> -- Try to convert html tags to ZBS console cmds (i.e. colors) hc3_emulator.terminalPort=<boolean> -- Port used for socket/telnet interface hc3_emulator.webPort=<number> -- Port used for web UI and events from HC3 hc3_emulator.HC3_logmessages=<boolean> -- Defult false. If true will push log messages to the HC3 also. hc3_emulator.supressTrigger -- Make the emulator ignore certain events from the HC3, like = PluginChangedViewEvent hc3_emulator.negativeTimeout=<boolean> -- Allow specification of negative timeout for setTimeout (will fire immediatly) hc3_emulator.strictClass=<boolean> -- Strict class semantics, requiring initializers hc3_emulator.consoleColors=<table> -- Maps fibaro.debug/self:debug etc to color (debug.color enables color debugging) hc3_emulator.sysConsoleColors=<table> -- Maps colors used for system logs hc3_emulator.userdataType=<boolean> -- If true intercepts type(...) to return 'userdata' for our Lua classes. Some apps checks this... Some useful emulator functions: hc3_emulator.setOffline(<boolean>,<boolean>) -- hc3_emulator.getIPaddress() -- Return HC3 IP address hc3_emulator.prettyJsonFormat(<table>) -- Return json formatted string of Lua table hc3_emulator.postTrigger(<event>,[<time ms>]) -- Posts a trigger to the emulator... hc3_emulator.loadScene(...) -- Load scene from file or HC3... hc3_emulator.loadQA(...) -- Load QA from file or HC3... hc3_emulator.downloadPlugin() -- (ZBS). Default ~/.zbstudio/packages hc3_emulator.downloadAssets() -- (ZBS). Default ~/.zbstudio/hc3emu hc3_emulator.downloadResources([<filename>]) -- Downloads a "backup" of HC3 resources hc3_emulator.loadResources([<filename>]) -- ...that can be loaded as "local" resources for the emulator. Some debug flags that can be set with hc3_emulator.debug.<flag>=<value> fibaro=false, -- Logs calls to fibaro api trigger=true, -- Logs incoming triggers from HC3 or internal emulator timers=nil, -- Logs low level info on timers being called, very noisy. refreshloop=false, -- Logs evertime refreshloop receives events mqtt=true, -- Logs mqtt message and callbacks http=false, -- Logs all net.HTTPClient():request. ALso includes the time the request took api=false, -- Logs all api request to the HC3 onAction=true, -- Logs call to onAction (incoming fibaro.calls etc UIEvent=true, -- Logs incoming UIEvents, from GUI elements zbsplug=true, -- Logs call from ZBS plugin calls webServer=false, -- Logs requests to /web/ including headers webServerReq=false, -- Logs requests to /web/ excluding headers files=false, -- Logs files loaded and run color=true, -- Logs in console using ANSI colors (see hc3_emulator.consoleColors for mapping) locl=true, -- Log creation of local devices breakOnInit=<boolean> -- Tries to set breakpoint on QuickApp:onInit (mobdebug) breakOnLoad=<boolean> -- Tries to set breakpoint on first line in loaded file (mobdebug) breakOnError=<boolean> -- Tries to break after error (makes it easier to look at call stack etc) ctx=false, -- Logs Lua context switches timersSched=false, -- Logs when timers are scheduled timersWarn=0.500, -- Logs when timers are called late or setTimeout with time < 0 timersExtra=true, -- Adds extra info to timers, like from where it's called and definition of function (small time penalty) In the example in the beginning, the HC3 credentials are listed in the header. If you don't want that (it's easy to forget it and share the code with your passwords in plain sights<9 you can create a credentials.lua file with your secret stuff and it will be automatically included by the SDK. The format should be return { ip="2912.168.77", user="admin", pwd="admin", mySecret="hgskjfhgjhgkdfh" } It returns a Lua table with the relevant keys. ip, user,and pwd is used to log into the HC3. We have added another key here to 'mySecret'. Assume that you want you QA to have a defined quickAppVariable with the value of mySecret. It could be the password to log into an external services. Then you can do like this if dofile and not hc3_emulator then hc3_emulator = { name="My QA", quickVars = {["password"]="$CREDS.mySecret"}, This define a quickAppVariable with the name 'password' and it fetches the key 'mySecret' from the credentials table and uses that as the value. When you QA starts up you can do self:getVarible('password') and it will return the credential. This is useful as not to litter your code with visible credentials. NOTE. Be aware that if you deploy the real QA with hc3_emulator.deploy=true or using the menu commands with the plugin, the deployed QA will have the quickAppVariable defined and if you upload that for sharing people will see your credential. If someone wants to try this in another IDE than Zerobrane that I use (like Visual Studio) the only thing that could be an issue is to have access to the Lua libraries require("socket") -- LuaSocket require("socket.url") -- LuaSocket require("socket.headers") -- LuaSocket require("ltn12") -- LuaSocket require("mime") -- LuaSocket require("lfs") -- LuaFileSystem They are pretty standard lua libraries - based on LuaSocket. @10der has managed to run it under Visual Studio on Windows. Here is an updated library/project map to work with the latest version of the emulator vscode_fibaro_bin.zip. Note that you should update the fibaroapiHC3.lua file provided i the archive when new are released as I will not update this archive for every new release. @petergebruers also have some tips. Any improvements are happily received (in code) and credits will be due granted. Links to notable post Here is a description of the various way to use the emulator when developing code (high-level) Some in-depth posts Running "Offline" (TBD) Running in "Mix mode". Mixing real devices and locally emulated devices (TBD) Running with a "Proxy QA" (TBD) Using real QA as "Proxy" (TBD) Downloading HC3 resources to file and emulate them locally (TBD) Running standard Lua with access to HC3 functions (developing management scripts etc) (TBD) Loading multiple QAs/Scenes and run them in parallel in the emulator (also getting QAs/Scenes from the HC3 and install them in emulator on the fly...) (TBD) Running faster than real-time and manipulating start dates (TBD) A ZeroBrane plugin to make life easier while debugging A post introducing the SDK with QuickApps. A post introducing the SDK with Scenes. Scene support is not complete. Creating and debugging multi-file QuickApps The debug flags that can be set are described The new dynamic load functions to run multiple QAs/Scenes in the emulator are described Telneting into the emulator to capture logs and issuing Lua calls <here> (nice way to test your code) Using the Web GUI Debugging setTimeout code and tracking timers. MQTT support. Another post with running a scene completly without being connected to the HC3. Some notes on the implementation of the SDK - if you would like to hack on it A collection of QA's I developed with the SDK - which means that they can be run offline ChildrenOfHue. A QA that creates QA children devices for your Hue devices (It's the Hue QA I use myself these day) iOSLocator. An iOS geopresence QA. iCal (iOS,Google) QA Telegram QA. Event watcher QA. Helper QA to get/subscribe on event triggers Vonage/Nexmo SMS service. Send SMS. Changelog: v 0.67 - numerous bug fixes caused by the restructuring. hc3_emulator.start{startTime="07:00 4/5/2000"} - will start the simulation at the given time. v 0.68 - fibaro.debug behaves more like original. v 0.70 - better offline support and speeding. v 0.72 - More offline and support for downloading HC3 resources to be used while running disconnected from the HC3 v 0.73 - Various speed-time related bugs v 0.75 - Better http sync behaviour. Set hc3_emulator.asyncHTTP=true to get some pseudo asynchronous behaviour v 0.77 - Support for 5.030.45. Initial support for childDevices and fixes for the changed handling of UI events v 0.78 - UI fix. Name of callbacks defaults to button.."Clicked", unless you have a onReleased=name or onChanged=name in the UI table struct. v 0.80 - Fixed bug in self:getVariable and self:setVariable v 0.81 - Better quickVariables handling for proxies, and self.childDevices list updated when children are deleted. v 0.83 - self:getVariable returns the empty string "" if the variable does not exists according to the latest behaviour on the HC3... 'class' is not redefined if available from Luabind... However, I've not had a chance to test if it's 100% compatible yet... v 0.84 - Initial support for mqtt. You need to have installed https://github.com/xHasKx/luamqtt so that require("mqtt") works from fibaroapiHC3.lua. I have tried to mimic the HC3 mqtt api but I have not really used mqtt that much so if someone uses it with fibaroapiHC3.lua and discovers if stuff is not compatible with the HC3 implementation please let me know and we fix it. v 0.85 - Compatibility fix for function 'class' to adhere more closely to the HC3/luabind version v 0.90 - Cleanup of code, Better handling of children and QuickApps, ZBS color output with ansi escapes; hc3_emulator.colorDebug=true v 0.93 - New model for QuickApp proxies. Better child device compatibility. v 0.95 - Various bug fixes - log prints more in line with HC3 log console. fibaro.emitCustomEvent bug fix. v 0.98 - First support for backup/download/upload with the ZeroBrane plugin (another post here) v 0.99 - Better trigger handling and new way to include SDK in your QA/scene code. No hc3_emulator.start at the end. v 0.100 - Web GUI emulator for QuickApps. New format for using credentials.lua. Bug fixes... v 0.102 - Better handling of children and their quickAppVariables v 0.104 - Rewrite of offline mode. Better web UI support. v 0.105 - Support for new QA file format (proxies work again) v 0.106 - Added support for net.UDPSocket() v 0.109 - UDPSocket bug fix. ( @10der), property() support for class() - much harder than it looks... v 0.110 - Oops, serious bug in 'class' affecting ...everything. Hopefully fixed. v 0.111 - Removed unnecessary os.exit(). urlencode api calls ( @10der) v 0.112 - UDP fixes. ( @10der) v 0.114 - Bug fix (global 'self' escaped) v 0.115 - Bug in url encode for api calls. UDPSocket :bind(ip,port) function added. v 0.116 - :bind(ip,port) really fixed.... v 0.117 - startup fix v 0.119 - "Softer os.exit()" - better compatibility with Visual Studio (thanks @10der) v 0.120 - Debugger friendly QuickApp class (no __index). First version of file/backup v 0.121 - api.get bug fix. Faster proxy/deploy. v 0.123 - QuickApp:setVariable bug (thanks @10der) v 0.124 - fibaro.clearTimeout added, MQTT fixes. v 0.125 - fibaro.alarm() was buggy - fixed. Set self.USERPIN to pincode to allow fibaro.alarm("disarm") to be allowed from emulator. v 0.126 - fix __fibaro_get_device() ( @10der) v 0.128 - fix sort order of triggers. Default room in offline mode ( @10der) v 0.130 - fix UI handling ( @rangee. More UI options. v 0.131 - fix uiCallbacks not always updating when updating proxy v 0.135 - fixes... v 0.137 - TCPSocket fixes v 0.138 - setTimeout for negative times are inserted in the queue.... i.e. will execute as soon as possible. v 0.140 - fixed bug with setInterval (clearInterval within a setInterval function didn't work...) v 0.141 - fix bug in net.TCPClient() v 0.145 - bug in printout of sockets... stricter class constructor requirements v 0.148 - MQTT event format bug ( @jayrock) v 0.150 - Initial websocket support. Need to download wsLua_ER.lua from my github and put in project directory. v 0.152 - support fibaroapiHC3plug.lua v0.4 v 0.155 - bugfixes. v 0.156 - html color bugfix v 0.198 - New version of emulator with better support for everything. Thanks to @petrkl12 that has been a guinea pig and helped in debugging the code. v 0.200 - Fixed bug in speedTime. plugin.restart() now restarts the QA in a correct way. v 0.299 - Major rewrite of the HC3 API - cleaner architecture and prepared for being split into sub-files (I'm approaching 10k lines now). Note 'end--hc3' required to end header. v 0.300 - Bugfixes from v0.299 v 0.301 - Better/simpler class definition - easier to debug/step into classes (avoiding __index unless class uses property() )
-
I have started to code a Hue QA that uses the new V2 api. It's still early beta... (v0.11) It's available via the QAUpdater QA. The QA is a standalone QA that keeps an updated state of the Hue resources and accept commands to change them - like turning on/off lights. It only provides an API (fibaro.call, fibaro.getValue) and no QuickAppChild devices (the latter can be built relatively easy built using HueConnector...) To use the QA you create a your own client QA that calls the HueConnector QA. Example client: local devices = { "9222ea53-37a6-4ac0-b57d-74bca1cfa23f", -- Sensor "3ab27084-d02f-44b9-bd56-70ea41163cb6", -- Tim "a007e50b-0bdd-4e48-bee0-97636d57285a", -- Switch } function QuickApp:hueInited() local function printf(...) print(string.format(...)) end -- local map = self.hue.getRsrc("deviceMap") -- Setup custom mapping from room+name to Hue ID. -- for id,info in pairs(map) do -- local name = ((info.room and (info.room.."_") or "")..info.name):gsub("[%-%s]","_") -- self.hue.idMap[name]=id -- print(name,"=>",id) -- end print(("-"):rep(40)) print("Mapping table:") -- Print out default mapping for name,id in pairs(self.hue.idMap) do printf("'%s' => '%s'",name,id) end print(("-"):rep(40)) self.hue.subscribeTo(devices) self.hue.listSubscribedDevices() self.hue.listAllDevices() -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","setColor","white") end, 0) -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","turnOff") end, 0) -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","turnOn") end, 3000) -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","turnOff") end, 5000) -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","turnOn") end, 7000) -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","setDim",0,4000) end, 10000) -- setTimeout(function() fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","setDim",100,4000) end, 15000) -- setTimeout(function() fibaro.call("Guest_room_Tim","setColor","green") end, 17000) -- setTimeout(function() print(fibaro.get("3ab27084-d02f-44b9-bd56-70ea41163cb6","on")) end, 19000) end function QuickApp:hueEvent(id,event) self:debug("Event:",uid," ",json.encode(event)) end function QuickApp:onInit() self:debug(self.name, self.id) self:setupUpHue() end This example uses 3 Hue devices, a motion/lux/temp sensor, a light (Tim), and a switch. The QA supports devices, rooms, zones and scenes. We can send command to the Hue light with fibaro.call. Note that the id is the Hue uid and not a device number. When a device changes state there is a callback to QuickApp:hueEvent with the uid and the event. There is a deviceMap (more about that later) accessible with self.hue.getRsrc("deviceMap") that maps Hue ids to the various properties of the device/resource. In particular, name and room. This allows us to build a map from our own IDs to hue ids as they may be easier to deal with. In the example above we map the light "3ab27084-d02f-44b9-bd56-70ea41163cb6" that has the name "Tim" and room "Guest room" to "Guest_room_Tim"="3ab27084-d02f-44b9-bd56-70ea41163cb6" in the self.hue.deviceMap[] table. That table is used by fibaro.call so if the id is in the self.hue.deviceMap table it will use that mapping. This allows us to call fibaro.call("Guest_room_Tim","setColor","green") in our example. but it also works with fibaro.call("3ab27084-d02f-44b9-bd56-70ea41163cb6","setColor","green") Only lights, rooms, zones and scenes can take commands: fibaro.call(uid,"turnOn"[,transition]) -- transition in ms. fibaro.call(uid,"turnOff"[,transition]) -- transition in ms. fibaro.call(uid,"toggle"[,transition]) -- transition in ms. fibaro.call(uid,"setDim",value[,transition])). -- value 0-100, transition in ms. fibaro.call(uid,"setTemperature",value[,transition]) -- value in mirek fibaro.call(uid,"setColor",<string> | {x=x, y=y} | {r=r,g=g,b=b}[,transition]) -- color string, ex "green" or x,y float values. (RGB support tbd) fibaro.call(uid,"recall"[,transition]) -- Recall scene for scene with uid. fibaro.call(uid,"sendRaw",<table>) -- POST raw command to Hue device with uid Sensor properties motion -- true/false temperature -- temperature light -- lux status -- connected/reachable power_state -- battery Buttons/switches properties button -- button pressed status -- connected/reachable power_state -- battery Lights properties on -- true/false dimming -- 0-100 color_temperature -- mirek color -- x,y status -- connected/reachable To use this there is a small Hue client library that needs to be included in the QA On top of this it would be relatively easy to create ex. childDevices for each device etc. So, there is some setup that needs be done for the HueConnector QA too. There are quickApp variables with "Hue_IP" and "Hue_User". The latter is the api key you get from the hub. You can dump the current devices, rooms, zones and scenes (the resources we can work with) When I log my resources looks like [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['1c10e485-e52b-4144-9991-46dbb2eedafa'] = { type='device', name='Middle window', model='LCT012', room='Living room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['21fc2e2f-05e6-4fbd-ad3b-a12762c88e72'] = { type='device', name='Hue white lamp 1', model='LWA001', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['2219eadd-9464-4149-b52d-073ed1d9754a'] = { type='device', name='Köksö2', model='LCG002', room='Köksö', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['2d7bfac8-688b-4889-b813-b927e875b533'] = { type='device', name='Star right', model='LCT012', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['3ab27084-d02f-44b9-bd56-70ea41163cb6'] = { type='device', name='Tim', model='LCT015', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['429ee799-9b86-43e5-bf31-ce3d06b45cc7'] = { type='device', name='Roof3', model='LCT012', room='Hall', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['598e4796-be01-482f-99c1-92f95fa8a18c'] = { type='device', name='Roof2', model='LCT012', room='Hall', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['59cbfb37-eba9-4746-9e64-ded409857abc'] = { type='device', name='Left window', model='LCT012', room='Living room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['5ddcb36b-f985-4876-88b6-a238c58b9dbf'] = { type='device', name='Star left', model='LCT012', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['721e69c5-bc75-4e99-b3ea-c05038ffa1af'] = { type='device', name='Star middle', model='LCT012', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['8a453c82-0072-4223-9c42-f395b5cb0c40'] = { type='device', name='Hue smart plug 1', model='LOM007', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['8dddf049-0a73-44e2-8fdd-e3c2310c1bb1'] = { type='device', name='Roof1', model='LCT012', room='Hall', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['9222ea53-37a6-4ac0-b57d-74bca1cfa23f'] = { type='device', name='Living room sensor', model='SML001', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['932bd43b-d8cd-44bc-b8bd-daaf72ae6f82'] = { type='device', name='Living room wall switch', model='RDM001', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['93d49902-6ce5-4383-9037-bfaeec8cd538'] = { type='device', name='Right window', model='LWO003', room='Living room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['9be444b2-1587-4fbe-89ac-efb809d7e629'] = { type='device', name='Roof lamp', model='LCT015', room='Bedroom', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['a001f510-48dd-47fc-b9ff-f779c40dd693'] = { type='device', name='Table1', model='LCA001', room='Living room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['a007e50b-0bdd-4e48-bee0-97636d57285a'] = { type='device', name='Dimmer switch', model='RWL021', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['a2b30b76-f044-46b6-9e1c-c8156baf00ab'] = { type='device', name='Table2', model='LCA001', room='Living room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['c4bef7c5-0173-4d57-ae6a-d7f8a14b4dde'] = { type='device', name='Roof5', model='LCT012', room='Hall', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['d3b04b72-c2f0-401f-85d7-a65f2db5c48e'] = { type='device', name='Roof4', model='LCT012', room='Hall', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['e82c2285-20f3-401f-9621-9dc356feb694'] = { type='device', name='Köksö1', model='LCG002', room='Köksö', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['f2a231b4-9c27-466f-8344-05c4012c742b'] = { type='device', name='Philips hue', model='BSB002', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['795959f5-9313-4aae-b930-b178b48249e0'] = { type='room', name='Guest room', model='bedroom', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['9ab242fb-fae1-47e5-a54f-51bb8e80ac31'] = { type='room', name='Köksö', model='kitchen', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['bbe472e6-8ea8-477b-a116-ca345452e056'] = { type='room', name='Hall', model='living_room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['bcd3daec-82a9-4de7-813a-3464beee0090'] = { type='room', name='Living room', model='living_room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['cc309f30-d0f4-4ab5-a31f-39cd2206be57'] = { type='room', name='Bedroom', model='bedroom', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['03541e04-3481-47e7-ad22-c167437ca905'] = { type='scene', name='Bright', model='unknown', room='Kitchen table', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['29d8ba67-980a-4ab9-9fa6-50a0f994b273'] = { type='scene', name='Bright', model='unknown', room='Window lights', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['dd2cef77-e4fb-455b-867f-bad85f8f846c'] = { type='scene', name='Miami', model='unknown', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['f1677f3f-db72-45b2-a922-97046cdbff9d'] = { type='scene', name='Bright', model='unknown', room='Guest room', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['39e1fc25-e926-42e5-a840-b2d21aaa08f3'] = { type='zone', name='Stars', model='recreation', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['79e44c37-15e0-4d93-8d89-230b14822270'] = { type='zone', name='Gymet', model='gym', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['9bfda4bf-b17e-4ec9-9123-a97afbcca814'] = { type='zone', name='Window lights', model='recreation', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['b5f12b5f-20c7-47a5-8535-c7a20fb9e66d'] = { type='zone', name='Kitchen island', model='kitchen', }, [12.08.2022] [10:02:42] [DEBUG] [QUICKAPP1001]: ['fe101c36-3dcc-4831-90f1-5052fc54e08b'] = { type='zone', name='Kitchen table', model='kitchen', }, That table is the one used when creating a custom mapping between names and Hue uids There will be improvements in the coming week and also hoping the V2 API will mature a bit more. There are some speed improvements that I know about that will improve the QA significantly...
- 43 replies
-
- 8
-
- qa
- development
-
(and 1 more)
Tagged with:
-
Latest version of Lualibs = lualibs v1.0.1.zip Changelog for v1.0.1 (thank to @petergebruers) - fix HC user authentication (was: user:password in URL, is now: basic authentication).- fix chunked responses (was: use only chunk 1, is now: concatenate chunks). Fixes "getDevicesId".- add error checking and display in the HTTP part, to get sensible error messages. Most of the information came from the french forum which can be found here all credits go to Steven! ZeroBrane is an IDE for development in Lua code. It offers you auto completion and partial support to use the actual fibaro: option in your code too. To get started grab the latest version from https://studio.zerobrane.com/download (1.5.0 as of writing) grab your favorite flavor. It supports Mac, Windows and Linux. To use the Lua Library you have to install it, grab the lua libs (top of page) for fibaro. You need to install these files in your c:\<yourlocation>\ZeroBraneStudio\lualibs (for Mac this would be /Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/lualibs) after that a restart of the app is a good thing to do. Use this always in your code when you start testing your setup. For example: require("FibaroSceneAPI") hc2_user = "youraccount" hc2_pwd = "yourpassword" hc2_ip = "192.168.x.x" local data = fibaro:getGlobal("somevariable") print(data) Do keep in mind this is your userid/password on the box itself, do NOT use a fibaro ID since that is only the login to your remote. To change the Colors to be the same as on Fibaro (if you feel really cozy with those colors) edit your user settings at: Edit -> Preferences -> Settings: User styles = loadfile('cfg/tomorrow.lua')('TomorrowNight') stylesoutshell = styles -- apply the same scheme to Output/Console windows styles.auxwindow = styles.text -- apply text colors to auxiliary windows styles.calltip = styles.text -- apply text colors to tooltips local colors = { orange = {255,158,89}, braun = {217,191,140}, darkgray = {38,38,38}, blue = {89,158,255}, green = {188,210,121}, red = {179,94,77}, white = {255,255,255}, gray = {102,102,102} } styles.comment = {fg = colors.gray} styles.operator = {fg = colors.white} styles.number = {fg = colors.red} styles.stringtxt = {fg = colors.green} styles.keywords0 = {fg = colors.blue} styles.text = {fg = colors.braun, bg = colors.darkgray} styles.keywords3 = {fg = colors.orange} styles.keywords4 = {fg = colors.orange} styles.keywords5 = {fg = colors.orange} styles.keywords6 = {fg = colors.orange} styles.keywords7 = {fg = colors.orange} And if you want to have auto completion you have to add fibaro.lua to your ZeroBraneStudio/api/lua folder. Please note that this file is the english file and has some few additions which i didn't see or where incorrect. Looks like: To activate it, please make sure you add it. Go to Edit -> Preferences -> Settings: System Add the following string to it: api = {luadeb = {'fibaro'}} The fibaro:calculateDistance doesn't work and the sourcetrigger needs to be set manually. See below snippet for testing: __fibaroSceneSourceTrigger = {type="global", name="Pushbullet"} -- __fibaroSceneSourceTrigger = {type="global", name="Pushbullet"} -- __fibaroSceneSourceTrigger = {type="property", deviceID=6, propertyName="value"} -- __fibaroSceneSourceTrigger = {type="autostart"} -- __fibaroSceneSourceTrigger = {type="other"} print(fibaro.getSourceTrigger().type) -- global print(fibaro.getSourceTrigger().name) -- Pushbullet __fibaroSceneSourceTrigger = {type="autostart"} print(fibaro.getSourceTrigger().type) -- autostart FAQ: Q: I get the following error message: lualibs/json/decode.lua:74: bad argument #1 to 'match' (string expected, got nil) A: It cannot reach Fibaro system correctly. Please make sure you have the right userid/pwd and correct ip number. Q: I don't see any completion on my fibaro: A: Make sure you added the completion Edit -> Preferences -> Settings: System (lualib) Q: Where do i get all my values from? A: You can make use of the excellent tool from @Krikroff found in this thread to grab all the values. Q: Where is this data coming from? A: Fibaro has an api interface, you can go there via http://192.16.x.x/docs where you can try it out. Q: I click on play but it does not keep running? A: Make sure you click the double green arrow. The other one stops untill you press forward. (F6 = Go, F5 = Waits on next itteration) Q: I want to change the width of the tabs A: Go to Edit -> Preferences -> Settings: User and add "editor.tabwidth = 3" Q: Disable wordwrap for long lines A: Go to Edit -> Preferences -> Settings: User and add "editor.usewrap = false" Q: How to i debug line by line? A: See below (credits go to Fred the Phew for below screenshots & explanation) Open Zerobranstudio and display the following windows if you have not already done so insert the following code in a new blank window Zerobranstudio (we will revise multiplication ) local loop = true local i = 1 local j = 1 while loop == true do i = i + 1 j = j + 2 print ( i .. "x" .. j .. "=" .. i * j ) end To activate dynamic tag tracking, simply select the name of the variable you want to track, then right click on it to bring up a context menu. You must then select the option Add watch expression as in the image below. In our case, it must be done for the 2 variables i & j. To switch to debug mode, press the F5 key once, the window should look like this. The green cursor is positioned on the first instruction, and the Watch window displays the values of i and j (to nil at the moment which is logical) Now press the F10 key to execute the program step by step, until the first result of the multiplication is displayed, as shown below. The result of the multiplication is consistent with the values of i and j. To test now the modification on the fly of a variable, we will re-run the loop a second time by pressing the F10 key several times but without executing the print instruction, as in the image below. The value of the 2 variables has been modified by programming. To modify dynamically the value of j, click on the Remote console tab, type the line i = 20 then press the Enter key to validate the command, as in the image below. We can then see that the value of ja has been modified in the Watch window. It is now enough to click on the tab Output (suspended), and to press the key F10 to resume the execution of the program. It is now that the value of j set by hand has been dynamically taken into account by the program. Happy Coding! \o/ (feel free to make remarks so i can make it better) lualibs.zip
- 25 replies
-
- 3
-
- development
- zerobrane
-
(and 2 more)
Tagged with:
-
What what be REST API endpoint and protocol / documentation for opening the gate on Fibaro Intercom? Like, there is mjpeg on http://ip_address:8080/live/mjpeg Thank you
- 9 replies
-
- intercom
- development
-
(and 1 more)
Tagged with:
-
Hi, I am using and maintaining some 50s scene on my HC2. I am developing mostly in ZeroBrane. Well so far so good. But the most anoying thing is that there is no way to "upload" scene to the HC2. Ideally this could be done from the development environment. So my question is: Is anybody using such a feature? And if yes, how? If not, I am currently looking into integrating such a feature in a GIT workflow, as git hook. So if there is any interst I would look further into it. While I have already a plan (REST/put with a decent JSON content, retrieving information from the lua script) I have still some questions, or could need some help. Even if it is just "testing". So if you there are any comments on this, just contact me. Best regards, Theo
- 4 replies
-
- tool
- development
-
(and 1 more)
Tagged with:
-
Since we are quiet some months further... I was wondering when the dev.Departement of Fibaro is coming with some news on the promissed NEST plugins and when it will be available? Or am I just the only one who would like to see this being implemented in our Hc2? (I am aware that there seems to be a IFTTT solution... But I prefer to use a direct plug for this...)
- 17 replies
-
- 1