10_MQTT_BRIDGE.pm 11 KB

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