Search in sources :

Example 1 with Channel

use of org.openhab.core.thing.Channel in project org.openhab.binding.zwave by openhab.

the class ZWaveThingHandler method initialiseNode.

void initialiseNode() {
    logger.debug("NODE {}: Initialising Thing Node...", nodeId);
    // Note that for dynamic channels, it seems that defaults can either be not set, or set with the incorrect
    // type. So, we read back as an Object to avoid casting problems.
    pollingPeriod = POLLING_PERIOD_DEFAULT;
    final Object pollParm = getConfig().get(ZWaveBindingConstants.CONFIGURATION_POLLPERIOD);
    if (pollParm instanceof BigDecimal) {
        try {
            pollingPeriod = ((BigDecimal) pollParm).intValue();
        } catch (final NumberFormatException ex) {
            logger.debug("NODE {}: pollingPeriod ({}) cannot be parsed - using default", nodeId, pollParm);
        }
    }
    final Object repollParm = getConfig().get(ZWaveBindingConstants.CONFIGURATION_CMDREPOLLPERIOD);
    if (repollParm instanceof BigDecimal) {
        try {
            commandPollDelay = ((BigDecimal) repollParm).intValue();
        } catch (final NumberFormatException ex) {
            logger.debug("NODE {}: commandPollDelay ({}) cannot be parsed - using default", nodeId, repollParm);
        }
    }
    // Create the channels list to simplify processing incoming events
    thingChannelsCmd = new ArrayList<ZWaveThingChannel>();
    thingChannelsState = new ArrayList<ZWaveThingChannel>();
    for (Channel channel : getThing().getChannels()) {
        logger.trace("NODE {}: Processing channel: {} == {}", nodeId, channel.getUID(), channel.getChannelTypeUID());
        // Process the channel properties and configuration
        Map<String, String> properties = channel.getProperties();
        Configuration configuration = channel.getConfiguration();
        for (String key : properties.keySet()) {
            logger.trace("NODE {}: Processing channel: {} == {}", nodeId, key, properties.get(key));
            String[] bindingType = key.split(":");
            if (bindingType.length != 3) {
                logger.trace("NODE {}: binding string != 3", nodeId);
                continue;
            }
            if (!ZWaveBindingConstants.CHANNEL_CFG_BINDING.equals(bindingType[0])) {
                logger.trace("NODE {}: binding string != CFG_BINDING", nodeId);
                continue;
            }
            String[] bindingProperties = properties.get(key).split(";");
            // TODO: Check length???
            // Get the command classes - comma separated
            String[] cmdClasses = bindingProperties[0].split(",");
            // Convert the arguments to a map
            // - comma separated list of arguments "arg1=val1, arg2=val2"
            Map<String, String> argumentMap = new HashMap<String, String>();
            if (bindingProperties.length == 2) {
                argumentMap = getZWaveProperties(bindingProperties[1]);
            }
            // Process the user configuration and add it to the argument map
            for (String configName : configuration.getProperties().keySet()) {
                argumentMap.put(configName, configuration.get(configName).toString());
            }
            // Add all the command classes...
            boolean first = true;
            for (String cc : cmdClasses) {
                String[] ccSplit = cc.split(":");
                int endpoint = 0;
                if (ccSplit.length == 2) {
                    endpoint = Integer.parseInt(ccSplit[1]);
                }
                // Get the data type
                DataType dataType = DataType.DecimalType;
                try {
                    dataType = DataType.valueOf(bindingType[2]);
                } catch (IllegalArgumentException e) {
                    logger.warn("NODE {}: Invalid item type defined {} for {}. Assuming DecimalType.", nodeId, bindingType[2], channel.getUID());
                }
                ZWaveThingChannel chan = new ZWaveThingChannel(controllerHandler, channel.getChannelTypeUID(), channel.getUID(), dataType, ccSplit[0], endpoint, argumentMap);
                // First time round, and this is a command - then add the command
                if (first && ("*".equals(bindingType[1]) || "Command".equals(bindingType[1]))) {
                    thingChannelsCmd.add(chan);
                    logger.debug("NODE {}: Initialising cmd channel {} for {}", nodeId, channel.getUID(), dataType);
                }
                // Add the state and polling handlers
                if ("*".equals(bindingType[1]) || "State".equals(bindingType[1])) {
                    logger.debug("NODE {}: Initialising state channel {} for {}", nodeId, channel.getUID(), dataType);
                    thingChannelsState.add(chan);
                }
                first = false;
            }
        }
        // if the channel is already linked, add it to our list of channels to poll for
        if (isLinked(channel.getUID().getId())) {
            thingChannelsPoll.add(channel.getUID());
        }
    }
    startPolling();
}
Also used : Configuration(org.openhab.core.config.core.Configuration) HashMap(java.util.HashMap) Channel(org.openhab.core.thing.Channel) BigDecimal(java.math.BigDecimal) DataType(org.openhab.binding.zwave.handler.ZWaveThingChannel.DataType)

