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