Skip to content

Commit

Permalink
Refactored CULHandler lifecycle and configuration.
Browse files Browse the repository at this point in the history
Fixes openhab#3118, openhab#2358

Signed-off-by: Patrick Ruckstuhl <patrick@ch.tario.org> (github: tarioch)
  • Loading branch information
tarioch committed Feb 2, 2016
1 parent fbd40dc commit f0e5a86
Show file tree
Hide file tree
Showing 35 changed files with 1,085 additions and 1,237 deletions.
Expand Up @@ -16,12 +16,11 @@
import org.openhab.binding.em.EMBindingProvider;
import org.openhab.binding.em.internal.EMBindingConfig.Datapoint;
import org.openhab.binding.em.internal.EMBindingConfig.EMType;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.AbstractBinding;
import org.openhab.core.library.types.DecimalType;
import org.openhab.io.transport.cul.CULDeviceException;
import org.openhab.io.transport.cul.CULHandler;
import org.openhab.io.transport.cul.CULLifecycleListenerListenerRegisterer;
import org.openhab.io.transport.cul.CULLifecycleManager;
import org.openhab.io.transport.cul.CULListener;
import org.openhab.io.transport.cul.CULManager;
import org.openhab.io.transport.cul.CULMode;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
Expand All @@ -35,82 +34,27 @@
* @author Till Klocke
* @since 1.4.0
*/
public class EMBinding extends AbstractActiveBinding<EMBindingProvider>implements ManagedService, CULListener {
public class EMBinding extends AbstractBinding<EMBindingProvider>implements ManagedService, CULListener {

private static final Logger logger = LoggerFactory.getLogger(EMBinding.class);

private final static String CONFIG_KEY_DEVICE_NAME = "device";
private long refreshInterval = 60000;
private String deviceName;

private CULHandler cul;
private final CULLifecycleManager culHandlerLifecycle;

private Map<String, Integer> counterMap = new HashMap<String, Integer>();

public EMBinding() {
culHandlerLifecycle = new CULLifecycleManager(CULMode.SLOW_RF,
new CULLifecycleListenerListenerRegisterer(this));
}

@Override
public void activate() {
culHandlerLifecycle.open();
}

@Override
public void deactivate() {
closeCUL();
}

private void closeCUL() {
if (cul != null) {
cul.unregisterListener(this);
CULManager.close(cul);
}
}

/**
* If the device name has changed, try to close the old device handler and
* create a new one
*
* @param deviceName
* The new deviceName
*/
private void setNewDeviceName(String deviceName) {
if (deviceName != null && this.deviceName != null && this.deviceName.equals(deviceName)) {
return;
}
if (this.deviceName != null && cul != null) {
closeCUL();
}
try {
cul = CULManager.getOpenCULHandler(deviceName, CULMode.SLOW_RF);
cul.registerListener(this);
this.deviceName = deviceName;
} catch (CULDeviceException e) {
logger.error("Can't get CULHandler", e);
}
}

/**
* @{inheritDoc
*/
@Override
protected long getRefreshInterval() {
return refreshInterval;
}

/**
* @{inheritDoc
*/
@Override
protected String getName() {
return "EM Refresh Service";
}

/**
* @{inheritDoc
*/
@Override
protected void execute() {
// Nothing to do
culHandlerLifecycle.close();
}

protected void addBindingProvider(EMBindingProvider bindingProvider) {
Expand All @@ -122,37 +66,18 @@ protected void removeBindingProvider(EMBindingProvider bindingProvider) {
}

/**
* {@inheritDoc}
* @{inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {

// to override the default refresh interval one has to add a
// parameter to openhab.cfg like
// <bindingName>:refresh=<intervalInMs>
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}

String deviceName = (String) config.get(CONFIG_KEY_DEVICE_NAME);
if (!StringUtils.isEmpty(deviceName)) {
setNewDeviceName(deviceName);
} else {
setProperlyConfigured(false);
throw new ConfigurationException(CONFIG_KEY_DEVICE_NAME, "Device name not configured");
}
setProperlyConfigured(true);
}
culHandlerLifecycle.config(config);
}

@Override
public void dataReceived(String data) {
if (!StringUtils.isEmpty(data) && data.startsWith("E")) {
parseDataLine(data);
}

}

/**
Expand Down Expand Up @@ -227,7 +152,6 @@ private EMBindingConfig findConfig(EMType type, String address, Datapoint datapo
@Override
public void error(Exception e) {
logger.error("Exception instead of new data from CUL", e);

}

}
Expand Up @@ -13,10 +13,8 @@
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
Expand All @@ -30,10 +28,10 @@
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.io.transport.cul.CULCommunicationException;
import org.openhab.io.transport.cul.CULDeviceException;
import org.openhab.io.transport.cul.CULHandler;
import org.openhab.io.transport.cul.CULLifecycleListener;
import org.openhab.io.transport.cul.CULLifecycleManager;
import org.openhab.io.transport.cul.CULListener;
import org.openhab.io.transport.cul.CULManager;
import org.openhab.io.transport.cul.CULMode;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
Expand Down Expand Up @@ -67,20 +65,6 @@ public class FHTBinding extends AbstractActiveBinding<FHTBindingProvider>impleme

private final static SimpleDateFormat configDateFormat = new SimpleDateFormat("mm:HH:dd:MM:yy");

/**
* Config key for the device address. i.e. serial:/dev/ttyACM0
*/
private final static String KEY_DEVICE = "device";

/**
* Config key for the device baud rate. i.e. baudrate:38400
*/
private final static String KEY_BAUD_RATE = "baudrate";
/**
* Config key for the device parity. i.e. parity:0
*/
private final static String KEY_PARITY = "parity";

/**
* Our housecode we need to simulate a central device.
*/
Expand All @@ -102,16 +86,13 @@ public class FHTBinding extends AbstractActiveBinding<FHTBindingProvider>impleme
*/
private final static String KEY_REPORTS_CRON = "reports.cron";

private String deviceName;
private Map<String, Object> properties = new HashMap<String, Object>();

private String housecode;
private boolean doTimeUpdate = false;
private String timeUpdatecronExpression;
private String reportsCronExpression;
private boolean requestReports;

private CULHandler cul;
private final CULLifecycleManager culHandlerLifecycle;

private JobKey updateTimeJobKey;
private JobKey requestReportJobKey;
Expand All @@ -126,55 +107,43 @@ public class FHTBinding extends AbstractActiveBinding<FHTBindingProvider>impleme
private HashMap<String, Integer> valueCache = new HashMap<String, Integer>();

public FHTBinding() {
culHandlerLifecycle = new CULLifecycleManager(CULMode.SLOW_RF, new CULLifecycleListener() {

@Override
public void open(CULHandler cul) throws CULCommunicationException {
cul.registerListener(FHTBinding.this);
cul.send("T01" + housecode);
}

@Override
public void close(CULHandler cul) {
cul.unregisterListener(FHTBinding.this);

}

});
}

@Override
public void activate() {
bindCULHandler();
culHandlerLifecycle.open();
}

@Override
public void deactivate() {
if (cul != null) {
CULManager.close(cul);
}
culHandlerLifecycle.close();
unscheduleJob(requestReportJobKey);
unscheduleJob(updateTimeJobKey);
}

private void bindCULHandler() {
if (!StringUtils.isEmpty(deviceName)) {
try {
cul = CULManager.getOpenCULHandler(deviceName, CULMode.SLOW_RF, properties);
cul.registerListener(this);
cul.send("T01" + housecode);
} catch (CULDeviceException e) {
logger.error("Can't open CUL", e);
} catch (CULCommunicationException e) {
logger.error("Can't set our own housecode", e);
}
}
}

private boolean checkCULDevice() {
if (cul == null) {
if (!culHandlerLifecycle.isCulReady()) {
logger.error("CUL device is not accessible");
return false;
}
return true;
}

private void setNewDeviceName(String newDeviceName) {
if (!StringUtils.isEmpty(newDeviceName)) {
if (cul != null) {
cul.unregisterListener(this);
CULManager.close(cul);
}
deviceName = newDeviceName;
bindCULHandler();
}
}

/**
* @{inheritDoc
*/
Expand Down Expand Up @@ -209,7 +178,7 @@ protected void execute() {
FHTDesiredTemperatureCommand waitingCommand = entry.getValue();
String commandString = "T" + waitingCommand.getAddress() + waitingCommand.getCommand();
try {
cul.send(commandString);
culHandlerLifecycle.getCul().send(commandString);
temperatureCommandQueue.remove(entry.getKey());
} catch (CULCommunicationException e) {
logger.error("Can't send desired temperature via CUL", e);
Expand Down Expand Up @@ -270,6 +239,7 @@ protected void removeBindingProvider(FHTBindingProvider bindingProvider) {
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
setProperlyConfigured(false);
if (config != null) {

// to override the default refresh interval one has to add a
Expand Down Expand Up @@ -308,20 +278,8 @@ public void updated(Dictionary<String, ?> config) throws ConfigurationException
unscheduleJob(requestReportJobKey);
}

// At last the device, after we received all other config values
String deviceName = parseMandatoryValue(KEY_DEVICE, config);

String baudRateString = parseMandatoryValue(KEY_BAUD_RATE, config);
if (StringUtils.isNotBlank(baudRateString)) {
properties.put(KEY_BAUD_RATE, baudRateString);
}

String parityString = parseMandatoryValue(KEY_PARITY, config);
if (StringUtils.isNotBlank(parityString)) {
properties.put(KEY_PARITY, parityString);
}
culHandlerLifecycle.config(config);

setNewDeviceName(deviceName);
setProperlyConfigured(true);
}
}
Expand Down Expand Up @@ -589,7 +547,7 @@ private void writeRegister(String device, String register, String value) {
sendBuffer.append(register); // register to write
sendBuffer.append(value);
try {
cul.send(sendBuffer.toString());
culHandlerLifecycle.getCul().send(sendBuffer.toString());
} catch (CULCommunicationException e) {
logger.error("Error while writing register " + register + " on device " + device);
}
Expand Down Expand Up @@ -619,7 +577,7 @@ private void writeRegisters(String deviceAddress, WriteRegisterCommand... comman
sendBuffer.append(command.value);
}
try {
cul.send(sendBuffer.toString());
culHandlerLifecycle.getCul().send(sendBuffer.toString());
} catch (CULCommunicationException e) {
logger.error("Error while writing multiple write register commands to the CUL", e);
}
Expand Down

0 comments on commit f0e5a86

Please sign in to comment.