Example 2 with Channel

use of org.openhab.core.thing.Channel in project openhab-addons by openhab.

the class AirQualityStationHandler method discoverAttributes.

private void discoverAttributes() {
    getAirQualityData().ifPresent(data -> {
        // Update thing properties
        Map<String, String> properties = new HashMap<>();
        properties.put(ATTRIBUTIONS, data.getAttributions());
        PointType serverLocation = locationProvider.getLocation();
        if (serverLocation != null) {
            PointType stationLocation = new PointType(data.getCity().getGeo());
            double distance = serverLocation.distanceFrom(stationLocation).doubleValue();
            properties.put(DISTANCE, new QuantityType<>(distance / 1000, KILO(SIUnits.METRE)).toString());
        }
        // Search and remove missing pollutant channels
        List<Channel> channels = new ArrayList<>(getThing().getChannels());
        Stream.of(Pollutant.values()).forEach(pollutant -> {
            String groupName = pollutant.name().toLowerCase();
            double value = data.getIaqiValue(pollutant);
            channels.removeIf(channel -> value == -1 && groupName.equals(channel.getUID().getGroupId()));
        });
        // Update thing configuration
        Configuration config = editConfiguration();
        config.put(AirQualityConfiguration.STATION_ID, data.getStationId());
        ThingBuilder thingBuilder = editThing();
        thingBuilder.withChannels(channels).withConfiguration(config).withProperties(properties).withLocation(data.getCity().getName());
        updateThing(thingBuilder.build());
    });
}
Also used : ThingBuilder(org.openhab.core.thing.binding.builder.ThingBuilder) Configuration(org.openhab.core.config.core.Configuration) SensitiveGroupConfiguration(org.openhab.binding.airquality.internal.config.SensitiveGroupConfiguration) AirQualityConfiguration(org.openhab.binding.airquality.internal.config.AirQualityConfiguration) HashMap(java.util.HashMap) QuantityType(org.openhab.core.library.types.QuantityType) Channel(org.openhab.core.thing.Channel) ArrayList(java.util.ArrayList) PointType(org.openhab.core.library.types.PointType)

Example 3 with Channel

use of org.openhab.core.thing.Channel in project openhab-addons by openhab.

the class BenqProjectorHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    String channelId = channelUID.getId();
    if (command instanceof RefreshType) {
        Channel channel = this.thing.getChannel(channelUID);
        if (channel != null && getThing().getStatus() == ThingStatus.ONLINE) {
            updateChannelState(channel);
        }
    } else {
        BenqProjectorCommandType benqCommand = BenqProjectorCommandType.getCommandType(channelId);
        sendDataToDevice(benqCommand, command);
    }
}
Also used : BenqProjectorCommandType(org.openhab.binding.benqprojector.internal.BenqProjectorCommandType) Channel(org.openhab.core.thing.Channel) RefreshType(org.openhab.core.types.RefreshType)

Example 4 with Channel

use of org.openhab.core.thing.Channel in project openhab-addons by openhab.

