Traffic with Google Maps in Domoticz

Moderator: leecollings

User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by remb0 »

great work! I will create a summary for the wiki.
but which key must I choose?
I see only this:
Google Maps APIs:
Google Maps Android API
Google Maps SDK for iOS
Google Maps JavaScript API
Google Places API for Android
Google Places API for iOS
Google Maps Roads API
Google Static Maps API
Google Street View Image API
Google Maps Embed API
Google Places API Web Service
Google Maps Geocoding API
Google Maps Directions API
Google Maps Distance Matrix API
Google Maps Geolocation API
Google Maps Elevation API
Google Maps Time Zone API
User avatar
Westcott
Posts: 423
Joined: Tuesday 09 December 2014 17:04
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: UK - Glos
Contact:

Re: Traffic with Google Maps in Domoticz

Post by Westcott »

It's "The Google Maps Directions API" , with this link to get your own API key -
https://developers.google.com/maps/docu ... troduction
Zwave - Sigma Z+ stick, Fibaro, Horstmann, Neo Coolcam, EUROtronic
RFlink - IR detectors and temperatures
Wifi - YeeLights, ESP32s, Anoop sockets
Zigbee - lots with zigbee2mqtt and ZbBridge
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

Correct!
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by remb0 »

wishes for this great script.

1:
One script for 2 routes: home>work and work to home.

2: instead of a text sensor a custom sensor (so you see a nice graph in logs)

3:
both in a specific time frame an alert if duration is above x.
when one pushmesage send don't send another again (otherwise we will spammed some days)
User avatar
G3rard
Posts: 669
Joined: Wednesday 04 March 2015 22:15
Target OS: -
Domoticz version: No
Location: The Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by G3rard »

Hi Remb0,

I have updated the script of woody a bit so it also can be used for the route work to home.
Also I only get a message when the traveltime is longer than usual. The scripts checks every 30 minutes and only in a certain timeframe, so you won't get spammed.

I am updating the travel time in a pressure sensor in Domoticz so I can use the graph in the log (I am not yet on the beta with the custom sensors).

You still need to change some things to the script:
- idx
- usual travel time
- coordinates
- Google API key
- path of the JSON.lua as I am running Domoticz on a Synology NAS

Code: Select all

---------------------------------
--Script to calculate duration and distance between two points using Google Maps
--Author   : woody4165 based on Neutrino Traffic with Waze, updated by G3rard
--Date     : 9 April 2016 
---------------------------------
commandArray={}

time = os.date("*t")
day = tonumber(os.date("%w"))

--idx of devices for capturing the travel minutes in both direction
idxhomework='252'
idxworkhome='253'
--usual traveltime (mins)
usualtimehomework = 50
usualtimeworkhome = 50
--coordinates home
fromx="xx.xxxxxx"
fromy="y.yyyyyy"
--coordinates work
tox="xx.xxxxxx"
toy="y.yyyyyy"
--Google Api Key
key='key'

--determine workday (Mo-Fri)
if (day > 0 and day < 6) then
    werkweek=true; weekend=false
else
    werkweek=false; weekend=true
end

--determine time (7:00-9:00, 16:00-19:00)
if ((time.hour > 6 and time.hour < 9) or (time.hour == 9 and time.min < 1)) then
    ochtend=true; middag=false
elseif ((time.hour > 15 and time.hour < 19) or (time.hour == 19 and time.min < 1)) then
    ochtend=false; middag=true
else
    ochtend=false; middag=false
end

--calculate traveltime
function traveltime(fromx,fromy,tox,toy)
    --import JSON.lua library
    json = (loadfile "/volume1/@appstore/domoticz/var/scripts/lua/functions/JSON.lua")()

    -- get data from Google Maps and decode it in gmaps
    local jsondata    = assert(io.popen('curl "https://maps.googleapis.com/maps/api/directions/json?origin='..fromx..','..fromy..'&destination='..tox..','..toy..'&departure_time=now&key='..key..'"'))
    local jsondevices = jsondata:read('*all')
    jsondata:close()
    local gmaps = json:decode(jsondevices)

    -- Read from the data table, and extract duration and distance in text
    distance = gmaps.routes[1].legs[1].distance.text
    duration = gmaps.routes[1].legs[1].duration_in_traffic.text

    -- mins is only the number part of duration (for evaulation purpose or to return a number in a number device)
    for minutes in string.gmatch(duration, "%d+") do mins = tonumber(minutes) end
    return mins
end

--weekday (Mo-Fri) and time between 7:00-9:00
if (werkweek and ochtend) then
    --every 30 minutes
    if((time.min % 30)==0) then
        homework=traveltime(fromx,fromy,tox,toy)
        message=tostring(homework)..' minuten naar kantoor | '..("%02d:%02d"):format(time.hour, time.min)
		print(message)
		--send message if traveltime is longer than usual
		if(homework > usualtimehomework) then
		    commandArray['SendNotification']=message
		end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxhomework..'|0|' .. tostring(homework)}
    end
