30_TradfriGateway.pm 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. # @author Peter Kappelt
  2. # @author Sebastian Kessler
  3. # @version 1.18.2
  4. package main;
  5. use strict;
  6. use warnings;
  7. use Data::Dumper;
  8. use JSON;
  9. use TradfriIo;
  10. sub TradfriGateway_Initialize($) {
  11. my ($hash) = @_;
  12. $hash->{DefFn} = 'TradfriGateway_Define';
  13. $hash->{UndefFn} = 'TradfriGateway_Undef';
  14. $hash->{SetFn} = 'TradfriGateway_Set';
  15. $hash->{GetFn} = 'TradfriGateway_Get';
  16. $hash->{ReadFn} = 'TradfriGateway_Read';
  17. $hash->{WriteFn} = 'TradfriGateway_Write';
  18. $hash->{ReadyFn} = 'TradfriGateway_Ready';
  19. $hash->{Clients} = "TradfriDevice:TradfriGroup";
  20. $hash->{MatchList} = {
  21. "1:TradfriDevice" => '^subscribedDeviceUpdate::',
  22. "2:TradfriGroup" => '(^subscribedGroupUpdate::)|(^moodList::)' ,
  23. };
  24. }
  25. sub TradfriGateway_Define($$) {
  26. my ($hash, $def) = @_;
  27. my @param = split('[ \t]+', $def);
  28. if(int(@param) < 3) {
  29. return "too few parameters: define <name> TradfriGateway <jTradfrie-ip:port>";
  30. }
  31. $hash->{name} = $param[0];
  32. if ($param[2] =~ /\b(\d{1,3}(?:\.\d{1,3}){3}:\d{1,5})\b/) {
  33. $hash->{DeviceName} = $param[2];
  34. }else {
  35. return "Invalid parameters: define <name> TradfriGateway <jTradfrie-ip:port> like 192.168.178.100:1505";
  36. }
  37. #close connection to socket, if open
  38. DevIo_CloseDev($hash) if(DevIo_IsOpen($hash));
  39. #open the socket connection
  40. DevIo_OpenDev($hash, 0, "TradfriGateway_DeviceInit");
  41. }
  42. sub TradfriGateway_Undef($$) {
  43. my ($hash, $arg) = @_;
  44. # close the connection
  45. DevIo_CloseDev($hash);
  46. return undef;
  47. }
  48. sub TradfriGateway_DeviceInit($){
  49. my $hash = shift;
  50. #subscribe to all devices and groups, update the moodlist of the group
  51. #@todo check, whether we this instance is the IODev of the device/ group
  52. foreach my $deviceID ( keys %{$modules{'TradfriDevice'}{defptr}}){
  53. TradfriGateway_Write($hash, 0, 'subscribe', $deviceID);
  54. }
  55. foreach my $groupID ( keys %{$modules{'TradfriGroup'}{defptr}}){
  56. TradfriGateway_Write($hash, 1, 'subscribe', $groupID);
  57. TradfriGateway_Write($hash, 1, 'moodlist', $groupID);
  58. }
  59. }
  60. # a write command, that is dispatch from the logical module to here via IOWrite requires at least two arguments:
  61. # - 1. Scope: Group (1) or Device (0)
  62. # - 2. Action : A command:
  63. # * list -> sets the readings groups/ devices
  64. # * moodlist (groups only) -> get all moods that are defined for this group
  65. # * subscribe -> subscribe to updated of that specific device
  66. # * set -> write a specific value to the group/ device
  67. # - 3. ID: ID of the group or device
  68. # - 4. attribute::value only for command set, attribute can be onoff, dimvalue, mood (groups only), color (devices only) or name
  69. sub TradfriGateway_Write ($@){
  70. my ( $hash, $groupOrDevice, $action, $id, $attrValue) = @_;
  71. if(!defined($groupOrDevice) && !defined($action)){
  72. Log(1, "[TradfriGateway] Not enough arguments for IOWrite!");
  73. return "Not enough arguments for IOWrite!";
  74. }
  75. my $command = '';
  76. #for cmd-buildup: decide on group/ device
  77. if($groupOrDevice){
  78. $command .= 'group::';
  79. }else{
  80. $command .= 'device::';
  81. }
  82. if($action eq 'list'){
  83. $command .= 'list';
  84. }elsif($action eq 'moodlist'){
  85. $command .= "moodlist::${id}";
  86. }elsif($action eq 'subscribe'){
  87. #silently return if connection is open.
  88. #at startup, every device/ group runs subscribe. If the connection isn't open, we do it later.
  89. return if($hash->{STATE} ne 'opened');
  90. $command .= "subscribe::${id}";
  91. }elsif($action eq 'set'){
  92. $command .= "set::${id}::${attrValue}";
  93. }else{
  94. return "Unknown command: " . $command;
  95. }
  96. #Check if open with DevIO
  97. if(!DevIo_IsOpen($hash)){
  98. Log(1, "TradfriGateway: Can't write, connection is not opened!");
  99. return "Can't write, connection is not opened!";
  100. }
  101. #return DevIo_Expect($hash, $command . "\n", 1);
  102. DevIo_SimpleWrite($hash, $command . "\n", 2, 0);
  103. return undef;
  104. }
  105. #data was received on the socket
  106. sub TradfriGateway_Read ($){
  107. my ( $hash ) = @_;
  108. my $msg = DevIo_SimpleRead($hash);
  109. if(!defined($msg)){
  110. return undef;
  111. }
  112. my $msgReadableWhitespace = $msg;
  113. $msgReadableWhitespace =~ s/\r/\\r/g;
  114. $msgReadableWhitespace =~ s/\n/\\n/g;
  115. Log(4, "[TradfriGateway] Received message on socket: \"" . $msgReadableWhitespace . "\"");
  116. #there might be multiple messages at once, they are split by newline. Iterate through each of them
  117. my @messagesSingle = split(/\n/, $msg);
  118. foreach my $message(@messagesSingle){
  119. #if there is whitespace left, remove it.
  120. $message =~ s/\r//g;
  121. $message =~ s/\n//g;
  122. #devices and groups
  123. #@todo not as JSON array
  124. if(($message ne '') && ((split(/::/, $message))[0] =~ /(?:group|device)List/)){
  125. my @newmsg = split(/::/, $message);
  126. my $returnstring ="";
  127. #parse the JSON data
  128. my $jsonData = eval{ JSON->new->utf8->decode($newmsg[1]) };
  129. if($@){
  130. Log 3, "TradfriGateway: - ".$newmsg[1]." - can't be eval as JSON";
  131. return undef; #the string was probably not valid JSON
  132. }
  133. if($newmsg[0] eq 'deviceList'){
  134. my @items = @{ $jsonData };
  135. foreach my $item ( @items ) {
  136. $returnstring = $returnstring.$item->{'deviceid'}." => ".$item->{'name'}."\n";
  137. }
  138. return readingsSingleUpdate($hash, 'devices', $returnstring, 1);
  139. }
  140. if($newmsg[0] eq 'groupList'){
  141. my @items = @{ $jsonData };
  142. foreach my $item ( @items ) {
  143. $returnstring = $returnstring.$item->{'groupid'}." => ".$item->{'name'}."\n";
  144. }
  145. return readingsSingleUpdate($hash, 'groups', $returnstring, 1);
  146. }
  147. }
  148. #dispatch the message if it isn't empty, only dispatch messages that come from an observe
  149. if(($message ne '') && ((split(/::/, $message))[0] =~ /(?:subscribed(?:Group|Device)Update)|(?:moodList)/)){
  150. Dispatch($hash, $message, undef);
  151. }
  152. }
  153. }
  154. sub TradfriGateway_Ready($){
  155. my ($hash) = @_;
  156. return DevIo_OpenDev($hash, 1, "TradfriGateway_DeviceInit") if($hash->{STATE} eq "disconnected");
  157. }
  158. sub TradfriGateway_Get($@) {
  159. my ( $hash, $name, $opt, @args ) = @_;
  160. return "\"get $name\" needs at least one argument" unless(defined($opt));
  161. if($opt eq 'deviceList'){
  162. return TradfriGateway_Write($hash, 0, 'list');
  163. }elsif($opt eq 'groupList'){
  164. return TradfriGateway_Write($hash, 1, 'list');
  165. }else {
  166. return "Unknown argument $opt, choose one of deviceList:noArg groupList:noArg";
  167. }
  168. }
  169. sub TradfriGateway_Set($@) {
  170. my ($hash, $name, $cmd) = @_;
  171. return "\"set $name\" needs at least one argument" unless(defined($cmd));
  172. if($cmd eq "reopen"){
  173. if(DevIo_IsOpen($hash)){
  174. #close connection to socket, if open
  175. DevIo_CloseDev($hash);
  176. Log 3, "TradfriGateway: Disconnect from ".$hash->{DeviceName};
  177. }
  178. #@todo react to return code
  179. DevIo_OpenDev($hash, 0, "TradfriGateway_DeviceInit");
  180. }else{
  181. return "unknown argument $cmd, choose one of reopen:noArg";
  182. }
  183. }
  184. 1;
  185. =pod
  186. =item device
  187. =item summary connects with an IKEA Trådfri gateway
  188. =item summary_DE stellt die Verbindung mit einem IKEA Trådfri Gateway her
  189. =begin html
  190. <a name="TradfriGateway"></a>
  191. <h3>TradfriGateway</h3>
  192. <ul>
  193. <i>TradfriGateway</i> stores the connection data for an IKEA Trådfri gateway. It is necessary for TradfriDevice and TradfriGroup
  194. <br><br>
  195. <a name="TradfriGatewaydefine"></a>
  196. <b>Define</b>
  197. <ul>
  198. <code>define &lt;name&gt; TradfriGateway &lt;gateway-ip&gt; &lt;gateway-secret&gt;</code>
  199. <br><br>
  200. Example: <code>define trGateway TradfriGateway TradfriGW.int.kappelt.net vBkxxxxxxxxxx7hz</code>
  201. <br><br>
  202. The IP can either be a "normal" IP-Address, like 192.168.2.60, or a DNS name (like shown above).<br>
  203. You can find the secret on a label on the bottom side of the gateway.
  204. The parameter "coap-client-path" is isn't used anymore and thus not shown here anymore. Please remove it as soon as possible, if you are still using it.<br>
  205. You need to run kCoAPSocket running in background, that acts like a translator between FHEM and the Trådfri Gateway.
  206. </ul>
  207. <br>
  208. <a name="TradfriGatewayset"></a>
  209. <b>Set</b><br>
  210. <ul>
  211. <code>set &lt;name&gt; &lt;option&gt; [&lt;value&gt;]</code>
  212. <br><br>
  213. You can set the following options. See <a href="http://fhem.de/commandref.html#set">commandref#set</a>
  214. for more info about the set command.
  215. <br><br>
  216. Options:
  217. <ul>
  218. <li><i>reopen</i><br>
  219. Re-open the connection to the Java TCP socket, that acts like a "translator" between FHEM and the Tradfri-CoAP-Infrastructure.<br>
  220. If the connection is already opened, it'll be closed and opened.<br>
  221. If the connection isn't open yet, a try to open it will be executed.<br>
  222. <b>Caution: </b>Running this command seems to trigger some issues! Do <i>not</i> run it before a update is available!</li>
  223. </ul>
  224. </ul>
  225. <br>
  226. <a name="TradfriGatewayget"></a>
  227. <b>Get</b><br>
  228. <ul>
  229. <code>get &lt;name&gt; &lt;option&gt;</code>
  230. <br><br>
  231. You can get the following information about the device. See
  232. <a href="http://fhem.de/commandref.html#get">commandref#get</a> for more info about
  233. the get command.
  234. <br><br>
  235. Options:
  236. <ul>
  237. <li><i>deviceList</i><br>
  238. Sets the reading "devices" to a JSON-formatted string of all device IDs and their names.</li>
  239. <li><i>groupList</i><br>
  240. Sets the reading "devices" to a JSON-formatted string of all group IDs and their names.</li>
  241. </ul>
  242. </ul>
  243. <br>
  244. <a name="TradfriGatewayattr"></a>
  245. <b>Attributes</b>
  246. <ul>
  247. <code>attr &lt;name&gt; &lt;attribute&gt; &lt;value&gt;</code>
  248. <br><br>
  249. See <a href="http://fhem.de/commandref.html#attr">commandref#attr</a> for more info about
  250. the attr command.
  251. <br><br>
  252. Attributes:
  253. <ul>
  254. <li><i></i><br>
  255. There are no custom attributes implemented
  256. </li>
  257. </ul>
  258. </ul>
  259. </ul>
  260. =end html
  261. =cut