]> git.basschouten.com Git - openhab-addons.git/blob
651e8d016afbd3f7779cfbbbb617906334caaeca
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.homematic.internal.communicator.server;
14
15 import java.io.EOFException;
16 import java.io.IOException;
17 import java.net.Socket;
18
19 import org.openhab.binding.homematic.internal.common.HomematicConfig;
20 import org.openhab.binding.homematic.internal.communicator.message.BinRpcMessage;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * Reads a BIN-RPC message from the socket and handles the method call.
26  *
27  * @author Gerhard Riegler - Initial contribution
28  */
29 public class BinRpcResponseHandler implements Runnable {
30     private final Logger logger = LoggerFactory.getLogger(BinRpcResponseHandler.class);
31
32     private Socket socket;
33     private RpcResponseHandler<byte[]> rpcResponseHandler;
34     private HomematicConfig config;
35     private long created;
36
37     public BinRpcResponseHandler(Socket socket, RpcResponseHandler<byte[]> rpcResponseHandler, HomematicConfig config) {
38         this.socket = socket;
39         this.rpcResponseHandler = rpcResponseHandler;
40         this.config = config;
41         this.created = System.currentTimeMillis();
42     }
43
44     /**
45      * Reads the event from the Homematic gateway and handles the method call.
46      */
47     @Override
48     public void run() {
49         try {
50             boolean isMaxAliveReached;
51             do {
52                 BinRpcMessage message = new BinRpcMessage(socket.getInputStream(), true, config.getEncoding());
53                 logger.trace("Event BinRpcMessage: {}", message);
54                 byte[] returnValue = rpcResponseHandler.handleMethodCall(message.getMethodName(),
55                         message.getResponseData());
56                 if (returnValue != null) {
57                     socket.getOutputStream().write(returnValue);
58                 }
59                 isMaxAliveReached = System.currentTimeMillis() - created > (config.getSocketMaxAlive() * 1000);
60             } while (!isMaxAliveReached);
61
62         } catch (EOFException eof) {
63             // ignore
64         } catch (Exception e) {
65             logger.warn("{}", e.getMessage(), e);
66         } finally {
67             try {
68                 socket.close();
69             } catch (IOException ioe) {
70                 // ignore
71             }
72         }
73     }
74 }