]> git.basschouten.com Git - openhab-addons.git/blob
4bcccd81fa8c24f243f26f42a9c066fb4e4cb5d5
[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.rotel.internal.communication;
14
15 import java.io.InterruptedIOException;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.binding.rotel.internal.RotelException;
19 import org.openhab.binding.rotel.internal.protocol.RotelAbstractProtocolHandler;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * A class that reads messages from the Rotel device in a dedicated thread
25  *
26  * @author Laurent Garnier - Initial contribution
27  */
28 @NonNullByDefault
29 public class RotelReaderThread extends Thread {
30
31     private static final int READ_BUFFER_SIZE = 16;
32
33     private final Logger logger = LoggerFactory.getLogger(RotelReaderThread.class);
34
35     private final RotelConnector connector;
36     private final RotelAbstractProtocolHandler protocolHandler;
37
38     /**
39      * Constructor
40      *
41      * @param connector the connector to read input data
42      * @param protocolHandler the protocol handler
43      * @param threadName the name of the thread
44      */
45     public RotelReaderThread(RotelConnector connector, RotelAbstractProtocolHandler protocolHandler,
46             String threadName) {
47         super(threadName);
48         this.connector = connector;
49         this.protocolHandler = protocolHandler;
50     }
51
52     @Override
53     public void run() {
54         logger.debug("Data listener started");
55
56         byte[] readDataBuffer = new byte[READ_BUFFER_SIZE];
57
58         try {
59             while (!Thread.interrupted()) {
60                 int len = connector.readInput(readDataBuffer);
61                 if (len > 0) {
62                     protocolHandler.handleIncomingData(readDataBuffer, len);
63                 }
64             }
65         } catch (InterruptedIOException e) {
66             Thread.currentThread().interrupt();
67             logger.debug("Interrupted via InterruptedIOException");
68         } catch (RotelException e) {
69             logger.debug("Reading failed: {}", e.getMessage(), e);
70             protocolHandler.handleInIncomingError();
71         }
72
73         logger.debug("Data listener stopped");
74     }
75 }