]> git.basschouten.com Git - openhab-addons.git/blob
8e8581c8daf2776c164059110e5d44fdda9d43a0
[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.chromecast.internal;
14
15 import static org.openhab.binding.chromecast.internal.ChromecastBindingConstants.*;
16 import static su.litvak.chromecast.api.v2.MediaStatus.PlayerState.*;
17
18 import java.io.IOException;
19 import java.time.Instant;
20 import java.time.ZoneId;
21 import java.time.ZonedDateTime;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.chromecast.internal.handler.ChromecastHandler;
29 import org.openhab.core.cache.ByteArrayFileCache;
30 import org.openhab.core.io.net.http.HttpUtil;
31 import org.openhab.core.library.types.DateTimeType;
32 import org.openhab.core.library.types.DecimalType;
33 import org.openhab.core.library.types.OnOffType;
34 import org.openhab.core.library.types.PercentType;
35 import org.openhab.core.library.types.PlayPauseType;
36 import org.openhab.core.library.types.PointType;
37 import org.openhab.core.library.types.QuantityType;
38 import org.openhab.core.library.types.RawType;
39 import org.openhab.core.library.types.StringType;
40 import org.openhab.core.library.unit.Units;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.thing.Thing;
43 import org.openhab.core.thing.ThingStatus;
44 import org.openhab.core.thing.ThingStatusDetail;
45 import org.openhab.core.types.State;
46 import org.openhab.core.types.UnDefType;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import su.litvak.chromecast.api.v2.Application;
51 import su.litvak.chromecast.api.v2.Media;
52 import su.litvak.chromecast.api.v2.MediaStatus;
53 import su.litvak.chromecast.api.v2.Status;
54 import su.litvak.chromecast.api.v2.Volume;
55
56 /**
57  * Responsible for updating the Thing status based on messages received from a ChromeCast. This doesn't query anything -
58  * it just parses the messages and updates the Thing. Message handling/scheduling/receiving is done elsewhere.
59  * <p>
60  * This also maintains state of both volume and the appSessionId (only if we started playing media).
61  *
62  * @author Jason Holmes - Initial contribution
63  */
64 @NonNullByDefault
65 public class ChromecastStatusUpdater {
66
67     private final Logger logger = LoggerFactory.getLogger(ChromecastStatusUpdater.class);
68
69     private final Thing thing;
70     private final ChromecastHandler callback;
71     private static final ByteArrayFileCache IMAGE_CACHE = new ByteArrayFileCache("org.openhab.binding.chromecast");
72
73     private @Nullable String appSessionId;
74     private PercentType volume = PercentType.ZERO;
75
76     public ChromecastStatusUpdater(Thing thing, ChromecastHandler callback) {
77         this.thing = thing;
78         this.callback = callback;
79     }
80
81     public PercentType getVolume() {
82         return volume;
83     }
84
85     public @Nullable String getAppSessionId() {
86         return appSessionId;
87     }
88
89     public void setAppSessionId(String appSessionId) {
90         this.appSessionId = appSessionId;
91     }
92
93     public void processStatusUpdate(final @Nullable Status status) {
94         if (status == null) {
95             updateStatus(ThingStatus.OFFLINE);
96             updateAppStatus(null);
97             updateVolumeStatus(null);
98             return;
99         }
100
101         if (status.applications == null) {
102             this.appSessionId = null;
103         }
104
105         updateStatus(ThingStatus.ONLINE);
106         updateAppStatus(status.getRunningApp());
107         updateVolumeStatus(status.volume);
108     }
109
110     public void updateAppStatus(final @Nullable Application application) {
111         State name = UnDefType.UNDEF;
112         State id = UnDefType.UNDEF;
113         State statusText = UnDefType.UNDEF;
114         OnOffType idling = OnOffType.ON;
115
116         if (application != null) {
117             name = new StringType(application.name);
118             id = new StringType(application.id);
119             statusText = new StringType(application.statusText);
120             idling = application.isIdleScreen ? OnOffType.ON : OnOffType.OFF;
121         }
122
123         callback.updateState(CHANNEL_APP_NAME, name);
124         callback.updateState(CHANNEL_APP_ID, id);
125         callback.updateState(CHANNEL_STATUS_TEXT, statusText);
126         callback.updateState(CHANNEL_IDLING, idling);
127     }
128
129     public void updateVolumeStatus(final @Nullable Volume volume) {
130         if (volume == null) {
131             return;
132         }
133
134         PercentType value = new PercentType((int) (volume.level * 100));
135         this.volume = value;
136
137         callback.updateState(CHANNEL_VOLUME, value);
138         callback.updateState(CHANNEL_MUTE, volume.muted ? OnOffType.ON : OnOffType.OFF);
139     }
140
141     public void updateMediaStatus(final @Nullable MediaStatus mediaStatus) {
142         logger.debug("MEDIA_STATUS {}", mediaStatus);
143
144         // In-between songs? It's thinking? It's not doing anything
145         if (mediaStatus == null) {
146             callback.updateState(CHANNEL_CONTROL, PlayPauseType.PAUSE);
147             callback.updateState(CHANNEL_STOP, OnOffType.ON);
148             callback.updateState(CHANNEL_CURRENT_TIME, UnDefType.UNDEF);
149             updateMediaInfoStatus(null);
150             return;
151         }
152
153         switch (mediaStatus.playerState) {
154             case IDLE:
155                 break;
156             case PAUSED:
157                 callback.updateState(CHANNEL_CONTROL, PlayPauseType.PAUSE);
158                 callback.updateState(CHANNEL_STOP, OnOffType.OFF);
159                 break;
160             case BUFFERING:
161             case LOADING:
162             case PLAYING:
163                 callback.updateState(CHANNEL_CONTROL, PlayPauseType.PLAY);
164                 callback.updateState(CHANNEL_STOP, OnOffType.OFF);
165                 break;
166             default:
167                 logger.debug("Unknown media status: {}", mediaStatus.playerState);
168                 break;
169         }
170
171         callback.updateState(CHANNEL_CURRENT_TIME, new QuantityType<>(mediaStatus.currentTime, Units.SECOND));
172
173         // If we're playing, paused or buffering but don't have any MEDIA information don't null everything out.
174         Media media = mediaStatus.media;
175         if (media == null && (mediaStatus.playerState == PLAYING || mediaStatus.playerState == PAUSED
176                 || mediaStatus.playerState == BUFFERING)) {
177             return;
178         }
179
180         updateMediaInfoStatus(media);
181     }
182
183     private void updateMediaInfoStatus(final @Nullable Media media) {
184         State duration = UnDefType.UNDEF;
185         String metadataType = Media.MetadataType.GENERIC.name();
186         if (media != null) {
187             metadataType = media.getMetadataType().name();
188
189             // duration can be null when a new song is about to play.
190             if (media.duration != null) {
191                 duration = new QuantityType<>(media.duration, Units.SECOND);
192             }
193         }
194
195         callback.updateState(CHANNEL_DURATION, duration);
196         callback.updateState(CHANNEL_METADATA_TYPE, new StringType(metadataType));
197
198         updateMetadataStatus(media == null || media.metadata == null ? Collections.emptyMap() : media.metadata);
199     }
200
201     private void updateMetadataStatus(Map<String, Object> metadata) {
202         updateLocation(metadata);
203         updateImage(metadata);
204
205         thing.getChannels().stream() //
206                 .map(channel -> channel.getUID())
207                 .filter(channelUID -> METADATA_SIMPLE_CHANNELS.contains(channelUID.getId()))
208                 .forEach(channelUID -> updateChannel(channelUID, metadata));
209     }
210
211     /** Lat/lon are combined into 1 channel so we have to handle them as a special case. */
212     private void updateLocation(Map<String, Object> metadata) {
213         if (!callback.isLinked(CHANNEL_LOCATION)) {
214             return;
215         }
216
217         Double lat = (Double) metadata.get(LOCATION_METADATA_LATITUDE);
218         Double lon = (Double) metadata.get(LOCATION_METADATA_LONGITUDE);
219         if (lat == null || lon == null) {
220             callback.updateState(CHANNEL_LOCATION, UnDefType.UNDEF);
221         } else {
222             PointType pointType = new PointType(new DecimalType(lat), new DecimalType(lon));
223             callback.updateState(CHANNEL_LOCATION, pointType);
224         }
225     }
226
227     private void updateImage(Map<String, Object> metadata) {
228         if (!(callback.isLinked(CHANNEL_IMAGE) || (callback.isLinked(CHANNEL_IMAGE_SRC)))) {
229             return;
230         }
231
232         // Channel name and metadata key don't match.
233         Object imagesValue = metadata.get("images");
234         if (imagesValue == null) {
235             callback.updateState(CHANNEL_IMAGE_SRC, UnDefType.UNDEF);
236             return;
237         }
238
239         String imageSrc = null;
240         @SuppressWarnings("unchecked")
241         List<Map<String, String>> strings = (List<Map<String, String>>) imagesValue;
242         for (Map<String, String> stringMap : strings) {
243             String url = stringMap.get("url");
244             if (url != null) {
245                 imageSrc = url;
246                 break;
247             }
248         }
249
250         if (callback.isLinked(CHANNEL_IMAGE_SRC)) {
251             callback.updateState(CHANNEL_IMAGE_SRC, imageSrc == null ? UnDefType.UNDEF : new StringType(imageSrc));
252         }
253
254         if (callback.isLinked(CHANNEL_IMAGE)) {
255             State image = imageSrc == null ? UnDefType.UNDEF : downloadImageFromCache(imageSrc);
256             callback.updateState(CHANNEL_IMAGE, image == null ? UnDefType.UNDEF : image);
257         }
258     }
259
260     private @Nullable RawType downloadImage(String url) {
261         logger.debug("Trying to download the content of URL '{}'", url);
262         RawType downloadedImage = HttpUtil.downloadImage(url);
263         if (downloadedImage == null) {
264             logger.debug("Failed to download the content of URL '{}'", url);
265         }
266         return downloadedImage;
267     }
268
269     private @Nullable RawType downloadImageFromCache(String url) {
270         if (IMAGE_CACHE.containsKey(url)) {
271             try {
272                 byte[] bytes = IMAGE_CACHE.get(url);
273                 String contentType = HttpUtil.guessContentTypeFromData(bytes);
274                 return new RawType(bytes,
275                         contentType == null || contentType.isEmpty() ? RawType.DEFAULT_MIME_TYPE : contentType);
276             } catch (IOException e) {
277                 logger.trace("Failed to download the content of URL '{}'", url, e);
278             }
279         } else {
280             RawType image = downloadImage(url);
281             if (image != null) {
282                 IMAGE_CACHE.put(url, image.getBytes());
283                 return image;
284             }
285         }
286         return null;
287     }
288
289     private void updateChannel(ChannelUID channelUID, Map<String, Object> metadata) {
290         if (!callback.isLinked(channelUID)) {
291             return;
292         }
293
294         Object value = getValue(channelUID.getId(), metadata);
295         State state;
296
297         if (value == null) {
298             state = UnDefType.UNDEF;
299         } else if (value instanceof Double) {
300             state = new DecimalType((Double) value);
301         } else if (value instanceof Integer) {
302             state = new DecimalType(((Integer) value).longValue());
303         } else if (value instanceof String) {
304             state = new StringType(value.toString());
305         } else if (value instanceof ZonedDateTime) {
306             state = new DateTimeType((ZonedDateTime) value);
307         } else {
308             state = UnDefType.UNDEF;
309             logger.warn("Update channel {}: Unsupported value type {}", channelUID, value.getClass().getSimpleName());
310         }
311
312         callback.updateState(channelUID, state);
313     }
314
315     private @Nullable Object getValue(String channelId, @Nullable Map<String, Object> metadata) {
316         if (metadata == null) {
317             return null;
318         }
319
320         if (CHANNEL_BROADCAST_DATE.equals(channelId) || CHANNEL_RELEASE_DATE.equals(channelId)
321                 || CHANNEL_CREATION_DATE.equals(channelId)) {
322             String dateString = (String) metadata.get(channelId);
323             return (dateString == null) ? null
324                     : ZonedDateTime.ofInstant(Instant.parse(dateString), ZoneId.systemDefault());
325         }
326
327         return metadata.get(channelId);
328     }
329
330     public void updateStatus(ThingStatus status) {
331         updateStatus(status, ThingStatusDetail.NONE, null);
332     }
333
334     public void updateStatus(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) {
335         callback.updateStatus(status, statusDetail, description);
336     }
337 }