10_MQTT_BRIDGE.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. ##############################################
  2. #
  3. # fhem bridge to mqtt (see http://mqtt.org)
  4. #
  5. # Copyright (C) 2018 Alexander Schulz
  6. # Copyright (C) 2017 Stephan Eisler
  7. # Copyright (C) 2014 - 2016 Norbert Truchsess
  8. #
  9. # This file is part of fhem.
  10. #
  11. # Fhem is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation, either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # Fhem 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. # You should have received a copy of the GNU General Public License
  22. # along with fhem. If not, see <http://www.gnu.org/licenses/>.
  23. #
  24. # $Id: 10_MQTT_BRIDGE.pm 17362 2018-09-17 12:57:29Z hexenmeister $
  25. #
  26. ##############################################
  27. use strict;
  28. use warnings;
  29. my %sets = (
  30. );
  31. my %gets = (
  32. "version" => "",
  33. "readings" => ""
  34. );
  35. sub MQTT_BRIDGE_Initialize($) {
  36. my $hash = shift @_;
  37. require "$main::attr{global}{modpath}/FHEM/00_MQTT.pm";
  38. # Consumer
  39. $hash->{DefFn} = "MQTT::Client_Define";
  40. $hash->{UndefFn} = "MQTT::Client_Undefine";
  41. $hash->{GetFn} = "MQTT::BRIDGE::Get";
  42. $hash->{NotifyFn} = "MQTT::BRIDGE::Notify";
  43. $hash->{AttrFn} = "MQTT::BRIDGE::Attr";
  44. $hash->{AttrList} =
  45. "IODev ".
  46. #"qos:".join(",",keys %MQTT::qos)." ".
  47. "qos ".
  48. "retain ".
  49. "publish-topic-base ".
  50. "publishState ".
  51. "publishReading_.* ".
  52. "subscribeSet ".
  53. "subscribeSet_.* ".
  54. $main::readingFnAttributes;
  55. main::LoadModule("MQTT");
  56. }
  57. package MQTT::BRIDGE;
  58. use strict;
  59. use warnings;
  60. use GPUtils qw(:all);
  61. use Net::MQTT::Constants;
  62. BEGIN {
  63. MQTT->import(qw(:all));
  64. GP_Import(qw(
  65. AttrVal
  66. CommandAttr
  67. readingsSingleUpdate
  68. Log3
  69. DoSet
  70. fhem
  71. defs
  72. AttrVal
  73. ReadingsVal
  74. ))
  75. };
  76. sub Get($$@) {
  77. my ($hash, $name, $command) = @_;
  78. return "Need at least one parameters" unless (defined $command);
  79. return "Unknown argument $command, choose one of " . join(" ", sort keys %gets)
  80. unless (defined($gets{$command}));
  81. COMMAND_HANDLER: {
  82. # populate dynamically from keys %{$defs{$sdev}{READINGS}}
  83. $command eq "readings" and do {
  84. my $base = AttrVal($name,"publish-topic-base","/$hash->{DEF}/");
  85. foreach my $reading (keys %{$main::defs{$hash->{DEF}}{READINGS}}) {
  86. unless (defined AttrVal($name,"publishReading_$reading",undef)) {
  87. CommandAttr($hash,"$name publishReading_$reading $base$reading");
  88. }
  89. };
  90. last;
  91. };
  92. };
  93. }
  94. #use Data::Dumper;
  95. sub Notify() {
  96. my ($hash,$dev) = @_;
  97. Log3($hash->{NAME},5,"Notify for $dev->{NAME}");
  98. #Log3($hash->{NAME},5,">>>>=====".Dumper($dev->{CHANGED}));
  99. foreach my $event (@{$dev->{CHANGED}}) {
  100. $event =~ /^([^:]+)(: )?(.*)$/;
  101. #Log3($hash->{NAME},5,">>>>>>>>>>>>>>>>>>");
  102. Log3($hash->{NAME},5,"$event, '".((defined $1) ? $1 : "-undef-")."', '".((defined $3) ? $3 : "-undef-")."'");
  103. my $msgid;
  104. if (defined $3 and $3 ne "") {
  105. if (defined $hash->{publishReadings}->{$1}) {
  106. my $retain = $hash->{".retain"}->{$1};
  107. $retain = $hash->{".retain"}->{'*'} unless defined($retain);
  108. my $qos = $hash->{".qos"}->{$1};
  109. $qos = $hash->{".qos"}->{'*'} unless defined($qos);
  110. #Log3($hash->{NAME},1,">>>>>>>>>>>>>>>>>> RETAIN: ".$retain); $retain=0; ### TEST
  111. $msgid = send_publish($hash->{IODev}, topic => $hash->{publishReadings}->{$1}, message => $3, qos => $qos, retain => $retain);
  112. readingsSingleUpdate($hash,"transmission-state","outgoing publish sent",1);
  113. }
  114. } else {
  115. if (defined $hash->{publishState}) {
  116. my $retain = $hash->{".retain"}->{""};
  117. $retain = $hash->{".retain"}->{'*'} unless defined($retain);
  118. my $qos = $hash->{".qos"}->{""};
  119. $qos = $hash->{".qos"}->{'*'} unless defined($qos);
  120. #Log3($hash->{NAME},1,">>>>>>>>>>>>>>>>>> RETAIN: ".$retain); $retain=0; ### TEST
  121. $msgid = send_publish($hash->{IODev}, topic => $hash->{publishState}, message => $1, qos => $qos, retain => $retain);
  122. readingsSingleUpdate($hash,"transmission-state","outgoing publish sent",1);
  123. }
  124. }
  125. $hash->{message_ids}->{$msgid}++ if defined $msgid;
  126. }
  127. }
  128. sub Attr($$$$) {
  129. my ($command,$name,$attribute,$value) = @_;
  130. my $hash = $main::defs{$name};
  131. ATTRIBUTE_HANDLER: {
  132. $attribute =~ /^subscribeSet(_?)(.*)/ and do {
  133. if ($command eq "set") {
  134. my ($mqos, $mretain,$mtopic, $mvalue, $mcmd)=MQTT::parsePublishCmdStr($value);
  135. if(!defined($mtopic)) { return "topic may not be empty";}
  136. unless (defined $hash->{subscribeSets}->{$mtopic}->{name} and $hash->{subscribeSets}->{$mtopic}->{name} eq $2) {
  137. unless (defined $hash->{subscribeSets}->{$mtopic}->{name}) {
  138. client_subscribe_topic($hash,$mtopic,$mqos,$mretain);
  139. }
  140. $hash->{subscribeSets}->{$mtopic}->{name} = $2;
  141. $hash->{subscribeSets}->{$mtopic}->{cmd} = $mcmd;
  142. }
  143. } else {
  144. foreach my $topic (keys %{$hash->{subscribeSets}}) {
  145. if ($hash->{subscribeSets}->{$topic}->{name} eq $2) {
  146. client_unsubscribe_topic($hash,$topic);
  147. delete $hash->{subscribeSets}->{$topic};
  148. last;
  149. }
  150. }
  151. }
  152. last;
  153. };
  154. $attribute eq "publishState" and do {
  155. if ($command eq "set") {
  156. $hash->{publishState} = $value;
  157. } else {
  158. delete $hash->{publishState};
  159. }
  160. last;
  161. };
  162. $attribute =~ /^publishReading_(.+)$/ and do {
  163. if ($command eq "set") {
  164. $hash->{publishReadings}->{$1} = $value;
  165. } else {
  166. delete $hash->{publishReadings}->{$1};
  167. }
  168. last;
  169. };
  170. return client_attr($hash,$command,$name,$attribute,$value);
  171. }
  172. }
  173. sub onmessage($$$) {
  174. my ($hash,$topic,$message) = @_;
  175. if (defined (my $command = $hash->{subscribeSets}->{$topic}->{name})) {
  176. my $do=1;
  177. if(defined (my $cmd = $hash->{subscribeSets}->{$topic}->{cmd})) {
  178. Log3($hash->{NAME},5,"evaluating cmd: $cmd");
  179. my $name = $hash->{NAME};
  180. my $device = $hash->{DEF};
  181. $do=eval($cmd);
  182. Log3($hash->{NAME},1,"ERROR evaluating $cmd: $@") if($@);
  183. $do=1 if (!defined($do));
  184. }
  185. if($do) {
  186. my @args = split ("[ \t]+",$message);
  187. if ($command eq "") {
  188. Log3($hash->{NAME},5,"calling DoSet($hash->{DEF}".(@args ? ",".join(",",@args) : ""));
  189. DoSet($hash->{DEF},@args);
  190. } else {
  191. Log3($hash->{NAME},5,"calling DoSet($hash->{DEF},$command".(@args ? ",".join(",",@args) : ""));
  192. DoSet($hash->{DEF},$command,@args);
  193. }
  194. }
  195. }
  196. }
  197. 1;
  198. =pod
  199. =item [device]
  200. =item summary MQTT_BRIDGE acts as a bridge in between an fhem-device and mqtt-topics
  201. =begin html
  202. <a name="MQTT_BRIDGE"></a>
  203. <h3>MQTT_BRIDGE</h3>
  204. <ul>
  205. <p>acts as a bridge in between an fhem-device and <a href="http://mqtt.org/">mqtt</a>-topics.</p>
  206. <p>requires a <a href="#MQTT">MQTT</a>-device as IODev<br/>
  207. Note: this module is based on <a href="https://metacpan.org/pod/distribution/Net-MQTT/lib/Net/MQTT.pod">Net::MQTT</a> which needs to be installed from CPAN first.</p>
  208. <a name="MQTT_BRIDGEdefine"></a>
  209. <p><b>Define</b></p>
  210. <ul>
  211. <p><code>define &lt;name&gt; MQTT_BRIDGE &lt;fhem-device-name&gt;</code></p>
  212. <p>Specifies the MQTT device.<br/>
  213. &lt;fhem-device-name&gt; is the fhem-device this MQTT_BRIDGE is linked to.</p>
  214. </ul>
  215. <a name="MQTT_BRIDGEget"></a>
  216. <p><b>Get</b></p>
  217. <ul>
  218. <li>
  219. <p><code>get &lt;name&gt; readings</code><br/>
  220. retrieves all existing readings from fhem-device and configures (default-)topics for them.<br/>
  221. attribute 'publish-topic-base' is prepended if set.</p>
  222. </li>
  223. </ul>
  224. <a name="MQTT_BRIDGEattr"></a>
  225. <p><b>Attributes</b></p>
  226. <ul>
  227. <li>
  228. <p><code>attr &lt;name&gt; subscribeSet [{Perl-expression}] [qos:?] [retain:?] &lt;topic&gt;</code><br/>
  229. configures a topic that will issue a 'set &lt;message&gt; whenever a message is received<br/>
  230. QOS and ratain can be optionally defined for this topic. <br/>
  231. Furthermore, a Perl statement can be provided which is executed when the message is received. The following variables are available for the expression: $hash, $name, $topic, $message, $device (linked device). Return value decides whether reading is set (true (e.g., 1) or undef) or discarded (false (e.g., 0)).
  232. </p>
  233. <p>Example:<br/>
  234. <code>attr mqttest subscribeSet {fhem("do somethin")} /topic/cmd</code>
  235. </p>
  236. </li>
  237. <li>
  238. <p><code>attr &lt;name&gt; subscribeSet_&lt;reading&gt; [{Perl-expression}] [qos:?] [retain:?] &lt;topic&gt;</code><br/>
  239. configures a topic that will issue a 'set &lt;reading&gt; &lt;message&gt; whenever a message is received. see above
  240. for Perl-Expression/QOS/retain</p>
  241. <p>Example:<br/>
  242. <code>attr mqttest subscribeSet_cmd {if ($message eq "config") fhem("set $device getconfig");; 0} /topic/cmd</code>
  243. </p>
  244. </li>
  245. <li>
  246. <p><code>attr &lt;name&gt; publishState &lt;topic&gt;</code><br/>
  247. configures a topic such that a message is sent to topic whenever the device state changes.</p>
  248. </li>
  249. <li>
  250. <p><code>attr &lt;name&gt; publishReading_&lt;reading&gt; &lt;topic&gt;</code><br/>
  251. configures a topic such that a message is sent to topic whenever the device readings value changes.</p>
  252. </li>
  253. <li>
  254. <p><code>attr &lt;name&gt; publish-topic-base &lt;topic&gt;</code><br/>
  255. this is used as base path when issueing 'get &lt;device&gt; readings' to construct topics to publish to based on the devices existing readings</p>
  256. </li>
  257. <li>
  258. <p><code>attr &lt;name&gt; retain &lt;flags&gt; ...</code><br/>
  259. Specifies the retain flag for all or specific readings. Possible values are 0, 1</p>
  260. <p>Examples:<br/>
  261. <code>attr mqttest retain 0</code><br/>
  262. defines retain 0 for all readings/topics (due to downward compatibility)<br>
  263. <code> retain *:0 1 test:1</code><br/>
  264. defines retain 0 for all readings/topics except the reading 'test'. Retain for 'test' is 1<br>
  265. </p>
  266. </li>
  267. <li>
  268. <p><code>attr &lt;name&gt; qos &lt;flags&gt; ...</code><br/>
  269. Specifies the QOS flag for all or specific readings. Possible values are 0, 1 or 2. Constants may be also used: at-most-once = 0, at-least-once = 1, exactly-once = 2</p>
  270. <p>Examples:<br/>
  271. <code>attr mqttest qos 0</code><br/>
  272. defines QOS 0 for all readings/topics (due to downward compatibility)<br>
  273. <code> retain *:0 1 test:1</code><br/>
  274. defines QOS 0 for all readings/topics except the reading 'test'. Retain for 'test' is 1<br>
  275. </p>
  276. </li>
  277. </ul>
  278. </ul>
  279. =end html
  280. =cut