Skip to content

Commit

Permalink
Added earthquake script
Browse files Browse the repository at this point in the history
  • Loading branch information
CreasolTech committed May 8, 2024
1 parent 1aeb755 commit edeec3b
Show file tree
Hide file tree
Showing 11 changed files with 322 additions and 42 deletions.
4 changes: 2 additions & 2 deletions alarm.lua
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,8 @@ function lightsNext()
end

function lightsCheck() -- check that zAlarmLights exists, if not init it and init lights[] dict
timenow=os.date("*t")
secondsnow = timenow.sec + timenow.min*60 + timenow.hour*3600
timeNow=os.date("*t")
secondsnow = timeNow.sec + timeNow.min*60 + timeNow.hour*3600
json=require("dkjson")
if (uservariables['zAlarmLights']==nil) then
lightsInit() -- init lights table
Expand Down
4 changes: 2 additions & 2 deletions config_fireAlarm.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ ROOMS={
{"Kitchen", "Temp_Cucina", 0.4, 30},
{"Living", "Temp_Soggiorno", 0.4, 30},
{"Office", "Temp_Studio", 0.6, 30},
{"Laundry", "Temp_Lavanderia", 2, 32}, -- DS1820 sensor behind the washer machine socket
{"Laundry", "Temp_Lavanderia", 3, 32}, -- DS1820 sensor behind the washer machine socket
{"Garage", "Temp_Garage", 0.6, 35},
-- {"Wallbox", "Temp_Wallbox", 0.3, 30},
{"Cellar", "TempRH_Cantina", 0.4, 24},
{"Bathroom", "Temp_Bagno", 1, 30},
{"Bedroom", "Temp_Camera", 0.4, 30},
{"Bedroom2", "TempRH_Camera", 0.6, 30},
{"Bedroom2", "TempRH_Camera", 2.5, 30},
{"BedroomVale", "Temp_Camera_Valentina",0.4, 30},
{"BedroomGuests", "Temp_Camera_Ospiti", 0.4, 30},
{"IroningRoom", "Temp_Stireria", 1.5, 35}, -- DS1820 sensor behind the power outlet connected to iron machine
Expand Down
7 changes: 4 additions & 3 deletions config_heatpump_emmeti.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
-- Written by Creasol, https://creasol.it - [email protected]
--

dofile "/home/pi/domoticz/scripts/lua/globalvariables.lua" -- some variables common to all scripts
dofile "/home/pi/domoticz/scripts/lua/globalfunctions.lua" -- some functions common to all scripts
dofile "scripts/lua/globalvariables.lua" -- some variables common to all scripts
dofile "scripts/lua/globalfunctions.lua" -- some functions common to all scripts

-- Some constants
TEMP_HISTERESIS=0.1
Expand All @@ -18,6 +18,7 @@ EVSTATE_DEV="EV State" -- EV state, used to know if vehicle is in chargin

--GasHeater='GasHeater' -- Activate gas heater instead of heat pump when external temperature very low: set to '' if a boiler does not exist
GasHeater='' -- it's not cheaper not greener than PDC => manually enabled only if PDC is not able to keep the temperature
GRID_VOLTAGE='Inverter - AC Voltage' -- Device measuring house voltage: if above 248V, heatpump can consume all available power
powerMeter='PowerMeter Grid' -- device name of power meter, that measure consumed power from the electric grid (negative when photovoltaic produced more than house usage)
inverterMeter='PV_PowerMeter' -- Inverter output power (photovoltaic). Set to '' if not available
inverter2Meter='PV_Garden' -- Inverter for the 2nd renewable energy source. Set to '' if not available
Expand Down Expand Up @@ -119,7 +120,7 @@ GHtimeMax=480 -- Minutes from midnight when GasHeater will be disabled
GHdevicesToEnable={} -- Device to enable when gas heater is ON {'devicename1','devicename2'}

DEBUG_LEVEL=E_INFO
DEBUG_LEVEL=E_DEBUG
--DEBUG_LEVEL=E_DEBUG
TELEGRAM_LEVEL=E_CRITICAL
DEBUG_PREFIX="HeatPump: "

6 changes: 5 additions & 1 deletion config_power.lua
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,17 @@ HOYMILES_ID='solar/116493522530/cmd/limit_nonpersistent_absolute' -- MQTT name t
--HOYMILES_ID='' -- MQTT name to set the output power limit using OpenDTU. '' to disable this function
HOYMILES_LIMIT_MAX=1600 -- Max power in watt
HOYMILES_TARGET_POWER=-6000 -- Target Power: 0 => no export. 50=import always at least 50W. -300=try to export always 300W
HOYMILES_LIMIT_PERC_DEV='PVgarden_Limit'
HOYMILES_PRODUCING_DEV='PVgarden_InverterProducing'
HOYMILES_RESTART_DEV='PVgarden_RestartInverter'

-- Output device: use any name of your choice
ledsGreen={'Led_Cucina_Green','Living_Led_Green','BagnoPT_LedG'} -- green LEDs that show power production
-- ledsRed={'Led_Cucina_Red','Living_Led_Red','BagnoPT_LedR' } -- red LEDs that show power usage
ledsRed={'Led_Cucina_Red','BagnoPT_LedR' } -- red LEDs that show power usage
ledsWhite={'Living_Led_White','Light_Night_Led','Led_Camera_White','Buzzer_Camera','Led_Camera_Ospiti_White','Led_Camera_Ospiti_WhiteLow'} -- White LEDs that will be activated in case of blackout. List of devices configured as On/Off switches
ledsWhite={'Living_Led_White','Light_Night_Led','Led_Camera_White','Led_Camera_Ospiti_White','Led_Camera_Ospiti_WhiteLow'} -- White LEDs that will be activated in case of blackout. List of devices configured as On/Off switches
ledsWhiteSelector={'Led_Cucina_White','BagnoPT_LedW'} -- White LEDs that will be activated in case of blackout. List of devices configured as Selector switches
blackoutBuzzers={'Buzzer_Camera'} -- Audio alert in case of power outage
HPMode='HeatPump_Mode' -- Selector switch for Off, Winter (heating), Summer (cooling)

EVLedStatus={''} -- status indicator for the electric car charging (1 flash => more than 1kW, 2 flashes => more than 2kW, ...}
Expand Down
6 changes: 3 additions & 3 deletions globalfunctions.lua
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,14 @@ end

function peakPower()
if (monthnow==nil) then monthnow = tonumber(os.date("%m")) end
if (timenow==nil) then timenow = os.date("*t") end
if (timeNow==nil) then timeNow = os.date("*t") end
if ((monthnow>=11 or monthnow<=3)) then
if ((timenow.hour>=7 and timenow.hour<10) or (timenow.hour>=17 and timenow.hour<21)) then
if ((timeNow.hour>=7 and timeNow.hour<10) or (timeNow.hour>=17 and timeNow.hour<21)) then
-- tonumber(otherdevices['Clouds_today'])<70)
return true
end
else -- from April to October
if ((timenow.hour>=7 and timenow.hour<10) or (timenow.hour>=18 and timenow.hour<22)) then
if ((timeNow.hour>=7 and timeNow.hour<10) or (timeNow.hour>=18 and timeNow.hour<22)) then
-- tonumber(otherdevices['Clouds_today'])<70)
return true
end
Expand Down
42 changes: 39 additions & 3 deletions power.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
--

