Earthquake info from KNMI

In this subforum you can show projects you have made, or you are busy with. Please create your own topic.

Moderator: leecollings

janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Earthquake info from KNMI

Post by janpep »

On https://www.seismicportal.eu/ and https://earthquake.usgs.gov/fdsnws/event/1/ I missed earthquakes that had occurred in the Netherlands. Looking further, I discovered the RSS feed of KNMI seismology.
This RSS provides an xml with the last 30 registrations of earthquakes and other seismo-acoustic sources in and around the Netherlands.

I ended up adapting the script I started with ( from https://www.domoticz.com/forum/viewtopic.php?t=41380) to parse the XML of this RSS feed. Below is the result.

Functionality:
  • Runs every 5 minutes and gets the most recent earthquakes.
  • Updates alert device only when info has changed.
  • It gives date, time, place, magintude, depth and distance (from your location), as well as a link for location on google maps and also a link for the more detailed source info at KNMI.
  • It sets the alert color based on configurable distance ranges. I now use 0-100 km = RED; 100-200 km = ORANGE; 200-300 km = YELLOW; >300 km = GREY.
  • It sends email when the distance is closer.
For the rest, see the comments in the script.

Result:
AardbevingInfo.png
AardbevingInfo.png (12.39 KiB) Viewed 1925 times

NB. I make use of the 'global_data' setup where scripts centrally store persistent data and where central helper functions are placed.
I give my entire 'global_data' script. You may or may not want to use the logging function. If not, you have also to modify corresponding lines in the script that call this function. Save this script as 'global_data', or take the used functions in your existing script.

t-Earthquake-KNMI

Code: Select all

-- 07-05-2024 script by Jan Peppink, https://ict.peppink.nl
-- Based on earlier script found on https://www.domoticz.com/forum/viewtopic.php?t=41380
-- Missed Dutch earthquakes. Modified script to get info from KNMI Aardbevingen RSS 
-- Parse XML result to get info from the most recent of 30 in the list.
-- URL = https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml

--- Your settings ----------------------------------------------------------------
-- First set the used device index numbers and variables you might want to change.
local alertIdx = n           -- Set to the idx of the Virtual Alert sensor you have to create for this script
local mailto = '[email protected]' -- Set E-mail adres to sent notification to.
local knmiURL = 'https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml'

-- Define distance for ALERTLEVEL colors
-- From dClose to the maxRadius we get: ALERTLEVEL_GREY
local dClose = 300          -- From distance dCloser to dClose: ALERTLEVEL_YELLOW
local dCloser = 200         -- From distance dClosest to dCloser: ALERTLEVEL_ORANGE (+ eMail notification)
local dClosest = 100        -- From distance 0 to closest: ALERTLEVEL_RED (+ eMail notification)

-- loging level 0 = NO logging, 1 = INFO, 2 = DEBUG, 3 = ERROR or 4 = FORCE
local debug_level = 0

return {
	on = {
		timer = { 
			'every 5 minutes',
        },
		httpResponses = { 'knmi-rss' }   -- matches callback string below
	},
    logging = {
    	level = domoticz.LOG_INFO,
    	marker = 'KNMI-',
    },	
	execute = function(domoticz, triggeredItem)
        -- Set Local environment=================
        local _u = domoticz.utils       -- Holds subset of handy utilities.
        local _h = domoticz.helpers     -- Holds the global functions.
        local _d = domoticz.globalData  -- Holds the global data.

	    -- Set your loccation coordinates from Domoticz settings =================
		local yourLatitude = domoticz.settings.location.latitude
		local yourLongitude = domoticz.settings.location.longitude

        -- Set your alert device index to store the result.
        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.

		local lTimediff = 0     -- Calculate diff in seconds between UTC and local time of this event.
		local delString = ""	-- Holds (sub) string to delete.

        -- Local Functions go here =============
		-- 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 (triggeredItem.isTimer) then
		    _h.logthis( domoticz, debug_level, knmiURL )
			domoticz.openURL({
			    url = knmiURL,
				method = 'GET',
				callback = 'knmi-rss'
			})	
		elseif (triggeredItem.isHTTPResponse) then
			if (triggeredItem.ok and triggeredItem.isXML) then
			    -- We have something, which looks like this:
                --<rss xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:georss="http://www.georss.org/georss" version="2.0">
                --  <channel>
                --      <copyright>Copyright KNMI</copyright>
                --      <description>KNMI - de laatste 30 registraties van aardbevingen en andere seismo-akoestische bronnen in en rondom Nederland</description>
                --      <title>KNMI - de meest recente registraties van aardbevingen en andere seismo-akoestische bronnen in en rondom Nederland</title>
                --      <item>
                --          <title>2024-05-05, 't Zandt, M=0.3</title>
                --          <description>2024-05-05, 19:14:45, Lat = 53.357, Lon = 6.783, Diepte = 3.0 km, M = 0.3, Plaats = 't Zandt, Author = KNMI, Type = Geinduceerd, Analyse = Reviewed</description>
                --          <geo:lat>53.357</geo:lat>
                --          <geo:lon>6.783</geo:lon>
                --          <georss:point>53.357 6.783</georss:point>
                --          <link>http://www.knmi.nl/nederland-nu/seismologie/aardbevingen/knmi2024ivvz</link>
                --          <guid>knmi2024ivvz</guid>
                --      </item>
                local result_table = triggeredItem.xml
                if type( result_table ) == "table" then
                    -- Get only the info from the first item.

                    -- Get link to page with details.
                    _h.logthis( domoticz, debug_level, result_table.rss.channel.item[1].link )
                    local qUrl = tostring( triggeredItem.xml.rss.channel.item[1].link )

                    -- The complete description to split up. Put is in a table.
                    _h.logthis( domoticz, debug_level, result_table.rss.channel.item[1].description )
                    local description_table = _u.stringSplit( result_table.rss.channel.item[1].description, ',' )

                    -- Get time (= UTC time) from the description_table.
                    -- Record 1 = 2024-05-05; Record 2 = 19:14:45 (strip the seconds)
                    local atUTCtime = description_table[1] .. ' ' .. string.sub( description_table[2], 1, 6 )
                    atUTCtime = domoticz.time.dateToDate( atUTCtime, 'yyyy-mm-dd hh:MM', 'dd-mm-yyyy hh:MM', 0 )
                    _h.logthis( domoticz, debug_level, 'atUTCtime = ' .. atUTCtime )

                    -- Calculate the Local time.			    
                    local qUnixtime = domoticz.time.dateToTimestamp( atUTCtime, 'dd-mm-yyyy hh:MM' )
                    lTimediff = _h.getUTCtimediffseconds( qUnixtime )
                    local atLocalTime = domoticz.time.timestampToDate( qUnixtime, 'dd-mm-yyyy hh:MM', lTimediff )
                    _h.logthis( domoticz, debug_level, 'atLocalTime = ' .. atLocalTime )

                    -- Record 3 = Lat = 53.357
                    delString = "Lat = "
                    local qLat = tostring(description_table[3]):gsub( delString, "" )
                    _h.logthis( domoticz, debug_level, 'qLat = ' .. qLat )
			    
                    -- Record 4 = Lon = 6.783
                    delString = "Lon = "
                    local qLon = tostring(description_table[4]):gsub( delString, "" )
                    _h.logthis( domoticz, debug_level, 'qLon = ' .. qLon )
			    
                    -- Record 5 = Diepte = 3.0 km
                    delString = "Diepte = "
                    local qDepth = tostring(description_table[5]):gsub( delString, "" )
                    _h.logthis( domoticz, debug_level, 'qDepth = ' .. qDepth )
			    
                    -- Record 6 = M = 0.3
                    delString = "M = "
                    local qMag = tostring( description_table[6]):gsub( delString, "" )
                    _h.logthis( domoticz, debug_level, 'qMag = ' .. qMag )
			    
                    -- Record 7 = Plaats = 't Zandt
                    delString = "Plaats = "
                    local qPlace = tostring(description_table[7]):gsub( delString, "" )
                    _h.logthis( domoticz, debug_level, 'qPlace = ' .. qPlace )

                    -- Record 8 = Author = KNMI
                    local qAuthor = description_table[8]
                
                    -- Record 9 = Type = Geinduceerd
                    local qType = description_table[9]
                
                    -- Record 10 = Analyse = Reviewed

                    -- Calculate distance from home location.
                    local distance = calculateDistance( yourLatitude, yourLongitude, qLat, qLon )
                    -- Round the distance to the nearest kilometer
                    local roundedDistance = _u.round( distance, 0 )
				
                    --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 ' .. qPlace .. '\n' .. 'Magnitude: ' .. qMag .. '. Diepte: ' .. qDepth .. '. Afstand: ' .. roundedDistance ..' km.\n' .. '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '" target="_blank">Toon locatie</a>' .. ' - ' .. '<a href="'  .. qUrl ..  '" target="_blank">Toon bron</a>' )

                    -- Only update and send mail when info has changed. and 
                    if alertText ~= lastalertText then
                        -- We have new information, so update the device.
                        domoticz.devices(alertIdx).updateAlertSensor(alertLevel, alertText)

                        -- Only send email when it comes closer then dCloser
                        if roundedDistance <= dCloser then
                            --Set and format the new mail message
                            local message = tostring('Plaats: ' .. qPlace .. '<br>' ..
                            'Magnitude: ' .. qMag .. '<br>' ..
                            'Diepte: ' .. qDepth .. '.<br>' ..
                            'Lokale Tijd: ' .. atLocalTime .. ' uur.<br>' ..
                            'UTC Tijd: ' .. atUTCtime .. ' uur.<br>' ..
                            'Afstand: ' .. roundedDistance .. 'km.<br>'..
                            'Coördinaten: ' .. qLat .. ','.. qLon .. '<br>' ..
                            qAuthor .. '<br>' ..
                            qType .. '<br>' ..
                            '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '">Toon locatie</a>' .. '<br>' ..
                            '<a href="' .. qUrl .. '">Toon bron</a>' .. '<br>')
                            domoticz.email( 'Aardbeving ' .. qPlace, message, mailto )
                        end
                    end
                else
                    _h.logthis( domoticz, debug_level, 'No result_table found' )
                end
	        else
    			_h.logthis( domoticz, debug_level, 'Item or XML - NOT OK' )
		    end
		else
			_h.logthis( domoticz, debug_level, 'Failed to fetch info' )
		end
	end
}
-- That's All --------------------------------------------------

