DZvents bug in handling httpResponses?

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

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

DZvents bug in handling httpResponses?

Post by janpep »

I run two scripts running every 5 minutes.
Both script have in common that the call an url to get an xml httpResponse.
Both get it (with different strings) in a LOCAL 'result_table' from where the content is processed.
Both scripts have a diferent callback string. Respectively 'knmi-rss' and 'alarmering'
Both scripts have a different Logging Marker set. Respectively 'KNMI-' and 'Alarmering-'

A few times per day I get an error message that a string is nil.
The log below shows the log of my 't-Earthquake-KNMI' script with Marker 'KNMI-'

Code: Select all

2024-05-21 13:05:00.517  Status: dzVents: Info: KNMI-: ------ Start internal script: t-Earthquake-KNMI:, trigger: "every 5 minutes"
2024-05-21 13:05:00.529  Status: dzVents: Debug: KNMI-: Processing device-adapter for KNMI Aardbevingen: Alert sensor  adapter
2024-05-21 13:05:00.529  Status: dzVents: Debug: KNMI-: OpenURL: url = https://cdn.knmi.nl/knmi/map/page/seismologie/GQuake_KNMI_RSS.xml
2024-05-21 13:05:00.529  Status: dzVents: Debug: KNMI-: OpenURL: method = GET
2024-05-21 13:05:00.529  Status: dzVents: Debug: KNMI-: OpenURL: post data = nil
2024-05-21 13:05:00.529  Status: dzVents: Debug: KNMI-: OpenURL: headers = nil
2024-05-21 13:05:00.530  Status: dzVents: Debug: KNMI-: OpenURL: callback = knmi-rss
2024-05-21 13:05:00.530  Status: dzVents: Info: KNMI-: ------ Finished t-Earthquake-KNMI
2024-05-21 13:05:01.308  Status: dzVents: Info: KNMI-: ------ Start internal script: t-Earthquake-KNMI: HTTPResponse: "knmi-rss"
2024-05-21 13:05:01.331  Status: dzVents: Debug: KNMI-: Processing device-adapter for KNMI Aardbevingen: Alert sensor  adapter
2024-05-21 13:05:01.331  Status: dzVents: Debug: KNMI-: result_table: type = table
2024-05-21 13:05:01.331  Status: dzVents: Debug: KNMI-: URL details = 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-21 13:05:01.331  Status: dzVents: Debug: KNMI-: Full description string = Ambulance voorwaarde scheppend naar Vorkweg in Alphen Aan Den Rijn
2024-05-21 13:05:01.331  Error: dzVents: Error: (3.1.8) KNMI-: An error occurred when calling event handler t-Earthquake-KNMI
2024-05-21 13:05:01.331  Error: dzVents: Error: (3.1.8) KNMI-: .../scripts/dzVents/generated_scripts/t-Earthquake-KNMI.lua:116: attempt to concatenate a nil value (field '?')
2024-05-21 13:05:01.331  Status: dzVents: Info: KNMI-: ------ Finished t-Earthquake-KNMI
  • Problem 1: In the line with the "URL details" you see the URL that comes from de ressult of the second script t-Alarmeringen! But marked with the marker of the first script!
  • Problem 2. The line with the Full description string also shows content that comes from alermeringen.nl and not from Earthquakes.
  • Problem 3: Later you see: t-Earthquake-KNMI.lua:116: attempt to concatenate a nil value. The first script cannot find a field. Of course. It searches for a field expexted in the httpresponse of script 1, but cannot find it in the httpresponse that clearly comes from script 2.
For me it is clear that the first script tries to process the httpRespons content of the second script.
Although scripts run at the same time, they have different name, different logging marker and most important different callback strings.
Question: How is it possible that this is mixed up?

Workaround:
For the moment I have scheduled the scirpts as:

Code: Select all

'at *:01', 'at *:06, 'at *:11', 'at *:16', 'at *:21', 'at *:26', 'at *:31', 'at *:46', 'at *:51', 'at *:56',
and

Code: Select all

'at *:02', 'at *:07', 'at *:12', 'at *:17', 'at *:22', 'at *:27', 'at *:32', 'at *:47', 'at *:52', 'at *:57',
That seems to work until now.

I hope someone can reproduce this or identify the cause.
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
boum
Posts: 135
Joined: Friday 18 January 2019 11:31
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.10717
Location: France
Contact:

Re: DZvents bug in handling httpResponses?

Post by boum »

you should share both scripts. not much can be done without that (you explained the issue well, but i don't think anybody will look at the issue with just that)
janpep
Posts: 270
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: DZvents bug in handling httpResponses?

Post by janpep »

I was hoping that someone might have a general idea of what could be causing this and didn't want to just dump the scripts.
But if anyone is willing to look into what the possible cause could be, I would really appreciate it.

Note: In the meantime I have adjusted the timetables so that they do not both run at the same time
The first script is the t-Earthquake-KNMI script. (meanwhile changed the schedule

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.
-- 13-05-2024 Added font color for hyperlinks.
-- 21-05-2024 Sometimes error on local atUTCtime = description_table[1] .. ' ' .. string.sub( description_table[2], 2, 6 )
--            bad argument #1 to 'sub' (string expected, got nil); However - Manually never seen.


--- Your settings ----------------------------------------------------------------
-- First set the used device index numbers and variables you might want to change.
local alertIdx = 1000           -- 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 2 minutes',  -- Only for testing.
			'at *:02',
			'at *:07',
			'at *:12',
			'at *:17',
			'at *:22',
			'at *:27',
			'at *:32',
			'at *:47',
			'at *:52',
			'at *:57',
        },
		httpResponses = {
            'knmi-rss'   -- matches callback string below
        }
	},
    logging = {
	    -- Level can be domoticz.LOG_INFO, domoicz.LOG_MODULE_EXEC_INFO, 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

        -- Use color variable for hyperlink font color
        htmlColor = 'Blue'

        -- 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.openURL({
			    url = knmiURL,
				method = 'GET',
				callback = 'knmi-rss'
			})	
		end
        
		if (triggeredItem.isHTTPResponse) then
            -- Process the obtained data.
			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
                    dz.log( 'result_table: type = ' .. type(result_table), dz.LOG_DEBUG )
                    -- Get only the info from the first item.

                    -- Get link to page with details.
                    dz.log( 'URL details = ' .. 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( 'Full description string = ' .. 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)
                    dz.log( 'String 1 = "' .. description_table[1] .. '" en String 2 = "' .. description_table[2] .. '"', dz.LOG_DEBUG )
                    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]
                    dz.log( 'qAuthor = ' .. qAuthor, dz.LOG_DEBUG )
                    
                    -- Record 9 = Type = Geinduceerd
                    local qType = description_table[9]
                    dz.log( 'qType = ' .. qType, dz.LOG_DEBUG )
                    
                    -- 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"><span style="color: ' ..  htmlColor .. '">Toon locatie</span></a>' .. ' - ' .. '<a href="'  .. qUrl ..  '" target="_blank"><span style="color: ' ..  htmlColor .. '">Toon bron</span></a>' )
                    dz.log( 'LastalertText = ' .. lastalertText, dz.LOG_DEBUG )
                    dz.log( 'NewalertText = ' .. alertText, dz.LOG_DEBUG )
                    
                    -- 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
		end
	end
}
-- That's All --------------------------------------------------
The second script is the t-Alarmeringen script.

Code: Select all

-- 03-12-2022 script by Jan Peppink, https://ict.peppink.nl
-- Creates a custom html page with x lines of the last alarm notifications for the city.
-- icon images are expected to be placed. See Your settings.

--- Your settings ----------------------------------------------------------------
-- First set the used device index numbers and variables you might want to change.
local maxLines = 10                         -- Max number of lines to show in the table.
local locationToSearch = 'MyStreet'   -- Get a notification when streetname is found.
local al_emailTo = '[email protected]' -- Set E-mail adres to sent notification to.
local cityName = 'Alphen Aan Den Rijn'  -- Used in header, and used to strip from text.
                                        -- Use the same spelling that is found in description.
--Set the Fullpath to the html file. Example '/home/username/domoticz/www/templates/Alarmeringen.html'
local htmlFile = '/home/username/domoticz/www/templates/Alarmeringen.html' 
--Set imageDir, where the icon_ambulance.web, icon_brandweer.webp, icon_politie.webp images are expected
local imageDir = '/templates/images' -- starting from root
--Set the URL to get the  rss for your city. Find city name at: https://alarmeringen.nl/plaatsen.html
-- Example region = 'http://alarmeringen.nl/feeds/region/hollands-midden.rss'
-- Example city = 'https://alarmeringen.nl/feeds/city/alphen-aan-den-rijn.rss'
local alarmeringURL = 'https://alarmeringen.nl/feeds/city/alphen-aan-den-rijn.rss'

return {
	on = {
		timer = {
            --'every 2 minutes',  -- Only for testing.
			'at *:01',
            'at *:06',
            'at *:11',
            'at *:16',
            'at *:21',
            'at *:26',
            'at *:31',
            'at *:46',
            'at *:51',
            'at *:56',
		},
		httpResponses = {
			'alarmering' -- must match with the callback passed to the openURL command
		}
	},
	logging = {
	    -- Level can be domoticz.LOG_INFO, domoicz.LOG_MODULE_EXEC_INFO, domoticz.LOG_DEBUG, domoticz.LOG_ERROR or domoticz.LOG_FORCE
        level = domoticz.LOG_INFO,
        --level = domoticz.LOG_DEBUG,
		marker = 'Alarmering-',
	},
	execute = function( dz, triggeredItem )
        -- Set Local environment=================
        local _u = dz.utils
        local _h = dz.helpers
        local _d = dz.globalData
        
        local locationFound = false

        -- Local Functions go here =============

        -- Now start to do something ============
		if (triggeredItem.isTimer) then
			dz.openURL({
				url = alarmeringURL,
				method = 'GET',
				callback = 'alarmering', -- see httpResponses above.
			})
		end

		if (triggeredItem.isHTTPResponse) then
            -- Process the obtained data.
			if (triggeredItem.ok and triggeredItem.isXML) then
                -- Results are in:
                -- triggeredItem.xml.rss.channel.description          -Alarmeringen.nl: Alle alarmeringen voor: Hollands Midden
                -- triggeredItem.xml.rss.channel.item
                -- triggeredItem.xml.rss.channel.item.title           -a1 coornhertdreef leiddp : 16161
                -- triggeredItem.xml.rss.channel.item.description     -Ambulance met spoed naar Coornhertdreef in Leiderdorp
                -- triggeredItem.xml.rss.channel.item.pubDate         -Fri, 09 Dec 2022 08:20:16 +0000

				-- utcTimeDiffSeconds to calculate local time from resulting pupDate
			    local utcTimeDiffSeconds = _h.getUTCtimediffseconds( dz.time.dDate )
                dz.log( 'utcTimeDiffSeconds = ' .. utcTimeDiffSeconds, dz.LOG_DEBUG )

                local result_table = triggeredItem.xml.rss.channel.item
                if type( result_table ) == "table" then
                    dz.log( 'Existing result_table: type = ' .. type( result_table ), dz.LOG_DEBUG )

					-- Witing the custom HTML file ----------------
					--Step 1. Remove old file and Open file for appending
					 dz.log( 'html file = ' .. htmlFile, dz.LOG_DEBUG )

                    if _u.fileExists( htmlFile) then os.remove( htmlFile ) end
                    local file = io.open( htmlFile, "a" )

					--Step 2. Write fileHeader ----------------
					local fileHeader = '<!DOCTYPE html>\n' ..
					'<html>\n' ..
					' <head>\n' ..
					'  <title>Laatste ' .. maxLines .. ' Alarmeringen.nl meldingen</title>\n' ..
					' </head>\n' ..
					' <body bgcolor="black">\n' ..
					'  <h1 style="text-align:center; color: white;">Alarmeringen.nl voor ' .. cityName .. ' </h1>\n' ..
					'<p></p>' ..
					'  <table border="1" style="border-collapse:collapse; margin-left:auto; margin-right:auto; color: yellow;" bgcolor="black"\n' ..
					'   <tr>\n' ..
					'    <th align="left" style="padding: 3px 10px 3px 10px; color: cyan;">Tijd</th>\n' ..
					'    <th colspan="2" align="left" style="padding: 3px 10px 3px 10px; color: cyan;">Laatste ' .. maxLines .. ' meldingen</th>\n' ..
					'   </tr>\n'
					file:write( fileHeader )

					--Step 3. Get and write tableContent in loop  ----------------
                    local tc = #result_table
                    local counter = 0
                    local tableContent = ''
				    for i = 1, tc do
                        --Interesting fields - example:
                        --title:        a2 pieter floriszstraat alphrn directe inzet 16162
                        --link:         http://alarmeringen.nl/zuid-holland/hollands-midden/alphen-aan-den-rijn/?utm_source=rss&utm_medium=hollands-midden&utm_campaign=sharing
                        --description:  Ambulance met gepaste spoed naar Pieter Floriszstraat in Alphen Aan Den Rijn
                        --pubDate:      Fri, 09 Dec 2022 08:13:18 +0000
				        -- 
				        --result_table[i].description
				        --result_table[i].title
				        --result_table[i].pubDate

			            if result_table[i].description ~= nil then
                            -- Skip if Ambulance = voorwaarde scheppend to
                            if string.find( result_table[i].description, 'voorwaarde scheppend' ) == nil then
                                --This string is not found so continue
			                    counter = counter + 1    

                                if counter <= maxLines then
	    		                    dz.log( '---------------- ', dz.LOG_DEBUG )
			                        dz.log( 'Title:        ' .. result_table[i].title, dz.LOG_DEBUG )
			                        dz.log( 'Link:        ' .. result_table[i].link, dz.LOG_DEBUG )
			                        dz.log( 'Description:  ' .. result_table[i].description, dz.LOG_DEBUG )
			                        dz.log( 'pubDate:      ' .. result_table[i].pubDate, dz.LOG_DEBUG )
				                    
    			                    -- date received. Format = Thu, 08 Dec 2022 01:37:39 +0000
	    		                    local rowDate = dz.time.dateToDate( result_table[i].pubDate, 'ddd, dd mmm yyyy hh:MM:ss +0000', 'dd-mm-yyyy hh:MM', utcTimeDiffSeconds )
		    	                    local rowLink = result_table[i].link
			                        local rowTitle = result_table[i].title

			                        -- trim off the cityName from description (case insensitive)
			                        local rowDescription = string.gsub( result_table[i].description, ' in ' .. cityName, ".")

				                    -- set rowImage based on description
				                    local rowImage = imageDir .. '/icon_politie.webp' --Is default, because 'Politie' is often not used in description.
				                    if string.find( result_table[i].description, "Ambulance") then rowImage = imageDir .. '/icon_ambulance.webp' end
				                    if string.find( result_table[i].description, "Brandweer") then rowImage = imageDir .. '/icon_brandweer.webp' end
				                    if string.find( result_table[i].description, "Politie") then rowImage = imageDir .. '/icon_politie.webp' end

    			                    dz.log( counter .. ': ' .. rowDate .. ' - ' .. rowDescription, dz.LOG_DEBUG )
			                    
    			                    -- Send notification when locationToSearch in in description
    			                    if string.find( result_table[i].description, locationToSearch ) then locationFound = true end

    					            tableContent = tableContent .. '   <tr>\n' ..
    					            '    <td align="left" valign="middle" style="padding: 3px 10px 5px 10px">' .. rowDate .. '</td>\n' ..
    					            '    <td align="left" valign="middle" style="padding: 3px 10px 5px 10px"><a target="_blank" rel="noopener" href="' .. rowLink.. '"><img src="' .. rowImage..  '" style="width:34px; height:25px"></a></td> \n' ..
                                    '    <td align="left" valign="middle" style="padding: 3px 10px 5px 10px">'.. rowTitle .. '</br>' .. rowDescription .. '</td> \n' ..
    					            '   </tr> \n'
	    	                    end
                            end
                        end
                    end

                    --Step 4. Append table footer with update time and close the table  -----
					local currentTime = dz.time.rawDateTime
					local updateTime = dz.time.dateToDate( currentTime, 'yyyy-mm-dd hh:MM:ss', 'dd-mm-yyyy hh:MM', 0 )
					dz.log( 'updateTime = ' .. updateTime, dz.LOG_DEBUG )

					tableContent = tableContent .. '   <tr>\n' ..
					'    <td colspan="3" align="right" style="padding: 3px 10px 3px 10px; color: cyan;">Update: ' .. updateTime .. ' uur</td>\n' ..
					'   </tr>\n' ..
					'  </table>\n'

					--Step 5. Write tableContent ----------------
					file:write(tableContent)

					--Step 6. Write fileFooter ------------------
					local fileFooter =	' </body>\n' ..
					'</html>'
					file:write(fileFooter)

					--Step 7. Close file ------------------------
					file:close()

					---------------------------------------- 
					-- Only one notification per session when location is found
					--_d.lastAlarmNotification format = '2022-12-10'
--					dz.log( 'lastAlarmNotification = ' .. _d.lastAlarmNotification, dz.LOG_DEBUG )
					if locationFound == true then
                        if _d.lastAlarmNotification == nil or _d.lastAlarmNotification < dz.time.rawDate then
                            _d.lastAlarmNotification = dz.time.rawDate
                            dz.log( locationToSearch .. ' found = ' .. tostring( locationFound ) .. ' on ' .. _d.lastAlarmNotification, dz.LOG_DEBUG )
						    dz.email( 'Alarmering.nl voor ' .. locationToSearch .. '!', '', al_emailTo, 0 )
                        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
    	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.
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests