Custom page Alarmeringen.nl by script

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

Moderator: leecollings

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

Custom page Alarmeringen.nl by script

Post by janpep »

Now that I am rewriting my scripts in a new format, I would like to share some of these projects here. Maybe it will help someone.

Emergency services often pass by with sirens. Sometimes I wonder what is or was going on. One time it turned out to be a chimney fire just a few houses away.

All alarm reports in the Netherlands are published and can be accessed per region or city via RSS feed.
You can find your place at: https://alarmeringen.nl
Here you see the spelling of the name of your own city, to then use it in the URL.
Example of the data obtained for Alphen aan den Rijn: https://alarmeringen.nl/feeds/city/alph ... n-rijn.rss

I parsed this XML data in a script to post the latest notifications. I did not find it useful to put this information in a text device.
The space is too limited and it doesn't look nice. That's why I decided to place it in a custom HTML page, which is entirely created via the script.
This page can be called up via the Custom menu. See the picture below.
  • The script places the latest notifications in a dynamically created table with time, icon and description of the notification.
  • I have placed three pictures with these icons of ambulance, fire brigade and police in the directory: /home/user/domoticz/www/templates/images.
  • The script refers to that. The images are used as a link to further information on the website.
  • The html file is placed in: /home/<username>/domoticz/www/templates by the script.
  • Your own street name can be entered in the script and a notification email will be sent when there is an emergency in your own street.
  • NB. A variable 'lastAlarmNotification' is placed in global_data, to ensure that a notification that has already been sent for your own street will not be given multiple times. Create that as:

    Code: Select all

    	-- Global persistent data
    	data = {
    	-- Used in t-Alarmeringen for Alarmeringen.nl.
    		lastAlarmNotification = {},
    	},
EDIT:
  • NB. Forgotten and added later: The script also refers to a global function in the global_data.

    Code: Select all

        -- 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,
            }


The result:
Alarmeringen-1-JanPep.png
Alarmeringen-1-JanPep.png (117.17 KiB) Viewed 2230 times
The first line in the description shows codes and overlaps with the second line. I kept it anyway, because it sometimes provides additional information.

The icons that are also used on the website:
icons_Alarmeringen.nl.zip
(4.32 KiB) Downloaded 62 times
Correct and double check Your settings, cityname, the full path to your domoticz/www/template directory and URL in the script.

t-Alarmeringen:

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 = 'yourStreetName'   -- Get a notification when streetname is found.
local al_emailTo = "[email protected]" -- Set E-mail adres to sent notification to.
local cityName = 'Name Of Your City'  -- 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/<URLnamefoundforyourcity>.rss'

return {
	on = {
		timer = {
			'every 5 minutes',
		},
		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 .. '!', '', ak_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 --------------------------------------------------
Last edited by janpep on Friday 24 May 2024 22:17, 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.
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

Script is not working:

attempt to index a nil value (local '_h')
debug:

Code: Select all

2024-05-24 21:37:00.260 Status: dzVents: Info: Alarmering-: ------ Start internal script: alarmeringen:, trigger: "every 1 minutes"
2024-05-24 21:37:00.260 Status: dzVents: Debug: Alarmering-: OpenURL: url = https://alarmeringen.nl/feeds/city/xx.rss
2024-05-24 21:37:00.260 Status: dzVents: Debug: Alarmering-: OpenURL: method = GET
2024-05-24 21:37:00.260 Status: dzVents: Debug: Alarmering-: OpenURL: post data = nil
2024-05-24 21:37:00.260 Status: dzVents: Debug: Alarmering-: OpenURL: headers = nil
2024-05-24 21:37:00.260 Status: dzVents: Debug: Alarmering-: OpenURL: callback = alarmering
2024-05-24 21:37:00.260 Status: dzVents: Info: Alarmering-: ------ Finished alarmeringen
2024-05-24 21:37:00.472 Status: dzVents: Info: Alarmering-: ------ Start internal script: alarmeringen: HTTPResponse: "alarmering"
2024-05-24 21:37:00.509 Status: dzVents: Info: Alarmering-: ------ Finished alarmeringen
2024-05-24 21:37:00.509 Error: dzVents: Error: (3.1.8) Alarmering-: An error occurred when calling event handler alarmeringen
2024-05-24 21:37:00.509 Error: dzVents: Error: (3.1.8) Alarmering-: ...oticz/scripts/dzVents/generated_scripts/alarmeringen.lua:65: attempt to index a nil value (local '_h')
(City changed to xx due reasons ;))
janpep
Posts: 270
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by janpep »

Excuse me.
the _h refers to:

Code: Select all

local _h = dz.helpers
it is used for global functions and used in the following line:

Code: Select all

local utcTimeDiffSeconds = _h.getUTCtimediffseconds( dz.time.dDate )
In your global_data script you can add this function that I forgot to mention (or create it as a local function and refer to that).

Code: Select all

    -- 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,
        }