global_data

Code: Select all

-- 05-01-2023: Script created by Jan peppink, https://ict.peppink.nl
-- This scripts holds all the globally persistent variables and helper functions
-- See the documentation in the wiki
-- NOTE: THERE CAN BE ONLY ONE global_data SCRIPT in your Domoticz install.
-- 26-03-2024: renamed variables; added: avgForcastwindspeed
-- 07-05-2024: Added function getUTCtimediffseconds

return {

	-- Global persistent data
	data = {
        -- Used in t-Alarmeringen for Alarmeringen.nl.
		lastAlarmNotification = {},
        -- Used in t-OpenMeteo-Air, d-OpenMeteo-Wind and d-StookwijzerLokaal.
        avgForcastLKI = { initial = 0 },
        avgForcastwindspeed = { initial = 0 },
        forcastHours = { initial = 0 },
    },

    -- Global helper functions
	helpers = {
	   getUTCtimediffseconds = function(qUnixtime)
            local timezone = os.date('%z', qUnixtime)   -- "+0200"
            local signum, hours, minutes = timezone:match '([+-])(%d%d)(%d%d)'
            local lTimediff = (tonumber(signum..hours)*3600 + tonumber(signum..minutes)*60)	       
            return lTimediff
        end,
        logthis = function( domoticz, debug_level, log_string )
		    -- Call this function with domoticz.helpers.logthis( domoticz, debug_level, 'string to log')
	    	-- The function gives the option to log or not to log under certain conditions.
		    -- You then have only to set debug_level once in a script to change the logging level (or skip logging).
            debug_level = debug_level or 0
            if debug_level ~= 0 then
                if debug_level == 1 then
                    log_level = domoticz.LOG_INFO
                elseif debug_level == 2 then
                    log_level = domoticz.LOG_DEBUG
                elseif debug_level == 3 then
                    log_level = domoticz.LOG_ERROR
                elseif debug_level == 4
                    then log_level = domoticz.LOG_FORCE
                else 
                    return
                end
                -- Function. Creates a logging entry in the Domoticz log but respects the log level settings.
                -- domoticz.LOG_INFO, domoticz.LOG_DEBUG, domoticz.LOG_ERROR or domoticz.LOG_FORCE
                -- In Domoticz settings you can set the log level for dzVents.
                -- For optional log_level the default is LOG_INFO
                if log_string ~= "" then
                    -- domoticz.log(message, [level])
                    domoticz.log( log_string, log_level )
                else
                    return
                end
            end
        end,
	}
}
-- That's All --------------------------------------------------
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
User avatar
waltervl
Posts: 5775
Joined: Monday 28 January 2019 18:48
Target OS: Linux
Domoticz version: 2024.7
Location: NL
Contact:

Re: Earthquake info from KNMI

Post by waltervl »

Thanks. I was triggered by your global_data logging. You made this to use a debug_level variable 0-4 instead of switching default script log level in the logging section?? Seems overcomplete to me....

Code: Select all

logging = {
    level = domoticz.LOG_DEBUG, --Can be .LOG_INFO, .LOG_MODULE_EXEC_INFO, .LOG_DEBUG or .LOG_ERROR
    marker = "Script-marker"
    },
Domoticz running on Udoo X86 (on Ubuntu)
Devices/plugins: ZigbeeforDomoticz (with Xiaomi, Ikea, Tuya devices), Nefit Easy, Midea Airco, Omnik Solar, Goodwe Solar
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

Yes, that may be true. I already had the feeling that I didn't understand this function properly. But then I wanted to go on and be able to set a rule at any desired location with the specific information I want to include in the log, while I can turn it on and off in one place in the script.

Code: Select all

_h.logthis( domoticz, debug_level, 'Log this, but only when debug_level > 0' )
In any case, the result is exactly what I wanted it to be and in global_data it can be called from any script.
With the functionality of the logging script marker I can just see that the scipt has run. (start and finish gives time it takes)
With the functionality of my function in combination with the debug_level, I can switch de more detailed logging on/off.
In fact I only use 0 or 1.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
User avatar
waltervl
Posts: 5775
Joined: Monday 28 January 2019 18:48
Target OS: Linux
Domoticz version: 2024.7
Location: NL
Contact:

Re: Earthquake info from KNMI

Post by waltervl »

You can set log level per logging line. eg

Code: Select all

dz.log('extra debug: Device 123 is ' .. myName, dz.LOG_DEBUG)  
From documentation:
domoticz.log(message, [level]): Function. Creates a logging entry in the Domoticz log but respects the log level settings. You can provide the loglevel: domoticz.LOG_INFO, domoticz.LOG_DEBUG, domoticz.LOG_ERROR or domoticz.LOG_FORCE. In Domoticz settings you can set the log level for dzVents.
See following topic for examples https://www.domoticz.com/forum/viewtopi ... 85#p279685
Domoticz running on Udoo X86 (on Ubuntu)
Devices/plugins: ZigbeeforDomoticz (with Xiaomi, Ikea, Tuya devices), Nefit Easy, Midea Airco, Omnik Solar, Goodwe Solar
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

Great! I will take a closer look to it.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

waltervl wrote: Wednesday 08 May 2024 16:01 See following topic for examples https://www.domoticz.com/forum/viewtopi ... 85#p279685
It's a bit off topic, but I see in the mentioned place that I am not the only one who wonders how to make the logging show or not show. :lol:
It can be detected from the examples given (thanks fot that!), but it is not very intuitive.
I still don't know if I fully understand it, but I can now achieve what I want with the test script below without using my separate log function in global_data.

1. I have kept the dzVents logging in Setup-Settings-Other to 'Errors only'.

2. For each line that I want to be able to include in the log, I use domoticz.LOG_INFO. E.g.:

Code: Select all

domoticz.log('Does this show up in the log?', domoticz.LOG_INFO )
3. When I want to see the logging I set the level = domoticz.LOG_INFO.
Result:

Code: Select all

2024-05-08 20:07:00.507 Status: dzVents: Info: test: ------ Start internal script: 3-TEST:, trigger: "every minute"
2024-05-08 20:07:00.508 Status: dzVents: Info: test: Does this show up in the log?
2024-05-08 20:07:00.510 Status: dzVents: Info: test: ------ Finished 3-TEST
4. When I want to turn it off I set the level higher to level = domoticz.LOG_MODULE_EXEC_INFO.
Result is what I wanted. Still be able to see that (and how long) the script ran without the details:

Code: Select all

2024-05-08 20:05:00.525 Status: dzVents: Info: test: ------ Start internal script: 3-TEST:, trigger: "every minute"
2024-05-08 20:05:00.527 Status: dzVents: Info: test: ------ Finished 3-TEST
Test script:

Code: Select all

-- 08-05-2024 script by Jan Peppink, https://ict.peppink.nl
-- Test script for logging functionality.
-- Change the level to domoticz.LOG_INFO to turn on.
-- Change the level to domoticz.LOG_MODULE_EXEC_INFO to turn off. (Start~ and end time remain visible in the log.)

return {
	on = {
	    timer = {
	        'every minute'
	       }
	},
	logging = {
	    -- Level can be domoticz.LOG_INFO, domoticz.LOG_MODULE_EXEC_INFO, domoticz.LOG_DEBUG or domoticz.LOG_ERROR
		level = domoticz.LOG_INFO, 
		marker = 'test',
	},
	execute = function(domoticz, device)
	    domoticz.log('Does this show up in the log?', domoticz.LOG_INFO )
	end
}
I think I will adjust my scripts accordingly.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

I updated the script and changed the logging + some minor other changes.
Note that function 'getUTCtimediffseconds' is still expected in global_data.

Code: Select all

