]> git.basschouten.com Git - openhab-addons.git/blob
870a9af3f759f138ad872cfacb95de14554bbb29
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.amplipi.internal;
14
15 import java.util.Optional;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.TimeoutException;
18
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;
43
44 import com.google.gson.Gson;
45
46 /**
47  * The {@link AmpliPiGroupHandler} is responsible for handling commands, which are
48  * sent to one of the AmpliPi Groups.
49  *
50  * @author Kai Kreuzer - Initial contribution
51  */
52 @NonNullByDefault
53 public class AmpliPiZoneHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
54
55     private final Logger logger = LoggerFactory.getLogger(AmpliPiZoneHandler.class);
56
57     private final HttpClient httpClient;
58     private final Gson gson;
59
60     private @Nullable AmpliPiHandler bridgeHandler;
61
62     private @Nullable Zone zoneState;
63
64     public AmpliPiZoneHandler(Thing thing, HttpClient httpClient) {
65         super(thing);
66         this.httpClient = httpClient;
67         this.gson = new Gson();
68     }
69
70     @Override
71     public void initialize() {
72         Bridge bridge = getBridge();
73         if (bridge != null) {
74             bridgeHandler = (AmpliPiHandler) bridge.getHandler();
75             if (bridgeHandler != null) {
76                 bridgeHandler.addStatusChangeListener(this);
77             } else {
78                 throw new IllegalStateException("Bridge handler must not be null here!");
79             }
80             if (bridge.getStatus() == ThingStatus.ONLINE) {
81                 updateStatus(ThingStatus.ONLINE);
82             } else {
83                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
84             }
85         } else {
86             throw new IllegalStateException("Bridge must not be null here!");
87         }
88     }
89
90     private int getId(Thing thing) {
91         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
92     }
93
94     private int getVolumeDelta(Thing thing) {
95         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_VOLUME_DELTA).toString());
96     }
97
98     @Override
99     public void handleCommand(ChannelUID channelUID, Command command) {
100         if (command == RefreshType.REFRESH) {
101             // do nothing - we just wait for the next automatic refresh
102             return;
103         }
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);
109                 }
110                 break;
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)) {
117                             zoneState.setVol(
118                                     Math.min(zoneState.getVol() + getVolumeDelta(thing), AmpliPiUtils.MAX_VOLUME_DB));
119                         } else {
120                             zoneState.setVol(
121                                     Math.max(zoneState.getVol() - getVolumeDelta(thing), AmpliPiUtils.MIN_VOLUME_DB));
122                         }
123                         update.setVol(zoneState.getVol());
124                     }
125                 }
126                 break;
127             case AmpliPiBindingConstants.CHANNEL_SOURCE:
128                 if (command instanceof DecimalType decimalCommand) {
129                     update.setSourceId(decimalCommand.intValue());
130                 }
131                 break;
132         }
133         if (bridgeHandler != null) {
134             String url = bridgeHandler.getUrl() + "/api/zones/" + getId(thing);
135             StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
136             try {
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());
142                 } else {
143                     updateStatus(ThingStatus.ONLINE);
144                 }
145             } catch (InterruptedException | TimeoutException | ExecutionException e) {
146                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
147                         "AmpliPi request failed: " + e.getMessage());
148             }
149         }
150     }
151
152     @Override
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);
157     }
158
159     private void updateZoneState(Zone state) {
160         this.zoneState = state;
161
162         Boolean mute = zoneState.getMute();
163         Integer vol = zoneState.getVol();
164         Integer sourceId = zoneState.getSourceId();
165
166         updateState(AmpliPiBindingConstants.CHANNEL_MUTE, OnOffType.from(mute));
167         updateState(AmpliPiBindingConstants.CHANNEL_VOLUME, AmpliPiUtils.volumeToPercentType(vol));
168         updateState(AmpliPiBindingConstants.CHANNEL_SOURCE, new DecimalType(sourceId));
169     }
170 }