-- At least a device with "Power" in its name has changed: let's go!

DEBUG_LEVEL=E_WARNING
--DEBUG_LEVEL=E_DEBUG

dofile "scripts/lua/config_power.lua" -- configuration file
timeNow=os.date("*t")

Expand All @@ -23,6 +27,7 @@ function PowerInit()
if (Power['ev']==nil) then Power['ev']=0 end -- used to force EV management now, without waiting 1 minute
if (Power['EV']==nil) then Power['EV']=0 end -- EV Charge power
if (Power['HL']==nil and HOYMILES_ID~='') then Power['HL']=HOYMILES_LIMIT_MAX end -- current limit value
if (Power['HS']==nil and HOYMILES_ID~='') then Power['HS']=0 end -- Inverter producing status (0=Off, 1=On)
--if (PowerAux==nil) then PowerAux={} end
end

Expand Down Expand Up @@ -241,15 +246,36 @@ for devName,devValue in pairs(devicechanged) do
end
end
if (HOYMILES_ID~='') then
-- set inverter limit to avoid exporting too much power to the grid (max 6000W in Italy, in case of single phase)
local newlimit=Power['HL']+currentPower-HOYMILES_TARGET_POWER
-- log(E_DEBUG, "HOYMILES: Power[HL]="..Power['HL'].." currentPower="..currentPower.." HOYMILES_TARGET_POWER="..HOYMILES_TARGET_POWER.." newlimit="..newlimit)
if (newlimit>HOYMILES_LIMIT_MAX) then
newlimit=HOYMILES_LIMIT_MAX
elseif (newlimit<0) then
newlimit=0
elseif (newlimit<100) then
newlimit=100 -- avoid turning off the inverter completely
end
if (tonumber(otherdevices[VOLTAGE_MAINS])>=250) then
log(E_WARNING,"HOYMILES: reduce max limit due to overvoltage")
newlimit=newlimit/2
end
local newlimitPerc=math.floor(newlimit*100/HOYMILES_LIMIT_MAX)
if (newlimit~=Power['HL'] or timeNow.min==0 and timeNow.sec>45) then
log(E_WARNING,"HOYMILES: transmit newlimit="..newlimit)
log(E_INFO,"HOYMILES: currentPower="..currentPower.." target="..HOYMILES_TARGET_POWER.." => Transmit newlimit="..newlimit.." "..newlimitPerc.."%")
os.execute('/usr/bin/mosquitto_pub -u '..MQTT_OWNER..' -P '..MQTT_PASSWORD..' -t '..HOYMILES_ID..' -m '..newlimit)
Power['HL']=newlimit
commandArray[#commandArray + 1]={['UpdateDevice']=otherdevices_idx[HOYMILES_LIMIT_PERC_DEV].."|0|".. newlimitPerc}
end
-- Now check that inverter is producing
if (otherdevices[HOYMILES_PRODUCING_DEV]=='Off') then
-- inverter not producing
if (Power['HS']==1 and tonumber(otherdevices[VOLTAGE_MAINS])>=240) then
-- inverter not producing due to overvoltage => restart it
log(E_WARNING,"HOYMILES: inverter not producing => restart now")
commandArray[HOYMILES_RESTART_DEV]='On'
end
Power['HS']=0
else
Power['HS']=1
end
end
end
Expand Down Expand Up @@ -397,6 +423,11 @@ for devName,devValue in pairs(devicechanged) do
Power['BLS_'..k]='On' -- store in a variable that this led was activated by blackout check
end
end
for k,buzzer in pairs(blackoutBuzzers) do
if (otherdevices_svalues[buzzer]~=nil) then
commandArray[buzzer]="On for 10"
end
end
else -- power restored
for k,led in pairs(ledsWhite) do
if (otherdevices[led]~=nil and otherdevices[led]~='0ff' and (Power['BL_'..k]==nil or Power['BL_'..k]=='On')) then
Expand All @@ -410,6 +441,11 @@ for devName,devValue in pairs(devicechanged) do
Power['BLS_'..k]=nil
end
end
for k,buzzer in pairs(blackoutBuzzers) do
if (otherdevices_svalues[buzzer]~=nil) then
commandArray[buzzer]="Off"
end
end
end
end
end
Expand Down
125 changes: 125 additions & 0 deletions script_time_earthquake.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
-- Original script from User mojso: see https://www.domoticz.com/forum/viewtopic.php?t=41380
-- This scripts gets earthquake info from www.seismicportal.eu for a defined area
-- Then updates dummy alert sensor with Time, Location, Magnitude, Depth, Distance
-- It takes the first entry (= the most recent one) and therefore runs every 5 minutes.
-- 21-03-2024 Version with some modifications by Jan Peppink, https://ict.peppink.nl
-- Make use of alert device in stead of text device.
-- Set alert color based on configurable distance.
-- Added links to source and map also in the device.
-- 2024-05-08: write as lua script by CreasolTech, using globalvariables and globalfunctions
-- Sends notifications by Telegram

commandArray={}
local timeNow=os.date('*t')
--if ((timeNow.min % 5)~=0) then return commandArray end -- exec script every 5 minutes

dofile "scripts/lua/globalvariables.lua"
dofile "scripts/lua/globalfunctions.lua"

DEBUG_LEVEL=E_WARNING
DEBUG_LEVEL=E_DEBUG
DEBUG_PREFIX="EarthQuake: "
EARTHQUAKE_DEV="EarthQuake" -- Create this text device by yourself!
MAXRADIUS=4 -- used to restrict data from the earthquake source
MAXDISTANCE=600 -- Max distance in km
MINMAGNITUDE=2.5 -- Min Richter magnitude
TELEGRAMMAGNITUDE=3 -- Min magnitude to send notification on smartphone
LATITUDE=45.88 -- Your latitude
LONGITUDE=12.18 -- Your longitude


--globalvariables
-- Set to your environment and preference
local mailto = '[email protected]' -- Set E-mail adres to sent to.
local alertIdx = n -- Set to the idx of the Virtual Alert sensor you have to create for this script

if (otherdevices[EARTHQUAKE_DEV]==nil) then
log(E_ERROR,"Please create a text device named "..EARTHQUAKE_DEV)
return commandArray
end
local lastalertText = otherdevices[EARTHQUAKE_DEV] -- Holds string of the previous round.
local alertText = ''

--Adjust these variables to get information about the place you want
local qMinmag = 2
local lTimediff = 3600 -- your local time 3600 equal +1 UTC time

-- Define distance for ALERTLEVEL colors
-- From dClose to radiusq ALERTLEVEL_GREY
local dClose = 750 -- From distance dCloser to dClose ALERTLEVEL_YELLOW
local dCloser = 500 -- From distance dClosest to dCloser ALERTLEVEL_ORANGE
local dClosest = 250 -- From distance 0 to closest ALERTLEVEL_RED

-- Local Functions go here =============
function titleCase( first, rest )
return first:upper()..rest:lower()
end

-- Calculate distance using Haversine formula
local function calculateDistance(lat1, lon1, lat2, lon2)
local R = 6371 -- Earth radius in kilometers
local dLat = math.rad(lat2 - lat1)
local dLon = math.rad(lon2 - lon1)
local a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(math.rad(lat1)) * math.cos(math.rad(lat2)) * math.sin(dLon / 2) * math.sin(dLon / 2)
local c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
local distance = R * c
return distance
end

-- Now start to do something ============
local fd=io.popen('curl -s "https://www.seismicportal.eu/fdsnws/event/1/query?limit=10&lat='..LATITUDE..'&lon='..LONGITUDE..'&minradius=0&maxradius='..MAXRADIUS..'&format=json&minmag='..MINMAGNITUDE..'"')
local response=assert(fd:read('*a'))
-- response = json data with list of earthquakes
json=require("dkjson")
local q=json.decode(response)
local qMag = tonumber(q.features[1].properties.mag)
local qRegion = tostring(q.features[1].properties.flynn_region)
local qTimeString = tostring(q.features[1].properties.time)
local qLat = tonumber(q.features[1].properties.lat)
local qLon = tonumber(q.features[1].properties.lon)
local qDepth = tonumber(q.features[1].properties.depth)

--local t = string.sub(cuando, 1,10)
local t = os.time{year=tonumber(qTimeString:sub(1,4)),
month=tonumber(qTimeString:sub(6,7)),
day=tonumber(qTimeString:sub(9,10)),
hour=tonumber(qTimeString:sub(12,13)),
min=tonumber(qTimeString:sub(15,16)),
sec=tonumber(qTimeString:sub(18,19))}
-- local atLocalTime = os.date('%H:%M %a %d %B %Y', t + lTimediff)
-- local atUTCtime = os.date('%H:%M %a %d %B %Y', t)
local atLocalTime = os.date('%d-%m-%Y %H:%M ', t + lTimediff)
local atUTCtime = os.date('%d-%m-%Y %H:%M ', t)
-- %d-%m-%Y %H:%M
qRegion = string.gsub(qRegion, "(%a)([%w_']*)", titleCase)

local distance = calculateDistance(LATITUDE, LONGITUDE, qLat, qLon)
-- Round the distance to the nearest kilometer
local roundedDistance = math.floor(distance + 0.5)

--Set and format the new alertText
local alertText = tostring( atLocalTime .. ' ' .. qRegion .. '\n' .. 'Mag: ' .. qMag .. '. Depth:' .. qDepth .. 'km Distance: ' .. roundedDistance .."km.\n"..'Location: <a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '" target="_new">Map</a>')

--[[
--Set and format the new mail message
local message = tostring('Location: ' .. qRegion .. '<br>' ..
'Magnitude: ' .. qMag .. '<br>' ..
'Depth: ' .. qDepth .. 'km<br>' ..
'UTC Time: ' .. atUTCtime .. '<br>' ..
'Locale Time: ' .. atLocalTime .. '<br>' ..
'Distance: ' .. roundedDistance .. 'km.<br>'..
'Coordinates: ' .. qLat .. ','.. qLon .. '<br>' ..
'<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '">Location</a>' .. '<br>' ..
'<a href="https://www.seismicportal.eu/">Source</a>' .. '<br>')
]]

-- Only update and sent message when info has changed. and
if (alertText ~= lastalertText and roundedDistance <= MAXDISTANCE) then
commandArray['UpdateDevice']=otherdevices_idx[EARTHQUAKE_DEV]..'|'.. math.floor(qMag-1) ..'|'..alertText
local priority=E_INFO
if (qMag>=TELEGRAMMAGNITUDE) then
priority=E_CRITICAL
end
log(priority,"Mag="..qMag.." Dist="..roundedDistance.."km "..qRegion.."\nhttps://maps.google.com/?q=" .. qLat .. ',' .. qLon )
end
return commandArray
Loading

0 comments on commit edeec3b

Please sign in to comment.