From a95550e2c1ea1300a15af4a00ba305c3480d5ce2 Mon Sep 17 00:00:00 2001 From: Dan Cunningham Date: Fri, 29 Mar 2019 13:35:57 -0700 Subject: [PATCH 1/3] Formatting changes, clean up executors, remove dead code, other mingor chnages Signed-off-by: Dan Cunningham --- .../META-INF/MANIFEST.MF | 2 +- .../OSGI-INF/OmnilinkDiscoveryService.xml | 21 - .../org.openhab.binding.omnilink/pom.xml | 2 +- .../OmnilinkBridgeDiscoveryService.java | 38 - .../omnilink/handler/AudioSourceHandler.java | 124 ++-- .../omnilink/handler/ButtonHandler.java | 15 +- .../omnilink/handler/ConsoleHandler.java | 15 +- .../omnilink/handler/EventLogPoller.java | 86 --- .../handler/OmnilinkBridgeHandler.java | 163 +++-- .../omnilink/handler/TemperatureFormat.java | 2 - .../internal/OmnilinkHandlerFactory.java | 23 +- .../internal/model/OSHISysteminfo.java | 675 ------------------ 12 files changed, 140 insertions(+), 1026 deletions(-) delete mode 100644 addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkDiscoveryService.xml delete mode 100644 addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/discovery/OmnilinkBridgeDiscoveryService.java delete mode 100644 addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/EventLogPoller.java delete mode 100644 addons/binding/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/model/OSHISysteminfo.java diff --git a/addons/binding/org.openhab.binding.omnilink/META-INF/MANIFEST.MF b/addons/binding/org.openhab.binding.omnilink/META-INF/MANIFEST.MF index 0fc9488b582ee..1d4862cbd7c58 100644 --- a/addons/binding/org.openhab.binding.omnilink/META-INF/MANIFEST.MF +++ b/addons/binding/org.openhab.binding.omnilink/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: Omnilink Binding Bundle-SymbolicName: org.openhab.binding.omnilink;singleton:=true Bundle-Vendor: openHAB -Bundle-Version: 2.4.0.qualifier +Bundle-Version: 2.5.0.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.8 Bundle-ClassPath: ., lib/gson-2.8.2.jar, diff --git a/addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkDiscoveryService.xml b/addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkDiscoveryService.xml deleted file mode 100644 index 4d9a364ced74d..0000000000000 --- a/addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkDiscoveryService.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - diff --git a/addons/binding/org.openhab.binding.omnilink/pom.xml b/addons/binding/org.openhab.binding.omnilink/pom.xml index 55f193bc0c8b2..dc5816dc008ca 100644 --- a/addons/binding/org.openhab.binding.omnilink/pom.xml +++ b/addons/binding/org.openhab.binding.omnilink/pom.xml @@ -6,7 +6,7 @@ org.openhab.binding pom - 2.4.0-SNAPSHOT + 2.5.0-SNAPSHOT org.openhab.binding diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/discovery/OmnilinkBridgeDiscoveryService.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/discovery/OmnilinkBridgeDiscoveryService.java deleted file mode 100644 index 7fb61f83d0e66..0000000000000 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/discovery/OmnilinkBridgeDiscoveryService.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2010-2018 by the respective copyright holders. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.openhab.binding.omnilink.discovery; - -import java.util.Collections; - -import org.eclipse.smarthome.config.discovery.AbstractDiscoveryService; -import org.eclipse.smarthome.core.thing.ThingTypeUID; -import org.openhab.binding.omnilink.OmnilinkBindingConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author Craig Hamilton - * - */ -public class OmnilinkBridgeDiscoveryService extends AbstractDiscoveryService { - private static final Logger logger = LoggerFactory.getLogger(OmnilinkBridgeDiscoveryService.class); - private static final int DISCOVER_TIMEOUT_SECONDS = 30; - - public OmnilinkBridgeDiscoveryService() { - super(Collections.singleton(new ThingTypeUID(OmnilinkBindingConstants.BINDING_ID, "-")), - DISCOVER_TIMEOUT_SECONDS, false); - } - - @Override - protected void startScan() { - logger.debug("start scan called for omnilink bridge"); - - } -} \ No newline at end of file diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AudioSourceHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AudioSourceHandler.java index f3cae34da8f45..010e914e6c3b7 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AudioSourceHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AudioSourceHandler.java @@ -8,8 +8,6 @@ */ package org.openhab.binding.omnilink.handler; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -32,35 +30,16 @@ public class AudioSourceHandler extends AbstractOmnilinkHandler { private final static Logger logger = LoggerFactory.getLogger(AudioSourceHandler.class); - private final static long POLL_DELAY = 5; // 5 Second polling - - private static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - private ScheduledFuture scheduledPolling = null; - public static synchronized void shutdownExecutor() { - logger.debug("Shutting down audio polling executor service"); - executorService.shutdownNow(); - } - - private static synchronized void startExecutor() { - if (executorService.isShutdown()) { - logger.debug("Starting audio polling executor service"); - executorService = Executors.newSingleThreadScheduledExecutor(); - } - } - public AudioSourceHandler(Thing thing) { super(thing); } @Override public void initialize() { - if (scheduledPolling != null) { - scheduledPolling.cancel(false); - } - + cancelPolling(); boolean autoStart = ((Boolean) getThing().getConfiguration() .get(OmnilinkBindingConstants.THING_PROPERTIES_AUTO_START)).booleanValue(); int sourceNumber = getThingNumber(); @@ -81,12 +60,9 @@ public synchronized void dispose() { } private synchronized void cancelPolling() { - if (scheduledPolling != null) { - if (scheduledPolling.isDone() == false) { - int sourceNumber = getThingNumber(); - logger.debug("Cancelling polling for Audio Source {}", sourceNumber); - scheduledPolling.cancel(false); - } + if (scheduledPolling != null && !scheduledPolling.isDone()) { + logger.debug("Cancelling polling for Audio Source {}", getThingNumber()); + scheduledPolling.cancel(false); } } @@ -94,15 +70,13 @@ private synchronized void schedulePolling() { cancelPolling(); int sourceNumber = getThingNumber(); logger.debug("Scheduling polling for Audio Source {}", sourceNumber); - startExecutor(); - scheduledPolling = executorService.scheduleWithFixedDelay(new PollAudioSource(getThingNumber()), 0, POLL_DELAY, + scheduledPolling = super.scheduler.scheduleWithFixedDelay(() -> pollAudioSource(), 0, POLL_DELAY, TimeUnit.SECONDS); } @Override public void handleCommand(ChannelUID channelUID, Command command) { String channelID = channelUID.getId(); - switch (channelID) { case OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_POLLING: if (command == RefreshType.REFRESH) { @@ -124,61 +98,49 @@ public void handleCommand(ChannelUID channelUID, Command command) { default: logger.warn("Channel ID ({}) not processed", channelID); break; - } - } - private class PollAudioSource implements Runnable { - - private final int sourceNumber; - - private PollAudioSource(int sourceNumber) { - this.sourceNumber = sourceNumber; - } - - @Override - public void run() { - logger.debug("Polling Audio Source {} Status", sourceNumber); - try { - int position = 0; - Message message; - while ((message = getOmnilinkBridgeHander().requestAudioSourceStatus(sourceNumber, position)) - .getMessageType() == Message.MESG_TYPE_AUDIO_SOURCE_STATUS) { - AudioSourceStatus audioSourceStatus = (AudioSourceStatus) message; - position = audioSourceStatus.getPosition(); - switch (position) { - case 1: - updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT1, - new StringType(audioSourceStatus.getSourceData())); - break; - case 2: - updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT2, - new StringType(audioSourceStatus.getSourceData())); - break; - case 3: - updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT3, - new StringType(audioSourceStatus.getSourceData())); - break; - case 4: - updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT4, - new StringType(audioSourceStatus.getSourceData())); - break; - case 5: - updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT5, - new StringType(audioSourceStatus.getSourceData())); - break; - case 6: - updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT6, - new StringType(audioSourceStatus.getSourceData())); - break; - } - + public void pollAudioSource() { + int sourceNumber = getThingNumber(); + logger.debug("Polling Audio Source {} Status", sourceNumber); + try { + int position = 0; + Message message; + while ((message = getOmnilinkBridgeHander().requestAudioSourceStatus(sourceNumber, position)) + .getMessageType() == Message.MESG_TYPE_AUDIO_SOURCE_STATUS) { + AudioSourceStatus audioSourceStatus = (AudioSourceStatus) message; + position = audioSourceStatus.getPosition(); + switch (position) { + case 1: + updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT1, + new StringType(audioSourceStatus.getSourceData())); + break; + case 2: + updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT2, + new StringType(audioSourceStatus.getSourceData())); + break; + case 3: + updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT3, + new StringType(audioSourceStatus.getSourceData())); + break; + case 4: + updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT4, + new StringType(audioSourceStatus.getSourceData())); + break; + case 5: + updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT5, + new StringType(audioSourceStatus.getSourceData())); + break; + case 6: + updateState(OmnilinkBindingConstants.CHANNEL_AUDIO_SOURCE_TEXT6, + new StringType(audioSourceStatus.getSourceData())); + break; } - } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) { - logger.warn("Exception Polling Audio Status", e); - } + } + } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) { + logger.warn("Exception Polling Audio Status", e); } } diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ButtonHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ButtonHandler.java index 30ff71fb7c7c9..c6b425472e7e0 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ButtonHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ButtonHandler.java @@ -8,8 +8,6 @@ */ package org.openhab.binding.omnilink.handler; -import java.util.Optional; - import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.types.Command; @@ -22,14 +20,13 @@ import com.digitaldan.jomnilinkII.OmniInvalidResponseException; import com.digitaldan.jomnilinkII.OmniUnknownMessageTypeException; import com.digitaldan.jomnilinkII.MessageTypes.CommandMessage; -import com.digitaldan.jomnilinkII.MessageTypes.statuses.Status; /** * * @author Craig Hamilton * */ -public class ButtonHandler extends AbstractOmnilinkStatusHandler { +public class ButtonHandler extends AbstractOmnilinkHandler { private Logger logger = LoggerFactory.getLogger(ButtonHandler.class); public ButtonHandler(Thing thing) { @@ -55,14 +52,4 @@ public void buttonActivated() { OmnilinkBindingConstants.TRIGGER_CHANNEL_BUTTON_ACTIVATED_EVENT); triggerChannel(activateChannel); } - - @Override - protected Optional retrieveStatus() { - return Optional.empty(); - } - - @Override - protected void updateChannels(Status t) { - // No links for buttons - } } diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ConsoleHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ConsoleHandler.java index 2cb7a3f81d53c..ced4b3630ffc7 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ConsoleHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/ConsoleHandler.java @@ -8,8 +8,6 @@ */ package org.openhab.binding.omnilink.handler; -import java.util.Optional; - import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.thing.ChannelUID; @@ -22,14 +20,13 @@ import com.digitaldan.jomnilinkII.OmniInvalidResponseException; import com.digitaldan.jomnilinkII.OmniUnknownMessageTypeException; import com.digitaldan.jomnilinkII.MessageTypes.CommandMessage; -import com.digitaldan.jomnilinkII.MessageTypes.statuses.Status; /** * * @author Craig Hamilton * */ -public class ConsoleHandler extends AbstractOmnilinkStatusHandler { +public class ConsoleHandler extends AbstractOmnilinkHandler { private Logger logger = LoggerFactory.getLogger(ConsoleHandler.class); public ConsoleHandler(Thing thing) { @@ -63,14 +60,4 @@ public void handleCommand(ChannelUID channelUID, Command command) { } } - - @Override - protected Optional retrieveStatus() { - return Optional.empty(); - } - - @Override - protected void updateChannels(Status t) { - // No Status. - } } diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/EventLogPoller.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/EventLogPoller.java deleted file mode 100644 index eb4a7554dd33a..0000000000000 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/EventLogPoller.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2010-2018 by the respective copyright holders. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.openhab.binding.omnilink.handler; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.digitaldan.jomnilinkII.Message; -import com.digitaldan.jomnilinkII.OmniInvalidResponseException; -import com.digitaldan.jomnilinkII.OmniUnknownMessageTypeException; -import com.digitaldan.jomnilinkII.MessageTypes.EventLogData; -import com.google.gson.Gson; - -public class EventLogPoller { - - private final static Logger logger = LoggerFactory.getLogger(AudioSourceHandler.class); - - private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - - public EventLogPoller(OmnilinkBridgeHandler bridgeHandler, int pollInterval) { - if (pollInterval < 1) { - throw new IllegalArgumentException("Poll interval must be greater than 0"); - } else { - executorService.scheduleWithFixedDelay(new PollLog(bridgeHandler), pollInterval, pollInterval, - TimeUnit.SECONDS); - } - } - - public void shutdown() { - logger.debug("Terminating EventLogPoller"); - executorService.shutdownNow(); - } - - private static class PollLog implements Runnable { - - private OmnilinkBridgeHandler bridgeHandler; - - private final Gson gson = new Gson(); - - private int eventLogNumber = 0; - - private PollLog(OmnilinkBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - - @Override - public void run() { - - // On first run, direction is -1 (most recent event), after its 1 for the next log message - - try { - Message message; - do { - logger.debug("Polling for event log messages."); - int direction = eventLogNumber == 0 ? -1 : 1; - message = bridgeHandler.reqEventLogData(eventLogNumber, direction); - if (message.getMessageType() == Message.MESG_TYPE_EVENT_LOG_DATA) { - EventLogData logData = (EventLogData) message; - logger.debug("Processing event log message number: {}", logData.getEventNumber()); - eventLogNumber = logData.getEventNumber(); - String json = gson.toJson(logData); - bridgeHandler.eventLogMessage(json); - } - } while (message.getMessageType() != Message.MESG_TYPE_END_OF_DATA); - - } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) { - logger.warn("Exception Polling Event Log", e); - } catch (NullPointerException e) { - logger.debug("NPE. Omni connection probably not set up.", e); - } - - } - - } - -} diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java index 625800d69252c..d162d534cbfec 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java @@ -29,7 +29,6 @@ import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler; -import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.types.Command; import org.openhab.binding.omnilink.OmnilinkBindingConstants; import org.openhab.binding.omnilink.config.OmnilinkBridgeConfig; @@ -45,6 +44,7 @@ import com.digitaldan.jomnilinkII.OmniNotConnectedException; import com.digitaldan.jomnilinkII.OmniUnknownMessageTypeException; import com.digitaldan.jomnilinkII.MessageTypes.CommandMessage; +import com.digitaldan.jomnilinkII.MessageTypes.EventLogData; import com.digitaldan.jomnilinkII.MessageTypes.ObjectStatus; import com.digitaldan.jomnilinkII.MessageTypes.SecurityCodeValidation; import com.digitaldan.jomnilinkII.MessageTypes.SystemFeatures; @@ -62,42 +62,35 @@ import com.digitaldan.jomnilinkII.MessageTypes.systemEvents.AllOnOffEvent; import com.digitaldan.jomnilinkII.MessageTypes.systemEvents.ButtonEvent; import com.digitaldan.jomnilinkII.MessageTypes.systemEvents.SystemEvent; +import com.google.gson.Gson; /** * * @author Craig Hamilton * */ -public class OmnilinkBridgeHandler extends BaseBridgeHandler implements NotificationListener { +public class OmnilinkBridgeHandler extends BaseBridgeHandler implements NotificationListener, DisconnectListener { private Logger logger = LoggerFactory.getLogger(OmnilinkBridgeHandler.class); private Connection omniConnection; private @Nullable ScheduledFuture connectJob; + private @Nullable ScheduledFuture eventPollingJob; private final int autoReconnectPeriod = 60; private TemperatureFormat temperatureFormat; private Optional audioPlayer = Optional.empty(); - private Optional eventLogPoller = Optional.empty(); - private final DisconnectListener retryingDisconnectListener; + private final Gson gson = new Gson(); + private int eventLogNumber = 0; public OmnilinkBridgeHandler(Bridge bridge) { super(bridge); - retryingDisconnectListener = new DisconnectListener() { - @Override - public void notConnectedEvent(Exception e) { - logger.debug("Received omnilink not connected event: {}", e.getMessage()); - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); - scheduleReconnectJob(); - } - }; } public void sendOmnilinkCommand(final int message, final int param1, final int param2) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { - try { omniConnection.controllerCommand(message, param1, param2); } catch (IOException | OmniNotConnectedException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } @@ -108,10 +101,9 @@ public SecurityCodeValidation reqSecurityCodeValidation(int area, int digit1, in try { return omniConnection.reqSecurityCodeValidation(area, digit1, digit2, digit3, digit4); } catch (IOException | OmniNotConnectedException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } - } public void activateKeypadEmergency(int area, int emergencyType) @@ -119,10 +111,9 @@ public void activateKeypadEmergency(int area, int emergencyType) try { omniConnection.activateKeypadEmergency(area, emergencyType); } catch (IOException | OmniNotConnectedException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } - } public SystemInformation reqSystemInformation() @@ -130,7 +121,7 @@ public SystemInformation reqSystemInformation() try { return omniConnection.reqSystemInformation(); } catch (IOException | OmniNotConnectedException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } } @@ -140,7 +131,7 @@ public SystemFormats reqSystemFormats() try { return omniConnection.reqSystemFormats(); } catch (IOException | OmniNotConnectedException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } } @@ -150,7 +141,7 @@ private SystemFeatures reqSystemFeatures() try { return omniConnection.reqSystemFeatures(); } catch (IOException | OmniNotConnectedException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } } @@ -206,7 +197,6 @@ public void handleCommand(ChannelUID channelUID, Command command) { } private void makeOmnilinkConnection() { - if (this.omniConnection != null && this.omniConnection.connected()) { return; } @@ -217,9 +207,8 @@ private void makeOmnilinkConnection() { omniConnection = new Connection(config.getIpAddress(), config.getPort(), config.getKey1() + ":" + config.getKey2()); temperatureFormat = TemperatureFormat.valueOf(reqSystemFormats().getTempFormat()); - // HAI only supports one audio player - cycle through features until we find a feature that is - // an - // audio player. + // HAI only supports one audio player - cycle through features until we find a feature that is an audio + // player. audioPlayer = reqSystemFeatures().getFeatures().stream() .map(featureCode -> AudioPlayer.getAudioPlayerForFeatureCode(featureCode)) .filter(Optional::isPresent).findFirst().orElse(Optional.empty()); @@ -227,20 +216,18 @@ private void makeOmnilinkConnection() { temperatureFormat = TemperatureFormat.valueOf(reqSystemFormats().getTempFormat()); if (config.getLogPollingSeconds() > 0) { - eventLogPoller = Optional - .of(new EventLogPoller(OmnilinkBridgeHandler.this, config.getLogPollingSeconds())); + startEventPolling(config.getLogPollingSeconds()); } omniConnection.addNotificationListener(OmnilinkBridgeHandler.this); - omniConnection.addDisconnectListener(retryingDisconnectListener); + omniConnection.addDisconnectListener(this); omniConnection.enableNotifications(); updateStatus(ThingStatus.ONLINE); cancelReconnectJob(false); } catch (UnknownHostException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); - logger.debug("{}", e.toString()); - // throw e; + logger.debug("Error connecting to omni {}", e); } catch (IOException e) { if (e.getCause() != null && e.getCause().getMessage().contains("Connection timed out")) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, @@ -252,14 +239,11 @@ private void makeOmnilinkConnection() { } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } - logger.debug("{}", e.toString()); - // throw e; + logger.debug("Error connecting to omni {}", e); } catch (Exception e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); - logger.debug("{}", e.toString()); - // throw e; + setOfflineAndReconnect(e.getMessage()); + logger.debug("Error connecting to omni {}", e); } - } @SuppressWarnings("null") @@ -309,7 +293,6 @@ public void objectStatusNotification(ObjectStatus objectStatus) { // Aux Sensors can be either temp or humidity, need to check both. Optional tempThing = getChildThing(OmnilinkBindingConstants.THING_TYPE_TEMP_SENSOR, status.getNumber()); - if (tempThing.isPresent()) { tempThing.map(Thing::getHandler) .ifPresent(theHandler -> ((TempSensorHandler) theHandler).updateChannels(auxSensorStatus)); @@ -318,21 +301,13 @@ public void objectStatusNotification(ObjectStatus objectStatus) { status.getNumber()); humidityThing.map(Thing::getHandler).ifPresent( theHandler -> ((HumiditySensorHandler) theHandler).updateChannels(auxSensorStatus)); - } - } else { logger.debug("Received Object Status Notification that was not processed: {}", objectStatus); } - } } - @Override - public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) { - logger.debug("childHandlerDisposed called with '{}', childThing '{}'", childHandler, childThing); - } - @SuppressWarnings("null") @Override public void systemEventNotification(SystemEvent event) { @@ -402,9 +377,14 @@ public void systemEventNotification(SystemEvent event) { } } + @Override + public void notConnectedEvent(Exception e) { + logger.debug("Received omnilink not connected event: {}", e.getMessage()); + setOfflineAndReconnect(e.getMessage()); + } + private void getSystemStatus() throws IOException, OmniNotConnectedException, OmniInvalidResponseException, OmniUnknownMessageTypeException { - if (omniConnection != null) { SystemStatus status = omniConnection.reqSystemStatus(); logger.debug("received system status: {}", status); @@ -416,10 +396,8 @@ private void getSystemStatus() throws IOException, OmniNotConnectedException, Om .append(String.format("%02d", status.getMinute())).append(":") .append(String.format("%02d", status.getSecond())).toString(); DateTimeType sysDateTime = new DateTimeType(dateString); - updateState(OmnilinkBindingConstants.CHANNEL_SYSTEMDATE, new DateTimeType(dateString)); logger.debug("System date is: {}", sysDateTime); - } } @@ -428,10 +406,9 @@ public Message reqObjectProperties(int objectType, int objectNum, int direction, try { return omniConnection.reqObjectProperties(objectType, objectNum, direction, filter1, filter2, filter3); } catch (OmniNotConnectedException | IOException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } - } public Message requestAudioSourceStatus(final int source, final int position) @@ -439,7 +416,7 @@ public Message requestAudioSourceStatus(final int source, final int position) try { return omniConnection.reqAudioSourceStatus(source, position); } catch (OmniNotConnectedException | IOException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } } @@ -450,7 +427,7 @@ public ObjectStatus requestObjectStatus(final int objType, final int startObject try { return omniConnection.reqObjectStatus(objType, startObject, endObject, extended); } catch (OmniNotConnectedException | IOException e) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage()); + setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); } } @@ -472,15 +449,12 @@ public void channelLinked(ChannelUID channelUID) { @Override public void dispose() { updateStatus(ThingStatus.OFFLINE); + cancelReconnectJob(true); + cancelEventPolling(); if (omniConnection != null) { - // must remove this before disconnect, as this tries to create another connection - omniConnection.removeDisconnecListener(retryingDisconnectListener); + omniConnection.removeDisconnecListener(this); omniConnection.disconnect(); } - AudioSourceHandler.shutdownExecutor(); - if (eventLogPoller.isPresent()) { - eventLogPoller.get().shutdown(); - } } private Optional getChildThing(ThingTypeUID type, int number) { @@ -514,34 +488,18 @@ public Message reqEventLogData(int eventNumber, int direction) updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage()); throw new BridgeOfflineException(e); } - - } - - /** - * Post a new event log message - * - * @param json Message in json format to post - */ - public void eventLogMessage(String json) { - logger.debug("Receieved event log message: {}", json); - updateState(OmnilinkBindingConstants.CHANNEL_EVENT_LOG, new StringType(json)); - } @Override public void initialize() { - if (!scheduleReconnectJob()) { - makeOmnilinkConnection(); - } + scheduleReconnectJob(); } - private boolean scheduleReconnectJob() { - if (autoReconnectPeriod > 0) { + private void scheduleReconnectJob() { + ScheduledFuture currentReconnectJob = connectJob; + if (currentReconnectJob == null || currentReconnectJob.isDone()) { connectJob = super.scheduler.scheduleWithFixedDelay(() -> makeOmnilinkConnection(), 0, autoReconnectPeriod, TimeUnit.SECONDS); - return true; - } else { - return false; } } @@ -549,8 +507,55 @@ private void cancelReconnectJob(boolean kill) { ScheduledFuture currentReconnectJob = connectJob; if (currentReconnectJob != null) { currentReconnectJob.cancel(kill); - connectJob = null; } } + private void setOfflineAndReconnect(String message) { + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message); + cancelEventPolling(); + if (omniConnection != null) { + omniConnection.removeDisconnecListener(this); + } + scheduleReconnectJob(); + } + + private void startEventPolling(int interval) { + ScheduledFuture eventPollingJobFuture = eventPollingJob; + if (eventPollingJobFuture == null || eventPollingJobFuture.isDone()) { + eventLogNumber = 0; + eventPollingJob = super.scheduler.scheduleWithFixedDelay(() -> pollEvents(), 0, interval, TimeUnit.SECONDS); + } + } + + private void cancelEventPolling() { + ScheduledFuture eventPollingJobFuture = eventPollingJob; + if (eventPollingJobFuture != null) { + eventPollingJobFuture.cancel(true); + } + } + + private void pollEvents() { + // On first run, direction is -1 (most recent event), after its 1 for the next log message + try { + Message message; + do { + logger.debug("Polling for event log messages."); + int direction = eventLogNumber == 0 ? -1 : 1; + message = reqEventLogData(eventLogNumber, direction); + if (message.getMessageType() == Message.MESG_TYPE_EVENT_LOG_DATA) { + EventLogData logData = (EventLogData) message; + logger.debug("Processing event log message number: {}", logData.getEventNumber()); + eventLogNumber = logData.getEventNumber(); + String json = gson.toJson(logData); + logger.debug("Receieved event log message: {}", json); + updateState(OmnilinkBindingConstants.CHANNEL_EVENT_LOG, new StringType(json)); + } + } while (message.getMessageType() != Message.MESG_TYPE_END_OF_DATA); + + } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) { + logger.warn("Exception Polling Event Log", e); + } catch (NullPointerException e) { + logger.debug("NPE. Omni connection probably not set up.", e); + } + } } diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/TemperatureFormat.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/TemperatureFormat.java index eaec0704dc0cb..c0ca2e054c1c7 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/TemperatureFormat.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/TemperatureFormat.java @@ -79,7 +79,5 @@ public static TemperatureFormat valueOf(int tempFormat) { } else { throw new IllegalArgumentException(); } - } - } diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java index a11b41ec72ea6..432412a100aa6 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java @@ -51,6 +51,14 @@ */ public class OmnilinkHandlerFactory extends BaseThingHandlerFactory { + private static final Logger logger = LoggerFactory.getLogger(OmnilinkHandlerFactory.class); + private final static Set SUPPORTED_THING_TYPES_UIDS = Collections + .unmodifiableSet(Stream.of(THING_TYPE_OMNI_AREA, THING_TYPE_ZONE, THING_TYPE_BRIDGE, THING_TYPE_FLAG, + THING_TYPE_ROOM, THING_TYPE_BUTTON, THING_TYPE_UNIT_UPB, THING_TYPE_THERMOSTAT, THING_TYPE_CONSOLE, + THING_TYPE_AUDIO_ZONE, THING_TYPE_AUDIO_SOURCE, THING_TYPE_TEMP_SENSOR, THING_TYPE_HUMIDITY_SENSOR, + THING_TYPE_LOCK).collect(Collectors.toSet())); + private final Map> discoveryServiceRegistrations = new HashMap>(); + @Override protected void removeHandler(ThingHandler thingHandler) { // if the omnilink bridge, let's fix up discovery @@ -62,16 +70,6 @@ protected void removeHandler(ThingHandler thingHandler) { } } - private static final Logger logger = LoggerFactory.getLogger(OmnilinkHandlerFactory.class); - - private final static Set SUPPORTED_THING_TYPES_UIDS = Collections - .unmodifiableSet(Stream.of(THING_TYPE_OMNI_AREA, THING_TYPE_ZONE, THING_TYPE_BRIDGE, THING_TYPE_FLAG, - THING_TYPE_ROOM, THING_TYPE_BUTTON, THING_TYPE_UNIT_UPB, THING_TYPE_THERMOSTAT, THING_TYPE_CONSOLE, - THING_TYPE_AUDIO_ZONE, THING_TYPE_AUDIO_SOURCE, THING_TYPE_TEMP_SENSOR, THING_TYPE_HUMIDITY_SENSOR, - THING_TYPE_LOCK).collect(Collectors.toSet())); - - private final Map> discoveryServiceRegistrations = new HashMap>(); - @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { return SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID); @@ -122,13 +120,10 @@ protected ThingHandler createHandler(Thing thing) { */ private void registerOmnilnkBridgeDiscoveryService(OmnilinkBridgeHandler bridgeHandler) { OmnilinkDiscoveryService discoveryService = new OmnilinkDiscoveryService(bridgeHandler); - ServiceRegistration discoveryServiceRegistration = bundleContext .registerService(DiscoveryService.class.getName(), discoveryService, new Hashtable()); discoveryServiceRegistrations.put(bridgeHandler.getThing().getUID(), discoveryServiceRegistration); - - logger.debug( - "registerOmnilinkBridgeDiscoveryService(): Bridge Handler - {}, Class Name - {}, Discovery Service - {}", + logger.debug("registerOmnilinkDiscoveryService(): Bridge Handler - {}, Class Name - {}, Discovery Service - {}", bridgeHandler, DiscoveryService.class.getName(), discoveryService); } diff --git a/addons/binding/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/model/OSHISysteminfo.java b/addons/binding/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/model/OSHISysteminfo.java deleted file mode 100644 index 7df2c97163211..0000000000000 --- a/addons/binding/org.openhab.binding.systeminfo/src/main/java/org/openhab/binding/systeminfo/internal/model/OSHISysteminfo.java +++ /dev/null @@ -1,675 +0,0 @@ -/** - * Copyright (c) 2010-2019 Contributors to the openHAB project - * - * See the NOTICE file(s) distributed with this work for additional - * information. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License 2.0 which is available at - * http://www.eclipse.org/legal/epl-2.0 - * - * SPDX-License-Identifier: EPL-2.0 - */ -package org.openhab.binding.systeminfo.internal.model; - -import java.math.BigDecimal; - -import org.apache.commons.lang.ArrayUtils; -import org.eclipse.smarthome.core.library.types.DecimalType; -import org.eclipse.smarthome.core.library.types.StringType; -import org.osgi.service.component.annotations.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import oshi.SystemInfo; -import oshi.hardware.CentralProcessor; -import oshi.hardware.ComputerSystem; -import oshi.hardware.Display; -import oshi.hardware.GlobalMemory; -import oshi.hardware.HWDiskStore; -import oshi.hardware.HardwareAbstractionLayer; -import oshi.hardware.NetworkIF; -import oshi.hardware.PowerSource; -import oshi.hardware.Sensors; -import oshi.software.os.OSFileStore; -import oshi.software.os.OSProcess; -import oshi.software.os.OperatingSystem; -import oshi.util.EdidUtil; - -/** - * This implementation of {@link SysteminfoInterface} is using the open source library OSHI to provide system - * information. OSHI is a free JNA-based (native) Operating System and Hardware Information library for Java. - * - * @author Svilen Valkanov - Initial contribution - * @author Lyubomir Papazov - Move the initialization logic that could potentially take long time to the - * initializeSysteminfo method - * @author Christoph Weitkamp - Update to OSHI 3.13.0 - Replaced deprecated method - * CentralProcessor#getSystemSerialNumber() - * - * @see OSHI github repository - */ -@Component(service = SysteminfoInterface.class) -public class OSHISysteminfo implements SysteminfoInterface { - - HardwareAbstractionLayer hal; - - private Logger logger = LoggerFactory.getLogger(OSHISysteminfo.class); - - // Dynamic objects (may be queried repeatedly) - private GlobalMemory memory; - private CentralProcessor cpu; - private Sensors sensors; - - // Static objects, should be recreated on each request - private ComputerSystem computerSystem; - private OperatingSystem operatingSystem; - private NetworkIF[] networks; - private Display[] displays; - private OSFileStore[] fileStores; - private PowerSource[] powerSources; - private HWDiskStore[] drives; - - public static final int PRECISION_AFTER_DECIMAL_SIGN = 1; - - /** - * Some of the methods used in this constructor execute native code and require execute permissions - * - */ - public OSHISysteminfo() { - logger.debug("OSHISysteminfo service is created"); - } - - @Override - public void initializeSysteminfo() { - logger.debug("OSHISysteminfo service starts initializing"); - - SystemInfo systemInfo = new SystemInfo(); - hal = systemInfo.getHardware(); - - // Doesn't need regular update, they may be queried repeatedly - memory = hal.getMemory(); - cpu = hal.getProcessor(); - sensors = hal.getSensors(); - - // Static objects, should be recreated on each request. In OSHI 4.0.0. it is planned to change this mechanism - - // see https://github.com/oshi/oshi/issues/310 - // TODO: Once the issue is resolved in OSHI , remove unnecessary object recreations from the public get methods - computerSystem = hal.getComputerSystem(); - operatingSystem = systemInfo.getOperatingSystem(); - networks = hal.getNetworkIFs(); - displays = hal.getDisplays(); - fileStores = operatingSystem.getFileSystem().getFileStores(); - powerSources = hal.getPowerSources(); - drives = hal.getDiskStores(); - } - - @SuppressWarnings("null") - private Object getDevice(Object[] devices, int index) throws DeviceNotFoundException { - if ((devices != null) && (devices.length <= index)) { - throw new DeviceNotFoundException("Device with index: " + index + " can not be found!"); - } - return devices[index]; - } - - private OSProcess getProcess(int pid) throws DeviceNotFoundException { - OSProcess process = operatingSystem.getProcess(pid); - if (process == null) { - throw new DeviceNotFoundException("Error while getting information for process with PID " + pid); - } - return process; - } - - @Override - public StringType getOsFamily() { - String osFamily = operatingSystem.getFamily(); - return new StringType(osFamily); - } - - @Override - public StringType getOsManufacturer() { - String osManufacturer = operatingSystem.getManufacturer(); - return new StringType(osManufacturer); - } - - @Override - public StringType getOsVersion() { - String osVersion = operatingSystem.getVersion().toString(); - return new StringType(osVersion); - } - - @Override - public StringType getCpuName() { - String name = cpu.getName(); - return new StringType(name); - } - - @Override - public StringType getCpuDescription() { - String model = cpu.getModel(); - String family = cpu.getFamily(); - String serialNumber = computerSystem.getSerialNumber(); - String identifier = cpu.getIdentifier(); - String vendor = cpu.getVendor(); - String architecture = cpu.isCpu64bit() ? "64 bit" : "32 bit"; - String descriptionFormatString = "Model: %s %s,family: %s, vendor: %s, sn: %s, identifier: %s "; - String description = String.format(descriptionFormatString, model, architecture, family, vendor, serialNumber, - identifier); - - return new StringType(description); - } - - @Override - public DecimalType getCpuLogicalCores() { - int logicalProcessorCount = cpu.getLogicalProcessorCount(); - return new DecimalType(logicalProcessorCount); - } - - @Override - public DecimalType getCpuPhysicalCores() { - int physicalProcessorCount = cpu.getPhysicalProcessorCount(); - return new DecimalType(physicalProcessorCount); - } - - @Override - public DecimalType getCpuLoad() { - double processorLoad = cpu.getSystemCpuLoad(); - BigDecimal processorLoadPercent = getPercentsValue(processorLoad); - return new DecimalType(processorLoadPercent); - } - - @Override - public DecimalType getMemoryTotal() { - long totalMemory = memory.getTotal(); - totalMemory = getSizeInMB(totalMemory); - return new DecimalType(totalMemory); - } - - @Override - public DecimalType getMemoryAvailable() { - long availableMemory = memory.getAvailable(); - availableMemory = getSizeInMB(availableMemory); - return new DecimalType(availableMemory); - } - - @Override - public DecimalType getMemoryUsed() { - long totalMemory = memory.getTotal(); - long availableMemory = memory.getAvailable(); - long usedMemory = totalMemory - availableMemory; - usedMemory = getSizeInMB(usedMemory); - return new DecimalType(usedMemory); - } - - @Override - public DecimalType getStorageTotal(int index) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the storage data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - fileStores = operatingSystem.getFileSystem().getFileStores(); - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, index); - long totalSpace = fileStore.getTotalSpace(); - totalSpace = getSizeInMB(totalSpace); - return new DecimalType(totalSpace); - } - - @Override - public DecimalType getStorageAvailable(int index) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the storage data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - fileStores = operatingSystem.getFileSystem().getFileStores(); - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, index); - long freeSpace = fileStore.getUsableSpace(); - freeSpace = getSizeInMB(freeSpace); - return new DecimalType(freeSpace); - } - - @Override - public DecimalType getStorageUsed(int index) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the storage data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - fileStores = operatingSystem.getFileSystem().getFileStores(); - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, index); - long totalSpace = fileStore.getTotalSpace(); - long freeSpace = fileStore.getUsableSpace(); - long usedSpace = totalSpace - freeSpace; - usedSpace = getSizeInMB(usedSpace); - return new DecimalType(usedSpace); - } - - @Override - public DecimalType getStorageAvailablePercent(int deviceIndex) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the storage data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - fileStores = operatingSystem.getFileSystem().getFileStores(); - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, deviceIndex); - long totalSpace = fileStore.getTotalSpace(); - long freeSpace = fileStore.getUsableSpace(); - if (totalSpace > 0) { - double freePercentDecimal = (double) freeSpace / (double) totalSpace; - BigDecimal freePercent = getPercentsValue(freePercentDecimal); - return new DecimalType(freePercent); - } else { - return null; - } - } - - @Override - public DecimalType getStorageUsedPercent(int deviceIndex) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the storage data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - fileStores = operatingSystem.getFileSystem().getFileStores(); - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, deviceIndex); - long totalSpace = fileStore.getTotalSpace(); - long freeSpace = fileStore.getUsableSpace(); - long usedSpace = totalSpace - freeSpace; - if (totalSpace > 0) { - double usedPercentDecimal = (double) usedSpace / (double) totalSpace; - BigDecimal usedPercent = getPercentsValue(usedPercentDecimal); - return new DecimalType(usedPercent); - } else { - return null; - } - } - - @Override - public StringType getStorageName(int index) throws DeviceNotFoundException { - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, index); - String name = fileStore.getName(); - return new StringType(name); - } - - @Override - public StringType getStorageType(int deviceIndex) throws DeviceNotFoundException { - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, deviceIndex); - String type = fileStore.getType(); - return new StringType(type); - } - - @Override - public StringType getStorageDescription(int index) throws DeviceNotFoundException { - OSFileStore fileStore = (OSFileStore) getDevice(fileStores, index); - String description = fileStore.getDescription(); - return new StringType(description); - } - - @Override - public StringType getNetworkIp(int index) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the network data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - networks = hal.getNetworkIFs(); - NetworkIF netInterface = (NetworkIF) getDevice(networks, index); - String[] ipAddresses = netInterface.getIPv4addr(); - String ipv4 = (String) getDevice(ipAddresses, 0); - return new StringType(ipv4); - } - - @Override - public StringType getNetworkName(int index) throws DeviceNotFoundException { - NetworkIF netInterface = (NetworkIF) getDevice(networks, index); - String name = netInterface.getName(); - return new StringType(name); - } - - @Override - public StringType getNetworkDisplayName(int index) throws DeviceNotFoundException { - NetworkIF netInterface = (NetworkIF) getDevice(networks, index); - String adapterName = netInterface.getDisplayName(); - return new StringType(adapterName); - } - - @Override - public StringType getDisplayInformation(int index) throws DeviceNotFoundException { - Display display = (Display) getDevice(displays, index); - - byte[] edid = display.getEdid(); - String manufacturer = EdidUtil.getManufacturerID(edid); - String product = EdidUtil.getProductID(edid); - String serialNumber = EdidUtil.getSerialNo(edid); - int width = EdidUtil.getHcm(edid); - int height = EdidUtil.getVcm(edid); - - String edidFormatString = "Product %s, manufacturer %s, SN: %s, Width: %d, Height: %d"; - String edidInfo = String.format(edidFormatString, product, manufacturer, serialNumber, width, height); - return new StringType(edidInfo); - } - - @Override - public DecimalType getSensorsCpuTemperature() { - BigDecimal cpuTemp = new BigDecimal(sensors.getCpuTemperature()); - cpuTemp = cpuTemp.setScale(PRECISION_AFTER_DECIMAL_SIGN, BigDecimal.ROUND_HALF_UP); - return cpuTemp.signum() == 1 ? new DecimalType(cpuTemp) : null; - } - - @Override - public DecimalType getSensorsCpuVoltage() { - BigDecimal cpuVoltage = new BigDecimal(sensors.getCpuVoltage()); - cpuVoltage = cpuVoltage.setScale(PRECISION_AFTER_DECIMAL_SIGN, BigDecimal.ROUND_HALF_UP); - return cpuVoltage.signum() == 1 ? new DecimalType(cpuVoltage) : null; - } - - @Override - public DecimalType getSensorsFanSpeed(int index) throws DeviceNotFoundException { - int[] fanSpeeds = sensors.getFanSpeeds(); - int speed = (int) getDevice(ArrayUtils.toObject(fanSpeeds), index); - return speed > 0 ? new DecimalType(speed) : null; - } - - @Override - public DecimalType getBatteryRemainingTime(int index) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the battery data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - powerSources = hal.getPowerSources(); - PowerSource powerSource = (PowerSource) getDevice(powerSources, index); - double remainingTimeInSeconds = powerSource.getTimeRemaining(); - // The getTimeRemaining() method returns (-1.0) if is calculating or (-2.0) if the time is unlimited. - BigDecimal remainingTime = getTimeInMinutes(remainingTimeInSeconds); - return remainingTime.signum() == 1 ? new DecimalType(remainingTime) : null; - } - - @Override - public DecimalType getBatteryRemainingCapacity(int index) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the battery data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - powerSources = hal.getPowerSources(); - PowerSource powerSource = (PowerSource) getDevice(powerSources, index); - double remainingCapacity = powerSource.getRemainingCapacity(); - BigDecimal remainingCapacityPercents = getPercentsValue(remainingCapacity); - return new DecimalType(remainingCapacityPercents); - } - - @Override - public StringType getBatteryName(int index) throws DeviceNotFoundException { - PowerSource powerSource = (PowerSource) getDevice(powerSources, index); - String name = powerSource.getName(); - return new StringType(name); - } - - @Override - public DecimalType getMemoryAvailablePercent() { - long availableMemory = memory.getAvailable(); - long totalMemory = memory.getTotal(); - if (totalMemory > 0) { - double freePercentDecimal = (double) availableMemory / (double) totalMemory; - BigDecimal freePercent = getPercentsValue(freePercentDecimal); - return new DecimalType(freePercent); - } else { - return null; - } - } - - @Override - public DecimalType getMemoryUsedPercent() { - long availableMemory = memory.getAvailable(); - long totalMemory = memory.getTotal(); - long usedMemory = totalMemory - availableMemory; - if (totalMemory > 0) { - double usedPercentDecimal = (double) usedMemory / (double) totalMemory; - BigDecimal usedPercent = getPercentsValue(usedPercentDecimal); - return new DecimalType(usedPercent); - } else { - return null; - } - } - - @Override - public StringType getDriveName(int deviceIndex) throws DeviceNotFoundException { - HWDiskStore drive = (HWDiskStore) getDevice(drives, deviceIndex); - String name = drive.getName(); - return new StringType(name); - } - - @Override - public StringType getDriveModel(int deviceIndex) throws DeviceNotFoundException { - HWDiskStore drive = (HWDiskStore) getDevice(drives, deviceIndex); - String model = drive.getModel(); - return new StringType(model); - } - - @Override - public StringType getDriveSerialNumber(int deviceIndex) throws DeviceNotFoundException { - HWDiskStore drive = (HWDiskStore) getDevice(drives, deviceIndex); - String serialNumber = drive.getSerial(); - return new StringType(serialNumber); - } - - @Override - public DecimalType getSwapTotal() { - long swapTotal = memory.getSwapTotal(); - swapTotal = getSizeInMB(swapTotal); - return swapTotal > 0 ? new DecimalType(swapTotal) : null; - } - - @Override - public DecimalType getSwapAvailable() { - long swapTotal = memory.getSwapTotal(); - long swapUsed = memory.getSwapUsed(); - long swapAvaialble = swapTotal - swapUsed; - swapAvaialble = getSizeInMB(swapAvaialble); - return swapAvaialble > 0 ? new DecimalType(swapAvaialble) : null; - } - - @Override - public DecimalType getSwapUsed() { - long swapTotal = memory.getSwapUsed(); - swapTotal = getSizeInMB(swapTotal); - return swapTotal > 0 ? new DecimalType(swapTotal) : null; - } - - @Override - public DecimalType getSwapAvailablePercent() { - long usedSwap = memory.getSwapUsed(); - long totalSwap = memory.getSwapTotal(); - long freeSwap = totalSwap - usedSwap; - if (totalSwap > 0) { - double freePercentDecimal = (double) freeSwap / (double) totalSwap; - BigDecimal freePercent = getPercentsValue(freePercentDecimal); - return new DecimalType(freePercent); - } else { - return null; - } - } - - @Override - public DecimalType getSwapUsedPercent() { - long usedSwap = memory.getSwapUsed(); - long totalSwap = memory.getSwapTotal(); - if (totalSwap > 0) { - double usedPercentDecimal = (double) usedSwap / (double) totalSwap; - BigDecimal usedPercent = getPercentsValue(usedPercentDecimal); - return new DecimalType(usedPercent); - } else { - return null; - } - } - - private long getSizeInMB(long sizeInBytes) { - return Math.round(sizeInBytes / (1024D * 1024)); - } - - private BigDecimal getPercentsValue(double decimalFraction) { - BigDecimal result = new BigDecimal(decimalFraction * 100); - result = result.setScale(PRECISION_AFTER_DECIMAL_SIGN, BigDecimal.ROUND_HALF_UP); - return result; - } - - private BigDecimal getTimeInMinutes(double timeInSeconds) { - BigDecimal timeInMinutes = new BigDecimal(timeInSeconds / 60); - timeInMinutes = timeInMinutes.setScale(PRECISION_AFTER_DECIMAL_SIGN, BigDecimal.ROUND_UP); - return timeInMinutes; - } - - /** - * {@inheritDoc} - * - * This information is available only on Mac and Linux OS. - */ - @Override - public DecimalType getCpuLoad1() { - BigDecimal avarageCpuLoad = getAvarageCpuLoad(1); - return avarageCpuLoad.signum() == -1 ? null : new DecimalType(avarageCpuLoad); - } - - /** - * {@inheritDoc} - * - * This information is available only on Mac and Linux OS. - */ - @Override - public DecimalType getCpuLoad5() { - BigDecimal avarageCpuLoad = getAvarageCpuLoad(5); - return avarageCpuLoad.signum() == -1 ? null : new DecimalType(avarageCpuLoad); - } - - /** - * {@inheritDoc} - * - * This information is available only on Mac and Linux OS. - */ - @Override - public DecimalType getCpuLoad15() { - BigDecimal avarageCpuLoad = getAvarageCpuLoad(15); - return avarageCpuLoad.signum() == -1 ? null : new DecimalType(avarageCpuLoad); - } - - private BigDecimal getAvarageCpuLoad(int timeInMunutes) { - // This parameter is specified in OSHI Javadoc - int index; - switch (timeInMunutes) { - case 1: - index = 0; - break; - case 5: - index = 1; - break; - case 15: - index = 2; - break; - default: - index = 2; - } - double processorLoads[] = cpu.getSystemLoadAverage(index + 1); - BigDecimal result = new BigDecimal(processorLoads[index]); - result = result.setScale(PRECISION_AFTER_DECIMAL_SIGN, BigDecimal.ROUND_HALF_UP); - return result; - } - - @Override - public DecimalType getCpuUptime() { - long seconds = cpu.getSystemUptime(); - return new DecimalType(getTimeInMinutes(seconds)); - } - - @Override - public DecimalType getCpuThreads() { - int threadCount = operatingSystem.getThreadCount(); - return new DecimalType(threadCount); - } - - @Override - public StringType getNetworkMac(int networkIndex) throws DeviceNotFoundException { - NetworkIF network = (NetworkIF) getDevice(networks, networkIndex); - String mac = network.getMacaddr(); - return new StringType(mac); - } - - @Override - public DecimalType getNetworkPacketsReceived(int networkIndex) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the network data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - networks = hal.getNetworkIFs(); - NetworkIF network = (NetworkIF) getDevice(networks, networkIndex); - network.updateNetworkStats(); - long packRecv = network.getPacketsRecv(); - return new DecimalType(packRecv); - } - - @Override - public DecimalType getNetworkPacketsSent(int networkIndex) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the network data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - networks = hal.getNetworkIFs(); - NetworkIF network = (NetworkIF) getDevice(networks, networkIndex); - network.updateNetworkStats(); - long packSent = network.getPacketsSent(); - return new DecimalType(packSent); - } - - @Override - public DecimalType getNetworkDataSent(int networkIndex) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the network data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - networks = hal.getNetworkIFs(); - NetworkIF network = (NetworkIF) getDevice(networks, networkIndex); - network.updateNetworkStats(); - long bytesSent = network.getBytesSent(); - return new DecimalType(getSizeInMB(bytesSent)); - } - - @Override - public DecimalType getNetworkDataReceived(int networkIndex) throws DeviceNotFoundException { - // In the current OSHI version a new query is required for the network data values to be updated - // In OSHI 4.0.0. it is planned to change this mechanism - see https://github.com/oshi/oshi/issues/310 - networks = hal.getNetworkIFs(); - NetworkIF network = (NetworkIF) getDevice(networks, networkIndex); - network.updateNetworkStats(); - long bytesRecv = network.getBytesRecv(); - return new DecimalType(getSizeInMB(bytesRecv)); - } - - @Override - public StringType getProcessName(int pid) throws DeviceNotFoundException { - if (pid > 0) { - OSProcess process = getProcess(pid); - String name = process.getName(); - return new StringType(name); - } else { - return null; - } - } - - @Override - public DecimalType getProcessCpuUsage(int pid) throws DeviceNotFoundException { - if (pid > 0) { - OSProcess process = getProcess(pid); - double cpuUsageRaw = (process.getKernelTime() + process.getUserTime()) / process.getUpTime(); - BigDecimal cpuUsage = getPercentsValue(cpuUsageRaw); - return new DecimalType(cpuUsage); - } else { - return null; - } - } - - @Override - public DecimalType getProcessMemoryUsage(int pid) throws DeviceNotFoundException { - if (pid > 0) { - OSProcess process = getProcess(pid); - long memortInBytes = process.getResidentSetSize(); - long memoryInMB = getSizeInMB(memortInBytes); - return new DecimalType(memoryInMB); - } else { - return null; - } - } - - @Override - public StringType getProcessPath(int pid) throws DeviceNotFoundException { - if (pid > 0) { - OSProcess process = getProcess(pid); - String path = process.getPath(); - return new StringType(path); - } else { - return null; - } - } - - @Override - public DecimalType getProcessThreads(int pid) throws DeviceNotFoundException { - if (pid > 0) { - OSProcess process = getProcess(pid); - int threadCount = process.getThreadCount(); - return new DecimalType(threadCount); - } else { - return null; - } - } - -} From 27768d3141f8922415efd2c7677157745ccc951d Mon Sep 17 00:00:00 2001 From: Dan Cunningham Date: Fri, 29 Mar 2019 15:51:49 -0700 Subject: [PATCH 2/3] Use annotation binding , avoid possible NPE Signed-off-by: Dan Cunningham --- .../OSGI-INF/OmnilinkHandlerFactory.xml | 20 ------------------- .../handler/AbstractOmnilinkHandler.java | 8 +++++++- .../internal/OmnilinkHandlerFactory.java | 3 +++ 3 files changed, 10 insertions(+), 21 deletions(-) delete mode 100644 addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkHandlerFactory.xml diff --git a/addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkHandlerFactory.xml b/addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkHandlerFactory.xml deleted file mode 100644 index 87767a9fc8761..0000000000000 --- a/addons/binding/org.openhab.binding.omnilink/OSGI-INF/OmnilinkHandlerFactory.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkHandler.java index ffa8dddf2c5f3..62987fcba97ae 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkHandler.java @@ -8,6 +8,7 @@ */ package org.openhab.binding.omnilink.handler; +import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusInfo; @@ -21,7 +22,12 @@ public AbstractOmnilinkHandler(Thing thing) { } public OmnilinkBridgeHandler getOmnilinkBridgeHander() { - return (OmnilinkBridgeHandler) getBridge().getHandler(); + Bridge bridge = getBridge(); + if (bridge != null) { + return (OmnilinkBridgeHandler) bridge.getHandler(); + } else { + return null; + } } /** diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java index 432412a100aa6..98602a9af667e 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/OmnilinkHandlerFactory.java @@ -25,6 +25,7 @@ import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.binding.BaseThingHandlerFactory; import org.eclipse.smarthome.core.thing.binding.ThingHandler; +import org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory; import org.openhab.binding.omnilink.discovery.OmnilinkDiscoveryService; import org.openhab.binding.omnilink.handler.AreaHandler; import org.openhab.binding.omnilink.handler.AudioSourceHandler; @@ -40,6 +41,7 @@ import org.openhab.binding.omnilink.handler.UpbUnitHandler; import org.openhab.binding.omnilink.handler.ZoneHandler; import org.osgi.framework.ServiceRegistration; +import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,6 +51,7 @@ * * @author Craig - Initial contribution */ +@Component(service = ThingHandlerFactory.class, configurationPid = "binding.omnilink") public class OmnilinkHandlerFactory extends BaseThingHandlerFactory { private static final Logger logger = LoggerFactory.getLogger(OmnilinkHandlerFactory.class); From 3af0fe04f32a0ffc8097be78e1128be4baa74834 Mon Sep 17 00:00:00 2001 From: digitaldan Date: Fri, 12 Apr 2019 10:02:16 -0700 Subject: [PATCH 3/3] Protect against NPE's if connection not yet created, update handlers only if the bridge is online. Signed-off-by: digitaldan --- .../AbstractOmnilinkStatusHandler.java | 21 ++++++- .../handler/OmnilinkBridgeHandler.java | 61 +++++++++++-------- 2 files changed, 52 insertions(+), 30 deletions(-) diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkStatusHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkStatusHandler.java index 346cb7546f5d3..2a6baae6ba71e 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkStatusHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/AbstractOmnilinkStatusHandler.java @@ -10,9 +10,11 @@ import java.util.Optional; +import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; +import org.eclipse.smarthome.core.thing.ThingStatusInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,9 +37,7 @@ public AbstractOmnilinkStatusHandler(Thing thing) { @Override public void initialize() { - Optional status = retrieveStatus(); - handleStatus(status.orElse(null)); // handle status will process null. - updateStatus(ThingStatus.ONLINE); + updateHandlerStatus(); } /** @@ -75,4 +75,19 @@ public void channelLinked(ChannelUID channelUID) { updateChannels(status.get()); } } + + @Override + public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { + super.bridgeStatusChanged(bridgeStatusInfo); + updateHandlerStatus(); + } + + private void updateHandlerStatus() { + Bridge bridge = getBridge(); + if (bridge != null && bridge.getStatus() == ThingStatus.ONLINE) { + Optional status = retrieveStatus(); + handleStatus(status.orElse(null)); // handle status will process null. + updateStatus(ThingStatus.ONLINE); + } + } } diff --git a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java index d162d534cbfec..6865169a33e3c 100644 --- a/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java +++ b/addons/binding/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/handler/OmnilinkBridgeHandler.java @@ -88,7 +88,7 @@ public OmnilinkBridgeHandler(Bridge bridge) { public void sendOmnilinkCommand(final int message, final int param1, final int param2) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - omniConnection.controllerCommand(message, param1, param2); + getOmniConnection().controllerCommand(message, param1, param2); } catch (IOException | OmniNotConnectedException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -99,7 +99,7 @@ public void sendOmnilinkCommand(final int message, final int param1, final int p public SecurityCodeValidation reqSecurityCodeValidation(int area, int digit1, int digit2, int digit3, int digit4) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqSecurityCodeValidation(area, digit1, digit2, digit3, digit4); + return getOmniConnection().reqSecurityCodeValidation(area, digit1, digit2, digit3, digit4); } catch (IOException | OmniNotConnectedException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -109,7 +109,7 @@ public SecurityCodeValidation reqSecurityCodeValidation(int area, int digit1, in public void activateKeypadEmergency(int area, int emergencyType) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - omniConnection.activateKeypadEmergency(area, emergencyType); + getOmniConnection().activateKeypadEmergency(area, emergencyType); } catch (IOException | OmniNotConnectedException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -119,7 +119,7 @@ public void activateKeypadEmergency(int area, int emergencyType) public SystemInformation reqSystemInformation() throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqSystemInformation(); + return getOmniConnection().reqSystemInformation(); } catch (IOException | OmniNotConnectedException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -129,7 +129,7 @@ public SystemInformation reqSystemInformation() public SystemFormats reqSystemFormats() throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqSystemFormats(); + return getOmniConnection().reqSystemFormats(); } catch (IOException | OmniNotConnectedException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -139,7 +139,7 @@ public SystemFormats reqSystemFormats() private SystemFeatures reqSystemFeatures() throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqSystemFeatures(); + return getOmniConnection().reqSystemFeatures(); } catch (IOException | OmniNotConnectedException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -156,8 +156,9 @@ public void handleCommand(ChannelUID channelUID, Command command) { ZoneId.systemDefault()); boolean inDaylightSavings = zdt.getZone().getRules().isDaylightSavings(zdt.toInstant()); try { - omniConnection.setTimeCommand(zdt.getYear() - 2000, zdt.getMonthValue(), zdt.getDayOfMonth(), - zdt.getDayOfWeek().getValue(), zdt.getHour(), zdt.getMinute(), inDaylightSavings); + getOmniConnection().setTimeCommand(zdt.getYear() - 2000, zdt.getMonthValue(), + zdt.getDayOfMonth(), zdt.getDayOfWeek().getValue(), zdt.getHour(), zdt.getMinute(), + inDaylightSavings); } catch (IOException | OmniNotConnectedException | OmniInvalidResponseException | OmniUnknownMessageTypeException e) { logger.debug("Unable to set system date", e); @@ -197,7 +198,7 @@ public void handleCommand(ChannelUID channelUID, Command command) { } private void makeOmnilinkConnection() { - if (this.omniConnection != null && this.omniConnection.connected()) { + if (omniConnection != null && omniConnection.connected()) { return; } @@ -385,26 +386,24 @@ public void notConnectedEvent(Exception e) { private void getSystemStatus() throws IOException, OmniNotConnectedException, OmniInvalidResponseException, OmniUnknownMessageTypeException { - if (omniConnection != null) { - SystemStatus status = omniConnection.reqSystemStatus(); - logger.debug("received system status: {}", status); - // let's update system time - String dateString = new StringBuilder().append(2000 + status.getYear()).append("-") - .append(String.format("%02d", status.getMonth())).append("-") - .append(String.format("%02d", status.getDay())).append("T") - .append(String.format("%02d", status.getHour())).append(":") - .append(String.format("%02d", status.getMinute())).append(":") - .append(String.format("%02d", status.getSecond())).toString(); - DateTimeType sysDateTime = new DateTimeType(dateString); - updateState(OmnilinkBindingConstants.CHANNEL_SYSTEMDATE, new DateTimeType(dateString)); - logger.debug("System date is: {}", sysDateTime); - } + SystemStatus status = getOmniConnection().reqSystemStatus(); + logger.debug("received system status: {}", status); + // let's update system time + String dateString = new StringBuilder().append(2000 + status.getYear()).append("-") + .append(String.format("%02d", status.getMonth())).append("-") + .append(String.format("%02d", status.getDay())).append("T") + .append(String.format("%02d", status.getHour())).append(":") + .append(String.format("%02d", status.getMinute())).append(":") + .append(String.format("%02d", status.getSecond())).toString(); + DateTimeType sysDateTime = new DateTimeType(dateString); + updateState(OmnilinkBindingConstants.CHANNEL_SYSTEMDATE, new DateTimeType(dateString)); + logger.debug("System date is: {}", sysDateTime); } public Message reqObjectProperties(int objectType, int objectNum, int direction, int filter1, int filter2, int filter3) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqObjectProperties(objectType, objectNum, direction, filter1, filter2, filter3); + return getOmniConnection().reqObjectProperties(objectType, objectNum, direction, filter1, filter2, filter3); } catch (OmniNotConnectedException | IOException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -414,7 +413,7 @@ public Message reqObjectProperties(int objectType, int objectNum, int direction, public Message requestAudioSourceStatus(final int source, final int position) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqAudioSourceStatus(source, position); + return getOmniConnection().reqAudioSourceStatus(source, position); } catch (OmniNotConnectedException | IOException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -425,7 +424,7 @@ public ObjectStatus requestObjectStatus(final int objType, final int startObject boolean extended) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.reqObjectStatus(objType, startObject, endObject, extended); + return getOmniConnection().reqObjectStatus(objType, startObject, endObject, extended); } catch (OmniNotConnectedException | IOException e) { setOfflineAndReconnect(e.getMessage()); throw new BridgeOfflineException(e); @@ -483,7 +482,7 @@ public Optional getAudioPlayer() { public Message reqEventLogData(int eventNumber, int direction) throws OmniInvalidResponseException, OmniUnknownMessageTypeException, BridgeOfflineException { try { - return omniConnection.uploadEventLogData(eventNumber, direction); + return getOmniConnection().uploadEventLogData(eventNumber, direction); } catch (OmniNotConnectedException | IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE, e.getMessage()); throw new BridgeOfflineException(e); @@ -558,4 +557,12 @@ private void pollEvents() { logger.debug("NPE. Omni connection probably not set up.", e); } } + + private Connection getOmniConnection() throws OmniNotConnectedException { + if (omniConnection != null) { + return omniConnection; + } else { + throw new OmniNotConnectedException("Connection not yet established."); + } + } }