With a friend we made some nice lua scripts.. but when you made some scripts you always need the same coding for: rounding, calculate time differences etc.
So we made the following file:
MyFunc.lua
- Spoiler: show
Code: Select all
local My ={}
function My.GetUserVar(UserVar)
Waarde=uservariables[UserVar]
if Waarde==nil then
print(". User variable not set for : " .. UserVar)
UserVarErr=UserVarErr+1
end
return Waarde
end
function My.File_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
function My.Round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function My.GetValue(Text, GetNr)
Part=1
for match in (Text..';'):gmatch("(.-)"..';') do
if Part==GetNr then MyValue = tonumber(match) end
Part=Part+1
end
return MyValue
end
-- replace the last character
function My.EnumClear(Text)
a=string.len(Text)
b=string.sub(Text,a,a)
if b=="," or b==" " then Text=string.sub(Text,1,a-1) end
a=string.len(Text)
b=string.sub(Text,a,a)
if b=="," or b==" " then Text=string.sub(Text,1,a-1) end
return Text
end
function My.ConvTime(TimeX)
year = string.sub(TimeX, 1, 4)
month = string.sub(TimeX, 6, 7)
day = string.sub(TimeX, 9, 10)
hour = string.sub(TimeX, 12, 13)
minutes = string.sub(TimeX, 15, 16)
seconds = string.sub(TimeX, 18, 19)
ResTime = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
return ResTime
end
function My.TimeDiff(Time1,Time2)
if string.len(Time1)>12 then Time1 = My.ConvTime(Time1) end
if string.len(Time2)>12 then Time2 = My.ConvTime(Time2) end
ResTime=os.difftime (Time1,Time2)
return ResTime
end
return My
You can use the functions in every lua script after you include the library with this lines:
Code: Select all
package.path = package.path .. ';' .. '/home/pi/domoticz/scripts/lua/?.lua'
My = require('MyFunc')
Example uasage
Check if file exist.
Code: Select all
if not My.File_exists(LogFile) then
Get UserVar and Print when missing
Get value of a user variable, but when the user variable not exist the function prints print (". User variable not set for : " .. UserVar) to the log.
When you use this function for all the variables users who copy your script gets in logging a message which variables they must make.
Code: Select all
LogFile = My.GetUserVar("SUN_LogFile")
Get the X value of a device
5 in this example can you change in the number of the value.
my Wind meter gives: 207.00;SSW;9;18;16.4;16.4 so I need fift value for temperature
Code: Select all
Variable = My.GetValue(otherdevices_svalues[DeviceName],5)
Round numbers.
Code: Select all
My.Round(ValueThatNeedsToRounded,1)
TimeDifferences
The example below gave to difference between now and the time that a devices is last changed in minutes
Code: Select all
TDiff = My.Round(My.TimeDiff(os.time(),otherdevices_lastupdate[DeviceManual])/60,0)
If you Have also some nice functions, reply with coding, explanation and example