I will edit and add it to the first post also.
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.
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

Still not working.

Code: Select all

2024-05-26 18:30:30.006 Error: dzVents: Error: (3.1.8) error loading module 'Alarmeringen' from file '/home/x/domoticz/scripts/dzVents/generated_scripts/Alarmeringen.lua':
2024-05-26 18:30:30.006 ...oticz/scripts/dzVents/generated_scripts/Alarmeringen.lua:5: unexpected symbol near '='
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

Please, write the total script from a till z.
I assume its an dzvents script?
You wrote about 2 extra inside scripts, do we need to add these into the mainscript, or as standalone?
So, please write the tutorial from start till a working custom page.. ;-)

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

Re: Custom page Alarmeringen.nl by script

Post by janpep »

As already mentioned, two things are centrally placed in global_data script.
I use it to store 'persistant' data that can be retrieved the next round, or from other scripts.
I also use it to have een central place for more general functions that are used in more than one script.
That is what it is for. See also the DZvents wiki regarding persistent data!

If you don't have it, you can create it,
NB. You can only have one script with this name!
You can add the code with the "Global persistent data" and the 'Global helper functions' that I gave in that script.

So the tutorial:
1. Place and save the t-Alarmeringen script, which is indeed a dzvents script.
2. Modify your personal things like path, streetname, city (check spelling), email etc.
3. Add the two parts I gave to your existing global_data script.
If you do not yet have that, you can use this and save it as 'global_data' !
( NB. I took out my other stuff and kept only what is needed in combination with the t-Alarmeringen script. )

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.

return {

	-- Global persistent data
	data = {
        -- Used in t-Alarmeringen for Alarmeringen.nl.
		lastAlarmNotification = {},
    },

    -- 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,
	}
}
-- That's All --------------------------------------------------
I thinkg that should work.
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.
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

Is it possible that there is already an global data?

Code: Select all

return {
	data = {
		myGlobalVar = { initial = 12 }
	},

	helpers = {
		myHelperFunction = function(domoticz)
		end
	}
}
if you i add your code into it, it will give some errors again.. so i removed it..
janpep
Posts: 270
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by janpep »

BarryT wrote: Sunday 26 May 2024 22:31 Is it possible that there is already an global data?
I do not know if you already have it. When you are working with scripts, you should know.
That is why I said that you can add it to your existing (when you have it already!), or create it with what I posted.
if you i add your code into it, it will give some errors again.. so i removed it..
May be it is easier when you show what error you see?
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.
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

Ah, it is working now. Thanks!
Is it also possible to get 2 (or more) places to monitor, or do we need another extra custom page?
janpep
Posts: 270
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by janpep »

BarryT wrote: Monday 27 May 2024 13:01 Ah, it is working now. Thanks!
Is it also possible to get 2 (or more) places to monitor, or do we need another extra custom page?
You are welcome.

For more places to monitor, may be you can use the option to get a region and filter out what you do not want.
OR perhaps more direct and easy:
Modifiy as:
A. Get the results for city 1 (as it is now) with the openurl.
B. In the callback1 you put the html content from the response to a file (as it is now), but without closing the body.
C. End this part by adding the second call for city 2 with the second openurl with a second callback2 string.
D in the second callback put the html from the response content to a second table in the same file.
E. Then end that by closing the html body.
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: 270
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by janpep »

If that is to difficult, you can also create a second page as you suggested.
Then save the script another time as t-Alarmeringen-2 or something like that.
Change the URL and cityname that is needed and also change the name of the html file for the second place.
That should also work.
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.
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

janpep wrote: Monday 27 May 2024 13:17
BarryT wrote: Monday 27 May 2024 13:01 Ah, it is working now. Thanks!
Is it also possible to get 2 (or more) places to monitor, or do we need another extra custom page?
You are welcome.

For more places to monitor, may be you can use the option to get a region and filter out what you do not want.
OR perhaps more direct and easy:
Modifiy as:
A. Get the results for city 1 (as it is now) with the openurl.
B. In the callback1 you put the html content from the response to a file (as it is now), but without closing the body.
C. End this part by adding the second call for city 2 with the second openurl with a second callback2 string.
D in the second callback put the html from the response content to a second table in the same file.
E. Then end that by closing the html body.
Can you explain that script?
Unfortunately a second script with another city and html page does not work, they both takes the same city. :D

Ps, i added an auto-refresh on the html page so you dont need to open again the page every 5 minutes.

Code: Select all

' <meta http-equiv="refresh" content="300"> ' ..
Btw it would be even that perfect if we can use the

Code: Select all

https://alarmeringen.nl/streek/achterhoek/
and only select wich cities you want to see / update in this script..
janpep
Posts: 270
Joined: Thursday 14 March 2024 10:11
Target OS: Linux
Domoticz version: 2025.1
Location: Netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by janpep »

First for your refresh.
I found out that this does not work.
Finally I found the suggestion to have to following line in the start script in /etc/init.d/domoticz.sh

Code: Select all

DAEMON_ARGS="$DAEMON_ARGS -nocache"
and I am very happy with that.

Second for the setup.
You asked for explain and you didn't ask for a quote.
So you have to fine tune yourself. Here a 'quick and dirty untested' setup to get the idea with city1 and city2 and two callbacks.

Code: Select all

--Example with two callbacks.
--- 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 = 'streetname'   -- Get a notification when streetname is found.
local al_emailTo = '[email protected]' -- Set E-mail adres to sent notification to.
local cityName1 = 'Your City 1'  -- Used in header, and used to strip from text.
                                        -- Use the same spelling that is found in description.
local cityName2= 'Your City 2  -- Used in header, and used to strip from text.
--Set the Fullpath to the html file. Example '/home/username/domoticz/www/templates/Alarmeringen.html'
local htmlFile = '/path/to//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 alarmeringURL1 = 'https://alarmeringen.nl/feeds/city/<city1>.rss'
local alarmeringURL2 = 'https://alarmeringen.nl/feeds/city/<city2>.rss'
        
----------------------------------------------------------------------------------
return {
	on = {
		timer = { 
			--'every 10 minutes',    -- Only used for testing.
        },
		httpResponses = {
            'city1',       -- matches callback string for city1 below
            'city2'       -- matches callback string for city 2below
        },
	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 = alarmeringURL1,
				method = 'GET',
				callback = 'city1', -- see httpResponses above.
			})
		end

        -- Process the obtained data.
        if ( triggeredItem.isHTTPResponse ) then
            -- For City 1 ------------------------------------------------------
            if triggeredItem.trigger == 'city1' then


		--Here goes everything for city 1 as in the original script.

		-- Replace the following ENDING of the table
		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'
		--with something that introduces city 2 and does not end the table. e.g.
		tableContent = tableContent .. '   <tr>\n' ..
					'    <td colspan="3" align="center" style="padding: 3px 10px 3px 10px; color: cyan;">City 2</td>\n' ..
					'   </tr>\n' 

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

		-- From Step 6 skip writing the  fileFooter ------------------

		--Step 7. Close file ------------------------
		file:close()
		--Keep the notification part if you like that.

		--Ending this part with the second call for city2
                -- Retrieve the data for city2
			dz.openURL({
				url = alarmeringURL2,
				method = 'GET',
				callback = 'city2', -- see httpResponses above.
			})
            end -- city 1

            -- For City 2 ------------------------------------------------------
            if triggeredItem.trigger == 'city2' then

		--Here goes everything for city 2 as in the original script. BUT

		-- Skip to remove the existing file but re-open it for appending.
                 local file = io.open( htmlFile, "a" )		

		--Skip Step 2 to  Write fileHeader ----------------

		--Keep Step 3. Get and write tableContent in loop  ----------------
                --Keep Step 4. Append table footer with update time and close the table  -----
		--Keep Step 5. Write tableContent ----------------
		--Keep Step 6. Write fileFooter ------------------
		--Keep Step 7. Close file ------------------------
		--Keep the notification part if you like that.
            end -- city 2

	-- Keep the remaining part and check if all the if - end combinations are still correct.
	
	end
}
-- That's All --------------------------------------------------
I hope this helps you to find the way through it, but I think here it ends for me.
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.
BarryT
Posts: 369
Joined: Tuesday 31 March 2015 22:06
Target OS: Linux
Domoticz version: 2024.3
Location: east netherlands
Contact:

