Page 2 of 6

Re: Traffic with waze in Domoticz

Posted: Sunday 25 October 2015 11:53
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

Re: Traffic with waze in Domoticz

Posted: Sunday 25 October 2015 13:39
by Derik
Please...
One says LUA..
Other says PHP...
What option, and what is the best script...? :D :D

Re: Traffic with waze in Domoticz

Posted: Sunday 25 October 2015 14:07
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.

Re: Traffic with waze in Domoticz

Posted: Sunday 25 October 2015 15:22
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

Re: Traffic with waze in Domoticz

Posted: Sunday 25 October 2015 17:10
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

Re: Traffic with waze in Domoticz

Posted: Sunday 25 October 2015 17:54
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

Re: Traffic with waze in Domoticz

Posted: Tuesday 27 October 2015 12:29
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

Re: Traffic with waze in Domoticz

Posted: Wednesday 04 November 2015 20:33
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.

Re: Traffic with waze in Domoticz

Posted: Wednesday 04 November 2015 20:39
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

Re: Traffic with waze in Domoticz

Posted: Wednesday 04 November 2015 22:45
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

Re: Traffic with waze in Domoticz

Posted: Friday 06 November 2015 8:23
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>

Re: Traffic with waze in Domoticz

Posted: Friday 06 November 2015 8:47
by G3rard
Thanks for sharing this code!

Re: Traffic with waze in Domoticz

Posted: Friday 06 November 2015 8:52
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)"

Re: Traffic with waze in Domoticz

Posted: Sunday 08 November 2015 23:05
by G3rard
Thanks for explaining the hardcoded stuff. The page works great over here :D.

Re: Traffic with waze in Domoticz

Posted: Tuesday 10 November 2015 14:24
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 :)

Re: Traffic with waze in Domoticz

Posted: Saturday 14 November 2015 22:07
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

Re: Traffic with waze in Domoticz

Posted: Monday 16 November 2015 19:52
by salvation
Some more people who have problem with the php script?
I receive a 403 - Forbidden.

Re: Traffic with waze in Domoticz

Posted: Monday 16 November 2015 19:59
by Egregius
Indeed, nothing but errors.

Re: Traffic with waze in Domoticz

Posted: Monday 23 November 2015 21:03
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) + "")


Re: Traffic with waze in Domoticz

Posted: Tuesday 24 November 2015 7:51
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.