diff --git a/ESH-INF/thing/thing-types.xml b/ESH-INF/thing/thing-types.xml index 3c1b210..012ba6d 100644 --- a/ESH-INF/thing/thing-types.xml +++ b/ESH-INF/thing/thing-types.xml @@ -1,91 +1,80 @@ Receiver control - - - Is receiver connected via TCP? - false - - - - Select serial port - COM1 - serial-port - Host name of receiver localhost network-address Network port number of receiver 1234 Select polling Interval 60 Switch Turn it on or off. Power Switch Mute on/off. Mute Dimmer Volume control SoundVolume String Select input diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF index 13d01c6..9114b22 100644 --- a/META-INF/MANIFEST.MF +++ b/META-INF/MANIFEST.MF @@ -1,21 +1,20 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: NadReceiver Binding Bundle-SymbolicName: org.openhab.binding.nadreceiver;singleton:=true Bundle-Vendor: openHAB Bundle-Version: 2.2.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.7 +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 Bundle-ClassPath: . Import-Package: com.google.common.collect, org.eclipse.jdt.annotation;resolution:=optional, - gnu.io, - org.eclipse.smarthome.config.core, - org.eclipse.smarthome.core.library.types, - org.eclipse.smarthome.core.thing, - org.eclipse.smarthome.core.thing.binding, - org.eclipse.smarthome.core.types, + org.openhab.config.core, + org.openhab.core.library.types, + org.openhab.core.thing, + org.openhab.core.thing.binding, + org.openhab.core.types, org.slf4j Service-Component: OSGI-INF/* Export-Package: org.openhab.binding.nadreceiver, org.openhab.binding.nadreceiver.handler diff --git a/pom.xml b/pom.xml index c5699a9..c2bf9a3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,29 +1,29 @@ - - - + + 4.0.0 org.openhab.addons.bundles org.openhab.addons.reactor.bundles 3.2.0 org.openhab.binding.nadreceiver NadReceiver Binding commons-net commons-net commons-net ${commons.net.version} compile + diff --git a/src/main/history/dependencies.xml b/src/main/history/dependencies.xml index f572fd1..60c183b 100644 --- a/src/main/history/dependencies.xml +++ b/src/main/history/dependencies.xml @@ -1,4 +1,7 @@ - + + wrap + wrap:mvn:org.lastnpe.eea/eea-all/2.2.1 + diff --git a/src/main/java/org/openhab/binding/nadreceiver/NadReceiverBindingConstants.java b/src/main/java/org/openhab/binding/nadreceiver/NadReceiverBindingConstants.java index 3f98341..8757b79 100644 --- a/src/main/java/org/openhab/binding/nadreceiver/NadReceiverBindingConstants.java +++ b/src/main/java/org/openhab/binding/nadreceiver/NadReceiverBindingConstants.java @@ -1,33 +1,33 @@ /** * Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) and others. * 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.nadreceiver; -import org.eclipse.smarthome.core.thing.ThingTypeUID; +import org.openhab.core.thing.ThingTypeUID; /** * The {@link NadReceiverBinding} class defines common constants, which are * used across the whole binding. * * @author Mikael Aasen - Initial contribution */ public class NadReceiverBindingConstants { public static final String BINDING_ID = "nadreceiver"; // List of all Thing Type UIDs public final static ThingTypeUID THING_TYPE_RECEIVER = new ThingTypeUID(BINDING_ID, "receiver"); // List of all Channel ids public final static String CHANNEL_POWER = "power"; public final static String CHANNEL_MUTE = "mute"; public final static String CHANNEL_VOLUME = "volume"; public final static String CHANNEL_SOURCE = "source"; public final static String CHANNEL_TUNER_BAND = "tuner_band"; public final static String CHANNEL_AM_FREQUENCY = "am_frequency"; public final static String CHANNEL_FM_FREQUENCY = "fm_frequency"; } diff --git a/src/main/java/org/openhab/binding/nadreceiver/handler/NadReceiverHandler.java b/src/main/java/org/openhab/binding/nadreceiver/handler/NadReceiverHandler.java index 5f818e6..7e19b24 100644 --- a/src/main/java/org/openhab/binding/nadreceiver/handler/NadReceiverHandler.java +++ b/src/main/java/org/openhab/binding/nadreceiver/handler/NadReceiverHandler.java @@ -1,461 +1,449 @@ /** * Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) and others. * 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.nadreceiver.handler; -import static org.eclipse.smarthome.core.library.unit.MetricPrefix.KILO; -import static org.eclipse.smarthome.core.library.unit.MetricPrefix.MEGA; +import static javax.measure.MetricPrefix.KILO; +import static javax.measure.MetricPrefix.MEGA; import static org.openhab.binding.nadreceiver.NadReceiverBindingConstants.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.measure.quantity.Frequency; -import org.eclipse.smarthome.core.library.types.*; -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.ThingStatusDetail; -import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; -import org.eclipse.smarthome.core.types.Command; -import org.eclipse.smarthome.core.types.RefreshType; -import org.eclipse.smarthome.core.types.StateOption; -import org.eclipse.smarthome.core.types.UnDefType; import org.openhab.binding.nadreceiver.internal.NadReceiverDynamicStateDescriptionProvider; import org.openhab.binding.nadreceiver.internal.PortServer; +import org.openhab.core.library.types.*; +import org.openhab.core.library.unit.Units; +import org.openhab.core.thing.ChannelUID; +import org.openhab.core.thing.Thing; +import org.openhab.core.thing.ThingStatus; +import org.openhab.core.thing.ThingStatusDetail; +import org.openhab.core.thing.binding.BaseThingHandler; +import org.openhab.core.types.Command; +import org.openhab.core.types.RefreshType; +import org.openhab.core.types.StateOption; +import org.openhab.core.types.UnDefType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import tec.uom.se.unit.Units; - /** * The {@link NadReceiverHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Mikael Aasen - Initial contribution * @author William Welliver - TCP mode suppot */ public class NadReceiverHandler extends BaseThingHandler implements Runnable { private Logger logger = LoggerFactory.getLogger(NadReceiverHandler.class); private boolean on = false; private PortServer port; private OutputStreamWriter output; private InputStream input; private NadReceiverDynamicStateDescriptionProvider stateDescriptionProvider; public NadReceiverHandler(Thing thing, NadReceiverDynamicStateDescriptionProvider stateDescriptionProvider) { super(thing); this.stateDescriptionProvider = stateDescriptionProvider; } private void configureSourceStateOptions(String sources) { ChannelUID channelId = new ChannelUID(getThing().getUID(), CHANNEL_SOURCE); List options = new ArrayList<>(); int i = 1; for (String source : sources.split(",")) { logger.warn("Adding state option " + i + " for " + channelId + ": " + source.trim()); options.add(new StateOption("" + i, source.trim())); i++; } stateDescriptionProvider.setStateOptions(channelId, options); } @Override public synchronized void initialize() { try { logger.warn("thing: " + getThing()); logger.warn("channel: " + getThing().getChannel(CHANNEL_POWER)); configureSourceStateOptions((String) getThing().getConfiguration().get("sources")); ChannelUID channelUID = getUidForChannel(CHANNEL_POWER); boolean powerOn = isOn(); updateState(channelUID, powerOn ? OnOffType.ON : OnOffType.OFF); if (powerOn) { refreshAll(); } else { channelUID = getUidForChannel(CHANNEL_VOLUME); updateState(channelUID, UnDefType.UNDEF); channelUID = getUidForChannel(CHANNEL_MUTE); updateState(channelUID, UnDefType.UNDEF); channelUID = getUidForChannel(CHANNEL_SOURCE); updateState(channelUID, UnDefType.UNDEF); channelUID = getUidForChannel(CHANNEL_TUNER_BAND); updateState(channelUID, UnDefType.UNDEF); channelUID = getUidForChannel(CHANNEL_AM_FREQUENCY); updateState(channelUID, UnDefType.UNDEF); channelUID = getUidForChannel(CHANNEL_FM_FREQUENCY); updateState(channelUID, UnDefType.UNDEF); updateStatus(ThingStatus.ONLINE); } } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } BigDecimal pollingInterval = (BigDecimal) getThing().getConfiguration().get("polling-interval"); if (pollingInterval != null && pollingInterval.longValue() != 0) { scheduler.scheduleAtFixedRate(this, pollingInterval.longValue(), pollingInterval.longValue(), TimeUnit.SECONDS); } } private void refreshAll() throws IOException { ChannelUID channelUID; try { channelUID = getUidForChannel(CHANNEL_VOLUME); updateState(channelUID, PercentType.valueOf(Double.toString(toPercent(askInt("Main.Volume"))))); boolean isMute = "On".equals(askString("Main.Mute", false)); channelUID = getUidForChannel(CHANNEL_MUTE); updateState(channelUID, isMute ? OnOffType.ON : OnOffType.OFF); channelUID = getUidForChannel(CHANNEL_SOURCE); updateState(channelUID, new StringType(Integer.toString(askInt("Main.Source")))); channelUID = getUidForChannel(CHANNEL_SOURCE); updateState(channelUID, new StringType(Integer.toString(askInt("Main.Source")))); channelUID = getUidForChannel(CHANNEL_TUNER_BAND); updateState(channelUID, new StringType(askString("Tuner.Band", false))); channelUID = getUidForChannel(CHANNEL_AM_FREQUENCY); updateState(channelUID, new QuantityType(BigDecimal.valueOf(askInt("Tuner.AM.Frequency")), KILO(Units.HERTZ))); channelUID = getUidForChannel(CHANNEL_FM_FREQUENCY); updateState(channelUID, new QuantityType(BigDecimal.valueOf(askFloat("Tuner.FM.Frequency")), MEGA(Units.HERTZ))); } catch (CommunicationException e) { logger.warn("Error communicating with receiver.", e); port.disconnect(); } } private ChannelUID getUidForChannel(String channelName) { return getThing().getChannel(channelName).getUID(); } @Override public void dispose() { try { port.disconnect(); } catch (NullPointerException e) { } } private synchronized void connect() { if (port == null || !port.isConnected()) { logger.warn("connecting"); - boolean tcpMode = (boolean) getThing().getConfiguration().get("isTcpPort"); - if (tcpMode) { - String hostName = (String) getThing().getConfiguration().get("hostName"); - BigDecimal portNumber = (BigDecimal) getThing().getConfiguration().get("tcpPort"); - - if (hostName == null || hostName.isEmpty()) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No host name specified."); - return; - } - - if (portNumber == null || portNumber.toBigInteger().intValue() == 0) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No TCP port specified."); - return; - } - port = new PortServer(); - port.setTcpMode(hostName, portNumber.toBigInteger().intValue()); + String hostName = (String) getThing().getConfiguration().get("hostName"); + BigDecimal portNumber = (BigDecimal) getThing().getConfiguration().get("tcpPort"); - } else { - String comPort = (String) getThing().getConfiguration().get("port"); - if (comPort == null || comPort.isEmpty()) { - updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No COM port specified."); - return; - } + if (hostName == null || hostName.isEmpty()) { + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No host name specified."); + return; + } - port = new PortServer(); - port.setSerialMode(comPort, 115200); + if (portNumber == null || portNumber.toBigInteger().intValue() == 0) { + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No TCP port specified."); + return; } + + port = new PortServer(); + port.setTcpMode(hostName, portNumber.toBigInteger().intValue()); + try { port.connect(); OutputStream outStream = port.getOutputStream(); output = new OutputStreamWriter(outStream); input = port.getInputStream(); } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); logger.warn("Error connecting to receiver.", e); } } } private double toPercent(double decibel) { return (decibel + 92) * 0.9; } private double toDecibel(double percent) { return (percent / 0.9) - 92; } @Override public void handleCommand(ChannelUID channelUID, Command command) { try { // logger.warn("configuration: " + this.getThing().getChannel(CHANNEL_SOURCE).getConfiguration()); if (channelUID.getId().equals(CHANNEL_POWER)) { handlePower(channelUID, command); } else if (channelUID.getId().equals(CHANNEL_VOLUME)) { handleVolume(channelUID, command); } else if (channelUID.getId().equals(CHANNEL_MUTE)) { handleMute(channelUID, command); } else if (channelUID.getId().equals(CHANNEL_SOURCE)) { handleSource(channelUID, command); } else if (channelUID.getId().equals(CHANNEL_TUNER_BAND)) { handleTunerBand(channelUID, command); } else if (channelUID.getId().equals(CHANNEL_AM_FREQUENCY)) { handleAMFrequency(channelUID, command); } else if (channelUID.getId().equals(CHANNEL_FM_FREQUENCY)) { handleFMFrequency(channelUID, command); } } catch (IOException | CommunicationException e) { port.disconnect(); port = null; updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); logger.error("Port port error: " + e.getMessage()); on = false; } } private void handleMute(ChannelUID channelUID, Command command) throws CommunicationException, IOException { if (command != null) { if (command instanceof OnOffType) { if (command.equals(OnOffType.ON)) { setValue("Main.Mute", "On"); } else if (command.equals(OnOffType.OFF)) { setValue("Main.Mute", "Off"); } } else if (command instanceof RefreshType) { boolean isMute = "On".equals(askString("Main.Mute", false)); updateState(channelUID, isMute ? OnOffType.ON : OnOffType.OFF); } } } private void handleSource(ChannelUID channelUID, Command command) throws CommunicationException, IOException { if (command != null) { if (command instanceof RefreshType) { updateState(channelUID, new StringType(Integer.toString(askInt("Main.Source")))); } else if (command instanceof StringType) { setValue("Main.Source", command.toString()); } } } private void handleTunerBand(ChannelUID channelUID, Command command) throws CommunicationException, IOException { if (command != null) { if (command instanceof RefreshType) { updateState(channelUID, new StringType(askString("Tuner.Band", false))); } else if (command instanceof StringType) { setValue("Tuner.Band", command.toString()); } } } private void handleAMFrequency(ChannelUID channelUID, Command command) throws CommunicationException, IOException { if (command != null) { if (command instanceof RefreshType) { updateState(channelUID, new QuantityType(BigDecimal.valueOf(askInt("Tuner.AM.Frequency")), KILO(Units.HERTZ))); } else if (command instanceof QuantityType) { QuantityType t = (QuantityType) command; t = t.toUnit(KILO(Units.HERTZ)); setValue("Tuner.AM.Frequency", "" + t.intValue()); } } } private void handleFMFrequency(ChannelUID channelUID, Command command) throws CommunicationException, IOException { if (command != null) { if (command instanceof RefreshType) { updateState(channelUID, new QuantityType(BigDecimal.valueOf(askInt("Tuner.AM.Frequency")), KILO(Units.HERTZ))); } else if (command instanceof QuantityType) { QuantityType t = (QuantityType) command; t = t.toUnit(MEGA(Units.HERTZ)); t.toBigDecimal().setScale(1).toPlainString(); setValue("Tuner.AM.Frequency", t.toBigDecimal().setScale(1).toPlainString()); } } } private void handlePower(ChannelUID channelUID, Command command) throws IOException, CommunicationException { logger.info("Setting power to: " + command.toString()); if (command != null) { if (command instanceof OnOffType) { if (command.equals(OnOffType.ON)) { on(); } else if (command.equals(OnOffType.OFF)) { off(); } } else if (command instanceof RefreshType) { updateState(channelUID, isOn() ? OnOffType.ON : OnOffType.OFF); } } } private void handleVolume(ChannelUID channelUID, Command command) throws CommunicationException, IOException { if (command != null) { if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.INCREASE) { adjustValue("Main.Volume", "+"); } else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) { adjustValue("Main.Volume", "-"); } else if (command instanceof DecimalType) { setValue("Main.Volume", Integer.toString((int) toDecibel(Double.parseDouble(command.toString())))); } else if (command instanceof RefreshType) { updateState(channelUID, PercentType.valueOf(Integer.toString((int) toPercent(askInt("Main.Volume"))))); } } } public void off() throws IOException, CommunicationException { connect(); setValue("Main.Power", "Off"); } public synchronized void on() throws IOException { connect(); int attempts = 0; do { output.write("\rMain.Power=On\r"); output.flush(); try { Thread.sleep(1000); } catch (InterruptedException e) { return; } } while (!isOn() && attempts++ < 3); if (isOn()) { refreshAll(); } } public boolean isOn() throws IOException { String power; try { power = askString("Main.Power", true); } catch (CommunicationException e) { power = ""; } on = "On".equals(power); return on; } private String askString(String key, boolean ignorePowerState) throws CommunicationException, IOException { String answer = requestResponse(key + "?", ignorePowerState); String[] parts = answer.split("="); if (parts.length == 2) { updateStatus(ThingStatus.ONLINE); return parts[1]; } throw new CommunicationException("Invalid response from receiver"); } private int askInt(String key) throws CommunicationException, IOException { try { return Integer.parseInt(askString(key, false)); } catch (NumberFormatException e) { throw new CommunicationException("Not a number received", e); } } private float askFloat(String key) throws CommunicationException, IOException { try { return Float.parseFloat(askString(key, false)); } catch (NumberFormatException e) { throw new CommunicationException("Not a number received", e); } } private void setValue(String key, String value) throws CommunicationException, IOException { String answer = requestResponse(key + "=" + value, false); String[] parts = answer.split("="); if (parts.length != 2) { throw new CommunicationException("Invalid response from receiver: (length=" + Integer.toString(parts.length) + ") key \"" + parts[0] + "\" answer " + answer + " expected \"" + key + "\""); } } private String adjustValue(String key, String operator) throws CommunicationException, IOException { String answer = requestResponse(key + operator, false); String[] parts = answer.split("="); if (parts.length == 2 && key.equals(parts[0])) { return parts[1]; } else { throw new CommunicationException("Got the wrong answer: " + answer); } } private synchronized String requestResponse(String request, boolean ignorePowerState) throws IOException, CommunicationException { if (!on && !ignorePowerState && !isOn()) { throw new CommunicationException("Receiver is off"); } connect(); while (input != null && input.available() > 0) { input.read(); } logger.debug("sending to receiver: " + request); output.write("\r" + request + "\r"); output.flush(); int data = input.read(); if (data != -1) { // logger.warn("got response from receiver: " + data); boolean end = false; String answer = ""; if (data != '\r') { answer += (char) data; } while (!end) { data = input.read(); if (data == '\r' || data == '\n') { end = true; } else if (data == -1) { throw new CommunicationException("Unexpected end of input"); } else { answer += (char) data; } } logger.debug("got response from receiver: " + answer); return answer; } throw new CommunicationException("Invalid response from receiver"); } @Override public void run() { ChannelUID channelUID = getUidForChannel(CHANNEL_POWER); try { boolean power = isOn(); updateStatus(ThingStatus.ONLINE); updateState(channelUID, power ? OnOffType.ON : OnOffType.OFF); if (power) { refreshAll(); } } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); logger.warn("Error communicating with receiver.", e); port.disconnect(); } } } diff --git a/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverDynamicStateDescriptionProvider.java b/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverDynamicStateDescriptionProvider.java index 420135d..2832afa 100644 --- a/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverDynamicStateDescriptionProvider.java +++ b/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverDynamicStateDescriptionProvider.java @@ -1,45 +1,45 @@ package org.openhab.binding.nadreceiver.internal; import java.util.Locale; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; -import org.eclipse.smarthome.core.thing.Channel; -import org.eclipse.smarthome.core.thing.binding.BaseDynamicStateDescriptionProvider; -import org.eclipse.smarthome.core.thing.i18n.ChannelTypeI18nLocalizationService; -import org.eclipse.smarthome.core.thing.type.DynamicStateDescriptionProvider; -import org.eclipse.smarthome.core.types.StateDescription; +import org.openhab.core.thing.Channel; +import org.openhab.core.thing.binding.BaseDynamicStateDescriptionProvider; +import org.openhab.core.thing.i18n.ChannelTypeI18nLocalizationService; +import org.openhab.core.thing.type.DynamicStateDescriptionProvider; +import org.openhab.core.types.StateDescription; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Dynamic provider of state options while leaving other state description fields as original. * */ @Component(service = { DynamicStateDescriptionProvider.class, NadReceiverDynamicStateDescriptionProvider.class }) @NonNullByDefault public class NadReceiverDynamicStateDescriptionProvider extends BaseDynamicStateDescriptionProvider { private Logger logger = LoggerFactory.getLogger(NadReceiverDynamicStateDescriptionProvider.class); @Activate public NadReceiverDynamicStateDescriptionProvider( final @Reference ChannelTypeI18nLocalizationService channelTypeI18nLocalizationService) { this.channelTypeI18nLocalizationService = channelTypeI18nLocalizationService; } @Override public @Nullable StateDescription getStateDescription(Channel channel, @Nullable StateDescription original, @Nullable Locale locale) { if (channel.getUID().getAsString().contains("receiver")) { logger.warn("getStateDescription " + channel.getUID()); StateDescription sd = super.getStateDescription(channel, original, locale); // logger.warn("getStateDescription " + channel.getUID() + " " + sd); return sd; } else return null; } } diff --git a/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverHandlerFactory.java b/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverHandlerFactory.java index d29628a..312ac82 100644 --- a/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverHandlerFactory.java +++ b/src/main/java/org/openhab/binding/nadreceiver/internal/NadReceiverHandlerFactory.java @@ -1,65 +1,66 @@ /** * 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.nadreceiver.internal; import static org.openhab.binding.nadreceiver.internal.NadReceiverBindingConstants.NAD_RECEIVER_THING_TYPE; import java.util.Collections; import java.util.Set; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.binding.BaseThingHandlerFactory; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerFactory; +import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; /** * The {@link NadReceiverHandlerFactory} is responsible for creating things and thing * handlers. * * @author Marc Chételat - Initial contribution */ @Component(configurationPid = "binding.nadreceiver", service = ThingHandlerFactory.class) public class NadReceiverHandlerFactory extends BaseThingHandlerFactory { private static final Set SUPPORTED_THING_TYPES_UIDS = Collections.singleton(NAD_RECEIVER_THING_TYPE); private NadSourcesOptionProvider stateOptionProvider; @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { return SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID); } @Override protected ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (NAD_RECEIVER_THING_TYPE.equals(thingTypeUID)) { return new NadReceiverHandler(thing, stateOptionProvider); } return null; } @Reference protected void setPresetChannelTypeProvider(NadSourcesOptionProvider stateOptionProvider) { this.stateOptionProvider = stateOptionProvider; } protected void unsetPresetChannelTypeProvider(NadSourcesOptionProvider stateOptionProvider) { this.stateOptionProvider = null; } } diff --git a/src/main/java/org/openhab/binding/nadreceiver/internal/PortServer.java b/src/main/java/org/openhab/binding/nadreceiver/internal/PortServer.java index 9b144c5..15c8aa3 100644 --- a/src/main/java/org/openhab/binding/nadreceiver/internal/PortServer.java +++ b/src/main/java/org/openhab/binding/nadreceiver/internal/PortServer.java @@ -1,122 +1,57 @@ package org.openhab.binding.nadreceiver.internal; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; -import gnu.io.NRSerialPort; - // TODO eliminate use of RuntimeException // TODO better error checking // TODO should we require a mode to be set, or just assume one? public class PortServer { - private NRSerialPort serialPort; private Socket tcpPort; - private boolean serialMode; private boolean tcpMode; // for TCP mode private String hostName; private int port; - // for Serial mode - private String comPort; - private int baudRate; - - public boolean isSerialMode() { - return serialMode; - } - - public boolean isTcpMode() { - return tcpMode; - } - public void disconnect() { - if (serialMode) { - serialPort.disconnect(); - } else if (tcpMode) { - try { - tcpPort.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } else { - throw new RuntimeException("No mode set."); + try { + tcpPort.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } } public InputStream getInputStream() throws IOException { - if (!isConnected()) { + if (!isConnected()) throw new RuntimeException("Not Connected."); - } else if (isTcpMode()) { - return tcpPort.getInputStream(); - } else { - return serialPort.getInputStream(); - } + return tcpPort.getInputStream(); } public boolean isConnected() { - if (serialMode) { - return serialPort.isConnected(); - } else if (tcpMode) { - return tcpPort.isConnected(); - } else { - throw new RuntimeException("No mode set."); - } + return tcpPort.isConnected(); } public OutputStream getOutputStream() throws IOException { if (!isConnected()) { throw new RuntimeException("Not Connected."); - } else if (isTcpMode()) { - return tcpPort.getOutputStream(); - } else { - return serialPort.getOutputStream(); } + return tcpPort.getOutputStream(); } public void connect() throws IOException { - if (serialMode) { - serialPort = new NRSerialPort(comPort, baudRate); - serialPort.connect(); - } else if (tcpMode) { - tcpPort = new Socket(hostName, port); - } else { - throw new RuntimeException("No mode set."); - } - } - - public void setSerialMode(String comPort, int baudRate) { - if (serialPort != null) { - throw new RuntimeException("Serial mode already set."); - } - if (tcpPort != null) { - throw new RuntimeException("Mode already set to TCP."); - } - - serialMode = true; - tcpMode = false; - - this.comPort = comPort; - this.baudRate = baudRate; + tcpPort = new Socket(hostName, port); } public void setTcpMode(String hostName, int port) { - if (tcpPort != null) { - throw new RuntimeException("TCP mode already set."); - } - if (serialPort != null) { - throw new RuntimeException("Mode already set to Serial."); - } - tcpMode = true; - serialMode = false; tcpPort = new Socket(); this.hostName = hostName; this.port = port; } }