Page 5 of 7

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 11:05
by Westcott
Use the "value" which is in seconds and divide by 60?

Your route won't work here in the UK, the A4 and A7 are 450km apart...

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 11:22
by woody4165
bran2000 wrote:Hi, i tried your new script !
it's working but the instructions about the traffic is in italian ?
anyway it can be in French for example ?
You mean the Message in Text box or in Telegram?

You can change as you want, just translate text in the script...

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 11:42
by woody4165
EBOOZ wrote:There's a bug when the time exceeds one hour.

Google API output:
Image

Sensors in Domoticz:
Image

Log in Domoticz:
Image

I couldn't find a solution yet. If anyone else has an idea? Much appreciated!
Correct and thanks.

I was grabbing the text thinking only on traffic minutes, not hours!

I've changed the code like this, taking the value instead of text and rounding the duration

Code: Select all

    -- Read from the data table, and extract duration and distance in value. Divide distance by 1000 and duration_in_traffic by 60
    distance = gmaps.routes[1].legs[1].distance.value/1000
    duration = gmaps.routes[1].legs[1].duration_in_traffic.value/60
    summary = gmaps.routes[1].summary
    mins=math.ceil(duration)
    -- mins round the duration

Here is the complete script modified.

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
idxtraffic='xx'
idxroute='xx'
--usual traveltime (mins)
usualtimehomework = 25
usualtimeworkhome = 25
-- Coordinates starting point
fromx="xx.xxxxx"
fromy="xx.xxxx"
-- Coordinates destination point
tox="xx.xxxx"
toy="xx.xxxx"
--Google Api Key
key='xxxxxxxxxxx'

--determine workday (Mo-Fri)
if (day > 0 and day < 6) then
    week=true; weekend=false
else
    week=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
    mattina=true; sera=false
elseif ((time.hour > 15 and time.hour < 19) or (time.hour == 19 and time.min < 1)) then
    mattina=false; sera=true
else
    mattina=false; sera=false
end


--calculate traveltime
function traveltime(fromx,fromy,tox,toy)
    --import JSON.lua library
    json = (loadfile "/home/pi/domoticz/scripts/lua/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 value. Divide distance by 1000 and duration_in_traffic by 60
    distance = gmaps.routes[1].legs[1].distance.value/1000
    duration = gmaps.routes[1].legs[1].duration_in_traffic.value/60
    summary = gmaps.routes[1].summary
    -- mins round the duration
    mins=math.ceil(duration)
    return mins
end

--weekday (Mo-Fri) and time between 7:00-9:00
if (week and mattina) then
    --every 15 minutes
    if((time.min % 15)==0) then
        traffic=traveltime(fromx,fromy,tox,toy)
        message=tostring(traffic)..'min per andare in ufficio alle '..("%02d:%02d"):format(time.hour, time.min)..' percorso '..tostring(summary)
      print(message)
      --send message if traveltime is longer than usual
      if(traffic > usualtimehomework) then
        os.execute('curl --data chat_id=xxxxxxxx --data-urlencode "text='..message..'"  "https://api.telegram.org/botxxxxxxxxxxxxx/sendMessage" ')
--          commandArray['SendNotification']=message
      end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}
    end

--weekday (Mo-Thu) and time between 16:00-19:00
elseif (week and sera) then
    --every 15 minutes
    if((time.min % 15)==0) then
        traffic=traveltime(tox,toy,fromx,fromy)
        message=tostring(traffic)..'min per andare a casa alle '..("%02d:%02d"):format(time.hour, time.min)..' percorso '..tostring(summary)
      print(message)
      --send message if traveltime is longer than usual
--      if(traffic > usualtimeworkhome) then
--        os.execute('curl --data chat_id=xxxxxx --data-urlencode "text='..message..'"  "https://api.telegram.org/botxxxxxxxxx/sendMessage" ')
--          commandArray['SendNotification']=message
--      end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}

    end
else
    -- set device to 0 to prevent device get the last value after working hour
    zero=0
    commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(zero)}
    commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(zero)}
end

return commandArray

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 12:35
by blackdog65
Hi,
I've been trying this handy script... well done and thanks!

