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