98_expandJSON.pm 10 KB

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