00_MYSENSORS.pm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. ##############################################
  2. #
  3. # fhem driver for MySensors serial or network gateway (see http://mysensors.org)
  4. #
  5. # Copyright (C) 2014 Norbert Truchsess
  6. #
  7. # This file is part of fhem.
  8. #
  9. # Fhem is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # Fhem is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with fhem. If not, see <http://www.gnu.org/licenses/>.
  21. #
  22. # $Id: 00_MYSENSORS.pm 9341 2015-10-02 14:55:54Z ntruchsess $
  23. #
  24. ##############################################
  25. my %sets = (
  26. "connect" => [],
  27. "disconnect" => [],
  28. "inclusion-mode" => [qw(on off)],
  29. );
  30. my %gets = (
  31. "version" => ""
  32. );
  33. my @clients = qw(
  34. MYSENSORS_DEVICE
  35. );
  36. sub MYSENSORS_Initialize($) {
  37. my $hash = shift @_;
  38. require "$main::attr{global}{modpath}/FHEM/DevIo.pm";
  39. # Provider
  40. $hash->{Clients} = join (':',@clients);
  41. $hash->{ReadyFn} = "MYSENSORS::Ready";
  42. $hash->{ReadFn} = "MYSENSORS::Read";
  43. # Consumer
  44. $hash->{DefFn} = "MYSENSORS::Define";
  45. $hash->{UndefFn} = "MYSENSORS::Undef";
  46. $hash->{SetFn} = "MYSENSORS::Set";
  47. $hash->{AttrFn} = "MYSENSORS::Attr";
  48. $hash->{NotifyFn} = "MYSENSORS::Notify";
  49. $hash->{AttrList} =
  50. "autocreate:1 ".
  51. "requestAck:1 ".
  52. "first-sensorid ".
  53. "last-sensorid ".
  54. "stateFormat";
  55. }
  56. package MYSENSORS;
  57. use Exporter ('import');
  58. @EXPORT = ();
  59. @EXPORT_OK = qw(sendMessage);
  60. %EXPORT_TAGS = (all => [@EXPORT_OK]);
  61. use strict;
  62. use warnings;
  63. use GPUtils qw(:all);
  64. use Device::MySensors::Constants qw(:all);
  65. use Device::MySensors::Message qw(:all);
  66. BEGIN {GP_Import(qw(
  67. CommandDefine
  68. CommandModify
  69. CommandAttr
  70. gettimeofday
  71. readingsSingleUpdate
  72. DevIo_OpenDev
  73. DevIo_SimpleWrite
  74. DevIo_SimpleRead
  75. DevIo_CloseDev
  76. RemoveInternalTimer
  77. InternalTimer
  78. AttrVal
  79. Log3
  80. ))};
  81. my %sensorAttr = (
  82. LIGHT => ['setCommands on:V_LIGHT:1 off:V_LIGHT:0' ],
  83. ARDUINO_NODE => [ 'config M' ],
  84. ARDUINO_REPEATER_NODE => [ 'config M' ],
  85. );
  86. sub Define($$) {
  87. my ( $hash, $def ) = @_;
  88. $hash->{NOTIFYDEV} = "global";
  89. if ($main::init_done) {
  90. return Start($hash);
  91. } else {
  92. return undef;
  93. }
  94. }
  95. sub Undef($) {
  96. Stop(shift);
  97. }
  98. sub Set($@) {
  99. my ($hash, @a) = @_;
  100. return "Need at least one parameters" if(@a < 2);
  101. return "Unknown argument $a[1], choose one of " . join(" ", map {@{$sets{$_}} ? $_.':'.join ',', @{$sets{$_}} : $_} sort keys %sets)
  102. if(!defined($sets{$a[1]}));
  103. my $command = $a[1];
  104. my $value = $a[2];
  105. COMMAND_HANDLER: {
  106. $command eq "connect" and do {
  107. Start($hash);
  108. last;
  109. };
  110. $command eq "disconnect" and do {
  111. Stop($hash);
  112. last;
  113. };
  114. $command eq "inclusion-mode" and do {
  115. sendMessage($hash,radioId => 0, childId => 0, cmd => C_INTERNAL, ack => 0, subType => I_INCLUSION_MODE, payload => $value eq 'on' ? 1 : 0);
  116. $hash->{'inclusion-mode'} = $value eq 'on' ? 1 : 0;
  117. last;
  118. };
  119. };
  120. }
  121. sub Attr($$$$) {
  122. my ($command,$name,$attribute,$value) = @_;
  123. my $hash = $main::defs{$name};
  124. ATTRIBUTE_HANDLER: {
  125. $attribute eq "autocreate" and do {
  126. if ($main::init_done) {
  127. my $mode = $command eq "set" ? 1 : 0;
  128. sendMessage($hash,radioId => $hash->{radioId}, childId => $hash->{childId}, ack => 0, subType => I_INCLUSION_MODE, payload => $mode);
  129. $hash->{'inclusion-mode'} = $mode;
  130. }
  131. last;
  132. };
  133. $attribute eq "requestAck" and do {
  134. if ($command eq "set") {
  135. $hash->{ack} = 1;
  136. } else {
  137. $hash->{ack} = 0;
  138. $hash->{messages} = {};
  139. $hash->{outstandingAck} = 0;
  140. }
  141. last;
  142. };
  143. }
  144. }
  145. sub Notify($$) {
  146. my ($hash,$dev) = @_;
  147. if( grep(m/^(INITIALIZED|REREADCFG)$/, @{$dev->{CHANGED}}) ) {
  148. Start($hash);
  149. } elsif( grep(m/^SAVE$/, @{$dev->{CHANGED}}) ) {
  150. }
  151. }
  152. sub Start($) {
  153. my $hash = shift;
  154. my ($dev) = split("[ \t]+", $hash->{DEF});
  155. $hash->{DeviceName} = $dev;
  156. CommandAttr(undef, "$hash->{NAME} stateFormat connection") unless AttrVal($hash->{NAME},"stateFormat",undef);
  157. DevIo_CloseDev($hash);
  158. return DevIo_OpenDev($hash, 0, "MYSENSORS::Init");
  159. }
  160. sub Stop($) {
  161. my $hash = shift;
  162. DevIo_CloseDev($hash);
  163. RemoveInternalTimer($hash);
  164. readingsSingleUpdate($hash,"connection","disconnected",1);
  165. }
  166. sub Ready($) {
  167. my $hash = shift;
  168. return DevIo_OpenDev($hash, 1, "MYSENSORS::Init") if($hash->{STATE} eq "disconnected");
  169. }
  170. sub Init($) {
  171. my $hash = shift;
  172. my $name = $hash->{NAME};
  173. $hash->{'inclusion-mode'} = AttrVal($name,"autocreate",0);
  174. $hash->{ack} = AttrVal($name,"requestAck",0);
  175. $hash->{outstandingAck} = 0;
  176. if ($hash->{ack}) {
  177. GP_ForallClients($hash,sub {
  178. my $client = shift;
  179. $hash->{messagesForRadioId}->{$client->{radioId}} = {
  180. lastseen => -1,
  181. nexttry => -1,
  182. numtries => 1,
  183. messages => [],
  184. };
  185. });
  186. }
  187. readingsSingleUpdate($hash,"connection","connected",1);
  188. sendMessage($hash, radioId => 0, childId => 0, cmd => C_INTERNAL, ack => 0, subType => I_VERSION, payload => '');
  189. return undef;
  190. }
  191. sub Timer($) {
  192. my $hash = shift;
  193. my $now = time;
  194. foreach my $radioid (keys %{$hash->{messagesForRadioId}}) {
  195. my $msgsForId = $hash->{messagesForRadioId}->{$radioid};
  196. if ($now > $msgsForId->{nexttry}) {
  197. foreach my $msg (@{$msgsForId->{messages}}) {
  198. my $txt = createMsg(%$msg);
  199. Log3 ($hash->{NAME},5,"MYSENSORS outstanding ack, re-send: ".dumpMsg($msg));
  200. DevIo_SimpleWrite($hash,"$txt\n",undef);
  201. }
  202. $msgsForId->{numtries}++;
  203. $msgsForId->{nexttry} = gettimeofday()+$msgsForId->{numtries};
  204. }
  205. }
  206. _scheduleTimer($hash);
  207. }
  208. sub Read {
  209. my ($hash) = @_;
  210. my $name = $hash->{NAME};
  211. my $buf = DevIo_SimpleRead($hash);
  212. return "" if(!defined($buf));
  213. my $data = $hash->{PARTIAL};
  214. Log3 ($name, 5, "MYSENSORS/RAW: $data/$buf");
  215. $data .= $buf;
  216. while ($data =~ m/\n/) {
  217. my $txt;
  218. ($txt,$data) = split("\n", $data, 2);
  219. $txt =~ s/\r//;
  220. if (my $msg = parseMsg($txt)) {
  221. Log3 ($name,5,"MYSENSORS Read: ".dumpMsg($msg));
  222. if ($msg->{ack}) {
  223. onAcknowledge($hash,$msg);
  224. }
  225. my $type = $msg->{cmd};
  226. MESSAGE_TYPE: {
  227. $type == C_PRESENTATION and do {
  228. onPresentationMsg($hash,$msg);
  229. last;
  230. };
  231. $type == C_SET and do {
  232. onSetMsg($hash,$msg);
  233. last;
  234. };
  235. $type == C_REQ and do {
  236. onRequestMsg($hash,$msg);
  237. last;
  238. };
  239. $type == C_INTERNAL and do {
  240. onInternalMsg($hash,$msg);
  241. last;
  242. };
  243. $type == C_STREAM and do {
  244. onStreamMsg($hash,$msg);
  245. last;
  246. };
  247. }
  248. } else {
  249. Log3 ($name,5,"MYSENSORS Read: ".$txt."is no parsable mysensors message");
  250. }
  251. }
  252. $hash->{PARTIAL} = $data;
  253. return undef;
  254. };
  255. sub onPresentationMsg($$) {
  256. my ($hash,$msg) = @_;
  257. my $client = matchClient($hash,$msg);
  258. my $clientname;
  259. my $sensorType = $msg->{subType};
  260. unless ($client) {
  261. if ($hash->{'inclusion-mode'}) {
  262. $clientname = "MYSENSOR_$msg->{radioId}";
  263. CommandDefine(undef,"$clientname MYSENSORS_DEVICE $msg->{radioId}");
  264. $client = $main::defs{$clientname};
  265. return unless ($client);
  266. } else {
  267. Log3($hash->{NAME},3,"MYSENSORS: ignoring presentation-msg from unknown radioId $msg->{radioId}, childId $msg->{childId}, sensorType $sensorType");
  268. return;
  269. }
  270. }
  271. MYSENSORS::DEVICE::onPresentationMessage($client,$msg);
  272. };
  273. sub onSetMsg($$) {
  274. my ($hash,$msg) = @_;
  275. if (my $client = matchClient($hash,$msg)) {
  276. MYSENSORS::DEVICE::onSetMessage($client,$msg);
  277. } else {
  278. Log3($hash->{NAME},3,"MYSENSORS: ignoring set-msg from unknown radioId $msg->{radioId}, childId $msg->{childId} for ".variableTypeToStr($msg->{subType}));
  279. }
  280. };
  281. sub onRequestMsg($$) {
  282. my ($hash,$msg) = @_;
  283. if (my $client = matchClient($hash,$msg)) {
  284. MYSENSORS::DEVICE::onRequestMessage($client,$msg);
  285. } else {
  286. Log3($hash->{NAME},3,"MYSENSORS: ignoring req-msg from unknown radioId $msg->{radioId}, childId $msg->{childId} for ".variableTypeToStr($msg->{subType}));
  287. }
  288. };
  289. sub onInternalMsg($$) {
  290. my ($hash,$msg) = @_;
  291. my $address = $msg->{radioId};
  292. my $type = $msg->{subType};
  293. if ($address == 0 or $address == 255) { #msg to or from gateway
  294. TYPE: {
  295. $type == I_INCLUSION_MODE and do {
  296. if (AttrVal($hash->{NAME},"autocreate",0)) { #if autocreate is switched on, keep gateways inclusion-mode active
  297. if ($msg->{payload} == 0) {
  298. sendMessage($hash,radioId => $msg->{radioId}, childId => $msg->{childId}, ack => 0, subType => I_INCLUSION_MODE, payload => 1);
  299. }
  300. } else {
  301. $hash->{'inclusion-mode'} = $msg->{payload};
  302. }
  303. last;
  304. };
  305. $type == I_GATEWAY_READY and do {
  306. readingsSingleUpdate($hash,'connection','startup complete',1);
  307. GP_ForallClients($hash,sub {
  308. my $client = shift;
  309. MYSENSORS::DEVICE::onGatewayStarted($client);
  310. });
  311. last;
  312. };
  313. $type == I_VERSION and do {
  314. $hash->{version} = $msg->{payload};
  315. last;
  316. };
  317. $type == I_LOG_MESSAGE and do {
  318. Log3($hash->{NAME},5,"MYSENSORS gateway $hash->{NAME}: $msg->{payload}");
  319. last;
  320. };
  321. $type == I_ID_REQUEST and do {
  322. if ($hash->{'inclusion-mode'}) {
  323. my %nodes = map {$_ => 1} (AttrVal($hash->{NAME},"first-sensorid",20) ... AttrVal($hash->{NAME},"last-sensorid",254));
  324. GP_ForallClients($hash,sub {
  325. my $client = shift;
  326. delete $nodes{$client->{radioId}};
  327. });
  328. if (keys %nodes) {
  329. my $newid = (sort keys %nodes)[0];
  330. sendMessage($hash,radioId => 255, childId => 255, cmd => C_INTERNAL, ack => 0, subType => I_ID_RESPONSE, payload => $newid);
  331. Log3($hash->{NAME},4,"MYSENSORS $hash->{NAME} assigned new nodeid $newid");
  332. } else {
  333. Log3($hash->{NAME},4,"MYSENSORS $hash->{NAME} cannot assign new nodeid");
  334. }
  335. } else {
  336. Log3($hash->{NAME},4,"MYSENSORS: ignoring id-request-msg from unknown radioId $msg->{radioId}");
  337. }
  338. last;
  339. };
  340. }
  341. } elsif (my $client = matchClient($hash,$msg)) {
  342. MYSENSORS::DEVICE::onInternalMessage($client,$msg);
  343. } else {
  344. Log3($hash->{NAME},3,"MYSENSORS: ignoring internal-msg from unknown radioId $msg->{radioId}, childId $msg->{childId} for ".internalMessageTypeToStr($msg->{subType}));
  345. }
  346. };
  347. sub onStreamMsg($$) {
  348. my ($hash,$msg) = @_;
  349. };
  350. sub onAcknowledge($$) {
  351. my ($hash,$msg) = @_;
  352. my $ack;
  353. if (defined (my $outstanding = $hash->{messagesForRadioId}->{$msg->{radioId}}->{messages})) {
  354. my @remainMsg = grep {
  355. $_->{childId} != $msg->{childId}
  356. or $_->{cmd} != $msg->{cmd}
  357. or $_->{subType} != $msg->{subType}
  358. or $_->{payload} ne $msg->{payload}
  359. } @$outstanding;
  360. if ($ack = @remainMsg < @$outstanding) {
  361. $hash->{outstandingAck} -= 1;
  362. @$outstanding = @remainMsg;
  363. }
  364. $hash->{messagesForRadioId}->{$msg->{radioId}}->{numtries} = 1;
  365. }
  366. Log3 ($hash->{NAME},4,"MYSENSORS Read: unexpected ack ".dumpMsg($msg)) unless $ack;
  367. }
  368. sub sendMessage($%) {
  369. my ($hash,%msg) = @_;
  370. $msg{ack} = $hash->{ack} unless defined $msg{ack};
  371. my $txt = createMsg(%msg);
  372. Log3 ($hash->{NAME},5,"MYSENSORS send: ".dumpMsg(\%msg));
  373. DevIo_SimpleWrite($hash,"$txt\n",undef);
  374. if ($msg{ack}) {
  375. my $messagesForRadioId = $hash->{messagesForRadioId}->{$msg{radioId}};
  376. unless (defined $messagesForRadioId) {
  377. $messagesForRadioId = {
  378. lastseen => -1,
  379. numtries => 1,
  380. messages => [],
  381. };
  382. $hash->{messagesForRadioId}->{$msg{radioId}} = $messagesForRadioId;
  383. }
  384. my $messages = $messagesForRadioId->{messages};
  385. @$messages = grep {
  386. $_->{childId} != $msg{childId}
  387. or $_->{cmd} != $msg{cmd}
  388. or $_->{subType} != $msg{subType}
  389. } @$messages;
  390. push @$messages,\%msg;
  391. $messagesForRadioId->{nexttry} = gettimeofday()+$messagesForRadioId->{numtries};
  392. _scheduleTimer($hash);
  393. }
  394. };
  395. sub _scheduleTimer($) {
  396. my ($hash) = @_;
  397. $hash->{outstandingAck} = 0;
  398. RemoveInternalTimer($hash);
  399. my $next;
  400. foreach my $radioid (keys %{$hash->{messagesForRadioId}}) {
  401. my $msgsForId = $hash->{messagesForRadioId}->{$radioid};
  402. $hash->{outstandingAck} += @{$msgsForId->{messages}};
  403. $next = $msgsForId->{nexttry} unless (defined $next and $next < $msgsForId->{nexttry});
  404. };
  405. InternalTimer($next, "MYSENSORS::Timer", $hash, 0) if (defined $next);
  406. }
  407. sub matchClient($$) {
  408. my ($hash,$msg) = @_;
  409. my $radioId = $msg->{radioId};
  410. my $found;
  411. GP_ForallClients($hash,sub {
  412. return if $found;
  413. my $client = shift;
  414. if ($client->{radioId} == $radioId) {
  415. $found = $client;
  416. }
  417. });
  418. return $found;
  419. }
  420. 1;
  421. =pod
  422. =begin html
  423. <a name="MYSENSORS"></a>
  424. <h3>MYSENSORS</h3>
  425. <ul>
  426. <p>connects fhem to <a href="http://MYSENSORS.org">MYSENSORS</a>.</p>
  427. <p>A single MYSENSORS device can serve multiple <a href="#MYSENSORS_DEVICE">MYSENSORS_DEVICE</a> clients.<br/>
  428. Each <a href="#MYSENSORS_DEVICE">MYSENSORS_DEVICE</a> represents a mysensors node.<br/>
  429. <a name="MYSENSORSdefine"></a>
  430. <p><b>Define</b></p>
  431. <ul>
  432. <p><code>define &lt;name&gt; MYSENSORS &lt;serial device&gt|&lt;ip:port&gt;</code></p>
  433. <p>Specifies the MYSENSORS device.</p>
  434. </ul>
  435. <a name="MYSENSORSset"></a>
  436. <p><b>Set</b></p>
  437. <ul>
  438. <li>
  439. <p><code>set &lt;name&gt; connect</code><br/>
  440. (re-)connects the MYSENSORS-device to the MYSENSORS-gateway</p>
  441. </li>
  442. <li>
  443. <p><code>set &lt;name&gt; disconnect</code><br/>
  444. disconnects the MYSENSORS-device from the MYSENSORS-gateway</p>
  445. </li>
  446. <li>
  447. <p><code>set &lt;name&gt; inclusion-mode on|off</code><br/>
  448. turns the gateways inclusion-mode on or off</p>
  449. </li>
  450. </ul>
  451. <a name="MYSENSORSattr"></a>
  452. <p><b>Attributes</b></p>
  453. <ul>
  454. <li>
  455. <p><code>att &lt;name&gt; autocreate</code><br/>
  456. enables auto-creation of MYSENSOR_DEVICE-devices on receival of presentation-messages</p>
  457. </li>
  458. <li>
  459. <p><code>att &lt;name&gt; requestAck</code><br/>
  460. request acknowledge from nodes.<br/>
  461. if set the Readings of nodes are updated not before requested acknowledge is received<br/>
  462. if not set the Readings of nodes are updated immediatly (not awaiting the acknowledge).
  463. May also be configured for individual nodes if not set for gateway.</p>
  464. </li>
  465. <li>
  466. <p><code>att &lt;name&gt; first-sensorid <&lt;number &lth; 255&gt;></code><br/>
  467. configures the lowest node-id assigned to a mysensor-node on request (defaults to 20)</p>
  468. </li>
  469. </ul>
  470. </ul>
  471. =end html
  472. =cut