]> git.basschouten.com Git - openhab-addons.git/blob
7e85dec9b8729045f48c08ab3acb0d44686423dd
[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.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 ApiConsumerHandler} 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         initializeOnceBridgeOnline(bridgeHandler);
84     }
85
86     private void initializeOnceBridgeOnline(FreeboxOsHandler bridgeHandler) {
87         Map<String, String> properties = editProperties();
88         try {
89             initializeProperties(properties);
90             checkAirMediaCapabilities(properties);
91             updateProperties(properties);
92         } catch (FreeboxException e) {
93             logger.warn("Error getting thing {} properties: {}", thing.getUID(), e.getMessage());
94         }
95
96         boolean isAudioReceiver = Boolean.parseBoolean(properties.get(MediaType.AUDIO.name()));
97         if (isAudioReceiver) {
98             configureMediaSink(bridgeHandler, properties.getOrDefault(Source.UPNP.name(), ""));
99         }
100
101         startRefreshJob();
102     }
103
104     private void configureMediaSink(FreeboxOsHandler bridgeHandler, String upnpName) {
105         try {
106             Receiver receiver = getManager(MediaReceiverManager.class).getReceiver(upnpName);
107             if (receiver != null && reg == null) {
108                 ApiConsumerConfiguration config = getConfig().as(ApiConsumerConfiguration.class);
109                 String callbackURL = bridgeHandler.getCallbackURL();
110                 if (!config.password.isEmpty() || !receiver.passwordProtected()) {
111                     reg = bridgeHandler.getBundleContext().registerService(
112                             AudioSink.class.getName(), new AirMediaSink(this, bridgeHandler.getAudioHTTPServer(),
113                                     callbackURL, receiver.name(), config.password, config.acceptAllMp3),
114                             new Hashtable<>());
115                 } else {
116                     logger.info("A password needs to be configured to enable Air Media capability.");
117                 }
118             }
119         } catch (FreeboxException e) {
120             logger.warn("Unable to retrieve Media Receivers: {}", e.getMessage());
121         }
122     }
123
124     public <T extends RestManager> T getManager(Class<T> clazz) throws FreeboxException {
125         FreeboxOsHandler handler = checkBridgeHandler();
126         if (handler != null) {
127             return handler.getManager(clazz);
128         }
129         throw new FreeboxException("Bridge handler not yet defined");
130     }
131
132     abstract void initializeProperties(Map<String, String> properties) throws FreeboxException;
133
134     @Override
135     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
136         FreeboxOsHandler bridgeHandler = checkBridgeHandler();
137         if (bridgeHandler != null) {
138             initializeOnceBridgeOnline(bridgeHandler);
139         } else {
140             stopJobs();
141         }
142     }
143
144     @Override
145     public void handleCommand(ChannelUID channelUID, Command command) {
146         if (getThing().getStatus() != ThingStatus.ONLINE) {
147             return;
148         }
149         try {
150             if (checkBridgeHandler() != null) {
151                 if (command instanceof RefreshType) {
152                     internalForcePoll();
153                 } else if (!internalHandleCommand(channelUID.getIdWithoutGroup(), command)) {
154                     logger.debug("Unexpected command {} on channel {}", command, channelUID.getId());
155                 }
156             }
157         } catch (FreeboxException e) {
158             logger.warn("Error handling command: {}", e.getMessage());
159         }
160     }
161
162     private void checkAirMediaCapabilities(Map<String, String> properties) throws FreeboxException {
163         String upnpName = properties.getOrDefault(Source.UPNP.name(), "");
164         Receiver receiver = getManager(MediaReceiverManager.class).getReceiver(upnpName);
165         if (receiver != null) {
166             receiver.capabilities().entrySet()
167                     .forEach(entry -> properties.put(entry.getKey().name(), entry.getValue().toString()));
168         }
169     }
170
171     private @Nullable FreeboxOsHandler checkBridgeHandler() {
172         Bridge bridge = getBridge();
173         if (bridge != null) {
174             BridgeHandler handler = bridge.getHandler();
175             if (handler instanceof FreeboxOsHandler fbOsHandler) {
176                 if (bridge.getStatus() == ThingStatus.ONLINE) {
177                     if (statusDrivenByBridge) {
178                         updateStatus(ThingStatus.ONLINE);
179                     }
180                     return fbOsHandler;
181                 }
182                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
183             } else {
184                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_MISSING_ERROR);
185             }
186         } else {
187             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
188         }
189         return null;
190     }
191
192     @Override
193     public void dispose() {
194         stopJobs();
195         ServiceRegistration<?> localReg = reg;
196         if (localReg != null) {
197             localReg.unregister();
198         }
199         super.dispose();
200     }
201
202     private void startRefreshJob() {
203         removeJob("GlobalJob");
204
205         int refreshInterval = getConfigAs(ApiConsumerConfiguration.class).refreshInterval;
206         logger.debug("Scheduling state update every {} seconds for thing {}...", refreshInterval, getThing().getUID());
207
208         ThingStatusDetail detail = thing.getStatusInfo().getStatusDetail();
209         if (ThingStatusDetail.DUTY_CYCLE.equals(detail)) {
210             try {
211                 internalPoll();
212             } catch (FreeboxException ignore) {
213                 // An exception is normal if the box is rebooting then let's try again later...
214                 addJob("Initialize", this::initialize, 10, TimeUnit.SECONDS);
215                 return;
216             }
217         }
218
219         addJob("GlobalJob", () -> {
220             try {
221                 internalPoll();
222             } catch (FreeboxException e) {
223                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
224             }
225         }, 0, refreshInterval, TimeUnit.SECONDS);
226     }
227
228     private void removeJob(String name) {
229         ScheduledFuture<?> existing = jobs.get(name);
230         if (existing != null && !existing.isCancelled()) {
231             existing.cancel(true);
232         }
233     }
234
235     @Override
236     public void addJob(String name, Runnable command, long initialDelay, long delay, TimeUnit unit) {
237         removeJob(name);
238         jobs.put(name, scheduler.scheduleWithFixedDelay(command, initialDelay, delay, unit));
239     }
240
241     @Override
242     public void addJob(String name, Runnable command, long delay, TimeUnit unit) {
243         removeJob(name);
244         jobs.put(name, scheduler.schedule(command, delay, unit));
245     }
246
247     @Override
248     public void stopJobs() {
249         jobs.keySet().forEach(name -> removeJob(name));
250         jobs.clear();
251     }
252
253     protected boolean internalHandleCommand(String channelId, Command command) throws FreeboxException {
254         return false;
255     }
256
257     protected abstract void internalPoll() throws FreeboxException;
258
259     protected void internalForcePoll() throws FreeboxException {
260         internalPoll();
261     }
262
263     private void updateIfActive(String group, String channelId, State state) {
264         ChannelUID id = new ChannelUID(getThing().getUID(), group, channelId);
265         if (isLinked(id)) {
266             updateState(id, state);
267         }
268     }
269
270     protected void updateIfActive(String channelId, State state) {
271         ChannelUID id = new ChannelUID(getThing().getUID(), channelId);
272         if (isLinked(id)) {
273             updateState(id, state);
274         }
275     }
276
277     protected void updateChannelDateTimeState(String channelId, @Nullable ZonedDateTime timestamp) {
278         updateIfActive(channelId, timestamp == null ? UnDefType.NULL : new DateTimeType(timestamp));
279     }
280
281     protected void updateChannelDateTimeState(String group, String channelId, @Nullable ZonedDateTime timestamp) {
282         updateIfActive(group, channelId, timestamp == null ? UnDefType.NULL : new DateTimeType(timestamp));
283     }
284
285     protected void updateChannelOnOff(String group, String channelId, boolean value) {
286         updateIfActive(group, channelId, OnOffType.from(value));
287     }
288
289     protected void updateChannelOnOff(String channelId, boolean value) {
290         updateIfActive(channelId, OnOffType.from(value));
291     }
292
293     protected void updateChannelString(String group, String channelId, @Nullable String value) {
294         updateIfActive(group, channelId, value != null ? new StringType(value) : UnDefType.NULL);
295     }
296
297     protected void updateChannelString(String group, String channelId, @Nullable IPAddress value) {
298         updateIfActive(group, channelId, value != null ? new StringType(value.toCanonicalString()) : UnDefType.NULL);
299     }
300
301     protected void updateChannelString(String channelId, @Nullable String value) {
302         updateIfActive(channelId, value != null ? new StringType(value) : UnDefType.NULL);
303     }
304
305     protected void updateChannelString(String channelId, Enum<?> value) {
306         updateIfActive(channelId, new StringType(value.name()));
307     }
308
309     protected void updateChannelString(String group, String channelId, Enum<?> value) {
310         updateIfActive(group, channelId, new StringType(value.name()));
311     }
312
313     protected void updateChannelQuantity(String group, String channelId, double d, Unit<?> unit) {
314         updateChannelQuantity(group, channelId, new QuantityType<>(d, unit));
315     }
316
317     protected void updateChannelQuantity(String channelId, @Nullable QuantityType<?> quantity) {
318         updateIfActive(channelId, quantity != null ? quantity : UnDefType.NULL);
319     }
320
321     protected void updateChannelQuantity(String group, String channelId, @Nullable QuantityType<?> quantity) {
322         updateIfActive(group, channelId, quantity != null ? quantity : UnDefType.NULL);
323     }
324
325     protected void updateChannelDecimal(String group, String channelId, @Nullable Integer value) {
326         updateIfActive(group, channelId, value != null ? new DecimalType(value) : UnDefType.NULL);
327     }
328
329     protected void updateChannelQuantity(String group, String channelId, QuantityType<?> qtty, Unit<?> unit) {
330         updateChannelQuantity(group, channelId, qtty.toUnit(unit));
331     }
332
333     @Override
334     public void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
335         super.updateStatus(status, statusDetail, description);
336     }
337
338     @Override
339     public Map<String, String> editProperties() {
340         return super.editProperties();
341     }
342
343     @Override
344     public void updateProperties(@Nullable Map<String, String> properties) {
345         super.updateProperties(properties);
346     }
347
348     @Override
349     public Configuration getConfig() {
350         return super.getConfig();
351     }
352
353     @Override
354     public int getClientId() {
355         return ((BigDecimal) getConfig().get(ClientConfiguration.ID)).intValue();
356     }
357 }