-- 07-05-2024 script by Jan Peppink, https://ict.peppink.nl
-- Based on earlier script found on https://www.domoticz.com/forum/viewtopic.php?t=41380
-- Missed Dutch earthquakes. Modified script to get info from KNMI Aardbevingen RSS.
-- Parse XML result to get info from the most recent of 30 in the list.
-- URL = https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml
-- Function 'getUTCtimediffseconds' expected in global_data.
-- 09-05-2024 directly make use of dz.log instead of the 'logthis' function in global_data.

--- Your settings ----------------------------------------------------------------
-- First set the used device index numbers and variables you might want to change.
local alertIdx = n           -- Set to the idx of the Virtual Alert sensor you have to create for this script
local mailto = '[email protected]' -- Set E-mail adres to sent notification to.
local knmiURL = 'https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml'

-- Define distance for ALERTLEVEL colors
-- From dClose to the maxRadius we get: ALERTLEVEL_GREY
local dClose = 300          -- From distance dCloser to dClose: ALERTLEVEL_YELLOW
local dCloser = 200         -- From distance dClosest to dCloser: ALERTLEVEL_ORANGE (+ eMail notification)
local dClosest = 100        -- From distance 0 to closest: ALERTLEVEL_RED (+ eMail notification)

return {
	on = {
		timer = { 
			'every 5 minutes',
        },
		httpResponses = {
            'knmi-rss'   -- matches callback string below
        }
	},
    logging = {
	    -- Level can be domoticz.LOG_INFO, domoticz.LOG_MODULE_EXEC_INFO, domoticz.LOG_DEBUG, domoticz.LOG_ERROR or domoticz.LOG_FORCE
        level = domoticz.LOG_MODULE_EXEC_INFO,  -- = OFF
        --level = domoticz.LOG_INFO,            -- = ON
        --level = domoticz.LOG_DEBUG,
        --level = domoticz.LOG_ERROR,
        --level = domoticz.LOG_FORCE, 
    	marker = 'KNMI-',
    },	
	execute = function(dz, triggeredItem)
        -- Set Local environment=================
        local _u = dz.utils       -- Holds subset of handy utilities.
        local _h = dz.helpers     -- Holds the global functions.
        local _d = dz.globalData  -- Holds the global data.

	    -- Set your loccation coordinates from Domoticz settings =================
		local yourLatitude = dz.settings.location.latitude
		local yourLongitude = dz.settings.location.longitude

        -- Set your alert device index to store the result.
        local alertLevel = dz.ALERTLEVEL_GREY -- Holds the alertLevel (color) to set
        local alertText = ''
		local lastalertText = dz.devices(alertIdx).text   -- Holds string of the previous round.

		local lTimediff = 0     -- Calculate diff in seconds between UTC and local time of this event.
		local delString = ""	-- Holds (sub) string to delete.

        -- Local Functions go here =============
		-- 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 (triggeredItem.isTimer) then
		    dz.log( knmiURL, dz.LOG_INFO )
			dz.openURL({
			    url = knmiURL,
				method = 'GET',
				callback = 'knmi-rss'
			})	
		elseif (triggeredItem.isHTTPResponse) then
			if (triggeredItem.ok and triggeredItem.isXML) then
			    -- We have something, which looks like this:
                --<rss xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:georss="http://www.georss.org/georss" version="2.0">
                --  <channel>
                --      <copyright>Copyright KNMI</copyright>
                --      <description>KNMI - de laatste 30 registraties van aardbevingen en andere seismo-akoestische bronnen in en rondom Nederland</description>
                --      <title>KNMI - de meest recente registraties van aardbevingen en andere seismo-akoestische bronnen in en rondom Nederland</title>
                --      <item>
                --          <title>2024-05-05, 't Zandt, M=0.3</title>
                --          <description>2024-05-05, 19:14:45, Lat = 53.357, Lon = 6.783, Diepte = 3.0 km, M = 0.3, Plaats = 't Zandt, Author = KNMI, Type = Geinduceerd, Analyse = Reviewed</description>
                --          <geo:lat>53.357</geo:lat>
                --          <geo:lon>6.783</geo:lon>
                --          <georss:point>53.357 6.783</georss:point>
                --          <link>http://www.knmi.nl/nederland-nu/seismologie/aardbevingen/knmi2024ivvz</link>
                --          <guid>knmi2024ivvz</guid>
                --      </item>
                local result_table = triggeredItem.xml
                if type( result_table ) == "table" then
                    -- Get only the info from the first item.

                    -- Get link to page with details.
                    dz.log( result_table.rss.channel.item[1].link, dz.LOG_INFO )
                    local qUrl = tostring( triggeredItem.xml.rss.channel.item[1].link )

                    -- The complete description to split up. Put is in a table.
                    dz.log( result_table.rss.channel.item[1].description, dz.LOG_INFO )
                    local description_table = _u.stringSplit( result_table.rss.channel.item[1].description, ',' )

                    -- Get time (= UTC time) from the description_table.
                    -- Record 1 = 2024-05-05; Record 2 = 19:14:45 (strip the seconds)
                    local atUTCtime = description_table[1] .. ' ' .. string.sub( description_table[2], 1, 6 )
                    atUTCtime = dz.time.dateToDate( atUTCtime, 'yyyy-mm-dd hh:MM', 'dd-mm-yyyy hh:MM', 0 )
                    dz.log( 'atUTCtime = ' .. atUTCtime, dz.LOG_INFO )

                    -- Calculate the Local time.			    
                    local qUnixtime = dz.time.dateToTimestamp( atUTCtime, 'dd-mm-yyyy hh:MM' )
                    lTimediff = _h.getUTCtimediffseconds( qUnixtime )
                    local atLocalTime = dz.time.timestampToDate( qUnixtime, 'dd-mm-yyyy hh:MM', lTimediff )
                    dz.log( 'atLocalTime = ' .. atLocalTime, dz.LOG_INFO )

                    -- Record 3 = Lat = 53.357
                    delString = "Lat = "
                    local qLat = tostring(description_table[3]):gsub( delString, "" )
                    dz.log( 'qLat = ' .. qLat, dz.LOG_INFO )
			    
                    -- Record 4 = Lon = 6.783
                    delString = "Lon = "
                    local qLon = tostring(description_table[4]):gsub( delString, "" )
                    dz.log( 'qLon = ' .. qLon, dz.LOG_INFO )
			    
                    -- Record 5 = Diepte = 3.0 km
                    delString = "Diepte = "
                    local qDepth = tostring(description_table[5]):gsub( delString, "" )
                    dz.log( 'qDepth = ' .. qDepth, dz.LOG_INFO )
			    
                    -- Record 6 = M = 0.3
                    delString = "M = "
                    local qMag = tostring( description_table[6]):gsub( delString, "" )
                    dz.log( 'qMag = ' .. qMag, dz.LOG_INFO )
			    
                    -- Record 7 = Plaats = 't Zandt
                    delString = "Plaats = "
                    local qPlace = tostring(description_table[7]):gsub( delString, "" )
                    dz.log( 'qPlace = ' .. qPlace, dz.LOG_INFO )

                    -- Record 8 = Author = KNMI
                    local qAuthor = description_table[8]
                
                    -- Record 9 = Type = Geinduceerd
                    local qType = description_table[9]
                
                    -- Record 10 = Analyse = Reviewed

                    -- Calculate distance from home location.
                    local distance = calculateDistance( yourLatitude, yourLongitude, qLat, qLon )
                    -- Round the distance to the nearest kilometer
                    local roundedDistance = _u.round( distance, 0 )
				
                    --Set Alertlevel color based on distance.
                    if roundedDistance < dClosest then
                        alertLevel = dz.ALERTLEVEL_RED
                    elseif roundedDistance >= dClosest and roundedDistance < dCloser then
                        alertLevel = dz.ALERTLEVEL_ORANGE
                    elseif roundedDistance >= dCloser and roundedDistance < dClose then
                        alertLevel = dz.ALERTLEVEL_YELLOW
                    else
                        alertLevel = dz.ALERTLEVEL_GREY
                    end
                
                    --Set and format the new alertText
                    local alertText = tostring( atLocalTime .. ' uur in ' .. qPlace .. '\n' .. 'Magnitude: ' .. qMag .. '. Diepte: ' .. qDepth .. '. Afstand: ' .. roundedDistance ..' km.\n' .. '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '" target="_blank">Toon locatie</a>' .. ' - ' .. '<a href="'  .. qUrl ..  '" target="_blank">Toon bron</a>' )

                    -- Only update and send mail when info has changed. and 
                    if alertText ~= lastalertText then
                        -- We have new information, so update the device.
                        dz.devices(alertIdx).updateAlertSensor(alertLevel, alertText)

                        -- Only send email when it comes closer then dCloser
                        if roundedDistance <= dCloser then
                            --Set and format the new mail message
                            local message = tostring('Plaats: ' .. qPlace .. '<br>' ..
                            'Magnitude: ' .. qMag .. '<br>' ..
                            'Diepte: ' .. qDepth .. '.<br>' ..
                            'Lokale Tijd: ' .. atLocalTime .. ' uur.<br>' ..
                            'UTC Tijd: ' .. atUTCtime .. ' uur.<br>' ..
                            'Afstand: ' .. roundedDistance .. 'km.<br>'..
                            'Coördinaten: ' .. qLat .. ','.. qLon .. '<br>' ..
                            qAuthor .. '<br>' ..
                            qType .. '<br>' ..
                            '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '">Toon locatie</a>' .. '<br>' ..
                            '<a href="' .. qUrl .. '">Toon bron</a>' .. '<br>')
                            dz.email( 'Aardbeving ' .. qPlace, message, mailto )
                        end
                    end
                else
                    dz.log( 'No result_table found', dz.LOG_DEBUG )
                end
	        else
    			dz.log( 'Item or XML - NOT OK', dz.LOG_DEBUG )
		    end
		else
			dz.log( 'Failed to fetch info', dz.LOG_DEBUG )
		end
	end
}
-- That's All --------------------------------------------------
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
BazemanKM
Posts: 35
Joined: Wednesday 22 July 2015 21:39
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Earthquake info from KNMI

Post by BazemanKM »

Thanx for this script. I like it!
HvdW
Posts: 601
Joined: Sunday 01 November 2015 22:45
Target OS: Raspberry Pi / ODroid
Domoticz version: 2023.2
Location: Twente
Contact:

Re: Earthquake info from KNMI

Post by HvdW »

Maybe it's easier to change all LOG_INFO in the script to LOG_DEBUG
Under normal circumstances you can set level to LOG_ERROR and change it to LOG_DEBUG when necessary.

Code: Select all

    logging = {
        level = domoticz.LOG_DEBUG,
        --level = domoticz.LOG_ERROR,
    	marker = 'KNMI-earthquake',
    },
Bugs bug me.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

HvdW wrote: Friday 10 May 2024 0:16 Maybe it's easier to change all LOG_INFO in the script to LOG_DEBUG
For your own use, you may modify it however you like.
In my opinion that is just another level to get the same result.
Anyway.... this is sufficient for me for this moment. If I want to see the info in the log, I set it to 'info' and if I don't want to see it, I set it one level higher. If certain errors occur, (end of the script) the lines are always logged with 'debug', so I can see this.
I don't necessarily need to see 'error' emails for every missed call, so for me this works as expected.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
Kedi
Posts: 569
Joined: Monday 20 March 2023 14:41
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Somewhere in NL
Contact:

Re: Earthquake info from KNMI

Post by Kedi »

I agree with @HvdW.
It makes the script more readable and you don't need a separate (global) function, which is slower then @HvdW solution.
I myself also rewrote the script to use variables instead of global data.
But as said it is just a preference.
Logic will get you from A to B. Imagination will take you everywhere.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

A few times I got this error (by email):

Code: Select all

2024-05-10 09:45:01.572 Error: dzVents: Error: (3.1.8) KNMI-: .../scripts/dzVents/generated_scripts/t-Earthquake-KNMI.lua:108: bad argument #1 to 'sub' (string expected, got nil)
This is the line where it gets the time. Not clear to me yet when this happens or why it is nil. I will have a closer look to it.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

Dear all,
In the previous update I had already said goodbye to the central log function. It took me a while to figure out how to use the functionality according to my own wishes while keeping the naming logic intact. The example of HvdW did not really appeal to me, because with the level LOG_ERROR set, I do not longer see the execution information in the log under normal circumstances. Based on your comments and waltervl's examples, I think I have it now.
  • In Setup-Settings-Other I have the level set to ERROR. When unexpected errors occur, I receive an email notification.
  • For normal use, to see only when and how long the script has been running, I set the level in the script to:

    Code: Select all

    level = domoticz.LOG_INFO
  • When I am editing and testing the script I set the level to:

    Code: Select all

    level = domoticz.LOG_DEBUG
  • In the case of DEBUG level, in addition to the information about the execution, I also see all the lines that are set to LOG_DEBUG:

    Code: Select all

    domoticz.log('Log this for debug', domoticz.LOG_DEBUG)
  • And when errors occur, regardless of the level settings, they are always reported with:

    Code: Select all

    domoticz.log('Log this in case of error', domoticz.LOG_ERROR)
Here is the result:

Code: Select all

-- 07-05-2024 script by Jan Peppink, https://ict.peppink.nl
-- Based on earlier script found on https://www.domoticz.com/forum/viewtopic.php?t=41380
-- Missed Dutch earthquakes. Modified script to get info from KNMI Aardbevingen RSS.
-- Parse XML result to get info from the most recent of 30 in the list.
-- URL = https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml
-- Function 'getUTCtimediffseconds' expected in global_data.
-- 09-05-2024 directly make use of dz.log instead of the 'logthis' function in global_data.
-- 10-05-2024 Again some adjustments to the log function.

--- Your settings ----------------------------------------------------------------
-- First set the used device index numbers and variables you might want to change.
local alertIdx = n           -- Set to the idx of the Virtual Alert sensor you have to create for this script
local mailto = '[email protected]' -- Set E-mail adres to sent notification to.
local knmiURL = 'https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml'

-- Define distance for ALERTLEVEL colors
-- From dClose to the maxRadius we get: ALERTLEVEL_GREY
local dClose = 300          -- From distance dCloser to dClose: ALERTLEVEL_YELLOW
local dCloser = 200         -- From distance dClosest to dCloser: ALERTLEVEL_ORANGE (+ eMail notification)
local dClosest = 100        -- From distance 0 to closest: ALERTLEVEL_RED (+ eMail notification)

return {
	on = {
		timer = { 
			'every 5 minutes',
        },
		httpResponses = {
            'knmi-rss'   -- matches callback string below
        }
	},
    logging = {
	    -- Level can be domoticz.LOG_INFO, domoicz.LOG_MODULE_EXEC_INF domoticz.LOG_DEBUG, domoticz.LOG_ERROR or domoticz.LOG_FORCE
        level = domoticz.LOG_INFO,
        --level = domoticz.LOG_DEBUG,        
    	marker = 'KNMI-',
    },	
	execute = function(dz, triggeredItem)
        -- Set Local environment=================
        local _u = dz.utils       -- Holds subset of handy utilities.
        local _h = dz.helpers     -- Holds the global functions.
        local _d = dz.globalData  -- Holds the global data.

	    -- Set your loccation coordinates from Domoticz settings =================
		local yourLatitude = dz.settings.location.latitude
		local yourLongitude = dz.settings.location.longitude

        -- Set your alert device index to store the result.
        local alertLevel = dz.ALERTLEVEL_GREY -- Holds the alertLevel (color) to set
        local alertText = ''
		local lastalertText = dz.devices(alertIdx).text   -- Holds string of the previous round.

		local lTimediff = 0     -- Calculate diff in seconds between UTC and local time of this event.
		local delString = ""	-- Holds (sub) string to delete.

        -- Local Functions go here =============
		-- 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 (triggeredItem.isTimer) then
		    dz.log( knmiURL, dz.LOG_DEBUG )
			dz.openURL({
			    url = knmiURL,
				method = 'GET',
				callback = 'knmi-rss'
			})	
		elseif (triggeredItem.isHTTPResponse) then
			if (triggeredItem.ok and triggeredItem.isXML) then
			    -- We have something, which looks like this:
                --<rss xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:georss="http://www.georss.org/georss" version="2.0">
                --  <channel>
                --      <copyright>Copyright KNMI</copyright>
                --      <description>KNMI - de laatste 30 registraties van aardbevingen en andere seismo-akoestische bronnen in en rondom Nederland</description>
                --      <title>KNMI - de meest recente registraties van aardbevingen en andere seismo-akoestische bronnen in en rondom Nederland</title>
                --      <item>
                --          <title>2024-05-05, 't Zandt, M=0.3</title>
                --          <description>2024-05-05, 19:14:45, Lat = 53.357, Lon = 6.783, Diepte = 3.0 km, M = 0.3, Plaats = 't Zandt, Author = KNMI, Type = Geinduceerd, Analyse = Reviewed</description>
                --          <geo:lat>53.357</geo:lat>
                --          <geo:lon>6.783</geo:lon>
                --          <georss:point>53.357 6.783</georss:point>
                --          <link>http://www.knmi.nl/nederland-nu/seismologie/aardbevingen/knmi2024ivvz</link>
                --          <guid>knmi2024ivvz</guid>
                --      </item>
                local result_table = triggeredItem.xml
                if type( result_table ) == "table" then
                    -- Get only the info from the first item.

                    -- Get link to page with details.
                    dz.log( result_table.rss.channel.item[1].link, dz.LOG_DEBUG )
                    local qUrl = tostring( triggeredItem.xml.rss.channel.item[1].link )

                    -- The complete description to split up. Put it in a table.
                    dz.log( result_table.rss.channel.item[1].description, dz.LOG_DEBUG )
                    local description_table = _u.stringSplit( result_table.rss.channel.item[1].description, ',' )

                    -- Get time (= UTC time) from the description_table.
                    -- Record 1 = 2024-05-05; Record 2 = 19:14:45 (strip the seconds)
                    local atUTCtime = description_table[1] .. ' ' .. string.sub( description_table[2], 2, 6 )
                    atUTCtime = dz.time.dateToDate( atUTCtime, 'yyyy-mm-dd hh:MM', 'dd-mm-yyyy hh:MM', 0 )
                    dz.log( 'atUTCtime = ' .. atUTCtime, dz.LOG_DEBUG )

                    -- Calculate the Local time.			    
                    local qUnixtime = dz.time.dateToTimestamp( atUTCtime, 'dd-mm-yyyy hh:MM' )
                    lTimediff = _h.getUTCtimediffseconds( qUnixtime )
                    local atLocalTime = dz.time.timestampToDate( qUnixtime, 'dd-mm-yyyy hh:MM', lTimediff )
                    dz.log( 'atLocalTime = ' .. atLocalTime, dz.LOG_DEBUG )

                    -- Record 3 = Lat = 53.357
                    delString = "Lat = "
                    local qLat = tostring(description_table[3]):gsub( delString, "" )
                    dz.log( 'qLat = ' .. qLat, dz.LOG_DEBUG )
			    
                    -- Record 4 = Lon = 6.783
                    delString = "Lon = "
                    local qLon = tostring(description_table[4]):gsub( delString, "" )
                    dz.log( 'qLon = ' .. qLon, dz.LOG_DEBUG )
			    
                    -- Record 5 = Diepte = 3.0 km
                    delString = "Diepte = "
                    local qDepth = tostring(description_table[5]):gsub( delString, "" )
                    dz.log( 'qDepth = ' .. qDepth, dz.LOG_DEBUG )
			    
                    -- Record 6 = M = 0.3
                    delString = "M = "
                    local qMag = tostring( description_table[6]):gsub( delString, "" )
                    dz.log( 'qMag = ' .. qMag, dz.LOG_DEBUG )
			    
                    -- Record 7 = Plaats = 't Zandt
                    delString = "Plaats = "
                    local qPlace = tostring(description_table[7]):gsub( delString, "" )
                    dz.log( 'qPlace = ' .. qPlace, dz.LOG_DEBUG )

                    -- Record 8 = Author = KNMI
                    local qAuthor = description_table[8]
                
                    -- Record 9 = Type = Geinduceerd
                    local qType = description_table[9]
                
                    -- Record 10 = Analyse = Reviewed

                    -- Calculate distance from home location.
                    local distance = calculateDistance( yourLatitude, yourLongitude, qLat, qLon )
                    -- Round the distance to the nearest kilometer
                    local roundedDistance = _u.round( distance, 0 )
				
                    --Set Alertlevel color based on distance.
                    if roundedDistance < dClosest then
                        alertLevel = dz.ALERTLEVEL_RED
                    elseif roundedDistance >= dClosest and roundedDistance < dCloser then
                        alertLevel = dz.ALERTLEVEL_ORANGE
                    elseif roundedDistance >= dCloser and roundedDistance < dClose then
                        alertLevel = dz.ALERTLEVEL_YELLOW
                    else
                        alertLevel = dz.ALERTLEVEL_GREY
                    end
                
                    --Set and format the new alertText
                    local alertText = tostring( atLocalTime .. ' uur in ' .. qPlace .. '\n' .. 'Magnitude: ' .. qMag .. '. Diepte: ' .. qDepth .. '. Afstand: ' .. roundedDistance ..' km.\n' .. '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '" target="_blank">Toon locatie</a>' .. ' - ' .. '<a href="'  .. qUrl ..  '" target="_blank">Toon bron</a>' )

                    -- Only update and send mail when info has changed. and 
                    if alertText ~= lastalertText then
                        -- We have new information, so update the device.
                        dz.devices(alertIdx).updateAlertSensor(alertLevel, alertText)

                        -- Only send email when it comes closer then dCloser
                        if roundedDistance <= dCloser then
                            --Set and format the new mail message
                            local message = tostring('Plaats: ' .. qPlace .. '<br>' ..
                            'Magnitude: ' .. qMag .. '<br>' ..
                            'Diepte: ' .. qDepth .. '.<br>' ..
                            'Lokale Tijd: ' .. atLocalTime .. ' uur.<br>' ..
                            'UTC Tijd: ' .. atUTCtime .. ' uur.<br>' ..
                            'Afstand: ' .. roundedDistance .. 'km.<br>'..
                            'Coördinaten: ' .. qLat .. ','.. qLon .. '<br>' ..
                            qAuthor .. '<br>' ..
                            qType .. '<br>' ..
                            '<a href="https://maps.google.com/?q=' .. qLat .. ',' .. qLon .. '">Toon locatie</a>' .. '<br>' ..
                            '<a href="' .. qUrl .. '">Toon bron</a>' .. '<br>')
                            -- Send the mail
                            dz.email( 'Aardbeving ' .. qPlace, message, mailto )
                        end
                    end
                else
                    dz.log( 'No result_table found', dz.LOG_ERROR )
                end
	        else
    			dz.log( 'Item or XML - NOT OK', dz.LOG_ERROR )
		    end
		else
			dz.log( 'Failed to fetch info', dz.LOG_ERROR )
		end
	end
}
-- That's All --------------------------------------------------
Note. I still have to look into the previously mentioned error.
EDIT: Found out that I had included a space before the time. Corrected that in the script:

Code: Select all

string.sub( description_table[2], 2, 6 )
Last edited by janpep on Friday 10 May 2024 19:23, edited 1 time in total.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
Kedi
Posts: 569
Joined: Monday 20 March 2023 14:41
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Somewhere in NL
Contact:

Re: Earthquake info from KNMI

Post by Kedi »

Just a small tip. I use dz instead of domoticz. Saves a lot of typing and is equal readable.
Logic will get you from A to B. Imagination will take you everywhere.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

Thanks for the tip. As you can see I introduced that in the latest update for every occurence after:

Code: Select all

execute = function(dz, triggeredItem)
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

I noticed very weird behaviour. Never seen it before.
Again I got an error when retreiving time from the description_table.

Code: Select all

2024-05-10 19:55:00.828 Error: dzVents: Error: (3.1.8) KNMI-: .../scripts/dzVents/generated_scripts/t-Earthquake-KNMI.lua:106: bad argument #1 to 'sub' (string expected, got nil)
At the same time I found a log entry that looks like it is interfering with another script that is also running every 5 minutes and retrieving alerts (police, fire brigade, ambulance) for my city.
Weird, because the marker of that scipt is set to 'Alarmering-', while it shows here as 'KNMI-'.
It seems to mix with the other script somehow.

Code: Select all

2024-05-10 19:55:00.828 Status: dzVents: Debug: KNMI-: http://alarmeringen.nl/zuid-holland/hollands-midden/alphen-aan-den-rijn/?utm_source=rss&utm_medium=alphen-aan-den-rijn&utm_campaign=sharing
2024-05-10 19:55:00.828 Status: dzVents: Debug: KNMI-: Ambulance voorwaarde scheppend naar Vorkweg in Alphen Aan Den Rijn
I'm still investigating what both scripts may share, but I had the idea they run strictly separate.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
BazemanKM
Posts: 35
Joined: Wednesday 22 July 2015 21:39
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Earthquake info from KNMI

Post by BazemanKM »

When running the Eartquake script, my KNMI weather alarm gets no data:

Code: Select all

local url = 'https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml' -- rss url
local scriptVar = 'WeerAlert' -- callback name

local WeerAlertDevice  = 'Weeralarm' -- name of alert device in domotcicz

local codes = {"Groen","Geel","Oranje","Rood"} -- available codes
local PV = 3 -- Province code
--[[ codes for the different provinces
2=Waddeneilanden        3=Groningen         4=Friesland         5=Drente
6=Noord-Holland         7=Flevoland         8=Overijsel         9=Gelderland
10=Utrecht              11=Zuid-Holland     12=Zeeland          13=Noord-Brabant
14=Limburg              15=Waddenzee        16=ijselmeer-gebied
--]]

return 
{
    on = 
    {
        timer = 
        {
            'every 10 minutes',
        },
        
        httpResponses =
        {
            scriptVar,
        },
    },


         -- ***** No changes required below this line *****

    logging = 
    {
        level = domoticz.LOG_INFO,
        marker = scriptVar,
    },
    
    execute = function(dz, item)
    
    local Weeralarm = dz.devices(WeerAlertDevice) --reference to the weather alarm device
        
        --Retrieve desired data from the returned xml file
        local function getData(data)
            rt = dz.utils.fromXML(data).rss.channel.item[PV]
            RelevanteData={["code"]=0,["text"]="Geen data"}
            --dz.log(rt["description"],dz.LOG_DEBUG) 
            --rt["description"]="Code Geel.<br>Enkele onweersbuien met kans op hagel.<p><a href='/kennis-en-datacentrum/waarschuwingen/onweersbuien'>Wat kan ik verwachten en wat kan ik doen bij onweersbuien?</a> (van 01/08/2023 10:00 tot 01/08/2023 16:00 uur)<br><br>"
            for key,value in ipairs(codes) do
                if string.match(rt["description"],value) then
                    RelevanteData["code"]=key
                    RelevanteData["text"]=rt["description"]:gsub("<a.-a>","")
                end
            end
            return RelevanteData
        end
        
        --update the specified device in domoticz
        local function UpdateDevice(data)
            local lastStatus = "0"
            lastStatus= tostring(Weeralarm.color)
            Weeralarm.updateAlertSensor(data["code"],data["text"])
            --un comment the next 3 lines to send a notification when the status has changed(this one is for telegram)
            if tostring(data["code"]) ~= lastStatus then 
                dz.notify('Domoticz', 'Weeralarm: \n'.. data["text"]:gsub("<.->",""), dz.PRIORITY_NORMAL,dz.SOUND_DEFAULT, "" , dz.NSS_TELEGRAM)
            end  
        end
        
        if item.isHTTPResponse then
            if item.ok then
                UpdateDevice(getData(item.data))
            else
                dz.log('There was a problem handling the request', dz.LOG_ERROR)
                dz.log(item, dz.LOG_ERROR)
            end
            return
        end

        dz.openURL(
        {
            url = url, 
            method = 'GET',
            callback = scriptVar,
        })
    end
}
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

BazemanKM wrote: Saturday 11 May 2024 0:03 When running the Eartquake script, my KNMI weather alarm gets no data:
Thanks for sharing your findings. At this time I have no idea what could be causing these strange phenomena. Also in my case it does not happen all the time. I will see if I can figure it out. But if no global variables of the same name are used, I do not yet see how scripts can influence each other's operation.
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
janpep
Posts: 268
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Earthquake info from KNMI

Post by janpep »

BazemanKM wrote: Saturday 11 May 2024 0:03 When running the Eartquake script, my KNMI weather alarm gets no data:

Code: Select all

local url = 'https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml' -- rss url
<cut>
I take the weatheralarm from weerlive.nl. This because I noticed that the URL you use (which I already had seen in other examples) only gives data from 31 Oct 2023 !!
Maybe I'm wrong, but I don't think you got many alarms anyway :-)
Dz on Ubuntu VM on DS718+ behind FRITZ!Box.
EvoHome; MELCloud; P1 meter; Z-Stick GEN5; Z-Wave-js-ui; Sonoff USB-Dongle Plus-E; Zigbee2Mqtt; MQTT; Greenwave powernodes 1+6; Fibaro switch, plugs, smoke; FRITZ!DECT 200. Scripts listed in profile interests.
BazemanKM
Posts: 35
Joined: Wednesday 22 July 2015 21:39
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Earthquake info from KNMI

Post by BazemanKM »

janpep wrote: Saturday 11 May 2024 10:27 I take the weatheralarm from weerlive.nl. This because I noticed that the URL you use (which I already had seen in other examples) only gives data from 31 Oct 2023 !!
Maybe I'm wrong, but I don't think you got many alarms anyway :-)
Haha, well thanx for pointing me at the old data.

Is your weerlive.nl script on this forum, maybe i should use that to.

By the way: I like to have te warnings in Telegram in stead of email. Some scripts i can change, the earthquake will do. The lokale stookwijzer is difficult.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest