]> git.basschouten.com Git - openhab-addons.git/blob
d110659c868231ae91d1055c7f9f0cebe373923c
[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.netatmo.internal.handler.capability;
14
15 import static org.openhab.binding.netatmo.internal.NetatmoBindingConstants.*;
16 import static org.openhab.binding.netatmo.internal.utils.ChannelTypeUtils.*;
17
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import javax.ws.rs.core.UriBuilder;
23 import javax.ws.rs.core.UriBuilderException;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.AlimentationStatus;
28 import org.openhab.binding.netatmo.internal.api.data.NetatmoConstants.SdCardStatus;
29 import org.openhab.binding.netatmo.internal.api.dto.HomeDataPerson;
30 import org.openhab.binding.netatmo.internal.api.dto.HomeEvent;
31 import org.openhab.binding.netatmo.internal.api.dto.HomeStatusModule;
32 import org.openhab.binding.netatmo.internal.api.dto.NAObject;
33 import org.openhab.binding.netatmo.internal.api.dto.WebhookEvent;
34 import org.openhab.binding.netatmo.internal.deserialization.NAObjectMap;
35 import org.openhab.binding.netatmo.internal.handler.CommonInterface;
36 import org.openhab.binding.netatmo.internal.handler.channelhelper.CameraChannelHelper;
37 import org.openhab.binding.netatmo.internal.handler.channelhelper.ChannelHelper;
38 import org.openhab.binding.netatmo.internal.providers.NetatmoDescriptionProvider;
39 import org.openhab.core.config.core.Configuration;
40 import org.openhab.core.library.types.OnOffType;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.openhab.core.types.State;
45 import org.openhab.core.types.StateOption;
46 import org.openhab.core.types.UnDefType;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * {@link CameraCapability} give to handle Welcome Camera specifics
52  *
53  * @author GaĆ«l L'hopital - Initial contribution
54  *
55  */
56 @NonNullByDefault
57 public class CameraCapability extends HomeSecurityThingCapability {
58     private static final String IP_ADDRESS = "ipAddress";
59
60     private final Logger logger = LoggerFactory.getLogger(CameraCapability.class);
61
62     private final CameraChannelHelper cameraHelper;
63     private final ChannelUID personChannelUID;
64
65     protected @Nullable String localUrl;
66     protected @Nullable String vpnUrl;
67     private boolean hasSubEventGroup;
68     private boolean hasLastEventGroup;
69
70     public CameraCapability(CommonInterface handler, NetatmoDescriptionProvider descriptionProvider,
71             List<ChannelHelper> channelHelpers) {
72         super(handler, descriptionProvider, channelHelpers);
73         this.personChannelUID = new ChannelUID(thingUID, GROUP_LAST_EVENT, CHANNEL_EVENT_PERSON_ID);
74         this.cameraHelper = (CameraChannelHelper) channelHelpers.stream().filter(c -> c instanceof CameraChannelHelper)
75                 .findFirst().orElseThrow(() -> new IllegalArgumentException(
76                         "CameraCapability must find a CameraChannelHelper, please file a bug report."));
77     }
78
79     @Override
80     public void initialize() {
81         hasSubEventGroup = !thing.getChannelsOfGroup(GROUP_SUB_EVENT).isEmpty();
82         hasLastEventGroup = !thing.getChannelsOfGroup(GROUP_LAST_EVENT).isEmpty();
83     }
84
85     @Override
86     public void updateHomeStatusModule(HomeStatusModule newData) {
87         super.updateHomeStatusModule(newData);
88         // Per documentation vpn_url expires every 3 hours and on camera reboot. So useless to reping it if not changed
89         String newVpnUrl = newData.getVpnUrl();
90         if (newVpnUrl != null && !newVpnUrl.equals(vpnUrl)) {
91             // This will also decrease the number of requests emitted toward Netatmo API.
92             localUrl = newData.isLocal() ? ping(newVpnUrl) : null;
93             logger.debug("localUrl set to {} for camera {}", localUrl, thingUID);
94             cameraHelper.setUrls(newVpnUrl, localUrl);
95             eventHelper.setUrls(newVpnUrl, localUrl);
96         }
97         vpnUrl = newVpnUrl;
98         if (!SdCardStatus.SD_CARD_WORKING.equals(newData.getSdStatus())
99                 || !AlimentationStatus.ALIM_CORRECT_POWER.equals(newData.getAlimStatus())) {
100             statusReason = "%s, %s".formatted(newData.getSdStatus(), newData.getAlimStatus());
101         }
102     }
103
104     @Override
105     protected void updateWebhookEvent(WebhookEvent event) {
106         super.updateWebhookEvent(event);
107
108         if (hasSubEventGroup) {
109             updateSubGroup(event, GROUP_SUB_EVENT);
110         }
111
112         if (hasLastEventGroup) {
113             updateSubGroup(event, GROUP_LAST_EVENT);
114         }
115
116         // The channel should get triggered at last (after super and sub methods), because this allows rules to access
117         // the new updated data from the other channels.
118         final String eventType = event.getEventType().name();
119         handler.recurseUpToHomeHandler(handler)
120                 .ifPresent(homeHandler -> homeHandler.triggerChannel(CHANNEL_HOME_EVENT, eventType));
121         handler.triggerChannel(CHANNEL_HOME_EVENT, eventType);
122     }
123
124     private void updateSubGroup(WebhookEvent event, String group) {
125         handler.updateState(group, CHANNEL_EVENT_TYPE, toStringType(event.getEventType()));
126         handler.updateState(group, CHANNEL_EVENT_TIME, toDateTimeType(event.getTime()));
127         handler.updateState(group, CHANNEL_EVENT_SNAPSHOT, toRawType(event.getSnapshotUrl()));
128         handler.updateState(group, CHANNEL_EVENT_SNAPSHOT_URL, toStringType(event.getSnapshotUrl()));
129         handler.updateState(group, CHANNEL_EVENT_VIGNETTE, toRawType(event.getVignetteUrl()));
130         handler.updateState(group, CHANNEL_EVENT_VIGNETTE_URL, toStringType(event.getVignetteUrl()));
131         handler.updateState(group, CHANNEL_EVENT_SUBTYPE,
132                 event.getSubTypeDescription().map(d -> toStringType(d)).orElse(UnDefType.NULL));
133         final String message = event.getName();
134         handler.updateState(group, CHANNEL_EVENT_MESSAGE,
135                 message == null || message.isBlank() ? UnDefType.NULL : toStringType(message));
136         State personId = event.getPersons().isEmpty() ? UnDefType.NULL
137                 : toStringType(event.getPersons().values().iterator().next().getId());
138         handler.updateState(personChannelUID, personId);
139     }
140
141     @Override
142     public void handleCommand(String channelName, Command command) {
143         if (command instanceof OnOffType && CHANNEL_MONITORING.equals(channelName)) {
144             getSecurityCapability().ifPresent(cap -> cap.changeStatus(localUrl, OnOffType.ON.equals(command)));
145         } else if (command instanceof RefreshType && CHANNEL_LIVEPICTURE.equals(channelName)) {
146             handler.updateState(GROUP_CAM_LIVE, CHANNEL_LIVEPICTURE,
147                     toRawType(cameraHelper.getLivePictureURL(localUrl != null, true)));
148         } else {
149             super.handleCommand(channelName, command);
150         }
151     }
152
153     @Override
154     protected void beforeNewData() {
155         super.beforeNewData();
156         getSecurityCapability().ifPresent(cap -> {
157             NAObjectMap<HomeDataPerson> persons = cap.getPersons();
158             descriptionProvider.setStateOptions(personChannelUID,
159                     persons.values().stream().map(p -> new StateOption(p.getId(), p.getName())).toList());
160         });
161     }
162
163     @Override
164     public List<NAObject> updateReadings() {
165         List<NAObject> result = new ArrayList<>();
166         getSecurityCapability().ifPresent(cap -> {
167             HomeEvent event = cap.getDeviceLastEvent(handler.getId(), moduleType.apiName);
168             if (event != null) {
169                 result.add(event);
170                 result.addAll(event.getSubEvents());
171             }
172         });
173         return result;
174     }
175
176     public @Nullable String ping(String vpnUrl) {
177         return getSecurityCapability().map(cap -> {
178             UriBuilder builder = UriBuilder.fromPath(cap.ping(vpnUrl));
179             URI apiLocalUrl = null;
180             try {
181                 apiLocalUrl = builder.build();
182                 if (apiLocalUrl.getHost().startsWith("169.254.")) {
183                     logger.warn("Suspicious local IP address received: {}", apiLocalUrl);
184                     Configuration config = handler.getThing().getConfiguration();
185                     if (config.containsKey(IP_ADDRESS)) {
186                         String provided = (String) config.get(IP_ADDRESS);
187                         apiLocalUrl = builder.host(provided).build();
188                         logger.info("Using {} as local url for '{}'", apiLocalUrl, thingUID);
189                     } else {
190                         logger.debug("No alternative ip Address provided, keeping API answer");
191                     }
192                 }
193             } catch (UriBuilderException e) { // Crashed at first URI build
194                 logger.warn("API returned a badly formatted local url address for '{}': {}", thingUID, e.getMessage());
195             } catch (IllegalArgumentException e) {
196                 logger.warn("Invalid fallback address provided in configuration for '{}' keeping API answer: {}",
197                         thingUID, e.getMessage());
198             }
199             return apiLocalUrl != null ? apiLocalUrl.toString() : null;
200         }).orElse(null);
201     }
202 }