10_MQTT_DEVICE.pm 13 KB

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