]> git.basschouten.com Git - openhab-addons.git/blob
9962b484f88fbce63705d598ad93252d75a15796
[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.Group;
28 import org.openhab.binding.amplipi.internal.model.GroupUpdate;
29 import org.openhab.binding.amplipi.internal.model.Status;
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 AmpliPiGroupHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
54
55     private final Logger logger = LoggerFactory.getLogger(AmpliPiGroupHandler.class);
56
57     private final HttpClient httpClient;
58     private final Gson gson;
59
60     private @Nullable AmpliPiHandler bridgeHandler;
61
62     public AmpliPiGroupHandler(Thing thing, HttpClient httpClient) {
63         super(thing);
64         this.httpClient = httpClient;
65         this.gson = new Gson();
66     }
67
68     private int getId(Thing thing) {
69         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
70     }
71
72     @Override
73     public void initialize() {
74         Bridge bridge = getBridge();
75         if (bridge != null) {
76             bridgeHandler = (AmpliPiHandler) bridge.getHandler();
77             if (bridgeHandler != null) {
78                 bridgeHandler.addStatusChangeListener(this);
79             } else {
80                 throw new IllegalStateException("Bridge handler must not be null here!");
81             }
82             if (bridge.getStatus() == ThingStatus.ONLINE) {
83                 updateStatus(ThingStatus.ONLINE);
84             } else {
85                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
86             }
87         } else {
88             throw new IllegalStateException("Bridge must not be null here!");
89         }
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         GroupUpdate update = new GroupUpdate();
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.setVolDelta(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/groups/" + getId(thing);
118             ;
119             StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
120             try {
121                 ContentResponse response = httpClient.newRequest(url).method(HttpMethod.PATCH)
122                         .content(contentProvider, "application/json").send();
123                 if (response.getStatus() != HttpStatus.OK_200) {
124                     logger.error("AmpliPi API returned HTTP status {}.", response.getStatus());
125                     logger.debug("Content: {}", response.getContentAsString());
126                 } else {
127                     updateStatus(ThingStatus.ONLINE);
128                 }
129             } catch (InterruptedException | TimeoutException | ExecutionException e) {
130                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
131                         "AmpliPi request failed: " + e.getMessage());
132             }
133         }
134     }
135
136     @Override
137     public void receive(@NonNull Status status) {
138         int id = getId(thing);
139         Optional<Group> group = status.getGroups().stream().filter(z -> z.getId().equals(id)).findFirst();
140         if (group.isPresent()) {
141             Boolean mute = group.get().getMute();
142             Integer volume = group.get().getVolDelta();
143             Integer source = group.get().getSourceId();
144             updateState(AmpliPiBindingConstants.CHANNEL_MUTE, mute ? OnOffType.ON : OnOffType.OFF);
145             updateState(AmpliPiBindingConstants.CHANNEL_VOLUME, AmpliPiUtils.volumeToPercentType(volume));
146             updateState(AmpliPiBindingConstants.CHANNEL_SOURCE, new DecimalType(source));
147         }
148     }
149 }