Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homematic #3

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -19,6 +19,7 @@
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.openhab.binding.homematic.handler.HomematicBridgeHandler;
import org.openhab.binding.homematic.internal.communicator.HomematicGateway;
import org.openhab.binding.homematic.internal.model.HmDevice;
import org.openhab.binding.homematic.type.UidUtils;
import org.slf4j.Logger;
Expand Down Expand Up @@ -105,10 +106,10 @@ public void loadDevices() {
@Override
public void run() {
try {
bridgeHandler.getGateway().loadAllDeviceMetadata();
final HomematicGateway gateway = bridgeHandler.getGateway();
gateway.loadAllDeviceMetadata();
bridgeHandler.getTypeGenerator().validateFirmwares();
logger.debug("Finished Homematic device discovery scan on gateway '{}'",
bridgeHandler.getGateway().getId());
logger.debug("Finished Homematic device discovery scan on gateway '{}'", gateway.getId());
} catch (Throwable ex) {
logger.error("{}", ex.getMessage(), ex);
} finally {
Expand Down
Expand Up @@ -11,6 +11,8 @@
import java.io.IOException;
import java.util.Hashtable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.eclipse.smarthome.config.discovery.DiscoveryService;
import org.eclipse.smarthome.core.net.NetUtil;
Expand All @@ -19,7 +21,9 @@
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.ThingUID;
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.eclipse.smarthome.core.types.RefreshType;
import org.openhab.binding.homematic.discovery.HomematicDeviceDiscoveryService;
Expand All @@ -28,6 +32,7 @@
import org.openhab.binding.homematic.internal.communicator.HomematicGatewayFactory;
import org.openhab.binding.homematic.internal.communicator.HomematicGatewayListener;
import org.openhab.binding.homematic.internal.misc.HomematicClientException;
import org.openhab.binding.homematic.internal.model.HmChannel;
import org.openhab.binding.homematic.internal.model.HmDatapoint;
import org.openhab.binding.homematic.internal.model.HmDevice;
import org.openhab.binding.homematic.type.HomematicTypeGenerator;
Expand All @@ -43,6 +48,10 @@
*/
public class HomematicBridgeHandler extends BaseBridgeHandler implements HomematicGatewayListener {
private final Logger logger = LoggerFactory.getLogger(HomematicBridgeHandler.class);

private boolean isInitialized = false;
private final Lock isInitializedLock = new ReentrantLock();

private static final long REINITIALIZE_DELAY_SECONDS = 10;
private static SimplePortPool portPool = new SimplePortPool();

Expand All @@ -65,6 +74,7 @@ public HomematicBridgeHandler(Bridge bridge, HomematicTypeGenerator typeGenerato
public void initialize() {
config = createHomematicConfig();
registerDeviceDiscoveryService();

final HomematicBridgeHandler instance = this;
scheduler.execute(new Runnable() {

Expand All @@ -78,6 +88,14 @@ public void run() {
discoveryService.startScan(null);
discoveryService.waitForScanFinishing();
updateStatus(ThingStatus.ONLINE);

try {
isInitializedLock.lock();
isInitialized = true;
} finally {
isInitializedLock.unlock();
}

if (!config.getGatewayInfo().isHomegear()) {
try {
gateway.loadRssiValues();
Expand All @@ -94,7 +112,6 @@ public void run() {
}
}
});

}

/**
Expand All @@ -117,6 +134,14 @@ public void run() {
public void dispose() {
logger.debug("Disposing bridge '{}'", getThing().getUID().getId());
super.dispose();

try {
isInitializedLock.lock();
isInitialized = false;
} finally {
isInitializedLock.unlock();
}

if (discoveryService != null) {
discoveryService.stopScan();
unregisterDeviceDiscoveryService();
Expand All @@ -135,7 +160,10 @@ public void dispose() {
*/
private void registerDeviceDiscoveryService() {
if (bundleContext != null) {
logger.trace("Registering HomematicDeviceDiscoveryService for bridge '{}'", getThing().getUID().getId());
if (logger.isTraceEnabled()) {
final ThingUID uid = getThing().getUID();
logger.trace("Registering HomematicDeviceDiscoveryService for bridge '{}'", uid.getId());
}
discoveryService = new HomematicDeviceDiscoveryService(this);
discoveryServiceRegistration = bundleContext.registerService(DiscoveryService.class.getName(),
discoveryService, new Hashtable<String, Object>());
Expand Down Expand Up @@ -166,8 +194,9 @@ public void setOfflineStatus() {
try {
gateway.getDevice(UidUtils.getHomematicAddress(hmThing));
} catch (HomematicClientException e) {
if (hmThing.getHandler() != null) {
((HomematicThingHandler) hmThing.getHandler()).updateStatus(ThingStatus.OFFLINE);
final ThingHandler handler = hmThing.getHandler();
if (handler != null) {
handler.dispose();
}
}
}
Expand Down Expand Up @@ -235,10 +264,15 @@ public void updateThing(HmDevice device) {
*/
@Override
public void onStateUpdated(HmDatapoint dp) {
Thing hmThing = getThingByUID(UidUtils.generateThingUID(dp.getChannel().getDevice(), getThing()));
if (hmThing != null) {
HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
thingHandler.updateDatapointState(dp);
final HmChannel hmChannel = dp.getChannel();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's better to do this in the AbstractHomematicGateway.eventReceived(). Good hint!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got NPE here :-)

if (hmChannel != null) {
Thing hmThing = getThingByUID(UidUtils.generateThingUID(hmChannel.getDevice(), getThing()));
if (hmThing.getHandler() instanceof HomematicThingHandler) {
HomematicThingHandler thingHandler = (HomematicThingHandler) hmThing.getHandler();
thingHandler.updateDatapointState(dp);
}
} else {
logger.warn("Datapoint '{}' have no valid channel assigned", dp);
}
}

Expand Down Expand Up @@ -281,7 +315,9 @@ public void onConnectionLost() {
*/
@Override
public void onConnectionResumed() {
updateStatus(ThingStatus.ONLINE);
if (isInitialized) {
updateStatus(ThingStatus.ONLINE);
}
reloadAllDeviceValues();
}

Expand Down
Expand Up @@ -15,6 +15,8 @@
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
Expand All @@ -23,6 +25,7 @@
import org.eclipse.smarthome.config.core.validation.ConfigValidationException;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.StopMoveType;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.Channel;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
Expand Down Expand Up @@ -58,6 +61,9 @@
public class HomematicThingHandler extends BaseThingHandler {
private Logger logger = LoggerFactory.getLogger(HomematicThingHandler.class);

private boolean isInitialized = false;
private final Lock isInitializedLock = new ReentrantLock();

public HomematicThingHandler(Thing thing) {
super(thing);
}
Expand All @@ -74,12 +80,11 @@ public void run() {
try {
HomematicGateway gateway = getHomematicGateway();
HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing()));
HmChannel channelZero = device.getChannel(0);
loadHomematicChannelValues(channelZero);
updateStatus(device);
logger.debug("Initializing thing '{}' from gateway '{}'", getThing().getUID(), gateway.getId());

// update properties
final HmChannel channelZero = device.getChannel(0);
Map<String, String> properties = editProperties();
setProperty(properties, channelZero, PROPERTY_BATTERY_TYPE, VIRTUAL_DATAPOINT_NAME_BATTERY_TYPE);
setProperty(properties, channelZero, Thing.PROPERTY_FIRMWARE_VERSION,
Expand All @@ -100,6 +105,13 @@ public void run() {
}
}
updateConfiguration(config);

try {
isInitializedLock.lock();
isInitialized = true;
} finally {
isInitializedLock.unlock();
}
} catch (HomematicClientException ex) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, ex.getMessage());
} catch (IOException ex) {
Expand All @@ -113,6 +125,22 @@ public void run() {
});
}

/**
* {@inheritDoc}
*/
@Override
public void dispose() {
super.dispose();
updateStatus(ThingStatus.OFFLINE);

try {
isInitializedLock.lock();
isInitialized = false;
} finally {
isInitializedLock.unlock();
}
}

/**
* Sets a thing property with a datapoint value.
*/
Expand Down Expand Up @@ -211,15 +239,15 @@ private void updateChannelState(ChannelUID channelUID)
*/
protected void updateDatapointState(HmDatapoint dp) {
try {
if (HomematicTypeGeneratorImpl.isStatusDatapoint(dp)) {
if (HomematicTypeGeneratorImpl.isStatusDatapoint(dp) && isInitialized) {
updateStatus(dp.getChannel().getDevice());
}
if (dp.getParamsetType() == HmParamsetType.MASTER) {
// update configuration
Configuration config = editConfiguration();
config.put(MetadataUtils.getParameterName(dp), dp.isEnumType() ? dp.getOptionValue() : dp.getValue());
updateConfiguration(config);
} else if (!HomematicTypeGeneratorImpl.isIgnoredDatapoint(dp)) {
} else if (!HomematicTypeGeneratorImpl.isIgnoredDatapoint(dp) && isInitialized) {
// update channel
ChannelUID channelUID = UidUtils.generateChannelUID(dp, thing.getUID());
Channel channel = thing.getChannel(channelUID.getId());
Expand All @@ -229,10 +257,10 @@ protected void updateDatapointState(HmDatapoint dp) {
logger.warn("Channel not found for datapoint '{}'", new HmDatapointInfo(dp));
}
}
} catch (BridgeHandlerNotAvailableException ex) {
// ignore
} catch (Exception ex) {
logger.error("{}", ex.getMessage(), ex);
} catch (BridgeHandlerNotAvailableException exception) {
logger.warn("{}", exception.getMessage(), exception);
} catch (Exception exception) {
logger.error("{}", exception.getMessage(), exception);
}
}

Expand All @@ -254,21 +282,18 @@ private void updateChannelState(final HmDatapoint dp, Channel channel)
/**
* Loads all values for the given Homematic channel if it is not initialized.
*/
private void loadHomematicChannelValues(HmChannel hmChannel)
private synchronized void loadHomematicChannelValues(HmChannel hmChannel)
throws BridgeHandlerNotAvailableException, IOException {
if (!hmChannel.isInitialized()) {
synchronized (this) {
if (!hmChannel.isInitialized()) {
try {
getHomematicGateway().loadChannelValues(hmChannel);
} catch (IOException ex) {
if (hmChannel.getDevice().isOffline()) {
logger.warn("Device '{}' is OFFLINE, can't update channel '{}'",
hmChannel.getDevice().getAddress(), hmChannel.getNumber());
} else {
throw ex;
}
}
try {
getHomematicGateway().loadChannelValues(hmChannel);
} catch (IOException ex) {
final HmDevice device = hmChannel.getDevice();
if (device.isOffline()) {
logger.warn("Device '{}' is OFFLINE, can't update channel '{}'", device.getAddress(),
hmChannel.getNumber());
} else {
throw ex;
}
}
}
Expand Down Expand Up @@ -302,14 +327,6 @@ private void updateStatus(HmDevice device) throws BridgeHandlerNotAvailableExcep
}
}

/**
* {@inheritDoc}
*/
@Override
protected void updateStatus(ThingStatus status) {
super.updateStatus(status);
}

/**
* Returns true, if the channel is linked at least to one item.
*/
Expand All @@ -328,15 +345,16 @@ private HmDatapointConfig getChannelConfig(Channel channel, HmDatapoint dp) {
* Returns the Homematic gateway if the bridge is available.
*/
private HomematicGateway getHomematicGateway() throws BridgeHandlerNotAvailableException {
if (getBridge() == null || getBridge().getHandler() == null
|| ((HomematicBridgeHandler) getBridge().getHandler()).getGateway() == null) {
final Bridge bridge = getBridge();
if (bridge == null || bridge.getHandler() == null
|| ((HomematicBridgeHandler) bridge.getHandler()).getGateway() == null) {
if (thing.getStatus() != ThingStatus.INITIALIZING) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_MISSING_ERROR);
}
throw new BridgeHandlerNotAvailableException("BridgeHandler not yet available!");
}

return ((HomematicBridgeHandler) getBridge().getHandler()).getGateway();
return ((HomematicBridgeHandler) bridge.getHandler()).getGateway();
}

/**
Expand Down Expand Up @@ -368,10 +386,11 @@ public void handleConfigurationUpdate(Map<String, Object> configurationParameter
try {
if (newValue != null) {
if (newValue instanceof BigDecimal) {
final BigDecimal decimal = (BigDecimal) newValue;
if (dp.isIntegerType()) {
newValue = ((BigDecimal) newValue).intValue();
newValue = decimal.intValue();
} else if (dp.isFloatType()) {
newValue = ((BigDecimal) newValue).doubleValue();
newValue = decimal.doubleValue();
}
}
if (ObjectUtils.notEqual(dp.isEnumType() ? dp.getOptionValue() : dp.getValue(),
Expand Down
Expand Up @@ -147,7 +147,8 @@ public void addChannelDatapoints(HmChannel channel, HmParamsetType paramsetType)
RpcRequest<T> request = createRpcRequest("getParamsetDescription");
request.addArg(getRpcAddress(channel.getDevice().getAddress()) + ":" + channel.getNumber());
request.addArg(paramsetType.toString());
new GetParamsetDescriptionParser(channel, paramsetType).parse(sendMessage(config.getRpcPort(channel), request));
final GetParamsetDescriptionParser parser = new GetParamsetDescriptionParser(channel, paramsetType);
parser.parse(sendMessage(config.getRpcPort(channel), request));
}

/**
Expand Down
Expand Up @@ -128,20 +128,17 @@ public void generate(HmDevice device) {
List<ChannelDefinition> channelDefinitions = new ArrayList<ChannelDefinition>();
// generate channel
for (HmDatapoint dp : channel.getDatapoints().values()) {
if (!isIgnoredDatapoint(dp)) {
if (dp.getParamsetType() == HmParamsetType.VALUES) {
ChannelTypeUID channelTypeUID = UidUtils.generateChannelTypeUID(dp);
ChannelType channelType = channelTypeProvider.getChannelType(channelTypeUID,
Locale.getDefault());
if (channelType == null) {
channelType = createChannelType(dp, channelTypeUID);
channelTypeProvider.addChannelType(channelType);
}

ChannelDefinition channelDef = new ChannelDefinition(dp.getName(),
channelType.getUID());
channelDefinitions.add(channelDef);
if (!isIgnoredDatapoint(dp) && (dp.getParamsetType() == HmParamsetType.VALUES)) {
final ChannelTypeUID channelTypeUID = UidUtils.generateChannelTypeUID(dp);
ChannelType channelType = channelTypeProvider.getChannelType(channelTypeUID,
Locale.getDefault());
if (channelType == null) {
channelType = createChannelType(dp, channelTypeUID);
channelTypeProvider.addChannelType(channelType);
}

ChannelDefinition channelDef = new ChannelDefinition(dp.getName(), channelType.getUID());
channelDefinitions.add(channelDef);
}
}

Expand Down