]> git.basschouten.com Git - openhab-addons.git/blob
3fd881c103611a2b5a4291624ff0a997096dc216
[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.mybmw.internal.handler;
14
15 import static org.openhab.binding.mybmw.internal.MyBMWConstants.*;
16 import static org.openhab.binding.mybmw.internal.utils.HTTPConstants.CONTENT_TYPE_JSON_ENCODED;
17
18 import java.nio.charset.StandardCharsets;
19 import java.util.Optional;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.eclipse.jetty.util.MultiMap;
26 import org.eclipse.jetty.util.UrlEncoded;
27 import org.openhab.binding.mybmw.internal.VehicleConfiguration;
28 import org.openhab.binding.mybmw.internal.dto.network.NetworkError;
29 import org.openhab.binding.mybmw.internal.dto.remote.ExecutionStatusContainer;
30 import org.openhab.binding.mybmw.internal.utils.Constants;
31 import org.openhab.binding.mybmw.internal.utils.Converter;
32 import org.openhab.binding.mybmw.internal.utils.HTTPConstants;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.google.gson.JsonSyntaxException;
37
38 /**
39  * The {@link RemoteServiceHandler} handles executions of remote services towards your Vehicle
40  *
41  * @see https://github.com/bimmerconnected/bimmer_connected/blob/master/bimmer_connected/remote_services.py
42  *
43  * @author Bernd Weymann - Initial contribution
44  * @author Norbert Truchsess - edit & send of charge profile
45  */
46 @NonNullByDefault
47 public class RemoteServiceHandler implements StringResponseCallback {
48     private final Logger logger = LoggerFactory.getLogger(RemoteServiceHandler.class);
49
50     private static final String EVENT_ID = "eventId";
51     private static final String DATA = "data";
52     private static final int GIVEUP_COUNTER = 12; // after 12 retries the state update will give up
53     private static final int STATE_UPDATE_SEC = HTTPConstants.HTTP_TIMEOUT_SEC + 1; // regular timeout + 1sec
54
55     private final MyBMWProxy proxy;
56     private final VehicleHandler handler;
57     private final String serviceExecutionAPI;
58     private final String serviceExecutionStateAPI;
59
60     private int counter = 0;
61     private Optional<ScheduledFuture<?>> stateJob = Optional.empty();
62     private Optional<String> serviceExecuting = Optional.empty();
63     private Optional<String> executingEventId = Optional.empty();
64
65     public enum ExecutionState {
66         READY,
67         INITIATED,
68         PENDING,
69         DELIVERED,
70         EXECUTED,
71         ERROR,
72         TIMEOUT
73     }
74
75     public enum RemoteService {
76         LIGHT_FLASH("Flash Lights", REMOTE_SERVICE_LIGHT_FLASH, REMOTE_SERVICE_LIGHT_FLASH),
77         VEHICLE_FINDER("Vehicle Finder", REMOTE_SERVICE_VEHICLE_FINDER, REMOTE_SERVICE_VEHICLE_FINDER),
78         DOOR_LOCK("Door Lock", REMOTE_SERVICE_DOOR_LOCK, REMOTE_SERVICE_DOOR_LOCK),
79         DOOR_UNLOCK("Door Unlock", REMOTE_SERVICE_DOOR_UNLOCK, REMOTE_SERVICE_DOOR_UNLOCK),
80         HORN_BLOW("Horn Blow", REMOTE_SERVICE_HORN, REMOTE_SERVICE_HORN),
81         CLIMATE_NOW_START("Start Climate", REMOTE_SERVICE_AIR_CONDITIONING_START, "climate-now?action=START"),
82         CLIMATE_NOW_STOP("Stop Climate", REMOTE_SERVICE_AIR_CONDITIONING_STOP, "climate-now?action=STOP");
83
84         private final String label;
85         private final String id;
86         private final String command;
87
88         RemoteService(final String label, final String id, String command) {
89             this.label = label;
90             this.id = id;
91             this.command = command;
92         }
93
94         public String getLabel() {
95             return label;
96         }
97
98         public String getId() {
99             return id;
100         }
101
102         public String getCommand() {
103             return command;
104         }
105     }
106
107     public RemoteServiceHandler(VehicleHandler vehicleHandler, MyBMWProxy myBmwProxy) {
108         handler = vehicleHandler;
109         proxy = myBmwProxy;
110         final VehicleConfiguration config = handler.getConfiguration().get();
111         serviceExecutionAPI = proxy.remoteCommandUrl + config.vin + "/";
112         serviceExecutionStateAPI = proxy.remoteStatusUrl;
113     }
114
115     boolean execute(RemoteService service, String... data) {
116         synchronized (this) {
117             if (serviceExecuting.isPresent()) {
118                 logger.debug("Execution rejected - {} still pending", serviceExecuting.get());
119                 // only one service executing
120                 return false;
121             }
122             serviceExecuting = Optional.of(service.getId());
123         }
124         final MultiMap<String> dataMap = new MultiMap<String>();
125         if (data.length > 0) {
126             dataMap.add(DATA, data[0]);
127             proxy.post(serviceExecutionAPI + service.getCommand(), CONTENT_TYPE_JSON_ENCODED, data[0],
128                     handler.getConfiguration().get().vehicleBrand, this);
129         } else {
130             proxy.post(serviceExecutionAPI + service.getCommand(), null, null,
131                     handler.getConfiguration().get().vehicleBrand, this);
132         }
133         return true;
134     }
135
136     public void getState() {
137         synchronized (this) {
138             serviceExecuting.ifPresentOrElse(service -> {
139                 if (counter >= GIVEUP_COUNTER) {
140                     logger.warn("Giving up updating state for {} after {} times", service, GIVEUP_COUNTER);
141                     handler.updateRemoteExecutionStatus(serviceExecuting.orElse(null),
142                             ExecutionState.TIMEOUT.name().toLowerCase());
143                     reset();
144                     // immediately refresh data
145                     handler.getData();
146                 } else {
147                     counter++;
148                     final MultiMap<String> dataMap = new MultiMap<String>();
149                     dataMap.add(EVENT_ID, executingEventId.get());
150                     final String encoded = UrlEncoded.encode(dataMap, StandardCharsets.UTF_8, false);
151                     proxy.post(serviceExecutionStateAPI + Constants.QUESTION + encoded, null, null,
152                             handler.getConfiguration().get().vehicleBrand, this);
153                 }
154             }, () -> {
155                 logger.warn("No Service executed to get state");
156             });
157             stateJob = Optional.empty();
158         }
159     }
160
161     @Override
162     public void onResponse(@Nullable String result) {
163         if (result != null) {
164             try {
165                 ExecutionStatusContainer esc = Converter.getGson().fromJson(result, ExecutionStatusContainer.class);
166                 if (esc != null) {
167                     if (esc.eventId != null) {
168                         // service initiated - store event id for further MyBMW updates
169                         executingEventId = Optional.of(esc.eventId);
170                         handler.updateRemoteExecutionStatus(serviceExecuting.orElse(null),
171                                 ExecutionState.INITIATED.name().toLowerCase());
172                     } else if (esc.eventStatus != null) {
173                         // service status updated
174                         synchronized (this) {
175                             handler.updateRemoteExecutionStatus(serviceExecuting.orElse(null),
176                                     esc.eventStatus.toLowerCase());
177                             if (ExecutionState.EXECUTED.name().equalsIgnoreCase(esc.eventStatus)
178                                     || ExecutionState.ERROR.name().equalsIgnoreCase(esc.eventStatus)) {
179                                 // refresh loop ends - update of status handled in the normal refreshInterval.
180                                 // Earlier update doesn't show better results!
181                                 reset();
182                                 return;
183                             }
184                         }
185                     }
186                 }
187             } catch (JsonSyntaxException jse) {
188                 logger.debug("RemoteService response is unparseable: {} {}", result, jse.getMessage());
189             }
190         }
191         // schedule even if no result is present until retries exceeded
192         synchronized (this) {
193             stateJob.ifPresent(job -> {
194                 if (!job.isDone()) {
195                     job.cancel(true);
196                 }
197             });
198             stateJob = Optional.of(handler.getScheduler().schedule(this::getState, STATE_UPDATE_SEC, TimeUnit.SECONDS));
199         }
200     }
201
202     @Override
203     public void onError(NetworkError error) {
204         synchronized (this) {
205             handler.updateRemoteExecutionStatus(serviceExecuting.orElse(null),
206                     ExecutionState.ERROR.name().toLowerCase() + Constants.SPACE + Integer.toString(error.status));
207             reset();
208         }
209     }
210
211     private void reset() {
212         serviceExecuting = Optional.empty();
213         executingEventId = Optional.empty();
214         counter = 0;
215     }
216
217     public void cancel() {
218         synchronized (this) {
219             stateJob.ifPresent(action -> {
220                 if (!action.isDone()) {
221                     action.cancel(true);
222                 }
223                 stateJob = Optional.empty();
224             });
225         }
226     }
227 }