98_TRAFFIC.pm 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. #########################################################################
  2. # $Id: 98_TRAFFIC.pm 16026 2018-01-28 18:06:52Z jmike $
  3. # fhem Modul which provides traffic details with Google Distance API
  4. #
  5. # This file is part of fhem.
  6. #
  7. # Fhem is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Fhem is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with fhem. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. # versioning: MAJOR.MINOR.PATCH, increment the:
  21. # MAJOR version when you make incompatible API changes
  22. # - includes changing CLI options, changing log-messages
  23. # MINOR version when you add functionality in a backwards-compatible manner
  24. # - includes adding new features and log-messages (as long as they don't break anything existing)
  25. # PATCH version when you make backwards-compatible bug fixes.
  26. #
  27. ##############################################################################
  28. # Changelog:
  29. #
  30. # 2016-07-26 initial release
  31. # 2016-07-28 added eta, readings in minutes
  32. # 2016-08-01 changed JSON decoding/encofing, added stateReading attribute, added outputReadings attribute
  33. # 2016-08-02 added attribute includeReturn, round minutes & smart zero'ing, avoid negative values, added update burst
  34. # 2016-08-05 fixed 3 perl warnings
  35. # 2016-08-09 added auto-update if status returns UNKOWN_ERROR, added outputReading average
  36. # 2016-09-25 bugfix Blocking, improved errormessage
  37. # 2016-10-07 version 1.0, adding to SVN
  38. # 2016-10-15 adding attribute updateSchedule to provide flexible updates, changed internal interval to INTERVAL
  39. # 2016-12-13 adding travelMode, fixing stateReading with value 0
  40. # 2016-12-15 adding reverseWaypoints attribute, adding weblink with auto create route via gmaps on verbose 5
  41. # 2017-04-21 reduced log entries if verbose is not set, fixed JSON error, Map available through FHEM-Web-toggle, and direct link
  42. # Map https, with APIKey, Traffic & customizable, new attributes GoogleMapsStyle,GoogleMapsSize,GoogleMapsLocation,GoogleMapsStroke,GoogleMapsDisableUI
  43. # 2017-04-21 added buttons to save current map settings, renamed attribute GoogleMapsLocation to GoogleMapsCenter
  44. # 2017-04-22 v1.3.2 stroke supports weight and opacity, minor fixes
  45. # 2017-12-51 v1.3.3 catch JSON decode issue, addedn Dbog_splitFn, added reading summary, new attr GoogleMapsFixedMap, net attr alternatives, new reading alternatives, alternatives, lighter&thinner on map
  46. # 2018-01-26 v1.3.4 fixed Dbog_splitFn, improved exception handling
  47. # 2018-01-28 v1.3.5 fixed Dbog_splitFn again
  48. # 2018-01-28 v1.3.6 removed perl warning on module load
  49. #
  50. ##############################################################################
  51. package main;
  52. use strict;
  53. use warnings;
  54. use Data::Dumper;
  55. use Time::HiRes qw(gettimeofday);
  56. use LWP::Simple qw($ua get);
  57. use Blocking;
  58. use POSIX;
  59. use JSON;
  60. die "MIME::Base64 missing!" unless(eval{require MIME::Base64});
  61. die "JSON missing!" unless(eval{require JSON});
  62. sub TRAFFIC_Initialize($);
  63. sub TRAFFIC_Define($$);
  64. sub TRAFFIC_Undef($$);
  65. sub TRAFFIC_Set($@);
  66. sub TRAFFIC_Attr(@);
  67. sub TRAFFIC_GetUpdate($);
  68. sub TRAFFIC_DbLog_split($);
  69. my %TRcmds = (
  70. 'update' => 'noArg',
  71. );
  72. my $TRVersion = '1.3.6';
  73. sub TRAFFIC_Initialize($){
  74. my ($hash) = @_;
  75. $hash->{DefFn} = "TRAFFIC_Define";
  76. $hash->{UndefFn} = "TRAFFIC_Undef";
  77. $hash->{SetFn} = "TRAFFIC_Set";
  78. $hash->{AttrFn} = "TRAFFIC_Attr";
  79. $hash->{AttrList} =
  80. "disable:0,1 start_address end_address raw_data:0,1 language waypoints returnWaypoints stateReading outputReadings travelMode:driving,walking,bicycling,transit includeReturn:0,1 updateSchedule GoogleMapsStyle:default,silver,dark,night GoogleMapsSize GoogleMapsZoom GoogleMapsCenter GoogleMapsStroke GoogleMapsTrafficLayer:0,1 GoogleMapsDisableUI:0,1 GoogleMapsFixedMap:0,1 alternatives:0,1 " .
  81. $readingFnAttributes;
  82. $data{FWEXT}{"/TRAFFIC"}{FUNC} = "TRAFFIC";
  83. $data{FWEXT}{"/TRAFFIC"}{FORKABLE} = 1;
  84. $hash->{FW_detailFn} = "TRAFFIC_fhemwebFn";
  85. $hash->{DbLog_splitFn} = "TRAFFIC_DbLog_split";
  86. }
  87. sub TRAFFIC_Define($$){
  88. my ($hash, $allDefs) = @_;
  89. my @deflines = split('\n',$allDefs);
  90. my @apiDefs = split('[ \t]+', shift @deflines);
  91. if(int(@apiDefs) < 3) {
  92. return "too few parameters: 'define <name> TRAFFIC <APIKEY>'";
  93. }
  94. $hash->{NAME} = $apiDefs[0];
  95. $hash->{APIKEY} = $apiDefs[2];
  96. $hash->{VERSION} = $TRVersion;
  97. delete($hash->{BURSTCOUNT}) if $hash->{BURSTCOUNT};
  98. delete($hash->{BURSTINTERVAL}) if $hash->{BURSTINTERVAL};
  99. my $name = $hash->{NAME};
  100. #clear all readings
  101. foreach my $clearReading ( keys %{$hash->{READINGS}}){
  102. Log3 $hash, 5, "TRAFFIC: ($name) READING: $clearReading deleted";
  103. delete($hash->{READINGS}{$clearReading});
  104. }
  105. #clear all helpers
  106. foreach my $helperName ( keys %{$hash->{helper}}){
  107. delete($hash->{helper}{$helperName});
  108. }
  109. # clear weblink
  110. FW_fC("delete ".$name."_weblink");
  111. # basic update INTERVAL
  112. if(scalar(@apiDefs) > 3 && $apiDefs[3] =~ m/^\d+$/){
  113. $hash->{INTERVAL} = $apiDefs[3];
  114. }else{
  115. $hash->{INTERVAL} = 3600;
  116. }
  117. Log3 $hash, 4, "TRAFFIC: ($name) defined ".$hash->{NAME}.' with interval set to '.$hash->{INTERVAL};
  118. # put in default verbose level
  119. $attr{$name}{"verbose"} = 1 if !$attr{$name}{"verbose"};
  120. $attr{$name}{"outputReadings"} = "text" if !$attr{$name}{"outputReadings"};
  121. readingsSingleUpdate( $hash, "state", "Initialized", 1 );
  122. my $firstTrigger = gettimeofday() + 2;
  123. $hash->{TRIGGERTIME} = $firstTrigger;
  124. $hash->{TRIGGERTIME_FMT} = FmtDateTime($firstTrigger);
  125. RemoveInternalTimer($hash);
  126. InternalTimer($firstTrigger, "TRAFFIC_StartUpdate", $hash, 0);
  127. Log3 $hash, 5, "TRAFFIC: ($name) InternalTimer set to call GetUpdate in 2 seconds for the first time";
  128. return undef;
  129. }
  130. sub TRAFFIC_Undef($$){
  131. my ( $hash, $arg ) = @_;
  132. RemoveInternalTimer ($hash);
  133. return undef;
  134. }
  135. sub TRAFFIC_fhemwebFn($$$$) {
  136. my ($FW_wname, $device, $room, $pageHash) = @_; # pageHash is set for summaryFn.
  137. my $name = $device;
  138. my $hash = $defs{$name};
  139. my $mapState = ReadingsVal($device,".map", "off") eq "on" ? "off" : "on";
  140. my $web = "<span><a href=\"$FW_ME?detail=$device&amp;cmd.$device=setreading $device .map $mapState$FW_CSRF\">toggle Map</a>&nbsp;&nbsp;</span><br>";
  141. if (ReadingsVal($device,".map","off") eq "on") {
  142. $web .= TRAFFIC_GetMap($device);
  143. $web .= TRAFFIC_weblink($device);
  144. $web .= "<form method=\"$FW_formmethod\" action=\"$FW_ME$FW_subdir\" >";
  145. $web .= FW_hidden("fwcsrf", $defs{$FW_wname}{CSRFTOKEN}) if($FW_CSRF);
  146. $web .= FW_hidden("detail", $device);
  147. $web .= FW_hidden("dev.attr$device", $device);
  148. $web .= "<input style='display:none' type='submit' value='save Zoom' class='attr' id='currentMapZoomSubmit'>";
  149. $web .= "<input type='hidden' name='val.attr$device' value='' id='currentMapZoom'>";
  150. $web .= "<input type='hidden' name='cmd.attr$device' value='attr'>";
  151. $web .= "<input type='hidden' name='arg.attr$device' value='GoogleMapsZoom'>";
  152. $web .= "</form>";
  153. $web .= "<form method=\"$FW_formmethod\" action=\"$FW_ME$FW_subdir\" >";
  154. $web .= FW_hidden("fwcsrf", $defs{$FW_wname}{CSRFTOKEN}) if($FW_CSRF);
  155. $web .= FW_hidden("detail", $device);
  156. $web .= FW_hidden("dev.attr$device", $device);
  157. $web .= "<input style='display:none' type='submit' value='save Center' class='attr' id='currentMapCenterSubmit'>";
  158. $web .= "<input type='hidden' name='val.attr$device' value='' id='currentMapCenter'>";
  159. $web .= "<input type='hidden' name='cmd.attr$device' value='attr'>";
  160. $web .= "<input type='hidden' name='arg.attr$device' value='GoogleMapsCenter'>";
  161. $web .= "</form>";
  162. }
  163. return $web;
  164. }
  165. sub TRAFFIC_GetMap($@){
  166. my $device = shift();
  167. my $name = $device;
  168. my $hash = $defs{$name};
  169. my $debugPoly=1;
  170. my @alternativesPoly = split(',',decode_base64($hash->{helper}{'Poly'}));
  171. my $returnDebugPoly = $hash->{helper}{'return_Poly'};
  172. my $GoogleMapsCenter = AttrVal($name, "GoogleMapsCenter", $hash->{helper}{'GoogleMapsCenter'});
  173. if(!$debugPoly || !$GoogleMapsCenter){
  174. return "<div>please update your device first</div>";
  175. }
  176. my%GoogleMapsStyles=(
  177. 'default' => "[]",
  178. 'silver' => '[{"elementType":"geometry","stylers":[{"color":"#f5f5f5"}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"elementType":"labels.text.fill","stylers":[{"color":"#616161"}]},{"elementType":"labels.text.stroke","stylers":[{"color":"#f5f5f5"}]},{"featureType":"administrative.land_parcel","elementType":"labels.text.fill","stylers":[{"color":"#bdbdbd"}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#eeeeee"}]},{"featureType":"poi","elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#e5e5e5"}]},{"featureType":"poi.park","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]},{"featureType":"road","elementType":"geometry","stylers":[{"color":"#ffffff"}]},{"featureType":"road.arterial","elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#dadada"}]},{"featureType":"road.highway","elementType":"labels.text.fill","stylers":[{"color":"#616161"}]},{"featureType":"road.local","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"color":"#e5e5e5"}]},{"featureType":"transit.station","elementType":"geometry","stylers":[{"color":"#eeeeee"}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#c9c9c9"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]}]',
  179. 'dark' => '[{"elementType":"geometry","stylers":[{"color":"#212121"}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"elementType":"labels.text.stroke","stylers":[{"color":"#212121"}]},{"featureType":"administrative","elementType":"geometry","stylers":[{"color":"#757575"}]},{"featureType":"administrative.country","elementType":"labels.text.fill","stylers":[{"color":"#9e9e9e"}]},{"featureType":"administrative.land_parcel","stylers":[{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"labels.text.fill","stylers":[{"color":"#bdbdbd"}]},{"featureType":"poi","elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#181818"}]},{"featureType":"poi.park","elementType":"labels.text.fill","stylers":[{"color":"#616161"}]},{"featureType":"poi.park","elementType":"labels.text.stroke","stylers":[{"color":"#1b1b1b"}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#2c2c2c"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#8a8a8a"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#373737"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#3c3c3c"}]},{"featureType":"road.highway.controlled_access","elementType":"geometry","stylers":[{"color":"#4e4e4e"}]},{"featureType":"road.local","elementType":"labels.text.fill","stylers":[{"color":"#616161"}]},{"featureType":"transit","elementType":"labels.text.fill","stylers":[{"color":"#757575"}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#000000"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#3d3d3d"}]}]',
  180. 'night' => '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]},{"elementType":"labels.text.fill","stylers":[{"color":"#746855"}]},{"elementType":"labels.text.stroke","stylers":[{"color":"#242f3e"}]},{"featureType":"administrative.locality","elementType":"labels.text.fill","stylers":[{"color":"#d59563"}]},{"featureType":"poi","elementType":"labels.text.fill","stylers":[{"color":"#d59563"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#263c3f"}]},{"featureType":"poi.park","elementType":"labels.text.fill","stylers":[{"color":"#6b9a76"}]},{"featureType":"road","elementType":"geometry","stylers":[{"color":"#38414e"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"color":"#212a37"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#9ca5b3"}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#746855"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#1f2835"}]},{"featureType":"road.highway","elementType":"labels.text.fill","stylers":[{"color":"#f3d19c"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#2f3948"}]},{"featureType":"transit.station","elementType":"labels.text.fill","stylers":[{"color":"#d59563"}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#17263c"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#515c6d"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#17263c"}]}]',
  181. );
  182. my $selectedGoogleMapsStyle = $GoogleMapsStyles{ AttrVal($name, "GoogleMapsStyle", 'default' )};
  183. if(!$selectedGoogleMapsStyle){$selectedGoogleMapsStyle = $GoogleMapsStyles{'default'}}; #catch attribute mistake here
  184. # load map scale and zoom from attr, override if empty/na
  185. my ( $GoogleMapsWidth, $GoogleMapsHeight ) = AttrVal($name, "GoogleMapsSize", '800,600') =~ m/(\d+),(\d+)/;
  186. my ( $GoogleMapsZoom ) = AttrVal($name, "GoogleMapsZoom", '10');
  187. my ( $GoogleMapsStroke1Color, $GoogleMapsStroke1Weight, $GoogleMapsStroke1Opacity, $GoogleMapsStroke2Color, $GoogleMapsStroke2Weight, $GoogleMapsStroke2Opacity ) = AttrVal($name, "GoogleMapsStroke", '#4cde44,6,100,#FF0000,1,100') =~ m/^(#[a-zA-z0-9]+),?(\d*),?(\d*),?(#[a-zA-z0-9]+)?,?(\d*),?(\d*)/;
  188. # catch incomplete configuration here and put in defaults
  189. $GoogleMapsStroke1Color = '#4cde44' if !$GoogleMapsStroke1Color;
  190. $GoogleMapsStroke1Weight = '6' if !$GoogleMapsStroke1Weight;
  191. $GoogleMapsStroke1Opacity = '100' if !$GoogleMapsStroke1Opacity;
  192. $GoogleMapsStroke2Color = '#FF0000' if !$GoogleMapsStroke2Color;
  193. $GoogleMapsStroke2Weight = '1' if !$GoogleMapsStroke2Weight;
  194. $GoogleMapsStroke2Opacity = '100' if !$GoogleMapsStroke2Opacity;
  195. # make percent value to 50 to 0.5 etc
  196. $GoogleMapsStroke1Opacity = ($GoogleMapsStroke1Opacity / 100);
  197. $GoogleMapsStroke2Opacity = ($GoogleMapsStroke2Opacity / 100);
  198. # pregenerate the alternatives colors, bit darker and thinner than the primary route
  199. my $GoogleMapsStrokeAColor = '#'.lightHex($GoogleMapsStroke1Color, '0.3');
  200. my $GoogleMapsStrokeAWeight = int($GoogleMapsStroke1Weight - 3);
  201. my $GoogleMapsStrokeAOpacity = $GoogleMapsStroke1Opacity;
  202. my $GoogleMapsDisableUI = '';
  203. $GoogleMapsDisableUI = "disableDefaultUI: true," if AttrVal($name, "GoogleMapsDisableUI", 0) eq 1;
  204. my $GoogleMapsFixedMap = '';
  205. $GoogleMapsFixedMap = "draggable: false," if AttrVal($name, "GoogleMapsFixedMap", 0) eq 1;
  206. Log3 $hash, 4, "TRAFFIC: ($name) drawing map in style ".AttrVal($name, "GoogleMapsStyle", 'default' )." in $GoogleMapsWidth x $GoogleMapsHeight px";
  207. my $map;
  208. $map .= '<div><script type="text/javascript" src="https://maps.google.com/maps/api/js?key='.$hash->{APIKEY}.'&libraries=geometry&amp"></script>';
  209. foreach my $polyIndex (0..$#alternativesPoly){
  210. $map .= '<input size="200" type="hidden" id="path'.$polyIndex.'" value="'.$alternativesPoly[$polyIndex].'">';
  211. }
  212. $map .= '<input size="200" type="hidden" id="pathR" value="'.decode_base64($returnDebugPoly).'">' if $returnDebugPoly && decode_base64($returnDebugPoly);
  213. $map .= '
  214. <div id="map"></div>
  215. <style>
  216. #map {width:'.$GoogleMapsWidth.'px;height:'.$GoogleMapsHeight.'px;}
  217. </style>
  218. <script type="text/javascript">
  219. function initialize() {
  220. var myLatlng = new google.maps.LatLng('.$GoogleMapsCenter.');
  221. var myOptions = {
  222. zoom: '.$GoogleMapsZoom.',
  223. '.$GoogleMapsFixedMap.'
  224. center: myLatlng,
  225. '.$GoogleMapsDisableUI.'
  226. mapTypeId: google.maps.MapTypeId.ROADMAP,
  227. styles: '.$selectedGoogleMapsStyle.'
  228. }
  229. var map = new google.maps.Map(document.getElementById("map"), myOptions);
  230. ';
  231. foreach my $polyIndex (1..$#alternativesPoly){
  232. $map .='var decodedPath = google.maps.geometry.encoding.decodePath(document.getElementById("path'.$polyIndex.'").value);
  233. var decodedLevels = decodeLevels("");
  234. var setRegion = new google.maps.Polyline({
  235. path: decodedPath,
  236. levels: decodedLevels,
  237. strokeColor: "'.$GoogleMapsStrokeAColor.'",
  238. strokeOpacity: '.$GoogleMapsStrokeAOpacity.',
  239. strokeWeight: '.$GoogleMapsStrokeAWeight.',
  240. map: map
  241. });
  242. ';
  243. }
  244. $map .= 'var decodedPathR = google.maps.geometry.encoding.decodePath(document.getElementById("pathR").value);
  245. var decodedLevelsR = decodeLevels("");
  246. var setRegionR = new google.maps.Polyline({
  247. path: decodedPathR,
  248. levels: decodedLevels,
  249. strokeColor: "'.$GoogleMapsStroke2Color.'",
  250. strokeOpacity: '.$GoogleMapsStroke2Opacity.',
  251. strokeWeight: '.$GoogleMapsStroke2Weight.',
  252. map: map
  253. });' if $returnDebugPoly && decode_base64($returnDebugPoly );
  254. $map .='var decodedPath = google.maps.geometry.encoding.decodePath(document.getElementById("path0").value);
  255. var decodedLevels = decodeLevels("");
  256. var setRegion = new google.maps.Polyline({
  257. path: decodedPath,
  258. levels: decodedLevels,
  259. strokeColor: "'.$GoogleMapsStroke1Color.'",
  260. strokeOpacity: '.$GoogleMapsStroke1Opacity.',
  261. strokeWeight: '.$GoogleMapsStroke1Weight.',
  262. map: map
  263. });
  264. ';
  265. $map .= 'var trafficLayer = new google.maps.TrafficLayer();
  266. trafficLayer.setMap(map);' if AttrVal($name, "GoogleMapsTrafficLayer", 0) eq 1;
  267. $map .='
  268. map.addListener("zoom_changed", function() {
  269. document.getElementById("currentMapZoom").value = map.getZoom();
  270. document.getElementById("currentMapZoomSubmit").style.display = "block";
  271. });
  272. map.addListener("dragend", function() {
  273. document.getElementById("currentMapCenter").value = map.getCenter().lat() + "," + map.getCenter().lng();
  274. document.getElementById("currentMapCenterSubmit").style.display = "block";
  275. });
  276. }
  277. function decodeLevels(encodedLevelsString) {
  278. var decodedLevels = [];
  279. for (var i = 0; i < encodedLevelsString.length; ++i) {
  280. var level = encodedLevelsString.charCodeAt(i) - 63;
  281. decodedLevels.push(level);
  282. }
  283. return decodedLevels;
  284. }
  285. initialize();
  286. </script></div>';
  287. return $map;
  288. }
  289. #
  290. # Attr command
  291. #########################################################################
  292. sub TRAFFIC_Attr(@){
  293. my ($cmd,$name,$attrName,$attrValue) = @_;
  294. # $cmd can be "del" or "set"
  295. # $name is device name
  296. my $hash = $defs{$name};
  297. if ($cmd eq "set") {
  298. addToDevAttrList($name, $attrName);
  299. Log3 $hash, 4, "TRAFFIC: ($name) attrName $attrName set to attrValue $attrValue";
  300. }
  301. if($attrName eq "disable" && $attrValue eq "1"){
  302. readingsSingleUpdate( $hash, "state", "disabled", 1 );
  303. }
  304. if($attrName eq "outputReadings" || $attrName eq "includeReturn" || $attrName eq "verbose"){
  305. #clear all readings
  306. foreach my $clearReading ( keys %{$hash->{READINGS}}){
  307. Log3 $hash, 5, "TRAFFIC: ($name) READING: $clearReading deleted";
  308. delete($hash->{READINGS}{$clearReading});
  309. }
  310. #clear all helpers
  311. foreach my $helperName ( keys %{$hash->{helper}}){
  312. delete($hash->{helper}{$helperName});
  313. }
  314. # start update
  315. InternalTimer(gettimeofday() + 1, "TRAFFIC_StartUpdate", $hash, 0);
  316. }
  317. return undef;
  318. }
  319. sub TRAFFIC_Set($@){
  320. my ($hash, @param) = @_;
  321. return "\"set <TRAFFIC>\" needs at least one argument: \n".join(" ",keys %TRcmds) if (int(@param) < 2);
  322. my $name = shift @param;
  323. my $set = shift @param;
  324. $hash->{VERSION} = $TRVersion if $hash->{VERSION} ne $TRVersion;
  325. if(AttrVal($name, "disable", 0 ) == 1){
  326. readingsSingleUpdate( $hash, "state", "disabled", 1 );
  327. Log3 $hash, 3, "TRAFFIC: ($name) is disabled, $set not set!";
  328. return undef;
  329. }else{
  330. Log3 $hash, 5, "TRAFFIC: ($name) set $name $set";
  331. }
  332. my $validCmds = join("|",keys %TRcmds);
  333. if($set !~ m/$validCmds/ ) {
  334. return join(' ', keys %TRcmds);
  335. }elsif($set =~ m/update/){
  336. Log3 $hash, 5, "TRAFFIC: ($name) update command recieved";
  337. # if update burst ist specified
  338. if( (my $burstCount = shift @param) && (my $burstInterval = shift @param)){
  339. Log3 $hash, 5, "TRAFFIC: ($name) update burst is set to $burstCount $burstInterval";
  340. $hash->{BURSTCOUNT} = $burstCount;
  341. $hash->{BURSTINTERVAL} = $burstInterval;
  342. }else{
  343. Log3 $hash, 5, "TRAFFIC: ($name) no update burst set";
  344. }
  345. # update internal timer and update NOW
  346. my $updateTrigger = gettimeofday() + 1;
  347. $hash->{TRIGGERTIME} = $updateTrigger;
  348. $hash->{TRIGGERTIME_FMT} = FmtDateTime($updateTrigger);
  349. RemoveInternalTimer($hash);
  350. # start update
  351. InternalTimer($updateTrigger, "TRAFFIC_StartUpdate", $hash, 0);
  352. return undef;
  353. }
  354. }
  355. sub TRAFFIC_StartUpdate($){
  356. my ( $hash ) = @_;
  357. my $name = $hash->{NAME};
  358. my ($sec,$min,$hour,$dayn,$month,$year,$wday,$yday,$isdst) = localtime(time);
  359. $wday=7 if $wday == 0; #sunday 0 -> sunday 7, monday 0 -> monday 1 ...
  360. if(AttrVal($name, "disable", 0 ) == 1){
  361. RemoveInternalTimer ($hash);
  362. Log3 $hash, 3, "TRAFFIC: ($name) is disabled";
  363. return undef;
  364. }
  365. if ( $hash->{INTERVAL}) {
  366. RemoveInternalTimer ($hash);
  367. delete($hash->{UPDATESCHEDULE});
  368. my $nextTrigger = gettimeofday() + $hash->{INTERVAL};
  369. if(defined(AttrVal($name, "updateSchedule", undef ))){
  370. Log3 $hash, 5, "TRAFFIC: ($name) flexible update Schedule defined";
  371. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  372. my @updateScheduleDef = split('\|', AttrVal($name, "updateSchedule", undef ));
  373. foreach my $upSched (@updateScheduleDef){
  374. my ($upFrom, $upTo, $upDay, $upInterval ) = $upSched =~ m/(\d+)-(\d+)\s(\d{1,})\s?(\d{1,})?/;
  375. if (!$upInterval){
  376. $upInterval = $upDay;
  377. $upDay='';
  378. }
  379. Log3 $hash, 5, "TRAFFIC: ($name) parsed schedule to upFrom $upFrom, upTo $upTo, upDay $upDay, upInterval $upInterval";
  380. if(!$upFrom || !$upTo || !$upInterval){
  381. Log3 $hash, 1, "TRAFIC: ($name) updateSchedule $upSched not defined correctly";
  382. }else{
  383. if($hour >= $upFrom && $hour < $upTo){
  384. if(!$upDay || $upDay == $wday ){
  385. $nextTrigger = gettimeofday() + $upInterval;
  386. Log3 $hash, 4, "TRAFFIC: ($name) schedule from $upFrom to $upTo (on day $upDay) every $upInterval seconds, matches (current hour $hour), nextTrigger set to $nextTrigger";
  387. $hash->{UPDATESCHEDULE} = $upSched;
  388. last;
  389. }else{
  390. Log3 $hash, 4, "TRAFFIC: ($name) $upSched does match the time but not the day ($wday)";
  391. }
  392. }else{
  393. Log3 $hash, 5, "TRAFFIC: ($name) schedule $upSched does not match ($hour)";
  394. }
  395. }
  396. }
  397. }
  398. if(defined($hash->{BURSTCOUNT}) && $hash->{BURSTCOUNT} > 0){
  399. $nextTrigger = gettimeofday() + $hash->{BURSTINTERVAL};
  400. Log3 $hash, 3, "TRAFFIC: ($name) next update defined by burst";
  401. $hash->{BURSTCOUNT}--;
  402. }elsif(defined($hash->{BURSTCOUNT}) && $hash->{BURSTCOUNT} == 0){
  403. delete($hash->{BURSTCOUNT});
  404. delete($hash->{BURSTINTERVAL});
  405. Log3 $hash, 4, "TRAFFIC: ($name) burst update is done";
  406. }
  407. $hash->{TRIGGERTIME} = $nextTrigger;
  408. $hash->{TRIGGERTIME_FMT} = FmtDateTime($nextTrigger);
  409. InternalTimer($nextTrigger, "TRAFFIC_StartUpdate", $hash, 0);
  410. Log3 $hash, 4, "TRAFFIC: ($name) internal interval timer set to call StartUpdate again at " . $hash->{TRIGGERTIME_FMT};
  411. }
  412. if(defined(AttrVal($name, "start_address", undef )) && defined(AttrVal($name, "end_address", undef ))){
  413. BlockingCall("TRAFFIC_DoUpdate",$hash->{NAME}.';;;normal',"TRAFFIC_FinishUpdate",60,"TRAFFIC_AbortUpdate",$hash);
  414. if(defined(AttrVal($name, "includeReturn", undef )) && AttrVal($name, "includeReturn", undef ) eq 1){
  415. BlockingCall("TRAFFIC_DoUpdate",$hash->{NAME}.';;;return',"TRAFFIC_FinishUpdate",60,"TRAFFIC_AbortUpdate",$hash);
  416. }
  417. }else{
  418. readingsSingleUpdate( $hash, "state", "incomplete configuration", 1 );
  419. Log3 $hash, 1, "TRAFFIC: ($name) is not configured correctly, please add start_address and end_address";
  420. }
  421. }
  422. sub TRAFFIC_AbortUpdate($){
  423. }
  424. sub TRAFFIC_DoUpdate(){
  425. my ($string) = @_;
  426. my ($hName, $direction) = split(";;;", $string); # direction is normal or return
  427. my $hash = $defs{$hName};
  428. my $dotrigger = 1;
  429. my $name = $hash->{NAME};
  430. my ($sec,$min,$hour,$dayn,$month,$year,$wday,$yday,$isdst) = localtime(time);
  431. Log3 $hash, 4, "TRAFFIC: ($name) TRAFFIC DoUpdate start";
  432. if ( $hash->{INTERVAL}) {
  433. RemoveInternalTimer ($hash);
  434. my $nextTrigger = gettimeofday() + $hash->{INTERVAL};
  435. $hash->{TRIGGERTIME} = $nextTrigger;
  436. $hash->{TRIGGERTIME_FMT} = FmtDateTime($nextTrigger);
  437. InternalTimer($nextTrigger, "TRAFFIC_StartUpdate", $hash, 0);
  438. Log3 $hash, 4, "TRAFFIC: ($name) internal interval timer set to call GetUpdate again in " . int($hash->{INTERVAL}). " seconds";
  439. }
  440. my $returnJSON;
  441. my $TRlanguage = '';
  442. if(defined(AttrVal($name,"language",undef))){
  443. $TRlanguage = '&language='.AttrVal($name,"language","");
  444. }else{
  445. Log3 $hash, 5, "TRAFFIC: ($name) no language specified";
  446. }
  447. my $TRwaypoints = '';
  448. if(defined(AttrVal($name,"waypoints",undef))){
  449. $TRwaypoints = '&waypoints=via:' . join('|via:', split('\|', AttrVal($name,"waypoints",undef)));
  450. }else{
  451. Log3 $hash, 4, "TRAFFIC: ($name) no waypoints specified";
  452. }
  453. if($direction eq "return"){
  454. if(defined(AttrVal($name,"returnWaypoints",undef))){
  455. $TRwaypoints = '&waypoints=via:' . join('|via:', split('\|', AttrVal($name,"returnWaypoints",undef)));
  456. Log3 $hash, 4, "TRAFFIC: ($name) using returnWaypoints";
  457. }elsif(defined(AttrVal($name,"waypoints",undef))){
  458. $TRwaypoints = '&waypoints=via:' . join('|via:', reverse split('\|', AttrVal($name,"waypoints",undef)));
  459. Log3 $hash, 4, "TRAFFIC: ($name) reversing waypoints";
  460. }else{
  461. Log3 $hash, 4, "TRAFFIC: ($name) no waypoints for return specified";
  462. }
  463. }
  464. my $origin = AttrVal($name, "start_address", 0 );
  465. my $destination = AttrVal($name, "end_address", 0 );
  466. my $travelMode = AttrVal($name, "travelMode", 'driving' );
  467. my $alternatives = 'false';
  468. $alternatives = 'true' if (AttrVal($name, "alternatives", undef ));
  469. if($direction eq "return"){
  470. $origin = AttrVal($name, "end_address", 0 );
  471. $destination = AttrVal($name, "start_address", 0 );
  472. $alternatives = 'false';
  473. }
  474. my $url = 'https://maps.googleapis.com/maps/api/directions/json?origin='.$origin.'&destination='.$destination.'&mode='.$travelMode.$TRlanguage.'&departure_time=now'.$TRwaypoints.'&key='.$hash->{APIKEY}.'&alternatives='.$alternatives;
  475. Log3 $hash, 4, "TRAFFIC: ($name) using $url";
  476. my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 } );
  477. $ua->default_header("HTTP_REFERER" => "www.google.de");
  478. my $body = $ua->get($url);
  479. # test json decode and catch error nicely
  480. eval {
  481. my $testJson = decode_json($body->decoded_content);
  482. 1;
  483. };
  484. if($@) {
  485. my $e = $@;
  486. Log3 $hash, 1, "TRAFFIC: ($name) decode_json on googles return failed, cant continue";
  487. Log3 $hash, 5, "TRAFFIC: ($name) received: ".Dumper($body->decoded_content);
  488. my %errorReturn = ('status' => 'API error','action' => 'retry');
  489. return "$name;;;$direction;;;".encode_json(\%errorReturn);
  490. };
  491. my $json = decode_json($body->decoded_content);
  492. my $duration_sec = $json->{'routes'}[0]->{'legs'}[0]->{'duration'}->{'value'} ;
  493. my $duration_in_traffic_sec = $json->{'routes'}[0]->{'legs'}[0]->{'duration_in_traffic'}->{'value'};
  494. $returnJSON->{'READINGS'}->{'duration'} = $json->{'routes'}[0]->{'legs'}[0]->{'duration'}->{'text'} if AttrVal($name, "outputReadings", "" ) =~ m/text/;
  495. $returnJSON->{'READINGS'}->{'duration_in_traffic'} = $json->{'routes'}[0]->{'legs'}[0]->{'duration_in_traffic'}->{'text'} if AttrVal($name, "outputReadings", "" ) =~ m/text/;
  496. $returnJSON->{'READINGS'}->{'distance'} = $json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'text'} if AttrVal($name, "outputReadings", "" ) =~ m/text/;
  497. $returnJSON->{'READINGS'}->{'state'} = $json->{'status'};
  498. $returnJSON->{'READINGS'}->{'status'} = $json->{'status'};
  499. $returnJSON->{'READINGS'}->{'eta'} = FmtTime( gettimeofday() + $duration_in_traffic_sec ) if defined($duration_in_traffic_sec);
  500. $returnJSON->{'READINGS'}->{'summary'} = $json->{'routes'}[0]->{'summary'};
  501. # handling alternatives
  502. $returnJSON->{'READINGS'}->{'alternatives'} = join( ", ", map { $_->{summary}.' - '.$_->{'legs'}[0]->{'duration_in_traffic'}->{'text'} } @{$json->{'routes'}} );
  503. $returnJSON->{'HELPER'}->{'Poly'} = encode_base64 (join(',', map{ $_->{overview_polyline}->{points} } @{$json->{'routes'}} ));
  504. $returnJSON->{'HELPER'}->{'GoogleMapsCenter'} = $json->{'routes'}[0]->{'legs'}[0]->{start_location}->{lat}.','.$json->{'routes'}[0]->{'legs'}[0]->{start_location}->{lng};
  505. if($duration_in_traffic_sec && $duration_sec){
  506. $returnJSON->{'READINGS'}->{'delay'} = prettySeconds($duration_in_traffic_sec - $duration_sec) if AttrVal($name, "outputReadings", "" ) =~ m/text/;
  507. Log3 $hash, 4, "TRAFFIC: ($name) delay in seconds = $duration_in_traffic_sec - $duration_sec";
  508. if (AttrVal($name, "outputReadings", "" ) =~ m/min/ && defined($duration_in_traffic_sec) && defined($duration_sec)){
  509. $returnJSON->{'READINGS'}->{'delay_min'} = int($duration_in_traffic_sec - $duration_sec);
  510. }
  511. if(defined($returnJSON->{'READINGS'}->{'delay_min'})){
  512. if( ( $returnJSON->{'READINGS'}->{'delay_min'} && $returnJSON->{'READINGS'}->{'delay_min'} =~ m/^-/ ) || $returnJSON->{'READINGS'}->{'delay_min'} < 60){
  513. Log3 $hash, 5, "TRAFFIC: ($name) delay_min was negative or less than 1min (".$returnJSON->{'READINGS'}->{'delay_min'}."), set to 0";
  514. $returnJSON->{'READINGS'}->{'delay_min'} = 0;
  515. }else{
  516. $returnJSON->{'READINGS'}->{'delay_min'} = int($returnJSON->{'READINGS'}->{'delay_min'} / 60 + 0.5); #divide 60 and round
  517. }
  518. }
  519. }else{
  520. Log3 $hash, 1, "TRAFFIC: ($name) did not receive duration_in_traffic, not able to calculate delay";
  521. }
  522. # condition based values
  523. $returnJSON->{'READINGS'}->{'error_message'} = $json->{'error_message'} if $json->{'error_message'};
  524. # output readings
  525. $returnJSON->{'READINGS'}->{'duration_min'} = int($duration_sec / 60 + 0.5) if AttrVal($name, "outputReadings", "" ) =~ m/min/ && defined($duration_sec);
  526. $returnJSON->{'READINGS'}->{'duration_in_traffic_min'} = int($duration_in_traffic_sec / 60 + 0.5) if AttrVal($name, "outputReadings", "" ) =~ m/min/ && defined($duration_in_traffic_sec);
  527. $returnJSON->{'READINGS'}->{'duration_sec'} = $duration_sec if AttrVal($name, "outputReadings", "" ) =~ m/sec/;
  528. $returnJSON->{'READINGS'}->{'duration_in_traffic_sec'} = $duration_in_traffic_sec if AttrVal($name, "outputReadings", "" ) =~ m/sec/;
  529. # raw data (seconds)
  530. $returnJSON->{'READINGS'}->{'distance'} = $json->{'routes'}[0]->{'legs'}[0]->{'distance'}->{'value'} if AttrVal($name, "raw_data", 0);
  531. # average readings
  532. if(AttrVal($name, "outputReadings", "" ) =~ m/average/){
  533. # calc average
  534. $returnJSON->{'READINGS'}->{'average_duration_min'} = int($hash->{READINGS}{'average_duration_min'}{VAL} + $returnJSON->{'READINGS'}->{'duration_min'}) / 2 if $returnJSON->{'READINGS'}->{'duration_min'};
  535. $returnJSON->{'READINGS'}->{'average_duration_in_traffic_min'} = int($hash->{READINGS}{'average_duration_in_traffic_min'}{VAL} + $returnJSON->{'READINGS'}->{'duration_in_traffic_min'}) / 2 if $returnJSON->{'READINGS'}->{'duration_in_traffic_min'};
  536. $returnJSON->{'READINGS'}->{'average_delay_min'} = int($hash->{READINGS}{'average_delay_min'}{VAL} + $returnJSON->{'READINGS'}->{'delay_min'}) / 2 if $returnJSON->{'READINGS'}->{'delay_min'};
  537. # override if this is the first average
  538. $returnJSON->{'READINGS'}->{'average_duration_min'} = $returnJSON->{'READINGS'}->{'duration_min'} if !$hash->{READINGS}{'average_duration_min'}{VAL};
  539. $returnJSON->{'READINGS'}->{'average_duration_in_traffic_min'} = $returnJSON->{'READINGS'}->{'duration_in_traffic_min'} if !$hash->{READINGS}{'average_duration_in_traffic_min'}{VAL};
  540. $returnJSON->{'READINGS'}->{'average_delay_min'} = $returnJSON->{'READINGS'}->{'delay_min'} if !$hash->{READINGS}{'average_delay_min'}{VAL};
  541. }
  542. Log3 $hash, 5, "TRAFFIC: ($name) returning from TRAFFIC DoUpdate: ".encode_json($returnJSON);
  543. Log3 $hash, 4, "TRAFFIC: ($name) TRAFFIC DoUpdate done";
  544. return "$name;;;$direction;;;".encode_json($returnJSON);
  545. }
  546. sub TRAFFIC_FinishUpdate($){
  547. my ($name,$direction,$rawJson) = split(/;;;/,shift);
  548. my $hash = $defs{$name};
  549. my %sensors;
  550. my $dotrigger = 1;
  551. my $json = decode_json($rawJson);
  552. # before we update anything, check if the status contains error, if yes -> retry
  553. if(defined($json->{'status'}) && $json->{'status'} =~ m/error/i){ # this handles potential JSON decode issues and retries
  554. if ($json->{'action'} eq 'retry'){
  555. Log3 $hash, 1, "TRAFFIC: ($name) TRAFFIC doUpdate returned an error \"".$json->{'status'}. "\" will schedule a retry in 5 seconds";
  556. RemoveInternalTimer ($hash);
  557. my $nextTrigger = gettimeofday() + 5;
  558. $hash->{TRIGGERTIME} = $nextTrigger;
  559. $hash->{TRIGGERTIME_FMT} = FmtDateTime($nextTrigger);
  560. InternalTimer($nextTrigger, "TRAFFIC_StartUpdate", $hash, 0);
  561. }else{
  562. Log3 $hash, 1, "TRAFFIC: ($name) TRAFFIC doUpdate returned an error: ".$json->{'status'};
  563. }
  564. }else{ #JSON decode did not return an error, lets update the device
  565. Log3 $hash, 4, "TRAFFIC: ($name) TRAFFIC_FinishUpdate start";
  566. readingsBeginUpdate($hash);
  567. my $readings = $json->{'READINGS'};
  568. my $helper = $json->{'HELPER'};
  569. foreach my $helperName (keys %{$helper}){
  570. if($direction eq 'return'){
  571. Log3 $hash, 4, "TRAFFIC: ($name) HelperUpdate: return_".$helperName." - ".$helper->{$helperName};
  572. $hash->{helper}{'return_'.$helperName} = $helper->{$helperName}; #testme
  573. }else{
  574. Log3 $hash, 4, "TRAFFIC: ($name) HelperUpdate: $helperName - ".$helper->{$helperName};
  575. $hash->{helper}{$helperName} = $helper->{$helperName}; #testme
  576. }
  577. }
  578. foreach my $readingName (keys %{$readings}){
  579. Log3 $hash, 4, "TRAFFIC: ($name) ReadingsUpdate: $readingName - ".$readings->{$readingName};
  580. if($direction eq 'return'){
  581. readingsBulkUpdate($hash,'return_'.$readingName,$readings->{$readingName});
  582. }else{
  583. readingsBulkUpdate($hash,$readingName,$readings->{$readingName});
  584. }
  585. }
  586. if(my $stateReading = AttrVal($name,"stateReading",undef)){
  587. Log3 $hash, 5, "TRAFFIC: ($name) stateReading defined, override state";
  588. if(defined($json->{'READINGS'}->{$stateReading})){
  589. readingsBulkUpdate($hash,'state',$json->{'READINGS'}->{$stateReading});
  590. }else{
  591. Log3 $hash, 1, "TRAFFIC: ($name) stateReading $stateReading not found";
  592. }
  593. }
  594. # if Google returned an error, we gonna try again in 3 seconds
  595. if(defined($json->{'READINGS'}->{'status'}) && $json->{'READINGS'}->{'status'} =~ m/error/i){ # UNKNOWN_ERROR indicates a directions request could not be processed due to a server error. The request may succeed if you try again.
  596. Log3 $hash, 1, "TRAFFIC: ($name) auto-retry as Google returned an error: ".$json->{'READINGS'}->{'status'};
  597. InternalTimer(gettimeofday() + 3, "TRAFFIC_StartUpdate", $hash, 0);
  598. }elsif(defined($hash->{READINGS}->{'error_message'})){
  599. Log3 $hash, 3, "TRAFFIC: ($name) removing reading error_message, status: ".$json->{'READINGS'}->{'status'};
  600. fhem("deletereading $name error_message");
  601. }
  602. readingsEndUpdate($hash, $dotrigger);
  603. Log3 $hash, 4, "TRAFFIC: ($name) TRAFFIC_FinishUpdate done";
  604. Log3 $hash, 5, "TRAFFIC: ($name) Helper: ".Dumper($hash->{helper});
  605. }# not an error
  606. }
  607. sub TRAFFIC_weblink{
  608. my $name = shift();
  609. return "<a href='$FW_ME/TRAFFIC?name=$name'>$FW_ME/TRAFFIC?name=$name</a><br>";
  610. }
  611. sub TRAFFIC(){
  612. my $name = $FW_webArgs{name};
  613. return if(!defined($name));
  614. $FW_RETTYPE = "text/html; charset=UTF-8";
  615. $FW_RET="";
  616. my $web .= TRAFFIC_GetMap($name);
  617. FW_pO $web;
  618. return ($FW_RETTYPE, $FW_RET);
  619. }
  620. sub TRAFFIC_DbLog_split($) {
  621. my ($event, $device) = @_;
  622. my $hash = $defs{$device};
  623. Log3 $hash, 5, "TRAFFIC: ($device) TRAFFIC_DbLog_split received event $event on device $device";
  624. my $readings; # this holds all possible readings and their units
  625. $readings->{'update'} = 'text';
  626. $readings->{'duration'} = 'text';
  627. $readings->{'duration_in_traffic'} = 'text';
  628. $readings->{'distance'} = 'text';
  629. $readings->{'state'} = 'text';
  630. $readings->{'status'} = 'text';
  631. $readings->{'eta'} = 'time';
  632. $readings->{'summary'} = 'text';
  633. $readings->{'alternatives'} = 'text';
  634. $readings->{'delay'} = 'text';
  635. $readings->{'delay_min'} = 'min';
  636. $readings->{'error_message'} = 'text';
  637. $readings->{'duration_min'} = 'min';
  638. $readings->{'duration_in_traffic_min'} = 'min';
  639. $readings->{'duration_sec'} = 'sec';
  640. $readings->{'duration_in_traffic_sec'} = 'sec';
  641. $readings->{'distance'} = 'km';
  642. $readings->{'average_duration_min'} = 'min';
  643. $readings->{'average_duration_in_traffic_min'} = 'min';
  644. $readings->{'average_delay_min'} = 'min';
  645. $readings->{'average_duration_min'} = 'min';
  646. $readings->{'average_duration_in_traffic_min'} = 'min';
  647. $readings->{'average_delay_min'} = 'min';
  648. my ($reading, $value, $unit) = "";
  649. my @parts = split(/ /,$event);
  650. $reading = shift @parts;
  651. $reading =~ tr/://d;
  652. my $alternativeReading = $reading;
  653. $alternativeReading =~ s/^return_//;
  654. $value = join(" ",@parts);
  655. if($readings->{$reading}){
  656. $unit = $readings->{$reading};
  657. $value =~ s/$unit$//; #try to remove the unit from the value
  658. }elsif($readings->{$alternativeReading}){
  659. $unit = $readings->{$alternativeReading};
  660. $value =~ s/$unit$//; #try to remove the unit from the value
  661. }else{
  662. Log3 $hash, 5, "TRAFFIC: ($device) TRAFFIC_DbLog_split auto detect unit for reading $reading value $value";
  663. $unit = 'min' if ($reading) =~ m/_min$/;
  664. $unit = 'sec' if ($reading) =~ m/_sec$/;
  665. $unit = 'km' if ($reading) =~ m/_km$/;
  666. }
  667. Log3 $hash, 5, "TRAFFIC: ($device) TRAFFIC_DbLog_split returning $reading, $value, $unit";
  668. return ($reading, $value, $unit);
  669. }
  670. sub prettySeconds {
  671. my $time = shift;
  672. if($time =~ m/^-/){
  673. return "0 min";
  674. }
  675. my $days = int($time / 86400);
  676. $time -= ($days * 86400);
  677. my $hours = int($time / 3600);
  678. $time -= ($hours * 3600);
  679. my $minutes = int($time / 60);
  680. my $seconds = $time % 60;
  681. $days = $days < 1 ? '' : $days .' days ';
  682. $hours = $hours < 1 ? '' : $hours .' hours ';
  683. $minutes = $minutes < 1 ? '' : $minutes . ' min ';
  684. $time = $days . $hours . $minutes;
  685. if(!$time){
  686. return "0 min";
  687. }else{
  688. return $time;
  689. }
  690. }
  691. sub minHex{ $_[0]<$_[1] ? $_[0] : $_[1] }
  692. sub degradeHex{
  693. my ($rgb, $degr) = (hex(shift), pop);
  694. $rgb -= minHex( $rgb&(0xff<<$_), $degr<<$_ ) for (0,8,16);
  695. return '%06x', $rgb;
  696. }
  697. sub lightHex {
  698. $_[0] =~ s/#//g;
  699. return sprintf '%02x'x3,
  700. map{ ($_ *= 1+$_[1]) > 0xff ? 0xff : $_ }
  701. map hex, unpack 'A2'x3, $_[0];
  702. }
  703. 1;
  704. #======================================================================
  705. #======================================================================
  706. #
  707. # HTML Documentation for help and commandref
  708. #
  709. #======================================================================
  710. #======================================================================
  711. =pod
  712. =item device
  713. =item summary provide traffic details with Google Distance API
  714. =item summary_DE stellt Verkehrsdaten mittels Google Distance API bereit
  715. =begin html
  716. <a name="TRAFFIC"></a>
  717. <h3>TRAFFIC</h3>
  718. <ul>
  719. <u><b>TRAFFIC - google maps directions module</b></u>
  720. <br>
  721. <br>
  722. This FHEM module collects and displays data obtained via the google maps directions api<br>
  723. requirements:<br>
  724. perl JSON module<br>
  725. perl LWP::SIMPLE module<br>
  726. perl MIME::Base64 module<br>
  727. Google maps API key<br>
  728. <br>
  729. <b>Features:</b>
  730. <br>
  731. <ul>
  732. <li>get distance between start and end location</li>
  733. <li>get travel time for route</li>
  734. <li>get travel time in traffic for route</li>
  735. <li>define additional waypoints</li>
  736. <li>calculate delay between travel-time and travel-time-in-traffic</li>
  737. <li>choose default language</li>
  738. <li>disable the device</li>
  739. <li>5 log levels</li>
  740. <li>get outputs in seconds / meter (raw_data)</li>
  741. <li>state of google maps returned in error reading (i.e. The provided API key is invalid)</li>
  742. <li>customize update interval (default 3600 seconds)</li>
  743. <li>calculate ETA with localtime and delay</li>
  744. <li>configure the output readings with attribute outputReadings, text, min sec</li>
  745. <li>configure the state-reading </li>
  746. <li>optionally display the same route in return</li>
  747. <li>one-time-burst, specify the amount and interval between updates</li>
  748. <li>different Travel Modes (driving, walking, bicycling and transit)</li>
  749. <li>flexible update schedule</li>
  750. <li>integrated Map to visualize configured route or embed to external GUI</li>
  751. </ul>
  752. <br>
  753. <br>
  754. <a name="TRAFFICdefine"></a>
  755. <b>Define:</b>
  756. <ul><br>
  757. <code>define &lt;name&gt; TRAFFIC &lt;YOUR-API-KEY&gt; [UPDATE-INTERVAL]</code>
  758. <br><br>
  759. example:<br>
  760. <code>define muc2berlin TRAFFIC ABCDEFGHIJKLMNOPQRSTVWYZ 600</code><br>
  761. </ul>
  762. <br>
  763. <br>
  764. <b>Attributes:</b>
  765. <ul>
  766. <li>"start_address" - Street, zipcode City <b>(mandatory)</b></li>
  767. <li>"end_address" - Street, zipcode City <b>(mandatory)</b></li>
  768. <li>"raw_data" - 0:1</li>
  769. <li>"alternatives" - 0:1, include alternative routes into readings and Map</li>
  770. <li>"language" - de, en etc.</li>
  771. <li>"waypoints" - Lat, Long coordinates, separated by | </li>
  772. <li>"returnWaypoints" - Lat, Long coordinates, separated by | </li>
  773. <li>"disable" - 0:1</li>
  774. <li>"stateReading" - name the reading which will be used in device state</li>
  775. <li>"outputReadings" - define what kind of readings you want to get: text, min, sec, average</li>
  776. <li>"updateSchedule" - define a flexible update schedule, syntax &lt;starthour&gt;-&lt;endhour&gt; [&lt;day&gt;] &lt;seconds&gt; , multiple entries by sparated by |<br> <i>example:</i> 7-9 1 120 - Monday between 7 and 9 every 2minutes <br> <i>example:</i> 17-19 120 - every Day between 17 and 19 every 2minutes <br> <i>example:</i> 6-8 1 60|6-8 2 60|6-8 3 60|6-8 4 60|6-8 5 60 - Monday till Friday, 60 seconds between 6 and 8 am</li>
  777. <li>"travelMode" - default: driving, options walking, bicycling or transit </li>
  778. <li>"GoogleMapsStyle" - choose your colors from: default,silver,dark,night</li>
  779. <li>"GoogleMapsSize" - Map size in pixel, &lt;width&gt;,&lt;height&gt;</li>
  780. <li>"GoogleMapsCenter" - Lat, Long coordinates of your map center, spearated by ,</li>
  781. <li>"GoogleMapsZoom" - sets your map zoom level</li>
  782. <li>"GoogleMapsStroke" - customize your map poly-strokes in color, weight and opacity <br> &lt;hex-color-code&gt;,[stroke-weight],[stroke-opacity],&lt;hex-color-code-of-return&gt;,[stroke-weight-of-return],[stroke-opacity-of-return]<br>must beginn with #color of each stroke, weight and opacity is optional<br><i>example:</i> #019cdf,#ffeb19<br><i>example:</i> #019cdf,20,#ffeb19<br><i>example:</i> #019cdf,20,#ffeb19,15<br><i>example:</i> #019cdf,#ffeb19,15<br><i>example:</i> #019cdf,20,80,#ffeb19<br><i>example:</i> #019cdf,#ffeb19,15,50<br><i>example:</i> #019cdf,20,80<br><i>default:</i> #4cde44,6,100,#FF0000,1,100</li>
  783. <li>"GoogleMapsTrafficLayer" - enable the basic Google Maps Traffic Layer</li>
  784. <li>"GoogleMapsDisableUI" - hide the map controls</li>
  785. </ul>
  786. <br>
  787. <br>
  788. <a name="TRAFFICreadings"></a>
  789. <b>Readings:</b>
  790. <ul>
  791. <li>alternatives</li>
  792. <li>delay</li>
  793. <li>delay_min</li>
  794. <li>distance</li>
  795. <li>duration</li>
  796. <li>duration_in_traffic</li>
  797. <li>duration_in_traffic_min</li>
  798. <li>duration_min</li>
  799. <li>error_message</li>
  800. <li>eta</li>
  801. <li>state</li>
  802. <li>summary</li>
  803. </ul>
  804. <br><br>
  805. <a name="TRAFFICset"></a>
  806. <b>Set</b>
  807. <ul>
  808. <li>update [burst-update-count] [burst-update-interval] - update readings manually</li>
  809. </ul>
  810. <br><br>
  811. </ul>
  812. =end html
  813. =cut