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.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.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 AmpliPiZoneHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
54 private final Logger logger = LoggerFactory.getLogger(AmpliPiZoneHandler.class);
56 private final HttpClient httpClient;
57 private final Gson gson;
59 private @Nullable AmpliPiHandler bridgeHandler;
61 public AmpliPiZoneHandler(Thing thing, HttpClient httpClient) {
63 this.httpClient = httpClient;
64 this.gson = new Gson();
68 public void initialize() {
69 Bridge bridge = getBridge();
71 bridgeHandler = (AmpliPiHandler) bridge.getHandler();
72 if (bridgeHandler != null) {
73 bridgeHandler.addStatusChangeListener(this);
75 throw new IllegalStateException("Bridge handler must not be null here!");
77 if (bridge.getStatus() == ThingStatus.ONLINE) {
78 updateStatus(ThingStatus.ONLINE);
80 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
83 throw new IllegalStateException("Bridge must not be null here!");
87 private int getId(Thing thing) {
88 return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
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 ZoneUpdate update = new ZoneUpdate();
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.setVol(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/zones/" + getId(thing);
117 StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
119 ContentResponse response = httpClient.newRequest(url).method(HttpMethod.PATCH)
120 .content(contentProvider, "application/json").send();
121 if (response.getStatus() != HttpStatus.OK_200) {
122 logger.error("AmpliPi API returned HTTP status {}.", response.getStatus());
123 logger.debug("Content: {}", response.getContentAsString());
125 updateStatus(ThingStatus.ONLINE);
127 } catch (InterruptedException | TimeoutException | ExecutionException e) {
128 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
129 "AmpliPi request failed: " + e.getMessage());
135 public void receive(Status status) {
136 int id = getId(thing);
137 Optional<Zone> zone = status.getZones().stream().filter(z -> z.getId().equals(id)).findFirst();
138 if (zone.isPresent()) {
139 Boolean mute = zone.get().getMute();
140 Integer volume = zone.get().getVol();
141 Integer source = zone.get().getSourceId();
142 updateState(AmpliPiBindingConstants.CHANNEL_MUTE, mute ? OnOffType.ON : OnOffType.OFF);
143 updateState(AmpliPiBindingConstants.CHANNEL_VOLUME, AmpliPiUtils.volumeToPercentType(volume));
144 updateState(AmpliPiBindingConstants.CHANNEL_SOURCE, new DecimalType(source));