the class ComfoAirHandler method handleCommand.

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
    String channelId = channelUID.getId();
    if (comfoAirConnector != null) {
        boolean isActive = !comfoAirConnector.getIsSuspended();
        if (isActive || channelId.equals(ACTIVATE_CHANNEL_ID)) {
            if (command instanceof RefreshType) {
                Channel channel = this.thing.getChannel(channelUID);
                if (channel != null) {
                    updateChannelState(channel);
                }
            } else {
                ComfoAirCommand changeCommand = ComfoAirCommandType.getChangeCommand(channelId, command);
                if (changeCommand != null) {
                    Set<String> keysToUpdate = getThing().getChannels().stream().map(Channel::getUID).filter(this::isLinked).map(ChannelUID::getId).collect(Collectors.toSet());
                    sendCommand(changeCommand, channelId);
                    Collection<ComfoAirCommand> affectedReadCommands = ComfoAirCommandType.getAffectedReadCommands(channelId, keysToUpdate);
                    if (!affectedReadCommands.isEmpty()) {
                        Runnable updateThread = new AffectedItemsUpdateThread(affectedReadCommands, keysToUpdate);
                        affectedItemsPoller = scheduler.schedule(updateThread, 3, TimeUnit.SECONDS);
                    }
                } else {
                    logger.warn("Unhandled command type: {}, channelId: {}", command.toString(), channelId);
                }
            }
        } else {
            logger.debug("Binding control is currently not active.");
        }
    }
}
Also used : Channel(org.openhab.core.thing.Channel) RefreshType(org.openhab.core.types.RefreshType)

Example 5 with Channel

use of org.openhab.core.thing.Channel in project openhab-addons by openhab.

the class CBusLightHandler method updateGroup.

public void updateGroup(int updateApplicationId, int updateGroupId, String value) {
    if (updateGroupId == groupId && updateApplicationId == applicationId) {
        Thing thing = getThing();
        Channel channel = thing.getChannel(CBusBindingConstants.CHANNEL_STATE);
        Channel channelLevel = thing.getChannel(CBusBindingConstants.CHANNEL_LEVEL);
        if (channel != null && channelLevel != null) {
            ChannelUID channelUID = channel.getUID();
            ChannelUID channelLevelUID = channelLevel.getUID();
            logger.debug("channel UID {} level UID {}", channelUID, channelLevelUID);
            if ("on".equalsIgnoreCase(value) || "255".equalsIgnoreCase(value)) {
                updateState(channelUID, OnOffType.ON);
                updateState(channelLevelUID, new PercentType(100));
            } else if ("off".equalsIgnoreCase(value) || "0".equalsIgnoreCase(value)) {
                updateState(channelUID, OnOffType.OFF);
                updateState(channelLevelUID, new PercentType(0));
            } else {
                try {
                    int v = Integer.parseInt(value);
                    updateState(channelUID, v > 0 ? OnOffType.ON : OnOffType.OFF);
                    updateState(channelLevelUID, new PercentType((int) (v * 100 / 255.0)));
                } catch (NumberFormatException e) {
                    logger.warn("Invalid value presented to channel {}. Received {}, expected On/Off", channelUID, value);
                }
            }
            logger.debug("Updating CBus Lighting Group {} with value {}", thing.getUID(), value);
        } else {
            logger.debug("Failed to Update CBus Lighting Group {} with value {}: No Channel", thing.getUID(), value);
        }
    }
}
Also used : ChannelUID(org.openhab.core.thing.ChannelUID) Channel(org.openhab.core.thing.Channel) PercentType(org.openhab.core.library.types.PercentType) Thing(org.openhab.core.thing.Thing)

Aggregations

Channel (org.openhab.core.thing.Channel)497 ChannelUID (org.openhab.core.thing.ChannelUID)190 ArrayList (java.util.ArrayList)107 Thing (org.openhab.core.thing.Thing)86 State (org.openhab.core.types.State)84 ChannelTypeUID (org.openhab.core.thing.type.ChannelTypeUID)81 ThingBuilder (org.openhab.core.thing.binding.builder.ThingBuilder)75 Nullable (org.eclipse.jdt.annotation.Nullable)66 Configuration (org.openhab.core.config.core.Configuration)63 StringType (org.openhab.core.library.types.StringType)56 Test (org.junit.jupiter.api.Test)55 HashMap (java.util.HashMap)51 RefreshType (org.openhab.core.types.RefreshType)51 DecimalType (org.openhab.core.library.types.DecimalType)48 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)42 ThingStatus (org.openhab.core.thing.ThingStatus)41 List (java.util.List)38 Command (org.openhab.core.types.Command)36 BigDecimal (java.math.BigDecimal)35 Map (java.util.Map)34