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 'quickapp'.
-
The EventRunner QuickApp makes it easy to write home automation rules, but also allows for development of very advanced rules Schedule actions at specific times with additional conditions Trigger actions when complex conditions are met Interact with other QuickApps and systems A complete event based programming language "eventscript" that is concise and powerful to describe concurrent automation rules. Example -- Setup some variables to use in rules (We could also use a "home-table") rule("xmas={ tree = 122, light = 166 }") -- xmas tree and light deviceIds rule("kitchen = {}") rule("kitchen.lamps = { 77, 98, 101 }"). -- deviceIds of lights in kitchen rule("kitchen.sensors = { 56, 33}") -- deviceIds of motion sensors in kitchen -- Define rules rule("kitchen.sensors:breached => kitchen.lamps:on") -- If any sensor is breached, turn on lights rule("trueFor(00:10,kitchen.sensors:safe) => kitchen.lamps:off") -- If all sensors are safe for 10 minutes, turn off lights rule("@sunset-01:00 & wday('sat-sun') => xmas.tree:on") -- 1 hour before sunsets on Saturday and Sunday turn on xmas tree rule("remote:key == '2:Pressed' => xmas.light:toggle") -- Key 2 on remote toggles xmas light on/off rule("kitchen.sensors:breached & once(06:00..08:00) => fibaro.call(RadioQA,'play')") -- Start radio when someone enters kitchen between 6 and 8, but only once Many more possibilities, with rules triggering on temperatures, alarm states, global variables etc etc... The rule language "event script" is designed to be reasonable easy to read. If condition before '=>' is true, then do the actions after the '=>'. If we don't have a '=>' it's just an expression that is computed, ex. for setting up variables like in the example. An beta of EventRunner5 is available now at https://github.com/jangabrielsson/EventRunner5 I will also publish versions available via the UpdaterQA which is probably the easiest way to install/update. Here is v0.5 for download EventRunner5.fqa It's still under development so there may be need for manual updates if too much break. Especially, the main file with the rules may go through some revisions and may require manual updates. However latest version is reasonable ok and worth trying out - many thanks to @Sjakie allowing me to test with his 219+ home rules... Goals with EventRunner5 Backwards compatibility for rules from ER4 (as much as possible...) Better error messages Better debug possibilities Easier to extend with custom functions Some new cool scripting functions Much cleaner code - which will allow me to sleep better at nights... Current version is almost on feature parity with ER4. There are some bloat in ER4 I would like to skip unless people really need it... There are most likely bugs lurking in ER5 as it is not tested as much yet (However, I'm eating my own dogfood and have started to use it...) Introduction EventScript basics Variables EventScript in depth... Functions and properties Time scheduling rules - scheduling rules for time of day and dates Interval rules - rules running at given intervals during the day Trigger rules Event rules Alarm rules - arming/disarming and triggering on alarms Http and Nodered - integration with http requests and nodeRed flows Working with rules Settings and options Debugging and finding faults with rules... Terminal 5 - interactive web based terminal to play with rules on the HC3/ER5 Custom property functions - define your own :<property> functions Custom objects Advanced topics Recipes - common rules... Known changes from ER4: ER5 is not based on fibaroExtra so a lot of extra functions are not available. Especially functions defined for QuickApp. Ex. self:debugf etc. '=' has less priority than '&'. In ER4 we could write rule("@sunset => lamp:isOn & flag = true") which, if lamp was on set flag to true. In ER5 the priority makes this being interpreted as rule("@sunset => (lamp:isOn & flag) = true") which is not what we want and generates a runtime error. Instead, in cases like this, wrap the assignment in parenthesis rule("@sunset => lamp:isOn & (flag = true)") Alarms for partitions works differently Function to define rule is eval(...). They way eval is defined is differently. Most of this functions comes from the table 'er' that is passed to main(...). See declarations in the beginning of the main() function. A variable 'rule' is defined in the beginning of main(er) that points to the eval function so we can use rule("rule string") for backward compatibility... Nodered integration is slightly different. to be continued...
- 411 replies
-
- 5
-
-
- rule engine
- quickapp
-
(and 1 more)
Tagged with:
-
A thread to share some coding techniques for QuickApps? Because QAs are "long running scenes" (they don't have to be loaded and restarted for every event) - it is actually worthwhile to build up a library of "nice to have" code and include them in QAs. Here is Fibaro's manual for QuickApps. Here is Fibaro's manual for creating QuickAppChild devices Here is Fibaro's manual for using MQTT client Here is Fibaro's manual for WebSocket client List of posts: Introduction to the QuickApp anatomy - tutorial Part 1. Lua functions and object-oriented programming. (QuickApp is a OO class, so we need that base) Part 2. The basic QuickApp functions and what they do... and how. Part 3. More on QuickApp event handling - interaction with the UI and fibaro.call(<quickApp>,"name",...) Part 4. QuickAppChildren and how to raise them... what makes them tick? Also a tutorial on using classes in QuickApps here... All functions and variables available in the QuickApp Lua environment Logging functions (replacement for color/html tags + tostring for customised data structure) Shared functions calls between QuickApps (Here is an improved version) Off-line HC3api to use fibaro.* calls on PCs/Linux/Mac (fibaroapiHC3.lua) Polling for triggers in a QuickApps (like fibaro.getSourceTrigger()) Here is another method using a helper QA Patching 'setTimeout' so you get an error message if the function crashes A generic template for a QuickApp A simple code-lock QuickApp (demonstrating the UI with buttons) A QuickApp for scheduling user profiles (demonstrates UI buttons that change labels/text to present options) It doesn't' actually schedules the profile yet. (here is a working version) Structuring a QuickApp using event handlers to cope with asynchronous calls - like when using net.HTTPClient() instead of FHTTP(). looping with setInterval (without drifting) A QD reporting if other QDs are crashing (leveraging the "polling for triggers" code) Coding and debugging HC3 QuickApps offline using PC/Mac/Linux and a Lua IDE (and auto-creating a proxy on the HC3) An example of a QuickApp that download and installs scenes and QuickApps from a repository (files in a flat format) Coding and debugging of HC3 scenes using fibaroapiHC3.lua (not strictly about QuickApps but related) - can speed-up time A more complex QD that reads Google calendars or iPhone calendars and schedule custom events (uses the QuickApp structure for asynchronous calls in a previous tip) A substitute for Lua's loadstring() Here is another method of loading code dynamically into a QA Creating proxy devices on the HC3 to share devices between HC2 and HC3 A "webhook" QD - pushing events to external apps Adding interfaces to QA's - ex. power and battery and updating the properties (updates the little battery and power icon UI) @tinman Using '/plugin/publishEvent' to emit 'centralSceneEvent' (and a few other) .... Ex. keyfob QA by @tinman QA Toolbox. A modular toolbox of add-on functions to QAs that makes it easier to develop QAs 'basic' - Generic QA functions for loggin, loading modules, and management - used by all other modules. (some documentation) 'childs' - QA functions to easily manage quickAppChild devices. Loading, saving state, getting UI events etc. 'events' - QA functions for defining event handlers and structuring your code accordingly. Makes it easy to setup timers in various ways... 'triggers' QA functions for recieving triggers like Scenes do. The events module will receive triggers if loaded, but own handler can be defined. 'rpc' - QA functions for declaring (synchronous) remote functions from other QAs files - QA functionality for copying files between QAs pubsub - QA functions for event publish/subscribe... ui - QA functions for manipulation the UI elements of a QA lua parser/compiler - QA function for emulating loadstring and evaluating Lua expression from strings profiler - Functions for timing code used in QA Reading label/button/slider values. Sha2.lib crypto libs for HC3 (MD5, HMAC, SHA-1, SHA-224, SHA-256, SHA-512/224, SHA-512/256, SHA-384, SHA-512, SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256) @tinman aes crypto lib @tinman List of HC3 device types and interfaces @tinman Readers note. I started to call QuickApp devices for QDs (as in QuickApp Device, thought QAs sounded like Question and Answers). So, I use the word QD here and there but I'm not religious about it...
-
This Quickapp retrieves power consumption, solar production, gas usage and water flow from the Iungo Monitor, Solarpanel and Watermeter (Child) Devices for Consumption, Production, Solar Power, Water Flow, Consumption High, Consumption Low, Production High, Production Low, Total Gas and Total Water FLow Version 1.1 (11th September 2021) Changed the Child Devices Consumption High, Consumption Low, Production High and Production Low to device type energyMeter to facilitate the new Energy Panel Added automaticaly change rateType interface of Child device Consumption High and Low to "consumption" and Production High and Low to "production" Changed the Main Device to device type powerSensor to show the power graphs Added Net Consumption to the value of the Main Device Changed the Child Devices Consumption, Production and Solar Power to device type powerSensor to show the power graphs Changed the Water Flow unit text from m³ to Litre Added the amount of m2 Solar Panels to the log text ot the Child Device Solar Power and to the labels Changed meterreading to automatically kWh, MWh of GWh Moved tarif informatie to main device log text Added Meter measurement for Consumption High, Consumption Low, Production High, Production Low, Gas and Water to reset the measurements Added Meter measurement Date for Consumption High, Consumption Low, Production High, Production Low, Gas and Water Removed Refresh button Added some extra debug information when debug level = 3 Version 1.0 (6th February 2021) Now also supports Iungo Solarpanel and Iungo Watermeter Added a lot of Child devices Added QuickApp Variable for user defined icon Mother Device Added QuickApp Variable for Solar Power m2 Removed calculation and storage of energy consumption of Fibaro devices Version 0.6 (22nd January 2021) Now also supports Iungo basic version Version 0.5 (21 January 2021) Initial version QuickApp variables (mandatory, they will be automatically added with the default values): IPaddress = IP address of your Iungo Monitor solarPanel = true or false for use of the SolarPanel module (default is false) waterMeter = true or false for use of the Watermeter module (default is false) interval = Number in seconds, the Lungo Monitor normally is updated every 10 seconds solarM2 = The amount of m2 Solar Panels (use . for decimals) for calculating Solar Power m2 debugLevel = Number (1=some, 2=few, 3=all, 4=simulation mode) (default = 1) meterConsHigh = Last meter measurement Consumption High meterConsLow = Last meter measurement Consumption Low meterProdHigh = Last meter measurement Production High meterProdLow = Last meter measurement Production Low meterGas = Last meter measurement Gas meterWater = Last meter measurement Water meterConsHighD = Date last meter measurement Consumption High meterConsLowD = Date last meter measurement Consumption Low meterProdHighD = Date last meter measurement Production High meterProdLowD = Date last meter measurement Production Low meterGasD = Date last meter measurement Gas meterWaterD = Date last meter measurement Water Tested with: Iungo lite version Firmware Rev 3683 (07-01-2021) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/iungo_monitor/archive/refs/tags/iungo_monitor-11.zip or Fibaro Marketplace: https://marketplace.fibaro.com/items/iungo-monitor How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqa
- 59 replies
-
How to press a QuickApp button from another QuickApp
RohitNz posted a question in Scenes and Interface
Whats the call to press a QAuickApp button from another QuickApp ? -
HomeWizard Wi-Fi Water Meter Quick App for HC3 The HomeWizard Water Meter gives you live insight into your water consumption. It reads your analog water meter. With the supplied adapter you can place the water meter on most existing Itron, Elster or Sensus analog water meters within 2 minutes. I got a lot of questions if I would create a Quick App for the HomeWizard Wi-Fi Water Meter. So I decided to build it, despite not owning the device. The Quick App reads the total and active water usage and it calculates the daily usage: Feel free to test and post your findings in this topic. Download You can download the beta Quick App v1.0b1 release from my GitHub repository (direct link to Wi-Fi_Water_Meter_v1.0b1.zip). If it's out of beta I'll upload it to the FIBARO Marketplace. You can download the Wi-Fi Water Meter from the FIBARO Marketplace.
-
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!) If you want to use vscode, I recommend this project that I'm currently focusing my development efforts on. /TQAE.lua v0.59 -- 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-main.tar On PC/Mac use suitable archive program to unpack the archive. ../TQAE/TQAE.lua ../TQAE/TQAE_QA.lua ../TQAE/modules/* ../TQAE/web/* ../TQAE/examples/* ../TQAE/... Alternatively, and preferred, clone the GitHub repository >git clone https://github.com/jangabrielsson/TQAE The setup procedure would be EMB-31KYQ6LT:~ erajgab$ mkdir development # Create new directory to develop in EMB-31KYQ6LT:~ erajgab$ cd development/ EMB-31KYQ6LT:development erajgab$ git clone https://github.com/jangabrielsson/TQAE # Clone repository Cloning into 'TQAE'... remote: Enumerating objects: 1790, done. remote: Counting objects: 100% (192/192), done. remote: Compressing objects: 100% (135/135), done. remote: Total 1790 (delta 118), reused 122 (delta 57), pack-reused 1598 Receiving objects: 100% (1790/1790), 1.75 MiB | 7.28 MiB/s, done. Resolving deltas: 100% (1198/1198), done. EMB-31KYQ6LT:development erajgab$ ls # We got the code... TQAE EMB-31KYQ6LT:development erajgab$ cd TQAE/ EMB-31KYQ6LT:TQAE erajgab$ ls LICENSE TQAE.tar.gz examples modules README.md TQAE_QA.lua jgabs_QAs setup TQAE.lua TQAEconfigs.example lib web EMB-31KYQ6LT:TQAE erajgab$ mkdir test # Create 2 directories to do your own development in EMB-31KYQ6LT:TQAE erajgab$ mkdir dev So both directories dev and test are in .gitignore, so you can update the TQAE code with the command (while standing in the TQAE directory) EMB-31KYQ6LT:TQAE erajgab$ git fetch This will update the TQAE code (it's usually updated quite often) but will leave your test and dev directories untouched. You can also link dev to some other directory where you do your development. 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 192.168.1.18:8976 [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. 192.168.1.18 is my machine, your IP address may be different. The port is 8976. While TQAE_QA.lua is running open http://192.168.1.18:8976/web/main 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 192.168.1.18:8976 [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(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) 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 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: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="192.168.1.57" } --%%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="192.168.1.57", 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="192.168.1.57" } --%%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="192.168.1.57" } 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="192.168.1.57" } --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
-
This is a vscode setup for QA development. It contains an emulator so you can run the QA in vscode and debug it, optionally sending commands to and synching with the HC3. It has support for code completion and syntax highlighting. It has some workflow tasks to download QAs from the HC3, edit them and package and upload them when done. It's tested on Windows 11 and MacOS, and should work on Linux too. The repository for downloading it is here https://github.com/jangabrielsson/fibemu Some documentation is available here https://github.com/jangabrielsson/fibemu/raw/main/FibEmu.pdf (work in progress) ...and here is the movie (how to install on Windows 11) This is how the setup looks in Vscode. It gives you a way to develop and run a QuickApp offline on your PC/Mac/Linux and let it interact with the HC3 in a controlled way. There is also a simple UI to interact with the QAs UI and see events etc. Steps to run Have pyton3 installed on your machine. pip install the needed python libraries from requirements.txt >pip install -r requirements.txt Create a config.json file with the credentials to access the HC3. See config.json.example Install the vscode extension "Local Lua Debugger" by Tom Blind Create a QA file in the directory, select launcher "Fibenv QA file (remote)" and run debug F5 For other examples, see files in the examples/ directory (it's the QA files I use to test compatibility...) The .gitignore file included, excludes the subdirectories ./dev and ./test so they can be used to test your own code without impacting the rest of the repository. If you want your own repository - see instructions below how to link the right folders. For installing the python libraries, I would recommend to create an virtual environment for python in the folder before doing the pip install -r requirements.txt... The trick here is that we have a a python wrapper for the lua runtime (Lupa) so we solve dependencies on luasocket etc. and we don't need any special headers in the QA lua file to invoke/include the emulator/apis to make the QA being able to execute (we don't even need Lua installed on our machine ) To give some hints to the emulator what type of QA we have etc. we can give directive similar to TQAE in our QA file (but a bit different) 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'. It integrates with the lua debugger so we can set breakpoints etc. Still work in progress and stuff that doesn't work so well yet - will update the post as it progresses... There is the beginning of an emulator UI at http://127.0.0.1:5004/ Currently implemented APIs have a swagger page at http://127.0.0.1:5004/docs Port (5004) can be changed 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) 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 <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:initChildDevices(table) The general setup to develop your own QAs is the have the repo 'fibemu' downloaded in a separate directory. Then create your own vscode development directory and copy the fibemu/.vscode/launch.json and fibemu/.vscode/settings.json to your own .vscode directory. Then inside your .vscode make a soft link from .vscode/emufiles to fibemu/.vscode/emufiles. This way you can pull down new version of fibemu without messing up your own directory and development. Also setup your config.json with credentials. 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 A 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)
- 71 replies
-
- 6
-
-
-
- visual studio code
- quickapp
-
(and 3 more)
Tagged with:
-
This QuickApp can be used as your Fibaro Homecenter 3 Weather Provider (Settings - 6. General - Main - Main Devices - Weather Provider) The Buienradar Weather QuickApp contains the current Dutch weather measurements, the weather forecast and the 5-day forecast The 5-days forecast is shown in the labels and the tomorrow forecast is shown in the child devices The current observations are measured by KNMI weather stations spread across The Netherlands and are updated every 10 minutes The weather report is updated several times a day by the Buienradar meteorologists The QuickApp has child devices for: Temperature °C Feel temperature °C Ground temperature °C Humidity % Absolute humidity g/m³ Airpressure hPa Windspeed m/s Windspeed km/h Winddirectiondegrees ° (plus wind direction and arrow) Windspeed Bft Windgusts km/h Rain mm/h Rain Last 24h mm Sunpower Watt/m² Visibility km Sunset (time) Sunrise (time) Sun Chance tomorrow % Min Temp tomorrow °C Max Temp tomorrow °C Rain Chance tomorrow % Min Rain tomorrow mm/h Max Rain tomorrow mm/h Wind tomorrow m/s (plus wind direction and arrow) Wind tomorrow km/h (plus wind direction and arrow) This QuickApp is plug-and-play. The only thing you can do, is change the Station ID to a weather-station nearby from the list or add some nice icons to the devices. Wind Chill (based on the JAG/TI-method) and is only valid for temperatures between -46 C and +10 C and is only valid for wind speed between 1.3 m/s and 49 m/s Windspeed is shown in m/s (km/3.6) Absolute humidity is the measure of water vapor (moisture) in the air, regardless of temperature. It is expressed as grams of moisture per cubic meter of air (g/m3) conditionCodes = {unavailable = 3200, clear = 32, rain = 40, snow = 43, storm = 38, cloudy = 30, fog = 20,} The time shown in the QuickApp, is the last time of the measurement from Buienradar (not the system time) Changes version 3.0 (23rd March 2022) Added 5-days forecast to the labels Addded child devices for: Feel temperature °C Ground temperature °C Windspeed km/h Windspeed Bft Windgusts km/h Rain Last 24h mm Sun Chance tomorrow % Min Temp tomorrow °C Max Temp tomorrow °C Rain Chance tomorrow % Min Rain tomorrow mm/h Max Rain tomorrow mm/h Wind tomorrow m/s (plus wind direction and arrow) Wind tomorrow km/h (plus wind direction and arrow) Changed SunPower device type to powerSensor Changed all Wind devices types to windSensor Converted date-times to more nice format Quickapp variable setGlobalVar changed to boolean Added Quickapp variable stationWarning to show a warning (once) if your station hasn't got some weather value (default is true) Optimised some code Changes version 2.1 (15th January 2021) Added weatherdescription: "Mix van opklaringen en hoge bewolking" to conditioncode "cloudy" "Half bewolkt" to conditioncode "cloudy" "Opklaring en lokaal nevel of mist" to conditioncode "fog" "Zwaar bewolkt met lichte sneeuwval" to conditionCode "snow" "Zwaar bewolkt met regen en winterse neerslag" to conditioncode "snow" "Afwisselend bewolkt met lichte sneeuwval" to conditioncode "snow" "Zware sneeuwval" to conditioncode "snow" "Opklaringen en kans op enkele pittige (onweers)buien" to conditioncode "rain" "Bewolkt en kans op enkele pittige (onweers)buien" to conditioncode "rain" Added Airpressure Text in log of Airpressure Child Device Changes version 2.0 (3rd January 2021) Added Child Devices for: Temperature °C (including feeltemperature and groundtemperature) Humidity % Absolute humidity g/m³ Airpressure hPa Windspeed m/s (including windspeedBft and Windgust km/h) Winddirectiondegrees ° (including winddirection and arrow) Rain mm/h (including rainFallLast24Hour mm) Sunpower watt/m² Visibility km Sunset (time) Sunrise (time) Re-arranged the labels Added backup station functionality for weather stations that don't have all the data, the data from 6260 Meetstation De Bilt is used. Improved check for missing data Added Quickapp variable for debug level (1=some, 2=few, 3=all). Recommended default value is 1. Changes version 1.0 (25th October 2020) Added weatherdescription "Zwaar bewolkt met wat lichte regen" to conditionCode "rain" Changes version 0.6 (9th September 2020) Changed conditionCodes storm = 38 snow = 43 and unknown = unavailable Added weatherdescription "Afwisselend bewolkt met (mogelijk) wat lichte regen" to conditionCode "rain" and and "Afwisselend bewolkt met lokaal mist(banken)" to conditionCode "fog" Changes version 0.5 (4th September 2020) Added wind direction, air pressure and feel temperature to QuickApp labels Changed stationname to regio in labels and log Changed the names of the Global Variables to meet the Fibaro standards and shortened them (please manually delete your old ones and change the names in your scenes) Added an extra check for response of Buienradar (jsonTable) Changes version 0.4 (22nd August 2020) Completely renewed code Several Global Variables are available for personal use Added QuickApp variable SetGlobalVar true or false, whether you want to use the Global Variables Added QuickApp variable Timeout for finetuning waiting for response Changes version 0.3 (11th August 2020) error message instead of debug message in case of an error Changed method of adding QuickApp variables, so they can be edited Weather conditions: The Buienradar weather description is converted to the right Fibaro condition codes, with the icons: Fibaro Dashboard: The Fibaro properties Temperature, Humidity and Wind values are updated to show in your dashboard: Mobile App: For the Mobile app these values are available: For the most accurate measurements you can select a Station in your neighborhood: 6391 Meetstation Arcen / 6275 Meetstation Arnhem / 6249 Meetstation Berkhout / 6308 Meetstation Cadzand / 6260 Meetstation De Bilt / 6235 Meetstation Den Helder / 6370 Meetstation Eindhoven / 6377 Meetstation Ell / 6321 Meetstation Euro platform / 6350 Meetstation Gilze Rijen / 6323 Meetstation Goes / 6283 Meetstation Groenlo-Hupsel / 6280 Meetstation Groningen / 6315 Meetstation Hansweert / 6278 Meetstation Heino / 6356 Meetstation Herwijnen / 6330 Meetstation Hoek van Holland / 6279 Meetstation Hoogeveen / 6251 Meetstation Hoorn Terschelling / 6258 Meetstation Houtribdijk / 6285 Meetstation Huibertgat / 6209 Meetstation IJmond / 6225 Meetstation IJmuiden / 6277 Meetstation Lauwersoog / 6320 Meetstation LE Goeree / 6270 Meetstation Leeuwarden / 6269 Meetstation Lelystad / 6348 Meetstation Lopik-Cabauw / 6380 Meetstation Maastricht / 6273 Meetstation Marknesse / 6286 Meetstation Nieuw Beerta / 6312 Meetstation Oosterschelde / 6344 Meetstation Rotterdam / 6343 Meetstation Rotterdam Geulhaven / 6316 Meetstation Schaar / 6240 Meetstation Schiphol / 6324 Meetstation Stavenisse / 6267 Meetstation Stavoren / 6229 Meetstation Texelhors / 6331 Meetstation Tholen / 6290 Meetstation Twente / 6313 Meetstation Vlakte aan de Raan / 6242 Meetstation Vlieland / 6310 Meetstation Vlissingen / 6375 Meetstation Volkel / 6215 Meetstation Voorschoten / 6319 Meetstation Westdorpe / 6248 Meetstation Wijdenes / 6257 Meetstation Wijk aan Zee / 6340 Meetstation Woensdrecht / 6239 Meetstation Zeeplatform F-3 / 6252 Meetstation Zeeplatform K13 QuickApp variables (mandatory, they will be automatically added with the default values): interval = Number in seconds to update the data (defaul = 601) timeout = Number in seconds to wait for a response (default = 5) stationID = Number of the station you want to use for weather measurements (default = 6260 Meetstation De Bilt) backupstationID = Number of the backup station for missing weather data from stations that don't have all the data (default = 6260 Meetstation De Bilt). Don't change this ID unless you know what you are doing. setGlobalVar = true or false, whether you want tu use the Global Variables (default = false) stationWarning = true or false, whether you want to receive warnings if your station hasn't got some weather value (default is true) debugLevel = Number (1=some, 2=few, 3=all) (default = 1) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/buienradar_weather/archive/refs/tags/buienradar_weather_30.zip or Fibaro Marketplace: https://marketplace.fibaro.com/items/buienradar-weather How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqa JSON data copyright: (C)opyright Buienradar / RTL. All rights reserved JSON data terms: This feed may be used freely under condition of source reference buienradar.nl including a hyperlink to https://www.buienradar.nl. The feed cannot be derived from users or other persons.
- 65 replies
-
- 3
-
-
-
Here is a link to a set of QAs to control Shelly devices. https://www.smarthome.com.au/free-shelly-quick-apps-for-fibaro-home-center-3/ It's both gen 1 and gen 2 devices. Gen 2 devices are easier to integrate with the web socket API than the gen 1 where we need to poll the device with regular interval. Battery operated devices are in general a pain to support as they sleep and wake up now and then - which makes polling difficult. So, battery devices are not in focus The QAs support the basic features expected from a device of that QA type so they fit into the fibaro model of handling devices. Extra features like setting timers etc that Shelly support is better handled with the pretty good mobile/cloud Shelly app. There are a lot of devices that are potentially supported but not all have been tested. Please give us feedback here or in https://www.smarthome.com.au/free-shelly-quick-apps-for-fibaro-home-center-3/ so we can come out with an 1.1 update... (gen 1 Shelly 1 and Shelly 1PM have issues but will be fixed in next release) The suite contains 5+1 different QAs that each support different Shelly devices. The devices tested, and devices not tested but we expect they could work are: ShellyMultiDevice v1.0 com.fibaro.deviceController + child devices Supported Shelly devices: - Shelly 3EM (Gen1). Note: untested Children: - com.fibaro.binarySwitch - com.fibaro.energyMeter - com.fibaro.energyMeter - com.fibaro.energyMeter - Shelly EM (Gen1). Note: tested Children: - com.fibaro.binarySwitch - com.fibaro.energyMeter - com.fibaro.energyMeter - Shelly Plus 2PM (Switch) (Gen2). Note: tested Children: - com.fibaro.binarySwitch - com.fibaro.binarySwitch - Shelly Pro 2 (Gen2). Note: untested Children: - com.fibaro.binarySwitch - com.fibaro.binarySwitch - Shelly Pro 2M (Switch) (Gen2). Note: tested Children: - com.fibaro.binarySwitch - com.fibaro.binarySwitch - Shelly Pro 3 (Gen2). Note: tested Children: - com.fibaro.binarySwitch - com.fibaro.binarySwitch - com.fibaro.binarySwitch - Shelly Pro 4PM (Gen2). Note: tested Children: - com.fibaro.binarySwitch - com.fibaro.binarySwitch - com.fibaro.binarySwitch - com.fibaro.binarySwitch Supported HC3 QuickAppMethods: - <com.fibaro.binarySwitch>:turnOn() - <com.fibaro.binarySwitch>:turnOff() - <com.fibaro.binarySwitch>:toggle() ShellySingleColor v1.0 com.fibaro.colorController Supported Shelly devices: - Shelly Color Bulb (Gen1). Note: tested, only color mode for now - Shelly RGBW2 Color (Gen1). Note: tested Supported HC3 QuickAppMethods: - QuickApp:turnOn() - QuickApp:turnOff() - QuickApp:setValue(val) - QuickApp:setColor(r,g,b,w) - QuickApp:startLevelIncrease() - QuickApp:startLevelDecrease() - QuickApp:stopLevelChange() ShellySingleCover v1.0 com.fibaro.rollerShutter Supported Shelly devices: - Shelly Plus 2PM (Cover) (Gen2). Note: tested - Shelly Pro 2M (Cover) (Gen2). Note: tested Supported HC3 QuickAppMethods: - QuickApp:open() - QuickApp:close() - QuickApp:stop() - QuickApp:setValue(value) ShellySingleDimmer v1.0 com.fibaro.multilevelSwitch Supported Shelly devices: - Shelly Dimmer 1 (Gen1). Note: tested - Shelly Dimmer 2 (Gen1). Note: tested - Shelly Vintage (Gen1). Note: tested Supported HC3 QuickAppMethods: - QuickApp:turnOn() - QuickApp:turnOff() - QuickApp:setValue(val) - QuickApp:startLevelIncrease() - QuickApp:startLevelDecrease() - QuickApp:stopLevelChange() ShellySingleSwitch v1.0 com.fibaro.binarySwitch Supported Shelly devices: - Shelly 1 (Gen1). Note: untested - Shelly 1L (Gen1). Note: untested - Shelly 1PM (Gen1). Note: tested, not working yet...TBD - Shelly Plus 1 (Gen2). Note: tested - Shelly Plus 1 PM (Gen2). Note: tested - Shelly Plus Plug IT (Gen2). Note: untested - Shelly Plus Plug S (Gen2). Note: tested - Shelly Plus Plug UK (Gen2). Note: untested - Shelly Plus Plug US (Gen2). Note: untested - Shelly Pro 1 (Gen2). Note: tested - Shelly Pro 1 PM (Gen2). Note: tested Supported HC3 QuickAppMethods: - QuickApp:turnOn() - QuickApp:turnOff() - QuickApp:toggle() ShellyPlusHT v1.0 com.fibaro.temperatureSensor + com.fibaro.humiditySensor child Supported Shelly devices: - Shelly Plus H&T (Gen2). Note: tested, experimental, only wakes up when new data is available Children: - com.fibaro.temperatureSensor - com.fibaro.humiditySensor Supported HC3 QuickAppMethods:
-
This QuickApp contains devices of soil moisture, soil temperature and surface temperature, from accumulated temperature and precipitation data from OpenWeather via Agro Monitoring. Soil temperature and moisture are essential indices that allow your customer to adjust irrigation work and prevent crop roots damage. Accumulated temperature and precipitation is essential to make a right decision depends on a threshold setting. Temperature quantity index calculated as the sum of daily temperatures. Humidity quantity index expressed as the sum of daily precipitation. Current soil data is updated 2 times a day. The soil temperature is provided in Kelvins and in this quickapp converted to Celsius (C = K - 273.15) IMPORTANT You need an API key and Polygon ID from https://agromonitoring.com You need to create your Api key and Polygon ID at https://agromonitoring.com/dashboard/dashboard-start After your registration click the "New" button in the top of the "Create polygon" screen. Click on the polygon icon or square icon on the map. Draw your polygon. If you choose a polygon shape icon do not forget to merge the first and last points to finish your polygon. Fill in the "Name" field and click the "Create" button to save your polygon. The API is free up to 60 calls per minute and a total area of polygons of 1000ha See: https://agromonitoring.com/dashboard/dashboard-start See: https://openweathermap.medium.com/dashboard-update-current-and-historical-soil-data-24422fc75c5b What is soil moisture? The science behind the measurement: https://www.metergroup.com/environment/articles/what-is-soil-moisture-science-behind-the-measurement/ Version 0.2 (24th May 2021)) Changed Soil Moisture (child) device from multilevelSensor to humiditySensor with percentage presentation Version 0.1 (22 May 2021) Initial version Variables (mandatory): apiKey = Get your free API key from https://agromonitoring.com polygon = Create your Polygon ID at https://agromonitoring.com/dashboard/dashboard-start or look it up with https://api.agromonitoring.com/agro/1.0/polygons?appid=apiKey interval = [number] in seconds time to get the data from the API timeout = [number] in seconds for http timeout debugLevel = Number (1=some, 2=few, 3=all, 4=simulation mode) (default = 1) icon = [numbber] User defined icon number (add the icon via an other device and lookup the number) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/agro_monitor/archive/refs/tags/agro_monitor-02.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/agro-monitor-soil-moisture How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqa
- 20 replies
-
- 1
-
-
- agro monitor
- moisture sensor
-
(and 7 more)
Tagged with:
-
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() )
-
Hi guys! I would like to say that I am a beginner on Fibaro. I would like to integrate my LED strip on HC3. I have the API Key, I downloaded the fqa file (from here https://marketplace.fibaro.com/items/govee-colorled-controller-qa) but I don't know how to proceed. I have created the Quick App, but I don't know what I have to do to configure it. Can anyone help me?
-
Hi, need to controll Epson projector (send PWR On, PWR Off, PWR?) messages For controllinhg Epson, need to send a command for establishing connection (0x450x530x430x2F0x560x0500x2E0x6E0x650x740x100x030x000x000x000x00) and after that send the command for interogating power status (0x500x570x520x3f0x0d) Testing this from Hercules utility, works great When coding in LUA, after sending first command, when trying to send second command I get Connection reset by peer error If sending just first command, I get a proper response, so, no error in connection or command string Here is my code: function QuickApp:onInit() self:debug("onInit") self.ip = self:getVariable("ip") self.port = tonumber(self:getVariable("port")) self.sock = net.TCPSocket() end function QuickApp:parseData(str) while true do if string.find(str, '0x') then i,j = string.find(str, '0x') str = string.sub(str, 1, i - 1) .. self:fromhex(string.sub(str, i + 2, j +2)) .. string.sub(str, j + 3) else return str end end end function QuickApp:fromhex(str) return (str:gsub('..', function(cc) return string.char(tonumber(cc, 16)) end)) end function QuickApp:connect(successCallback) print("connecting:", self.ip, self.port) self.sock:connect(self.ip, self.port, { success = function() self:debug("connected") successCallback() end, error = function(err) self.sock:close() self:debug("connection error connect", err) end, }) end function QuickApp:init(event) --self:connect() self:send("0x450x530x430x2F0x560x0500x2E0x6E0x650x740x100x030x000x000x000x00", true, "0x500x570x520x3f0x0d") end function QuickApp:send(dataToSend, waitForResponse, pwr) self:connect(function() local dataConverted = self:parseData(dataToSend) local pwrConverted = self:parseData(pwr) self.sock:write(dataConverted) fibaro.setTimeout(1000, function() self.sock:write(pwrConverted) end) self.sock:read({ success = function(data) self:debug("response data:", data) --self.sock:close() end, error = function(err) self:debug("response error wait ", err) --self.sock:close() end }) fibaro.setTimeout(1000, function() self.sock:write(pwrConverted) end) self.sock:read({ success = function(data) self:debug("response data:", data) --self.sock:close() end, error = function(err) self:debug("response error wait ", err) --self.sock:close() end }) end) end Looks like the connection is closed after frist call, but do not know how to keep alive, tried everything Can anybody help me? Regards
- 2 replies
-
- lua socket
- epson
-
(and 2 more)
Tagged with:
-
The Radiation Monitor collects radiation levels from all available stations around the world and shows 5 nearest stations to your location and one station with highest current readings and one station with the highest 24 hour average readings. The QuickApp uses the location (latitude and ongitude) of your Homecenter to measure the distance to the stations and to get the nearest stations. The bearings in degrees from your location to the stations is shown. Next to the measurements, the five nearest reactors are shown. The languages English, French, Polish and Duth are supported. Thanks to @Sankotronic for his work for his HC2 Virtual Device version and ideas. The main device shows the nearest measurement μSv/h. There are Child Devices for: Nearest sensor 24h average μSv/h 2nd, 3rd, 4th, 5th nearest sensor measurement with the 24 average in the log text Nearest maximum measurement Nearest maximum 24h average measurement The nearest five reactors are retrieved once at startup of the QuickApp or at the next interval if you click on the button. Radioactive@Home is a Polish science project using the distributed computing capabilities of the BOINC platform. The main goal of the project is to create a free and continuously updated map of radiation levels available for everyone, by gathering information about gamma radiation using sensors connected to the computers of volunteers willing to participate in the project. Project is completely non-commercial, participating will be free of charge (excluding cost of detector) and the software will be licensed under the GNU General Public License (GPL). μSv/h: The sievert (symbol: Sv) is a unit in the International System of Units (SI) intended to represent the stochastic health risk of ionizing radiation. In land navigation, a 'bearing' is ordinarily calculated in a clockwise direction starting from a reference direction of 0° and increasing to 359.9 degrees. Measured in this way, a bearing is referred to as an azimuth by the US Army but not by armies in other English speaking nations, which use the term bearing. The human population is continuously exposed to ionizing radiation from several natural sources (cosmic and terrestrial contributions). For most individuals, exposure to natural sources exceeds that from all man-made (artificial) sources combined. The man-made sources arise from peaceful (e.g. medical use, energy generation, and associated fuel cycle facilities, radioisotope production, waste management) and military purposes (nuclear tests and their fallout or radioactive release, nuclear explosions). Radiation levels: Green: Radiation up to 0.3 μSv/h Yellow: Radiation between 0.3 and 0.8 μSv/h Red: Radiation above 0.8 μSv/h 1.14 µSv/h - Shelter population 5.7 µSv/h - Evacuation of population 11.4 µSv/h - Issue Iodine tablets 0.114 µSv/h - Max daily dose == 1 mSv/year Reverse Geocoding by Nominatim Reverse geocoding generates an address from a latitude and longitude. The reverse geocoding API does not exactly compute the address for the coordinate it receives. It works by finding the closest suitable OSM object and returning its address information. This may occasionally lead to unexpected results. QuickApp code logics: onInit() Initialise the QuickApp getQuickAppVariables() Get all Quickapp Variables or create them createVariables() Setup the global variables setupChildDevices() -- Setup all child devices loadMap() Get the webpage from http://radioactiveathome.org/map/ (This is the main loop of the QuickApp) extractData() Extract the data from the webpage source-code geoDistance() Calculate the distance from the HC3 (QuickApp variables) lat/lon to the sensors lat/lon geoBearing() Calculate the bearing from the HC3 (QuickApp variables) lat/lon to the sensors lat/lon Check for the values to give the right dot colours for the sample and average measurements Store the values of all sensors in a table and sort the table on distance Run through the table to get the maximum sample and maximum average measurements. If there are more than one, get the one that is the nearest-by updateIcon() Set the icon (colour) based on the sensor measurement getCity() Get the cities and countries for the seven selected sensors from https://nominatim.openstreetmap.org/ and store them in a table updateLabels() Update the labels updateProperties() Update the properties updateChildDevices() Update the Child Devices Return to the main loop loadMap() Links: Radioactive@Home Map: http://radioactiveathome.org/map/ Status servers: http://radioactiveathome.org/boinc/server_status.php Reverse geocoding: https://nominatim.org/release-docs/latest/api/Reverse/ licence:Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright Nominatim Usage Policy (aka Geocoding Policy): https://operations.osmfoundation.org/policies/nominatim/ Variables (mandatory and created automatically): latitude = Latitude of your location (Default is the latitude of your HC3) longitude = Longitude of your location (Default is the longitude of your HC3) language = Preferred language (default = en) (supported languages are French (fr), Polish (pl) and Dutch (nl)) interval = Interval in seconds to get the data from the Radioactive@Home website debugLevel = Number (1=some, 2=few, 3=most, 4=all) (default = 1, debugLevel 4 is only recommended for solving difficult issues) icon_refresh = User defined icon number for refresh status icon_green = User defined icon number for values less than 0.3 μSv/h icon_yellow = User defined icon number for values between 0.3 and 0.8 μSv/h icon_red = User defined icon number for values greater than 0.8 μSv/h icon_error = User defined icon number in case of an error gettng the data Version 1.3 (17th July 2023) Added extra check for the right response from Geocity (in case of response {"error":"Unable to geocode"}) Version 1.2 (11th January 2023) Added support for Croatian language thanks to @Sankotronic Version 1.1 (9th January 2023) Changed handling of negative values for dots and icons: if tonumber(num) >= 0 and tonumber(num) <= 0.3 then Added a better translation for French (thanks to @fredokl) Version 1.0 (5th November 2022) Added the nearest five reactors to the labels with distance and bearing Added a button to refresh the list of (five nearest) reactors Added a warning at startup if the latitude or longitude differs from the setup of your HC3 Replaced the creation of the dots 🟢🟡🔴 to the labels, so no longer for all sensors Added some extra notifications to the labels in case the website is down Extended the http timeout a bit, to give the reverse geocoding some more time to respond Added translations for new functions Version 0.5 (29th October 2022) Added translation to the Reverse API geocoding response (city and country) Changed calculation of the bearings only for the 7 selected sensors, not all sensors Optimized the code and added more structure by using multi file code (main, childs and i18n) Version 0.4 (22nd October 2022) Added six Child devices for the nearest sensor 24h average, 2nd, 3rd, 4th, 5th nearest sensor sample, the nearest sensor maximum sample and the nearest sensor maximum 24h average Added icons based on sensor measurements to all Child Devices Added translations for the labels and properties from English to French, Polish and Dutch. (Thanks to @ppeterr and @fredokl for help with the translation) Limited the details of the response of the Reverse Geocoding with zoom=10 (address detail = city) Version 0.3 (16th October 2022) Added the City and Country also for worst sample and worst average sensors Added all debug information and set the debug levels Optimised the code Version 0.2 (15th October 2022) Added the City and Country for all 5 sensors, not only the first one Version 0.1 (15th October 2022) Initial version Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/radiation_monitor/archive/refs/tags/radiation_monitor-13.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/radiation-monitor How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqa Icons thanks to @Sankotronic
- 88 replies
-
- 6
-
-
-
- radiation
- radiation level
-
(and 3 more)
Tagged with:
-
Hi @m.roszak Is there any update for providing Encryption of Quick Apps? Fibaro have the marketplace All over the wold a marketplace is a place where people buy and sell stuff - but neither is possible at Fibaro Marketplace. In my opinion Fibaro forces professional programmers to share their work for free, with no way to protect their work. I am not a programmer myself, so i pay for other people's work or get it for free from those that grateful provide that. I have paid for the following QA Irobot Roomba, Home connect, Hikvision NVR, Text to speak TTS - and they amazing guys who did those can only beg that people will donate if they choose to share them public. So if the donations is the only way to go, is this ok with Fibaro guidelines posting it at the "Marketplace" with a beg for donations??? I spoke with Roth Nordic and other companies, and they will not provide API information to their systems, if its not possible to protect the API commands. So with Fibaro's missing strategy for protecting QA is blocking for a lot integrations. When do you provide Encryption / remove Edit function of Quick Apps? To anyone else - dont ask me for the QAs - ask Fibaro for a way protecting QA, and I predict they will come soon after. Irobot Boomba HIKVision - creating a binary sensors for all enabled SmartEvents in Hikvision NVR Siemens Home Connect using Bearer token
-
This Quickapp retrieves energy consumption, energy production, gas and water usage from the (P1 Monitor) energy, gas and water meter. This Quickapp uses the software of ztatz.nl to get the values from your smart energymeter. The ztatz plug-and-play software can run on a Raspberry Pi or in a Docker container. The Energy consumption and energy production are added to the HC3 energy panel. Use the child devices Todays Consumption and Todays Production to store energy data (kWh) in the Energy Panel. And use the child devices Consumption and Production for instantaneous power (Watt) in the Energy Panel calculations. Child Devices for: Consumption (Watt) (input for instantaneous power in Energy Panel calculations) Production (Watt) (input for instantaneous power in Energy Panel calculations) Todays Consumption (kWh) (input for energy panel) Todays Production (kWh) (input for energy panel) Waterflow (Liter) Consumption High (kWh) Consumption Low (kWh) Production High (kWh) Production Low (kWh) Consumption L1 (Watt) Consumption L2 (Watt) Consumption L3 (Watt) Production L1 (Watt) Production L2 (Watt) Production L3 (Watt) Ampere L1 (Amp) Ampere L2 (Amp) Ampere L3 (Amp) Voltage L1 (Volt) Voltage L2 (Volt) Voltage L3 (Volt) Total Gas (m³) Total Waterflow (m³) Interval: It is possible to process messages from the smart meter every second. Of course, this is only possible if the smart meter actually sends a message every second. This can be turned on via the ztatz software P1 port configuration page via the "maximum processing speed" option. Note that this gives a higher load on the Rpi (or Docker). It has been tested on the Rpi3/Rpi4 and works well on it. Older or other RPIs have not been tested. The P1 Monitor QuickApp uses 2 API calls each cycle, and if you also use Waterflow, 3 API calls each cycle. With an interval setting of 10 seconds there is an API call every 5 seconds (and with Waterflow enabled, every 3.33 seconds). So the fastest interval setting will probably be 3 seconds with Waterflow and 2 seconds without Waterflow. Ztatz software: https://www.ztatz.nl Docker container based on the ztatz.nl software: The container version has the same functionality as the full version for the Raspberry Pi. Docker container: https://hub.docker.com/r/mclaassen/p1mon I use a Raspberry Pi Smart Meter Cable Starter Kit Raspberry Pi 4 Model B Rev 1.1 2GB 32GB Micro SDHC Smart Meter cable P1 Monitor software from: https://www.ztatz.nl Water Flow Sensor (M18 8mm sensing DC 5V NPN NO LJ18A3-8-Z/BX-5V cylinder inductive proximity sensor switch work voltage 5VDC special for MCU) Version 2.0 (8th January 2023) Changed child device types for optimal support of the Energy Panel: kWh -> com.fibaro.energyMeter ampere/voltage -> com.fibaro.electricMeter Watt -> com.fibaro.powerMeter gas -> com.fibaro.gasMeter water -> com.fibaro.waterMeter Removed Power device calculation Removed child devices for gross consumption and device consumption Changed code to multi file Added for translations for English, French, Polish and Dutch Version 1.6 (8th January 2022) Changed the waterflow algoritme to show more stable and more acurate measurements Small change in the code for checking existance of waterflow sensor Changed the Waterflow unit from Liter to L/min Added experimental net consumption to power Added Lasthour gas to labels Changed the API request for status to json output Version 1.5 (4th September 2021) Support of new Energy Panel: Changed Child device Net Consumption to Main device with type com.fibaro.powerSensor (value can be positive or negative) Added Child device Todays Consumption to show the daily energy consumption in kWh Added Child device Todays Production to show the daily energy production in kWh Changed Child device Consumption High and Low to com.fibaro.energyMeter (kWh in property "value"; "rateType" = consumption). These values will be shown in the new energy panel. Changed Child device Production High and Low to com.fibaro.energyMeter (kWh in property "value"; "rateType" = production). These values will be shown in the new energy panel. Added automaticaly change rateType interface of Child device Consumption High and Low to "consumption" and Production High and Low to "production Changed Child device Consumption and Production to type com.fibaro.powerSensor (Watt) to show power graphs Changed Child device Consumption L1, L2 and L3 and Production L1, L2 and L3 to type com.fibaro.powerSensor (Watt) to show power graphs Additional changes: Added todays Maximum consumption and todays Maximum production and timestamp to the label text and Child device log text Added todays Maximum consumption and todays Maximum production automatic format measurement to W, Kw, MW or GW Added todays Consumption low and high (kWh) and todays Production low and high (kWh) to the label text and Child devices log text Added todays Consumption of gas in the label text and Child device log text Added Timestamp in format dd-mm-yyyy hh:mm:ss to log of Main device and labels Placed production below consumption in the labels Solved bug when Production is higher than Consumption with calculation of Gross Consumption (Gross Consumption = Net Consumption minus or plus Device Consumption) Version 1.4 (11th April 2021) Added Child Devices Waterflow and Total Waterflow Version 1.3 (13th February 2021) Added Child Devices for Voltage L1 L2 L3 Version 1.2 (6th February 2021) Added a lot of Child Device Version 1.1 (18th January 2021) Solved a bug when powerID = 0 Version 1.0 (15th Januari 2021) Changed routine te get Energy Device ID's fast (no more maxNodeID needed) Added "Update Devicelist" button to update the Energy devicelist Added Tarifcode High and Low (and empty for flat fee) Rounded Consumption and Production to zero digits Watt Added Quickapp variable for debug level (1=some, 2=few, 3=all). Recommended default value is 1. Re-aranged the labels Cleaned up some code Version 0.3 (16th August 2020) Added Quickapp variables for easy configuration Added Power Production Changed method of adding QuickApp variables, so they can be edited Tested on P1 Monitor version: 20221105 V2.1.0 Raspberry Pi model: Raspberry Pi 4 Model B Rev 1.1 Linux-5.15.74-v7l+-armv7l-with-glibc2.31 Python version: 3.9.2 QuickApp variables (mandatory, they will be automatically added with the default values): IPaddress = IP address of your P1 monitor interval = Number in seconds, the P1 Monitor normally is updated every 10 seconds, sometimes even faster debugLevel = Number (1=some, 2=few, 3=all) (default = 1) waterMeter = Existance of watermeter true or false (default = false) language = Preferred language (default = en) (supported languages are Engish (en), French (fr), Polish (pl) and Dutch (nl)) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/p1_monitor/archive/refs/tags/p1_monitor_20.zip or Fibaro Marketplace: https://marketplace.fibaro.com/items/p1-monitor How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqa
- 108 replies
-
- 3
-
-
- energy
- power meter
-
(and 8 more)
Tagged with:
-
This QuickApp gets your energy consumption and production data from Tibber Live. This QuickApp can be used in combination with the Tibber Monitor to get the Tibber Prices. Based on the Fibaro WebSockets/GraphQL demo by Peter Gebruers If you use Tibber for your Energy Panel, you can use this Tibber Live QuickApp for your energy consumption and production combined with the Tibber Monitor QuickApp to provide the Energy Panel with the hourly prices. Main device with positive or negative actual power consumption Child devices are available for: power (Actual consumption with maxPower in log text) powerProduction (Actual production with maxPowerProduction in log text) accumulatedConsumption (Todays consumption, also the child device for the Energy Panel) accumulatedProduction (Todays production) accumulatedCost (Todays cost) accumulatedConsumptionLastHour (Consumed since since last hour shift) accumulatedProductionLastHour (Produced since last hour shift) lastMeterConsumption (Total consumption) lastMeterProduction (Total production) voltagePhase1 voltagePhase2 voltagePhase3 currentL1 currentL2 currentL3 Available information: power (Consumption at the moment (Watt)) maxPower (Peak consumption since midnight (Watt)) powerProduction (Net production (A-) at the moment (Watt)) maxPowerProduction (Max net production since midnight (Watt)) accumulatedConsumption (kWh consumed since midnight) accumulatedProduction (net kWh produced since midnight) accumulatedCost (Accumulated cost since midnight; requires active Tibber power deal) currency (Currency of displayed cost; requires active Tibber power deal) lastMeterConsumption (Last meter active import register state (kWh)) lastMeterProduction (Last meter active export register state (kWh)) voltagePhase1 (Voltage on phase 1) * voltagePhase2 (Voltage on phase 2) * voltagePhase3 (Voltage on phase 3) * currentL1 (Current on L1) * currentL2 (Current on L2) * currentL3 (Current on L3) * accumulatedConsumptionLastHour (kWh consumed since since last hour shift) accumulatedProductionLastHour (net kWh produced since last hour shift) accumulatedReward (Accumulated reward since midnight; requires active Tibber power deal) minPower (Min consumption since midnight (Watt)) averagePower (Average consumption since midnight (Watt)) powerReactive (Reactive consumption (Q+) at the moment (kVAr)) * powerProductionReactive (Net reactive production (Q-) at the moment (kVAr)) * minPowerProduction (Min net production since midnight (Watt)) maxPowerProduction (Max net production since midnight (Watt)) powerFactor (Power factor (active power / apparent power)) * signalStrength (Device signal strength (Pulse - dB; Watty - percent)) * timestamp (Timestamp when usage occurred) * on Kaifa and Aidon meters the value is not part of every HAN data frame therefore the value is null at timestamps with second value other than 0, 10, 20, 30, 40, 50. There can be other deviations based on concrete meter firmware. In this QuickApp "null" values are replaced by their previous values. To communicate with the API you need to acquire a OAuth access token and pass this along with every request passed to the server. A Personal Access Token give you access to your data and your data only. This is ideal for DIY people that want to leverage the Tibber platform to extend the smartness of their home. Such a token can be acquired here: https://developer.tibber.com When creating your access token or OAuth client you’ll be asked which scopes you want the access token to be associated with. These scopes tells the API which data and operations the client is allowed to perform on the user’s behalf. The scopes your app requires depend on the type of data it is trying to request. If you for example need access to user information you add the USER scope. If information about the user's homes is needed you add the appropriate HOME scopes. If you have more than one home in your subscription, you need to fill in your home number the change between your homes. If the Tibber server disconnects the webSocket, the QuickApp wil do a re-connect for the amount in the QuickApp variable reconnect. If the re-connect fails for that amount, there will be a timeout for the seconds in the QuickApp variable timeout. Use this QuickApp at your own risk. You are responsible for ensuring that the information provided via this QuickApp do not contain errors. Tibber is a registered trademark being the property of TIBBER. TIBBER reserves all rights to the registered trademarks. Information which is published on TIBBER’s websites belongs to TIBBER or is used with the permission of the rights holder. Making of copies, presentations, distribution, display or any other transfer of the information on the website to the public is, except for strictly private use, prohibited unless done with the consent of TIBBER. Published material on dedicated TIBBER press websites, intended for public use, is exempt from the consent requirement. Also see: https://tibber.com/en/legal-notice Guide Communicating with the Tibber API: https://developer.tibber.com/docs/guides/calling-api Tibber API Explorer: https://developer.tibber.com/explorer Tibber gitHub: https://github.com/tibber Tibber SDK NET: https://github.com/tibber/Tibber.SDK.NET/tree/master/src/Tibber.Sdk Fibaro webSocket manual: https://manuals.fibaro.com/knowledge-base-browse/hc3-quick-apps-websocket-client/ Fibaro Forum - Headers in webSocket: https://forum.fibaro.com/topic/60307-added-support-for-headers-in-websocket-connections-any-documentation WebSocket++ Documentation: https://docs.websocketpp.org GraphQL over WebSocket Protocol: https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md GraphQL query language: https://spec.graphql.org/June2018/#sec-Language Version 3.0 (8th March 2023) Removed Tibber old Websocket code Prepared, not enabled: Check home.features.realTimeConsumptionEnabled has a true value always before reconnecting Prepared, not enabled: Added button to disconnect or re-connect the Tibber webSocket Prepared: Added quickapp variable homeNr (most of the time 1) to be able to check the response realTimeConsumptionEnabled Version 2.3 (beta 8th December 2022) Improved the 60 seconds interval child devices update, it now never skips a beat Added translation for English (en), Dutch (nl), Swedish (se), Norwegian (no) Changed the json response for the debugLevel=4 Offline Simulation mode, the date/time format was wrong Added random (jitter) reconnection handleDisconnected and handleError between 10 and 15 seconds Added random (jitter) reconnection interval handleDisconnected and handleError plus between 1 and 10 seconds Added exponential backoff (increasing delay) between each timeout. The increase is limited to 10 times the value in the quickapp reconnect variable. Version 2.2 (20th November 2022) Changed to new Tibber webSocket requirements, required from December 2022 Version 2.1 (15th October 2022) Child devices are now updated every (whole) minute to reduce CPU load Replaced zero values for Voltage L1 L2 L3 with the previous value Version 2.0 (5th August 2022) Added two child devices, Hourly Consumption and Hourly Production Added re-connect routine to handleError. If an Tibber error occurs, the QuickApp will try to re-connect. Thanks @JcBorgs for testing. Improved routine to handle Tibber null values. Thanks @Darquan for testing. Changed labels a bit to save some space Changed "volt" and "amp" text in the labels. Thanks @Morten22 for mentioning. Changed kWh device types from com.fibaro.electricMeter to com.fibaro.energyMeter Version 1.0 (19th June 2022) Initial webSocket version Tibber Live Thanks @JcBorgs for testing all beta versions and great suggestion to improve the quickapp Based on the Fibaro WebSockets/GraphQL demo by @petergebruers Variables (mandatory and created automatically): token = Authorization token (see the Tibber website: https://developer.tibber.com) homeId = Tibber Home ID (see the Tibber website: https://developer.tibber.com) homeNr = Tibber home (nodes) number if you have more than one home (default = 1) language = Preferred language (default = en) (supported languages are English (en), Swedisch (se), Norwegian (no) and Dutch (nl)) reconnect = Amount of re-connects after disconnect from Tibber server (default = 10) timeout = Pause after maximum amount of re-connects (default = 300 seconds) debugLevel = Number (1=some, 2=few, 3=all, 4=Offline Simulation Mode, 5=Live Test Mode) (default = 1) Fibaro Firmware: Minimal version 5.111.48 (beta) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/tibber_live/archive/refs/tags/tibber-live-30.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/tibber-live How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqa
- 60 replies
-
- 7
-
-
-
QA for creating HomeTable in global variables in HC3. Why using hometable? Instalation: 1. upload this QA 2. In QA variables you can change name for hometable, name for scenes and time for regular update of hometable 3. In QA -> source files -> ManualData you can add your own data (it will be also saved in final hometable in global variables) How to read data from hometable: -- in case that your name for hometable is default=HomeTable local tbl = fibaro.getGlobalVariable("HomeTable") local HT = json.decode(tbl) -- structure for devices is <room>.<deviceName> local idQA_TV=HT.LivingRoom.TV -- structure for scenes is <ScenesName>.<sceneName> -- default value for <ScenesName> is Scenes local idSc_Lights=HT.Scenes.Lights -- structure for your own inputs from ManualData local myValue1=HT.myData1.myNameValue1 -- 0 local myValue2=HT.myData1.myNameValue2 -- "default value" Names for rooms, devices and scenes are corrected by following replaces: {["%."]="",["-"]="",["%("]="",["%)"]="",["&"]="",[":"]="",["%["]="",["%]"]="",["%+"]="",["%%"]="",["%/"]="",["%$"]=""} {["Á"]="A",["Ä"]="A",["Ą"]="A",["À"]="A",["Â"]="A",["Č"]="C",["Ć"]="C",["Ç"]="C",["Ď"]="D",["É"]="E",["Ě"]="E",["Ë"]="E",["Ę"]="E",["È"]="E",["Ê"]="E",["Í"]="I",["Ï"]="I",["Î"]="I",["Ĺ"]="L",["Ľ"]="L",["Ł"]="L",["Ň"]="N",["Ń"]="N",["Ó"]="O",["Ô"]="O",["Ö"]="O",["Ő"]="O",["Œ"]="O",["Ŕ"]="R",["Ř"]="R", ["Š"]="S",["Ś"]="S",["Ť"]="T",["Ú"]="U",["Ů"]="U",["Ü"]="U",["Ű"]="U",["Ù"]="U",["Û"]="U",["Ý"]="Y",["Ÿ"]="Y",["Ž"]="Z",["Ż"]="Z",["Ź"]="Z",["á"]="a",["ä"]="a",["ą"]="a",["à"]="a",["â"]="a",["č"]="c",["ć"]="c",["ç"]="c",["ď"]="d",["é"]="e",["ě"]="e",["ë"]="e",["ę"]="e",["è"]="e",["ê"]="e",["í"]="i",["ï"]="i",["î"]="i",["ĺ"]="l",["ľ"]="l",["ł"]="l",["ň"]="n",["ń"]="n",["ó"]="o",["ö"]="o",["ô"]="o",["ő"]="o",["œ"]="o",["ř"]="r",["ŕ"]="r",["š"]="s",["ś"]="s",["ť"]="t",["ú"]="u",["ů"]="u",["ü"]="u",["ű"]="u",["ù"]="u",["û"]="u",["ý"]="y",["ÿ"]="y",["ž"]="z",["ż"]="z",["ź"]="z"} Hometable in global variables will be overwrite only if newly generated hometable will be different. Version of QA HomeTable: 0.12 - 21.1.2021 HomeTable.fqa
-
So I have been working on integrating my ceiling fan & light into my HC3 hub. I want to treat the fan control as a device and the light control as a device. But the problem is that I need buttons and sliders for user interaction. I get that the focus is primarily on z-wave integration but it is very shortsighted to imagine that everything the user installs in his/her Smart Home will be z-wave enabled. Furthermore, it seems that Fibaro does not have much market share in the United States. Consequently we are left in the dust having to integrate our devices ourselves. The Fibaro tech support seems very non-responsive to its community of owners and simply patches bugs without sharing new and updated features. For example, I noticed there is a new thermostat UI that appeared recently. Or at least I did not see it before a certain recent FW update. I presume it was made available because Fibaro needed it to sell their own thermostat device. Truly, I love my hub. The use of a web interface is far superior to using a smart phone app, IMHO. And, if I cannot easily find a z-wave enabled device, I can create or help someone else create a device handler for this device. I use and enjoy my Alexa but home automation is far more than telling Alexa to turn on my lights. And why should I rely on an internet device for more sophisticated control strategies? Right now my z-wave continues to operate even when my ISP goes offline. My ceiling fan will rely on my WiFi operating but it does not have to go to the cloud to be controlled. Only my Nest Thermostat will lose connection to my hub when my internet goes offline. When the time (and money) comes, I will replace it with something z-wave or maybe WiFi but not cloud controlled. I think the biggest takeaway from this rant is that there needs to be a means to create custom UIs for child devices. An added bonus would be a few different control objects. Things like a select box, a multi-select box, a check box (or something that looks like a pushbutton?), ways to group things (a container) or a means to draw a line between sections. Granted that images may be memory hogs so adding a bunch of icons or other small pictures would be memory intensive but small icons that could be added to a global list in the device might mitigate some of that. It seems that many of these structures are integral to the HTML world and a part of the web client. We just need a way to safely use them in the UI. Also, a comprehensive list of Lua methods that we can use along with simple descriptions of their use. Fibaro relies too heavily on its community so leverage that community to learn and share their knowledge on use. Fibaro need not shy away from providing this list because they don't want to write extensive descriptions of each and every method. Reward your faithful users with better tools to take advantage of your systems and you may be rewarded with an increase in sales. You could think of it as hiring a huge team of unpaid integrators who develop creative ways to solve problems. I was impressed with one user who described his sophisticated solution to control his home energy use based on the hourly electric rates that his utility company makes available each day. We don't have that need in North America (yet) but I am aware of a niche market that could be tapped for remote locations who exist off-grid and use solar energy exclusively. Thank you for your time in reading this. I feel better having expressed myself even though I figure this will be ignored or looked at as impractical. Have a great day (or night). Peter
- 9 replies
-
- quickapp
- quickappchild
-
(and 3 more)
Tagged with:
-
Witam, szukam odpowiedzi na uważam dość szczegółowe pytanie dotyczące QuickApp. Otóż postawiłem sobie cel by z pomocą QuickApp "Termostat auto" zrobić sterowanie prędkością wentylatora od klimatyzacji. W termostacie MCO Home MH8-FC spotkałem się z czymś takim że ma on taką wbudowaną opcję w interface służącą do tego, dodatkowo ma też sekcję pokazującą w jaki jest stan jego pracy, wygląda to tak: Zależy mi na tym żeby stworzyć QuickApp, który też będzie miał te dwie sekcje, chodzi o to żeby nie tworzyć tego ręcznie za pomocą kontrolek i etykiet.
-
This QuickApp gets extra information from your SolarEdge managed Solar Panels to give you the most insight of your SolarEdge installation. Site Details: Site details, such as name, location, status, etc. Site Overview: Site overview data. Inventory: Inventory of SolarEdge equipment in the site, including inverters/SMIs, batteries, meters, gateways and sensors. Inverter Technical Data: Return specific inverter data for a given timeframe. Site Power: Site power measurements in 15 minutes resolution. Site Energy: Site energy measurements in 15 minutes resolution. Site Environmental Benefits: All environmental benefits based on site energy production: CO2 emissions saved, equivalent trees planted, and light bulbs powered for a day. Use of the monitoring server API is subject to a query limit of 300 requests for a specific account token and a parallel query limit of 300 requests for each specific site ID from the same source IP. The monitoring server API allows up to 3 concurrent API calls from the same source IP. Any additional concurrent calls will return HTTP 429 error – too many requests. See API documentation on https://www.solaredge.com/sites/default/files/se_monitoring_api.pdf Site Details: id – the siteID name – the site name account id – the account this site belongs to status – the site status (see Site Status on page 53) peak power – site peak power currency - e.g. EUR installationDate – site installation date (format: yyyy-MM-DD hh:mm:ss ) ptoDate – permission to operate date notes type – site type location: country state city address secondary address zip time zone alertQuantity - number of open alerts in this site * alertSeverity – the highest alert severity in this site * publicSettings: isPublic - if this site is public (true or false) public name - name * Alert information is only available when using an API_KEY generated by an account. API_KEY generated at the site level does not return this information. Inventory: Inverter name – the inverter name e.g. Inverter 1 manufacturer – manufacturer name (SolarEdge) model name e.g. SE16K Firmware version e.g. 2.52.311 communicationMethod – the communication interface used to connect to server. e.g.: Ethernet or WIFI. serialNumber – the equipment serial number e.g.: 7F123456-00 connectedOptimizers – number of optimizers connected to the inverter Meters name – the inverter name e.g. “FeedInMeter” Manufacturer – e.g. “WattNode” Model – meter model number SN – serial number (if applicable) Type – metertype, e.g. “Production” Firmware Version (if applicable) Connected To – Name of SolarEdge device the meter is connected to connectedSolaredgeDeviceSN – serial number of the inverter/gateway the meter is connected to form – physical for a HW meter or virtual if calculated by arithmetic between other meters Sensors (Irradiance/wind/temperature sensors) connectedSolaredgeDeviceSN – the S/N of the device it is connected to e.g. 12345678-00 Id – e.g. “SensorDirectIrradiance” connectedTo – name of the device it is connected to e.g. “Gateway 1” Category – e.g.IRRADIANCE Type – e.g. “Plane of array irradiance” Gateways name – the inverter name e.g. Inverter 1 serialNumber – the equipment serialnumber e.g. 7F123456-00 Firmwareversion Batteries Name SerialNumber Manufacturer - the battery manufacturer name Model - the battery model name Nameplate capacity - the nameplate capacity of the battery as provided by the manufacturer Firmwareversion ConnectedTo – Name of SolarEdge device the battery is connected to connectedSolaredgeDeviceSN – serial number of the inverter/gateway the battery is connected to Interver Technical data: timestamp AC current (divided per phase) AC voltage (divided per phase) AC frequency (divided per phase) QRef (divided per phase) CosPhi (divided per phase) TotalActivePower apparentPower - Supported starting communication board version 2.474 activePower - Supported starting communication board version 2.474 reactivePower DC voltage groundFaultResistance powerLimit % Lifetime energy - Supported starting communication board version 2.474 totalEnergy temperature - Celsius inverterMode SLEEPING – night mode STARTING – pre-production MPPT – production THROTTLED – Forced power reduction SHUTTING_DOWN – Shutdown procedure FAULT – error mode STANDBY – maintenance LOCKED_STDBY – standby mode lock LOCKED_FIRE_FIGHTERS – firefighters lock mode LOCKED_FORCE_SHUTDOWN – forced shutdown from server LOCKED_COMM_TIMEOUT – communication timeout LOCKED_INV_TRIP – inverter self-lock trip LOCKED_INV_ARC_DETECTED – inverter self-lock on arc detection LOCKED_DG – inverter lock due to DG mode enable LOCKED_PHASE_BALANCER – inverter lock due to phase imbalance (1ph, Australia only) LOCKED_PRE_COMMISSIONING – inverter lock due to pre-commissioning LOCKED_INTERNAL – inverter lock due to an undisclosed internal reason operationMode 0 – On-grid 1 – Operating in off-grid mode using PV or battery 2 - Operating in off-grid mode with generator (e.g. diesel) is present apparentPower - VA (divided per phase) activePower - VA (divided per phase) reactivePower - VAR (divided per phase) cosPhi (divided per phase) vL1ToN - 1ph only vL2ToN - 1ph only vL1To2 - 3ph only vL2To3 - 3ph only vL3To1 - 3ph only Environmental Benefits: CO2 - quantity of CO2 emissions that would have been generated by an equivalent fossil fuel system SO2 - quantity of SO2 emissions that would have been generated by an equivalent fossil fuel system NOX - quantity of NOX emissions that would have been generated by an equivalent fossil fuel system treesPlanted - equivalent planting of new trees for reducing CO2 levels lightBulbs - number of light bulbs that could have been powered by the site for a day Site Power Detailed: timeUnit - the time unit (QUARTER_OF_AN_HOUR) unit - the measurement units (e.g. Watt) type - i.e. Production, Consumption, SelfConsumption, FeedIn (export) or Purchased (import) date - date and time value - power in Watt at that time of the day Site Energy Detailed: timeUnit - the time unit (QUARTER_OF_AN_HOUR) unit - the measurement units (e.g. Wh) type - i.e. Production, Consumption, SelfConsumption, FeedIn (export) or Purchased (import) date - date and time value - power in Wh at that time of the day Overview: id currentPower lastDayData energy lastDayData revenue lastMonthData energy lastMonthData revenue lastYearData energy lastYearData revenue lifeTimeData energy lifeTimeData revenue lastUpdateTime Changes version 0.1 (25th June 2023) - First (development) version Variables (mandatory and created automatically): - siteID = Site ID of your SolarEdge Inverter (see your Inverter Site Details) - apiKey = API key of your SolarEdge Inverter (contact your installer if you don't have one) - serialNumber = Short serialNumer of your SolarEdge Inverter (see your Inverter Inventory Details) - language = Preferred language (default = English (en)) - debugLevel = Number (1=some, 2=few, 3=all, 4=simulation mode) (default = 1) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/solaredge_extra/archive/refs/tags/solaredge_extra-01.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/solaredge-extra How to install: Open the Configuration Interface Go to Settings > Devices Click + Choose Other Device Choose Upload File Choose file from your computer with .fqax
- 4 replies
-
- 2
-
-
- solarenergy
- solaredge
-
(and 2 more)
Tagged with:
-
What I normally do is to have a QuickApp for a particular function. For example Blinds_Controller, Gate_Controller or Bathroom_Controller. Where all the business logic is inside the QA. Then other scenes or users or Alexa just press the buttons in the QA to execute something. A few of the Logic examples in the Blinds Controller Will not open a blind in the Movie Room if someone is watching a movie. Will not close the blinds at night if there is a storm forecast, in case we lose power and cant activate them next morning Will not close blinds on Doors or Windows if they are open/ajar This way, I don't have to replicate the logic everywhere. BTW, there is an override button for the user, so they can bypass the restrictions if so desired. For some of the logic, it would be nice to know if a user pressed the button or a scene. I see this in the logs, but there is nothing there. Can I determine if a user or a scene pressed a button What is the "values":[null] in the event. [2023-06-05] [01:00:05] [TRACE] [QA-GATE]: UIEvent: {"eventType":"onReleased","values":[null],"elementName":"bnt_Lock","deviceId":1757}
-
I made the mistake of buying the wrong model of the Nice Gate controller - it doesnt interface with Fibaro. It only has one input, the rest are coded. To make everything work I have cannibalized one remote and attached it to a raspberry pi with relays. This is working fine. But the QA on Yubii seems to crash when being used, and I have to go back and open the QA again. I suspect that I should be creating the HTTPClient class when required instead of creating it at startup. If so, I don't know how to free it when done. --[[Gate Controller Written by Rohit Gupta No copyright, use freely Versions 3.00 20230505 Created for HC3 --]] __TAG = 'GATE' local Lock = 0955 local Bool = {[false]='LOCKED', [true]='UNLOCKED'} GOpen = '/gate/open' GClose = '/gate/close' GPed = '/gate/pedestrian' -- These show messages conditional on flags and in colour in the Log function Error (Msg) end function Debug (Msg) end function Warning (Msg) end function Trace (Msg) end function Status (Msg) end function Device_State (Device) return fibaro.get (Device, 'value') end function Turn_Device_On (Device) fibaro.call (Device, "turnOn") end function Turn_Device_Off (Device) fibaro.call (Device, "turnOff") end function QuickApp.Show_Gate_Status (Msg) self:updateView ('lblStatus', 'text', Msg) end function QuickApp:Show_Lock_Status () local State = Device_State (Lock) self:updateView ('lbl_Lock', 'text', 'External Access = '..Bool[State]) end function QuickApp:Post (Param, Action) Status (Action) self.Http:request(self.Address..Param, { options = {data = 'text', method = 'POST'}, success = function(response) Update (Action) self.Posted = true Debug ('response:'..response.status) end, error = function(message) Show_Gate_Status (Action..' '..message) self:updateProperty ('value', Action == 'Open') Debug ('error:', message) end}) end function QuickApp:onOpen () Update_Gate_Status ('Opening') self:Post (GOpen, 'Open') end function QuickApp:onClose () Update_Gate_Status ('Closing') self:Post (GClose, 'Close') end function QuickApp:onPed () Update_Gate_Status ('Pedestrian') self:Post (GPed, 'Pedestrian') end function QuickApp:onLock () Turn_Device_On (Lock) self:Show_Lock_Status () end function QuickApp:onUnlock () Turn_Device_Off (Lock) self:Show_Lock_Status () end function QuickApp:onInit() Status ('Started') self.Address = self:getVariable("Address") Status (self.Address) self.Http = net.HTTPClient () self:Show_Lock_Status () end Lock/Unlock address a separate Fibaro relay that kills power to the Gate Controller. The interface has 5 buttons - Open, Close, Pedestrian, Lock and Unlock. And there is only one variable Address which is the ipaddress of the Pi. What have I stuffed up ?
-
In the past I have used fibaro.sleep. As I am migrating from HC2 to HC3, I have started using setInterval. People seem to insist it is better, even though it destroys the readability of the code. I am finding that it doesn't always work. Sometimes it does not wait at all. Here Loop_Secs is 15, and it shows that in the log. Sometimes it works for two iterations and then just does not wait. At other times, it does not wait at all. While I was building it up and Main was empty, it was whizzing so fast, I could not get in from the browser and had to restart the HC. What am I missing ? function QuickApp:Loop () self:Main () Debug ('Waiting for '..Loop_Secs..' secs') setInterval (self:Loop(), Loop_Secs*1000) end
-
Hey Is any one has solution for controlling QA with alexa voice command i build quick apps for my devices as binary switch so i can control them from alexa to turn on/off only but nothing else i want to be able to control and set all option and buttons i created in QA, I can't find any solutions
- 4 replies
-
- quickapp
- alexa voice control
-
(and 2 more)
Tagged with: