10_MQTT_DEVICE.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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_DEVICE.pm 15202 2017-10-05 20:35:33Z eisler $
  24. #
  25. ##############################################
  26. use strict;
  27. use warnings;
  28. my %gets = (
  29. "version" => "",
  30. );
  31. sub MQTT_DEVICE_Initialize($) {
  32. my $hash = shift @_;
  33. # Consumer
  34. $hash->{DefFn} = "MQTT::DEVICE::Define";
  35. $hash->{UndefFn} = "MQTT::Client_Undefine";
  36. $hash->{SetFn} = "MQTT::DEVICE::Set";
  37. $hash->{AttrFn} = "MQTT::DEVICE::Attr";
  38. #$hash->{OnMessageFn} = "MQTT::DEVICE::onmessage";
  39. $hash->{AttrList} =
  40. "IODev ".
  41. #"qos:".join(",",keys %MQTT::qos)." ".
  42. "qos ".
  43. "retain ".
  44. "publishSet ".
  45. "publishSet_.* ".
  46. "subscribeReading_.* ".
  47. "autoSubscribeReadings ".
  48. $main::readingFnAttributes;
  49. main::LoadModule("MQTT");
  50. }
  51. package MQTT::DEVICE;
  52. use strict;
  53. use warnings;
  54. use GPUtils qw(:all);
  55. use Net::MQTT::Constants;
  56. BEGIN {
  57. MQTT->import(qw(:all));
  58. GP_Import(qw(
  59. CommandDeleteReading
  60. CommandAttr
  61. readingsSingleUpdate
  62. Log3
  63. fhem
  64. defs
  65. AttrVal
  66. ReadingsVal
  67. ))
  68. };
  69. sub Define() {
  70. my ( $hash, $def ) = @_;
  71. $hash->{sets} = {};
  72. return MQTT::Client_Define($hash,$def);
  73. };
  74. sub Set($$$@) {
  75. my ($hash,$name,$command,@values) = @_;
  76. return "Need at least one parameters" unless defined $command;
  77. my $msgid;
  78. my $mark=0;
  79. if($command ne '?') {
  80. if(defined($hash->{publishSets}->{$command})) {
  81. my $value = join " ",@values;
  82. my $retain = $hash->{".retain"}->{$command};
  83. $retain = $hash->{".retain"}->{'*'} unless defined($retain);
  84. my $qos = $hash->{".qos"}->{$command};
  85. $qos = $hash->{".qos"}->{'*'} unless defined($qos);
  86. #Log3($hash->{NAME},1,">>>>>>>>>>>>>>>>>> RETAIN: ".$retain); $retain=0; ### TEST
  87. $msgid = send_publish($hash->{IODev}, topic => $hash->{publishSets}->{$command}->{topic}, message => $value, qos => $qos, retain => $retain);
  88. readingsSingleUpdate($hash,$command,$value,1);
  89. $mark=1;
  90. } elsif(defined($hash->{publishSets}->{""})) {
  91. my $value = join (" ", ($command, @values));
  92. my $retain = $hash->{".retain"}->{""};
  93. $retain = $hash->{".retain"}->{'*'} unless defined($retain);
  94. my $qos = $hash->{".qos"}->{""};
  95. $qos = $hash->{".qos"}->{'*'} unless defined($qos);
  96. #Log3($hash->{NAME},1,">>>>>>>>>>>>>>>>>> RETAIN: ".$retain); $retain=0; ### TEST
  97. $msgid = send_publish($hash->{IODev}, topic => $hash->{publishSets}->{""}->{topic}, message => $value, qos => $qos, retain => $retain);
  98. readingsSingleUpdate($hash,"state",$command,1);
  99. $mark=1;
  100. }
  101. }
  102. if(!$mark) {
  103. return "Unknown argument $command, choose one of " . join(" ", map {$hash->{sets}->{$_} eq "" ? $_ : "$_:".$hash->{sets}->{$_}} sort keys %{$hash->{sets}})
  104. }
  105. $hash->{message_ids}->{$msgid}++ if defined $msgid;
  106. readingsSingleUpdate($hash,"transmission-state","outgoing publish sent",1);
  107. return undef;
  108. }
  109. sub Attr($$$$) {
  110. my ($command,$name,$attribute,$value) = @_;
  111. my $hash = $main::defs{$name};
  112. ATTRIBUTE_HANDLER: {
  113. $attribute =~ /^subscribeReading_(.+)/ and do {
  114. if ($command eq "set") {
  115. my ($mqos, $mretain,$mtopic, $mvalue, $mcmd)=MQTT::parsePublishCmdStr($value);
  116. if(!defined($mtopic)) {return "topic may not be empty";}
  117. unless (defined $hash->{subscribeReadings}->{$mtopic}->{name} and $hash->{subscribeReadings}->{$mtopic}->{name} eq $1) {
  118. unless (defined $hash->{subscribeReadings}->{$mtopic}->{name}) {
  119. client_subscribe_topic($hash,$mtopic,$mqos,$mretain);
  120. }
  121. $hash->{subscribeReadings}->{$mtopic}->{name} = $1;
  122. $hash->{subscribeReadings}->{$mtopic}->{cmd} = $mcmd;
  123. }
  124. } else {
  125. foreach my $topic (keys %{$hash->{subscribeReadings}}) {
  126. if ($hash->{subscribeReadings}->{$topic}->{name} eq $1) {
  127. client_unsubscribe_topic($hash,$topic);
  128. delete $hash->{subscribeReadings}->{$topic};
  129. CommandDeleteReading(undef,"$hash->{NAME} $1");
  130. last;
  131. }
  132. }
  133. }
  134. last;
  135. };
  136. $attribute eq "autoSubscribeReadings" and do {
  137. if ($command eq "set") {
  138. unless (defined $hash->{'.autoSubscribeTopic'} and $hash->{'.autoSubscribeTopic'} eq $value) {
  139. if (defined $hash->{'.autoSubscribeTopic'}) {
  140. client_unsubscribe_topic($hash,$hash->{'.autoSubscribeTopic'});
  141. }
  142. $hash->{'.autoSubscribeTopic'} = $value;
  143. $hash->{'.autoSubscribeExpr'} = topic_to_regexp($value);
  144. client_subscribe_topic($hash,$value);
  145. }
  146. } else {
  147. if (defined $hash->{'.autoSubscribeTopic'}) {
  148. client_unsubscribe_topic($hash,$hash->{'.autoSubscribeTopic'});
  149. delete $hash->{'.autoSubscribeTopic'};
  150. delete $hash->{'.autoSubscribeExpr'};
  151. }
  152. }
  153. last;
  154. };
  155. $attribute =~ /^publishSet(_?)(.*)/ and do {
  156. if ($command eq "set") {
  157. my @values = split ("[ \t]+",$value);
  158. my $topic = pop @values;
  159. $hash->{publishSets}->{$2} = {
  160. 'values' => \@values,
  161. topic => $topic,
  162. };
  163. if ($2 eq "") {
  164. if(@values) {
  165. foreach my $set (@values) {
  166. $hash->{sets}->{$set}="";
  167. my($setname,@restvalues) = split(":",$set);
  168. if(@restvalues) {
  169. $hash->{publishSets}->{$setname} = {
  170. 'values' => \@restvalues,
  171. topic => $topic,
  172. };
  173. }
  174. }
  175. } else {
  176. $hash->{sets}->{""}="";
  177. }
  178. } else {
  179. $hash->{sets}->{$2}=join(",",@values);
  180. }
  181. } else {
  182. if ($2 eq "") {
  183. foreach my $set (@{$hash->{publishSets}->{$2}->{'values'}}) {
  184. delete $hash->{sets}->{$set};
  185. }
  186. } else {
  187. CommandDeleteReading(undef,"$hash->{NAME} $2");
  188. delete $hash->{sets}->{$2};
  189. }
  190. delete $hash->{publishSets}->{$2};
  191. }
  192. last;
  193. };
  194. return client_attr($hash,$command,$name,$attribute,$value);
  195. }
  196. }
  197. sub onmessage($$$) {
  198. my ($hash,$topic,$message) = @_;
  199. if (defined (my $reading = $hash->{subscribeReadings}->{$topic}->{name})) {
  200. my $do=1;
  201. if(defined (my $cmd = $hash->{subscribeReadings}->{$topic}->{cmd})) {
  202. Log3($hash->{NAME},5,"evaluating cmd: $cmd");
  203. my $name = $hash->{NAME};
  204. $do=eval($cmd);
  205. Log3($hash->{NAME},1,"ERROR evaluating $cmd: $@") if($@);
  206. $do=1 if (!defined($do));
  207. }
  208. if($do) {
  209. Log3($hash->{NAME},5,"calling readingsSingleUpdate($hash->{NAME},$reading,$message,1)");
  210. readingsSingleUpdate($hash,$reading,$message,1);
  211. }
  212. } elsif ($topic =~ $hash->{'.autoSubscribeExpr'}) {
  213. Log3($hash->{NAME},5,"calling readingsSingleUpdate($hash->{NAME},$1,$message,1)");
  214. CommandAttr(undef,"$hash->{NAME} subscribeReading_$1 $topic");
  215. readingsSingleUpdate($hash,$1,$message,1);
  216. }
  217. }
  218. 1;
  219. =pod
  220. =item [device]
  221. =item summary MQTT_DEVICE acts as a fhem-device that is mapped to mqtt-topics
  222. =begin html
  223. <a name="MQTT_DEVICE"></a>
  224. <h3>MQTT_DEVICE</h3>
  225. <ul>
  226. <p>acts as a fhem-device that is mapped to <a href="http://mqtt.org/">mqtt</a>-topics.</p>
  227. <p>requires a <a href="#MQTT">MQTT</a>-device as IODev<br/>
  228. 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>
  229. <a name="MQTT_DEVICEdefine"></a>
  230. <p><b>Define</b></p>
  231. <ul>
  232. <p><code>define &lt;name&gt; MQTT_DEVICE</code><br/>
  233. Specifies the MQTT device.</p>
  234. </ul>
  235. <a name="MQTT_DEVICEset"></a>
  236. <p><b>Set</b></p>
  237. <ul>
  238. <li>
  239. <p><code>set &lt;name&gt; &lt;command&gt;</code><br/>
  240. sets reading 'state' and publishes the command to topic configured via attr publishSet</p>
  241. </li>
  242. <li>
  243. <p><code>set &lt;name&gt; &lt;reading&gt; &lt;value&gt;</code><br/>
  244. sets reading &lt;reading&gt; and publishes the command to topic configured via attr publishSet_&lt;reading&gt;</p>
  245. </li>
  246. </ul>
  247. <a name="MQTT_DEVICEattr"></a>
  248. <p><b>Attributes</b></p>
  249. <ul>
  250. <li>
  251. <p><code>attr &lt;name&gt; publishSet [[&lt;reading&gt;:]&lt;commands_or_options&gt;] &lt;topic&gt;</code><br/>
  252. configures set commands and UI-options e.g. 'slider' that may be used to both set given reading ('state' if not defined) and publish to configured topic</p>
  253. <p>example:<br/>
  254. <code>attr mqttest publishSet on off switch:on,off level:slider,0,1,100 /topic/123</code>
  255. </p>
  256. </li>
  257. <li>
  258. <p><code>attr &lt;name&gt; publishSet_&lt;reading&gt; [&lt;values&gt;]* &lt;topic&gt;</code><br/>
  259. configures reading that may be used to both set 'reading' (to optionally configured values) and publish to configured topic</p>
  260. </li>
  261. <li>
  262. <p><code>attr &lt;name&gt; autoSubscribeReadings &lt;topic&gt;</code><br/>
  263. specify a mqtt-topic pattern with wildcard (e.c. 'myhouse/kitchen/+') and MQTT_DEVICE automagically creates readings based on the wildcard-match<br/>
  264. e.g a message received with topic 'myhouse/kitchen/temperature' would create and update a reading 'temperature'</p>
  265. </li>
  266. <li>
  267. <p><code>attr &lt;name&gt; subscribeReading_&lt;reading&gt; [{Perl-expression}] [qos:?] [retain:?] &lt;topic&gt;</code><br/>
  268. mapps a reading to a specific topic. The reading is updated whenever a message to the configured topic arrives.<br/>
  269. QOS and ratain can be optionally defined for this topic. <br/>
  270. 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. Return value decides whether reading is set (true (e.g., 1) or undef) or discarded (false (e.g., 0)).
  271. </p>
  272. <p>Example:<br/>
  273. <code>attr mqttest subscribeReading_cmd {fhem("set something off")} /topic/cmd</code>
  274. </p>
  275. </li>
  276. <li>
  277. <p><code>attr &lt;name&gt; retain &lt;flags&gt; ...</code><br/>
  278. Specifies the retain flag for all or specific readings. Possible values are 0, 1</p>
  279. <p>Examples:<br/>
  280. <code>attr mqttest retain 0</code><br/>
  281. defines retain 0 for all readings/topics (due to downward compatibility)<br>
  282. <code> retain *:0 1 test:1</code><br/>
  283. defines retain 0 for all readings/topics except the reading 'test'. Retain for 'test' is 1<br>
  284. </p>
  285. </li>
  286. <li>
  287. <p><code>attr &lt;name&gt; qos &lt;flags&gt; ...</code><br/>
  288. 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>
  289. <p>Examples:<br/>
  290. <code>attr mqttest qos 0</code><br/>
  291. defines QOS 0 for all readings/topics (due to downward compatibility)<br>
  292. <code> retain *:0 1 test:1</code><br/>
  293. defines QOS 0 for all readings/topics except the reading 'test'. Retain for 'test' is 1<br>
  294. </p>
  295. </li>
  296. </ul>
  297. </ul>
  298. =end html
  299. =cut