10_MQTT_DEVICE.pm 13 KB

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