When I updated to the latest script my original dummy/custom sensors where "time to work" and "time to home" both with axis label minutes. With the new script, I set the 1st as idxtraffic and 2nd idxroute but both just show "18 mins" but I get

Code: Select all

 2016-04-18 11:15:00.878 LUA: 18min to go to the office at 11:15 route Lynn Rd 
in the log.
Any ideas?

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 12:46
by woody4165
Are you getting traffic data from and to work at the same time? Meaning that you changed some working hours in the script?

The script was intended to get data from home to work at a certain hours and from work to home at other ones.

Don't know if this is the case.

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 13:09
by blackdog65
Hi Woody,
Thanks for the quick reply.
Yeah I did alter the times as my travel times are different, but also I'd like to temporarily extend the hours for testing.

How should I set the

Code: Select all

--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
    mattina=true; sera=false
elseif ((time.hour > 15 and time.hour < 19) or (time.hour == 19 and time.min < 1)) then
    mattina=false; sera=true
else
    mattina=false; sera=false
end

So that I could run it (for testing) 07:00-12:00, 13:00-19:00 without breaking it?

I currently have

Code: Select all

--determine time (7:00-12:00, 13:00-16:00)
if ((time.hour > 6 and time.hour < 12) or (time.hour == 12 and time.min < 1)) then
    morning=true; will_be=false
elseif ((time.hour > 12 and time.hour < 16) or (time.hour == 16 and time.min < 1)) then
    morning=false; will_be=true
else
    morning=false; will_be=false
end
Thanks,

Sean

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 13:36
by woody4165
The Google API call is made within a function that is called in both case, home->work and work->home, and in both cases it return to the same variable.

Try to change this

Code: Select all

if (week and mattina) then
    --every 5 minutes
    if((time.min % 5)==0) then
        traffic=traveltime(fromx,fromy,tox,toy)
        message=tostring(traffic)..'min per andare in ufficio alle '..("%02d:%02d"):format(time.hour, time.min)..' percorso '..tostring(summary)
      --send message if traveltime is longer than usual
      if(traffic > usualtimehomework) then
        os.execute('curl --data chat_id=2285843 --data-urlencode "text='..message..'"  "https://api.telegram.org/bot196378808:AAFq49rg69CYODb2CBMBfLmKskseZCAvemA/sendMessage" ')
--          commandArray['SendNotification']=message
      end
        --return a text to the device (eg. 12 mins)
--        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic) .. '-->'}
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}
    end

--weekday (Mo-Thu) and time between 16:00-19:00
elseif (week and sera) then
    --every 5 minutes
    if((time.min % 5)==0) then
        traffic=traveltime(tox,toy,fromx,fromy)
        message=tostring(traffic)..'min per andare a casa alle '..("%02d:%02d"):format(time.hour, time.min)..' percorso '..tostring(summary)
      --send message if traveltime is longer than usual
--      if(traffic > usualtimeworkhome) then
--        os.execute('curl --data chat_id=2285843 --data-urlencode "text='..message..'"  "https://api.telegram.org/bot196378808:AAFq49rg69CYODb2CBMBfLmKskseZCAvemA/sendMessage" ')
--          commandArray['SendNotification']=message
--      end
        --return a text to the device (eg. 12 mins)
--        commandArray[2]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic) .. '<--'}
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}

    end
 
into this

Code: Select all

if (week and mattina) then
    --every 5 minutes
    if((time.min % 5)==0) then
        traffic_Home2Work=traveltime(fromx,fromy,tox,toy)
        message=tostring(traffic_Home2Work)..'min per andare in ufficio alle '..("%02d:%02d"):format(time.hour, time.min)..' percorso '..tostring(summary)
      --send message if traveltime is longer than usual
      if(traffic_Home2Work > usualtimehomework) then
        os.execute('curl --data chat_id=2285843 --data-urlencode "text='..message..'"  "https://api.telegram.org/bot196378808:AAFq49rg69CYODb2CBMBfLmKskseZCAvemA/sendMessage" ')
--          commandArray['SendNotification']=message
      end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic_Home2Work)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}
    end

