]> git.basschouten.com Git - openhab-addons.git/blob
ff3ad20e3377efd53eb03fb0e3959e8584c55c56
[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.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;
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     public AmpliPiZoneHandler(Thing thing, HttpClient httpClient) {
63         super(thing);
64         this.httpClient = httpClient;
65         this.gson = new Gson();
66     }
67
68     @Override
69     public void initialize() {
70         Bridge bridge = getBridge();
71         if (bridge != null) {
72             bridgeHandler = (AmpliPiHandler) bridge.getHandler();
73             if (bridgeHandler != null) {
74                 bridgeHandler.addStatusChangeListener(this);
75             } else {
76                 throw new IllegalStateException("Bridge handler must not be null here!");
77             }
78             if (bridge.getStatus() == ThingStatus.ONLINE) {
79                 updateStatus(ThingStatus.ONLINE);
80             } else {
81                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
82             }
83         } else {
84             throw new IllegalStateException("Bridge must not be null here!");
85         }
86     }
87
88     private int getId(Thing thing) {
89         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
90     }
91
92     @Override
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
96             return;
97         }
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);
103                 }
104                 break;
105             case AmpliPiBindingConstants.CHANNEL_VOLUME:
106                 if (command instanceof PercentType) {
107                     update.setVol(AmpliPiUtils.percentTypeToVolume((PercentType) command));
108                 }
109                 break;
110             case AmpliPiBindingConstants.CHANNEL_SOURCE:
111                 if (command instanceof DecimalType) {
112                     update.setSourceId(((DecimalType) command).intValue());
113                 }
114                 break;
115         }
116         if (bridgeHandler != null) {
117             String url = bridgeHandler.getUrl() + "/api/zones/" + getId(thing);
118             StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
119             try {
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());
125                 } else {
126                     updateStatus(ThingStatus.ONLINE);
127                 }
128             } catch (InterruptedException | TimeoutException | ExecutionException e) {
129                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
130                         "AmpliPi request failed: " + e.getMessage());
131             }
132         }
133     }
134
135     @Override
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));
146         }
147     }
148 }