]> git.basschouten.com Git - openhab-addons.git/blob
252f4c3ebf7474b4ecd130daae2bce8ed20d14f3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.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;
42
43 import com.google.gson.Gson;
44
45 /**
46  * The {@link AmpliPiGroupHandler} is responsible for handling commands, which are
47  * sent to one of the AmpliPi Groups.
48  *
49  * @author Kai Kreuzer - Initial contribution
50  */
51 @NonNullByDefault
52 public class AmpliPiZoneHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
53
54     private final Logger logger = LoggerFactory.getLogger(AmpliPiZoneHandler.class);
55
56     private final HttpClient httpClient;
57     private final Gson gson;
58
59     private @Nullable AmpliPiHandler bridgeHandler;
60
61     public AmpliPiZoneHandler(Thing thing, HttpClient httpClient) {
62         super(thing);
63         this.httpClient = httpClient;
64         this.gson = new Gson();
65     }
66
67     @Override
68     public void initialize() {
69         Bridge bridge = getBridge();
70         if (bridge != null) {
71             bridgeHandler = (AmpliPiHandler) bridge.getHandler();
72             if (bridgeHandler != null) {
73                 bridgeHandler.addStatusChangeListener(this);
74             } else {
75                 throw new IllegalStateException("Bridge handler must not be null here!");
76             }
77             if (bridge.getStatus() == ThingStatus.ONLINE) {
78                 updateStatus(ThingStatus.ONLINE);
79             } else {
80                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
81             }
82         } else {
83             throw new IllegalStateException("Bridge must not be null here!");
84         }
85     }
86
87     private int getId(Thing thing) {
88         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
89     }
90
91     @Override
92     public void handleCommand(ChannelUID channelUID, Command command) {
93         if (command == RefreshType.REFRESH) {
94             // do nothing - we just wait for the next automatic refresh
95             return;
96         }
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);
102                 }
103                 break;
104             case AmpliPiBindingConstants.CHANNEL_VOLUME:
105                 if (command instanceof PercentType) {
106                     update.setVol(AmpliPiUtils.percentTypeToVolume((PercentType) command));
107                 }
108                 break;
109             case AmpliPiBindingConstants.CHANNEL_SOURCE:
110                 if (command instanceof DecimalType) {
111                     update.setSourceId(((DecimalType) command).intValue());
112                 }
113                 break;
114         }
115         if (bridgeHandler != null) {
116             String url = bridgeHandler.getUrl() + "/api/zones/" + getId(thing);
117             StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
118             try {
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());
124                 } else {
125                     updateStatus(ThingStatus.ONLINE);
126                 }
127             } catch (InterruptedException | TimeoutException | ExecutionException e) {
128                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
129                         "AmpliPi request failed: " + e.getMessage());
130             }
131         }
132     }
133
134     @Override
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));
145         }
146     }
147 }