--weekday (Mo-Thu) and time between 16:00-19:00
elseif (week and sera) then
    --every 5 minutes
    if((time.min % 5)==0) then
        traffic_Work2Home=traveltime(tox,toy,fromx,fromy)
        message=tostring(traffic_Work2Home)..'min per andare a casa alle '..("%02d:%02d"):format(time.hour, time.min)..' percorso '..tostring(summary)
      --send message if traveltime is longer than usual
--      if(traffic_Work2Home > usualtimeworkhome) then
--        os.execute('curl --data chat_id=2285843 --data-urlencode "text='..message..'"  "https://api.telegram.org/bot196378808:AAFq49rg69CYODb2CBMBfLmKskseZCAvemA/sendMessage" ')
--          commandArray['SendNotification']=message
--      end
        --return a text to the device (eg. 12 mins)
        commandArray[1]={['UpdateDevice'] =idxtraffic..'|0|' .. tostring(traffic_Work2Home)}
        commandArray[2]={['UpdateDevice'] =idxroute..'|0|' .. tostring(message)}

    end
In changed the variable "traffic" into "traffic_Home2Work" in the morning part, and "traffic" into "traffic_Work2Home" in the afternoon part.

Try this. If it's ok, I will made this change in the script and post it fully.

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 15:39
by bran2000
woody4165 wrote:
bran2000 wrote:Hi, i tried your new script !
it's working but the instructions about the traffic is in italian ?
anyway it can be in French for example ?
You mean the Message in Text box or in Telegram?

You can change as you want, just translate text in the script...
thanks i just did

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 16:57
by blackdog65
Hi Woody,
The script runs, noted in log, but seems to be frozen at "18Mins" with no further route info.

Re: Traffic with Google Maps in Domoticz

Posted: Monday 18 April 2016 18:05
by woody4165
blackdog65 wrote:Hi Woody,
The script runs, noted in log, but seems to be frozen at "18Mins" with no further route info.
Where is freezing, can you show the log and the part of the script you think is causing this?

Re: Traffic with Google Maps in Domoticz

Posted: Tuesday 19 April 2016 9:02
by EBOOZ
woody4165 wrote:
EBOOZ wrote:There's a bug when the time exceeds one hour.
I was grabbing the text thinking only on traffic minutes, not hours!

I've changed the code like this, taking the value instead of text and rounding the duration
Thanks, woody! Works like a charm :)

Re: Traffic with Google Maps in Domoticz

Posted: Tuesday 19 April 2016 18:03
by blackdog65
Hi again Woody,
Sorry for the delay, I had an emergency trip to London :twisted: hate the place

So, here's my log output, note there is now no route info as before.

Code: Select all

 2016-04-19 15:20:01.956 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:25:01.396 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:30:01.323 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:35:02.251 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:40:01.664 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:45:01.816 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:50:01.206 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 15:55:03.046 EventSystem: Script event triggered: script_time_traffic.lua
2016-04-19 16:00:01.445 EventSystem: Script event triggered: script_time_traffic.lua 
But I have found that my sensors were not frozen but since the code change at 1300 yesterday there has been minimal movement.
graph.png
graph.png (26.3 KiB) Viewed 3537 times
My big worry is that my sensors look like this,
sensors.png
sensors.png (17.02 KiB) Viewed 3537 times
with no reference to "route"
Am I doing something wrong?
Sean

Re: Traffic with Google Maps in Domoticz

Posted: Tuesday 19 April 2016 18:28
by woody4165
Hi Sean

I think we have to distinguish two things.
Are these sensors text or what?

I'm using beta Domoticz and using a Custom sensor to get minutes number (and get graph) and a Text sensor to have the same text I'm going to send via Telegram, with the route.

So, if you want to get both information you get two choices:
you are on stable version (and you don't have Custom Sensor) or you don't need/want graph, you need to create two text Sensor and put there the complete text using something like these that you can find in my script published before:

Code: Select all

message=tostring(traffic_Home2Work)..'min to go to office at '..("%02d:%02d"):format(time.hour, time.min)..' route '..tostring(summary)
if you want Custom Sensors to have also graph you can create either only two sensors, one Custom and one Text and use it for Home2Work and Work2Home, since they are in different hours, or either create two couple of sensor like before and get information separated.

Hope I haven't confused you more... 8-)

In any case, if you post your script I can take a look into it...

Re: Traffic with Google Maps in Domoticz

Posted: Wednesday 20 April 2016 12:17
by blackdog65
Yay! I have it! I had 2 custom sensor. I changed it to one custom and one txt and it works perfectly.

Many thanks Woody, I hope I can help you one day :)

