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.openweathermap.internal.handler;
15 import static org.openhab.binding.openweathermap.internal.OpenWeatherMapBindingConstants.*;
17 import java.time.Instant;
18 import java.time.ZonedDateTime;
19 import java.util.ArrayList;
20 import java.util.List;
23 import javax.measure.Unit;
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;
59 * The {@link AbstractOpenWeatherMapHandler} is responsible for handling commands, which are sent to one of the
62 * @author Christoph Weitkamp - Initial contribution
65 public abstract class AbstractOpenWeatherMapHandler extends BaseThingHandler {
67 private final Logger logger = LoggerFactory.getLogger(AbstractOpenWeatherMapHandler.class);
69 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER_AND_FORECAST,
70 THING_TYPE_UVINDEX, THING_TYPE_AIR_POLLUTION, THING_TYPE_ONECALL_WEATHER_AND_FORECAST,
71 THING_TYPE_ONECALL_HISTORY);
73 private final TimeZoneProvider timeZoneProvider;
75 // keeps track of the parsed location
76 protected @Nullable PointType location;
78 public AbstractOpenWeatherMapHandler(Thing thing, final TimeZoneProvider timeZoneProvider) {
80 this.timeZoneProvider = timeZoneProvider;
84 public void initialize() {
85 OpenWeatherMapLocationConfiguration config = getConfigAs(OpenWeatherMapLocationConfiguration.class);
87 boolean configValid = true;
88 if (config.location == null || config.location.trim().isEmpty()) {
89 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
90 "@text/offline.conf-error-missing-location");
95 location = new PointType(config.location);
96 } catch (IllegalArgumentException e) {
97 logger.warn("Error parsing 'location' parameter: {}", e.getMessage());
98 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
99 "@text/offline.conf-error-parsing-location");
105 updateStatus(ThingStatus.UNKNOWN);
110 public void handleCommand(ChannelUID channelUID, Command command) {
111 if (command instanceof RefreshType) {
112 updateChannel(channelUID);
114 logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
119 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
120 if (ThingStatus.ONLINE.equals(bridgeStatusInfo.getStatus())
121 && ThingStatusDetail.BRIDGE_OFFLINE.equals(getThing().getStatusInfo().getStatusDetail())) {
122 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
123 } else if (ThingStatus.OFFLINE.equals(bridgeStatusInfo.getStatus())
124 && !ThingStatus.OFFLINE.equals(getThing().getStatus())) {
125 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
130 * Updates OpenWeatherMap data for this location.
132 * @param connection {@link OpenWeatherMapConnection} instance
134 public void updateData(OpenWeatherMapConnection connection) {
136 if (requestData(connection)) {
138 updateStatus(ThingStatus.ONLINE);
140 } catch (CommunicationException e) {
141 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getRawMessage());
142 } catch (ConfigurationException e) {
143 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getRawMessage());
148 * Requests the data from OpenWeatherMap API.
150 * @param connection {@link OpenWeatherMapConnection} instance
151 * @return true, if the request for the OpenWeatherMap data was successful
152 * @throws CommunicationException if there is a problem retrieving the data
153 * @throws ConfigurationException if there is a configuration error
155 protected abstract boolean requestData(OpenWeatherMapConnection connection)
156 throws CommunicationException, ConfigurationException;
159 * Updates all channels of this handler from the latest OpenWeatherMap data retrieved.
161 private void updateChannels() {
162 for (Channel channel : getThing().getChannels()) {
163 ChannelUID channelUID = channel.getUID();
164 if (ChannelKind.STATE.equals(channel.getKind()) && channelUID.isInGroup() && channelUID.getGroupId() != null
165 && isLinked(channelUID)) {
166 updateChannel(channelUID);
172 * Updates the channel with the given UID from the latest OpenWeatherMap data retrieved.
174 * @param channelUID UID of the channel
176 protected abstract void updateChannel(ChannelUID channelUID);
178 protected State getDateTimeTypeState(@Nullable Integer value) {
179 return (value == null) ? UnDefType.UNDEF
180 : new DateTimeType(ZonedDateTime.ofInstant(Instant.ofEpochSecond(value.longValue()),
181 timeZoneProvider.getTimeZone()));
184 protected State getDecimalTypeState(@Nullable Double value) {
185 return (value == null) ? UnDefType.UNDEF : new DecimalType(value);
188 protected State getPointTypeState(@Nullable Double latitude, @Nullable Double longitude) {
189 return ((latitude == null) || (longitude == null)) ? UnDefType.UNDEF
190 : new PointType(new DecimalType(latitude), new DecimalType(longitude));
193 protected State getRawTypeState(@Nullable RawType image) {
194 return (image == null) ? UnDefType.UNDEF : image;
197 protected State getStringTypeState(@Nullable String value) {
198 return (value == null) ? UnDefType.UNDEF : new StringType(value);
201 protected State getQuantityTypeState(@Nullable Number value, Unit<?> unit) {
202 return (value == null) ? UnDefType.UNDEF : new QuantityType<>(value, unit);
205 protected List<Channel> createChannelsForGroup(String channelGroupId, ChannelGroupTypeUID channelGroupTypeUID) {
206 logger.debug("Building channel group '{}' for thing '{}' and GroupType '{}'.", channelGroupId,
207 getThing().getUID(), channelGroupTypeUID);
208 List<Channel> channels = new ArrayList<>();
209 ThingHandlerCallback callback = getCallback();
210 if (callback != null) {
211 for (ChannelBuilder channelBuilder : callback.createChannelBuilders(
212 new ChannelGroupUID(getThing().getUID(), channelGroupId), channelGroupTypeUID)) {
213 Channel newChannel = channelBuilder.build(),
214 existingChannel = getThing().getChannel(newChannel.getUID().getId());
215 if (existingChannel != null) {
216 logger.trace("Thing '{}' already has an existing channel '{}'. Omit adding new channel '{}'.",
217 getThing().getUID(), existingChannel.getUID(), newChannel.getUID());
220 channels.add(newChannel);
223 logger.debug("Built channels: {}", channels);
227 protected List<Channel> removeChannelsOfGroup(String channelGroupId) {
228 logger.debug("Removing channel group '{}' from thing '{}'.", channelGroupId, getThing().getUID());
229 return getThing().getChannelsOfGroup(channelGroupId);