Re: Custom page Alarmeringen.nl by script

Post by BarryT »

janpep wrote: Monday 27 May 2024 21:25 First for your refresh.
I found out that this does not work.
Finally I found the suggestion to have to following line in the start script in /etc/init.d/domoticz.sh

Code: Select all

DAEMON_ARGS="$DAEMON_ARGS -nocache"
and I am very happy with that.
I already using the nocache since years because it works better for me then with the cache on..
Second for the setup.
You asked for explain and you didn't ask for a quote.
So you have to fine tune yourself. Here a 'quick and dirty untested' setup to get the idea with city1 and city2 and two callbacks.

Code: Select all

--Example with two callbacks.
--- 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 = 'streetname'   -- Get a notification when streetname is found.
local al_emailTo = '[email protected]' -- Set E-mail adres to sent notification to.
local cityName1 = 'Your City 1'  -- Used in header, and used to strip from text.
                                        -- Use the same spelling that is found in description.
local cityName2= 'Your City 2  -- Used in header, and used to strip from text.
--Set the Fullpath to the html file. Example '/home/username/domoticz/www/templates/Alarmeringen.html'
local htmlFile = '/path/to//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 alarmeringURL1 = 'https://alarmeringen.nl/feeds/city/<city1>.rss'
local alarmeringURL2 = 'https://alarmeringen.nl/feeds/city/<city2>.rss'
        
----------------------------------------------------------------------------------
return {
	on = {
		timer = { 
			--'every 10 minutes',    -- Only used for testing.
        },
		httpResponses = {
            'city1',       -- matches callback string for city1 below
            'city2'       -- matches callback string for city 2below
        },
	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 = alarmeringURL1,
				method = 'GET',
				callback = 'city1', -- see httpResponses above.
			})
		end

        -- Process the obtained data.
        if ( triggeredItem.isHTTPResponse ) then
            -- For City 1 ------------------------------------------------------
            if triggeredItem.trigger == 'city1' then


		--Here goes everything for city 1 as in the original script.

		-- Replace the following ENDING of the table
		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'
		--with something that introduces city 2 and does not end the table. e.g.
		tableContent = tableContent .. '   <tr>\n' ..
					'    <td colspan="3" align="center" style="padding: 3px 10px 3px 10px; color: cyan;">City 2</td>\n' ..
					'   </tr>\n' 

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

		-- From Step 6 skip writing the  fileFooter ------------------

		--Step 7. Close file ------------------------
		file:close()
		--Keep the notification part if you like that.

		--Ending this part with the second call for city2
                -- Retrieve the data for city2
			dz.openURL({
				url = alarmeringURL2,
				method = 'GET',
				callback = 'city2', -- see httpResponses above.
			})
            end -- city 1

            -- For City 2 ------------------------------------------------------
            if triggeredItem.trigger == 'city2' then

		--Here goes everything for city 2 as in the original script. BUT

		-- Skip to remove the existing file but re-open it for appending.
                 local file = io.open( htmlFile, "a" )		

		--Skip Step 2 to  Write fileHeader ----------------

		--Keep Step 3. Get and write tableContent in loop  ----------------
                --Keep Step 4. Append table footer with update time and close the table  -----
		--Keep Step 5. Write tableContent ----------------
		--Keep Step 6. Write fileFooter ------------------
		--Keep Step 7. Close file ------------------------
		--Keep the notification part if you like that.
            end -- city 2

	-- Keep the remaining part and check if all the if - end combinations are still correct.
	
	end
}
-- That's All --------------------------------------------------
I hope this helps you to find the way through it, but I think here it ends for me.
Thanks! Will check it out!
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest