Script examples (Lua)

Moderator: leecollings

tozzke
Posts: 135
Joined: Friday 02 January 2015 9:22
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: Netherlands
Contact:

Re: Script examples (Lua)

Post by tozzke »

Nautilus wrote:
ToneStrife wrote: I edit myslef, I have to select that is a Device Event not All. Anywhere I can find which should I select there?
Choose device script if you have a "devicechanged" trigger on the script ( = you wan the script to run on each device change) and select time script if you only have "otherdevices" conditions ("devicechanged is not available in time scripts) and you want to run the script once a minute. I see no reason to select "All" option in any circumstance but probably there is some special cases...:)
tozzke wrote:try changing it to:

Code: Select all

commandArray = {}
if (otherdevices['Gala'] == 'On' or otherdevices['Carlos'] == 'On') and otherdevices['Familia'] == 'Off' then
    commandArray['Familia'] = 'On'

elseif otherdevices['Gala'] == 'Off' and otherdevices['Carlos'] == 'Off' and otherdevices['Familia'] == 'On' then
    commandArray['Familia'] = 'Off'
end
return commandArray
This is a good option (except I think the first condition needs to be otherdevices['Gala'] == 'On' and otherdevices['Carlos'] == 'On' and second (otherdevices['Gala'] == 'Off' or otherdevices['Carlos'] == 'Off) => requirement for "Familia" was that both are home) if it is enough that "Familia" switch is updated with up to one minute delay. The above would need to be defined as time script. But I think the original should work as well as long as it is defined as device script...
No, you want the combined switch 'Familia' to turn on when one of both is at home and turn off when both aren't at home anymore.
If you's use this 'Familia' switch in another script to turn lights on and off, the light will go on when one of both is at home and will turn off when nobody is at home anymore. At least that's the way it usually needs to work, a combined switch which has all the family members in it.

What you suggest will result in that the lights will go on when both are at home and will go off when one of both left home, leaving the one at home in the dark.
Nautilus
Posts: 722
Joined: Friday 02 October 2015 12:12
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: Finland
Contact:

Re: Script examples (Lua)

Post by Nautilus »

tozzke wrote: No, you want the combined switch 'Familia' to turn on when one of both is at home and turn off when both aren't at home anymore.
If you's use this 'Familia' switch in another script to turn lights on and off, the light will go on when one of both is at home and will turn off when nobody is at home anymore. At least that's the way it usually needs to work, a combined switch which has all the family members in it.

What you suggest will result in that the lights will go on when both are at home and will go off when one of both left home, leaving the one at home in the dark.
I'm not saying whether this is clever or not, actually that is something we cannot comment as long as we don't know how ToneStrife wants to use the switch :) But I'm sure he has a good reason for this as the exact quote from the first post is:
I have also made one called Familia (family) to be turned On if both are at home
ToneStrife
Posts: 20
Joined: Sunday 16 April 2017 17:02
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by ToneStrife »

Yes, the point about the Both home. So I finally make it work.

My final question is that I make it work when I change from all to devices in the Lua config. How do I know which one I have to use everytime?
Nautilus
Posts: 722
Joined: Friday 02 October 2015 12:12
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: Finland
Contact:

Re: Script examples (Lua)

Post by Nautilus »

ToneStrife wrote:Yes, the point about the Both home. So I finally make it work.

My final question is that I make it work when I change from all to devices in the Lua config. How do I know which one I have to use everytime?
Was there something unclear in my first reply? :) A recap:
Choose device script if you have a "devicechanged" trigger on the script ( = you wan the script to run on each device change) and select time script if you only have "otherdevices" conditions ("devicechanged is not available in time scripts) and you want to run the script once a minute. I see no reason to select "All" option in any circumstance but probably there is some special cases...:)
In short:
All: usually not needed (triggered always?)
Device: triggered on all device changes
Time: triggered once a minute
ToneStrife
Posts: 20
Joined: Sunday 16 April 2017 17:02
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by ToneStrife »

Thanks!
tozzke
Posts: 135
Joined: Friday 02 January 2015 9:22
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: Netherlands
Contact:

Philips Hue bridge update

Post by tozzke »

Perhaps there are more people interested in whether or not there is an update available for your Philips Hue bridge ;)

Code: Select all

-- script_time_Philips Hue bridge update.lua

-- config ---------------------------------------------------------
local hue_update = 'Philips Hue bridge'                                         -- selector switch (with states 'Off' and 'Level 10' with the name 'Update available!'
local update_available = 'Set Level: 10'
local url = 'http://<IP HUE BRIDGE>/api/<API KEY>/config'

local tempfilename = '/home/pi/domoticz/scripts/philips_hue_update.tmp'         -- can be anywhere as long as it's writeable
-- config ---------------------------------------------------------
 
commandArray = {}

local function runEvery60min()
    print('<font color="blue">Philips Hue update status: ')
    os.execute('curl -s -o "'..tempfilename..'" '..url)

    local line = ''
    
    for line in io.lines(tempfilename) do
        if      string.find(line,'"updatestate":0') then
                    print('<font color="grey">Philips Hue: No update available</font>')
                if  otherdevices[hue_update] ~= 'Off' then
                    commandArray[hue_update] = 'Off'
                    print('<font color="grey">Philips Hue: Update installed</font>')
                    commandArray['SendNotification']='Philips Hue bridge#The update has been installed'
                end
        elseif  string.find(line,'"updatestate":1') then
                    print ('<font color="green">Philips Hue: Update is downloading</font>')
                if  otherdevices[hue_update] ~= 'Update available!' then
                    commandArray[hue_update] = update_available
                    commandArray['SendNotification']='Philips Hue bridge#There is an update available!'
                end
        elseif  string.find(line,'"updatestate":2') then
                    print('<font color="green">Philips Hue: Update is downloaded and ready to install</font>')
                if  otherdevices[hue_update] ~= 'Update available!' then
                    commandArray[hue_update] = update_available
                    commandArray['SendNotification']='Philips Hue bridge#There is an update available!'
                end
        elseif  string.find(line,'"updatestate":3') then
                    print('<font color="green">Philips Hue: Update is installing</font>')
                if  otherdevices[hue_update] ~= 'Update available!' then
                    commandArray[hue_update] = update_available
                    commandArray['SendNotification']='Philips Hue bridge#There is an update available!'
                end
        end
    end
end

local m = os.date('%M')

if (m % 60 == 0) then
	runEvery60min()
end

return commandArray
Probably not the prettiest script (a bit of copy/paste work), but it seems to work just fine :)
If someone can make it more efficient, feel free to do so ;)
Kivi
Posts: 6
Joined: Wednesday 15 April 2015 20:54
Target OS: Linux
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by Kivi »