Re: Traffic with Google Maps in Domoticz

Posted: Saturday 23 April 2016 17:33
by woody4165
No, problem. We are here to help each other! :D

Re: Traffic with Google Maps in Domoticz

Posted: Saturday 23 April 2016 18:43
by sj3fk3
EBOOZ wrote:There's a bug when the time exceeds one hour.

Google API output:
Image

I couldn't find a solution yet. If anyone else has an idea? Much appreciated!
Yes, don't use the text but use the value and just divide by 60 to get minutes..

Re: Traffic with Google Maps in Domoticz

Posted: Wednesday 04 May 2016 11:48
by sjefk
Hi all,

I am struggling a bit with this script..
Getting the following error:

2016-05-04 11:40:00.552 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_google.lua: /home/pi/domoticz/scripts/lua/script_time_google.lua:55: attempt to index field '?' (a nil value)

Problem seems to be line 55 .. which is..

distance = gmaps.routes[1].legs[1].distance.value/1000

So i suspected something is wrong with the url on line 49.. so i executed this in the browser and without any error..

https://maps.googleapis.com/maps/api/di ... le-api-key

The output of the url seems also ok..

"copyrights" : "Kaartgegevens ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "65,0 km",
"value" : 65016
},
"duration" : {
"text" : "43 min.",
"value" : 2579
},
"end_address" : "Atoomweg 60, 3542 AB Utrecht, Nederland",
"end_location" : {
"lat" : 52.1106402,
"lng" : 5.062270199999999
},
"start_address" : "Van Leeuwenhoeklaan 53-55, 4904 KP Oosterhout, Nederland",
"start_location" : {
"lat" : 51.6200264,
"lng" : 4.8544003
},

Can somebody point me in the right direction ?

Best regards,

Sjef

Re: Traffic with Google Maps in Domoticz

