Traffic with waze in Domoticz

Moderator: leecollings

User avatar
jvdz
Posts: 2189
Joined: Tuesday 30 December 2014 19:25
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.107
Location: Netherlands
Contact:

Re: Traffic with waze in Domoticz

Post by jvdz »

salvation wrote:
Egregius wrote:Yes, I noticed that also...
I've also tried the LUA variant but it's not working. Get the same message as others. Seems the call to waze is not correct and returns an empty result. But I didn't know how to fix.
I have it working with this url in the posted lua code:

Code: Select all

	local waze=assert(io.popen('curl "https://www.waze.com/row-RoutingManager/routingRequest?from=x%3A'..departx..'+y%3A'..departy..'&to=x%3A'..arrivex..'+y%3A'..arrivey..'&returnJSON=true&returnGeometries=true&returnInstructions=true&timeout=60000&nPaths=1&clientVersion=4.0.0&options=AVOID_TRAILS%3At%2CALLOW_UTURNS"'))
Also changed the LUA script to retrieve the travel time in both directions, update 2 devices in Domoticz and run it with crontab every 5 minutes, in stead of running this by the domoticz event system to avoid introducing delays in there.

Jos
New Garbage collection scripts: https://github.com/jvanderzande/GarbageCalendar
Derik
Posts: 1601
Joined: Friday 18 October 2013 23:33
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Arnhem/Nijmegen Nederland
Contact:

Re: Traffic with waze in Domoticz

Post by Derik »

Please...
One says LUA..
Other says PHP...
What option, and what is the best script...? :D :D
Xu4: Beta Extreme antenna RFXcomE,WU Fi Ping ip P1 Gen5 PVOutput Harmony HUE SolarmanPv OTG Winddelen Alive ESP Buienradar MySensors WOL Winddelen counting RPi: Beta SMAspot RFlinkTest Domoticz ...Different backups
User avatar
Egregius
Posts: 2582
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: Traffic with waze in Domoticz

Post by Egregius »

Depends on your needs and skills ;)
I like PHP, I entirely control Domiticz from it.
Many others prefer lua, alltough there are lot's of difficulties and shortcomings.
Derik
Posts: 1601
Joined: Friday 18 October 2013 23:33
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Arnhem/Nijmegen Nederland
Contact:

Re: Traffic with waze in Domoticz

Post by Derik »

Egregius wrote:Depends on your needs and skills ;)
I like PHP, I entirely control Domiticz from it.
Many others prefer lua, alltough there are lot's of difficulties and shortcomings.

A simple working script..
That is monitoring waze...
Time = x between xy
Route = y to x or x to y
File = x
File = xxx switch domoticz IDX on

And that for multiple time's and multiple routes
Xu4: Beta Extreme antenna RFXcomE,WU Fi Ping ip P1 Gen5 PVOutput Harmony HUE SolarmanPv OTG Winddelen Alive ESP Buienradar MySensors WOL Winddelen counting RPi: Beta SMAspot RFlinkTest Domoticz ...Different backups
User avatar
jvdz
Posts: 2189
Joined: Tuesday 30 December 2014 19:25
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.107
Location: Netherlands
Contact:

Re: Traffic with waze in Domoticz

Post by jvdz »

Derik wrote: A simple working script..
That is monitoring waze...
Time = x between xy
Route = y to x or x to y
File = x
File = xxx switch domoticz IDX on

And that for multiple time's and multiple routes
You also want Mayo with that? :D

Here is my LUA version that handles 2 routes at this moment but easy to extent:

Code: Select all

-- file waze_get_travel_times.lua
-----------------------------------------------------------------------------------------------------------------
--
-- get the travel times via Waze for home-work and work-home and update 2 devices in Domoticz to track the times
-- copied the base code from domoticz forum member iero  http://www.domoticz.com/forum/viewtopic.php?f=23&t=7777
--
-----------------------------------------------------------------------------------------------------------------

