2 * Copyright (c) 2010-2021 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.harmonyhub.internal.handler;
15 import static org.openhab.binding.harmonyhub.internal.HarmonyHubBindingConstants.*;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.Comparator;
20 import java.util.LinkedList;
21 import java.util.List;
23 import java.util.concurrent.CompletableFuture;
24 import java.util.concurrent.CopyOnWriteArrayList;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.harmonyhub.internal.HarmonyHubHandlerFactory;
31 import org.openhab.binding.harmonyhub.internal.config.HarmonyHubConfig;
32 import org.openhab.core.config.core.Configuration;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.NextPreviousType;
35 import org.openhab.core.library.types.PlayPauseType;
36 import org.openhab.core.library.types.RewindFastforwardType;
37 import org.openhab.core.library.types.StringType;
38 import org.openhab.core.thing.Bridge;
39 import org.openhab.core.thing.Channel;
40 import org.openhab.core.thing.ChannelUID;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.thing.ThingTypeUID;
44 import org.openhab.core.thing.binding.BaseBridgeHandler;
45 import org.openhab.core.thing.binding.builder.BridgeBuilder;
46 import org.openhab.core.thing.binding.builder.ChannelBuilder;
47 import org.openhab.core.thing.type.ChannelType;
48 import org.openhab.core.thing.type.ChannelTypeBuilder;
49 import org.openhab.core.thing.type.ChannelTypeUID;
50 import org.openhab.core.types.Command;
51 import org.openhab.core.types.RefreshType;
52 import org.openhab.core.types.StateDescriptionFragmentBuilder;
53 import org.openhab.core.types.StateOption;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 import com.digitaldan.harmony.HarmonyClient;
58 import com.digitaldan.harmony.HarmonyClientListener;
59 import com.digitaldan.harmony.config.Activity;
60 import com.digitaldan.harmony.config.Activity.Status;
61 import com.digitaldan.harmony.config.HarmonyConfig;
64 * The {@link HarmonyHubHandler} is responsible for handling commands for Harmony Hubs, which are
65 * sent to one of the channels.
67 * @author Dan Cunningham - Initial contribution
68 * @author Pawel Pieczul - added support for hub status changes
69 * @author Wouter Born - Add null annotations
72 public class HarmonyHubHandler extends BaseBridgeHandler implements HarmonyClientListener {
74 private final Logger logger = LoggerFactory.getLogger(HarmonyHubHandler.class);
76 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(HARMONY_HUB_THING_TYPE);
78 private static final Comparator<Activity> ACTIVITY_COMPERATOR = Comparator.comparing(Activity::getActivityOrder,
79 Comparator.nullsFirst(Integer::compareTo));
81 private static final int RETRY_TIME = 60;
82 private static final int HEARTBEAT_INTERVAL = 30;
83 // Websocket will timeout after 60 seconds, pick a sensible max under this,
84 private static final int HEARTBEAT_INTERVAL_MAX = 50;
85 private List<HubStatusListener> listeners = new CopyOnWriteArrayList<>();
86 private final HarmonyHubHandlerFactory factory;
87 private @NonNullByDefault({}) HarmonyHubConfig config;
88 private final HarmonyClient client;
89 private @Nullable ScheduledFuture<?> retryJob;
90 private @Nullable ScheduledFuture<?> heartBeatJob;
92 private int heartBeatInterval;
94 public HarmonyHubHandler(Bridge bridge, HarmonyHubHandlerFactory factory) {
96 this.factory = factory;
97 client = new HarmonyClient(factory.getHttpClient());
98 client.addListener(this);
102 public void handleCommand(ChannelUID channelUID, Command command) {
103 logger.trace("Handling command '{}' for {}", command, channelUID);
105 if (getThing().getStatus() != ThingStatus.ONLINE) {
106 logger.debug("Hub is offline, ignoring command {} for channel {}", command, channelUID);
110 if (command instanceof RefreshType) {
111 client.getCurrentActivity().thenAccept(activity -> {
112 updateState(activity);
117 Channel channel = getThing().getChannel(channelUID.getId());
118 if (channel == null) {
119 logger.warn("No such channel for UID {}", channelUID);
123 switch (channel.getUID().getId()) {
124 case CHANNEL_CURRENT_ACTIVITY:
125 if (command instanceof DecimalType) {
127 client.startActivity(((DecimalType) command).intValue());
128 } catch (Exception e) {
129 logger.warn("Could not start activity", e);
134 int actId = Integer.parseInt(command.toString());
135 client.startActivity(actId);
136 } catch (NumberFormatException ignored) {
137 client.startActivityByName(command.toString());
139 } catch (IllegalArgumentException e) {
140 logger.warn("Activity '{}' is not known by the hub, ignoring it.", command);
141 } catch (Exception e) {
142 logger.warn("Could not start activity", e);
146 case CHANNEL_BUTTON_PRESS:
147 client.pressButtonCurrentActivity(command.toString());
151 if (command instanceof PlayPauseType) {
152 if (command == PlayPauseType.PLAY) {
154 } else if (command == PlayPauseType.PAUSE) {
157 } else if (command instanceof NextPreviousType) {
158 if (command == NextPreviousType.NEXT) {
160 } else if (command == NextPreviousType.PREVIOUS) {
161 cmd = "SkipBackward";
163 } else if (command instanceof RewindFastforwardType) {
164 if (command == RewindFastforwardType.FASTFORWARD) {
166 } else if (command == RewindFastforwardType.REWIND) {
171 client.pressButtonCurrentActivity(cmd);
173 logger.warn("Unknown player type {}", command);
177 logger.warn("Unknown channel id {}", channel.getUID().getId());
182 public void initialize() {
183 config = getConfigAs(HarmonyHubConfig.class);
185 updateStatus(ThingStatus.UNKNOWN);
186 retryJob = scheduler.schedule(this::connect, 0, TimeUnit.SECONDS);
190 public void dispose() {
194 factory.removeChannelTypesForThing(getThing().getUID());
198 protected void updateStatus(ThingStatus status, ThingStatusDetail detail, @Nullable String comment) {
199 super.updateStatus(status, detail, comment);
200 logger.debug("Updating listeners with status {}", status);
201 for (HubStatusListener listener : listeners) {
202 listener.hubStatusChanged(status);
207 public void channelLinked(ChannelUID channelUID) {
208 client.getCurrentActivity().thenAccept((activity) -> {
209 updateState(channelUID, new StringType(activity.getLabel()));
214 public void hubDisconnected(@Nullable String reason) {
215 if (getThing().getStatus() == ThingStatus.ONLINE) {
216 setOfflineAndReconnect(String.format("Could not connect: %s", reason));
221 public void hubConnected() {
222 heartBeatJob = scheduler.scheduleWithFixedDelay(() -> {
225 } catch (Exception e) {
226 logger.debug("heartbeat failed", e);
227 setOfflineAndReconnect("Hearbeat failed");
229 }, heartBeatInterval, heartBeatInterval, TimeUnit.SECONDS);
230 updateStatus(ThingStatus.ONLINE);
231 getConfigFuture().thenAcceptAsync(harmonyConfig -> updateCurrentActivityChannel(harmonyConfig), scheduler)
232 .exceptionally(e -> {
233 setOfflineAndReconnect("Getting config failed: " + e.getMessage());
236 client.getCurrentActivity().thenAccept(activity -> {
237 updateState(activity);
242 public void activityStatusChanged(@Nullable Activity activity, @Nullable Status status) {
243 updateActivityStatus(activity, status);
247 public void activityStarted(@Nullable Activity activity) {
248 updateState(activity);
252 * Starts the connection process
254 private synchronized void connect() {
257 heartBeatInterval = Math.min(config.heartBeatInterval > 0 ? config.heartBeatInterval : HEARTBEAT_INTERVAL,
258 HEARTBEAT_INTERVAL_MAX);
260 String host = config.host;
262 // earlier versions required a name and used network discovery to find the hub and retrieve the host,
263 // this section is to not break that and also update older configurations to use the host configuration
264 // option instead of name
265 if (host == null || host.isBlank()) {
266 host = getThing().getProperties().get(HUB_PROPERTY_HOST);
267 if (host != null && !host.isBlank()) {
268 Configuration genericConfig = getConfig();
269 genericConfig.put(HUB_PROPERTY_HOST, host);
270 updateConfiguration(genericConfig);
272 logger.debug("host not configured");
273 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "host not configured");
279 logger.debug("Connecting: host {}", host);
280 client.connect(host);
281 } catch (Exception e) {
282 logger.debug("Could not connect to HarmonyHub at {}", host, e);
283 setOfflineAndReconnect("Could not connect: " + e.getMessage());
287 private void disconnectFromHub() {
288 ScheduledFuture<?> localHeartBeatJob = heartBeatJob;
289 if (localHeartBeatJob != null && !localHeartBeatJob.isDone()) {
290 localHeartBeatJob.cancel(false);
295 private void setOfflineAndReconnect(String error) {
297 retryJob = scheduler.schedule(this::connect, RETRY_TIME, TimeUnit.SECONDS);
298 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error);
301 private void cancelRetry() {
302 ScheduledFuture<?> localRetryJob = retryJob;
303 if (localRetryJob != null && !localRetryJob.isDone()) {
304 localRetryJob.cancel(false);
308 private void updateState(@Nullable Activity activity) {
309 if (activity != null) {
310 logger.debug("Updating current activity to {}", activity.getLabel());
311 updateState(new ChannelUID(getThing().getUID(), CHANNEL_CURRENT_ACTIVITY),
312 new StringType(activity.getLabel()));
316 private void updateActivityStatus(@Nullable Activity activity, @Nullable Status status) {
317 if (activity == null) {
318 logger.debug("Cannot update activity status of {} with activity that is null", getThing().getUID());
320 } else if (status == null) {
321 logger.debug("Cannot update activity status of {} with status that is null", getThing().getUID());
325 logger.debug("Received {} activity status for {}", status, activity.getLabel());
327 case ACTIVITY_IS_STARTING:
328 triggerChannel(CHANNEL_ACTIVITY_STARTING_TRIGGER, getEventName(activity));
330 case ACTIVITY_IS_STARTED:
332 // hub is off is received with power-off activity
333 triggerChannel(CHANNEL_ACTIVITY_STARTED_TRIGGER, getEventName(activity));
335 case HUB_IS_TURNING_OFF:
336 // hub is turning off is received for current activity, we will translate it into activity starting
337 // trigger of power-off activity (with ID=-1)
338 getConfigFuture().thenAccept(config -> {
339 if (config != null) {
340 Activity powerOff = config.getActivityById(-1);
341 if (powerOff != null) {
342 triggerChannel(CHANNEL_ACTIVITY_STARTING_TRIGGER, getEventName(powerOff));
345 }).exceptionally(e -> {
346 setOfflineAndReconnect("Getting config failed: " + e.getMessage());
355 private String getEventName(Activity activity) {
356 return activity.getLabel().replaceAll("[^A-Za-z0-9]", "_");
360 * Updates the current activity channel with the available activities as option states.
362 private void updateCurrentActivityChannel(@Nullable HarmonyConfig config) {
363 ChannelTypeUID channelTypeUID = new ChannelTypeUID(getThing().getUID() + ":" + CHANNEL_CURRENT_ACTIVITY);
365 if (config == null) {
366 logger.debug("Cannot update {} when HarmonyConfig is null", channelTypeUID);
370 logger.debug("Updating {}", channelTypeUID);
372 List<Activity> activities = config.getActivities();
373 // sort our activities in order
374 Collections.sort(activities, ACTIVITY_COMPERATOR);
376 // add our activities as channel state options
377 List<StateOption> states = new LinkedList<>();
378 for (Activity activity : activities) {
379 states.add(new StateOption(activity.getLabel(), activity.getLabel()));
382 ChannelType channelType = ChannelTypeBuilder.state(channelTypeUID, "Current Activity", "String")
383 .withDescription("Current activity for " + getThing().getLabel())
384 .withStateDescriptionFragment(StateDescriptionFragmentBuilder.create().withPattern("%s")
385 .withReadOnly(false).withOptions(states).build())
388 factory.addChannelType(channelType);
390 Channel channel = ChannelBuilder.create(new ChannelUID(getThing().getUID(), CHANNEL_CURRENT_ACTIVITY), "String")
391 .withType(channelTypeUID).build();
393 // replace existing currentActivity with updated one
394 List<Channel> newChannels = new ArrayList<>();
395 for (Channel c : getThing().getChannels()) {
396 if (!c.getUID().equals(channel.getUID())) {
400 newChannels.add(channel);
402 BridgeBuilder thingBuilder = editThing();
403 thingBuilder.withChannels(newChannels);
404 updateThing(thingBuilder.build());
408 * Sends a button press to a device
413 public void pressButton(int device, String button) {
414 client.pressButton(device, button);
418 * Sends a button press to a device
423 public void pressButton(String device, String button) {
424 client.pressButton(device, button);
427 public CompletableFuture<@Nullable HarmonyConfig> getConfigFuture() {
428 return client.getConfig();
432 * Adds a HubConnectedListener
436 public void addHubStatusListener(HubStatusListener listener) {
437 listeners.add(listener);
438 listener.hubStatusChanged(getThing().getStatus());
442 * Removes a HubConnectedListener
446 public void removeHubStatusListener(HubStatusListener listener) {
447 listeners.remove(listener);