46_TeslaPowerwall2AC.pm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 15976 2018-01-24 04:58:51Z 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.4.0";
  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 /^DELETEATTR.$name.interval$/,@{$events}
  178. or (grep /^DEFINED.$name$/,@{$events} and $init_done) );
  179. return;
  180. }
  181. sub TeslaPowerwall2AC_Get($@) {
  182. my ($hash, $name, $cmd) = @_;
  183. my $arg;
  184. if( $cmd eq 'statusSOE' ) {
  185. $arg = lc($cmd);
  186. } elsif( $cmd eq 'aggregates' ) {
  187. $arg = lc($cmd);
  188. } elsif( $cmd eq 'siteinfo' ) {
  189. $arg = lc($cmd);
  190. } elsif( $cmd eq 'powerwalls' ) {
  191. $arg = lc($cmd);
  192. } elsif( $cmd eq 'sitemaster' ) {
  193. $arg = lc($cmd);
  194. } elsif( $cmd eq 'registration' ) {
  195. $arg = lc($cmd);
  196. } elsif( $cmd eq 'status' ) {
  197. $arg = lc($cmd);
  198. } else {
  199. my $list = 'statusSOE:noArg aggregates:noArg siteinfo:noArg sitemaster:noArg powerwalls:noArg registration:noArg status:noArg';
  200. return "Unknown argument $cmd, choose one of $list";
  201. }
  202. return 'There are still path commands in the action queue'
  203. if( defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) > 0 );
  204. unshift( @{$hash->{actionQueue}}, $arg );
  205. TeslaPowerwall2AC_GetData($hash);
  206. return undef;
  207. }
  208. sub TeslaPowerwall2AC_Timer_GetData($) {
  209. my $hash = shift;
  210. my $name = $hash->{NAME};
  211. if( defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) == 0 ) {
  212. if( not IsDisabled($name) ) {
  213. while( my $obj = each %paths ) {
  214. unshift( @{$hash->{actionQueue}}, $obj );
  215. }
  216. TeslaPowerwall2AC_GetData($hash);
  217. } else {
  218. readingsSingleUpdate($hash,'state','disabled',1);
  219. }
  220. }
  221. InternalTimer( gettimeofday()+$hash->{INTERVAL}, 'TeslaPowerwall2AC_Timer_GetData', $hash );
  222. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Call InternalTimer TeslaPowerwall2AC_Timer_GetData";
  223. }
  224. sub TeslaPowerwall2AC_GetData($) {
  225. my ($hash) = @_;
  226. my $name = $hash->{NAME};
  227. my $host = $hash->{HOST};
  228. my $port = $hash->{PORT};
  229. my $path = pop( @{$hash->{actionQueue}} );
  230. my $uri = $host . ':' . $port . '/api/' . $paths{$path};
  231. readingsSingleUpdate($hash,'state','fetch data - ' . scalar(@{$hash->{actionQueue}}) . ' entries in the Queue',1);
  232. HttpUtils_NonblockingGet(
  233. {
  234. url => "http://" . $uri,
  235. timeout => 5,
  236. method => 'GET',
  237. hash => $hash,
  238. setCmd => $path,
  239. doTrigger => 1,
  240. callback => \&TeslaPowerwall2AC_ErrorHandling,
  241. }
  242. );
  243. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Send with URI: http://$uri";
  244. }
  245. sub TeslaPowerwall2AC_ErrorHandling($$$) {
  246. my ($param,$err,$data) = @_;
  247. my $hash = $param->{hash};
  248. my $name = $hash->{NAME};
  249. ### Begin Error Handling
  250. if( defined( $err ) ) {
  251. if( $err ne "" ) {
  252. readingsBeginUpdate( $hash );
  253. readingsBulkUpdate( $hash, 'state', $err, 1);
  254. readingsBulkUpdate( $hash, 'lastRequestError', $err, 1 );
  255. readingsEndUpdate( $hash, 1 );
  256. Log3 $name, 3, "TeslaPowerwall2AC ($name) - RequestERROR: $err";
  257. $hash->{actionQueue} = [];
  258. return;
  259. }
  260. }
  261. if( $data eq "" and exists( $param->{code} ) && $param->{code} ne 200 ) {
  262. readingsBeginUpdate( $hash );
  263. readingsBulkUpdate( $hash, 'state', $param->{code}, 1 );
  264. readingsBulkUpdate( $hash, 'lastRequestError', $param->{code}, 1 );
  265. Log3 $name, 3, "TeslaPowerwall2AC ($name) - RequestERROR: ".$param->{code};
  266. readingsEndUpdate( $hash, 1 );
  267. Log3 $name, 5, "TeslaPowerwall2AC ($name) - RequestERROR: received http code ".$param->{code}." without any data after requesting";
  268. $hash->{actionQueue} = [];
  269. return;
  270. }
  271. if( ( $data =~ /Error/i ) and exists( $param->{code} ) ) {
  272. readingsBeginUpdate( $hash );
  273. readingsBulkUpdate( $hash, 'state', $param->{code}, 1 );
  274. readingsBulkUpdate( $hash, "lastRequestError", $param->{code}, 1 );
  275. readingsEndUpdate( $hash, 1 );
  276. Log3 $name, 3, "TeslaPowerwall2AC ($name) - statusRequestERROR: http error ".$param->{code};
  277. $hash->{actionQueue} = [];
  278. return;
  279. ### End Error Handling
  280. }
  281. TeslaPowerwall2AC_GetData($hash)
  282. if( defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) > 0 );
  283. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Recieve JSON data: $data";
  284. TeslaPowerwall2AC_ResponseProcessing($hash,$param->{setCmd},$data);
  285. }
  286. sub TeslaPowerwall2AC_ResponseProcessing($$$) {
  287. my ($hash,$path,$json) = @_;
  288. my $name = $hash->{NAME};
  289. my $decode_json;
  290. my $readings;
  291. $decode_json = eval{decode_json($json)};
  292. if($@){
  293. Log3 $name, 4, "TeslaPowerwall2AC ($name) - error while request: $@";
  294. readingsBeginUpdate($hash);
  295. readingsBulkUpdate($hash, 'JSON Error', $@);
  296. readingsBulkUpdate($hash, 'state', 'JSON error');
  297. readingsEndUpdate($hash,1);
  298. return;
  299. }
  300. #### Verarbeitung der Readings zum passenden Path
  301. if( $path eq 'aggregates') {
  302. $readings = TeslaPowerwall2AC_ReadingsProcessing_Aggregates($hash,$decode_json);
  303. } elsif( $path eq 'powerwalls') {
  304. $readings = TeslaPowerwall2AC_ReadingsProcessing_Powerwalls($hash,$decode_json);
  305. } else {
  306. $readings = $decode_json;
  307. }
  308. TeslaPowerwall2AC_WriteReadings($hash,$path,$readings);
  309. }
  310. sub TeslaPowerwall2AC_WriteReadings($$$) {
  311. my ($hash,$path,$readings) = @_;
  312. my $name = $hash->{NAME};
  313. Log3 $name, 4, "TeslaPowerwall2AC ($name) - Write Readings";
  314. readingsBeginUpdate($hash);
  315. while( my ($r,$v) = each %{$readings} ) {
  316. readingsBulkUpdate($hash,$path.'-'.$r,$v);
  317. }
  318. readingsBulkUpdate($hash,'batteryLevel',sprintf("%.1f",$readings->{percentage})) if( defined($readings->{percentage}) );
  319. readingsBulkUpdate($hash,'batteryPower',sprintf("%.1f",(ReadingsVal($name,'siteinfo-nominal_system_energy_kWh',0)/100) * ReadingsVal($name,'statussoe-percentage',0) ) );
  320. readingsBulkUpdateIfChanged($hash,'actionQueue',scalar(@{$hash->{actionQueue}}) . ' entries in the Queue');
  321. readingsBulkUpdateIfChanged($hash,'state',(defined($hash->{actionQueue}) and scalar(@{$hash->{actionQueue}}) == 0 ? 'ready' : 'fetch data - ' . scalar(@{$hash->{actionQueue}}) . ' paths in actionQueue'));
  322. readingsEndUpdate($hash,1);
  323. }
  324. sub TeslaPowerwall2AC_ReadingsProcessing_Aggregates($$) {
  325. my ($hash,$decode_json) = @_;
  326. my $name = $hash->{NAME};
  327. my %readings;
  328. if( ref($decode_json) eq "HASH" ) {
  329. while( my $obj = each %{$decode_json} ) {
  330. while( my ($r,$v) = each %{$decode_json->{$obj}} ) {
  331. $readings{$obj.'-'.$r} = $v;
  332. }
  333. }
  334. } else {
  335. $readings{'error'} = 'aggregates response is not a Hash';
  336. }
  337. return \%readings;
  338. }
  339. sub TeslaPowerwall2AC_ReadingsProcessing_Powerwalls($$) {
  340. my ($hash,$decode_json) = @_;
  341. my $name = $hash->{NAME};
  342. my %readings;
  343. if( ref($decode_json->{powerwalls}) eq "ARRAY" and scalar(@{$decode_json->{powerwalls}}) > 0 ) {
  344. my $i = 0;
  345. foreach my $powerwall (@{$decode_json->{powerwalls}}) {
  346. if( ref($powerwall) eq "HASH" ) {
  347. while( my ($r,$v) = each %{$powerwall} ) {
  348. $readings{'wall_'.$i.'_'.$r} = $v;
  349. }
  350. $i++;
  351. }
  352. }
  353. $readings{'numberOfWalls'} = $i;
  354. } else {
  355. $readings{'error'} = 'aggregates response is not a Array';
  356. }
  357. return \%readings;
  358. }
  359. 1;
  360. =pod
  361. =item device
  362. =item summary Modul to retrieves data from a Tesla Powerwall 2AC
  363. =item summary_DE
  364. =begin html
  365. <a name="TeslaPowerwall2AC"></a>
  366. <h3>Tesla Powerwall 2 AC</h3>
  367. <ul>
  368. <u><b>TeslaPowerwall2AC - Retrieves data from a Tesla Powerwall 2AC System</b></u>
  369. <br>
  370. With this module it is possible to read the data from a Tesla Powerwall 2AC and to set it as reading.
  371. <br><br>
  372. <a name="TeslaPowerwall2ACdefine"></a>
  373. <b>Define</b>
  374. <ul><br>
  375. <code>define &lt;name&gt; TeslaPowerwall2AC &lt;HOST&gt;</code>
  376. <br><br>
  377. Example:
  378. <ul><br>
  379. <code>define myPowerWall TeslaPowerwall2AC 192.168.1.34</code><br>
  380. </ul>
  381. <br>
  382. This statement creates a Device with the name myPowerWall and the Host IP 192.168.1.34.<br>
  383. After the device has been created, the current data of Powerwall is automatically read from the device.
  384. </ul>
  385. <br><br>
  386. <a name="TeslaPowerwall2ACreadings"></a>
  387. <b>Readings</b>
  388. <ul>
  389. <li>actionQueue - information about the entries in the action queue</li>
  390. <li>aggregates-* - readings of the /api/meters/aggregates response</li>
  391. <li>batteryLevel - battery level in percent</li>
  392. <li>batteryPower - battery capacity in kWh</li>
  393. <li>powerwalls-* - readings of the /api/powerwalls response</li>
  394. <li>registration-* - readings of the /api/customer/registration response</li>
  395. <li>siteinfo-* - readings of the /api/site_info response</li>
  396. <li>sitemaster-* - readings of the /api/sitemaster response</li>
  397. <li>state - information about internel modul processes</li>
  398. <li>status-* - readings of the /api/status response</li>
  399. <li>statussoe-* - readings of the /api/system_status/soe response</li>
  400. </ul>
  401. <a name="TeslaPowerwall2ACget"></a>
  402. <b>get</b>
  403. <ul>
  404. <li>aggregates - fetch data from url path /api/meters/aggregates</li>
  405. <li>powerwalls - fetch data from url path /api/powerwalls</li>
  406. <li>registration - fetch data from url path /api/customer/registration</li>
  407. <li>siteinfo - fetch data from url path /api/site_info</li>
  408. <li>sitemaster - fetch data from url path /api/sitemaster</li>
  409. <li>status - fetch data from url path /api/status</li>
  410. <li>statussoe - fetch data from url path /api/system_status/soe</li>
  411. </ul>
  412. <a name="TeslaPowerwall2ACattribute"></a>
  413. <b>Attribute</b>
  414. <ul>
  415. <li>interval - interval in seconds for automatically fetch data (default 300)</li>
  416. </ul>
  417. </ul>
  418. =end html
  419. =begin html_DE
  420. <a name="TeslaPowerwall2AC"></a>
  421. <h3>Tesla Powerwall 2 AC</h3>
  422. =end html_DE
  423. =cut