2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.mybmw.internal.handler;
15 import static org.openhab.binding.mybmw.internal.MyBMWConstants.*;
16 import static org.openhab.binding.mybmw.internal.utils.HTTPConstants.CONTENT_TYPE_JSON_ENCODED;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Optional;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
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;
36 import com.google.gson.JsonSyntaxException;
39 * The {@link RemoteServiceHandler} handles executions of remote services towards your Vehicle
41 * @see https://github.com/bimmerconnected/bimmer_connected/blob/master/bimmer_connected/remote_services.py
43 * @author Bernd Weymann - Initial contribution
44 * @author Norbert Truchsess - edit & send of charge profile
47 public class RemoteServiceHandler implements StringResponseCallback {
48 private final Logger logger = LoggerFactory.getLogger(RemoteServiceHandler.class);
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
55 private final MyBMWProxy proxy;
56 private final VehicleHandler handler;
57 private final String serviceExecutionAPI;
58 private final String serviceExecutionStateAPI;
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();
65 public enum ExecutionState {
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");
84 private final String label;
85 private final String id;
86 private final String command;
88 RemoteService(final String label, final String id, String command) {
91 this.command = command;
94 public String getLabel() {
98 public String getId() {
102 public String getCommand() {
107 public RemoteServiceHandler(VehicleHandler vehicleHandler, MyBMWProxy myBmwProxy) {
108 handler = vehicleHandler;
110 final VehicleConfiguration config = handler.getConfiguration().get();
111 serviceExecutionAPI = proxy.remoteCommandUrl + config.vin + "/";
112 serviceExecutionStateAPI = proxy.remoteStatusUrl;
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
122 serviceExecuting = Optional.of(service.getId());
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);
130 proxy.post(serviceExecutionAPI + service.getCommand(), null, null,
131 handler.getConfiguration().get().vehicleBrand, this);
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());
144 // immediately refresh data
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);
155 logger.warn("No Service executed to get state");
157 stateJob = Optional.empty();
162 public void onResponse(@Nullable String result) {
163 if (result != null) {
165 ExecutionStatusContainer esc = Converter.getGson().fromJson(result, ExecutionStatusContainer.class);
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!
187 } catch (JsonSyntaxException jse) {
188 logger.debug("RemoteService response is unparseable: {} {}", result, jse.getMessage());
191 // schedule even if no result is present until retries exceeded
192 synchronized (this) {
193 stateJob.ifPresent(job -> {
198 stateJob = Optional.of(handler.getScheduler().schedule(this::getState, STATE_UPDATE_SEC, TimeUnit.SECONDS));
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));
211 private void reset() {
212 serviceExecuting = Optional.empty();
213 executingEventId = Optional.empty();
217 public void cancel() {
218 synchronized (this) {
219 stateJob.ifPresent(action -> {
220 if (!action.isDone()) {
223 stateJob = Optional.empty();