98_geodata.pm 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # $Id: 98_geodata.pm 5089 2014-03-01 21:06:35Z betateilchen $
  2. package main;
  3. use strict;
  4. use warnings;
  5. use Time::HiRes qw(gettimeofday);
  6. use feature qw/say switch/;
  7. require XML::Simple;
  8. require LWP::UserAgent;
  9. use Data::Dumper;
  10. sub geodata_Initialize($){
  11. my ($hash) = @_;
  12. $hash->{DefFn} = "geodata_Define";
  13. $hash->{UndefFn} = "geodata_Undefine";
  14. $hash->{AttrFn} = "geodata_Attr";
  15. $hash->{ShutdownFn} = "geodata_Shutdown";
  16. $hash->{AttrList} = "geo_wuApiKey geo_googleApiKey ".
  17. "geo_language:de,en geo_owoGetUrl ".
  18. $readingFnAttributes;
  19. }
  20. sub geodata_Define($$){
  21. my ($hash, $def) = @_;
  22. my $name = $hash->{NAME};
  23. my @a = split("[ \t][ \t]*", $def);
  24. return 'usage: define <name> geodata <latitude> <longitude> <altitude>' if @a < 4;
  25. Log3($name, 4, 'Setting global attributes lat/lon/alt');
  26. $attr{global}{latitude} = $a[2];
  27. $attr{global}{longitude} = $a[3];
  28. # $attr{global}{altitude} = $a[4];
  29. Log3($name, 4, 'Updating readings lat/lon/alt/state');
  30. readingsBeginUpdate($hash);
  31. readingsBulkUpdate($hash, 'latitude', $a[2]);
  32. readingsBulkUpdate($hash, 'longitude', $a[3]);
  33. # readingsBulkUpdate($hash, 'altitude', $a[4]);
  34. readingsBulkUpdate($hash, 'state', 'defined');
  35. readingsEndUpdate($hash,1);
  36. geodata_collectData($hash);
  37. return;
  38. }
  39. sub geodata_Undefine($$){
  40. my($hash, $name) = @_;
  41. RemoveInternalTimer($hash);
  42. return;
  43. }
  44. sub geodata_Attr($){
  45. my @a = @_;
  46. my $hash = $defs{$a[1]};
  47. my (undef, $name, $attrName, $attrValue) = @a;
  48. given($attrName){
  49. when("geo_googleApiKey"){
  50. $attr{$name}{$attrName} = $attrValue;
  51. geodata_collectData($hash);
  52. break;
  53. }
  54. when("geo_wuApiKey"){
  55. $attr{$name}{$attrName} = $attrValue;
  56. geodata_collectData($hash);
  57. break;
  58. }
  59. default {
  60. $attr{$name}{$attrName} = $attrValue;
  61. }
  62. }
  63. return "";
  64. return;
  65. }
  66. sub geodata_Shutdown($) {
  67. my ($hash) = @_;
  68. my $name = $hash->{NAME};
  69. Log3 ($name,4,"geodata $name: shutdown requested");
  70. return undef;
  71. }
  72. sub geodata_collectData($){
  73. my ($hash) = @_;
  74. my $name = $hash->{NAME};
  75. my $ua = LWP::UserAgent->new;
  76. $ua->timeout(10); # test
  77. $ua->env_proxy;
  78. _geodata_owoInfo($hash, $ua);
  79. my $apiKey;
  80. $apiKey = AttrVal($name, 'geo_wuApiKey', undef);
  81. _wu_geolookup($hash, $ua, $apiKey) if(defined($apiKey));
  82. $apiKey = AttrVal($name, 'geo_googleApiKey', undef);
  83. _geodata_googledata($hash, $ua, $apiKey) if(defined($apiKey));
  84. InternalTimer(gettimeofday()+3600, "geodata_collectData", $hash, 0);
  85. return;
  86. }
  87. sub _wu_geolookup($$$) {
  88. my ($hash, $ua, $wuapikey) = @_;
  89. my $name = $hash->{NAME};
  90. my $lat = ReadingsVal($name, 'latitude', '');
  91. my $lon = ReadingsVal($name, 'longitude', '');
  92. my $geolookupUrl = "http://api.wunderground.com/api/$wuapikey/geolookup/q/$lat,$lon.xml";
  93. my $xml = new XML::Simple;
  94. my ($response, $htmldata, $query, $dummy);
  95. #----------------------------------------------------------
  96. # retrieving: geolookup data
  97. #
  98. eval {$response = $ua->get("$geolookupUrl")};
  99. ## ToDo: errorhandling
  100. $htmldata = $xml->XMLin($response->decoded_content, KeyAttr => '' );
  101. $dummy = $htmldata->{location}{country};
  102. $query = "/lang:$dummy".$htmldata->{location}{l};
  103. $hash->{HELPER}{WUQUERY} = $query;
  104. readingsBeginUpdate($hash);
  105. readingsBulkUpdate($hash, 'wuTerms', $htmldata->{termsofService});
  106. readingsBulkUpdate($hash, 'wuVersion', $htmldata->{version});
  107. readingsBulkUpdate($hash, 'nextAirportCity', $htmldata->{location}{nearby_weather_stations}{airport}{station}[0]{city});
  108. readingsBulkUpdate($hash, 'nextAirportICAO', $htmldata->{location}{nearby_weather_stations}{airport}{station}[0]{icao});
  109. #----------------------------------------------------------
  110. # retrieving astronomy data
  111. #
  112. $geolookupUrl = "http://api.wunderground.com/api/$wuapikey/astronomy/$query.xml";
  113. eval {$response = $ua->get("$geolookupUrl")};
  114. ## ToDo: errorhandling
  115. $htmldata = $xml->XMLin($response->decoded_content, KeyAttr => '' );
  116. $dummy = $htmldata->{sun_phase}{sunrise}{hour}.':'.$htmldata->{sun_phase}{sunrise}{minute};
  117. readingsBulkUpdate($hash, 'sunrise', $dummy);
  118. $dummy = $htmldata->{sun_phase}{sunset}{hour}.':'.$htmldata->{sun_phase}{sunset}{minute};
  119. readingsBulkUpdate($hash, 'sunset', $dummy);
  120. readingsBulkUpdate($hash, 'moon_phase', $htmldata->{moon_phase}{percentIlluminated});
  121. readingsBulkUpdate($hash, 'moon_age_days', $htmldata->{moon_phase}{ageOfMoon});
  122. #----------------------------------------------------------
  123. # retrieving conditions data
  124. #
  125. $geolookupUrl = "http://api.wunderground.com/api/$wuapikey/conditions/$query.xml";
  126. eval {$response = $ua->get("$geolookupUrl")};
  127. ## ToDo: errorhandling
  128. $htmldata = $xml->XMLin($response->decoded_content, KeyAttr => '' );
  129. $dummy = sprintf("%.0f", $htmldata->{current_observation}{display_location}{elevation});
  130. readingsBulkUpdate($hash, 'altitude', $dummy);
  131. readingsBulkUpdate($hash, 'city', $htmldata->{current_observation}{display_location}{city});
  132. readingsBulkUpdate($hash, 'country', $htmldata->{current_observation}{display_location}{country});
  133. readingsBulkUpdate($hash, 'country_iso', $htmldata->{current_observation}{display_location}{country_iso3166});
  134. readingsBulkUpdate($hash, 'country_name', $htmldata->{current_observation}{display_location}{state_name});
  135. readingsBulkUpdate($hash, 'observation', $htmldata->{current_observation}{observation_epoch});
  136. readingsBulkUpdate($hash, 'tz_long', $htmldata->{current_observation}{local_tz_long});
  137. readingsBulkUpdate($hash, 'tz_offset', $htmldata->{current_observation}{local_tz_offset});
  138. readingsBulkUpdate($hash, 'tz_short', $htmldata->{current_observation}{local_tz_short});
  139. $dummy = $htmldata->{current_observation}{display_location}{zip};
  140. readingsBulkUpdate($hash, 'zip', $dummy) if $dummy ne '00000';
  141. #Debug(Dumper($htmldata));
  142. readingsBulkUpdate($hash, 'state', 'active');
  143. readingsEndUpdate($hash, 1);
  144. return;
  145. }
  146. sub _geodata_googledata($$$) {
  147. my ($hash, $ua, $apiKey) = @_;
  148. my $name = $hash->{NAME};
  149. if(!defined($apiKey)) {
  150. Log3($name, 2, 'Api key for elevation not found!');
  151. return;
  152. }
  153. my $urlString = AttrVal($name, 'geo_elevationUrl','https://maps.googleapis.com/maps/api/elevation/xml');
  154. my $lat = ReadingsVal($name, 'latitude', '');
  155. my $lon = ReadingsVal($name, 'longitude', '');
  156. my $xml = new XML::Simple;
  157. my ($response, $owodata, $dummy);
  158. my $urlString2 = "?sensor=false&locations=$lat,$lon&key=$apiKey";
  159. $urlString .= $urlString2;
  160. eval {$response = $ua->get("$urlString")};
  161. readingsBeginUpdate($hash);
  162. $owodata = $xml->XMLin($response->decoded_content, KeyAttr => 'result' );
  163. $dummy = $owodata->{result}{elevation};
  164. $dummy = sprintf("%.0f", $dummy);
  165. readingsBulkUpdate($hash, 'altitude', $dummy);
  166. $attr{global}{altitude} = $dummy;
  167. $urlString = AttrVal($name, 'geo_timezoneUrl', 'https://maps.googleapis.com/maps/api/timezone/xml');
  168. $urlString2 = "?sensor=false&location=$lat,$lon&key=$apiKey&timestamp=".time;
  169. $urlString2 .= "&language=".AttrVal($name, 'geo_language', 'en');
  170. $urlString .= $urlString2;
  171. eval {$response = $ua->get("$urlString")};
  172. $owodata = $xml->XMLin($response->decoded_content, KeyAttr => '' );
  173. readingsBulkUpdate($hash, 'timeZoneId', $owodata->{time_zone_id});
  174. readingsBulkUpdate($hash, 'dstOffset', $owodata->{dst_offset});
  175. readingsBulkUpdate($hash, 'timeZoneName', latin1ToUtf8($owodata->{time_zone_name}));
  176. readingsBulkUpdate($hash, 'rawOffset', $owodata->{raw_offset});
  177. readingsEndUpdate($hash, 1);
  178. return;
  179. }
  180. sub _geodata_owoInfo($$){
  181. my ($hash,$ua) = @_;
  182. my $name = $hash->{NAME};
  183. my $urlString = AttrVal($name, "geo_owoGetUrl", "http://api.openweathermap.org/data/2.5/weather");
  184. my $lat = ReadingsVal($name, 'latitude', '');
  185. my $lon = ReadingsVal($name, 'longitude', '');
  186. my $xml = new XML::Simple;
  187. my ($response, $owodata, $dummy);
  188. $urlString .= "?lat=$lat&lon=$lon&mode=xml";
  189. eval {$response = $ua->get("$urlString")};
  190. #
  191. # error handling for not found stations (error 404 from server)
  192. #
  193. # if($response->decoded_content =~ m/error/i){ do errorhandling}
  194. $owodata = $xml->XMLin($response->decoded_content, KeyAttr => 'current' );
  195. if(defined($owodata)){
  196. (undef, $dummy) = split(/T/, $owodata->{city}{sun}{rise});
  197. readingsBeginUpdate($hash);
  198. readingsBulkUpdate($hash, "sunriseToday", $dummy); # $owodata->{city}{sun}{rise});
  199. (undef, $dummy) = split(/T/, $owodata->{city}{sun}{set});
  200. readingsBulkUpdate($hash, "sunsetToday", $dummy); #$owodata->{city}{sun}{set});
  201. readingsBulkUpdate($hash, "country", $owodata->{city}{country});
  202. readingsBulkUpdate($hash, "state", "active");
  203. readingsEndUpdate($hash, 1);
  204. }
  205. return;
  206. }
  207. 1;
  208. # $attr{$name}{geo_owoGetUrl} = "http://api.openweathermap.org/data/2.5/weather";
  209. =pod
  210. =begin html
  211. <a name="geodata"></a>
  212. <h3>geodata</h3>
  213. <ul>
  214. Collect some location based data from various internet sources.<br/>
  215. Data will be updated once an hour.<br/>
  216. <br/><ul>
  217. <li><b>openweathermap</b> will always be used.</li>
  218. <li><b>wunderground api</b> will be used, if wunderground api key is provided by attribute.</li>
  219. <li><b>google api</b> will be used, if google api key is provided by attribute.<br/>
  220. Currently google's elevation api and timezone api are used, so check access to those apis for your api key.</li>
  221. </ul>
  222. <br/>
  223. <a name="geodatadefine"></a>
  224. <b>Define</b><br/>
  225. <br/>
  226. <ul><code>define &lt;location&gt; latitude longitude</code><br/></ul>
  227. <br/>
  228. <a name="geodataset"></a>
  229. <b>Set</b>
  230. <ul>n/a</ul><br/>
  231. <br/>
  232. <a name="geodataget"></a>
  233. <b>Get</b>
  234. <ul>n/a</ul><br/>
  235. <br/>
  236. <a name="geodataattr"></a>
  237. <b>Attributes</b><br/>
  238. <br/>
  239. <ul>
  240. <li><b>geo_owoGetUrl</b> - used to correct owo api url manually, normally not needed.</li>
  241. <li><b>geo_wuApiKey</b> - enter your wunderground api key to access wunderground data.</li>
  242. <li><b>geo_googleApiKey</b> - enter your google api key to access google api.</li>
  243. <li><b>geo_language:de,en</b> - select language to be used if supported by api.</li>
  244. </ul><br/>
  245. <br/>
  246. </ul>
  247. =end html