end

--weekday (Mo-Thu) and time between 16:00-19:00
if (werkweek and middag) then
    --every 30 minutes
    if((time.min % 30)==0) then
        workhome=traveltime(tox,toy,fromx,fromy)
        message=tostring(workhome)..' minuten naar huis | '..("%02d:%02d"):format(time.hour, time.min)
		print(message)
		--send message if traveltime is longer than usual
		if(workhome > usualtimeworkhome) then
		    commandArray['SendNotification']=message
		end
        --return a text to the device (eg. 12 mins)
        commandArray[2]={['UpdateDevice'] =idxworkhome..'|0|' .. tostring(workhome)}
    end
end

return commandArray
Not using Domoticz anymore
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

Hi G3rard.

Well done!!!!
It's very clear and clean now...
One question regarding SendNotification.
It will send the notification using all the channels defined in Domoticz.
Is there a way to send it using only one of the channels?
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
xces
Posts: 39
Joined: Thursday 05 February 2015 9:02
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by xces »

i have taken the liberty to refactor (rewrite) the script since it did not feel 'finished' in my eyes. I rewrote it out the top of my head, so it might contain errors but it is simplified a lot.

see here for syntax highlighting: http://codepad.org/IosDVkqX

Code: Select all

---------------------------------
--Script to calculate duration and distance between two points using Google Maps
--Author : woody4165 based on Neutrino Traffic with Waze, updated by G3rard, refactored by xces
--Date : 9 April 2016 
---------------------------------

-- We don't have to run this script at all if:
-- 1) we are not at a half hour mark
-- 2) we are currently in the weekend (or)
time = os.date("*t")
day = tonumber(os.date("%w"))
if ( ((time.min % 30) > 0) or ((day == 0) or (day == 6))) then
	return {}
end

-- Settings for this script
key = 'key'				--Google Api Key
homeX = 'xx.xxxxxx'		--coordinates home
homeY = 'y.yyyyyy'
workX = 'xx.xxxxxx'		--coordinates work
workY = 'y.yyyyyy'
homeWorkIdx = '252'		--idx of devices for capturing the travel minutes
homeWorkMins = 50		--usual traveltime (mins)
homeWorkMsg = "minutes traveltime to the office"
workHomeIdx = '253'		--idx of devices for capturing the travel minutes
workHomeMins = 50		--usual traveltime (mins)
workHomeMsg = "minutes traveltime to home"

-- Start script
commandArray={}

--determine time (7:00-9:00, 16:00-19:00)
if ((time.hour > 6 and time.hour < 9) or (time.hour == 9 and time.min < 1)) then
	-- Morning, traveling from home to work
	sourceX = homeX
	sourceY = homeY
	targetX = workX
	targetY = workY
	deviceIdx = homeWorkIdx
	usualMins = homeWorkMins
	notificationMsg = homeWorkMsg
elseif ((time.hour > 15 and time.hour < 19) or (time.hour == 19 and time.min < 1)) then
	-- Afternoon, traveling from work to home
	sourceX = workX
	sourceY = workY
	targetX = homeX
	targetY = homeY
	deviceIdx = workHomeIdx
	usualMins = workHomeMins
	notificationMsg = workHomeMsg
else
	-- Script is running in a period where we don't have to do anything, so bail
	return commandArray 
end

-- calculates traveltime
function traveltime(fromx, fromy, tox, toy)
	--import JSON.lua library
	json = (loadfile "/volume1/@appstore/domoticz/var/scripts/lua/functions/JSON.lua")()

	-- get data from Google Maps and decode it in gmaps
	local jsondata = assert(io.popen('curl "https://maps.googleapis.com/maps/api/directions/json?origin='..fromx..','..fromy..'&destination='..tox..','..toy..'&departure_time=now&key='..key..'"'))
	local jsondevices = jsondata:read('*all')
	jsondata:close()
	local gmaps = json:decode(jsondevices)

	-- Read from the data table, and extract duration and distance in text
	distance = gmaps.routes[1].legs[1].distance.text
	duration = gmaps.routes[1].legs[1].duration_in_traffic.text

	-- mins is only the number part of duration (for evaulation purpose or to return a number in a number device)
	for minutes in string.gmatch(duration, "%d+") do
		mins = tonumber(minutes)
	end
	return mins
end

-- Since we already put the variables above, we can now simplyfy the code below
currentTravelTimeInMins = traveltime(sourceX, sourceY, targetX, targetY)
message = tostring(currentTravelTimeInMins) .. ' ' .. notificationMsg .. ' | ' .. ("%02d:%02d"):format(time.hour, time.min)
print(message)