can some1 help me out whit this simple lua script. the user var is never readed and writed when using like so and the script wont work at all :(

Code: Select all

commandArray = {}

 if (otherdevices['alarm'] == 'Off' and otherdevices['IsDark']== 'Off' and uservariables["Coming_home_light"] == "0" ) then
        commandArray['Sofa & paint light']='On'
        commandArray['Lamp livingroom']='On'
        commandArray['bed light]='On'
        commandArray['Variable:Coming_home_light'] = 1
 elseif (otherdevices['alarm'] == 'Off' and uservariables["Coming_home_light"] == "1" ) then
                commandArray['Variable:Coming_home_light'] = 0
 end
User avatar
Siewert308SW
Posts: 288
Joined: Monday 29 December 2014 15:47
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: The Netherlands
Contact:

Re: Script examples (Lua)

Post by Siewert308SW »

Kivi wrote: Sunday 28 January 2018 16:32 can some1 help me out whit this simple lua script. the user var is never readed and writed when using like so and the script wont work at all :(

Code: Select all

commandArray = {}

 if (otherdevices['alarm'] == 'Off' and otherdevices['IsDark']== 'Off' and uservariables["Coming_home_light"] == "0" ) then
        commandArray['Sofa & paint light']='On'
        commandArray['Lamp livingroom']='On'
        commandArray['bed light]='On'
        commandArray['Variable:Coming_home_light'] = 1
 elseif (otherdevices['alarm'] == 'Off' and uservariables["Coming_home_light"] == "1" ) then
                commandArray['Variable:Coming_home_light'] = 0
 end
You mismatched those characters.

Code: Select all

if (otherdevices['alarm'] == 'Off' and otherdevices['IsDark']== 'Off' and uservariables['Coming_home_light'] == 0 ) then
        commandArray['Sofa & paint light']='On'
        commandArray['Lamp livingroom']='On'
        commandArray['bed light]='On'
        commandArray['Variable:Coming_home_light'] = '1'
 elseif (otherdevices['alarm'] == 'Off' and uservariables['Coming_home_light'] == 1) then
                commandArray['Variable:Coming_home_light'] = '0'
 end
Setup:
- RPi4 - Domo Stable / Aeotec Z-stick7 / PiHole Unbound Gemini
- RPi4 - PiHole / PiVPN Unbound Gemini
- Synology DS923+ / DS218j
- P1 Gas/Power, SmartGateway watermeter
- Fibaro switches, contacts, plugs, smoke/Co2 ect
- rootfs @ USB HDD
Kivi
Posts: 6
Joined: Wednesday 15 April 2015 20:54
Target OS: Linux
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by Kivi »

After editing the script and testing, I still cant get this work. If I remove second if statement then the script works fine, but whit if uservariables the script wont do nothing, why is that? I also made test blocky script and still dident succseed.

Code: Select all

commandArray = {}
if (devicechanged['Alarm'] == 'Off' and otherdevices['IsDark'] == 'On') then
   if ( uservariables["Coming_home_light"] == 1 ) then
                print('<font color="blue">debug: statement works</font>')
                commandArray[light_switch]= 'On'
                commandArray['Sofa & paint light']= 'On'
        end
end
return commandArray
User avatar
cyberclwn
Posts: 103
Joined: Thursday 20 August 2015 22:53
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Location: The Netherlands
Contact:

Re: Script examples (Lua)

Post by cyberclwn »

Hey,

Can you try change the line:
Kivi wrote: Sunday 28 January 2018 21:36

Code: Select all

if ( uservariables["Coming_home_light"] == 1 ) then
to

Code: Select all

if (tonumber(uservariables["Coming_home_light"]) == 1 ) then

And probably also the other way around:

Code: Select all

commandArray['Variable:Coming_home_light'] = 1

Code: Select all

commandArray['Variable:Coming_home_light'] = tostring('1')
3xPi 2B (Domoticz "live", Domoticz "sandbox", PhotoFrame)
RFXCom433(E), KaKu, Oregon Scientific, Keyes 2-relay, Logitech Media Server, MiLight, Smartwares heating controller(2x), IR Send/Receive, Keyes PIR, XH-M131 DuskSensor, DHT22/11
snuiter
Posts: 67
Joined: Saturday 17 June 2017 12:30
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: Script examples (Lua)

Post by snuiter »

Hi,
need your help on lua/dZvent script to get output back in domoticz either to dummy switch/script to process.

I can check the tv status via domoticz raspberry(rPi1). TV is connected to remote raspberry pi(rPi2)
this works on the console but not via a script in domoticz.

Need some help to point me in the right direction.

This is the command I run on the command line

Code: Select all

ssh 192.168.x.x 'echo pow 0 | cec-client -s -d 1 | grep "power status:" | sed "s/..............//" '
output is either "on" or "standby"

Now I am trying with os.execute command in script, but not able to get the response from the command.

Any suggestion how to do that.
In a dZvent script I put these two line just for testing purposes

Code: Select all

	local t = os.execute('ping -c 192.168.x.x')
	print(t)
tried several other things but don't seem to be able to get the output I see from the same command on the console.

Any help is appreciated
bertus
Posts: 3
Joined: Friday 21 September 2018 16:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

cannot update user variable from Lua script

Post by bertus »

The LUA script below is meant to increment a user variable within domoticz; access to the variable works but updating it does not. please advice

counter = tonumber(uservariables["SWITCH"])
Commandarray = {}
if (devicechanged['SWITCH'] == 'On') then
counter = counter + 1
commandarray['variable:SWITCH'] = tostring(counter)
end
return commandarray
DutchHans
Posts: 229
Joined: Friday 03 April 2015 20:44
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Germany (near dutch border)
Contact:

Re: Script examples (Lua)

Post by DutchHans »

It's commandArray... Mind the capital A

Cheers,Hans
bertus
Posts: 3
Joined: Friday 21 September 2018 16:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by bertus »

Hi Hans,
thanks for the hint.
unfortunately it does not fix the issue...
Cheers, Bertus
bertus
Posts: 3
Joined: Friday 21 September 2018 16:25
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by bertus »

Hi Hans,
indeed caused by na uppercase misspell : variable
now it works
Cheers
User avatar
Petturik
Posts: 2
Joined: Friday 13 July 2018 13:05
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: NL
Contact:

Re: Script examples (Lua)

Post by Petturik »

Just wanted to share my Gardenlighting script.

Seeing I wanted a dimmer connected to the lighting and a standalone button to control the lighting aswell, I made this script.
Well, made, I compiled it from several examples.

Comments and feedback are welcome :

Code: Select all

-- If PIR detects motion (turns on) 
-- it's 10 minutes before sunset
-- AND the garden lights are off
-- turn them on for 2 minutes on level 50 

-- I don't want to override the "Scare" lighting by switching my kitchen switch, 
-- so I'll make a timer which runs for 2 minutes (see 'Timer Tuin').
-- During those 2 minutes, the lights can't be turned off by the kitchen switch

-- I want to receive a notification when movement is detected in the garden, but only when lights won't be turned on due to not meeting the 'ss' requirement

-- If the Kitchen switch is turned on,
-- AND the gardenlights are off,
-- turn them on at level 20.
-- But if the Kitchen switch is turned on and the Gardentimer is on,
-- turn off Kitchen switch

-- If the Kitchen switch is turned off
-- AND the gardenlights are not off
-- AND the timertest is not on,
-- turn off gardenlights

commandArray = {}

 -- get current time
    tn = os.date("*t")
    mn = tn.min + tn.hour * 60
 
 -- set sunset time
    ss = timeofday['SunsetInMinutes'] - 10
 
 -- devices
    n1 = 'nep'
    b1 = 'Burglar - Tuin'               -- Motion detection garden
    d1 = 'Tuin - Dim'                  	-- Dimmer for gardenlights
    s1 = 'Tuin'                      	-- Kitchen switch for gardenlights
    tt = 'Tuin - Timer'                	-- Dummy switch on a 3 minute "off" timer
 
 -- variables and commands
    dc = devicechanged
    otd = otherdevices
    ca = commandArray
    doff = (otd[d1]=="Off")
    dnoff = (otd[d1]~="Off")
    don = (otd[d1]=="On")
    soff = (dc[s1] == 'Off')
    son = (dc[s1] == 'On')
    ott = otd[tt]
  
if (dc[b1] == 'On' )                                          
    then
    	if (mn >= ss) 
            and doff
    	        then ca[d1]= 'Set Level 50 FOR 2'
                     ca[tt]= 'On'
                    print("Beweging, '".. d1 .."' aan voor 2 minuten")

        elseif (mn <= ss)
            and doff    
                then 
                    -- ca['SendNotification']= '#Beweging in de tuin, maar het is niet donker genoeg om de verlichting in te schakelen####telegram'
                    print("Beweging, maar niet in het donker")
end
    
elseif son 
    then
    	if doff 
    		    then ca[2]={[d1]= 'Set Level 20'}
                    print("'".. s1 .."' ingeschakeld, ik ga aan")
        elseif (ott=="On")
                then ca[3]={[s1]= 'Off'}
                    print("'".. d1 .."' staat aan, '".. s1 .."' gaat weer uit")
end
 
elseif soff 
    then
    	if dnoff
    		and (ott~="On") 
    		    then ca[4]={[d1]= 'Off'}
                    print("'".. s1 .."' uitgeschakeld, ik ga uit") 
end

end

return commandArray
p.s. I commented out the notification part, seeing it would spam me on a sunny day with the kids running around the garden all day :D
RPi3b+
Z-Wave(+)
Zigbee
ESP8266
rickiewickie
Posts: 6
Joined: Sunday 28 January 2018 12:51
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by rickiewickie »

Hi all,

Just finished a script which helps me to monitor certain devices that contains a specific text (Status_Check) in the device description field, and of course I want to share it to you guys :D

Function of the script: Find devices that matches the description above and are offline for more than 3 days.

Of course there a multiple ways to do this, but for me the best way was to enter the domoticz database directly and play around with SQL. And so I did..

Entering the database directly gives you a lot of options, but be aware that you also can destroy your database!

Comments and feedback is more than welcome.

Code: Select all


------------------ INSTALATION REQUIREMENTS-------------------------
--- sudo apt-get install sqlite3
--- sudo apt-get install lua-sql-sqlite3
--- In case of errors that lua module / files etc does not exists , use the following command
--- sudo ln -s /usr/lib/arm-linux-gnueabihf/lua /usr/local/lib/lua
--- Script is based on https://www.domoticz.com/forum/viewtopic.php?t=20283
--- Run as a time based scripts

local newline = ""
local extraline = ""
local subject = "DOMOTICZ- [Offline Devices Report] "
local mailto  = "r**********@hotmail.com"
local body =  ""  -- declare variable.  
 
 
commandArray = {}


time = os.date("*t")
if time.min % 60 == 0 then 

  
    local luasql = require('luasql.sqlite3') -- Tell LUA to use the luasql.sqlite3 library
    local env = luasql.sqlite3() -- intitialize the SQL-environment
    local db = env:connect('/home/pi/domoticz/domoticz.db') -- Make connection to the Domoticz database

 -- retrieve a cursor
cur = assert (db:execute"SELECT ID, Name, Description,LastUpdate FROM DeviceStatus WHERE Description Like '%Status_Check%' AND LastUpdate <= datetime('now','-3 days')")
-- print all rows, the rows will be indexed by field names
row = cur:fetch ({}, "a")
while row do
  
    newline = "IDX: \t" .. tostring(row.ID) .. "\t Name: " .. row.Name .."<br>"
    extraline = extraline .. newline .. "\n"
    
  -- reusing the table of results
  row = cur:fetch (row, "a")
end
 
    cur:close()
    db:close() -- After using the database you have to close the connection
    env:close() -- and close the environment
    
local content = ""
if extraline ~= "" then
    content = extraline
end


body = "Dear Domotic User,  <br> <br>This is a scheduled report to find devices that are offline for a more than 3 days. \n <br>Below a overview of all offline devices: \n <br><br> " .. content .. "\n\n <br>  With kind regards, \n <br><br> Your Home Automation System\n"
--print(body)


-- Only send an email when devices are found.
if content ~= "" then
print("Start to send a report.")
commandArray['SendEmail']=''..subject..'#'..body..'#'..mailto..''
end


end  -- end of time controller
 
 return commandArray
Search: modifying database, SQL, offline devices
postman
Posts: 1
Joined: Saturday 09 February 2019 19:48
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10659
Location: FRL NL
Contact:

Re: Script examples (Lua)

Post by postman »

Hi all,
(sorry for writing a book.. ;) )

I'm new to Domoticz and this Forum. Reason I got interested in Domoticz is that we recently bought a new house and I would like to (over time) turn it into a 'smarter' house.

So, my first projects is the mechanical ventilation. The mechanical ventilation has inlets in the toilet, kitchen and bathroom, but only 1 three-way switch in the kitchen :? So I would like to automate this and I had the following setup in mind:
- Control the vent-box on its 0-10v input using Qubino 0-10v dimmer
- Humidity sensor in the bathroom
- PIR sensor in the toilet

I know there are plenty of scripts around that you can copy-paste, but you don't learn from copy-pasting, so I decided to have a look at some examples and dive right in. The script I came up with works pretty well and does what it's supposed to do, but I would like some feedback from the LUA-masters on ways to improve the script, or other tips and tricks with regards to the usage of LUA, for example: I only use 'otherdevices' in my script, could I also use 'devicechanged'? I'm not sure about the difference in usage there. Also, what's the difference in declaring variables 'local' or not?

Here's the script:
I don't have the components yet I went ahead and set everything up using virtual switches/sensors. I used a dimmer to emulate the hum-sensor, so I understand at some point I will have to switch that out for the actual sensor and adjust the way the humidity is extracted...

It uses:
- Dimmer to control the vent-box
- Regular switch to activate a temporary ventilation boost on demand (using the timer function to turn it off automatically after, say, 30 mins)
- Switch that will be triggered by a PIR in the toilet. (using the timer function to turn it off automatically after, say, 15 mins)
- Dimmer to emulate a humidity sensor

Code: Select all

commandArray = {}

-- Variables
local debug                 = true
local vent_speed_min        = 15
local vent_speed_max        = 85

local vent_speed_toilet     = 50
local vent_speed_boost      = 85
local humidity_trigger      = 60
local humidity_step         = 5

-- Devices
local vent_switch    		= 'Vent'
local vent_boost_switch     = 'VentBoost (v)'
local toilet_visit_switch   = 'Toilet bezoek (v)'
local hum_sensor = 'Badkamer hum'

-- Functions 'borrowed' from @jvdz
-- round
function Round(num, idp)
   return tonumber(string.format("%." ..(idp or 0).. "f", num))
end
-- debug print
function dprint(text)
   if debug then print("@VSM:"..text) end
end

print('VentScript Module')

-- Internal variables
local new_fan_speed         = 0
local current_vent_speed = tonumber(otherdevices_svalues[vent_switch])
local bathroom_hum = tonumber(otherdevices_svalues[hum_sensor])
local hum_vent_ratio = (vent_speed_max - vent_speed_min) / (100 - humidity_trigger)
dprint('Calculated vent speed ratio: '.. hum_vent_ratio)


-- If the fan switch is set to Off, do nothing and return
if otherdevices[vent_switch] == "Off" then
    return
end

-- If the VentBoost switch is activated
if otherdevices[vent_boost_switch] == "On" then
    new_fan_speed = vent_speed_boost
    dprint('The VentBoost switch is activated. Setting new fan speed: '..new_fan_speed)
end
-- Someone went to the toilet
if otherdevices[toilet_visit_switch] == "On" and new_fan_speed < vent_speed_toilet then
    new_fan_speed = vent_speed_toilet
    dprint('Someone on the toilet and fan speed lower than toilet setting. Setting new fan speed: '..new_fan_speed)
end
-- Determine humidity fan speed
if bathroom_hum >= humidity_trigger then
    humidity = bathroom_hum
    if (bathroom_hum % humidity_step) > 0 then
        humidity = bathroom_hum + humidity_step - (bathroom_hum % humidity_step)
        -- Calculated humidity can be greater than 100 because of humidity_step size
        if humidity > 100 then
            humidity = 100
        end
    end

    hum_fan_speed = Round(vent_speed_min + ((humidity-humidity_trigger) * hum_vent_ratio))
    dprint('Actual humidity='..bathroom_hum..'; Humidity used for calculation='..humidity)
    dprint('Calculated Hum vent speed: '..hum_fan_speed)
    
    if hum_fan_speed > new_fan_speed then
        new_fan_speed = hum_fan_speed
        dprint('Humidity is higher then '..humidity_trigger..'%. Setting new fan speed: '..new_fan_speed)
    end
end
-- No new fan speed has been set based on above criteria, so set new fan speed to minimum/idle speed
if new_fan_speed == 0 then
    new_fan_speed = vent_speed_min
    dprint('No new fan speed is set. Setting new fan speed to MIN: '..new_fan_speed)
end
-- If the new fan speed not equals current speed, update the speed
if new_fan_speed ~= current_vent_speed then
    commandArray[vent_switch]='Set Level: '..tostring(new_fan_speed)..' %'
    print('New fan speed not equals current speed. Update vent speed to: '..new_fan_speed)
end

return commandArray
Thanks for any feedback or comments you may have.

Edit:
Updated the script to include a humidity step size, as I probably don't wan't my vent speed to change on every % humidity change (to save battery).
- Rpi3
- Razberry2 Z-Wave controller
- RFXtrx443XL
pybypl
Posts: 6
Joined: Thursday 10 November 2016 11:00
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by pybypl »

snuiter wrote: Wednesday 02 May 2018 19:45 Hi,
need your help on lua/dZvent script to get output back in domoticz either to dummy switch/script to process.

I can check the tv status via domoticz raspberry(rPi1). TV is connected to remote raspberry pi(rPi2)
this works on the console but not via a script in domoticz.

Need some help to point me in the right direction.

This is the command I run on the command line

Code: Select all

ssh 192.168.x.x 'echo pow 0 | cec-client -s -d 1 | grep "power status:" | sed "s/..............//" '
output is either "on" or "standby"

Now I am trying with os.execute command in script, but not able to get the response from the command.

Any suggestion how to do that.
In a dZvent script I put these two line just for testing purposes

Code: Select all

	local t = os.execute('ping -c 192.168.x.x')
	print(t)
tried several other things but don't seem to be able to get the output I see from the same command on the console.

Any help is appreciated
dont do it via lua script, create a bash script tvstatus.sh in /scripts
with content:
ssh 192.168.x.x 'echo pow 0 | cec-client -s -d 1 | grep "power status:" | sed "s/..............//" '
in next line set this dummy switch variable using json

and put this script to cron every 30/60 secs.
In case of trouble contact me via pm.
Tamil112
Posts: 10
Joined: Friday 15 November 2019 14:46
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Script examples (Lua)

Post by Tamil112 »

hi i am using this script and i like it al lot!!! only thing i want to do is still alternate my scene even if this script is running? can someone help me implant this in this script? i am newbie( DONT KNOW NOTHING) about LUA

hope to hear from you
thorbj wrote: Friday 06 February 2015 12:57 I made these two scripts to turn on the lights in the livingroom based on motion and lumen values in the room, and to turn off the lights if the lumen-values are high.
So far tests are great, so I hope it works for everyone else who wants to try it to.


TURN ON LIGHTS:

Code: Select all

-- ~/domoticz/scripts/lua/script_device_livingroomon.lua
-- When entering room, script reads current light level
-- and turns on the lights in the room based on given options.
-- If it's between 8AM and 8PM it chooses a scenery for day-lights,
-- and otherwise for evening/night-lights. It also measures the
-- lumen-values and decides if it is to bright in the room to
-- turn on the lights.
commandArray = {}

-- SETTINGS --
a = 'Lux sensor' -- name of the lux sensor
b = 'Motion Sensor' -- name of the motion sensor
c = 'Lamp 1' -- name of a lamp that this script should depend on

d = 500 -- maximum lumen value
-- END SETTINGS --

-- Define hours for day and evening lights
h = tonumber((os.date('%H')))
if     (h >= 8 and h < 20)
   then
   x = 'Scene:Livingroom ON day'
   else
   x = 'Scene:Livingroom ON night'
end

-- Get values from Lux sensor
V = otherdevices_svalues[a]

-- Remove charachters from datastring
function stripchars(str, chrs)
   local s = str:gsub("["..chrs.."]", '')
   return s end

-- Remove " Lux" from V
w = stripchars( V, " Lux" )

-- Issue command "x" if lux is below 500 (d) and motion is detected and dimmer is off
if    (tonumber(w) <= d and devicechanged[b] == 'On' and otherdevices[c] == 'Off') then   
   commandArray[x]='On'
   print(x)
end
return commandArray
TURN OFF LIGHTS:

Code: Select all

-- ~/domoticz/scripts/lua/script_device_livingroomoff.lua
-- This script reads the current lumen-values from a lux sensor and
-- turns off the lights if the values is above a given number.
commandArray = {}

-- SETTINGS --
a = 'Lux sensor' -- name of the lux sensor
b = 'Lamp 1' -- name of a lamp that this script should depend on
c = 'Lamp 2' -- name of an eventual second lamp that this script should depend on

d = 500 -- maximum lumen value

e = 'Scene:Livingroom OFF' -- name of scenario to be initiated

p = 'Lights in the livingroom has been turned off due to high lumen-values' -- text to be printed in log
-- END SETTINGS --

-- Get values from the Lux sensor
V = otherdevices_svalues[a]

-- Function to strip charachters
function
 stripchars(str, chrs)
 local s = str:gsub("["..chrs.."]", '')
 return s
end

-- Strip " Lux" from V
w = stripchars( V, " Lux" )

-- Turn off lights if dimmer is on and Lux is higher than 500 (d)
if     (tonumber(w) > d and otherdevices[b] == 'On' or tonumber(w) > d and otherdevices[c] == 'On') then   
 commandArray[e]='Off'
 print(p)
end
return commandArray
Cheers!
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests