2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.dbquery.internal;
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.openhab.binding.dbquery.internal.error.UnnexpectedCondition;
18 import org.openhab.core.library.types.DateTimeType;
19 import org.openhab.core.library.types.DecimalType;
20 import org.openhab.core.library.types.OnOffType;
21 import org.openhab.core.library.types.OpenClosedType;
22 import org.openhab.core.library.types.StringType;
23 import org.openhab.core.thing.Channel;
24 import org.openhab.core.thing.type.ChannelTypeUID;
25 import org.openhab.core.types.State;
26 import org.openhab.core.types.UnDefType;
29 * Updates a query result to needed channels doing needed conversions
31 * @author Joan Pujol - Initial contribution
34 public class QueryResultChannelUpdater {
35 private final ChannelStateUpdater channelStateUpdater;
36 private final ChannelsToUpdateQueryResult channels2Update;
37 private final Value2StateConverter value2StateConverter;
39 public QueryResultChannelUpdater(ChannelStateUpdater channelStateUpdater,
40 ChannelsToUpdateQueryResult channelsToUpdate) {
41 this.channelStateUpdater = channelStateUpdater;
42 this.channels2Update = channelsToUpdate;
43 this.value2StateConverter = new Value2StateConverter();
46 public void clearChannelResults() {
47 for (Channel channel : channels2Update.getChannels()) {
48 channelStateUpdater.updateChannelState(channel, UnDefType.NULL);
52 public void updateChannelResults(@Nullable Object extractedResult) {
53 for (Channel channel : channels2Update.getChannels()) {
54 Class<? extends State> targetType = calculateItemType(channel);
55 State state = value2StateConverter.convertValue(extractedResult, targetType);
56 channelStateUpdater.updateChannelState(channel, state);
60 private Class<? extends State> calculateItemType(Channel channel) {
61 ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
62 String channelID = channelTypeUID != null ? channelTypeUID.getId()
63 : DBQueryBindingConstants.RESULT_STRING_CHANNEL_TYPE;
65 case DBQueryBindingConstants.RESULT_STRING_CHANNEL_TYPE:
66 return StringType.class;
67 case DBQueryBindingConstants.RESULT_NUMBER_CHANNEL_TYPE:
68 return DecimalType.class;
69 case DBQueryBindingConstants.RESULT_DATETIME_CHANNEL_TYPE:
70 return DateTimeType.class;
71 case DBQueryBindingConstants.RESULT_SWITCH_CHANNEL_TYPE:
72 return OnOffType.class;
73 case DBQueryBindingConstants.RESULT_CONTACT_CHANNEL_TYPE:
74 return OpenClosedType.class;
76 throw new UnnexpectedCondition("Unexpected channel type " + channelTypeUID);