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.amplipi.internal;
15 import java.util.Optional;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.TimeoutException;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.eclipse.jetty.client.HttpClient;
23 import org.eclipse.jetty.client.api.ContentResponse;
24 import org.eclipse.jetty.client.util.StringContentProvider;
25 import org.eclipse.jetty.http.HttpMethod;
26 import org.eclipse.jetty.http.HttpStatus;
27 import org.openhab.binding.amplipi.internal.model.Group;
28 import org.openhab.binding.amplipi.internal.model.GroupUpdate;
29 import org.openhab.binding.amplipi.internal.model.Status;
30 import org.openhab.core.library.types.DecimalType;
31 import org.openhab.core.library.types.OnOffType;
32 import org.openhab.core.library.types.PercentType;
33 import org.openhab.core.thing.Bridge;
34 import org.openhab.core.thing.ChannelUID;
35 import org.openhab.core.thing.Thing;
36 import org.openhab.core.thing.ThingStatus;
37 import org.openhab.core.thing.ThingStatusDetail;
38 import org.openhab.core.thing.binding.BaseThingHandler;
39 import org.openhab.core.types.Command;
40 import org.openhab.core.types.RefreshType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 import com.google.gson.Gson;
47 * The {@link AmpliPiGroupHandler} is responsible for handling commands, which are
48 * sent to one of the AmpliPi Groups.
50 * @author Kai Kreuzer - Initial contribution
53 public class AmpliPiGroupHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
55 private final Logger logger = LoggerFactory.getLogger(AmpliPiGroupHandler.class);
57 private final HttpClient httpClient;
58 private final Gson gson;
60 private @Nullable AmpliPiHandler bridgeHandler;
62 public AmpliPiGroupHandler(Thing thing, HttpClient httpClient) {
64 this.httpClient = httpClient;
65 this.gson = new Gson();
68 private int getId(Thing thing) {
69 return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
73 public void initialize() {
74 Bridge bridge = getBridge();
76 bridgeHandler = (AmpliPiHandler) bridge.getHandler();
77 if (bridgeHandler != null) {
78 bridgeHandler.addStatusChangeListener(this);
80 throw new IllegalStateException("Bridge handler must not be null here!");
82 if (bridge.getStatus() == ThingStatus.ONLINE) {
83 updateStatus(ThingStatus.ONLINE);
85 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
88 throw new IllegalStateException("Bridge must not be null here!");
93 public void handleCommand(@NonNull ChannelUID channelUID, @NonNull Command command) {
94 if (command == RefreshType.REFRESH) {
95 // do nothing - we just wait for the next automatic refresh
98 GroupUpdate update = new GroupUpdate();
99 switch (channelUID.getId()) {
100 case AmpliPiBindingConstants.CHANNEL_MUTE:
101 if (command instanceof OnOffType) {
102 update.setMute(command == OnOffType.ON);
105 case AmpliPiBindingConstants.CHANNEL_VOLUME:
106 if (command instanceof PercentType) {
107 update.setVolDelta(AmpliPiUtils.percentTypeToVolume((PercentType) command));
110 case AmpliPiBindingConstants.CHANNEL_SOURCE:
111 if (command instanceof DecimalType) {
112 update.setSourceId(((DecimalType) command).intValue());
116 if (bridgeHandler != null) {
117 String url = bridgeHandler.getUrl() + "/api/groups/" + getId(thing);
119 StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
121 ContentResponse response = httpClient.newRequest(url).method(HttpMethod.PATCH)
122 .content(contentProvider, "application/json").send();
123 if (response.getStatus() != HttpStatus.OK_200) {
124 logger.error("AmpliPi API returned HTTP status {}.", response.getStatus());
125 logger.debug("Content: {}", response.getContentAsString());
127 updateStatus(ThingStatus.ONLINE);
129 } catch (InterruptedException | TimeoutException | ExecutionException e) {
130 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
131 "AmpliPi request failed: " + e.getMessage());
137 public void receive(@NonNull Status status) {
138 int id = getId(thing);
139 Optional<Group> group = status.getGroups().stream().filter(z -> z.getId().equals(id)).findFirst();
140 if (group.isPresent()) {
141 Boolean mute = group.get().getMute();
142 Integer volume = group.get().getVolDelta();
143 Integer source = group.get().getSourceId();
144 updateState(AmpliPiBindingConstants.CHANNEL_MUTE, mute ? OnOffType.ON : OnOffType.OFF);
145 updateState(AmpliPiBindingConstants.CHANNEL_VOLUME, AmpliPiUtils.volumeToPercentType(volume));
146 updateState(AmpliPiBindingConstants.CHANNEL_SOURCE, new DecimalType(source));