]> git.basschouten.com Git - openhab-addons.git/blob
0f32129d8d420811afbbbb7cf28a4ac026183f75
[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.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.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 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     private @Nullable Group groupState;
63
64     public AmpliPiGroupHandler(Thing thing, HttpClient httpClient) {
65         super(thing);
66         this.httpClient = httpClient;
67         this.gson = new Gson();
68     }
69
70     private int getId(Thing thing) {
71         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_ID).toString());
72     }
73
74     private int getVolumeDelta(Thing thing) {
75         return Integer.valueOf(thing.getConfiguration().get(AmpliPiBindingConstants.CFG_PARAM_VOLUME_DELTA).toString());
76     }
77
78     @Override
79     public void initialize() {
80         Bridge bridge = getBridge();
81         if (bridge != null) {
82             bridgeHandler = (AmpliPiHandler) bridge.getHandler();
83             if (bridgeHandler != null) {
84                 bridgeHandler.addStatusChangeListener(this);
85             } else {
86                 throw new IllegalStateException("Bridge handler must not be null here!");
87             }
88             if (bridge.getStatus() == ThingStatus.ONLINE) {
89                 updateStatus(ThingStatus.ONLINE);
90             } else {
91                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
92             }
93         } else {
94             throw new IllegalStateException("Bridge must not be null here!");
95         }
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         GroupUpdate update = new GroupUpdate();
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.setVolDelta(AmpliPiUtils.percentTypeToVolume(percentCommand));
114                 } else if (command instanceof IncreaseDecreaseType) {
115                     if (groupState != null) {
116                         if (IncreaseDecreaseType.INCREASE.equals(command)) {
117                             groupState.setVolDelta(Math.min(groupState.getVolDelta() + getVolumeDelta(thing),
118                                     AmpliPiUtils.MAX_VOLUME_DB));
119                         } else {
120                             groupState.setVolDelta(Math.max(groupState.getVolDelta() - getVolumeDelta(thing),
121                                     AmpliPiUtils.MIN_VOLUME_DB));
122                         }
123                         update.setVolDelta(groupState.getVolDelta());
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/groups/" + 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<Group> group = status.getGroups().stream().filter(z -> z.getId().equals(id)).findFirst();
156         group.ifPresent(this::updateGroupState);
157     }
158
159     private void updateGroupState(Group state) {
160         this.groupState = state;
161
162         Boolean mute = groupState.getMute();
163         Integer volDelta = groupState.getVolDelta();
164         Integer sourceId = groupState.getSourceId();
165
166         updateState(AmpliPiBindingConstants.CHANNEL_MUTE, OnOffType.from(mute));
167         updateState(AmpliPiBindingConstants.CHANNEL_VOLUME, AmpliPiUtils.volumeToPercentType(volDelta));
168         updateState(AmpliPiBindingConstants.CHANNEL_SOURCE, new DecimalType(sourceId));
169     }
170 }