2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.teleinfo.internal.serial;
15 import java.io.IOException;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.teleinfo.internal.data.Frame;
20 import org.openhab.binding.teleinfo.internal.reader.io.TeleinfoInputStream;
21 import org.openhab.binding.teleinfo.internal.reader.io.serialport.InvalidFrameException;
22 import org.openhab.core.io.transport.serial.SerialPort;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * The {@link TeleinfoReceiveThread} class defines a thread to decode and fire Teleinfo frames for Serial controller.
29 * @author Nicolas SIBERIL - Initial contribution
32 public class TeleinfoReceiveThread extends Thread {
34 private final Logger logger = LoggerFactory.getLogger(TeleinfoReceiveThread.class);
36 private SerialPort serialPort;
37 private @Nullable TeleinfoReceiveThreadListener listener;
38 private boolean autoRepairInvalidADPSgroupLine;
40 public TeleinfoReceiveThread(SerialPort serialPort, final TeleinfoSerialControllerHandler listener,
41 boolean autoRepairInvalidADPSgroupLine) {
42 super("OH-binding-TeleinfoReceiveThread-" + listener.getThing().getUID().getId());
44 this.serialPort = serialPort;
45 this.listener = listener;
46 this.autoRepairInvalidADPSgroupLine = autoRepairInvalidADPSgroupLine;
51 try (TeleinfoInputStream teleinfoStream = new TeleinfoInputStream(serialPort.getInputStream(),
52 autoRepairInvalidADPSgroupLine)) {
53 while (!interrupted()) {
54 TeleinfoReceiveThreadListener listener = this.listener;
55 if (listener != null) {
57 Frame nextFrame = teleinfoStream.readNextFrame();
58 if (nextFrame != null) {
59 listener.onFrameReceived(nextFrame);
61 } catch (InvalidFrameException e) {
62 logger.warn("Got invalid frame. Detail: \"{}\"", e.getLocalizedMessage());
63 listener.onInvalidFrameReceived(this, e);
64 } catch (IOException e) {
65 logger.warn("Got I/O exception. Detail: \"{}\"", e.getLocalizedMessage(), e);
66 listener.onSerialPortInputStreamIOException(this, e);
68 } catch (IllegalStateException e) {
69 logger.warn("Got illegal state exception", e);
73 } catch (IOException e) {
74 logger.warn("An error occurred during serial port input stream opening", e);
77 serialPort.removeEventListener();
80 public @Nullable TeleinfoReceiveThreadListener getListener() {
84 public void setListener(@Nullable TeleinfoReceiveThreadListener listener) {
85 this.listener = listener;