]> git.basschouten.com Git - openhab-addons.git/blob
846ca2554b6f278c216ae331822b5e18b09c3a15
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.openweathermap.internal.handler;
14
15 import static org.openhab.binding.openweathermap.internal.OpenWeatherMapBindingConstants.*;
16
17 import java.time.Instant;
18 import java.time.ZonedDateTime;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.Set;
22
23 import javax.measure.Unit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.openweathermap.internal.config.OpenWeatherMapLocationConfiguration;
28 import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapConnection;
29 import org.openhab.core.i18n.CommunicationException;
30 import org.openhab.core.i18n.ConfigurationException;
31 import org.openhab.core.i18n.TimeZoneProvider;
32 import org.openhab.core.library.types.DateTimeType;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.PointType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.library.types.RawType;
37 import org.openhab.core.library.types.StringType;
38 import org.openhab.core.thing.Channel;
39 import org.openhab.core.thing.ChannelGroupUID;
40 import org.openhab.core.thing.ChannelUID;
41 import org.openhab.core.thing.Thing;
42 import org.openhab.core.thing.ThingStatus;
43 import org.openhab.core.thing.ThingStatusDetail;
44 import org.openhab.core.thing.ThingStatusInfo;
45 import org.openhab.core.thing.ThingTypeUID;
46 import org.openhab.core.thing.binding.BaseThingHandler;
47 import org.openhab.core.thing.binding.ThingHandlerCallback;
48 import org.openhab.core.thing.binding.builder.ChannelBuilder;
49 import org.openhab.core.thing.type.ChannelGroupTypeUID;
50 import org.openhab.core.thing.type.ChannelKind;
51 import org.openhab.core.types.Command;
52 import org.openhab.core.types.RefreshType;
53 import org.openhab.core.types.State;
54 import org.openhab.core.types.UnDefType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * The {@link AbstractOpenWeatherMapHandler} is responsible for handling commands, which are sent to one of the
60  * channels.
61  *
62  * @author Christoph Weitkamp - Initial contribution
63  */
64 @NonNullByDefault
65 public abstract class AbstractOpenWeatherMapHandler extends BaseThingHandler {
66
67     private final Logger logger = LoggerFactory.getLogger(AbstractOpenWeatherMapHandler.class);
68
69     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER_AND_FORECAST,
70             THING_TYPE_AIR_POLLUTION, THING_TYPE_ONECALL_WEATHER_AND_FORECAST, THING_TYPE_ONECALL_HISTORY);
71
72     private final TimeZoneProvider timeZoneProvider;
73
74     // keeps track of the parsed location
75     protected @Nullable PointType location;
76
77     public AbstractOpenWeatherMapHandler(Thing thing, final TimeZoneProvider timeZoneProvider) {
78         super(thing);
79         this.timeZoneProvider = timeZoneProvider;
80     }
81
82     @Override
83     public void initialize() {
84         OpenWeatherMapLocationConfiguration config = getConfigAs(OpenWeatherMapLocationConfiguration.class);
85
86         boolean configValid = true;
87         if (config.location == null || config.location.trim().isEmpty()) {
88             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
89                     "@text/offline.conf-error-missing-location");
90             configValid = false;
91         }
92
93         try {
94             location = new PointType(config.location);
95         } catch (IllegalArgumentException e) {
96             logger.warn("Error parsing 'location' parameter: {}", e.getMessage());
97             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
98                     "@text/offline.conf-error-parsing-location");
99             location = null;
100             configValid = false;
101         }
102
103         if (configValid) {
104             updateStatus(ThingStatus.UNKNOWN);
105         }
106     }
107
108     @Override
109     public void handleCommand(ChannelUID channelUID, Command command) {
110         if (command instanceof RefreshType) {
111             updateChannel(channelUID);
112         } else {
113             logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
114         }
115     }
116
117     @Override
118     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
119         if (ThingStatus.ONLINE.equals(bridgeStatusInfo.getStatus())
120                 && ThingStatusDetail.BRIDGE_OFFLINE.equals(getThing().getStatusInfo().getStatusDetail())) {
121             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
122         } else if (ThingStatus.OFFLINE.equals(bridgeStatusInfo.getStatus())
123                 && !ThingStatus.OFFLINE.equals(getThing().getStatus())) {
124             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
125         }
126     }
127
128     /**
129      * Updates OpenWeatherMap data for this location.
130      *
131      * @param connection {@link OpenWeatherMapConnection} instance
132      */
133     public void updateData(OpenWeatherMapConnection connection) {
134         try {
135             if (requestData(connection)) {
136                 updateChannels();
137                 updateStatus(ThingStatus.ONLINE);
138             }
139         } catch (CommunicationException e) {
140             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getRawMessage());
141         } catch (ConfigurationException e) {
142             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getRawMessage());
143         }
144     }
145
146     /**
147      * Requests the data from OpenWeatherMap API.
148      *
149      * @param connection {@link OpenWeatherMapConnection} instance
150      * @return true, if the request for the OpenWeatherMap data was successful
151      * @throws CommunicationException if there is a problem retrieving the data
152      * @throws ConfigurationException if there is a configuration error
153      */
154     protected abstract boolean requestData(OpenWeatherMapConnection connection)
155             throws CommunicationException, ConfigurationException;
156
157     /**
158      * Updates all channels of this handler from the latest OpenWeatherMap data retrieved.
159      */
160     private void updateChannels() {
161         for (Channel channel : getThing().getChannels()) {
162             ChannelUID channelUID = channel.getUID();
163             if (ChannelKind.STATE.equals(channel.getKind()) && channelUID.isInGroup() && channelUID.getGroupId() != null
164                     && isLinked(channelUID)) {
165                 updateChannel(channelUID);
166             }
167         }
168     }
169
170     /**
171      * Updates the channel with the given UID from the latest OpenWeatherMap data retrieved.
172      *
173      * @param channelUID UID of the channel
174      */
175     protected abstract void updateChannel(ChannelUID channelUID);
176
177     protected State getDateTimeTypeState(@Nullable Integer value) {
178         return (value == null) ? UnDefType.UNDEF
179                 : new DateTimeType(ZonedDateTime.ofInstant(Instant.ofEpochSecond(value.longValue()),
180                         timeZoneProvider.getTimeZone()));
181     }
182
183     protected State getDecimalTypeState(@Nullable Double value) {
184         return (value == null) ? UnDefType.UNDEF : new DecimalType(value);
185     }
186
187     protected State getPointTypeState(@Nullable Double latitude, @Nullable Double longitude) {
188         return ((latitude == null) || (longitude == null)) ? UnDefType.UNDEF
189                 : new PointType(new DecimalType(latitude), new DecimalType(longitude));
190     }
191
192     protected State getRawTypeState(@Nullable RawType image) {
193         return (image == null) ? UnDefType.UNDEF : image;
194     }
195
196     protected State getStringTypeState(@Nullable String value) {
197         return (value == null) ? UnDefType.UNDEF : new StringType(value);
198     }
199
200     protected State getQuantityTypeState(@Nullable Number value, Unit<?> unit) {
201         return (value == null) ? UnDefType.UNDEF : new QuantityType<>(value, unit);
202     }
203
204     protected List<Channel> createChannelsForGroup(String channelGroupId, ChannelGroupTypeUID channelGroupTypeUID) {
205         logger.debug("Building channel group '{}' for thing '{}' and GroupType '{}'.", channelGroupId,
206                 getThing().getUID(), channelGroupTypeUID);
207         List<Channel> channels = new ArrayList<>();
208         ThingHandlerCallback callback = getCallback();
209         if (callback != null) {
210             for (ChannelBuilder channelBuilder : callback.createChannelBuilders(
211                     new ChannelGroupUID(getThing().getUID(), channelGroupId), channelGroupTypeUID)) {
212                 Channel newChannel = channelBuilder.build(),
213                         existingChannel = getThing().getChannel(newChannel.getUID().getId());
214                 if (existingChannel != null) {
215                     logger.trace("Thing '{}' already has an existing channel '{}'. Omit adding new channel '{}'.",
216                             getThing().getUID(), existingChannel.getUID(), newChannel.getUID());
217                     continue;
218                 }
219                 channels.add(newChannel);
220             }
221         }
222         logger.debug("Built channels: {}", channels);
223         return channels;
224     }
225
226     protected List<Channel> removeChannelsOfGroup(String channelGroupId) {
227         logger.debug("Removing channel group '{}' from thing '{}'.", channelGroupId, getThing().getUID());
228         return getThing().getChannelsOfGroup(channelGroupId);
229     }
230 }