function traveltime(departx,departy,arrivex,arrivey)
	--get route from WAZE--
	local waze=assert(io.popen('curl "https://www.waze.com/row-RoutingManager/routingRequest?from=x%3A'..departx..'+y%3A'..departy..'&to=x%3A'..arrivex..'+y%3A'..arrivey..'&returnJSON=true&returnGeometries=true&returnInstructions=true&timeout=60000&nPaths=1&clientVersion=4.0.0&options=AVOID_TRAILS%3At%2CALLOW_UTURNS"'))
	local trajet = waze:read('*all')
	waze:close()

	print("========================================================================================================")
	print(trajet)
	local jsonTrajet = json:decode(trajet)

	--Get major road from JSON
	routeName = jsonTrajet['response']['routeName']
	--Get route steps from JSON info
	route = jsonTrajet['response']['results']

	--Calculate the total time by adding the time of all sections
	routeTotalTimeSec = 0
	for response,results in pairs(route) do
	   routeTotalTimeSec = routeTotalTimeSec + results['crossTime']
	end

	--translate the number of seconds to minutes
	routeTotalTimeMin = routeTotalTimeSec/60-((routeTotalTimeSec%60)/60)

	return routeTotalTimeMin
end

--import JSON addin (already used with DTGBOT and stored in the standard library)
json = (loadfile "/usr/local/share/lua/5.2/JSON.lua")()
-- Update these variables ---------------
--idx of devices for capturing the travel minutes in both direction
idxhomework = '250'
idxworkhome = '251'
--coordinates Home
departy="xx.xxxxxxx"
departx="x.xxxxx"
--Coordinates Work
arrivey="xx.xxxxxx"
arrivex="x.xxxxx"
-- get travel time
homework=traveltime(departx,departy,arrivex,arrivey)
workhome=traveltime(arrivex,arrivey,departx,departy)
print("homework:",homework,"workhome:",workhome)
-- update Domoticz devices
url='http://192.168.x.xx:8080/json.htm?type=command&param=udevice&idx=' .. idxhomework .. '&nvalue=0&svalue=' .. homework
read = os.execute('curl -s "'..url..'"')
url='http://192.168.x.xx:8080/json.htm?type=command&param=udevice&idx=' .. idxworkhome .. '&nvalue=0&svalue=' .. workhome
read = os.execute('curl -s "'..url..'"')
.. and I run it with Crontab every 5 minutes:

Code: Select all

# get Home-Work travel times
*/5 * * * * sudo lua /home/pi/domoticz/scripts/waze_get_travel_times.lua > /var/tmp/waze.log
Jos
New Garbage collection scripts: https://github.com/jvanderzande/GarbageCalendar
Derik
Posts: 1601
Joined: Friday 18 October 2013 23:33
Target OS: Raspberry Pi / ODroid
Domoticz version: BETA
Location: Arnhem/Nijmegen Nederland
Contact:

Re: Traffic with waze in Domoticz

Post by Derik »

Jos and Iero thanks...!!!

I don not like Mayo..
Better a beautiful .... ;)

Only the script is a little bit the high maths for me....

I have to study for this..
So i give it a try..
When i got problems...

I be back
Xu4: Beta Extreme antenna RFXcomE,WU Fi Ping ip P1 Gen5 PVOutput Harmony HUE SolarmanPv OTG Winddelen Alive ESP Buienradar MySensors WOL Winddelen counting RPi: Beta SMAspot RFlinkTest Domoticz ...Different backups
Whatsek
Posts: 16
Joined: Saturday 31 May 2014 23:48
Target OS: Raspberry Pi / ODroid
Domoticz version: Latest B
Location: Hilversum, The Netherlands
Contact:

Re: Traffic with waze in Domoticz

Post by Whatsek »

You also want Mayo with that? :D

Here is my LUA version that handles 2 routes at this moment but easy to extent:
Thank you for the Mayo, your scripts works fine! Tx
salvation
Posts: 38
Joined: Saturday 06 September 2014 15:34
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: Traffic with waze in Domoticz

Post by salvation »

I want to send a notification when on a specific time the value of the pressure sensor > specific value.

For example:

Code: Select all

	--Check current traveltime
	if (uservariables['home'] == 'true' timeCurrent == '0705') then
		if (otherdevices['travelTimeHomeWork'] > 30) then
			commandArray['SendNotification']='Druk op de weg#Let op, langer dan gemiddelde reistijd. Huidige reistijd is: #0'
		end
	end
But I don't get the value of the sensor in LUA, somebody who knows how I can achieve this? otherdevices['travelTimeHomeWork'] > 30 is not working and I couldn't find the correct syntax for the pressure device and LUA.
User avatar
jvdz
Posts: 2189
Joined: Tuesday 30 December 2014 19:25
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.107
Location: Netherlands
Contact:

Re: Traffic with waze in Domoticz

Post by jvdz »

Shouldn't that be something like:

Code: Select all

otherdevices_svalues['travelTimeHomeWork']
Not sure what exactly is returned for a pressure sensor, so you might want to temporarily add a print() to display the retuned value so you can see.

Jos
New Garbage collection scripts: https://github.com/jvanderzande/GarbageCalendar
salvation
Posts: 38
Joined: Saturday 06 September 2014 15:34
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: Traffic with waze in Domoticz

Post by salvation »

Thnx, that did the trick.

Final script for this one:

Code: Select all

--Set system variables
commandArray = {}
timeCurrent = os.date("%H%M")

	--Check if it's no holiday
	if ( uservariables['isHoliday'] == 'false' ) then

		--Check current traveltime travelTimeHomeWork
		if (uservariables['home'] == 'true' and timeCurrent == '0705') then
			if (tonumber(otherdevices_svalues['travelTimeHomeWork']) > 23) then
				commandArray['SendNotification']='Druk op de weg#Let op, langer dan gemiddelde reistijd. Huidige reistijd is: ' .. otherdevices_svalues['travelTimeHomeWork'] .. ' minuten #0'
			end
		end

		--Check current traveltime travelTimeWorkHome
		if (uservariables['home'] == 'true' and timeCurrent == '1640') then
			if (tonumber(otherdevices_svalues['travelTimeWorkHome']) > 23) then
				commandArray['SendNotification']='Druk op de weg#Let op, langer dan gemiddelde reistijd. Huidige reistijd is: ' .. otherdevices_svalues['travelTimeWorkHome'] .. ' minuten #0'
			end
		end
	end

return commandArray
User avatar
Egregius
Posts: 2582
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: Traffic with waze in Domoticz

Post by Egregius »

I got a question thrue PM for the code of my traffic php page, here it goes, so someone else can also use it:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Traffic information</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<meta name="HandheldFriendly" content="true" /><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="viewport" content="width=device-width,height=device-height,user-scalable=yes,minimal-ui" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="refresh" content="30;traffic.php" >
</head><body>
<?php //error_reporting(E_ALL);ini_set("display_errors", "on");
if (ob_get_level() == 0) ob_start();

function traffic($startlat, $startlon, $endlat, $endlon) {
	GLOBAL $traffic;
	$traffic=file_get_contents('https://www.waze.com/row-RoutingManager/routingRequest?from=x%3A'.$startlon.'+y%3A'.$startlat.'&to=x%3A'.$endlon.'+y%3A'.$endlat.'&at=0&returnJSON=true&timeout=60000&nPaths=1&clientVersion=4.0.0');
	$traffic=json_decode($traffic,true);
	$tijd=0;$lengte=0;
	if(isset($traffic['response']['results'])) {
			foreach($traffic['response']['results'] as $street) {
			$tijd = $tijd + $street['crossTime'];
		}
		return $tijd;
	} 
}
echo '<a href="javascript:location.reload();" style="padding:12px 42px;font-size:20px;font-weight:500;">Verkeersinfo van '.strftime("%k:%M:%S",time()).'</a>';
ob_flush();flush();

echo '<table cellpadding="3px" cellspacing="0px" border="1px" bordercolor="#BBB" bordercolorlight="#BBB" bordercolordark="#BBB"><tr><td width="110px">Van</td><td width="110px">Naar</td><td width="75px" align="center">Tijd</td><td width="75px">Vertraging</td><tr>';
$tijd = traffic(50.892565,3.114135,50.877122,4.164326);
if($tijd>0) {echo '<tr><td>Home</td><td>Work</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>3600) echo strftime("%k:%M:%S",$tijd-3600-3600); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();
$tijd = traffic(50.877122,4.164326,50.892565,3.114135);
if($tijd>0) {echo '<tr><td>Work</td><td>Home</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>3600) echo strftime("%k:%M:%S",$tijd-3600-3600); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();

$tijd = traffic(50.892565,3.114135,50.928279,5.392641);
if($tijd>0) {echo '<tr><td>Home</td><td>Hasselt</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>7200) echo strftime("%k:%M:%S",$tijd-3600-7200); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();
$tijd = traffic(50.928279,5.392641,50.892565,3.114135);
if($tijd>0) {echo '<tr><td>Hasselt</td><td>Home</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>7200) echo strftime("%k:%M:%S",$tijd-3600-7200); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();

$tijd = traffic(50.892565,3.114135,51.033714,3.701498);
if($tijd>0) {echo '<tr><td>Home</td><td>Gent</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>2656) echo strftime("%k:%M:%S",$tijd-3600-2656); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();
$tijd = traffic(51.033714,3.701498,50.892565,3.114135);
if($tijd>0) {echo '<tr><td>Gent</td><td>Home</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>2656) echo strftime("%k:%M:%S",$tijd-3600-2656); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();

$tijd = traffic(50.892565,3.114135,51.208264,4.441884);
if($tijd>0) {echo '<tr><td>Home</td><td>Antwerpen</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>4285) echo strftime("%k:%M:%S",$tijd-3600-4285); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();
$tijd = traffic(51.208264,4.441884,50.892565,3.114135);
if($tijd>0) {echo '<tr><td>Antwerpen</td><td>Home</td><td align="center">'.strftime("%k:%M:%S",$tijd-3600).'</td><td align="center">';if($tijd>4285) echo strftime("%k:%M:%S",$tijd-3600-4285); echo '</td></tr>';} else echo '<tr><td colspan="4">error</td></tr>';
ob_flush();flush();

echo '</table>';
ob_end_flush();
?>
</body></html>
User avatar
G3rard
Posts: 669
Joined: Wednesday 04 March 2015 22:15
Target OS: -
Domoticz version: No
Location: The Netherlands
Contact:

Re: Traffic with waze in Domoticz

Post by G3rard »

Thanks for sharing this code!
Not using Domoticz anymore
User avatar
Egregius
Posts: 2582
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: Traffic with waze in Domoticz

Post by Egregius »

You're welcome.

The code gives this as page:
Image

You'll notice that their is quite some hardcoded stuff in it. Like "if($tijd>4285) echo strftime("%k:%M:%S",$tijd-3600-4285);" shows the delay. 4825 is the 'normal' route time.
The usage of the function is "traffic($startlat, $startlon, $endlat, $endlon)"
User avatar
G3rard
Posts: 669
Joined: Wednesday 04 March 2015 22:15
Target OS: -
Domoticz version: No
Location: The Netherlands
Contact:

Re: Traffic with waze in Domoticz

Post by G3rard »

Thanks for explaining the hardcoded stuff. The page works great over here :D.
Not using Domoticz anymore
Timple
Posts: 5
Joined: Tuesday 20 January 2015 8:05
Target OS: Linux
Domoticz version:
Contact:

Re: Traffic with waze in Domoticz

Post by Timple »

I really like this idea! It inspired me to do the same with this page:
http://www.rijdendetreinen.nl/vertrekti ... /eindhoven (actual train departure times).

I will open a new topic if I have it successfully working, could take a while :)
jmleglise
Posts: 192
Joined: Monday 12 January 2015 23:27
Target OS: Raspberry Pi / ODroid
Domoticz version: 2022.1
Location: FRANCE
Contact:

Re: Traffic with waze in Domoticz

Post by jmleglise »

For those who get the " attempt to index local 'jsonTrajet' (a nil value)" error, here some tips on windows platform :

1/ curl program must be installed and accessible. And a CRT certificate must be accessible to. (as the API is SSL). So I put the curl.exe and curl-ca-bundle.crt in the domoticz directory. (the one where domoticz.exe is)

2/ And be carefull for the path of the json.lua. Like this : json = (loadfile "D:\\Domoticz\\scripts\\lua\\json.lua")()

3/ FYI, x=longitude. y=latitude
My script : https://github.com/jmleglise
RFXTRX433E: Blind Somfy RTS, Portal Somfy Evolvia, chacon IO, Oregon, PIR sensor PT2262
My Last project : Location de maison de vacances a Ouistreham vue mer
KMTronic USB relay
Chinese Z-WAVE: Neo CoolCam
salvation
Posts: 38
Joined: Saturday 06 September 2014 15:34
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

Re: Traffic with waze in Domoticz

Post by salvation »

Some more people who have problem with the php script?
I receive a 403 - Forbidden.
User avatar
Egregius
Posts: 2582
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: Traffic with waze in Domoticz

Post by Egregius »

Indeed, nothing but errors.
bricololo
Posts: 13
Joined: Tuesday 18 February 2014 11:51
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: France
Contact:

Re: Traffic with waze in Domoticz

Post by bricololo »

I use a python script, It's works great.
I put this script in the crontab and run it every 5 min.

Code: Select all

#!/usr/bin/env python2.7
import time
import RPi.GPIO as GPIO
import urllib2
import json

# Parametres
domoticzserver="192.168.0.20:8083"

#requete waze

print "home - work"
idx='113'
startlat='-----------'
startlon=''-----------'
endlat=''-----------'
endlon=''-----------'
extract_var = urllib2.urlopen("https://www.waze.com/row-RoutingManager/routingRequest?from=x%3A" + startlon + "+y%3A" + startlat + "&to=x%3A" + endlon + "+y%3A" + endlat + "").read()
#print "requete recuperee : ", extract_var
#extraction du temps de trajet
pos1 = extract_var.find('<summary time="')+len('<summary time="')
pos2 = extract_var.find('" length=')
pos3 = pos2 + len('" length="')
pos4 = extract_var.find('</route>') - 4
timesec = extract_var[pos1:pos2]
distance = float(extract_var[pos3:pos4])/1000
timesec=int(timesec)
print "Distance : ", distance, " km"
#print "Temps de trajet : ", timesec, " secondes"
timemin=round(float(timesec)/60,2)
print "Temps de trajet : ", timemin, " minutes", "     ==>  format a envoyer a domoticz"
print "Temps de trajet : ", int(timesec/60), " minutes", (float(timesec)/60 - int(timesec/60))*60, " secondes"
urllib2.urlopen("http://" + domoticzserver + "/json.htm?type=command&param=udevice&idx=" + idx + "&nvalue=0&svalue=" + str(timemin) + "")

User avatar
Egregius
Posts: 2582
Joined: Thursday 09 April 2015 12:19
Target OS: Linux
Domoticz version: v2024.7
Location: Beitem, BE
Contact:

Re: Traffic with waze in Domoticz

Post by Egregius »

I guess they try to protect their service.
When I use curl instead of file_get_contents and add a Firefox user agent to it it works again.
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest