98_expandJSON.pm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # $Id: 98_expandJSON.pm 16115 2018-02-08 08:20:45Z dev0 $
  2. ################################################################################
  3. #
  4. # Copyright (c) 2017 dev0
  5. #
  6. # This script is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # The GNU General Public License can be found at
  12. # http://www.gnu.org/copyleft/gpl.html.
  13. # A copy is found in the textfile GPL.txt and important notices to the license
  14. # from the author is found in LICENSE.txt distributed with these scripts.
  15. #
  16. # This script is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # This copyright notice MUST APPEAR in all copies of the script!
  22. #
  23. ################################################################################
  24. my $module_version = "1.12";
  25. package main;
  26. use strict;
  27. use warnings;
  28. use POSIX;
  29. use Encode;
  30. sub expandJSON_expand($$$$;$$); # Forum #66761
  31. sub expandJSON_Initialize($$) {
  32. my ($hash) = @_;
  33. $hash->{DefFn} = "expandJSON_Define";
  34. $hash->{NotifyFn} = "expandJSON_Notify";
  35. $hash->{AttrFn} = "expandJSON_Attr";
  36. $hash->{AttrList} = "addStateEvent:1,0 "
  37. . "addReadingsPrefix:1,0 "
  38. . "disable:1,0 "
  39. . "disabledForIntervals "
  40. . "do_not_notify:1,0";
  41. }
  42. sub expandJSON_Define(@) {
  43. my ($hash, $def) = @_;
  44. my @a = split("[ \t][ \t]*", $def);
  45. my $usg = "\nUse 'define <name> expandJSON <event regexp>"
  46. . " [<target reading regexp>]";
  47. return "Wrong syntax: $usg" if(int(@a) < 3);
  48. return "ERROR: Perl module JSON is not installed"
  49. if (expandJSON_isPmInstalled($hash,"JSON"));
  50. my $name = $a[0];
  51. my $type = $a[1];
  52. # source regexp
  53. my $re = $a[2];
  54. return "Bad regexp: starting with *" if($re =~ m/^\*/);
  55. eval { "test" =~ m/^$re$/ };
  56. return "Bad regexp $re: $@" if($@);
  57. $hash->{s_regexp} = $re;
  58. InternalTimer(gettimeofday(), sub(){notifyRegexpChanged($hash, $re);}, $hash);
  59. # dest regexp
  60. if (defined $a[3]) {
  61. $re = $a[3];
  62. return "Bad regexp: starting with *" if($re =~ m/^\*/);
  63. eval { "test" =~ m/^$re$/ };
  64. return "Bad regexp $re: $@" if($@);
  65. $hash->{t_regexp} = $re;
  66. }
  67. else {
  68. $hash->{t_regexp} = ".*";
  69. }
  70. my $doTrigger = ($name !~ m/^$re$/); # Forum #34516
  71. readingsSingleUpdate($hash, "state", "active", $doTrigger);
  72. $hash->{version} = $module_version;
  73. return undef;
  74. }
  75. sub expandJSON_Attr($$) {
  76. my ($cmd,$name,$aName,$aVal) = @_;
  77. my $hash = $defs{$name};
  78. my $type = $hash->{TYPE};
  79. my $ret;
  80. if ($cmd eq "set" && !defined $aVal) {
  81. $ret = "not empty"
  82. }
  83. elsif ($aName eq "addReadingsPrefix") {
  84. $cmd eq "set"
  85. ? $aVal =~ m/^[01]$/ ? ($hash->{helper}{$aName} = $aVal) : ($ret = "0|1")
  86. : delete $hash->{helper}{$aName}
  87. }
  88. elsif ($aName eq "do_not_notify") {
  89. $ret = "0|1" if $cmd eq "set" && $aVal !~ m/^[01]$/;
  90. }
  91. elsif ($aName eq "disable") {
  92. if ($cmd eq "set") {
  93. if ($aVal !~ m/^[01]$/) { $ret = "0|1" }
  94. else { readingsSingleUpdate($hash, "state", $aVal?"disabled":"active", 1) }
  95. }
  96. elsif ($cmd eq "del") { readingsSingleUpdate($hash, "state", "active", 1) }
  97. }
  98. if ($ret) {
  99. my $v = defined $aVal ? $aVal : "";
  100. my $msg = "$type: attr $name $aName $v: value must be: ";
  101. Log3 $name, 2, $msg.$ret;
  102. return $msg.$ret;
  103. }
  104. return undef;
  105. }
  106. sub expandJSON_Notify($$) {
  107. my ($hash, $dhash) = @_;
  108. my $name = $hash->{NAME};
  109. return "" if(IsDisabled($name));
  110. my $events = deviceEvents($dhash, AttrVal($name, "addStateEvent", 0));
  111. return if( !grep { m/{.*}\s*$/s } @{ $events } ); #there is no JSON content
  112. for (my $i = 0; $i < int(@{$events}); $i++) {
  113. my $event = $events->[$i];
  114. $event = "" if(!defined($event));
  115. my $re = $hash->{s_regexp};
  116. my $devName = $dhash->{NAME};
  117. my $found = ($devName =~ m/^$re$/ || "$devName:$event" =~ m/^$re$/s);
  118. if ($found) {
  119. my $type = $hash->{TYPE};
  120. Log3 $name, 5, "$type $name: Found $devName:$event";
  121. my ($reading,$value) = $event =~ m/^\s*{.*}\s*$/s
  122. ? ("state", $event)
  123. : split(": ", $event, 2);
  124. $hash->{STATE} = $dhash->{NTFY_TRIGGERTIME};
  125. if ($value !~ m/^\s*{.*}\s*$/s) { # eg. state with an invalid json
  126. Log3 $name, 5, "$type $name: Invalid JSON: $value";
  127. return;
  128. }
  129. Log3 $name, 5, "$type $name: Yield decode: $hash | $devName | $reading "
  130. . "| $value";
  131. InternalTimer(
  132. gettimeofday(),
  133. sub(){ expandJSON_decode($hash,$devName,$reading,$value) },
  134. $hash);
  135. }
  136. }
  137. return undef;
  138. }
  139. sub expandJSON_decode($$$$) {
  140. my ($p) = @_;
  141. my ($hash,$dname,$dreading,$dvalue) = @_;
  142. my ($name,$type) = ($hash->{NAME},$hash->{TYPE});
  143. my $dhash = $defs{$dname};
  144. my $h;
  145. eval { $h = decode_json(encode_utf8($dvalue)); 1; };
  146. if ( $@ ) {
  147. Log3 $name, 2, "$type $name: Bad JSON: $dname $dreading: $dvalue";
  148. Log3 $name, 2, "$type $name: $@";
  149. return undef;
  150. }
  151. my $sPrefix = $hash->{helper}{addReadingsPrefix} ? $dreading."_" : "";
  152. readingsBeginUpdate($dhash);
  153. expandJSON_expand($hash,$dhash,$sPrefix,$h);
  154. readingsEndUpdate($dhash, AttrVal($name,"do_not_notify",0) ? 0 : 1);
  155. return undef;
  156. }
  157. sub expandJSON_expand($$$$;$$) {
  158. # thanx to bgewehr for the root position of this recursive snippet
  159. # https://github.com/bgewehr/fhem
  160. my ($hash,$dhash,$sPrefix,$ref,$prefix,$suffix) = @_;
  161. $prefix = "" if( !$prefix );
  162. $suffix = "" if( !$suffix );
  163. $suffix = "_$suffix" if( $suffix );
  164. if( ref( $ref ) eq "ARRAY" ) {
  165. while( my ($key,$value) = each @{ $ref } ) {
  166. expandJSON_expand($hash,$dhash,$sPrefix,$value,
  167. $prefix.sprintf("%02i",$key+1)."_");
  168. }
  169. }
  170. elsif( ref( $ref ) eq "HASH" ) {
  171. while( my ($key,$value) = each %{ $ref } ) {
  172. if( ref( $value ) ) {
  173. expandJSON_expand($hash,$dhash,$sPrefix,$value,$prefix.$key.$suffix."_");
  174. }
  175. else {
  176. # replace illegal characters in reading names
  177. (my $reading = $sPrefix.$prefix.$key.$suffix) =~ s/[^A-Za-z\d_\.\-\/]/_/g;
  178. readingsBulkUpdate($dhash, $reading, $value)
  179. if $reading =~ m/^$hash->{t_regexp}$/;
  180. }
  181. }
  182. }
  183. elsif( ref( $ref ) eq "JSON::PP::Boolean" ) { # Forum #82734
  184. (my $reading = $sPrefix.$prefix) =~ s/[^A-Za-z\d_\.\-\/]/_/g;
  185. $reading = substr($reading, 0, -1); #remove tailing _
  186. readingsBulkUpdate($dhash, $reading, $ref ? 1 : 0)
  187. if $reading =~ m/^$hash->{t_regexp}$/;
  188. }
  189. }
  190. sub expandJSON_isPmInstalled($$)
  191. {
  192. my ($hash,$pm) = @_;
  193. my ($name,$type) = ($hash->{NAME},$hash->{TYPE});
  194. if (not eval "use $pm;1")
  195. {
  196. Log3 $name, 1, "$type $name: perl modul missing: $pm. Install it, please.";
  197. $hash->{MISSING_MODULES} .= "$pm ";
  198. return "failed: $pm";
  199. }
  200. return undef;
  201. }
  202. 1;
  203. =pod
  204. =item helper
  205. =item summary Expand a JSON string from a reading into individual readings
  206. =item summary_DE Expandiert eine JSON Zeichenkette in individuelle Readings
  207. =begin html
  208. <a name="expandJSON"></a>
  209. <h3>expandJSON</h3>
  210. <ul>
  211. <p>Expand a JSON string from a reading into individual readings</p>
  212. <ul>
  213. <li>Requirement: perl module JSON<br>
  214. Use "cpan install JSON" or operating system's package manager to install
  215. Perl JSON Modul. Depending on your os the required package is named:
  216. libjson-perl or perl-JSON.
  217. </li>
  218. </ul><br>
  219. <a name="expandJSONdefine"></a>
  220. <b>Define</b><br><br>
  221. <ul>
  222. <code>define &lt;name&gt; expandJSON &lt;source_regex&gt;
  223. [&lt;target_regex&gt;]</code><br><br>
  224. <li>
  225. <a name="">&lt;name&gt;</a><br>
  226. A name of your choice.</li><br>
  227. <li>
  228. <a name="">&lt;source_regex&gt;</a><br>
  229. Regexp that must match your devices, readings and values that contain
  230. the JSON strings. Regexp syntax is the same as used by notify and must not
  231. contain spaces.<br>
  232. </li><br>
  233. <li>
  234. <a name="">&lt;target_regex&gt;</a><br>
  235. Optional: This regexp is used to determine whether the target reading is
  236. converted or not at all. If not set then all readings will be used. If set
  237. then only matching readings will be used. Regexp syntax is the same as
  238. used by notify and must not contain spaces.<br>
  239. </li><br>
  240. <li>
  241. Examples:<br>
  242. <br>
  243. <u>Source reading:</u><br>
  244. <code>
  245. device:{.*} #state without attribute addStateEvent<br>
  246. device:state:.{.*} #state with attribute addStateEvent<br>
  247. device:reading:.{.*}<br>
  248. Sonoff.*:ENERGY.*:.{.*}<br>
  249. .*wifiIOT.*:.*sensor.*:.{.*}<br>
  250. (?i)dev.*:(sensor1|sensor2|teleme.*):.{.*}<br>
  251. (devX:{.*}|devY.*:jsonY:.{.*Wifi.*{.*SSID.*}.*})
  252. </code><br>
  253. <br>
  254. <u>Target reading:</u><br>
  255. <code>.*power.*</code><br>
  256. <code>(Power|Current|Voltage|.*day)</code><br><br>
  257. <u>Complete definitions:</u><br>
  258. <code>define ej1 expandJSON device:sourceReading:.{.*} targetReading
  259. </code><br>
  260. <code>define ej2 expandJSON Sonoff.*:ENERGY.*:.{.*} (Power|.*day)
  261. </code><br>
  262. <code>define ej3 expandJSON (?i).*_sensordev_.*:.*:.{.*}
  263. </code><br><br>
  264. </li><br>
  265. </ul>
  266. <a name="expandJSONset"></a>
  267. <b>Set</b><br><br>
  268. <ul>
  269. N/A<br><br>
  270. </ul>
  271. <a name="expandJSONget"></a>
  272. <b>Get</b><br><br>
  273. <ul>
  274. N/A<br><br>
  275. </ul>
  276. <a name="expandJSON_attr"></a>
  277. <b>Attributes</b><br><br>
  278. <ul>
  279. <li><a name="expandJSON_attr_addReadingsPrefix">addReadingsPrefix</a><br>
  280. Add source reading as prefix to new generated readings. Useful if you have
  281. more than one reading with a JSON string that should be converted.
  282. </li><br>
  283. <li><a name="expandJSON_attr_disable">disable</a><br>
  284. Used to disable this device.
  285. </li><br>
  286. <li><a name="expandJSON_attr_do_not_notify">do_not_notify</a><br>
  287. Do not generate events for converted readings at all. Think twice before
  288. using this attribute. In most cases, it is more appropriate to use
  289. event-on-change-reading in target devices.
  290. </li><br>
  291. <li><a href="#disabledForIntervals">disabledForIntervals</a></li>
  292. <li><a href="#addStateEvent">addStateEvent</a></li>
  293. </ul>
  294. </ul>
  295. =end html
  296. =cut