-- send message if traveltime is longer than usual
if (currentTravelTimeInMins > usualMins) then
	commandArray['SendNotification'] = message
end

-- return a text to the device (eg. 12 mins)
commandArray[1] = { ['UpdateDevice'] = deviceIdx .. '|0|' .. tostring(currentTravelTimeInMins) }

return commandArray
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

Nice job xces!

I just had to move before declaration of variables the

Code: Select all

-- Start script
commandArray={}
because I was getting this error

Code: Select all

Error: EventSystem: Lua script Traffic did not return a commandArray
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
User avatar
remb0
Posts: 499
Joined: Thursday 11 July 2013 22:21
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands
Contact:

Re: Traffic with Google Maps in Domoticz

Post by remb0 »

nice to see that the community is working together.

other things I will try:
- get the home adres lattitude and longitude from settings.
- better printing in logs
- use custom sensor for a nice graph (so also run outside the period for the logs/statstics)
- can we change hours in more specific time? 6:50 till 7:10 (thats the time I must sit in my car and start driving
and then 16:15 / 16:40 when notification is send )
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

A couple of questions regarding the log.

Since this device will be used mainly for 4-6hrs per day, how do you intend using the log/graph.

I see that after the "working" period the value of the device remain the last that was set.
Probably, should be set to 0, don't you think?
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

Moved to a Dummy Custom Device, and now using log and graph.

In my Frontpage.js, I added some code to change the description of the tab from "Home to Office" to "Office to Home" depending on the operating hours and coloring in green or red depending on the same value of usualtime.
I set to 0 the device when not in operating hours, so the graph is more readable.
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
assenzuid
Posts: 135
Joined: Friday 13 November 2015 9:11
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands, Emmen Area
Contact:

Re: Traffic with Google Maps in Domoticz

Post by assenzuid »

Great stuff. I will also try to implement this.
I have also a feature request.
Is it possible to get some traffic information say around 30Kms of my Home coordinates in a readable view?
My programming knowledge is not so good
bran2000
Posts: 60
Joined: Saturday 20 June 2015 10:16
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Traffic with Google Maps in Domoticz

Post by bran2000 »

Hi,
i have a problem : i used the last script and modify the idx, the coordinates and the Google api key.
your script lua is in the events.
it doesn't work the switch "text"not display anything.
i see in your script a import json.lua Library, do i need to create the file json.lua in the folder /home/pi/domoticz/scripts/lua/ ?
thanks
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

Yes. You need to have JSON.lua (you should find somewhere in the wiki or in the forum where to download) and copy possibly in the lua folder under domoticz/script and call it within this script.
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

assenzuid wrote:Great stuff. I will also try to implement this.
I have also a feature request.
Is it possible to get some traffic information say around 30Kms of my Home coordinates in a readable view?
My programming knowledge is not so good
I don't think that Google give this kind of information in a text way.
The only thing that is near to that is a google map view with colored street, but I don't think can be useful.
If you have a website that give this information and produce such an XML or a file like that maybe it can be checked.
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
bran2000
Posts: 60
Joined: Saturday 20 June 2015 10:16
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Traffic with Google Maps in Domoticz

Post by bran2000 »

Any idea where i can download the JSON.lua ?
i don't find any link
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

Have you tried to search in the wiki for "json.lua"?
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
bran2000
Posts: 60
Joined: Saturday 20 June 2015 10:16
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Traffic with Google Maps in Domoticz

Post by bran2000 »

woody4165 wrote:Nice job xces!

I just had to move before declaration of variables the

Code: Select all

-- Start script
commandArray={}
because I was getting this error

Code: Select all

Error: EventSystem: Lua script Traffic did not return a commandArray
i have the same mistake, what do you mean to move before declaration of variables; how i correct this ?
woody4165
Posts: 476
Joined: Monday 14 March 2016 13:55
Target OS: Linux
Domoticz version: beta
Location: Rome, Italy
Contact:

Re: Traffic with Google Maps in Domoticz

Post by woody4165 »

I have moved it before time = os.date(*t)

And it worked for me.
Cubietruck - Linux cubietruck 4.13.16 (Debian GNU/Linux 8 (jessie)) + Domoticz + RFLink, Xiaomi Gateway, Owl USB, Yeelight Color and B/W, ESP8266, Broadlink RM2, Netatmo Thermostat
bran2000
Posts: 60
Joined: Saturday 20 June 2015 10:16
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

Re: Traffic with Google Maps in Domoticz

Post by bran2000 »

Thanks, it's working for me too !
any idea where i can download the "json.lua" ?
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest