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.concurrent.Semaphore;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.binding.dsmr.internal.device.connector.DSMRConnectorErrorEvent;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * The {@link DSMRDeviceRunnable} runs a {@link DSMRDevice} and blocks until it is restarted or shutdown. If it is
24 * restarted it will restart the {@link DSMRDevice}. If it is shutdown the run will end. By using a semaphore to restart
25 * and shutdown this class handles the actual {@link DSMRDevice}, while threads calling restart and shutdown can finish
28 * @author Hilbrand Bouwkamp - Initial contribution
31 public class DSMRDeviceRunnable implements Runnable {
32 private final Logger logger = LoggerFactory.getLogger(DSMRDeviceRunnable.class);
33 private final Semaphore semaphore = new Semaphore(0);
34 private final DSMRDevice device;
35 private final DSMREventListener portEventListener;
38 * Keeps state of running. If false run will stop.
40 private boolean running;
45 * @param device the device to control
46 * @param eventListener listener to used ot report errors.
48 public DSMRDeviceRunnable(DSMRDevice device, DSMREventListener eventListener) {
50 this.portEventListener = eventListener;
54 * Sets state to restart the dsmr device.
56 public void restart() {
61 * Sets state to shutdown the dsmr device.
69 * Controls the dsmr device. Runs until shutdown.
76 while (running && !Thread.interrupted()) {
78 // Just drain all other permits to make sure it's not called twice
79 semaphore.drainPermits();
81 logger.trace("Restarting device");
85 logger.trace("Device shutdown");
86 } catch (RuntimeException e) {
87 logger.warn("DSMRDeviceRunnable stopped with a RuntimeException", e);
88 portEventListener.handleErrorEvent(DSMRConnectorErrorEvent.READ_ERROR);
89 } catch (InterruptedException e) {
90 Thread.currentThread().interrupt();
97 * Wrapper around semaphore to only release when no permits available.
99 private void releaseSemaphore() {
100 synchronized (semaphore) {
101 if (semaphore.availablePermits() == 0) {