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'.
-
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...
-
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 ?
-
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.com 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
- 104 replies
-
- 3
-
-
Tiny QuickApp Emulator (TQAE) started out as a simple modular QuickApp emulator but have evolved into a pretty good development environment. (Great intro to TQAE <here> from @Joep - thanks!) /TQAE.lua v0.57 -- 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
-
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:
-
Hi, I currently have my hc3 setup with the quickapp p1 meter for house energy metering and made my own quickapp for metering the solarpanels. I used most of the code from the p1 quickapp to make sure it would work simply because I am not a coding wizard sadly :). I started running my quickapp and it worked like a charm, except for the energy panel aspect. I was producing megawatt houres of energy... The consumption also was acting up wierd at the same time. The child app resposible for reading the kwh data from the Growatt inverter is setup as an energyMeter like this: {name="Zon productie vandaag", className="ProductionToday", type="com.fibaro.energyMeter"} some more code of this child: class 'ProductionToday'(QuickAppChild) function ProductionToday:__init(device) QuickAppChild.__init(self, device) self:updateProperty("rateType", "production") end function ProductionToday:updateValue(devicedata) self:updateProperty("value", tonumber(devicedata.epvtotal)) --tonumber(devicedata.epvtotal) self:updateProperty("unit", "kWh") self:updateProperty("log", devicedata.update_timestamp) end When I noticed it starting to register megawatts I removed the line of code responsible for saving the data. self:updateProperty("storeEnergyData", true) While coding this quickapp I came across multiple "special" ways of fibaro to register certain types of data. My question now is, how does fibaro read this kwh data and process 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
- 57 replies
-
This Quickapp retrieves energy consumption, energy production and gas usage from the Toon Energy meter version 1 or 2. This QuickApp has Child Devices for Consumption (Watt), Production (Watt), Consumption High (kWh), Consumption Low (kWh), Production High (kWh), Production Low (kWh), Production Actual (Watt), Gas Usage (l/h) and Total Gas (m³) The Energy Usage from the Child devices Consumption High, Consumption Low, Production High and Production Low can be used for the HC3 Energy Panel Your Toon Energy Meter needs to be rooted, see: https://github.com/JackV2020/Root-A-Toon-USB-Stick. This is the recommended all in one solution with a one time boot from USB stick, 10 minutes of work and done. After rooting you don't need a subscription anymore and you have access to a ToonStore with a growing number of apps. For more technical people there is a possibility to ssh into the Toon if they want with username root and password toon. Rooting is at your own risk, look here for further support and info: See also: https://github.com/ToonSoftwareCollective/Root-A-Toon (if you already have a running Linux environment) See also: https://toonforum.nl/ See also: https://www.domoticaforum.eu/ Version 2.0 (22th April 2023) Changed to multifile Changed powerSensor to powerMeter and multiSensor to gasMeter Added translation for English and Dutch Added support for Toon version 2v6 (for example firmware version V5.49.19) Added support for Toon version 2v5 Added support for Toon version 2v4 Added support for Toon version 2v3 Improved debug messages Version 1.3 (20th February 2022) Solved issue with "NaN" responses or other bad responses from Toon Energy Added child device voor actual solar production Version 1.2 (27th December 2021) Solved code error with toonVersion Version 1.1 (27th December 2021) Added support for Toon version 1 Added Simulation notice in labels Version 1.0 (3th October 2021) Ready for download Version 0.2 (30th September 2021) Gas from m³/h to l/h Splashed a bug Version 0.1 (29th September 2021) Initial version Variables (mandatory): IPaddress = IP address of your Toon Meter toonVersion = Version 1 or 2 (default) Interval = Number in seconds 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/toon_energy/archive/refs/tags/toon_energy-20.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/toon-energy 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
- 24 replies
-
- 2
-
-
-
- toon from eneco
- download
- (and 5 more)
-
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
-
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
- 59 replies
-
- 6
-
-
-
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() )
-
Integracja Fibaro HC3 QuickAPP z ESP8266 Cześć, nie znalazłem nigdzie działającej integracji hc3 quickapp i esp8266, więc postanowiłem sam taką stworzyć. Instalacja Instalujemy ESPEASY po szczegóły odsyłam na https://www.letscontrolit.com/wiki/index.php/ESPEasy Konfigurujemy połączenie Wi-Fi do naszej sieci domowej Na routerze musimy zarezerwować adres IP który dostało ESP8266 Dodajemy QuickAPP: -> -> -> Wskazujemy plik z załącznika ESP8266_Przekaznik.fqa W zakładce zmienne edytujemy adres IP urządzenia oraz pin na którym znajduje się przekaźnik Jak działa kod Po otwarciu strony http://adresip/control?cmd=GPIO,0,1 zmienia się stan na naszym pinie Kod napisałem w ten sposób, że LUA analizuje zwrotny kod JSON z ESP8266 przez co mamy potwierdzenie że polecenie włączenia lub wyłączenia zostało wykonane. ESP8266_Przekaznik.fqa
-
Hi, I already found lots of LUA scripts and other "inserts" for Bose Soundtouch but I can't find anything that works on HC3. Is someone already working on a QuickApp or some kind of VD for the Bose Soundtouch ? I don't have the proper skills to make something myself and I would love to integrate my Bose …. Thank you
-
I have seen somewhere in documentation a reference to some garage door openers. But when I look in swagger for the device in the /devices/hierarchy listing there is no entry. So my question is this, is there a mechanism to create a new device type? There probably isn't much to change and it could be built on an existing device type, I expect. I envision having four states (open, close, opening, closing) as well as an error state of some sort. I would also prefer to tell Alexa or Google Assistant or Siri to "Open the garage" not "Turn on the garage" but that may be asking a bit much, I fear. I will say that having taken the plunge into this adventure I am starting to understand things better. @jgab's TQAE has helped immensely. Thank you @jgab. Further, the tutorials that he has put on here are very helpful. I grow a bit frustrated that there are no "official" references for QAs and I haven't found a good way to find the relevant information quickly. Someday, when I grow up, I hope to be just like @jgab 😁 Thanks for any guidance on the above. PeterV959
-
This QuickApp monitors your Solax managed Solar Panels The QuickApp has (child) devices for Solarpower/m², Today production, Total production, Total Power to Grid, Total Energy to Grid, Energy from Grid, Total Power/m², Battery Energy, AC Power R, AC Power S, AC Power T, Battery Power, Power DC1, Power DC2, Power DC3 and Power DC4 The rateType interface of child device Today Energy is automatically set to "production" The readings from the child device Today Energy will be shown in the new energy panel The readings from the child device Total Energy is automatically set to the right Wh unit (Wh, kWh, MWh or GWh) See API documentation on https://www.eu.solaxcloud.com/phoebus/resource/files/userGuide/Solax_API_for_End-user_V1.0.pdf User can get a specific range of information through the granted tokenID. Please obtain your tokenID on the API page of Solaxcloud for free. The tokenID can be used to obtain real-time data of your inverter system. The obtain frequency need to be lower than 10 times/min and 10,000 times/day. Version 3.0 (19th February 2023) Changed the descriptions of the Solax Cloud values Converted the feedinpower value from positive to negative or from negative to positive Added translation for English, Dutch and Portugese Added child device for consumeenergy Version 2.1 (4th December 2022) Prevented almost empty responses like these: {"success":false,"exception":"Query success!","result":"this sn did not access!"} Added log text to main device if no data from Solax Cloud Version 2.0 (16th April 2022) Added Child Devices for feedinpower, feedinenergy, consumeenergy, feedinpowerM2, soc, peps1, peps2, peps3, batPower, powerdc1, powerdc2, powerdc3, powerdc4 Added all values returned from the Solax Cloud to the labels Changed all the device types to the most current ones Changed the handling of bad responses from the Solax Cloud Replaced null values in responses with 0.0 Optimized some code Version 1.0 (17th November 2021) Tested, ready for release Version 0.2 (15th November 2021) Changed json response Version 0.1 (13th November 2021) First (test) version Variables (mandatory): tokenId = token ID of your Solax Inverter, obtain your tokenID on the API page of Solaxcloud for free inverterSN = Unique identifier (Serial No.) of your Solax inverter solarM2 = The amount of m2 Solar Panels (use . for decimals) for calculating Solar Power m² (default = 0) interval = The default is 300 seconds (5 minutes), the daily API limitation is maximum 10 times/min and 10,000 times/day debugLevel = Number (1=some, 2=few, 3=all, 4=simulation mode) (default = 1) API items: Description (Accuracy) (Unit) inverterSN: Unique identifier of inverter (Serial No.) sn: Unique identifier of communication module (Registration No.) acpower: Inverter.AC.power.total (1) (W) yieldtoday: Inverter.AC.energy.out.daily (0.1) (KWh) yieldtotal: Inverter.AC.energy.out.total (0.1) (KWh) feedinpower: Grid.power.total (1) (W) feedinenergy: Grid.energy.toGrid.total (0.01) (KWh) consumeenergy: Grid.energy.fromGrid.total (0.01) (KWh) feedinpowerM2: Inverter.Meter2.AC.power.total (1) (W) soc: inverter.DC.battery.energy.SOC (1) (%) peps1: Inverter.AC.EPS.power.R (1) (W) peps2: Inverter.AC.EPS.power.S (1) (W) peps3: Inverter.AC.EPS.power.T (1) (W) inverterType: Inverter type, details refer to Table 4 in appendix inverterStatus: Inverter status, details refer to Table 5 in appendix uploadTime: Update time (format 2016-10-26 17:33:01) batPower: Inverter.DC.Battery.power.total (1) (W) powerdc1: Inverter.DC.PV.power.MPPT1 (1) (W) powerdc2: Inverter.DC.PV.power.MPPT2 (1) (W) powerdc3: Inverter.DC.PV.power.MPPT3 (1) (W) powerdc4: Inverter.DC.PV.power.MPPT4 (1) (W) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/solax_monitor/archive/refs/tags/solax-monitor-30.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/solax-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
- 49 replies
-
- 1
-
-
Error 403 on QuickApp http request
edouardc posted a question in Other Devices / Third-party devices
Hi Team, I try to develop some QuickApp on my HC3, but I have an problem with the http request : When I call an API (here switchbot api), the external API respond me an 403 error... The probleme isn't the API because the same request with an little php script works... I have tried much methods but I get only the response code 403. Recently, I have downloaded an quickapp on the marketplace. All review on it are good but for me, it's doesn't work. When I see the console logs, I can see the 403 error code from this downloaded QuickApp too. Do you have an idea for my problem ? You can find my function code here : function QuickApp:GetDeviceList() self.http = net.HTTPClient({timeout=10*1000}) local apikey = self:getVariable("apikey"); self:debug(apikey); --For debug an my token is successfuly loaded local address = "https://api.switch-bot.com/v1.0/devices" --local address = "http://10.0.10.10:1880/debug" self.http:request(address, { options = { headers = { ["Authorization"] = apikey, ["Content-Type"] = "application/json; charset=utf8", ["Accept"] = "application/json", ["User-agent"] = "Mozilla/5.0" --For try but no change }, checkCertificate = false, method = 'POST' }, success = function(response) self:debug(response.status); --return : 403 self:debug(response.data); --return: nothing self:debug(response.headers);--return: array self:debug(message); --return: nil end, }); end -
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. [email protected] 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: [email protected] 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 [email protected] 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.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-12.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
- 80 replies
-
- 6
-
-
-
- quickapp
- [email protected]
-
(and 3 more)
Tagged with:
-
The QuickApp Air Quality OpenWeatherMap provides the current and forecast measurements for your location on Air Quality. Besides basic Air Quality Index the QuickApp provides also data about polluting gases such as Carbon monoxide (CO), Nitrogen monoxide (NO), Nitrogen dioxide (NO2), Ozone (O3), Sulphur dioxide (SO2), Ammonia (NH3), and particulates (PM2.5 and PM10). This QuickApp has Child Devices for Carbon monoxide (CO), Nitrogen monoxide (NO), Nitrogen dioxide (NO2), Ozone (O3), Sulphur dioxide (SO2), Ammonia (NH3), PM2.5 and PM10 for current measurement. This QuickApp has also Child Devices for Air Quality Index, Carbon monoxide (CO), Nitrogen monoxide (NO), Nitrogen dioxide (NO2), Ozone (O3), Sulphur dioxide (SO2), Ammonia (NH3), PM2.5 and PM10 for forecast measurement. This QuickApp has Child Devices for Carbon monoxide (CO), Nitrogen monoxide (NO), Nitrogen dioxide (NO2), Ozone (O3), Sulphur dioxide (SO2), Ammonia (NH3), PM2.5 and PM10. Common Air Quality Index (CAQI) The Common Air Quality Index (CAQI) is an air quality index used in Europe since 2006. In November 2017, the European Environment Agency announced the European Air Quality Index (EAQI) and started encouraging its use on websites and for other ways of informing the public about air quality. As of 2012, the EU-supported project CiteairII argued that the CAQI had been evaluated on a "large set" of data, and described the CAQI's motivation and definition. CiteairII stated that having an air quality index that would be easy to present to the general public was a major motivation, leaving aside the more complex question of a health-based index, which would require, for example, effects of combined levels of different pollutants. The main aim of the CAQI was to have an index that would encourage wide comparison across the EU, without replacing local indices. CiteairII stated that the "main goal of the CAQI is not to warn people for possible adverse health effects of poor air quality but to attract their attention to urban air pollution and its main source (traffic) and help them decrease their exposure." The CAQI is a number on a scale from 1 to 100, where a low value means good air quality and a high value means bad air quality. The index is defined in both hourly and daily versions, and separately near roads (a "roadside" or "traffic" index) or away from roads (a "background" index). As of 2012, the CAQI had two mandatory components for the roadside index, NO2 and PM10, and three mandatory components for the background index, NO2, PM10 and O3. It also included optional pollutants PM2.5, CO and SO2. A "sub-index" is calculated for each of the mandatory (and optional if available) components. The CAQI is defined as the sub-index that represents the worst quality among those components. Here is a description of Air Quality index levels Pollutant concentration in μg/m3: Index NO2 PM10 O3 PM25 (optional) Good 1 0-50 0-25 0-60 0-15 Fair 2 50-100 25-50 60-120 15-30 Moderate 3 100-200 50-90 120-180 30-55 Poor 4 200-400 90-180 180-240 55-110 Very Poor 5 >400 >180 >240 >110 See more on CAQI: https://en.wikipedia.org/wiki/Air_quality_index IMPORTANT You need an API key from https://home.openweathermap.org The API is free up to 60 calls per minute Version 1.1 (10th November 2022) Added extra check for partly empty response ("coord" not empty but "list" is empty) Added extra message to the labels and de log text if there is no response Warning added in case the "forecast measurements" are not available Version 1.0 (7th November 2021) Added forecast measurements with hours you want your forecast. The forecast is shown in child devices and labels for all measurements. Version 0.1 (9th October 2021) Initial version Variables (mandatory): apiKey = Get your free API key from https://home.openweathermap.org latitude = latitude of your location (Default is the latitude of your HC3) longitude = longitude of your location (Default is the longitude of your HC3) 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) Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/air_quality_openweathermap/archive/refs/tags/air_quality_owm-11.zip or from the Fibaro Marketplace: https://marketplace.fibaro.com/items/air-quality-openweathermap 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
- 17 replies
-
- 6
-
-
-
- air quality data
- air quality
-
(and 3 more)
Tagged with:
-
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.
-
This is a Quickapp script for HC3. I am trying to get this to work in a VD on HC2. Is it possible, or do I have to do it together with a scene to make it work? Can anyone help? function QuickApp:onInit() self:updateProperty("unit", "kr/kWh") self.refresh = 60 -- in seconds local function loop() self:webrequest(); setTimeout(loop,self.refresh * 1000) end if self.username ~= "changeme" then loop() end end function QuickApp:webrequest() local tid = os.date("%R") local minutt = os.date("%M") --OPPDATERER STRØMPRIS OG SNITT HVER TIME if (minutt == "00") then self:OppdaterPris(); self:OppdaterSnitt(); end end function QuickApp:OppdaterPris() --Opprette lokale variable local GammelStrompris = fibaro.get(126,"value") local NyStrompris --Definerer http local http = net.HTTPClient(); --Definerer strengen Payload til å være kommando til tibber local payload = '{"query": "{viewer {homes {currentSubscription{priceInfo{current{total}}}}}}", "variables": null, "operationName": null}'; --API.POST til Tibber-- http : request('https://api.tibber.com/v1-beta/gql', { options = { method = "POST", headers = { ['Authorization'] = '.........', --Min Tibber ID her. ['Content-Type'] = 'application/json' }, data = payload -- Query. }, success = function(response) --fibaro.debug (response.data) --Verifiser at en har fått response.data. Dette er data som en har fått fra Tibber local data = json.decode(response.data); --fjernet local under??? NyStrompris = json.encode(data.data.viewer.homes[1].currentSubscription.priceInfo.current.total); self:updateProperty("value", tonumber(NyStrompris)) --print("OK") end, error = function(err) fibaro.debug ("Error:" .. err) end }); end function QuickApp:OppdaterSnitt() --Definerer http local http = net.HTTPClient(); --Definerer strengen average til å være kommando til tibber local average = '{"query": "{viewer {homes {currentSubscription{priceRating{daily{entries{total}}}}}}}", "variables": null, "operationName": null}'; --API.POST Til Tibber http : request ('https://api.tibber.com/v1-beta/gql', { options = { method = "POST", headers = { ['Authorization'] = '...............', --Min Tibber ID her. ['Content-Type'] = 'application/json' }, data = average -- Query }, success = function(response) --fibaro.debug(response.data) --Verifiser at en har fått response.data. Dette er data som en har fått fra Tibber local data = json.decode(response.data); local Nypris = tostring(json.encode(data.data.viewer.homes[1].currentSubscription.priceRating.daily.entries[31].total)); self:updateProperty("log", tostring(Nypris)) end, } ) end
-
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 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.
- 61 replies
-
- 3
-
-
-
This QuickApp reads the PM2.5, PM10, Temperature, Humidity and Airpressure values directly from a sensor somewhere in this world That sensor doesn't have to be your own sensor, any sensor can be used, just find one in your neighborhood For locating the sensor(ID's) in your neighborhood see: https://sensor.community/en/ Select two (!) SensorID's, one for PM2.5 and PM10 values and one for Temperature, Humidity and Airpressure values The PM2.5, PM10, Temperature, Humidity, Absolute Humidity and Airpressure readings are stored in the value of six (child) devices, so you can read the value from your own scenes This QuickApp will send notifications when PM2.5 or PM10 readings reach a breakpoint (if userID ~= 0) 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) See also https://luftdaten.info See also for CVS files: https://archive.luftdaten.info See also https://github.com/opendata-stuttgart/ API documentation: https://github.com/opendata-stuttgart/meta/wiki/EN-APIs QuickApp variables (mandatory, they will be automatically added with the default values): sensorID1 = [number] SensorID for PM2.5 and PM10 values, your own sensor or from someone else, 13463 is an example sensorID2 = [number] SensorID for Temperature, Humidity and Airpressure values, your own sensor or from someone else, 13464 is an example interval = [number] in seconds time to get the sensor data from sensor.community timeout = [number] in seconds for http timeout userID = [number] userID to notify of PM2.5 / PM10 breakpoints debugLevel = [number] Debug logging (1=some, 2=few, 3=all) (default = 1) icon = [numbber] User defined icon number (add the icon via an other device and lookup the number) Version 1.0 (7th February 2021) Added Child Devices for Temperature, Humidity, Absolute Humidity and Airpressure Changed the quickapp variable SensorID to two variables, one for PM values and one for Temperature, Humidity and Airpressure values Added Quickapp variable for debug level (1=some, 2=few, 3=all). Recommended default value is 1. Added QuickApp Variable for user defined icon master device-- Added Airpressure Text in log of Airpressure Child Device Removed QuickApp Variable address, there was no need to change it by user Added values for Temperature, Humidity, Absolute Humidity and Airpressure to the lables Added values for Country, Latitude and Longitude to the labels Added Sensor ID to the log below the value Added "Refresh" button Added extra check for empty data return from Sensor Community Version 0.4 (19th August 2020] Added child devices for PM2.5 and PM10 Added time of measurement, adjusted to your timezone Added Timeout QuickApp variable with high http timeout value to prevent errors Error message instead off debug message in case of an error Changed method of adding QuickApp variables, so they can be edited Version 0.3 (15th June 2020) Link to CVS files added in comment Fixed some typos Fixed breakpoint check 0 - 30 and 0 - 50 notifications Fixed retrieve of json data Version 0.2 (14th June 2020) Link to API documentation added Solved bug / crash: Better selection of the first part of the apiResult Changed some debugging logica Added UserID (mandatory) for sending push notifications Added push notifications based on the PM2.5 and PM10 breakpoints Solved bud / crash if there only was one reading from the api, most of the time there are two readings (last 5 minutes) Version 0.1 (13th June 2020) Initial version Suggestions are welcome. If someone feels the need to improve the QuickApp, you are very welcome. Download the QuickApp here (download the file and un-zip): https://github.com/GitHub4Eddy/sensor_community/archive/sensor_community_1.zip or Fibaro Marketplace: https://marketplace.fibaro.com/items/sensor-community 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