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.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.Status;
27 import org.openhab.binding.amplipi.internal.model.Zone;
28 import org.openhab.binding.amplipi.internal.model.ZoneUpdate;
29 import org.openhab.core.library.types.DecimalType;
30 import org.openhab.core.library.types.IncreaseDecreaseType;
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 AmpliPiZoneHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
55 private final Logger logger = LoggerFactory.getLogger(AmpliPiZoneHandler.class);
57 private final HttpClient httpClient;
58 private final Gson gson;
60 private @Nullable AmpliPiHandler bridgeHandler;
62 private @Nullable Zone zoneState;
64 public AmpliPiZoneHandler(Thing thing, HttpClient httpClient) {
66 this.httpClient = httpClient;
67 this.gson = new Gson();
71 public void initialize() {
72 Bridge bridge = getBridge();
74 bridgeHandler = (AmpliPiHandler) bridge.getHandler();
75 if (bridgeHandler != null) {
76 bridgeHandler.addStatusChangeListener(this);
78 throw new IllegalStateException("Bridge handler must not be null here!");
80 if (bridge.getStatus() == ThingStatus.ONLINE) {
81 updateStatus(ThingStatus.ONLINE);
83 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
86 throw new IllegalStateException("Bridge must not be null here!");
90 private int getId(Thing thing) {
91 return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
94 private int getVolumeDelta(Thing thing) {
95 return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_VOLUME_DELTA).toString());
99 public void handleCommand(ChannelUID channelUID, Command command) {
100 if (command == RefreshType.REFRESH) {
101 // do nothing - we just wait for the next automatic refresh
104 ZoneUpdate update = new ZoneUpdate();
105 switch (channelUID.getId()) {
106 case AmpliPiBindingConstants.CHANNEL_MUTE:
107 if (command instanceof OnOffType) {
108 update.setMute(command == OnOffType.ON);
111 case AmpliPiBindingConstants.CHANNEL_VOLUME:
112 if (command instanceof PercentType percentCommand) {
113 update.setVol(AmpliPiUtils.percentTypeToVolume(percentCommand));
114 } else if (command instanceof IncreaseDecreaseType) {
115 if (zoneState != null) {
116 if (IncreaseDecreaseType.INCREASE.equals(command)) {
118 Math.min(zoneState.getVol() + getVolumeDelta(thing), AmpliPiUtils.MAX_VOLUME_DB));
121 Math.max(zoneState.getVol() - getVolumeDelta(thing), AmpliPiUtils.MIN_VOLUME_DB));
123 update.setVol(zoneState.getVol());
127 case AmpliPiBindingConstants.CHANNEL_SOURCE:
128 if (command instanceof DecimalType decimalCommand) {
129 update.setSourceId(decimalCommand.intValue());
133 if (bridgeHandler != null) {
134 String url = bridgeHandler.getUrl() + "/api/zones/" + getId(thing);
135 StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
137 ContentResponse response = httpClient.newRequest(url).method(HttpMethod.PATCH)
138 .content(contentProvider, "application/json").send();
139 if (response.getStatus() != HttpStatus.OK_200) {
140 logger.error("AmpliPi API returned HTTP status {}.", response.getStatus());
141 logger.debug("Content: {}", response.getContentAsString());
143 updateStatus(ThingStatus.ONLINE);
145 } catch (InterruptedException | TimeoutException | ExecutionException e) {
146 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
147 "AmpliPi request failed: " + e.getMessage());
153 public void receive(Status status) {
154 int id = getId(thing);
155 Optional<Zone> zone = status.getZones().stream().filter(z -> z.getId().equals(id)).findFirst();
156 zone.ifPresent(this::updateZoneState);
159 private void updateZoneState(Zone state) {
160 this.zoneState = state;
162 Boolean mute = zoneState.getMute();
163 Integer vol = zoneState.getVol();
164 Integer sourceId = zoneState.getSourceId();
166 updateState(AmpliPiBindingConstants.CHANNEL_MUTE, mute ? OnOffType.ON : OnOffType.OFF);
167 updateState(AmpliPiBindingConstants.CHANNEL_VOLUME, AmpliPiUtils.volumeToPercentType(vol));
168 updateState(AmpliPiBindingConstants.CHANNEL_SOURCE, new DecimalType(sourceId));