]> git.basschouten.com Git - openhab-addons.git/blob
800958e2ba59f684a6a09270fbcb7f8802f51461
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.Group;
27 import org.openhab.binding.amplipi.internal.model.GroupUpdate;
28 import org.openhab.binding.amplipi.internal.model.Status;
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 AmpliPiGroupHandler extends BaseThingHandler implements AmpliPiStatusChangeListener {
53
54     private final Logger logger = LoggerFactory.getLogger(AmpliPiGroupHandler.class);
55
56     private final HttpClient httpClient;
57     private final Gson gson;
58
59     private @Nullable AmpliPiHandler bridgeHandler;
60
61     public AmpliPiGroupHandler(Thing thing, HttpClient httpClient) {
62         super(thing);
63         this.httpClient = httpClient;
64         this.gson = new Gson();
65     }
66
67     private int getId(Thing thing) {
68         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
69     }
70
71     @Override
72     public void initialize() {
73         Bridge bridge = getBridge();
74         if (bridge != null) {
75             bridgeHandler = (AmpliPiHandler) bridge.getHandler();
76             if (bridgeHandler != null) {
77                 bridgeHandler.addStatusChangeListener(this);
78             } else {
79                 throw new IllegalStateException("Bridge handler must not be null here!");
80             }
81             if (bridge.getStatus() == ThingStatus.ONLINE) {
82                 updateStatus(ThingStatus.ONLINE);
83             } else {
84                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
85             }
86         } else {
87             throw new IllegalStateException("Bridge must not be null here!");
88         }
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         GroupUpdate update = new GroupUpdate();
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.setVolDelta(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/groups/" + getId(thing);
117             ;
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(Status status) {
137         int id = getId(thing);
138         Optional<Group> group = status.getGroups().stream().filter(z -> z.getId().equals(id)).findFirst();
139         if (group.isPresent()) {
140             Boolean mute = group.get().getMute();
141             Integer volume = group.get().getVolDelta();
142             Integer source = group.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 }