Search in sources :

Example 1 with ValueTransformation

use of org.openhab.binding.modbus.internal.ValueTransformation in project openhab-addons by openhab.

the class ModbusDataThingHandler method processUpdatedValue.

/**
 * Update linked channels
 *
 * @param numericState numeric state corresponding to polled data (or UNDEF with floating point NaN or infinity)
 * @param boolValue boolean value corresponding to polled data
 * @return updated channel data
 */
private Map<ChannelUID, State> processUpdatedValue(State numericState, boolean boolValue) {
    ValueTransformation localReadTransformation = readTransformation;
    if (localReadTransformation == null) {
        // We should always have transformation available if thing is initalized properly
        logger.trace("No transformation available, aborting processUpdatedValue");
        return Collections.emptyMap();
    }
    Map<ChannelUID, State> states = new HashMap<>();
    CHANNEL_ID_TO_ACCEPTED_TYPES.keySet().stream().forEach(channelId -> {
        ChannelUID channelUID = getChannelUID(channelId);
        if (!isLinked(channelUID)) {
            return;
        }
        List<Class<? extends State>> acceptedDataTypes = CHANNEL_ID_TO_ACCEPTED_TYPES.get(channelId);
        if (acceptedDataTypes.isEmpty()) {
            return;
        }
        State boolLikeState;
        if (containsOnOff(acceptedDataTypes)) {
            boolLikeState = boolValue ? OnOffType.ON : OnOffType.OFF;
        } else if (containsOpenClosed(acceptedDataTypes)) {
            boolLikeState = boolValue ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
        } else {
            boolLikeState = null;
        }
        State transformedState;
        if (localReadTransformation.isIdentityTransform()) {
            if (boolLikeState != null) {
                // A bit of smartness for ON/OFF and OPEN/CLOSED with boolean like items
                transformedState = boolLikeState;
            } else {
                // Numeric states always go through transformation. This allows value of 17.5 to be
                // converted to
                // 17.5% with percent types (instead of raising error)
                transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes, numericState);
            }
        } else {
            transformedState = localReadTransformation.transformState(bundleContext, acceptedDataTypes, numericState);
        }
        if (transformedState != null) {
            logger.trace("Channel {} will be updated to '{}' (type {}). Input data: number value {} (value type '{}' taken into account) and bool value {}. Transformation: {}", channelId, transformedState, transformedState.getClass().getSimpleName(), numericState, readValueType, boolValue, localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
            states.put(channelUID, transformedState);
        } else {
            String types = String.join(", ", acceptedDataTypes.stream().map(cls -> cls.getSimpleName()).toArray(String[]::new));
            logger.warn("Channel {} will not be updated since transformation was unsuccessful. Channel is expecting the following data types [{}]. Input data: number value {} (value type '{}' taken into account) and bool value {}. Transformation: {}", channelId, types, numericState, readValueType, boolValue, localReadTransformation.isIdentityTransform() ? "<identity>" : localReadTransformation);
        }
    });
    ChannelUID lastReadSuccessUID = getChannelUID(ModbusBindingConstantsInternal.CHANNEL_LAST_READ_SUCCESS);
    if (isLinked(lastReadSuccessUID)) {
        states.put(lastReadSuccessUID, new DateTimeType());
    }
    updateExpiredChannels(states);
    return states;
}
Also used : DateTimeType(org.openhab.core.library.types.DateTimeType) HashMap(java.util.HashMap) ChannelUID(org.openhab.core.thing.ChannelUID) State(org.openhab.core.types.State) ValueTransformation(org.openhab.binding.modbus.internal.ValueTransformation) SingleValueTransformation(org.openhab.binding.modbus.internal.SingleValueTransformation)

Example 2 with ValueTransformation

use of org.openhab.binding.modbus.internal.ValueTransformation in project openhab-addons by openhab.

the class ModbusDataThingHandler method transformCommandAndProcessJSON.

/**
 * Transform received command using the transformation.
 *
 * In case of JSON as transformation output, the output processed using {@link processJsonTransform}.
 *
 * @param channelUID channel UID corresponding to received command
 * @param command command to be transformed
 * @return transformed command. Null is returned with JSON transformation outputs and configuration errors
 *
 * @see processJsonTransform
 */
