Welcome to Smart Home Forum by FIBARO
Dear Guest,
as you can notice parts of Smart Home Forum by FIBARO is not available for you. You have to register in order to view all content and post in our community. Don't worry! Registration is a simple free process that requires minimal information for you to sign up. Become a part of of Smart Home Forum by FIBARO by creating an account.
As a member you can:
- Start new topics and reply to others
- Follow topics and users to get email updates
- Get your own profile page and make new friends
- Send personal messages
- ... and learn a lot about our system!
Regards,
Smart Home Forum by FIBARO Team
Search the Community
Showing results for tags 'LUA'.
-
Introduction to API and http requests Like the other 'Introduction to' posts I'm h0ping this may help some of the people begining their HC2 and lua journey Corrections and suggestions to improve always welcome. What is an API An API can be used to execute commands but the majority are used to request a response or status. Most API’s are interrogated through a http or https request. Some API’s require authentication in the form of a username or a password or an API key. There are public API’s and private API’s. There are a number of API types and the one of the most widely used is a called RESTAPI. This type of API is supported by the HC2 but there are others such MQTT, SOAP, etc The following are API’s that you may have come across in this forum and there are many others Home Center 2 : http://<hc2-ip>/docs (where hc2-ip is the ipaddress of your hc2 192.168.x.x OWN : open weather map ( https://openweathermap.org/api ) Sonos-http-api : ( https://github.com/jishi/node-sonos-http-api ) AWS Polly: used for TTS (http://docs.aws.amazon.com/polly/latest/dg/API_Reference.html ) VoiceRSS : used for TTS (http://www.voicerss.org/api/documentation.aspx ) Some organisations like AWS or Google have multiple API’s that are used for different purposes Structure All API’s has a set of web methods with a set structure. An API call or request can be either a GET, DELETE, POST, PUT and for this introduction we will focus on the GET This means that the data format is predictable and as such is easy to traverse and extract responses. Most RESTAPI responses have a format that conforms to json standard. Json is a way to store information in an organized, easy-to-access manner. It gives us a human-readable collection of data that we can access in a really logical manner. All public API’s are documented like the ones outlined above so a under will know what to expect when they issue a http request. A simple json example would be something like local jStr = {"age" : "24", “hometown" : "Missoula, MT", "gender" : "male" }; A slightly more complicated json string could be be {"coord":{"lon":15.98,"lat":45.81},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main" :{"temp":10.86,"pressure":1018.82, "humidity":66,"temp_min":10.86,"temp_max":10.86,"sea_level":1035.43,"grnd_level":1018.82},"wind":{"speed":1.06,"deg":281.501},"clouds":{"all":32},"dt":1487346966,"sys":{"message":0.0038,"country":"HR","sunrise":1487310847,"sunset":1487348795},"id":6618983,"name":"Zagreb - Centar","cod":200} This could also be referreed to as a tbale because of it's structured format. Fortunately there are websites like http://jsonprettyprint.com/ that make these json strings easier to read { "coord": { "lon": 15.98, "lat": 45.81 }, "weather": [ { "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03d" } ], "base": "stations", "main": { "temp": 10.86, "pressure": 1018.82, "humidity": 66, "temp_min": 10.86, "temp_max": 10.86, "sea_level": 1035.43, "grnd_level": 1018.82 }, "wind": { "speed": 1.06, "deg": 281.501 }, "clouds": { "all": 32 }, "dt": 1487346966, "sys": { "message": 0.0038, "country": "HR", "sunrise": 1487310847, "sunset": 1487348795 }, "id": 6618983, "name": "Zagreb - Centar", "cod": 200 } To access an api you need 2 things ip address, port, etc to make the http/https request Structure/format of the response so you know how to traverse it and extract what you want The easiest way to explain and learn is by example. As it is highly likely that everybody reading this will have a HC2 we can use to demonstrate the principles. The HC2 RESTAPI is documented on the Fibaro developer site at https://developer.fibaro.com/docs/fghc-restapi The one we will look at is devices. This the first one under the General category at the developers website above. The developer website shows the various parameters that are returned with this call. The API can be used to request information or complete an action. We will look at the request for information If you go to http://,hc2-ip./docs you will see the interactive or inline documentation for web API Go to the section on devices and select deviceid enter a device number ( I selected device 176 which is a dimmer module ) and click Try It. You will see the json formatted or encoded response for that API call. You will also see the full url for the call. If you copy the url and paste it into a browser you will get the same thing (except as one long string) {"id":176,"name":"kitchenPendant","roomID":7,"type":"com.fibaro.multilevelSwitch","baseType":"com.fibaro.binarySwitch","enabled":true,"visible":true,"isPlugin":false,"parentId":175,"remoteGatewayId":0,"interfaces":["deviceGrouping","fibaroFirmwareUpdate","levelChange","light","power","zwave","zwaveConfiguration","zwaveSceneActivation"],"properties":{"parameters":[{"id":1,"lastReportedValue":255,"lastSetValue":255,"size":1,"value":255},{"id":6,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":7,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":8,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":9,"lastReportedValue":5,"lastSetValue":5,"size":1,"value":5},{"id":10,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":11,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":12,"lastReportedValue":99,"lastSetValue":99,"size":1,"value":99},{"id":13,"lastReportedValue":2,"lastSetValue":2,"size":1,"value":2},{"id":14,"lastReportedValue":2,"lastSetValue":2,"size":1,"value":2},{"id":15,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":16,"lastReportedValue":1,"lastSetValue":1,"size":1,"value":1},{"id":17,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":18,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":19,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0},{"id":20,"lastReportedValue":110,"lastSetValue":110,"size":1,"value":110},{"id":30,"lastReportedValue":3,"lastSetValue":3,"size":1,"value":3},{"id":39,"lastReportedValue":600,"lastSetValue":600,"size":2,"value":600},{"id":41,"lastReportedValue":0,"lastSetValue":0,"size":1,"value":0}],"pollingTimeSec":0,"zwaveCompany":"Fibargroup","zwaveInfo":"3,3,52","zwaveVersion":"2.2","configured":"true","dead":"false","deviceControlType":"23","deviceGroup":"[]","deviceGroupMaster":"0","deviceIcon":"15","emailNotificationID":"0","emailNotificationType":"0","endPointId":"0","firmwareUpdate":"{\"info\":\"\",\"progress\":0,\"status\":\"UpToDate\",\"updateVersion\":\"2.2\"}","isLight":"true","liliOffCommand":"","liliOnCommand":"","log":"","logTemp":"","manufacturer":"","markAsDead":"false","model":"","nodeId":"49","parametersTemplate":"235","power":"0.00","powerConsumption":"42","productInfo":"1,15,1,0,16,10,2,2","pushNotificationID":"0","pushNotificationType":"0","remoteGatewayId":"0","saveLogs":"true","sceneActivation":"0","serialNumber":"","showEnergy":"true","smsNotificationID":"0","smsNotificationType":"0","updateVersion":"","useTemplate":"true","userDescription":"","value":"0"},"actions":{"associationGet":1,"associationSet":2,"getParameter":1,"reconfigure":0,"setParameter":2,"setValue":1,"startLevelDecrease":0,"startLevelIncrease":0,"stopLevelChange":0,"turnOff":0,"turnOn":0,"updateFirmware":1},"created":1486747960,"modified":1486747960,"sortOrder":13} EXAMPLE - API Call from a Virtual Device The following is a http request to the HC2 api. Copy the following in a button or main loop in a virtual device local device = fibaro:getSelfId() localhost = '127.0.0.1' local port = 11111 diag = Net.FHttp(localhost, port); response = diag:GET("/api/devices/176") result = json.decode(response); fibaro:debug("name: "..result.name) fibaro:debug("properties.value: "..result.properties.value) run the vd and open the debug window You’ll see the name and value of the device you selected. If you look through the json response from further up in the tutorial you’ll see the correlation between the results and the json There are some examples of how to iterate through an array in another one of the tutorials I posted. Please see my signature… One last one in case you have difficulty sleeping and the if the above was too simple This function iterates through all the virtual devices on your HC2 and looks for one called 'LAN Network 2.0' The 'LAN Network 2.0' virtual device has multiple labels The function iterates through the virtual device and counts all the labels ( in the json for the virtual device these are called rows) For each row above it looks for an element type ‘Label’ It then iterates through all the labels checking that they match the default format of Label1, Lable2, etc. string.match(jT[i].properties.rows[r].elements[e].name, "Label")) == "Label" The result is a loop inside a loop inside another loop, iterating and checking at each step full code for function to pick through when you have some time. function labelCheck() fibaro:log("vdCheck mode enabled") local device, localhost, port = fibaro:getSelfId(), '127.0.0.1', 11111; diag = Net.FHttp(localhost, port); response = diag:GET("/api/virtualDevices") jT = json.decode(response); for i = 1, #jT do if jT[i].name == "LAN Monitor 2.0" then if #jT[i].properties.rows == #jN then labelCount = "true" else labelCount = "false" end for r = 1, #jT[i].properties.rows do for e = 1, #jT[i].properties.rows[r].elements do if (string.match(jT[i].properties.rows[r].elements[e].name, "Label")) == "Label" then labelMatch = labelMatch else labelMatch = "false" end end end end end if labelCount == "true" and labelMatch ~= "false" then fibaro:debug("Quantity and format of labels is correct") else if labelCount == "false" then fibaro:debug("Quantity of labels incorrect") fibaro:log("Quantity of labels incorrect") end fibaro:sleep(3000) if labelMatch == "false" then fibaro:debug("Label format is incorrect") fibaro:log("Label format is incorrect") end end end Happy coding and suggestions to improve/correct always welcome -f
-
Hi, I have two functions in a scene that I call one after the other function1 - create global variable if it doesn't exist (through the api) function2 - write some data to the global variable the second function will fail as the 'create variable' hasn't been completed by the time I try to write to it. I can add a delay or a check that the 'variable is not nill' (ie it exists) in function2 but it still fails to execute correctly I think I recall seeing that a http request in a scene will not always run in the order of the scene ? is this correct or something else here at play. If so has anybody found a way within a single scene to create a variable on the fly and then save data to it successfully. As a last resort I was thinking about having the scene run once to create the table, call a second instance of itself and kill the first instance. I'm not sure if this would even work but it seemed like a very inefficient workaround even if possible I have seen many virtual device examples of creating a variable on the fly and saving data to it but none from a scene Thanks -f @jompa68, @petergebruers, @Sankotronic
-
Hi Everyone v 2.6 now available for users that have the SMsgH installed Three offerings - Please read below to see which is right for you 1) WWWAPI Monitor {v1.0} - New (Mar8th) - vd that monitors only availability of the internet with option for sonos-api device. (leverages Smart Message Hub {v1.0} 2) Network Device Monitor VD {v2.5} - vd that can monitor several + devices and has built-in alert notification options (pushover/pc2popup/hc2email/allinone) or 3) Network Device Monitor VD {v2.6} - vd that can monitor several + devices and deigned to be used with the recently released Smart Message Hub {v1.0} Regards [Autofrank] LAN Monitor / Network Device Monitor {v2.6} ------ to be used with Smart Message Hub {v 1.0} Modified to to be used with Smart Message Hub - Label check removed to simplify virtual device 4 simple steps to upgrade from v2.5 to v2.6 Import the new virtual device Configure your SendMsg preferences Copy your v2.5 jsonNetwork table to v 2.6 and set UpdateData to 'true' Set UpdateData to 'false' and that's it !! LAN Monitor / Network Device Monitor {v2.5} ------ has built in Notification Services The main difference between 2.0 and 2.5 are the following Virtual Device ONLY - ( no need for separate scene, table updates are now done through VD) Global variable table is created automatically created for new users Added HC2 Popup service as an extra notification option The following features are still available Individual LAN devices can be marked for Alert Alert Notification options configurable for HC2 email (default), pushover, or ALLINONE (@jompa68) One Alert will be received when device goes offline and another when it comes back online Online/Offline status is captured in global table that can be used to trigger other events Debug routine called vdCheck will verify that correct quantity of vd labels and format was setup Status/Error/Check feedback through the virtual device log console as visible through the Web UI I use this to monitor Internet, Unifi Security Gateway, HC2, Sonos API (pi), TV's, Sat Box, Apple TV, Droid Box, Alarm Panel, Alarm Gateway, Syn NAS Global cache device, Cameras, Tablets, Sonos players, Access points and phones. Alerts setup for Internet, USG, Sonos API, Access points, cameras, Sonos players, Alarm panel, alarm gateway and NAS. There are some nuances with some devices such as TV's and Phones. Open Ports of some devices that were shared by users Internet google (port 80) Sonos players/zone (port 1400) Sonos API (port 5005 or 5006) Raspberry Pi Hosting API (port 22) iPhone Port (port 62078) Smarter coffee maker (port 2081) Smarter iKittle (port 2081) Philips TV 47PFL5000 (port 1925) Foscam cameras (port 88) NAS Netgear U6 (port 80) Global cache GC100-12 (port 21) Humax FoxSat satellite receiver(port 80) Apple TV Gen 3 (port 5000) NPET MXQ Pro TV Box - Android 5.1 (port 7002) Sony TV’s (port 80) Samsung TV (port 8080) Synology NAs DS415Play (port 80) SPC Gateway (port 80) Siemens Alarm Panel (port 443) HKVision IP Camera (port 80) Unifi security Gateway (port 80) Unifi UniFi AC LR Access Point (port 22) Samsung Galaxy S6 / S7 (port 5060) Samsung Tablet (port 5060) Generic Android Tablets (port 5060) Airport Express and Airport Extreme (port 5009) Amazon Echo Dot and Fullsize Echo (port 4070) == INSTALLATION: Upgrading from 2.0 == - Import the LAN Monitor 2.5 VD and copy in device table from Update Network Table 2.0 - Run VD with updateData = "true" to update the Network table (default setting is false) - Run VD with updateData = "false" to operate in normal mode - Update notification and frequency of update options == INSTALLATION: First Time Users == STEP 1 - Import the LAN Monitor 2.5 virtual device - Populate the device table. Device, ip, port and enter alert = "1" for device notification - alert is user configurible per device - alert = 1 (enable alerts - alerts sent if it goes offline or comes back online ) - alert = 0 (disable alerts for this device) - Select the notification options - Run VD with updateData = "true" to populate the device table - Run VD with updateData = "false" to operate in normal mode Step 2 (optional) - create labels to display device status in VD - Create one label for each device in the global variable table, use the default ID - Label1, Label2, etc. - Enter Label Names (1, 2, 3, etc) to match order order of devices in Table (devices can be skipped but ID's must match) - Select Main label to display one device when observing through Web UI - If you want to use all labels you can use Set vdCheck = "true" to confirm correct quantity and format of labels. == FILES == Use the version if you don't have Smart Message Hub installed >> Network device Monitor VD {v2.5} ------------> LAN_Monitor_2.5.vfib Use this version if you HAVE Smart Message Hub installed >> Network Device Monitor VD {v 2.6} -----------> LAN_Monitor_2.6.vfib Thanks to @jompa68 , @petergebruers , @sonnyboy and @boerremk for their input Regards -f
- 119 replies
-
- 3
-
- lan monitor 2.6
- lan monitor 2.5
-
(and 2 more)
Tagged with:
-
Hi, I've been looking to find a way to mimic a dawn awakening using a RGB strip driven by a fibaro RGB module @petergebruers provided some RBG / HSL translation and I've been working on the colour sequence that is stored in an array It's essentially burnt orange -> yellow -> blue'ish -> almost white There area few of the transitions I am not 100% happy with but I was looking for a few people to test what I have done to date and see if I am on the right path The scene has a sleep of 1 second but in reality I'd probably have it close to 10 or 15 which would give an overall start to finish time of -10 minutes to aid a gradual wakeup Comment out line 7 if you don't use a HomeTable Line 61 contains the reference to the RGB strip, amend as required. @andyp - You expressed an interest in this before All feedback welcome - Feel free to tweak the colors or just pass back comments Thanks -f -- DAWN SIMULATOR USING AN RGB STRIP -- THANKS TO petergebruers FOR THE BULK OF THE CODE -- BETA --[[ %% properties %% events %% globals --]] local jT = json.decode(fibaro:getGlobalValue("HomeTable")) --Hue_2_RGB( v1, v2, vH ) function Hue_2_RGB(v1, v2, vH) if ( vH < 0 ) then vH = vH + 1 end if ( vH > 1 ) then vH = vH - 1 end if ( ( 6 * vH ) < 1 ) then return ( v1 + ( v2 - v1 ) * 6 * vH ) end if ( ( 2 * vH ) < 1 )then return ( v2 ) end if ( ( 3 * vH ) < 2 ) then return ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - vH ) * 6 ) end return ( v1 ) end function RGB(H,S,L) if s==0 then return L*255,L*255,L*255 end local var_2 if ( L < 0.5 ) then var_2 = L * ( 1 + S ) else var_2 = ( L + S ) - ( S * L ) end local var_1 = 2 * L - var_2 return 255 * Hue_2_RGB( var_1, var_2, H + ( 1 / 3 ) ) , 255 * Hue_2_RGB( var_1, var_2, H ), 255 * Hue_2_RGB( var_1, var_2, H - ( 1 / 3 ) ) end local R,G,B=RGB(120,0.5,0.5) fibaro:debug("R "..R.." G "..G.." B "..B) R,G,B=RGB(120,0,0.5) fibaro:debug("R "..R.." G "..G.." B "..B) local dawnHSL={ {0,0,0}, -- turn off. {0.03,0.67,0.012}, {0.04,0.68,0.013}, {0.06,0.69,0.014}, {0.08,0.70,0.015}, {0.09,0.71,0.016}, {0.10,0.73,0.017}, {0.12,0.75,0.018}, {0.13,0.77,0.019}, {0.15,0.79,0.020}, {0.19,0.83,0.022}, {0.20,0.84,0.023}, {0.21,0.86,0.024}, {0.22,0.87,0.023}, {0.23,0.89,0.026}, {0.25,0.91,0.028}, {0.41,0.90,0.033}, {0.41,0.88,0.034}, {0.41,0.86,0.035}, {0.42,0.85,0.036}, {0.43,0.83,0.037}, {0.44,0.81,0.038}, {0.44,0.79,0.038}, {0.44,0.78,0.040}, {0.45,0.77,0.041}, {0.45,0.75,0.042}, {0.44,0.73,0.043}, {0.46,0.72,0.044}, {0.46,0.70,0.045}, {0.47,0.69,0.046}, {0.47,0.67,0.047}, {0.48,0.66,0.048}, {0.49,0.63,0.049}, {0.50,0.61,0.050}, {0.51,0.58,0.051}, {0.52,0.56,0.052}, {0.53,0.53,0.053}, {0.54,0.51,0.054}, {0.55,0.48,0.055}, {0.56,0.46,0.056}, {0.58,0.44,0.057}, {0.59,0.42,0.058}, {0.59,0.39,0.059}, {0.59,0.37,0.060}, {0.60,0.35,0.061}, {0.60,0.32,0.062}, {0.60,0.28,0.063}, {0.60,0.24,0.064}, {0.61,0.22,0.065}, {0.61,0.20,0.066}, {0.61,0.18,0.067}, {0.61,0.16,0.068}, {0.61,0.15,0.069}, {0.61,0.14,0.070}, {0.61,0.13,0.071}, {0.61,0.12,0.072}, {0.60,0.11,0.073}, {0.60,0.10,0.074}, {0.60,0.09,0.075}, {0.60,0.08,0.076}, {0.60,0.07,0.077}, {0.60,0.05,0.078}, {0.60,0.05,0.079}, {0.60,0.05,0.080}, {0.60,0.05,0.082}, {0.60,0.04,0.083}, {0.60,0.03,0.084}, {0.60,0.02,0.085}, {0.60,0.01,0.086}, {0.60,0.02,0.087}, {0.60,0.01,0.088}, } fibaro:debug(string.format("R G B ")) for k,v in pairs(dawnHSL) do local R,G,B=RGB(v[1],v[2],v[3]) fibaro:debug(string.format("%05.1f %05.1f %05.1f",R,G,B)) fibaro:call(jT.master_bedroom.LEDLight, "setColor",math.floor(R+0.5), math.floor(G+0.5), math.floor(B+0.5), "0") fibaro:sleep(1000) end
-
Hi, I have external lights. I use geolocation with ifttt. When I arrive near my house my lights turn on automatically. But it must light up when it is dark. At sunset. I created one variable : I created 3 scenes. First scene : --[[ %% autostart %% properties %% weather %% events %% globals --]] local sourceTrigger = fibaro:getSourceTrigger(); function tempFunc() local currentDate = os.date("*t"); local startSource = fibaro:getSourceTrigger(); if ( ( ((currentDate.wday == 1 or currentDate.wday == 2 or currentDate.wday == 3 or currentDate.wday == 4 or currentDate.wday == 5 or currentDate.wday == 6 or currentDate.wday == 7) and string.format("%02d", currentDate.hour) .. ":" .. string.format("%02d", currentDate.min) == fibaro:getValue(1, "sunsetHour")) ) ) then fibaro:setGlobal("ext", "1"); end setTimeout(tempFunc, 60*1000) end if (sourceTrigger["type"] == "autostart") then tempFunc() else local currentDate = os.date("*t"); local startSource = fibaro:getSourceTrigger(); if ( startSource["type"] == "other" ) then fibaro:setGlobal("ext", "1"); end end My first scene Sets my variable to 1 when the sun goes down My second scene sets my variable to 0 when the sun rises. --[[ %% autostart %% properties %% weather %% events %% globals --]] local sourceTrigger = fibaro:getSourceTrigger(); function tempFunc() local currentDate = os.date("*t"); local startSource = fibaro:getSourceTrigger(); if ( ( ((currentDate.wday == 1 or currentDate.wday == 2 or currentDate.wday == 3 or currentDate.wday == 4 or currentDate.wday == 5 or currentDate.wday == 6 or currentDate.wday == 7) and string.format("%02d", currentDate.hour) .. ":" .. string.format("%02d", currentDate.min) == fibaro:getValue(1, "sunriseHour")) ) ) then fibaro:setGlobal("ext", "0"); end setTimeout(tempFunc, 60*1000) end if (sourceTrigger["type"] == "autostart") then tempFunc() else local currentDate = os.date("*t"); local startSource = fibaro:getSourceTrigger(); if ( startSource["type"] == "other" ) then fibaro:setGlobal("ext", "0"); end end And My third scene that executes the lighting of my lights when ext = 1 and that the sun goes down. --[[ %% properties %% weather %% events %% globals ext --]] local startSource = fibaro:getSourceTrigger(); if ( ( tonumber(fibaro:getGlobalValue("ext")) == tonumber("1") ) or startSource["type"] == "other" ) then fibaro:call(32, "turnOn"); end I have a problem, It makes day or night my scene of lighting my lights work all the time. I don't understand. One idea ? if you can help me please. Thx.
-
Hi, I have been working with the pushover service recently as an alternative the native notification service within the HC2. I think it is worth exploring if you are looking for another option. Since it is fresh in my mind I thought I'd document it and share to hopefully help others This draws on previous work from @SDeath and @sj3fk3 and others so all credit goes to them. STEP 1 – SIGN UP AND GET USER KEY 1. Sign up at pushover.net, usual stuff. You can use a trial account for 7 days and after that you'll need to purchase a license per platform (ie iOS, Android, etc) irrespective of how many devices you have with each platform. The licenses per platform are approx €5 each so they shouldn't break the bank 2. Open confirmation email and verify account 3. Log back into pushover and make note of your User Key which will be something like ubp44xxxxxxxxxxxxxx8497aihkq and this is your User Key 4. Copy this out as you will need this in the scenes in HC2 Note: There is also a pushover email address under your user key should you need this for another project but you don't need it for what we are doing here STEP 2 - REGISTER YOU APPLICATION 1. Scroll down to the bottom of the dashboard and click (Register Application/Create an API Token) 2. Give it a Name (we call our HC2 domino so I named it domino) This will appear in your client device where you receive your messages 3. Type = Application 4. Description/URL and icon all optional. (I added an icon as it appears on the alerts that you receive on your client devices (72px x 72px, png) and attached is the one I used) 5. Check the box and Click Create Application 6. This is the second Token Key, it’s something like aphmpbezxxxxxxxxxerqjwsg. Copy is out as you will need this in the scenes in HC2 STEP 3 – ADD CLIENT DEVICES (TO RECEIVE ALERTS ON ) 1. Android/iOS - Download the app from the appropriate store playstore or appstore 2. Log in to the app using your username and password that you got when you opened your pushover.net account 3. Give your device a name and click Register Device (I think it's better to avoid spaces and special characters if possible) 4. Go back to pushover.com and on your dashboard you'll see this new device added with the name you gave it. (Clicking the Pushover icon on the top left gets you back to your dashboard should you navigate off to another page) Repeat all part of STEP 3 for all other client devices. If you have multiple you'll end up with something like following You will see an Alert in your pushover app for each device that is added Within the pushover dashboard you can set up quiet times, groups and aliases but you don't need any of this to get started. STEP 4 – HC2 SETUP 1. Create a variable called pushoverBody in the top part of the variables panel 2. Create a new scene called pushoverSend and copy the following code into it ( this is the 'engine' that will call the pushover api and send the alert) 3. You will need to add your own user key and token key to line 14 -- SCENE THAT SAVES THE DATA TO THE GLOBAL VARIABLE 'pushoverBody' AND SENDS TO API --[[ %% events %% properties %% globals pushoverBody --]] -- Stops the scene if gv not populated if (tonumber(fibaro:getGlobalValue("pushoverBody")) == 0) then fibaro:abort(); end local selfhttp = net.HTTPClient({timeout=2000}) local tkn, usr = "a51eryn9t2qcg5bvoubzhqs29z2yc6", "u2n4tb99eckm6qw3hz365ts9r5z6r8" local msg = fibaro:getGlobalValue("pushoverBody") local requestBody = 'token=' ..tkn ..'&user=' ..usr ..msg selfhttp:request('https://api.pushover.net/1/messages.json', { options={ headers = selfhttp.controlHeaders, data = requestBody, method = 'POST', timeout = 5000 }, success = function(status) local result = json.decode(status.data); if result.status == 1 then fibaro:debug("Success: " ..result.request); else fibaro:debug("Failed: " ..status.data); end end, error = function(error) fibaro:debug("Success: " ..error); end }) --Reset the gv to 0 for next message fibaro:setGlobal("pushoverBody", "0") 4. Create another scene and call the pushover Test 5. Copy the following code to run a test (Change line 11 & 12 to the names of your device(s) that you wish to send the alert to. I have included 2 devices on my sample code) Change the Alert/Message Text as required -- CODE THAT SENDS THE DATA TO 'pushoverBody' GLOBAL VARIABLE -- THIS IS THE PART THAT YOU INCLUDE IN A SCENE TO SEND THE ALERT --[[ %% events %% properties %% globals pushoverBody --]] local dvc, prio = "Dad_Phone,Kitchen_iPad", "0" local ttl, msg = "Home Alert! - Panic", "Panic activated from Home." local requestBody = '&device='..dvc ..'&priority=' ..prio ..'&title=' ..ttl ..'&message=' ..msg fibaro:setGlobal("pushoverBody", requestBody) 6. Confirm that you should see an alert on the devices that you specified This is the code that you can put into any scene that you wish to send an alert from, making the necessary adjustments to receiving devices, message and priority should you wish Full details of the API can be found at https://pushover.net/api After 7 days it will stop working and you will need to purchase the required licenses at ~ €5 each .. and that it !! -f
-
Ok, this is not the best solution and might need a few more tweaks to make it look perfect (but i wasn't going for perfection) Get Chrome, install the plugin called "Stylish" after you installed it, go to preferences, make a new rule and add your domain name or ip address of your fibaro. Then add the following css code: .kitBody { width: 1100px; } #mainLoop_0 { width: 98%; height: 600px !important; } #Container1 { width: 98%; } #Top { width: 98%; } #Menu { width: 98%; } .Left { width: 13%; } .Content { width: 85%; } .Sections { width: 100%; } .SectionContent { width: auto; } #Top { float: left; } .kit { width: 100%; } .kitBody { width: 100%; } .kitBodyRight { width: 96%; } #kitsContainer { width: 100%; } .DeviceEditRight { padding-left: 25px; } .SceneArea { width: 98%; height: 600px; } .DeviceEditParametrs { width: 96%; } .CodeMirror { height: inherit; } Once you done this, at least the lua code window looks like this: So what this does is change the css code so that it tries to span the full screen that you have. So i assume you have a high resolution monitor or else it might look funny p.s. found a class that is called ".FisrtHeadline" Nice typo, it is in the html and css..
-
Good Morning Scene - Sharing Ideas/generating discussion
AutoFrank posted a topic in Home Automation
Hi, Changing this post a little to generate some discussion around good morning sequences and what people are currently or planning to do. I'm hoping to get some ideas myself and may also help some people just starting this journey.. I'll start - This is my good morning sequence and it's triggered on weekdays at 6:40 and 8:00 on weekends by a scheduler derived from @Sankotronic Main Scene code. Music control is with the sonos-htt-api and TTS is AWS Polly. I have some sleep steps that I removed to allow some actions to finish before others start or just to provide seperation. Group 4 music zones upstairs using sonos api presets, select zones, radio station and play at zero vol Change radio station if station not available Set home mode (This may be redundant) Set sleepstate to Awake mode Switch ON Satelite Box Raise vol in master bedroom slowly to preset level Raise music vol in landing room slowly to preset level Raise music vol in kids1 room room slowly to preset level Raise music vol in kids2 room room slowly to preset level Set alarm to UNSET TTS Morning Greeting (weather, temp etc) - Master Bedroom Switch main bathroom mirror light on for kids TTS Morning Greeting (weather, etc)- kids1 room TTS Morning Greeting (weather, etc)- kids2 room Wait for motion trigger in kitchen and switch on kitchen spotlights Slowly raise the other lights to preset levels Slowly raise the kitchen, hall and playroom music to preset levels What else are other people doing ? Thanks -f- 4 replies
-
- discussion
- scene
-
(and 2 more)
Tagged with:
-
Hi, I have been working to automate more of my morning routine and wanted to share what I have to date Questions, ideas, comments, refinements welcome -f --[[ %% properties %% events %% globals --]] local jT = json.decode(fibaro:getGlobalValue("HomeTable")) if (fibaro:countScenes()>2) then fibaro:abort() end fibaro:call(jT.vd.SonosPresets, "pressButton",2) -- Group zones, select radio and play at zero vol fibaro:sleep(5000) -- sleep 5 seconds for preset to complete fibaro:call(jT.vd.SonosPresets, "pressButton",16) -- Change radio station if station not available fibaro:sleep(5000) -- sleep 5 seconds for channel selection fibaro:setGlobal( "House_Mode", "HOME") -- set home mode (This may be redundant) fibaro:setGlobal(sleepState, sleepStateMapping.Awake) -- Set sleepstate to Awake fibaro:call(jT.vd.MediaSourcePresets, "pressButton",3) -- Switch ON Sat Box fibaro:call(jT.vd.SonosPresets, "pressButton",13) -- raise vol in master bedroom slowly fibaro:sleep(3000) -- sleep 30 seconds fibaro:call(jT.vd.SonosPresets, "pressButton",14) -- raise vol in landing room slowly fibaro:sleep(3000) -- sleep 30 seconds fibaro:call(jT.vd.SonosPresets, "pressButton",11) -- raise vol in twins room slowly fibaro:call(jT.vd.SonosPresets, "pressButton",12) -- raise vol in franks room slowly fibaro:sleep(30000) -- sleep 30 seconds fibaro:call(jT.vd.AlarmManagement, "pressButton",16) -- Set alarm to UNSET fibaro:sleep(5000) -- sleep 5 seconds fibaro:call(jT.vd.SonosTTS, "pressButton",14) -- Morning Greeting (weather, temp etc) - Master Bed fibaro:call(jT.bathroom.MirrorLight, "turnOn") -- main bathroom mirror light on fibaro:sleep(30000) -- sleep 30 seconds fibaro:call(jT.vd.SonosTTS, "pressButton",15) -- Morning Greeting (weather, etc)- Twins Room fibaro:sleep(20000) -- Sleep for 20 seconds to let greeting finish fibaro:call(jT.vd.SonosTTS, "pressButton",16) -- Morning Greeting (weatherm, etc)- Franks Room fibaro:sleep(900000) -- sleep 15 mins fibaro:call(jT.vd.LightsPresets, "pressButton",21) -- Kitchen Morning Lights scene
-
Hi, I have some Merten/Schneider Eletric radio push button "switches" I would like to use as trigger for turning on and off lights in a room but I do not know what code I would need to use for this to work. The push button in question is Schneider Eletric WDE002903/ Merten MTN5051-0000. Has anyone used this kind og buttons in their Fibaro HC2 system and/or is able to give input on what code is needed to use this as a trigger? Thanks for all help, Kristoffer Merten MTN5051-0000.pdf
-
[TUTORIAL] Introduction to Lua tables (2nd edition)
AutoFrank posted a topic in Tutorials and Guides
**MAJOR UPDATE TO THIS TUTORIAL** Hi, This tutorial has been going through a major update and expansion since the first release. Special thanks deserved to @petergebruers and others for helping me understand many of the underlying table concepts and for also contributing a lot to this tutorial. It may be a good idea to paste some of the code in this tutorial into a test scene to understand how they work by reviewing the output Topics covered with lots of sample code and expected outputs Table basics Creating tables and printing (ordered, non-ordered, numerical and non numerical keys) #operator - pros and cons kv pairs - advantages Updating tables - adding adding, inserting values Nested Tables - printing, updating, inserting, Summary of key points Storing tables in global variables I would have found this very useful when I started so hopefully some users will find it useful as well. -frank & peter Tables A table is a tree structure, consisting of field and each field has a "key" and "value" pair. The key can be any Lua value except nil and NaN. A table can store anything except nil. The name of the table is the variable that stores a reference to the table so it can be accessed Creating Tables and displaying the table data a = {} This is the smallest table and stores the reference to the table {} in the variable a Consider the following table print("table with numerical keys") fav = {[1] = "4FM", [2] = "96FM", [3] = "Calm", [4] = "Heart", [5] = "Red_FM"} fav is the table (or at least the name of the variable where the table is stored), in the above table 'fav', it has 5 fields and each field consists of a key/value pair 4 is the key and 4FM is the value , 2 is a key and 96FM is the value, etc You can display all the key/value pairs using the following ... print("table with numerical keys and using k/v pairs to display the fields but they won't be in order") fav = {[1] = "4FM", [2] = "96FM", [3] = "Calm", [4] = "Heart", [5] = "Red_FM"} for k,v in pairs(fav) do print("k: " ..k..", v: "..v) end the result is ... and you'll notice that the results are NOT returned in order if you have numerical keys [1], [2] then you will need to use ipairs to return them in order print("table with numerical keys and using k/v ipairs to display the fields in order") fav = {[1] = "4FM", [2] = "96FM", [3] = "Calm", [4] = "Heart", [5] = "Red_FM"} for k,v in ipairs(fav) do print("k: " ..k..", v: "..v) end #operator The #operator (#tablename) is used by a lot of people to identify the length of the table and use this to iterate through the table but it is not always recommended an example of where it will work is here print("table with numerical keys and using the #operator to iterate through the table") radio = {"4FM", "96FM", "Calm", "Heart", "Red_FM"} print("#operator: "..#radio) for i = 1, #radio do print(radio[i]) end if the table keys are numerical and contiguous, it will work.. ....but if they are not or you have inserted or removed values then it won't work A good example of where it doesn't work very well is here print("table where numerical keys are not explicitly defined but are still the table keys") print(" example where the #operator doesnt return the correct count") radio = {"4FM", "96FM", "Calm", "Heart", "Red_FM"} for k,v in pairs(radio) do print("k: " ..k..", v: "..v) end print("#operator: "..#radio) -- remove one value, set it to nil radio[3] = nil for k,v in pairs(radio) do print("k: " ..k..", v: "..v) end print("#operator: "..#radio) you can see that the second loop in the debug is showing an #operator value of 5 (because it is the last key but there are only 4 key/value pairs as we removed one Another approach that is recommended to use is as follows use the k/v approach to count the fields and then use the counter to iterate through.. print("table where numerical keys are not explicitly defined but are still the table keys") print(" example using k/v pairs to calculate the correct table field count") radio = {"4FM", "96FM", "Calm", "Heart", "Red_FM"} counter = 0 for k,v in pairs(radio) do counter=counter+1 end print("counter: "..counter) for i = 1, counter do print(radio[i]) end radio[3] = nil -- remove the row by setting the key to nil counter = 0 for k,v in pairs(radio) do counter=counter+1 end print("counter: "..counter) for i = 1, counter do print(radio[i]) end and you can see that the counter is correct in both loops Updating Tables you can update a table by setting Key/Value pairs or delete a value as follows print("table where numerical keys are not explicitly defined but are still the table keys") print("examples of updating the table") fav = {"4FM", "96FM", "Calm", "Heart", "Red_FM"} -- update one value add another value fav[2] = "Soul" fav[4] = "Classic" -- delete value at key 1 fav[1] = nil for k,v in pairs(fav) do print("k: " ..k..", v: "..v) end if the k/v pair already exists it overwrites it or of the k/v pair didn't exist, it simply adds it as above This is the same example but the table has the numerical keys explicitly defined print("updating a table") fav = { [1] = "4FM", [2] = "96FM", [3] = "Calm", } fav[2] = "Soul" fav[4] = "Classic" for k,v in ipairs(fav) do print("k: " ..k..", v: "..v) end Example of adding key/value pairs to this table using table.insert fav= {"4FM","96FM", "Soul", "Jazz"} table.insert(fav, "Calm") table.insert(fav, "Red_FM") table.insert(fav, "Heart") for k,v in pairs(fav) do print("k: " ..k..", v: "..v) end The extra key/value pairs will be added as extra fields as you cannot specify the exact field you want to update as in the approach above Tables with non-numerical keys are also possible as shown below print("Table initialiser with alpha keys") fav = { ["a"] = "4FM", ["b"] = "96FM", ["c"] = "Calm", ["d"] = "Heart", ["e"] = "Red_FM"} for k,v in pairs(fav) do print("k: " ..k..", v: "..v) end the same table can be represented in a simpler form print("Table initialiser with alpha keys - simplified") fav = { a = "4FM", b= "96FM", c= "Calm", d = "Heart", e= "Red_FM"} for k,v in pairs(fav) do print("k: " ..k..", v: "..v) end If you chose or have to use non numerical keys or a mix, then Lua makes no guarantee on order as the spec says random. The only way to order a table with non-numerical keys (such as alphabetical order) is to use an external reference. Nested Tables Lets take the following table, it looks like each value in the key/value pair is a table in itself as if one table is nested inside the other table = { [1] = {loc="utility_room", name="HeatingTemp"}, [2] = {loc="bed_room", name="FreezerTemp"}, } for k,v in pairs(table) do print(k,v) end if you run the usual k/v code you will see the second/nested set of tables To list the k/v inside the second table you need to iterate through the first table we use a counter like before to find out how many fields are in the outer most table There are two tables nested within the outer most table table [1] which has two fields with k/v pairs table [2] which has two fields with k/v pairs print("Nested table example") table = { [1] = {loc="utility_room", name="HeatingTemp"}, [2] = {loc="bed_room", name="FreezerTemp"}, } for k,v in pairs(table) do print("first level key: " ..k..", first level value: "..tostring(v)) for k2,v2 in pairs(v) do -- This works because we KNOW v is a table. print(" second level key: " ..k2..", second level value: "..v2) end end we then use the counter to expose the k/v pairs at table[1] and table [2] with the following result You could also expose specific values (in the nested able) using the following table = { [1] = {loc="utility_room", name="HeatingTemp"}, [2] = {loc="bed_room", name="FreezerTemp"}, } for k,v in pairs(table) do print("location: "..table[k].loc) end with the following expected result You could also have used the #operator that we discussed earlier BUT only because the key's in the outer-most table are numerical and contingous for i = 1, #table do -- #list refers to the max number of items in the table fibaro:debug(table[i].ip, table[i].port) end Updating a value in a nested table If you want to update a specific value in the nested table you need to use the k/v method we have discussed fav = { [1] = {loc="utility_room", name="HeatingTemp"}, [2] = {loc="bed_room", name="FreezerTemp"}, } -- update nested table on the second field with a new value fav[2].loc = "kitchen" fav[2].name = "Hobtemp" -- or you could use the following format to do accomplish the same update fav[2]["loc"] = "kitchen" fav[2]["name"] = "Hobtemp" -- print out the updated table... for k,v in pairs(fav) do for k,v in pairs(fav[k]) do print("k: " ..k..", v: "..v) end end -- second option to print out the updated table with more explanation for k,v in pairs(fav) do print("first level key: " ..k..", first level value: "..tostring(v)) for k2,v2 in pairs(v) do -- This works because we KNOW v is a table. print(" second level key: " ..k2..", second level value: "..v2) end end the result is If you want to add/insert a new k/v pair in the nested level, you can use the table.insert method fav = { [1] = {loc="utility_room", name="HeatingTemp"}, [2] = {loc="bed_room", name="FreezerTemp"}, } -- insert a new value table.insert(fav,{loc="bedroom", name="sinktemp"}) -- print out the updated table... for k,v in pairs(fav) do for k,v in pairs(fav[k]) do print("k: " ..k..", v: "..v) end end -- second option to print out the updated table with more explanation for k,v in pairs(fav) do print("first level key: " ..k..", first level value: "..tostring(v)) for k2,v2 in pairs(v) do -- This works because we KNOW v is a table. print(" second level key: " ..k2..", second level value: "..v2) end end and the result is three fields in the table So before we go to the last task of storing the table in a global variable, I thought it would be good to have a quick recap.. Summary A table is a tree structure, consisting of field and each field has a "key" and "value" pair. The name of the table is the variable that stores a reference to the table so it can be accessed you can explicitly declare a numerical key in a table but you don't have to for a table with a numerical key - use ipairs to print the table fields in order #operator can be used but ONLY for tables with numerical keys that are contiguous it is recommended to use the standard k/v approach to count the number of fields remove a value by setting its key = nil update a table using the table[key] method add a new field using table.insert(table, "value") and will add a numerical key table.insert will not work with tables with non-numerical keys tables with non-numerical keys cannot be printed in order by ipairs, result will be random nested tables require iteration to print the inner-most tables multiple levels of iteration required for multi-nested tables updating nested table - iterate with k/v and use table[key].nested-key = "value" inserting into nested table - iterate with k/v and use table.insert(table,{key="value, key="value} tables can be very confusing and frustrating to us newbie's , so take your time Storing a table in a global variable if you take the following table structure Table = { group = { option1=1560,option2=1507,option3=881 }, } If you want to store this table in a global variable you will need to encode the table as a string. One of the most common formats to encode a table (structure) is json from json.org "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate." To save the table you need to encode it and then save it to the global variable jTable = json.encode(table) fibaro:setGlobal("StateTable", jTable) In order to read back a single value you need to decode the string local jT = json.decode(fibaro:getGlobalValue("Table")) once it's decoded you can then read one of the values or manipulate the table fibaro:debug(jT.group.option1) Updating a single value - assign the new value, encode it and the store it..... jT.group.option3 = 987 jTable = json.encode(jT) fibaro:setGlobal("StateTable", jTable) Making json strings/output easier to read... Sometimes a json string can be difficult to read and understand its structure. Typically they would look something like this... {"widget": {"debug": "on","window": {"title": "Sample Konfabulator Widget","name": "main_window","width": 500,"height": 500},"image": {"src": "Images/Sun.png","name": "sun1","hOffset": 250, "vOffset": 250,"alignment": "center"},"text": {"data": "Click Here","size": 36,"style": "bold","name": "text1","hOffset": 250,"vOffset": 100,"alignment": "center","onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"}}} There are a number of websites that will 'pretify' the string make it easier to read the structure and enable you to understand how you might navigate it. If you take json string above and paste it into http://jsonprettyprint.com/ it will display it more like a table This format is easier to understand { "widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images\/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity \/ 100) * 90;" } } } Finally.... There is a very good discussion on using a table in a predefined variables to store the ID's of scenes and devices for the HC2 - https://forum.fibaro.com/index.php?/topic/23942-tutorial-using-a-hometable-to-store-device-and-scene-ids/ suggestions to improve welcome -f- 47 replies
-
- 9
-
- 2nd edition
- lua
-
(and 3 more)
Tagged with:
-
Witam Prośba do zespołu projektantów systemu. Może już czas na usprawnienie edytora skryptów LUA ? Można by dodać kilka nowych funkcji ( występujących w innych, popularnych edytorach ) takich jak: ctrl+g - skocz do linii numer ... ctrl+f - wyszukaj frazę ...... ctrl+h - zamień frazę .... na nową .... ctrl+s - zapisz poprawki ctrl+F1 - okno z pomocą - opis funkcji biblioteki fibaro pozycjonowanie kursora ( x, y ) - jest numeracja wierszy, brak numeracji kolumn własny dobór kolorystyki "elementów" skryptu (komentarzy, funkcji, łańcuchów znakowych, liczb itd. ) Wiem, że to nie jest potrzeba pierwszej kolejności ale wielu z nas aby dokonać zmian kopiuje skrypt, przenosi go do innego edytora i tam robi poprawki. Następnie poprawiony skrypt ponownie wkleja do edytora HC2. Usprawnienie edytora HC2 poprzez dodanie tych kilku funkcji wyeliminowałoby ten zbędny "zabieg".
-
Hi, I had the requirement for a very simple scheduler. The code below is a stripped down version of @Sankotronic Main Scene code and just contains the Scene Scheduler. Thanks to @Sankotronic for his permission to post this. -- SIMPLE SCHEDULER. -- STRIPPED DOWN VERSION OF 'MAIN SCENE' CODE BY SANKOTRONIC --[[ %% autostart %% properties %% globals --]] if (fibaro:countScenes() > 1) then fibaro:abort(); end local jT = json.decode(fibaro:getGlobalValue("HomeTable")); -- comment out if you don't use a hometable local currenttime = os.date('*t'); local currentwday = currenttime['wday']; local TimeCurrent = os.date("%H:%M", os.time()); -- SCHEDULED SCENES SETUP -- (seperate multiple entries by comma) local runSceneSchedName = {"Test Scene 1", "Test Scene 2"}; -- Add scene names local runSceneSchedID = {641, jT.scene.Wakeup}; -- add scene ID's or references local runSceneSchedHour = {{"21:47"}, {"07:30"}}; -- Add times to run the scenes local runSceneSchedWeek = {{1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1}}; -- specify what day to run the scenes, Sunday is first day in array function doSceneSched() if #runSceneSchedID > 0 then for i = 1, #runSceneSchedID do if runSceneSchedWeek[i][currentwday] == 1 then for t = 1, #runSceneSchedHour[i] do if runSceneSchedHour[i][t] == TimeCurrent then fibaro:startScene(runSceneSchedID[i]); end end end end end end -- MAIN LOOP while true do currenttime = os.date('*t'); currentwday = currenttime['wday']; TimeCurrent = os.date("%H:%M", os.time()); doSceneSched(); fibaro:sleep(59700); end The full Main Scene code can be found at https://forum.fibaro.com/index.php?/topic/23510-scene-main-scene-for-time-based-events-control-v-125/ I thought this many be useful for some new users starting out or those like me that need a simple yet well written scheduler and may even be a stepping stone for some to the full Main Scene. -f
- 14 replies
-
- sankoronic
- scheduler
-
(and 3 more)
Tagged with:
-
Hello A few months ago my virtual device for my engine heater became very slow and sometimes it doesn't work at all. Sometimes it gets better if i reboot the HC2 but it´s not funny when it´s -30 C and I get late to work because the car wont start and there is no way to be sure if it will work or not the next morning. Is this a known problem and is there a way to read the logfiles on the HC2? The diagnostics panel doesn't say much. The VD has been working great for several months before it became slow/not working. It might have happened after an upgrade. The controlled device works if i manually set i to active. Several other LUA scripts also became non working after an upgrade (cant remember if it happened at the same time) but I got them working just by changing something, save, change back and save again. I also get "to many instances" on other LUA scripts but not on the engine heater. Maybe they overload the HC2 and make it slow? I attached the VD and the scripts. LightsTimerToManyInstancesNotWorking.txt -- a timer that will turn off the lights if any of the two devices is on for more than xx minutes Motorvärmare_V-vfib-json -- The virtual device EngineHeaterLUA.txt -- the script for the VD LightsTimerToManyInstancesNotWorking.txt Motorvärmare_V.vfib.json EngineHeaterLUA.txt
-
Hi, I must confess that I use only "value", "lastBreached", "turnOn" and "turnOff" properties and commands for z-wave devices in my scenes. I don't actually know what "log" and "logTemp" and the others are. They may be very useful, but I cannot find any documentation for them. Are there any? Has anyone tried to figure out what they are, and maybe made a list?? Fredrik
- 3 replies
-
- lua
- documentation
-
(and 1 more)
Tagged with:
-
hi guys, is there a way to expand the tiny lua editor window? I find it very hard to code in there. thanks for any hints. kro
-
What is the syntax of sonos "text-to-speech" function in lua?
-
I really have a feeling someone will reply and i feel stupid... but.. How do you call a scene so it will start from a VD? fibaro:call(id,'start') doesn't work, and i can't really see examples for it.
-
Hi HC2 guru's Would a scene with a xxx value in the header/properties or a VD main loop be more efficient (ie use less resources) if I wanted to use a sensor (motion, light, humidity) to trigger an action. I find some of my sensors don't always react to a scene header trigger and in a vd. I think I could also exert a better level of control with repeat triggers with a vd but I wanted to make sure that this approach wouldn't impact the HC2 excessively Thanks -f
-
Hoping someone can shed some light on this... Trying to send a HTTPS GET request to an AWS API Gateway endpoint. Here's the Lua code (obviously I've removed any privileged information for the purposes of posting here): httpClient = net.HTTPClient(); httpClient:request ( 'https://**********.execute-api.eu-west-1.amazonaws.com/****/***********', { options = { method = "GET", headers = { ['x-api-key'] = '*****************************' } }, success = function (response) fibaro:debug (response.data) end, error = function (err) fibaro:debug ("Error:" .. err) end }) I get an 'Error:Transport endpoint is already connected' message in the debug window. That's not a response from the API (no requests get logged on the AWS side, so the HC2 isn't getting as far as making the request at all.) If I try making a HTTPS request to another URL (like Google for example) it works with no issue. Also I know the API endpoint works, because I can call it from CURL and it does exactly what I expect. It's just from a scene. Seems like others have had the same issue, specifically with AWS API Gateway. Anyone know how to get this to work? Cheers, Dan
-
Hi, i'm trying to execute this call using lua on the hc2 ws://<spc_web_gateway_host>:<port>/ws/spc/ Any idea how this could be done. thanks frank
-
Hi, Just spotted the new UR weather device after the 4.11 upgrade It seems pretty accurate for my location can this be queries using lua or through the API Thanks Frank
-
So I have a Good Morning Scene, and it executes other scenes.. I am struggling with understanding if lua waits for return of a scene or fires in parallel? The problem presents as this:- My good morning scene sets some globals, and executes scenes to switch alarms off and turn heating on (via scenes) etc.. then it builds a json table and puts it into a predefined Global... after that is calles a final scene that reads the global and TTS's it to speakers.. Problem is, half the time it seems to be reading the last updated speech body, and not the one that has just been set in the global.. is this a sequencing thing? or issue with globals? should I use a regular global and not a predefined one? I even tried to chain the scenes being called from good morning by nesting setTimeout functions..
-
Apologies for the newbie question but, is there a LUA IDE application / tool already available, or does everyone tend to use the one they feel comfortable with?
-
hi, This tutorial is based on an idea that i believe originated to @cag014 some time back and has been adopted by many. So well deserved kudos to @cag014 and others that helped originate and develop the concept. I am merely a scribe that has benefited from this. I decided to write a quick tutorial for two reasons... I implemented this over christmas and and found it very useful and much easier than I thought It would appear that we have some new forum members that got HC2 devices from Santa The core of this approach is to store all the reference ID's to your devices, virtual devices, scenes, etc in a json encoded table. The references like jT.kitchen.light are used in the scene or vd and device ID can easily be changed in the table. One important benefit is that it you need to exclude/include a device the device ID will change. With this approach you simple change the reference in the Home table and your done. Without this approach you wll need to go through your code and change the device ID where appropriate. ** This doesn't get over the need to enter ID as triggers in the scene headers as fibaro doesn't allow variable in the header ** The solution has two parts to it. The home table itself where the data is stored. - this is held in a predefined variable (lower part of variables panel) The references in your scenes and virtual devices use this table HOME TABLE This can be created and maintained through either a scene or a virtual device. I chose a VD but there is no advantage I can thing of using one way or the other. Go to Panel, Variables Panel and create a new predefined variable (lower part of panel) called HomeTable. When you create a predefined variable it has two values. Name the variable and save. Edit the variable and simply delete the second value. Using either a scene or a vd create your table and store it. This is lua from my VD. I create one button and enter the code below. The top part shows the format of the table. I opted to place each element I am looking to store into rooms and/or other natural groupings but you can choose any way to structure. I'll attached a copy of my full table at the end of this to show what I use it for. The next part encodes and stores the data The last part is where I read back one entry to show the table stored okay. -- HOME TABLE FOR ALL DEVICES, SCENES ETC. jsonHome = { hall = { Lights=88,Lamp=1421,Temp=1,Motion=1,Humidity=1,Lux=1,ZRC90=1447,SmallBathLight=147,SmallBathMotion=1, SmallBathTemp=1,SmallBathLux=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, kitchen = { Pendant=176,Table=174,Spotlights=90,Temp=1549,Motion=1548,Humidity=1551,Lux=1550,UV=1552,XmasLight=1531, WineFridgeTemp=1,Dishwasher=1,rcTV=1490,rcSonos=1561,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, } jHomeTable = json.encode(jsonHome) -- ENCODES THE DATA IN JSON FORMAT BEFORE STORING fibaro:setGlobal("HomeTable", jHomeTable) -- THIS STORES THE DATA IN THE VARIABLE fibaro:debug("global jTable created") -- STANDARD DEBUG LINE TO DISPLAY A MESSAGE -- I then like to read back a entry from the table to show that the table didnt get corrupt in the process. local jT = json.decode(fibaro:getGlobalValue("HomeTable")) -- REFERENCE TO DECODE TABLE fibaro:debug(jT.kitchen.Motion) -- DISPLAY ONE VARIALE the output of this when I click the button (or run the scene is as follows) It is reading back the ID (1548) stored for Motion under the kitchen grouping I would recommend using an external editor like Notepad++ or Zerobrane to edit/manage the code in the vd and then copy back to the vd when ready to update as the HC2 lua editor is very small At this stage you now have your table REFERENCING THE TABLE CONTENTS IN YOUR SCENES AND VIRTUAL DEVICES For this you need to place the following line of code in each scene or vd local jT = json.decode(fibaro:getGlobalValue("HomeTable")) and then use references instead of device ID's in the scene code. The easiest way to explain this is with an example. This scene switches on a light in my kitchen if it is dark, motion is detected and no light is on already --[[ %% properties 1548 value %% events %% global --]] local jT = json.decode(fibaro:getGlobalValue("HomeTable")) -- KITCHEN AUTOLIGHTS if (tonumber(fibaro:getGlobalValue("Darkness")) == 1 ) and (tonumber(fibaro:getValue(jT.kitchen.Motion, "value")) > 0 ) and (tonumber(fibaro:getValue(jT.kitchen.Spotlights, "value")) == 0 ) and (tonumber(fibaro:getValue(jT.kitchen.Pendant, "value")) == 0 ) and (tonumber(fibaro:getValue(jT.kitchen.Table, "value")) == 0 ) and (tonumber(fibaro:getValue(jT.sunroom.Light, "value")) == 0 ) and (tonumber(fibaro:getValue(jT.sunroom.Lamp, "value")) == 0 ) then fibaro:call(jT.kitchen.Pendant, "setValue", "40") UpdateEventLog("kitchen lights auto on") end It's easy enough to see how the references are built up if you examine the scene v the table at the top of this post and that it !! Addition: If you need to adjust a single parameter in the table you can use the following. This can be useful if you don't want to adjust one value and then copy the whole table back into the vd and update or more useful if you want to adjust the value in the fly in a script. -- NEW PARAMETER VALUE jT.kitchen.Motion=2000 -- TO SAVE THE CHANGE jSonosTable = json.encode(jT) fibaro:setGlobal("SonosTable", jSonosTable) fibaro:debug("global jTable created") Hopefully this will help some users If you have any suggestions as to how to improve this please let me know and I'll edit -frank ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copy of my table to show how flexible this approach can be jsonHome = { system = { Sunset_SunRise=1560,houseStatus=1507,alarmStatus=881,HouseTemps=1236,sonosSummary=1407,sonosTTS=1452, sonosSequences=1536,TVSequences=1545,lightingSequences=1534,powerConsump=1484,specialHouseMode=1538 }, hall = { Lights=88,Lamp=1421,Temp=1,Motion=1,Humidity=1,Lux=1,ZRC90=1447,SmallBathLight=147,SmallBathMotion=1, SmallBathTemp=1,SmallBathLux=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, playroom = { Light=84,TVLight=1438,XmasLight=1518,Motion=1595,Temp=1596,rcPlayroomTV=1487,rcSonos=1574,Lux=1597,Humidity=1598,UV=1598,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, living_room = { Light=231,libraryLight=164,libraryTopSocket=166,Temp=1584,Lamp=1423,Lux=1585,Motion=1583,Humidity=1,UV=1,TVLight=1499,XmasLight=1513,rcSonos=1,rcLivingRoomTV=1506,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, utility_room = { Light=141,Temp=1194,Motion=1270,Humidity=1,Lux=1,UV=1,FreezerTemp=1,Washer=1,Dryer=1 }, equipment_rack = { RackSummary=1453,Rack1Temp=1192,Rack2Temp=1193,fanUpper1=1432,fanLower2=1434,powerAmpLower=1269, powerAmpUpper=1267,heatingFlowTemp=1199,rcSatBox=1491,SatBoxPresets=1492,rcHdmiMatrix=1489,rcAppleTV=1539, rcAppleTvSystem=1540,rcBluRay=1544,rcDroidBox=1541,networkMonitor=1493,avDeviceMonitor=1494,haDeviceMonitor=1495,hc2Resources=1391 }, kitchen = { Pendant=176,Table=174,Spotlights=90,Temp=1549,Motion=1548,Humidity=1551,Lux=1550,UV=1552,XmasLight=1531, WineFridgeTemp=1,Dishwasher=1,rcTV=1490,rcSonos=1561,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, sunroom = { Light=172,Lamp=6,projectionScreenPower=1509,rcProjector=1542,rcProjectorScreen=1543 }, dining_room = { Light=25,Lamp=1,Motion=1,Temp=1202,Lux=1,Humidity=1,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, pizza_bbq_area = { CenterLights=253,Spotlight=710,Lanterns=712,HeaterSwitch=255,LEDLights=238,Motion=705,Heaters=250,Temp=1,Lux=1, Humidity=1,rcSonos=1,PizzaBbqCam=761,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, garage = { Light=895,BenchLight=1,DoorOpener=80,DoorStatus=778,Temp=1578,Humidity=1590,Lux=1589,Motion=1587,UV=1591, GarageControl=1559,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, driveway = { porchLight=68,pillarLights=145,Spotlight=893,Motion=1429,GateTemp=958,GateOpener=94,GateStatus=956,GateControl=1537,DrivewayCam=1556,FrontDoorCam=1557 }, back_garden = { patioLight=64,utilityLight=76,sidePatioLights=60,boundaryLights=62,Spotlight=58,Motion=1427,Humidity=218,Lux=217,Temp=958,XmasLight=1523,BackGardenCam=1558 }, hotpress = { Light=143,DoorStatus=888,Temp=890 }, bathroom = { Light=162,MirrorLight=1468,MirrorDemist=1470,Temp=1170,Humidity=1,Motion=1 }, guest_bedroom = { Light=31,Lamp=718,Temp=1588,Motion=1587,Lux=1589,Humidity=1590,UV=1591,BathLight=1,BathTemp=1,BathMotion=1,BathHumidity=1,BathFan=1,BathMirrorLight=1460,BathMirrorDemist=1462,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, master_bedroom = { Light=56,LampDad=29,LampMum=1,Temp=1,Motion=1247,Lux=1, Humidity=1,BathLight=1,BathTemp=871,BathMotion=870,BathHumidity=1,BathLux=872,BathFan=1,BathMirrorLight=1464,BathMirrorDemist=1466,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, lau_eth_bedroom = { Light=52,Temp=1185,Motion=1253,Lamp=1440,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, frank_bedroom = { Light=54,Temp=1200,Motion=1255,Lamp=1450,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, office = { Light=33,Temp=1186,Motion=1251,Lamp=720,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, Landing_Stairs = { stairsLight=92,landingLight=168,rcSonos=1,TTS_message="",TTS_volume=10,RadFav=3,IsPlaying=1,nowPlaying="",vol=1,clip="" }, scene = { MainScene=614,AlarmControl=598,rebootHC2=593,goodMorning=463,goodNight=331,LeavingHome=483,welcomeHome=488,quietMorning=499,kidsToBed=490,plaroomTvOn=580,firstFloorMusicOn=579,firstFloorAllOff=578, hallSceneControl=519,StairsLight30=556,GateOpen5=526,GateOpenHold=361,GateOpenClose=425,DumpEventLog=565,PlayroomOff=617 }, vd = { AlarmManagement=881,TVPresets=1545,SonosTTS=1452,LightPresets=1534,HouseModeExt=1538,SonosPresets=1536,RackTempMngt=1453,MediaSourcePresets=1567,JhomeTable=1566,GateControl=1537,GarageControl=1559 }, users = { admin=2,frank=1564,sylvia=1565 }, ios = { frankS6=993,sylviaS7=1526,frankipad=1532,sylviaipad=1533 }, IsOnline = { GlobalCache=1,SatBox=1,AppleTV=1,AndroidBox=1,TVPlayroom=1,TVKitchen=1,TVLiving=1,Projector=1,HC2=1,SynNAS=1,AlarmGateway=1,AlarmPanel=1,SonosAPI=1,DrivewayCam=1,GardenCam=1,FrontDoorCam=1,PizzaBBQCam=1,Internet=1,USG=1,HouseAP=1,GarageAP=1 }, }