2 * Copyright (c) 2010-2023 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.dsmr.internal.device;
15 import java.util.Optional;
16 import java.util.concurrent.Semaphore;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.binding.dsmr.internal.device.connector.DSMRErrorStatus;
20 import org.openhab.binding.dsmr.internal.device.p1telegram.P1TelegramListener;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * The {@link DSMRDeviceRunnable} runs a {@link DSMRDevice} and blocks until it is restarted or shutdown. If it is
26 * restarted it will restart the {@link DSMRDevice}. If it is shutdown the run will end. By using a semaphore to restart
27 * and shutdown this class handles the actual {@link DSMRDevice}, while threads calling restart and shutdown can finish
30 * @author Hilbrand Bouwkamp - Initial contribution
33 public class DSMRDeviceRunnable implements Runnable {
34 private final Logger logger = LoggerFactory.getLogger(DSMRDeviceRunnable.class);
35 private final Semaphore semaphore = new Semaphore(0);
36 private final DSMRDevice device;
37 private final P1TelegramListener portEventListener;
40 * Keeps state of running. If false run will stop.
42 private boolean running;
47 * @param device the device to control
48 * @param eventListener listener to used ot report errors.
50 public DSMRDeviceRunnable(final DSMRDevice device, final P1TelegramListener eventListener) {
52 this.portEventListener = eventListener;
56 * Sets state to restart the dsmr device.
58 public void restart() {
63 * Sets state to shutdown the dsmr device.
71 * Controls the dsmr device. Runs until shutdown.
78 while (running && !Thread.interrupted()) {
80 // Just drain all other permits to make sure it's not called twice
81 semaphore.drainPermits();
83 logger.trace("Restarting device");
87 logger.trace("Device shutdown");
88 } catch (final RuntimeException e) {
89 logger.warn("DSMRDeviceRunnable stopped with a RuntimeException", e);
90 portEventListener.onError(DSMRErrorStatus.SERIAL_DATA_READ_ERROR,
91 Optional.ofNullable(e.getMessage()).orElse(""));
92 } catch (final InterruptedException e) {
93 Thread.currentThread().interrupt();
100 * Wrapper around semaphore to only release when no permits available.
102 private void releaseSemaphore() {
103 synchronized (semaphore) {
104 if (semaphore.availablePermits() == 0) {