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.Status;
28 import org.openhab.binding.amplipi.internal.model.Zone;
29 import org.openhab.binding.amplipi.internal.model.ZoneUpdate;
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 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 public AmpliPiZoneHandler(Thing thing, HttpClient httpClient) {
64 this.httpClient = httpClient;
65 this.gson = new Gson();
69 public void initialize() {
70 Bridge bridge = getBridge();
72 bridgeHandler = (AmpliPiHandler) bridge.getHandler();
73 if (bridgeHandler != null) {
74 bridgeHandler.addStatusChangeListener(this);
76 throw new IllegalStateException("Bridge handler must not be null here!");
78 if (bridge.getStatus() == ThingStatus.ONLINE) {
79 updateStatus(ThingStatus.ONLINE);
81 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
84 throw new IllegalStateException("Bridge must not be null here!");
88 private int getId(Thing thing) {
89 return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
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 ZoneUpdate update = new ZoneUpdate();
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.setVol(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/zones/" + 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(@NonNull Status status) {
137 int id = getId(thing);
138 Optional<Zone> zone = status.getZones().stream().filter(z -> z.getId().equals(id)).findFirst();
139 if (zone.isPresent()) {
140 Boolean mute = zone.get().getMute();
141 Integer volume = zone.get().getVol();
142 Integer source = zone.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));