]> git.basschouten.com Git - openhab-addons.git/blob
40e09d372a08d5476ff18101383dd977ca257b78
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.freeboxos.internal.handler;
14
15 import java.math.BigDecimal;
16 import java.time.ZonedDateTime;
17 import java.util.HashMap;
18 import java.util.Hashtable;
19 import java.util.Map;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import javax.measure.Unit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.freeboxos.internal.api.FreeboxException;
28 import org.openhab.binding.freeboxos.internal.api.rest.LanBrowserManager.Source;
29 import org.openhab.binding.freeboxos.internal.api.rest.MediaReceiverManager;
30 import org.openhab.binding.freeboxos.internal.api.rest.MediaReceiverManager.MediaType;
31 import org.openhab.binding.freeboxos.internal.api.rest.MediaReceiverManager.Receiver;
32 import org.openhab.binding.freeboxos.internal.api.rest.RestManager;
33 import org.openhab.binding.freeboxos.internal.config.ApiConsumerConfiguration;
34 import org.openhab.binding.freeboxos.internal.config.ClientConfiguration;
35 import org.openhab.core.audio.AudioSink;
36 import org.openhab.core.config.core.Configuration;
37 import org.openhab.core.library.types.DateTimeType;
38 import org.openhab.core.library.types.DecimalType;
39 import org.openhab.core.library.types.OnOffType;
40 import org.openhab.core.library.types.QuantityType;
41 import org.openhab.core.library.types.StringType;
42 import org.openhab.core.thing.Bridge;
43 import org.openhab.core.thing.ChannelUID;
44 import org.openhab.core.thing.Thing;
45 import org.openhab.core.thing.ThingStatus;
46 import org.openhab.core.thing.ThingStatusDetail;
47 import org.openhab.core.thing.ThingStatusInfo;
48 import org.openhab.core.thing.binding.BaseThingHandler;
49 import org.openhab.core.thing.binding.BridgeHandler;
50 import org.openhab.core.types.Command;
51 import org.openhab.core.types.RefreshType;
52 import org.openhab.core.types.State;
53 import org.openhab.core.types.UnDefType;
54 import org.osgi.framework.ServiceRegistration;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import inet.ipaddr.IPAddress;
59
60 /**
61  * The {@link ServerHandler} is a base abstract class for all devices made available by the FreeboxOs bridge
62  *
63  * @author GaĆ«l L'hopital - Initial contribution
64  */
65 @NonNullByDefault
66 public abstract class ApiConsumerHandler extends BaseThingHandler implements ApiConsumerIntf {
67     private final Logger logger = LoggerFactory.getLogger(ApiConsumerHandler.class);
68     private final Map<String, ScheduledFuture<?>> jobs = new HashMap<>();
69
70     private @Nullable ServiceRegistration<?> reg;
71     protected boolean statusDrivenByBridge = true;
72
73     ApiConsumerHandler(Thing thing) {
74         super(thing);
75     }
76
77     @Override
78     public void initialize() {
79         FreeboxOsHandler bridgeHandler = checkBridgeHandler();
80         if (bridgeHandler == null) {
81             return;
82         }
83
84         Map<String, String> properties = editProperties();
85         if (properties.isEmpty()) {
86             try {
87                 initializeProperties(properties);
88                 checkAirMediaCapabilities(properties);
89                 updateProperties(properties);
90             } catch (FreeboxException e) {
91                 logger.warn("Error getting thing {} properties: {}", thing.getUID(), e.getMessage());
92             }
93         }
94
95         boolean isAudioReceiver = Boolean.parseBoolean(properties.get(MediaType.AUDIO.name()));
96         if (isAudioReceiver) {
97             configureMediaSink(bridgeHandler, properties.getOrDefault(Source.UPNP.name(), ""));
98         }
99
100         startRefreshJob();
101     }
102
103     private void configureMediaSink(FreeboxOsHandler bridgeHandler, String upnpName) {
104         try {
105             Receiver receiver = getManager(MediaReceiverManager.class).getReceiver(upnpName);
106             if (receiver != null && reg == null) {
107                 ApiConsumerConfiguration config = getConfig().as(ApiConsumerConfiguration.class);
108                 String callbackURL = bridgeHandler.getCallbackURL();
109                 if (!config.password.isEmpty() || !receiver.passwordProtected()) {
110                     reg = bridgeHandler.getBundleContext().registerService(
111                             AudioSink.class.getName(), new AirMediaSink(this, bridgeHandler.getAudioHTTPServer(),
112                                     callbackURL, receiver.name(), config.password, config.acceptAllMp3),
113                             new Hashtable<>());
114                 } else {
115                     logger.info("A password needs to be configured to enable Air Media capability.");
116                 }
117             }
118         } catch (FreeboxException e) {
119             logger.warn("Unable to retrieve Media Receivers: {}", e.getMessage());
120         }
121     }
122
123     public <T extends RestManager> T getManager(Class<T> clazz) throws FreeboxException {
124         FreeboxOsHandler handler = checkBridgeHandler();
125         if (handler != null) {
126             return handler.getManager(clazz);
127         }
128         throw new FreeboxException("Bridge handler not yet defined");
129     }
130
131     abstract void initializeProperties(Map<String, String> properties) throws FreeboxException;
132
133     @Override
134     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
135         if (checkBridgeHandler() != null) {
136             startRefreshJob();
137         } else {
138             stopJobs();
139         }
140     }
141
142     @Override
143     public void handleCommand(ChannelUID channelUID, Command command) {
144         if (getThing().getStatus() != ThingStatus.ONLINE) {
145             return;
146         }
147         try {
148             if (checkBridgeHandler() != null) {
149                 if (command instanceof RefreshType) {
150                     internalPoll();
151                 } else if (!internalHandleCommand(channelUID.getIdWithoutGroup(), command)) {
152                     logger.debug("Unexpected command {} on channel {}", command, channelUID.getId());
153                 }
154             }
155         } catch (FreeboxException e) {
156             logger.warn("Error handling command: {}", e.getMessage());
157         }
158     }
159
160     private void checkAirMediaCapabilities(Map<String, String> properties) throws FreeboxException {
161         String upnpName = properties.getOrDefault(Source.UPNP.name(), "");
162         Receiver receiver = getManager(MediaReceiverManager.class).getReceiver(upnpName);
163         if (receiver != null) {
164             receiver.capabilities().entrySet()
165                     .forEach(entry -> properties.put(entry.getKey().name(), entry.getValue().toString()));
166         }
167     }
168
169     private @Nullable FreeboxOsHandler checkBridgeHandler() {
170         Bridge bridge = getBridge();
171         if (bridge != null) {
172             BridgeHandler handler = bridge.getHandler();
173             if (handler instanceof FreeboxOsHandler fbOsHandler) {
174                 if (bridge.getStatus() == ThingStatus.ONLINE) {
175                     if (statusDrivenByBridge) {
176                         updateStatus(ThingStatus.ONLINE);
177                     }
178                     return fbOsHandler;
179                 }
180                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
181             } else {
182                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_MISSING_ERROR);
183             }
184         } else {
185             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
186         }
187         return null;
188     }
189
190     @Override
191     public void dispose() {
192         stopJobs();
193         ServiceRegistration<?> localReg = reg;
194         if (localReg != null) {
195             localReg.unregister();
196         }
197         super.dispose();
198     }
199
200     private void startRefreshJob() {
201         removeJob("GlobalJob");
202
203         int refreshInterval = getConfigAs(ApiConsumerConfiguration.class).refreshInterval;
204         logger.debug("Scheduling state update every {} seconds for thing {}...", refreshInterval, getThing().getUID());
205
206         ThingStatusDetail detail = thing.getStatusInfo().getStatusDetail();
207         if (ThingStatusDetail.DUTY_CYCLE.equals(detail)) {
208             try {
209                 internalPoll();
210             } catch (FreeboxException ignore) {
211                 // An exception is normal if the box is rebooting then let's try again later...
212                 addJob("Initialize", this::initialize, 10, TimeUnit.SECONDS);
213                 return;
214             }
215         }
216
217         addJob("GlobalJob", () -> {
218             try {
219                 internalPoll();
220             } catch (FreeboxException e) {
221                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
222             }
223         }, 0, refreshInterval, TimeUnit.SECONDS);
224     }
225
226     private void removeJob(String name) {
227         ScheduledFuture<?> existing = jobs.get(name);
228         if (existing != null && !existing.isCancelled()) {
229             existing.cancel(true);
230         }
231     }
232
233     @Override
234     public void addJob(String name, Runnable command, long initialDelay, long delay, TimeUnit unit) {
235         removeJob(name);
236         jobs.put(name, scheduler.scheduleWithFixedDelay(command, initialDelay, delay, unit));
237     }
238
239     @Override
240     public void addJob(String name, Runnable command, long delay, TimeUnit unit) {
241         removeJob(name);
242         jobs.put(name, scheduler.schedule(command, delay, unit));
243     }
244
245     @Override
246     public void stopJobs() {
247         jobs.keySet().forEach(name -> removeJob(name));
248         jobs.clear();
249     }
250
251     protected boolean internalHandleCommand(String channelId, Command command) throws FreeboxException {
252         return false;
253     }
254
255     protected abstract void internalPoll() throws FreeboxException;
256
257     private void updateIfActive(String group, String channelId, State state) {
258         ChannelUID id = new ChannelUID(getThing().getUID(), group, channelId);
259         if (isLinked(id)) {
260             updateState(id, state);
261         }
262     }
263
264     protected void updateIfActive(String channelId, State state) {
265         ChannelUID id = new ChannelUID(getThing().getUID(), channelId);
266         if (isLinked(id)) {
267             updateState(id, state);
268         }
269     }
270
271     protected void updateChannelDateTimeState(String channelId, @Nullable ZonedDateTime timestamp) {
272         updateIfActive(channelId, timestamp == null ? UnDefType.NULL : new DateTimeType(timestamp));
273     }
274
275     protected void updateChannelDateTimeState(String group, String channelId, @Nullable ZonedDateTime timestamp) {
276         updateIfActive(group, channelId, timestamp == null ? UnDefType.NULL : new DateTimeType(timestamp));
277     }
278
279     protected void updateChannelOnOff(String group, String channelId, boolean value) {
280         updateIfActive(group, channelId, OnOffType.from(value));
281     }
282
283     protected void updateChannelOnOff(String channelId, boolean value) {
284         updateIfActive(channelId, OnOffType.from(value));
285     }
286
287     protected void updateChannelString(String group, String channelId, @Nullable String value) {
288         updateIfActive(group, channelId, value != null ? new StringType(value) : UnDefType.NULL);
289     }
290
291     protected void updateChannelString(String group, String channelId, @Nullable IPAddress value) {
292         updateIfActive(group, channelId, value != null ? new StringType(value.toCanonicalString()) : UnDefType.NULL);
293     }
294
295     protected void updateChannelString(String channelId, @Nullable String value) {
296         updateIfActive(channelId, value != null ? new StringType(value) : UnDefType.NULL);
297     }
298
299     protected void updateChannelString(String channelId, Enum<?> value) {
300         updateIfActive(channelId, new StringType(value.name()));
301     }
302
303     protected void updateChannelString(String group, String channelId, Enum<?> value) {
304         updateIfActive(group, channelId, new StringType(value.name()));
305     }
306
307     protected void updateChannelQuantity(String group, String channelId, double d, Unit<?> unit) {
308         updateChannelQuantity(group, channelId, new QuantityType<>(d, unit));
309     }
310
311     protected void updateChannelQuantity(String channelId, @Nullable QuantityType<?> quantity) {
312         updateIfActive(channelId, quantity != null ? quantity : UnDefType.NULL);
313     }
314
315     protected void updateChannelQuantity(String group, String channelId, @Nullable QuantityType<?> quantity) {
316         updateIfActive(group, channelId, quantity != null ? quantity : UnDefType.NULL);
317     }
318
319     protected void updateChannelDecimal(String group, String channelId, @Nullable Integer value) {
320         updateIfActive(group, channelId, value != null ? new DecimalType(value) : UnDefType.NULL);
321     }
322
323     protected void updateChannelQuantity(String group, String channelId, QuantityType<?> qtty, Unit<?> unit) {
324         updateChannelQuantity(group, channelId, qtty.toUnit(unit));
325     }
326
327     @Override
328     public void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
329         super.updateStatus(status, statusDetail, description);
330     }
331
332     @Override
333     public Map<String, String> editProperties() {
334         return super.editProperties();
335     }
336
337     @Override
338     public void updateProperties(@Nullable Map<String, String> properties) {
339         super.updateProperties(properties);
340     }
341
342     @Override
343     public Configuration getConfig() {
344         return super.getConfig();
345     }
346
347     @Override
348     public int getClientId() {
349         return ((BigDecimal) getConfig().get(ClientConfiguration.ID)).intValue();
350     }
351 }