Posted: Wednesday 04 May 2016 12:00
by Westcott
Is that the complete output?
The outer 'routes' section seems to be missing.
If I try it with my key I get (with 'routes') -
{
geocoded_waypoints: [
{
geocoder_status: "OK",
place_id: "EjhWYW4gTGVldXdlbmhvZWtsYWFuIDUzLTU1LCA0OTA0IEtQIE9vc3RlcmhvdXQsIE5lZGVybGFuZA",
types: [
"street_address"
]
},
{
geocoder_status: "OK",
place_id: "ChIJ-zDCwLhvxkcREbu0NLbbhRI",
types: [
"street_address"
]
}
],
routes: [
{
bounds: {
northeast: {
lat: 52.1154437,
lng: 5.1058217
},
southwest: {
lat: 51.6188531,
lng: 4.8544003
}
},
copyrights: "Map data ©2016 Google",
legs: [
{
distance: {
text: "65.0 km",
value: 65016
},

Re: Traffic with Google Maps in Domoticz

Posted: Wednesday 04 May 2016 12:10
by sjefk
No, this is not the complete output..
The complete output is a lot.. also with directions but let's check if i can find the 'outer' section of the route.
I removed the steps from the output below.

{
"geocoded_waypoints" : [
{
"geocoder_status" : "OK",
"place_id" : "EjhWYW4gTGVldXdlbmhvZWtsYWFuIDUzLTU1LCA0OTA0IEtQIE9vc3RlcmhvdXQsIE5lZGVybGFuZA",
"types" : [ "street_address" ]
},
{
"geocoder_status" : "OK",
"place_id" : "ChIJ-zDCwLhvxkcREbu0NLbbhRI",
"types" : [ "street_address" ]
}
],
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 52.1154437,
"lng" : 5.1058217
},
"southwest" : {
"lat" : 51.6188531,
"lng" : 4.8544003
}
},
"copyrights" : "Kaartgegevens ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "65,0 km",
"value" : 65016
},
"duration" : {
"text" : "43 min.",
"value" : 2579
},
"end_address" : "Atoomweg 60, 3542 AB Utrecht, Nederland",
"end_location" : {
"lat" : 52.1106402,
"lng" : 5.062270199999999
},
"start_address" : "Van Leeuwenhoeklaan 53-55, 4904 KP Oosterhout, Nederland",
"start_location" : {
"lat" : 51.6200264,
"lng" : 4.8544003
},

.. ],
"via_waypoint" : []
}
],
"overview_polyline" : {
"points" : "e`azH_cs\\xBuGhByEFQWGcAoAoDgEmCaD_CqCW]J[Zq@r@mBTm@MMiBqBaEqEsFyGoAgAsE_FYYaEsESa@gCgCyAaAl@_FhAsEbBgFy@q@mB}@gA}@kEgE_@KwAcBcBqBaPqRgPmRqDcD{FgDkDkAcDi@{DUsIPkWv@gXx@eWdA}d@lDa{@vGkFPmH?yI_@oIcAgJgB{^}HsYgG_GoAoj@mLka@qIaEk@{Ee@mDQw_@eAu`@cAmGi@mG}@oH_BmOoEkF{AuBw@eBs@{HwDaG{DmDsCsCoCqDaEeDkE}FmJaRq`@iKcUuDoHoG_KsGiIaJ{JgGoGyHuHaIgHiEaDoF}C{FgCqHuCcNgFmZgLiGmBqFiAeEi@e`@uDeEU}CEgLTeKXgYv@eLZwC?oG[cMsAm^cEkiAiMwFs@eIgBkiAca@eQcG}PaFsO{Dur@qQsEoAeMcEoLgEi}@y[u}@_\\wFsB_JyDsL_Gsj@oXcP_IkRuJuLsGsDmB_x@mb@qNuHqFkC{IcDyEuAgWsHo\\sJki@{O_OqEoHcDsUkLcy@oa@uUoLkH_EmAw@oEaDqE}Dos@ws@ei@ki@{FsGcDyEmBgDcCaF_B}DkAaDsB_HaBsHoAgHcAgHsAmMoAeTk@mUOqMAcHCeK@oUFgcA@_E?km@M}J]qKe@{HmAgN{AgLuAcIwDiPaByF_BaF_DoIoF}LmIaPwL}R{MsR}JwMkA{AOe@oFkIuAgCo@}AqA}E[iBw@_FWkEu@sG{@}CaAcBy@{@iAo@oA_@eAGeCf@}BzB}@xA_BfEeBpGwAjEiAbC{DjGoC|D{@bBMt@aDxFeBtDcCtF_JxSaLlWsBdEoAnBsBpCeBhBaFtD{PbKuKvF{PhIkUfKkE|AaI~BkLbDmJnDcJ`EiOhHcRlJqNzHuHfDsS~HsE|AuEjAoFz@sBPgHViIE{\\a@}z@wAcm@s@aDO{C[sEq@kDu@{H{ByMiEcCu@c@a@aDoA{JkDiNeEyNsEaBs@sAeAeDgDuBmAsA]uAOgFAiB[cDa@iGoB{MsDkE_A_IcCaCk@aGaAiDOkFGkGP}FPgMtByGvB{GxCoEdCaTlOiK|HcMnI{K`KwH|HaDrD{CvDmH`LoC~D}EvIQJeDhFiDdEsC`G[h@c@x@OAc@a@{H{IuCqBwA{@YIiBWmBMwBg@SIX{@lAgBpGaHrAgBxEsFvGeH"
},
"summary" : "A27",
"warnings" : [],
"waypoint_order" : []
}
],
"status" : "OK"
}

Re: Traffic with Google Maps in Domoticz

Posted: Wednesday 04 May 2016 13:06
by woody4165
It's really strange...

I just test it moving just the json part to another script and I have like this:

Code: Select all

    --import JSON.lua library
    json = (loadfile "/home/pi/domoticz/scripts/lua/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
    distancet = gmaps.routes[1].legs[1].distance.text
    distance = gmaps.routes[1].legs[1].distance.value/1000

    duration = gmaps.routes[1].legs[1].duration_in_traffic.text
    
    
    print("distance "..distance.." distancet "..distancet.." duration "..duration)


And all is working fine...

what if you print just jsondevices to see if there is something before decoding, just like this

Code: Select all

print(jsondevices)