Page 1 of 1

Earthquake info from www.seismicportal.eu

Posted: Thursday 18 January 2024 12:04
by mojso
Earthquake info from www.seismicportal.eu
more detailed information on telegram about the earthquake

Code: Select all

-- This script was created by mojso
-- https://github.com/mojso/Domoticz_scripts
--this scripts gets earthquake info from www.seismicportal.eu for a defined area and then updates a text sensor with Magnitude and location
--it takes the first entry (= the most recent one) and therefore runs every 5 minutes

return {
	on = {
		timer = { 'every 5 minutes'},
		httpResponses = { 'kwakeV4' } -- matches callback string below
	},
	
	execute = function(domoticz, triggerItem)

-----Adjust these variables to get information about the place you want
local yourLatitude = xx.xxxx
local yourLongitude = xx.xxxx
local radiusq = 700  --radius for how far you want to receive information
local minmagq = 1
local yourlocaltime = 3600  -- your local time 3600 equal +1 UTC time

function titleCase( first, rest )
   return first:upper()..rest:lower()
end
local sensor = domoticz.devices('EarthquakeDevice')
local currInfo = tostring(sensor.text)

		if (triggerItem.isTimer) then
			domoticz.openURL({
				url = 'www.seismicportal.eu/fdsnws/event/1/query?limit=10&lat='..yourLatitude..'&lon='..yourLongitude..'&minradius=0.1&maxradius=180&format=json&minmag='..minmagq..'',
				method = 'GET',
				callback = 'kwakeV4'
			})
			
		elseif (triggerItem.isHTTPResponse) then

	local response = triggerItem
		if (response.ok and response.isJSON) then

				local mgt = tonumber(response.json.features[1].properties.mag)
				local lugar = tostring(response.json.features[1].properties.flynn_region)
				local timestampString = tostring(response.json.features[1].properties.time)
				local latq = tonumber(response.json.features[1].properties.lat)
				local lonq = tonumber(response.json.features[1].properties.lon)
				local depthq = tonumber(response.json.features[1].properties.depth)
				--local t = string.sub(cuando, 1,10)
				local t = os.time{year=tonumber(timestampString:sub(1,4)), 
                                   month=tonumber(timestampString:sub(6,7)), 
                                   day=tonumber(timestampString:sub(9,10)), 
                                   hour=tonumber(timestampString:sub(12,13)), 
                                   min=tonumber(timestampString:sub(15,16)), 
                                   sec=tonumber(timestampString:sub(18,19))}
		                local reString = os.date('%H:%M %a %d %B %Y', t + yourlocaltime) 
				        local reStringUTC = os.date('%H:%M %a %d %B %Y', t)
				lugar = string.gsub(lugar, "(%a)([%w_']*)", titleCase)
				
							-- 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

        local distance = calculateDistance(yourLatitude, yourLongitude, latq, lonq)
-- Round the distance to the nearest kilometer
        local roundedDistance = math.floor(distance + 0.5)
              local qInfo = tostring('Magnitude of '.. mgt.. ' in '..lugar.. ' at '..reString.. ' '  .. roundedDistance ..'km Away from you')
						local message = tostring(" ‼ Earthquake detected ‼ \n" ..
						            "🎯 Distance: " .. roundedDistance .. "km Away from you\n" ..
						            "UTC Time: " ..reStringUTC.. "\n" ..
						            "Your Time: " ..reString.. "\n" ..
                                    "Magnitude: " .. mgt .. "\n" ..
                                    "Depth: " .. depthq .. "km \n" ..
                                    "Location: " .. lugar .. "\n" ..
                                    "Coordinates: " .. latq .. ",".. lonq .. "\n" ..
                                    "Map address: https://maps.google.com/?q="..latq..","..lonq)
                                    if qInfo ~= currInfo and  roundedDistance < radiusq then
    						sensor.updateText(qInfo)
    						-- if you don't want to receive notifications, put -- at the beginning of the row below 
    						domoticz.notify('qInfo', message , domoticz.PRIORITY_NORMAL,nil,nil,domoticz.NSS_TELEGRAM)
                            --domoticz.notify('qInfo', qInfo , domoticz.PRIORITY_NORMAL,nil,nil,domoticz.NSS_HTTP)
                    
    						end
    					

		end

			else
				print('**kwake failed to fetch info')
			end
		
	end
}



Re: Earthquake info from www.seismicportal.eu

Posted: Thursday 18 January 2024 15:53
by EdwinK
Thanks. Put it place now.

Re: Earthquake info from www.seismicportal.eu

Posted: Thursday 21 March 2024 14:43
by janpep
Thank you.
Very nice script and functionality.
It inspired me to adapt it to my personal situation, for which I made a number of changes and additions.
I still have to see if you can also limit the search area in the query to a desired radius around your own location.

For now:
-- Make use of alert device in stead of text device. (create that first and then use the idx.)
-- Get your own coordinates from the Domoticz settings
-- Set alert color based on configurable distance ranges.
I use 0-250 km = RED; 250-500 km = ORANGE; 500-750 km = YELLOW; 750-max distance set = GREY
-- Translated and reordered the content.
-- Reordered date format in atLocalTime and atUTCtime
-- Reordered info in alertText and email.
-- Added links to source and map also in the device.
-- Changed notification to email and set a mailto
-- Changed naming of some variables attempt to a more consistent naming.

It looks like this:
AardbevingInfo.png
AardbevingInfo.png (10.08 KiB) Viewed 1085 times

Code: Select all

-- 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 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.
--	Get your own coordinates from the Domoticz settings
--	Set alert color based on configurable distance.
--	Translated and reordered the content.
--	Reordered date format in atLocalTime and atUTCtime
--	Reordered info in alertText.
-- 	Added links to source and map also in the device.
--	Changed notification to email and set a mailto
--	Changed naming of some variables attempt to a more consistent naming.

return {
	on = {
		timer = { 'every 2 minutes' },
		httpResponses = { 'qResponse' }   -- matches callback string below
	},
	
	execute = function(domoticz, triggerItem)
		-- 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
        	local qRadius = 1000		-- Set the radius for how far you want to receive information
        
		-- Set your loccation coordinates from Domoticz settings =================
		local yourLatitude = domoticz.settings.location.latitude
		local yourLongitude = domoticz.settings.location.longitude

		local alertLevel = domoticz.ALERTLEVEL_GREY -- Holds the alertLevel (color) to set
		local alertText = ''
		local lastalertText = domoticz.devices(alertIdx).text	-- Holds string of the previous round.

		--Adjust these variables to get information about the place you want
		local qMinmag = 1
		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 ============
		if (triggerItem.isTimer) then
			domoticz.openURL({
				url = 'www.seismicportal.eu/fdsnws/event/1/query?limit=10&lat='..yourLatitude..'&lon='..yourLongitude..'&minradius=0&maxradius=180&format=json&minmag='..qMinmag..'',
				method = 'GET',
				callback = 'qResponse'
			})	
		elseif (triggerItem.isHTTPResponse) then
			local response = triggerItem
			
			if (response.ok and response.isJSON) then
			    -- We have something.
				local qMag = tonumber(response.json.features[1].properties.mag)
				local qRegion = tostring(response.json.features[1].properties.flynn_region)
				local qTimeString = tostring(response.json.features[1].properties.time)
				local qLat = tonumber(response.json.features[1].properties.lat)
				local qLon = tonumber(response.json.features[1].properties.lon)
				local qDepth = tonumber(response.json.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(yourLatitude, yourLongitude, qLat, qLon)
				-- Round the distance to the nearest kilometer
				local roundedDistance = math.floor(distance + 0.5)
				
                --Set Alertlevel color based on distance.
				if roundedDistance < dClosest then
				    alertLevel = domoticz.ALERTLEVEL_RED
				elseif roundedDistance >= dClosest and roundedDistance < dCloser then
                    alertLevel = domoticz.ALERTLEVEL_ORANGE
                elseif roundedDistance >= dCloser and roundedDistance < dClose then
                    alertLevel = domoticz.ALERTLEVEL_YELLOW
                else
                    alertLevel = domoticz.ALERTLEVEL_GREY
                end
                
                --Set and format the new alertText
				local alertText = tostring(  atLocalTime .. ' uur in ' .. qRegion .. '\n' .. 'Magnitude: ' .. qMag .. '. Diepte: ' .. qDepth .. ' km. Afstand: ' .. roundedDistance ..' km.\n' .. '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '" target="_blank">Toon locatie</a>' .. ' - ' .. '<a href="https://www.seismicportal.eu/" target="_blank">Toon bron</a>')
                
                --Set and format the new mail message				
				local message = tostring('Locatie       : ' .. qRegion .. '<br>' ..
					'Magnitude: ' .. qMag .. '<br>' ..
					'Diepte: ' .. qDepth .. 'km<br>' ..
					'UTC Tijd: ' .. atUTCtime .. '<br>' ..
					'Lokale Tijd: ' .. atLocalTime .. '<br>' ..
					'🎯 Afstand: ' .. roundedDistance .. 'km.<br>'..
					'Coordinaten: ' .. qLat .. ','.. qLon .. '<br>' ..
					'<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '">Toon locatie</a>' .. '<br>' ..
					'<a href="https://www.seismicportal.eu/">Toon bron</a>' .. '<br>')

                -- Only update and sent message when info has changed. and 
				if alertText ~= lastalertText and roundedDistance < qRadius then
				    domoticz.devices(alertIdx).updateAlertSensor(alertLevel, alertText)
					domoticz.email( 'Aardbeving in ' .. qRegion, message, mailto )
				end			
			end
		else
			print('** EarthquakeInfo script failed to fetch info')
		end
	end
}

Re: Earthquake info from www.seismicportal.eu

Posted: Tuesday 07 May 2024 20:05
by janpep
I am curious about your experiences with https://www.seismicportal.eu/ I noticed that earthquakes have now occurred in the Netherlands that were not on the list.

I then looked at the API on USGS. See: https://earthquake.usgs.gov/fdsnws/event/1/
I experienced the same thing here!

I don't necessarily need to know about every earthquake anywhere in the world. I am mainly concerned with earthquakes in the Netherlands and the immediate surroundings, so I started searching further and came across the RSS feed of the KNMI. See: https://cdn.knmi.nl/knmi/map/page/seism ... MI_RSS.xml

I have now decided to rebuild the script and parse the XML from this RSS feed.
I kept the same procedure and check every 5 minutes for the latest one listed and only update if there is new information.

Re: Earthquake info from www.seismicportal.eu

Posted: Wednesday 08 May 2024 13:43
by HvdW
janpep wrote: Tuesday 07 May 2024 20:05 I have now decided to rebuild the script and parse the XML from this RSS feed.
I kept the same procedure and check every 5 minutes for the latest one listed and only update if there is new information.
I'm waiting for your new code to be published.
This earthquake thingy is completely useless here in Twente but nevertheless a beautifull addition to the Domoticz setup.

Re: Earthquake info from www.seismicportal.eu

Posted: Wednesday 08 May 2024 14:50
by janpep
In order not to mix the content with the current topic, I have started a new topic for the KNMI Earthquakes RSS feed.
See: Earthquake info from KNMI

Re: Earthquake info from www.seismicportal.eu

Posted: Wednesday 08 May 2024 21:57
by psubiaco
Wow, I took this dzVents script and rewrite in LUA to get earthquake alerts.
script_time_earthquake.lua can be found at https://github.com/CreasolTech/domoticz_lua_scripts
Of course it's possible to set your location, max distance, min magnitude to update the Domoticz alert sensor, min magnitude to have a Telegram notification on your smartphone.
screenshot of domoticz panel showing earthquakes
screenshot of domoticz panel showing earthquakes
domoticz_earthquake.png (47.23 KiB) Viewed 959 times

Re: Earthquake info from www.seismicportal.eu

Posted: Wednesday 08 May 2024 22:47
by janpep
I see the example from Switzerland. That was my 'problem'!
I also got earthquakes from Switzerland, Poland, Italy, Greece etc. where I do not live. But from this source I never received information from the Netherlands, while they have occured and where reported on other sites like KNMI as mentioned.

Re: Earthquake info from www.seismicportal.eu

Posted: Thursday 09 May 2024 1:36
by mojso
This is my second version of my script.

Code: Select all

-- This script was created by mojso
-- https://github.com/mojso/Domoticz_scripts
--this scripts gets earthquake info from www.seismicportal.eu for a defined area and then updates a text sensor with Magnitude and location
--it takes the first entry (= the most recent one) and therefore runs every 5 minutes

return {
	on = {
		timer = { 'every 2 minutes'},
		httpResponses = { 'kwakeV4' } -- matches callback string below
	},
	
	execute = function(domoticz, triggerItem)

-----Adjust these variables to get information about the place you want
local yourLatitude =  domoticz.settings.location.latitude 
local yourLongitude = domoticz.settings.location.longitude
local radiusq = 300  --radius for how far you want to receive information
local radiusq2 = 700 -- second radius
local minmagq = 1 --min magnitude for first radius
local minmagq2 = 4.2 -- min magnitude for second radius
local yourlocaltime = 7200  -- your local time 3600 equal +1 UTC time
local minmagworld = 6.5 --minimum earthquake magnitude for the whole world

function titleCase( first, rest )
   return first:upper()..rest:lower()
end
local sensor = domoticz.devices('Earthquake EU radius')
local currInfo = tostring(sensor.text)

		if (triggerItem.isTimer) then
			domoticz.openURL({
				url = 'www.seismicportal.eu/fdsnws/event/1/query?limit=10&lat='..yourLatitude..'&lon='..yourLongitude..'&minradius=0.1&maxradius=180&format=json&minmag='..minmagq..'',
				method = 'GET',
				callback = 'kwakeV4'
			})
			
		elseif (triggerItem.isHTTPResponse) then

	local response = triggerItem
		if (response.ok and response.isJSON) then

				local mgt = tonumber(response.json.features[1].properties.mag)
				local lugar = tostring(response.json.features[1].properties.flynn_region)
				local timestampString = tostring(response.json.features[1].properties.time)
				local latq = tonumber(response.json.features[1].properties.lat)
				local lonq = tonumber(response.json.features[1].properties.lon)
				local depthq = tonumber(response.json.features[1].properties.depth)
				local qid = tonumber(response.json.features[1].properties.source_id)
				--local t = string.sub(cuando, 1,10)
				local t = os.time{year=tonumber(timestampString:sub(1,4)), 
                                   month=tonumber(timestampString:sub(6,7)), 
                                   day=tonumber(timestampString:sub(9,10)), 
                                   hour=tonumber(timestampString:sub(12,13)), 
                                   min=tonumber(timestampString:sub(15,16)), 
                                   sec=tonumber(timestampString:sub(18,19))}
		                local reString = os.date('%H:%M %a %d %B %Y', t + yourlocaltime) 
				        local reStringUTC = os.date('%H:%M %a %d %B %Y', t)
				lugar = string.gsub(lugar, "(%a)([%w_']*)", titleCase)
				
							-- 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

        local distance = calculateDistance(yourLatitude, yourLongitude, latq, lonq)
-- Round the distance to the nearest kilometer
        local roundedDistance = math.floor(distance + 0.5)
        local mapurl = '<a href="https://maps.google.com/?q='..latq..','..lonq..'"><font color="green">Location</font></a>'
        local moreinfo = '<a href="https://m.emsc.eu/?id='..qid..'"><font color="green">More info</font></a>'
              local qInfo = tostring('Magnitude of '.. mgt.. '<br> in '..lugar.. '<br> at '..reString.. '<br>'  .. roundedDistance ..'km Away from you <br>'.. mapurl .. ' | ' .. moreinfo)
						local message = tostring(" ‼ Earthquake detected ‼ \n" ..
						            "🎯 Distance: " .. roundedDistance .. "km Away from you\n" ..
						            "UTC Time: " ..reStringUTC.. "\n" ..
						            "Your Time: " ..reString.. "\n" ..
                                    "Magnitude: " .. mgt .. "\n" ..
                                    "Depth: " .. depthq .. "km \n" ..
                                    "Location: " .. lugar .. "\n" ..
                                    "Coordinates: " .. latq .. ", ".. lonq .. "\n" ..
                                    "Map address: https://maps.google.com/?q="..latq..","..lonq.. "\n" ..
                                     "More Info: https://m.emsc.eu/?id="..qid)
         -- Message to Kodi
            local mesageKodi = tostring('Magnitude of '.. mgt.. ' in '..lugar.. ' at '..reString.. ' , '  .. roundedDistance ..'km Away from you ')
        -- --------        
                                    if qInfo ~= currInfo and  roundedDistance < radiusq or qInfo ~= currInfo and mgt >= minmagworld or qInfo ~= currInfo and  roundedDistance > radiusq  and roundedDistance < radiusq2 and mgt > minmagq2 then
    						sensor.updateText(qInfo)
    						-- if you don't want to receive notifications, put -- at the beginning of the row below 
    						domoticz.notify('qInfo', message , domoticz.PRIORITY_NORMAL,nil,nil,domoticz.NSS_TELEGRAM)
                            domoticz.notify('qInfo', mesageKodi , domoticz.PRIORITY_NORMAL,nil,nil,domoticz.NSS_KODI)
                    
    						end
    					

		end

			else
				print('**kwake failed to fetch info')
			end
		
	end
}