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.utils.HTTPConstants.*;
17 import java.nio.charset.StandardCharsets;
18 import java.security.KeyFactory;
19 import java.security.MessageDigest;
20 import java.security.PublicKey;
21 import java.security.spec.X509EncodedKeySpec;
22 import java.util.Base64;
23 import java.util.Optional;
24 import java.util.concurrent.TimeUnit;
26 import javax.crypto.Cipher;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.eclipse.jetty.client.HttpClient;
31 import org.eclipse.jetty.client.HttpResponseException;
32 import org.eclipse.jetty.client.api.ContentResponse;
33 import org.eclipse.jetty.client.api.Request;
34 import org.eclipse.jetty.client.api.Result;
35 import org.eclipse.jetty.client.util.BufferingResponseListener;
36 import org.eclipse.jetty.client.util.StringContentProvider;
37 import org.eclipse.jetty.http.HttpHeader;
38 import org.eclipse.jetty.util.MultiMap;
39 import org.eclipse.jetty.util.UrlEncoded;
40 import org.openhab.binding.mybmw.internal.MyBMWConfiguration;
41 import org.openhab.binding.mybmw.internal.VehicleConfiguration;
42 import org.openhab.binding.mybmw.internal.dto.auth.AuthQueryResponse;
43 import org.openhab.binding.mybmw.internal.dto.auth.AuthResponse;
44 import org.openhab.binding.mybmw.internal.dto.auth.ChinaPublicKeyResponse;
45 import org.openhab.binding.mybmw.internal.dto.auth.ChinaTokenExpiration;
46 import org.openhab.binding.mybmw.internal.dto.auth.ChinaTokenResponse;
47 import org.openhab.binding.mybmw.internal.dto.network.NetworkError;
48 import org.openhab.binding.mybmw.internal.handler.simulation.Injector;
49 import org.openhab.binding.mybmw.internal.utils.BimmerConstants;
50 import org.openhab.binding.mybmw.internal.utils.Constants;
51 import org.openhab.binding.mybmw.internal.utils.Converter;
52 import org.openhab.binding.mybmw.internal.utils.HTTPConstants;
53 import org.openhab.binding.mybmw.internal.utils.ImageProperties;
54 import org.openhab.core.io.net.http.HttpClientFactory;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * The {@link MyBMWProxy} This class holds the important constants for the BMW Connected Drive Authorization.
60 * They are taken from the Bimmercode from github <a href="https://github.com/bimmerconnected/bimmer_connected">
61 * https://github.com/bimmerconnected/bimmer_connected</a>.
62 * File defining these constants
63 * <a href="https://github.com/bimmerconnected/bimmer_connected/blob/master/bimmer_connected/account.py">
64 * https://github.com/bimmerconnected/bimmer_connected/blob/master/bimmer_connected/account.py</a>
65 * <a href="https://customer.bmwgroup.com/one/app/oauth.js">https://customer.bmwgroup.com/one/app/oauth.js</a>
67 * @author Bernd Weymann - Initial contribution
68 * @author Norbert Truchsess - edit and send of charge profile
71 public class MyBMWProxy {
72 private final Logger logger = LoggerFactory.getLogger(MyBMWProxy.class);
73 private Optional<RemoteServiceHandler> remoteServiceHandler = Optional.empty();
74 private final Token token = new Token();
75 private final HttpClient httpClient;
76 private final MyBMWConfiguration configuration;
79 * URLs taken from https://github.com/bimmerconnected/bimmer_connected/blob/master/bimmer_connected/const.py
81 final String vehicleUrl;
82 final String remoteCommandUrl;
83 final String remoteStatusUrl;
84 final String serviceExecutionAPI = "/executeService";
85 final String serviceExecutionStateAPI = "/serviceExecutionStatus";
86 final String remoteServiceEADRXstatusUrl = BimmerConstants.API_REMOTE_SERVICE_BASE_URL
87 + "eventStatus?eventId={event_id}";
89 public MyBMWProxy(HttpClientFactory httpClientFactory, MyBMWConfiguration config) {
90 httpClient = httpClientFactory.getCommonHttpClient();
91 configuration = config;
93 vehicleUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(configuration.region)
94 + BimmerConstants.API_VEHICLES;
96 remoteCommandUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(configuration.region)
97 + BimmerConstants.API_REMOTE_SERVICE_BASE_URL;
98 remoteStatusUrl = remoteCommandUrl + "eventStatus";
101 public synchronized void call(final String url, final boolean post, final @Nullable String encoding,
102 final @Nullable String params, final String brand, final ResponseCallback callback) {
103 // only executed in "simulation mode"
104 // SimulationTest.testSimulationOff() assures Injector is off when releasing
105 if (Injector.isActive()) {
106 if (url.equals(vehicleUrl)) {
107 ((StringResponseCallback) callback).onResponse(Injector.getDiscovery());
108 } else if (url.endsWith(vehicleUrl)) {
109 ((StringResponseCallback) callback).onResponse(Injector.getStatus());
111 logger.debug("Simulation of {} not supported", url);
116 // return in case of unknown brand
117 if (!BimmerConstants.ALL_BRANDS.contains(brand.toLowerCase())) {
118 logger.warn("Unknown Brand {}", brand);
123 final String completeUrl;
127 req = httpClient.POST(url);
128 if (encoding != null) {
129 req.header(HttpHeader.CONTENT_TYPE, encoding);
130 if (CONTENT_TYPE_URL_ENCODED.equals(encoding)) {
131 req.content(new StringContentProvider(CONTENT_TYPE_URL_ENCODED, params, StandardCharsets.UTF_8));
132 } else if (CONTENT_TYPE_JSON_ENCODED.equals(encoding)) {
133 req.content(new StringContentProvider(CONTENT_TYPE_JSON_ENCODED, params, StandardCharsets.UTF_8));
137 completeUrl = params == null ? url : url + Constants.QUESTION + params;
138 req = httpClient.newRequest(completeUrl);
140 req.header(HttpHeader.AUTHORIZATION, getToken().getBearerToken());
141 req.header(HTTPConstants.X_USER_AGENT,
142 String.format(BimmerConstants.X_USER_AGENT, brand, configuration.region));
143 req.header(HttpHeader.ACCEPT_LANGUAGE, configuration.language);
144 if (callback instanceof ByteResponseCallback) {
145 req.header(HttpHeader.ACCEPT, "image/png");
147 req.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON_ENCODED);
150 req.timeout(HTTP_TIMEOUT_SEC, TimeUnit.SECONDS).send(new BufferingResponseListener() {
151 @NonNullByDefault({})
153 public void onComplete(Result result) {
154 if (result.getResponse().getStatus() != 200) {
155 NetworkError error = new NetworkError();
156 error.url = completeUrl;
157 error.status = result.getResponse().getStatus();
158 if (result.getResponse().getReason() != null) {
159 error.reason = result.getResponse().getReason();
161 error.reason = result.getFailure().getMessage();
163 error.params = result.getRequest().getParams().toString();
164 logger.debug("HTTP Error {}", error.toString());
165 callback.onError(error);
167 if (callback instanceof StringResponseCallback responseCallback) {
168 responseCallback.onResponse(getContentAsString());
169 } else if (callback instanceof ByteResponseCallback responseCallback) {
170 responseCallback.onResponse(getContent());
172 logger.error("unexpected reponse type {}", callback.getClass().getName());
179 public void get(String url, @Nullable String coding, @Nullable String params, final String brand,
180 ResponseCallback callback) {
181 call(url, false, coding, params, brand, callback);
184 public void post(String url, @Nullable String coding, @Nullable String params, final String brand,
185 ResponseCallback callback) {
186 call(url, true, coding, params, brand, callback);
190 * request all vehicles for one specific brand
195 public void requestVehicles(String brand, StringResponseCallback callback) {
196 // calculate necessary parameters for query
197 MultiMap<String> vehicleParams = new MultiMap<String>();
198 vehicleParams.put(BimmerConstants.TIRE_GUARD_MODE, Constants.ENABLED);
199 vehicleParams.put(BimmerConstants.APP_DATE_TIME, Long.toString(System.currentTimeMillis()));
200 vehicleParams.put(BimmerConstants.APP_TIMEZONE, Integer.toString(Converter.getOffsetMinutes()));
201 String params = UrlEncoded.encode(vehicleParams, StandardCharsets.UTF_8, false);
202 get(vehicleUrl + "?" + params, null, null, brand, callback);
206 * request vehicles for all possible brands
210 public void requestVehicles(StringResponseCallback callback) {
211 BimmerConstants.ALL_BRANDS.forEach(brand -> {
212 requestVehicles(brand, callback);
216 public void requestImage(VehicleConfiguration config, ImageProperties props, ByteResponseCallback callback) {
217 final String localImageUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(configuration.region)
218 + "/eadrax-ics/v3/presentation/vehicles/" + config.vin + "/images?carView=" + props.viewport;
219 get(localImageUrl, null, null, config.vehicleBrand, callback);
223 * request charge statistics for electric vehicles
227 public void requestChargeStatistics(VehicleConfiguration config, StringResponseCallback callback) {
228 MultiMap<String> chargeStatisticsParams = new MultiMap<String>();
229 chargeStatisticsParams.put("vin", config.vin);
230 chargeStatisticsParams.put("currentDate", Converter.getCurrentISOTime());
231 String params = UrlEncoded.encode(chargeStatisticsParams, StandardCharsets.UTF_8, false);
232 String chargeStatisticsUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(configuration.region)
233 + "/eadrax-chs/v1/charging-statistics?" + params;
234 get(chargeStatisticsUrl, null, null, config.vehicleBrand, callback);
238 * request charge statistics for electric vehicles
242 public void requestChargeSessions(VehicleConfiguration config, StringResponseCallback callback) {
243 MultiMap<String> chargeSessionsParams = new MultiMap<String>();
244 chargeSessionsParams.put("vin", "WBY1Z81040V905639");
245 chargeSessionsParams.put("maxResults", "40");
246 chargeSessionsParams.put("include_date_picker", "true");
247 String params = UrlEncoded.encode(chargeSessionsParams, StandardCharsets.UTF_8, false);
248 String chargeSessionsUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(configuration.region)
249 + "/eadrax-chs/v1/charging-sessions?" + params;
251 get(chargeSessionsUrl, null, null, config.vehicleBrand, callback);
254 RemoteServiceHandler getRemoteServiceHandler(VehicleHandler vehicleHandler) {
255 remoteServiceHandler = Optional.of(new RemoteServiceHandler(vehicleHandler, this));
256 return remoteServiceHandler.get();
262 * Gets new token if old one is expired or invalid. In case of error the token remains.
263 * So if token refresh fails the corresponding requests will also fail and update the
264 * Thing status accordingly.
268 public Token getToken() {
269 if (!token.isValid()) {
270 boolean tokenUpdateSuccess = false;
271 switch (configuration.region) {
272 case BimmerConstants.REGION_CHINA:
273 tokenUpdateSuccess = updateTokenChina();
275 case BimmerConstants.REGION_NORTH_AMERICA:
276 tokenUpdateSuccess = updateToken();
278 case BimmerConstants.REGION_ROW:
279 tokenUpdateSuccess = updateToken();
282 logger.warn("Region {} not supported", configuration.region);
285 if (!tokenUpdateSuccess) {
286 logger.debug("Authorization failed!");
293 * Everything is catched by surroundig try catch
295 * - JSONSyntax Exceptions
296 * - potential NullPointer Exceptions
300 @SuppressWarnings("null")
301 public synchronized boolean updateToken() {
304 * Step 1) Get basic values for further queries
306 String authValuesUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(configuration.region)
307 + BimmerConstants.API_OAUTH_CONFIG;
308 Request authValuesRequest = httpClient.newRequest(authValuesUrl);
309 authValuesRequest.header(ACP_SUBSCRIPTION_KEY, BimmerConstants.OCP_APIM_KEYS.get(configuration.region));
310 authValuesRequest.header(X_USER_AGENT,
311 String.format(BimmerConstants.X_USER_AGENT, BimmerConstants.BRAND_BMW, configuration.region));
313 ContentResponse authValuesResponse = authValuesRequest.send();
314 if (authValuesResponse.getStatus() != 200) {
315 throw new HttpResponseException("URL: " + authValuesRequest.getURI() + ", Error: "
316 + authValuesResponse.getStatus() + ", Message: " + authValuesResponse.getContentAsString(),
319 AuthQueryResponse aqr = Converter.getGson().fromJson(authValuesResponse.getContentAsString(),
320 AuthQueryResponse.class);
323 * Step 2) Calculate values for base parameters
325 String verfifierBytes = Converter.getRandomString(64);
326 String codeVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(verfifierBytes.getBytes());
327 MessageDigest digest = MessageDigest.getInstance("SHA-256");
328 byte[] hash = digest.digest(codeVerifier.getBytes(StandardCharsets.UTF_8));
329 String codeChallange = Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
330 String stateBytes = Converter.getRandomString(16);
331 String state = Base64.getUrlEncoder().withoutPadding().encodeToString(stateBytes.getBytes());
333 MultiMap<String> baseParams = new MultiMap<String>();
334 baseParams.put(CLIENT_ID, aqr.clientId);
335 baseParams.put(RESPONSE_TYPE, CODE);
336 baseParams.put(REDIRECT_URI, aqr.returnUrl);
337 baseParams.put(STATE, state);
338 baseParams.put(NONCE, BimmerConstants.LOGIN_NONCE);
339 baseParams.put(SCOPE, String.join(Constants.SPACE, aqr.scopes));
340 baseParams.put(CODE_CHALLENGE, codeChallange);
341 baseParams.put(CODE_CHALLENGE_METHOD, "S256");
344 * Step 3) Authorization with username and password
346 String loginUrl = aqr.gcdmBaseUrl + BimmerConstants.OAUTH_ENDPOINT;
347 Request loginRequest = httpClient.POST(loginUrl);
348 loginRequest.header(HttpHeader.CONTENT_TYPE, CONTENT_TYPE_URL_ENCODED);
350 MultiMap<String> loginParams = new MultiMap<String>(baseParams);
351 loginParams.put(GRANT_TYPE, BimmerConstants.AUTHORIZATION_CODE);
352 loginParams.put(USERNAME, configuration.userName);
353 loginParams.put(PASSWORD, configuration.password);
354 loginRequest.content(new StringContentProvider(CONTENT_TYPE_URL_ENCODED,
355 UrlEncoded.encode(loginParams, StandardCharsets.UTF_8, false), StandardCharsets.UTF_8));
356 ContentResponse loginResponse = loginRequest.send();
357 if (loginResponse.getStatus() != 200) {
358 throw new HttpResponseException("URL: " + loginRequest.getURI() + ", Error: "
359 + loginResponse.getStatus() + ", Message: " + loginResponse.getContentAsString(),
362 String authCode = getAuthCode(loginResponse.getContentAsString());
365 * Step 4) Authorize with code
367 Request authRequest = httpClient.POST(loginUrl).followRedirects(false);
368 MultiMap<String> authParams = new MultiMap<String>(baseParams);
369 authParams.put(AUTHORIZATION, authCode);
370 authRequest.header(HttpHeader.CONTENT_TYPE, CONTENT_TYPE_URL_ENCODED);
371 authRequest.content(new StringContentProvider(CONTENT_TYPE_URL_ENCODED,
372 UrlEncoded.encode(authParams, StandardCharsets.UTF_8, false), StandardCharsets.UTF_8));
373 ContentResponse authResponse = authRequest.send();
374 if (authResponse.getStatus() != 302) {
375 throw new HttpResponseException("URL: " + authRequest.getURI() + ", Error: " + authResponse.getStatus()
376 + ", Message: " + authResponse.getContentAsString(), authResponse);
378 String code = MyBMWProxy.codeFromUrl(authResponse.getHeaders().get(HttpHeader.LOCATION));
381 * Step 5) Request token
383 Request codeRequest = httpClient.POST(aqr.tokenEndpoint);
384 String basicAuth = "Basic "
385 + Base64.getUrlEncoder().encodeToString((aqr.clientId + ":" + aqr.clientSecret).getBytes());
386 codeRequest.header(HttpHeader.CONTENT_TYPE, CONTENT_TYPE_URL_ENCODED);
387 codeRequest.header(AUTHORIZATION, basicAuth);
389 MultiMap<String> codeParams = new MultiMap<String>();
390 codeParams.put(CODE, code);
391 codeParams.put(CODE_VERIFIER, codeVerifier);
392 codeParams.put(REDIRECT_URI, aqr.returnUrl);
393 codeParams.put(GRANT_TYPE, BimmerConstants.AUTHORIZATION_CODE);
394 codeRequest.content(new StringContentProvider(CONTENT_TYPE_URL_ENCODED,
395 UrlEncoded.encode(codeParams, StandardCharsets.UTF_8, false), StandardCharsets.UTF_8));
396 ContentResponse codeResponse = codeRequest.send();
397 if (codeResponse.getStatus() != 200) {
398 throw new HttpResponseException("URL: " + codeRequest.getURI() + ", Error: " + codeResponse.getStatus()
399 + ", Message: " + codeResponse.getContentAsString(), codeResponse);
401 AuthResponse ar = Converter.getGson().fromJson(codeResponse.getContentAsString(), AuthResponse.class);
402 token.setType(ar.tokenType);
403 token.setToken(ar.accessToken);
404 token.setExpiration(ar.expiresIn);
406 } catch (Exception e) {
407 logger.warn("Authorization Exception: {}", e.getMessage());
412 private String getAuthCode(String response) {
413 String[] keys = response.split("&");
414 for (int i = 0; i < keys.length; i++) {
415 if (keys[i].startsWith(AUTHORIZATION)) {
416 String authCode = keys[i].split("=")[1];
417 authCode = authCode.split("\"")[0];
421 return Constants.EMPTY;
424 public static String codeFromUrl(String encodedUrl) {
425 final MultiMap<String> tokenMap = new MultiMap<String>();
426 UrlEncoded.decodeTo(encodedUrl, tokenMap, StandardCharsets.US_ASCII);
427 final StringBuilder codeFound = new StringBuilder();
428 tokenMap.forEach((key, value) -> {
429 if (!value.isEmpty()) {
430 String val = value.get(0);
431 if (key.endsWith(CODE)) {
432 codeFound.append(val);
436 return codeFound.toString();
439 @SuppressWarnings("null")
440 public synchronized boolean updateTokenChina() {
443 * Step 1) get public key
445 String publicKeyUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(BimmerConstants.REGION_CHINA)
446 + BimmerConstants.CHINA_PUBLIC_KEY;
447 Request oauthQueryRequest = httpClient.newRequest(publicKeyUrl);
448 oauthQueryRequest.header(HttpHeader.USER_AGENT, BimmerConstants.USER_AGENT);
449 oauthQueryRequest.header(X_USER_AGENT,
450 String.format(BimmerConstants.X_USER_AGENT, BimmerConstants.BRAND_BMW, configuration.region));
451 ContentResponse publicKeyResponse = oauthQueryRequest.send();
452 if (publicKeyResponse.getStatus() != 200) {
453 throw new HttpResponseException("URL: " + oauthQueryRequest.getURI() + ", Error: "
454 + publicKeyResponse.getStatus() + ", Message: " + publicKeyResponse.getContentAsString(),
457 ChinaPublicKeyResponse pkr = Converter.getGson().fromJson(publicKeyResponse.getContentAsString(),
458 ChinaPublicKeyResponse.class);
461 * Step 2) Encode password with public key
463 // https://www.baeldung.com/java-read-pem-file-keys
464 String publicKeyStr = pkr.data.value;
465 String publicKeyPEM = publicKeyStr.replace("-----BEGIN PUBLIC KEY-----", "")
466 .replaceAll(System.lineSeparator(), "").replace("-----END PUBLIC KEY-----", "").replace("\\r", "")
467 .replace("\\n", "").trim();
468 byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
469 X509EncodedKeySpec spec = new X509EncodedKeySpec(encoded);
470 KeyFactory kf = KeyFactory.getInstance("RSA");
471 PublicKey publicKey = kf.generatePublic(spec);
472 // https://www.thexcoders.net/java-ciphers-rsa/
473 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
474 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
475 byte[] encryptedBytes = cipher.doFinal(configuration.password.getBytes());
476 String encodedPassword = Base64.getEncoder().encodeToString(encryptedBytes);
479 * Step 3) Send Auth with encoded password
481 String tokenUrl = "https://" + BimmerConstants.EADRAX_SERVER_MAP.get(BimmerConstants.REGION_CHINA)
482 + BimmerConstants.CHINA_LOGIN;
483 Request loginRequest = httpClient.POST(tokenUrl);
484 loginRequest.header(X_USER_AGENT,
485 String.format(BimmerConstants.X_USER_AGENT, BimmerConstants.BRAND_BMW, configuration.region));
486 String jsonContent = "{ \"mobile\":\"" + configuration.userName + "\", \"password\":\"" + encodedPassword
488 loginRequest.content(new StringContentProvider(jsonContent));
489 ContentResponse tokenResponse = loginRequest.send();
490 if (tokenResponse.getStatus() != 200) {
491 throw new HttpResponseException("URL: " + loginRequest.getURI() + ", Error: "
492 + tokenResponse.getStatus() + ", Message: " + tokenResponse.getContentAsString(),
495 String authCode = getAuthCode(tokenResponse.getContentAsString());
498 * Step 4) Decode access token
500 ChinaTokenResponse cat = Converter.getGson().fromJson(authCode, ChinaTokenResponse.class);
501 String token = cat.data.accessToken;
502 // https://www.baeldung.com/java-jwt-token-decode
503 String[] chunks = token.split("\\.");
504 String tokenJwtDecodeStr = new String(Base64.getUrlDecoder().decode(chunks[1]));
505 ChinaTokenExpiration cte = Converter.getGson().fromJson(tokenJwtDecodeStr, ChinaTokenExpiration.class);
506 Token t = new Token();
508 t.setType(cat.data.tokenType);
509 t.setExpirationTotal(cte.exp);
511 } catch (Exception e) {
512 logger.warn("Authorization Exception: {}", e.getMessage());