2 * Copyright (c) 2010-2024 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_AIR_POLLUTION, THING_TYPE_ONECALL_WEATHER_AND_FORECAST, THING_TYPE_ONECALL_HISTORY);
72 private final TimeZoneProvider timeZoneProvider;
74 // keeps track of the parsed location
75 protected @Nullable PointType location;
77 public AbstractOpenWeatherMapHandler(Thing thing, final TimeZoneProvider timeZoneProvider) {
79 this.timeZoneProvider = timeZoneProvider;
83 public void initialize() {
84 OpenWeatherMapLocationConfiguration config = getConfigAs(OpenWeatherMapLocationConfiguration.class);
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");
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");
104 updateStatus(ThingStatus.UNKNOWN);
109 public void handleCommand(ChannelUID channelUID, Command command) {
110 if (command instanceof RefreshType) {
111 updateChannel(channelUID);
113 logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
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);
129 * Updates OpenWeatherMap data for this location.
131 * @param connection {@link OpenWeatherMapConnection} instance
133 public void updateData(OpenWeatherMapConnection connection) {
135 if (requestData(connection)) {
137 updateStatus(ThingStatus.ONLINE);
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());
147 * Requests the data from OpenWeatherMap API.
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
154 protected abstract boolean requestData(OpenWeatherMapConnection connection)
155 throws CommunicationException, ConfigurationException;
158 * Updates all channels of this handler from the latest OpenWeatherMap data retrieved.
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);
171 * Updates the channel with the given UID from the latest OpenWeatherMap data retrieved.
173 * @param channelUID UID of the channel
175 protected abstract void updateChannel(ChannelUID channelUID);
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()));
183 protected State getDecimalTypeState(@Nullable Double value) {
184 return (value == null) ? UnDefType.UNDEF : new DecimalType(value);
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));
192 protected State getRawTypeState(@Nullable RawType image) {
193 return (image == null) ? UnDefType.UNDEF : image;
196 protected State getStringTypeState(@Nullable String value) {
197 return (value == null) ? UnDefType.UNDEF : new StringType(value);
200 protected State getQuantityTypeState(@Nullable Number value, Unit<?> unit) {
201 return (value == null) ? UnDefType.UNDEF : new QuantityType<>(value, unit);
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());
219 channels.add(newChannel);
222 logger.debug("Built channels: {}", channels);
226 protected List<Channel> removeChannelsOfGroup(String channelGroupId) {
227 logger.debug("Removing channel group '{}' from thing '{}'.", channelGroupId, getThing().getUID());
228 return getThing().getChannelsOfGroup(channelGroupId);