46_TeslaPowerwall2AC.pm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. ###############################################################################
  2. #
  3. # Developed with Kate
  4. #
  5. # (c) 2017 Copyright: Marko Oldenburg (leongaultier at gmail dot com)
  6. # All rights reserved
  7. #
  8. # This script is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # any later version.
  12. #
  13. # The GNU General Public License can be found at
  14. # http://www.gnu.org/copyleft/gpl.html.
  15. # A copy is found in the textfile GPL.txt and important notices to the license
  16. # from the author is found in LICENSE.txt distributed with these scripts.
  17. #
  18. # This script is distributed in the hope that it will be useful,
  19. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. # GNU General Public License for more details.
  22. #
  23. #
  24. # $Id: 46_TeslaPowerwall2AC.pm 15311 2017-10-23 19:53:19Z CoolTux $
  25. #
  26. ###############################################################################
  27. ##
  28. ##
  29. ## Das JSON Modul immer in einem eval aufrufen
  30. # $data = eval{decode_json($data)};
  31. #
  32. # if($@){
  33. # Log3($SELF, 2, "$TYPE ($SELF) - error while request: $@");
  34. #
  35. # readingsSingleUpdate($hash, "state", "error", 1);
  36. #
  37. # return;
  38. # }
  39. #
  40. #######
  41. #######
  42. # URLs zum Abrufen diverser Daten
  43. # http://<ip-Powerwall>/api/system_status/soe
  44. # http://<ip-Powerwall>/api/meters/aggregates
  45. # http://<ip-Powerwall>/api/site_info
  46. # http://<ip-Powerwall>/api/sitemaster
  47. # http://<ip-Powerwall>/api/powerwalls
  48. # http://<ip-Powerwall>/api/networks
  49. # http://<ip-Powerwall>/api/system/networks
  50. # http://<ip-Powerwall>/api/operation
  51. #
  52. ##
  53. ##
  54. package main;
  55. my $missingModul = "";
  56. use strict;
  57. use warnings;
  58. use HttpUtils;
  59. eval "use JSON;1" or $missingModul .= "JSON ";
  60. my $version = "0.2.3";
  61. # Declare functions
  62. sub TeslaPowerwall2AC_Attr(@);
  63. sub TeslaPowerwall2AC_Define($$);
  64. sub TeslaPowerwall2AC_Initialize($);
  65. sub TeslaPowerwall2AC_Get($@);
  66. sub TeslaPowerwall2AC_Notify($$);
  67. sub TeslaPowerwall2AC_GetData($);
  68. sub TeslaPowerwall2AC_Undef($$);
  69. sub TeslaPowerwall2AC_ResponseProcessing($$$);
  70. sub TeslaPowerwall2AC_ReadingsProcessing_Aggregates($$);
  71. sub TeslaPowerwall2AC_ReadingsProcessing_Powerwalls($$);
  72. sub TeslaPowerwall2AC_ErrorHandling($$$);
  73. sub TeslaPowerwall2AC_WriteReadings($$$);
  74. sub TeslaPowerwall2AC_Timer_GetData($);
  75. my %paths = ( 'statussoe' => 'system_status/soe',
  76. 'aggregates' => 'meters/aggregates',
  77. 'siteinfo' => 'site_info',
  78. 'sitemaster' => 'sitemaster',
  79. 'powerwalls' => 'powerwalls',
  80. 'registration' => 'customer/registration',
  81. 'status' => 'status'
  82. );
  83. sub TeslaPowerwall2AC_Initialize($) {
  84. my ($hash) = @_;
  85. # Consumer
  86. $hash->{GetFn} = "TeslaPowerwall2AC_Get";
  87. $hash->{DefFn} = "TeslaPowerwall2AC_Define";
  88. $hash->{UndefFn} = "TeslaPowerwall2AC_Undef";
  89. $hash->{NotifyFn} = "TeslaPowerwall2AC_Notify";
  90. $hash->{AttrFn} = "TeslaPowerwall2AC_Attr";
  91. $hash->{AttrList} = "interval ".
  92. "disable:1 ".
  93. $readingFnAttributes;
  94. foreach my $d(sort keys %{$modules{TeslaPowerwall2AC}{defptr}}) {
  95. my $hash = $modules{TeslaPowerwall2AC}{defptr}{$d};
  96. $hash->{VERSION} = $version;
  97. }
  98. }
  99. sub TeslaPowerwall2AC_Define($$) {
  100. my ( $hash, $def ) = @_;
  101. my @a = split( "[ \t][ \t]*", $def );
  102. return "too few parameters: define <name> TeslaPowerwall2AC <HOST>" if( @a != 3);
  103. return "Cannot define a TeslaPowerwall2AC device. Perl modul $missingModul is missing." if ( $missingModul );
  104. my $name = $a[0];
  105. my $host = $a[2];
  106. $hash->{HOST} = $host;
  107. $hash->{INTERVAL} = 300;
  108. $hash->{PORT} = 80;
  109. $hash->{VERSION} = $version;
  110. $hash->{NOTIFYDEV} = "global";
  111. $hash->{actionQueue} = [];
  112. $attr{$name}{room} = "Tesla" if( !defined( $attr{$name}{room} ) );
  113. Log3 $name, 3, "TeslaPowerwall2AC ($name) - defined TeslaPowerwall2AC Device with Host $host, Port $hash->{PORT} and Interval $hash->{INTERVAL}";
  114. $modules{TeslaPowerwall2AC}{defptr}{HOST} = $hash;
  115. return undef;
  116. }
  117. sub TeslaPowerwall2AC_Undef($$) {
  118. my ( $hash, $arg ) = @_;
  119. my $name = $hash->{NAME};
  120. Log3 $name, 3, "TeslaPowerwall2AC ($name) - Device $name deleted";
  121. delete $modules{TeslaPowerwall2AC}{defptr}{HOST} if( defined($modules{TeslaPowerwall2AC}{defptr}{HOST}) and $hash->{HOST} );
  122. return undef;
  123. }
  124. sub TeslaPowerwall2AC_Attr(@) {
  125. my ( $cmd, $name, $attrName, $attrVal ) = @_;
  126. my $hash = $defs{$name};
  127. if( $attrName eq "disable" ) {
  128. if( $cmd eq "set" and $attrVal eq "1" ) {
  129. RemoveInternalTimer($hash);
  130. readingsSingleUpdate ( $hash, "state", "disabled", 1 );
  131. Log3 $name, 3, "TeslaPowerwall2AC ($name) - disabled";
  132. } elsif( $cmd eq "del" ) {
  133. Log3 $name, 3, "TeslaPowerwall2AC ($name) - enabled";
  134. }
  135. }
  136. if( $attrName eq "disabledForIntervals" ) {
  137. if( $cmd eq "set" ) {
  138. return "check disabledForIntervals Syntax HH:MM-HH:MM or 'HH:MM-HH:MM HH:MM-HH:MM ...'"
  139. unless($attrVal =~ /^((\d{2}:\d{2})-(\d{2}:\d{2})\s?)+$/);
  140. Log3 $name, 3, "TeslaPowerwall2AC ($name) - disabledForIntervals";
  141. readingsSingleUpdate ( $hash, "state", "disabled", 1 );
  142. } elsif( $cmd eq "del" ) {
  143. Log3 $name, 3, "TeslaPowerwall2AC ($name) - enabled";
  144. readingsSingleUpdate( $hash, "state", "active", 1 );
  145. }
  146. }
  147. if( $attrName eq "interval" ) {
  148. if( $cmd eq "set" ) {
  149. if( $attrVal < 30 ) {
  150. Log3 $name, 3, "TeslaPowerwall2AC ($name) - interval too small, please use something >= 30 (sec), default is 300 (sec)";
  151. return "interval too small, please use something >= 30 (sec), default is 300 (sec)";
  152. } else {
  153. RemoveInternalTimer($hash);
  154. $hash->{INTERVAL} = $attrVal;
  155. Log3 $name, 3, "TeslaPowerwall2AC ($name) - set interval to $attrVal";
  156. TeslaPowerwall2AC_Timer_GetData($hash);
  157. }
  158. } elsif( $cmd eq "del" ) {
  159. RemoveInternalTimer($hash);
  160. $hash->{INTERVAL} = 300;
  161. Log3 $name, 3, "TeslaPowerwall2AC ($name) - set interval to default";
  162. TeslaPowerwall2AC_Timer_GetData($hash);
  163. }
  164. }
  165. return undef;
  166. }
  167. sub TeslaPowerwall2AC_Notify($$) {
  168. my ($hash,$dev) = @_;
  169. my $name = $hash->{NAME};
  170. return if (IsDisabled($name));
  171. my $devname = $dev->{NAME};
  172. my $devtype = $dev->{TYPE};
  173. my $events = deviceEvents($dev,1);
  174. return if (!$events);
  175. TeslaPowerwall2AC_Timer_GetData($hash) if( grep /^INITIALIZED$/,@{$events}
  176. or grep /^DELETEATTR.$name.disable$/,@{$events}
  177. or (grep /^DEFINED.$name$/,@{$events} and $init_done) );
  178. return;
  179. }
  180. sub TeslaPowerwall2AC_Get($@) {
  181. my ($hash, $name, $cmd) = @_;
  182. my $arg;
  183. if( $cmd eq 'statusSOE' ) {
  184. $arg = lc($cmd);
  185. } elsif( $cmd eq 'aggregates' ) {
  186. $arg = lc($cmd);
  187. } elsif( $cmd eq 'siteinfo' ) {
  188. $arg = lc($cmd);
  189. } elsif( $cmd eq 'powerwalls' ) {
  190. $arg = lc($cmd);
  191. } elsif( $cmd eq 'sitemaster' ) {
  192. $arg = lc($cmd);
  193. } elsif( $cmd eq 'registration' ) {
  194. $arg = lc($cmd);
  195. } elsif( $cmd eq 'status' ) {
  196. $arg = lc($cmd);
  197. } else {
  198. my $list = 'statusSOE:noArg aggregates:noArg siteinfo:noArg sitemaster:noArg powerwalls:noArg registration:noArg status:noArg';
  199. return "Unknown argument $cmd, choose one of $list";
  200. }
  201. return 'There are still path commands in the action queue'
  202. if( defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) > 0 );
  203. unshift( @{$hash->{actionQueue}}, $arg );
  204. TeslaPowerwall2AC_GetData($hash);
  205. return undef;
  206. }
  207. sub TeslaPowerwall2AC_Timer_GetData($) {
  208. my $hash = shift;
  209. my $name = $hash->{NAME};
  210. if( defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) == 0 ) {
  211. if( not IsDisabled($name) ) {
  212. while( my $obj = each %paths ) {
  213. unshift( @{$hash->{actionQueue}}, $obj );
  214. }
  215. TeslaPowerwall2AC_GetData($hash);
  216. } else {
  217. readingsSingleUpdate($hash,'state','disabled',1);
  218. }
  219. }
  220. InternalTimer( gettimeofday()+$hash->{INTERVAL}, 'TeslaPowerwall2AC_Timer_GetData', $hash );
  221. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Call InternalTimer TeslaPowerwall2AC_Timer_GetData";
  222. }
  223. sub TeslaPowerwall2AC_GetData($) {
  224. my ($hash) = @_;
  225. my $name = $hash->{NAME};
  226. my $host = $hash->{HOST};
  227. my $port = $hash->{PORT};
  228. my $path = pop( @{$hash->{actionQueue}} );
  229. my $uri = $host . ':' . $port . '/api/' . $paths{$path};
  230. readingsSingleUpdate($hash,'state','fetch data - ' . scalar(@{$hash->{actionQueue}}) . ' entries in the Queue',1);
  231. HttpUtils_NonblockingGet(
  232. {
  233. url => "http://" . $uri,
  234. timeout => 5,
  235. method => 'GET',
  236. hash => $hash,
  237. setCmd => $path,
  238. doTrigger => 1,
  239. callback => \&TeslaPowerwall2AC_ErrorHandling,
  240. }
  241. );
  242. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Send with URI: http://$uri";
  243. }
  244. sub TeslaPowerwall2AC_ErrorHandling($$$) {
  245. my ($param,$err,$data) = @_;
  246. my $hash = $param->{hash};
  247. my $name = $hash->{NAME};
  248. ### Begin Error Handling
  249. if( defined( $err ) ) {
  250. if( $err ne "" ) {
  251. readingsBeginUpdate( $hash );
  252. readingsBulkUpdate( $hash, 'state', $err, 1);
  253. readingsBulkUpdate( $hash, 'lastRequestError', $err, 1 );
  254. readingsEndUpdate( $hash, 1 );
  255. Log3 $name, 3, "TeslaPowerwall2AC ($name) - RequestERROR: $err";
  256. $hash->{actionQueue} = [];
  257. return;
  258. }
  259. }
  260. if( $data eq "" and exists( $param->{code} ) && $param->{code} ne 200 ) {
  261. readingsBeginUpdate( $hash );
  262. readingsBulkUpdate( $hash, 'state', $param->{code}, 1 );
  263. readingsBulkUpdate( $hash, 'lastRequestError', $param->{code}, 1 );
  264. Log3 $name, 3, "TeslaPowerwall2AC ($name) - RequestERROR: ".$param->{code};
  265. readingsEndUpdate( $hash, 1 );
  266. Log3 $name, 5, "TeslaPowerwall2AC ($name) - RequestERROR: received http code ".$param->{code}." without any data after requesting";
  267. $hash->{actionQueue} = [];
  268. return;
  269. }
  270. if( ( $data =~ /Error/i ) and exists( $param->{code} ) ) {
  271. readingsBeginUpdate( $hash );
  272. readingsBulkUpdate( $hash, 'state', $param->{code}, 1 );
  273. readingsBulkUpdate( $hash, "lastRequestError", $param->{code}, 1 );
  274. readingsEndUpdate( $hash, 1 );
  275. Log3 $name, 3, "TeslaPowerwall2AC ($name) - statusRequestERROR: http error ".$param->{code};
  276. $hash->{actionQueue} = [];
  277. return;
  278. ### End Error Handling
  279. }
  280. TeslaPowerwall2AC_GetData($hash)
  281. if( defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) > 0 );
  282. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Recieve JSON data: $data";
  283. TeslaPowerwall2AC_ResponseProcessing($hash,$param->{setCmd},$data);
  284. }
  285. sub TeslaPowerwall2AC_ResponseProcessing($$$) {
  286. my ($hash,$path,$json) = @_;
  287. my $name = $hash->{NAME};
  288. my $decode_json;
  289. my $readings;
  290. $decode_json = eval{decode_json($json)};
  291. if($@){
  292. Log3 $name, 4, "TeslaPowerwall2AC ($name) - error while request: $@";
  293. readingsBeginUpdate($hash);
  294. readingsBulkUpdate($hash, 'JSON Error', $@);
  295. readingsBulkUpdate($hash, 'state', 'JSON error');
  296. readingsEndUpdate($hash,1);
  297. return;
  298. }
  299. #### Verarbeitung der Readings zum passenden Path
  300. if( $path eq 'aggregates') {
  301. $readings = TeslaPowerwall2AC_ReadingsProcessing_Aggregates($hash,$decode_json);
  302. } elsif( $path eq 'powerwalls') {
  303. $readings = TeslaPowerwall2AC_ReadingsProcessing_Powerwalls($hash,$decode_json);
  304. } else {
  305. $readings = $decode_json;
  306. }
  307. TeslaPowerwall2AC_WriteReadings($hash,$path,$readings);
  308. }
  309. sub TeslaPowerwall2AC_WriteReadings($$$) {
  310. my ($hash,$path,$readings) = @_;
  311. my $name = $hash->{NAME};
  312. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Write Readings";
  313. readingsBeginUpdate($hash);
  314. while( my ($r,$v) = each %{$readings} ) {
  315. readingsBulkUpdate($hash,$path.'-'.$r,$v);
  316. }
  317. readingsBulkUpdate($hash,'batteryLevel',sprintf("%.1f",$readings->{percentage})) if( defined($readings->{percentage}) );
  318. readingsBulkUpdate($hash,'batteryPower',sprintf("%.1f",(ReadingsVal($name,'siteinfo-nominal_system_energy_kWh',0)/100) * ReadingsVal($name,'statussoe-percentage',0) ) );
  319. readingsBulkUpdateIfChanged($hash,'actionQueue',scalar(@{$hash->{actionQueue}}) . ' entries in the Queue');
  320. readingsBulkUpdateIfChanged($hash,'state',(defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) == 0 ? 'ready' : 'fetch data - ' . scalar(@{$hash->{actionQueue}}) . ' paths in actionQueue'));
  321. readingsEndUpdate($hash,1);
  322. }
  323. sub TeslaPowerwall2AC_ReadingsProcessing_Aggregates($$) {
  324. my ($hash,$decode_json) = @_;
  325. my $name = $hash->{NAME};
  326. my %readings;
  327. if( ref($decode_json) eq "HASH" ) {
  328. while( my $obj = each %{$decode_json} ) {
  329. while( my ($r,$v) = each %{$decode_json->{$obj}} ) {
  330. $readings{$obj.'-'.$r} = $v;
  331. }
  332. }
  333. } else {
  334. $readings{'error'} = 'aggregates response is not a Hash';
  335. }
  336. return \%readings;
  337. }
  338. sub TeslaPowerwall2AC_ReadingsProcessing_Powerwalls($$) {
  339. my ($hash,$decode_json) = @_;
  340. my $name = $hash->{NAME};
  341. my %readings;
  342. if( ref($decode_json->{powerwalls}) eq "ARRAY" and scalar(@{$decode_json->{powerwalls}}) > 0 ) {
  343. foreach my $powerwall (@{$decode_json->{powerwalls}}) {
  344. if( ref($powerwall) eq "HASH" ) {
  345. while( my ($r,$v) = each %{$powerwall} ) {
  346. $readings{$r} = $v;
  347. }
  348. }
  349. }
  350. } else {
  351. $readings{'error'} = 'aggregates response is not a Array';
  352. }
  353. return \%readings;
  354. }
  355. 1;
  356. =pod
  357. =item device
  358. =item summary Modul to retrieves data from a Tesla Powerwall 2AC
  359. =item summary_DE
  360. =begin html
  361. <a name="TeslaPowerwall2AC"></a>
  362. <h3>Tesla Powerwall 2 AC</h3>
  363. <ul>
  364. <u><b>TeslaPowerwall2AC - Retrieves data from a Tesla Powerwall 2AC System</b></u>
  365. <br>
  366. With this module it is possible to read the data from a Tesla Powerwall 2AC and to set it as reading.
  367. <br><br>
  368. <a name="TeslaPowerwall2ACdefine"></a>
  369. <b>Define</b>
  370. <ul><br>
  371. <code>define &lt;name&gt; TeslaPowerwall2AC &lt;HOST&gt;</code>
  372. <br><br>
  373. Example:
  374. <ul><br>
  375. <code>define myPowerWall TeslaPowerwall2AC 192.168.1.34</code><br>
  376. </ul>
  377. <br>
  378. This statement creates a Device with the name myPowerWall and the Host IP 192.168.1.34.<br>
  379. After the device has been created, the current data of Powerwall is automatically read from the device.
  380. </ul>
  381. <br><br>
  382. <a name="TeslaPowerwall2ACreadings"></a>
  383. <b>Readings</b>
  384. <ul>
  385. <li>actionQueue - information about the entries in the action queue</li>
  386. <li>aggregates-* - readings of the /api/meters/aggregates response</li>
  387. <li>batteryLevel - battery level in percent</li>
  388. <li>batteryPower - battery capacity in kWh</li>
  389. <li>powerwalls-* - readings of the /api/powerwalls response</li>
  390. <li>registration-* - readings of the /api/customer/registration response</li>
  391. <li>siteinfo-* - readings of the /api/site_info response</li>
  392. <li>sitemaster-* - readings of the /api/sitemaster response</li>
  393. <li>state - information about internel modul processes</li>
  394. <li>status-* - readings of the /api/status response</li>
  395. <li>statussoe-* - readings of the /api/system_status/soe response</li>
  396. </ul>
  397. <a name="TeslaPowerwall2ACget"></a>
  398. <b>get</b>
  399. <ul>
  400. <li>aggregates - fetch data from url path /api/meters/aggregates</li>
  401. <li>powerwalls - fetch data from url path /api/powerwalls</li>
  402. <li>registration - fetch data from url path /api/customer/registration</li>
  403. <li>siteinfo - fetch data from url path /api/site_info</li>
  404. <li>sitemaster - fetch data from url path /api/sitemaster</li>
  405. <li>status - fetch data from url path /api/status</li>
  406. <li>statussoe - fetch data from url path /api/system_status/soe</li>
  407. </ul>
  408. <a name="TeslaPowerwall2ACattribute"></a>
  409. <b>Attribute</b>
  410. <ul>
  411. <li>interval - interval in seconds for automatically fetch data (default 300)</li>
  412. </ul>
  413. </ul>
  414. =end html
  415. =begin html_DE
  416. <a name="TeslaPowerwall2AC"></a>
  417. <h3>Tesla Powerwall 2 AC</h3>
  418. =end html_DE
  419. =cut