@Nullable
private Optional<Command> transformCommandAndProcessJSON(ChannelUID channelUID, Command command) {
    String transformOutput;
    Optional<Command> transformedCommand;
    ValueTransformation writeTransformation = this.writeTransformation;
    if (writeTransformation == null || writeTransformation.isIdentityTransform()) {
        transformedCommand = Optional.of(command);
    } else {
        transformOutput = writeTransformation.transform(bundleContext, command.toString());
        if (transformOutput.contains("[")) {
            processJsonTransform(command, transformOutput);
            return null;
        } else if (writeParametersHavingTransformationOnly) {
            updateStatusIfChanged(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format("Seems to have writeTransformation but no other write parameters. Since the transformation did not return a JSON for command '%s' (channel %s), this is a configuration error", command, channelUID));
            return null;
        } else {
            transformedCommand = SingleValueTransformation.tryConvertToCommand(transformOutput);
            logger.trace("Converted transform output '{}' to command '{}' (type {})", transformOutput, transformedCommand.map(c -> c.toString()).orElse("<conversion failed>"), transformedCommand.map(c -> c.getClass().getName()).orElse("<conversion failed>"));
        }
    }
    return transformedCommand;
}
Also used : ModbusBindingConstantsInternal(org.openhab.binding.modbus.internal.ModbusBindingConstantsInternal) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) DateTimeType(org.openhab.core.library.types.DateTimeType) ModbusConstants(org.openhab.core.io.transport.modbus.ModbusConstants) BitArray(org.openhab.core.io.transport.modbus.BitArray) DateTimeItem(org.openhab.core.library.items.DateTimeItem) HexUtils(org.openhab.core.util.HexUtils) BigDecimal(java.math.BigDecimal) Nullable(org.eclipse.jdt.annotation.Nullable) ModbusWriteCoilRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusWriteCoilRequestBlueprint) ThingHandlerCallback(org.openhab.core.thing.binding.ThingHandlerCallback) Duration(java.time.Duration) Map(java.util.Map) ModbusCommunicationInterface(org.openhab.core.io.transport.modbus.ModbusCommunicationInterface) NumberItem(org.openhab.core.library.items.NumberItem) EndpointNotInitializedException(org.openhab.binding.modbus.handler.EndpointNotInitializedException) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Collection(java.util.Collection) UnDefType(org.openhab.core.types.UnDefType) BaseThingHandler(org.openhab.core.thing.binding.BaseThingHandler) BridgeHandler(org.openhab.core.thing.binding.BridgeHandler) ModbusReadFunctionCode(org.openhab.core.io.transport.modbus.ModbusReadFunctionCode) CascadedValueTransformationImpl(org.openhab.binding.modbus.internal.CascadedValueTransformationImpl) ModbusTransportException(org.openhab.core.io.transport.modbus.exception.ModbusTransportException) BundleContext(org.osgi.framework.BundleContext) Objects(java.util.Objects) List(java.util.List) ValueType(org.openhab.core.io.transport.modbus.ModbusConstants.ValueType) AsyncModbusWriteResult(org.openhab.core.io.transport.modbus.AsyncModbusWriteResult) Optional(java.util.Optional) ModbusPollerThingHandler(org.openhab.binding.modbus.handler.ModbusPollerThingHandler) ModbusReadRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint) OpenClosedType(org.openhab.core.library.types.OpenClosedType) DimmerItem(org.openhab.core.library.items.DimmerItem) AsyncModbusFailure(org.openhab.core.io.transport.modbus.AsyncModbusFailure) ModbusRegisterArray(org.openhab.core.io.transport.modbus.ModbusRegisterArray) ModbusWriteRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint) SwitchItem(org.openhab.core.library.items.SwitchItem) LocalDateTime(java.time.LocalDateTime) ValueTransformation(org.openhab.binding.modbus.internal.ValueTransformation) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ModbusDataConfiguration(org.openhab.binding.modbus.internal.config.ModbusDataConfiguration) ModbusBitUtilities(org.openhab.core.io.transport.modbus.ModbusBitUtilities) ModbusWriteRegisterRequestBlueprint(org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint) Thing(org.openhab.core.thing.Thing) ChannelUID(org.openhab.core.thing.ChannelUID) ThingStatusInfo(org.openhab.core.thing.ThingStatusInfo) WriteRequestJsonUtilities(org.openhab.core.io.transport.modbus.json.WriteRequestJsonUtilities) DecimalType(org.openhab.core.library.types.DecimalType) ModbusConnectionException(org.openhab.core.io.transport.modbus.exception.ModbusConnectionException) ModbusConfigurationException(org.openhab.binding.modbus.internal.ModbusConfigurationException) ThingStatus(org.openhab.core.thing.ThingStatus) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) RollershutterItem(org.openhab.core.library.items.RollershutterItem) State(org.openhab.core.types.State) RefreshType(org.openhab.core.types.RefreshType) ThingStatusDetail(org.openhab.core.thing.ThingStatusDetail) TimeUnit(java.util.concurrent.TimeUnit) ModbusEndpointThingHandler(org.openhab.binding.modbus.handler.ModbusEndpointThingHandler) StringItem(org.openhab.core.library.items.StringItem) ContactItem(org.openhab.core.library.items.ContactItem) AsyncModbusReadResult(org.openhab.core.io.transport.modbus.AsyncModbusReadResult) SingleValueTransformation(org.openhab.binding.modbus.internal.SingleValueTransformation) Collections(java.util.Collections) FrameworkUtil(org.osgi.framework.FrameworkUtil) Bridge(org.openhab.core.thing.Bridge) Command(org.openhab.core.types.Command) ValueTransformation(org.openhab.binding.modbus.internal.ValueTransformation) SingleValueTransformation(org.openhab.binding.modbus.internal.SingleValueTransformation) Nullable(org.eclipse.jdt.annotation.Nullable)

Aggregations

HashMap (java.util.HashMap)2 SingleValueTransformation (org.openhab.binding.modbus.internal.SingleValueTransformation)2 ValueTransformation (org.openhab.binding.modbus.internal.ValueTransformation)2 DateTimeType (org.openhab.core.library.types.DateTimeType)2 ChannelUID (org.openhab.core.thing.ChannelUID)2 State (org.openhab.core.types.State)2 BigDecimal (java.math.BigDecimal)1 Duration (java.time.Duration)1 LocalDateTime (java.time.LocalDateTime)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 TimeUnit (java.util.concurrent.TimeUnit)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)1 Nullable (org.eclipse.jdt.annotation.Nullable)1 EndpointNotInitializedException (org.openhab.binding.modbus.handler.EndpointNotInitializedException)1