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.amazonechocontrol.internal;
15 import java.io.IOException;
16 import java.net.HttpCookie;
18 import java.net.URISyntaxException;
19 import java.nio.ByteBuffer;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Date;
24 import java.util.List;
25 import java.util.Timer;
26 import java.util.TimerTask;
27 import java.util.UUID;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.ThreadLocalRandom;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.eclipse.jetty.util.ssl.SslContextFactory;
35 import org.eclipse.jetty.websocket.api.Session;
36 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
37 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
38 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
39 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
40 import org.eclipse.jetty.websocket.api.annotations.WebSocket;
41 import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
42 import org.eclipse.jetty.websocket.client.WebSocketClient;
43 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonPushCommand;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 import com.google.gson.Gson;
48 import com.google.gson.JsonSyntaxException;
51 * The {@link WebSocketConnection} encapsulate the Web Socket connection to the amazon server.
52 * The code is based on
53 * https://github.com/Apollon77/alexa-remote/blob/master/alexa-wsmqtt.js
55 * @author Michael Geramb - Initial contribution
56 * @author Ingo Fischer - (https://github.com/Apollon77/alexa-remote/blob/master/alexa-wsmqtt.js)
59 public class WebSocketConnection {
60 private final Logger logger = LoggerFactory.getLogger(WebSocketConnection.class);
61 private final Gson gson = new Gson();
62 private final WebSocketClient webSocketClient;
63 private final IWebSocketCommandHandler webSocketCommandHandler;
64 private final AmazonEchoControlWebSocket amazonEchoControlWebSocket;
66 private @Nullable Session session;
67 private @Nullable Timer pingTimer;
68 private @Nullable Timer pongTimeoutTimer;
69 private @Nullable Future<?> sessionFuture;
71 private boolean closed;
73 public WebSocketConnection(String amazonSite, List<HttpCookie> sessionCookies,
74 IWebSocketCommandHandler webSocketCommandHandler) throws IOException {
75 this.webSocketCommandHandler = webSocketCommandHandler;
76 amazonEchoControlWebSocket = new AmazonEchoControlWebSocket();
77 HttpClient httpClient = new HttpClient(new SslContextFactory.Client());
78 webSocketClient = new WebSocketClient(httpClient);
81 if ("amazon.com".equalsIgnoreCase(amazonSite)) {
82 host = "dp-gw-na-js." + amazonSite;
84 host = "dp-gw-na." + amazonSite;
87 String deviceSerial = "";
88 List<HttpCookie> cookiesForWs = new ArrayList<>();
89 for (HttpCookie cookie : sessionCookies) {
90 if (cookie.getName().equals("ubid-acbde")) {
91 deviceSerial = cookie.getValue();
93 // Clone the cookie without the security attribute, because the web socket implementation ignore secure
95 String value = cookie.getValue().replaceAll("^\"|\"$", "");
96 HttpCookie cookieForWs = new HttpCookie(cookie.getName(), value);
97 cookiesForWs.add(cookieForWs);
99 deviceSerial += "-" + new Date().getTime();
102 uri = new URI("wss://" + host + "/?x-amz-device-type=ALEGCNGL9K0HM&x-amz-device-serial=" + deviceSerial);
105 webSocketClient.start();
106 } catch (Exception e) {
107 logger.warn("Web socket start failed", e);
108 throw new IOException("Web socket start failed");
111 ClientUpgradeRequest request = new ClientUpgradeRequest();
112 request.setHeader("Host", host);
113 request.setHeader("Origin", "alexa." + amazonSite);
114 request.setCookies(cookiesForWs);
116 initPongTimeoutTimer();
118 sessionFuture = webSocketClient.connect(amazonEchoControlWebSocket, uri, request);
119 } catch (URISyntaxException e) {
120 logger.debug("Initialize web socket failed", e);
124 private void setSession(Session session) {
125 this.session = session;
126 logger.debug("Web Socket session started");
127 Timer pingTimer = new Timer();
128 this.pingTimer = pingTimer;
129 pingTimer.schedule(new TimerTask() {
133 amazonEchoControlWebSocket.sendPing();
138 public boolean isClosed() {
142 public void close() {
144 Timer pingTimer = this.pingTimer;
145 if (pingTimer != null) {
148 clearPongTimeoutTimer();
149 Session session = this.session;
151 if (session != null) {
154 } catch (Exception e) {
155 logger.debug("Closing session failed", e);
158 logger.trace("Connect future = {}", sessionFuture);
159 final Future<?> sessionFuture = this.sessionFuture;
160 if (sessionFuture != null && !sessionFuture.isDone()) {
161 sessionFuture.cancel(true);
164 webSocketClient.stop();
165 } catch (InterruptedException e) {
167 } catch (Exception e) {
168 logger.debug("Stopping websocket failed", e);
170 webSocketClient.destroy();
173 void clearPongTimeoutTimer() {
174 Timer pongTimeoutTimer = this.pongTimeoutTimer;
175 this.pongTimeoutTimer = null;
176 if (pongTimeoutTimer != null) {
177 logger.trace("Cancelling pong timeout");
178 pongTimeoutTimer.cancel();
182 void initPongTimeoutTimer() {
183 clearPongTimeoutTimer();
184 Timer pongTimeoutTimer = new Timer();
185 this.pongTimeoutTimer = pongTimeoutTimer;
186 logger.trace("Scheduling pong timeout");
187 pongTimeoutTimer.schedule(new TimerTask() {
191 logger.trace("Pong timeout reached. Closing connection.");
197 @WebSocket(maxTextMessageSize = 64 * 1024, maxBinaryMessageSize = 64 * 1024)
198 public class AmazonEchoControlWebSocket {
202 AmazonEchoControlWebSocket() {
203 this.messageId = ThreadLocalRandom.current().nextInt(0, Short.MAX_VALUE);
206 void sendMessage(String message) {
207 sendMessage(message.getBytes(StandardCharsets.UTF_8));
210 void sendMessageHex(String message) {
211 sendMessage(hexStringToByteArray(message));
214 void sendMessage(byte[] buffer) {
216 logger.debug("Send message with length {}", buffer.length);
217 Session session = WebSocketConnection.this.session;
218 if (session != null) {
219 session.getRemote().sendBytes(ByteBuffer.wrap(buffer));
221 } catch (IOException e) {
222 logger.debug("Send message failed", e);
223 WebSocketConnection.this.close();
227 byte[] hexStringToByteArray(String str) {
228 byte[] bytes = new byte[str.length() / 2];
229 for (int i = 0; i < bytes.length; i++) {
230 String strValue = str.substring(2 * i, 2 * i + 2);
231 bytes[i] = (byte) Integer.parseInt(strValue, 16);
236 long readHex(byte[] data, int index, int length) {
237 String str = readString(data, index, length);
238 if (str.startsWith("0x")) {
239 str = str.substring(2);
241 return Long.parseLong(str, 16);
244 String readString(byte[] data, int index, int length) {
245 return new String(data, index, length, StandardCharsets.UTF_8);
250 Content content = new Content();
251 String contentTune = "";
252 String messageType = "";
256 String moreFlag = "";
261 String messageType = "";
262 String protocolVersion = "";
263 String connectionUUID = "";
267 String subMessageType = "";
269 String destinationIdentityUrn = "";
270 String deviceIdentityUrn = "";
273 byte[] payloadData = new byte[0];
275 JsonPushCommand pushCommand;
278 Message parseIncomingMessage(byte[] data) {
280 Message message = new Message();
281 message.service = readString(data, data.length - 4, 4);
283 if (message.service.equals("TUNE")) {
284 message.checksum = readHex(data, idx, 10);
285 idx += 11; // 10 + delimiter;
286 int contentLength = (int) readHex(data, idx, 10);
287 idx += 11; // 10 + delimiter;
288 message.contentTune = readString(data, idx, contentLength - 4 - idx);
289 } else if (message.service.equals("FABE")) {
290 message.messageType = readString(data, idx, 3);
292 message.channel = readHex(data, idx, 10);
293 idx += 11; // 10 + delimiter;
294 message.messageId = readHex(data, idx, 10);
295 idx += 11; // 10 + delimiter;
296 message.moreFlag = readString(data, idx, 1);
297 idx += 2; // 1 + delimiter;
298 message.seq = readHex(data, idx, 10);
299 idx += 11; // 10 + delimiter;
300 message.checksum = readHex(data, idx, 10);
301 idx += 11; // 10 + delimiter;
303 // currently not used: long contentLength = readHex(data, idx, 10);
304 idx += 11; // 10 + delimiter;
306 message.content.messageType = readString(data, idx, 3);
309 if (message.channel == 0x361) { // GW_HANDSHAKE_CHANNEL
310 if (message.content.messageType.equals("ACK")) {
311 int length = (int) readHex(data, idx, 10);
312 idx += 11; // 10 + delimiter;
313 message.content.protocolVersion = readString(data, idx, length);
315 length = (int) readHex(data, idx, 10);
316 idx += 11; // 10 + delimiter;
317 message.content.connectionUUID = readString(data, idx, length);
319 message.content.established = readHex(data, idx, 10);
320 idx += 11; // 10 + delimiter;
321 message.content.timestampINI = readHex(data, idx, 18);
322 idx += 19; // 18 + delimiter;
323 message.content.timestampACK = readHex(data, idx, 18);
324 idx += 19; // 18 + delimiter;
326 } else if (message.channel == 0x362) { // GW_CHANNEL
327 if (message.content.messageType.equals("GWM")) {
328 message.content.subMessageType = readString(data, idx, 3);
330 message.content.channel = readHex(data, idx, 10);
331 idx += 11; // 10 + delimiter;
333 if (message.content.channel == 0xb479) { // DEE_WEBSITE_MESSAGING
334 int length = (int) readHex(data, idx, 10);
335 idx += 11; // 10 + delimiter;
336 message.content.destinationIdentityUrn = readString(data, idx, length);
339 length = (int) readHex(data, idx, 10);
340 idx += 11; // 10 + delimiter;
341 String idData = readString(data, idx, length);
344 String[] idDataElements = idData.split(" ", 2);
345 message.content.deviceIdentityUrn = idDataElements[0];
346 String payload = null;
347 if (idDataElements.length == 2) {
348 payload = idDataElements[1];
350 if (payload == null) {
351 payload = readString(data, idx, data.length - 4 - idx);
353 if (!payload.isEmpty()) {
355 message.content.pushCommand = gson.fromJson(payload, JsonPushCommand.class);
356 } catch (JsonSyntaxException e) {
357 logger.info("Parsing json failed, illegal JSON: {}", payload, e);
360 message.content.payload = payload;
363 } else if (message.channel == 0x65) { // CHANNEL_FOR_HEARTBEAT
364 idx -= 1; // no delimiter!
365 message.content.payloadData = Arrays.copyOfRange(data, idx, data.length - 4);
372 public void onWebSocketConnect(@Nullable Session session) {
373 if (session != null) {
374 this.msgCounter = -1;
376 sendMessage("0x99d4f71a 0x0000001d A:HTUNE");
378 logger.debug("Web Socket connect without session");
383 public void onWebSocketBinary(byte @Nullable [] data, int offset, int len) {
388 if (this.msgCounter == 0) {
390 "0xa6f6a951 0x0000009c {\"protocolName\":\"A:H\",\"parameters\":{\"AlphaProtocolHandler.receiveWindowSize\":\"16\",\"AlphaProtocolHandler.maxFragmentSize\":\"16000\"}}TUNE");
391 sendMessage(encodeGWHandshake());
392 } else if (this.msgCounter == 1) {
393 sendMessage(encodeGWRegister());
396 byte[] buffer = data;
397 if (offset > 0 || len != buffer.length) {
398 buffer = Arrays.copyOfRange(data, offset, offset + len);
401 Message message = parseIncomingMessage(buffer);
402 if (message.service.equals("FABE") && message.content.messageType.equals("PON")
403 && message.content.payloadData.length > 0) {
404 logger.debug("Pong received");
405 WebSocketConnection.this.clearPongTimeoutTimer();
408 JsonPushCommand pushCommand = message.content.pushCommand;
409 logger.debug("Message received: {}", message.content.payload);
410 if (pushCommand != null) {
411 webSocketCommandHandler.webSocketCommandReceived(pushCommand);
415 } catch (Exception e) {
416 logger.debug("Handling of push notification failed", e);
422 public void onWebSocketText(@Nullable String message) {
423 logger.trace("Received text message: '{}'", message);
427 public void onWebSocketClose(int code, @Nullable String reason) {
428 logger.info("Web Socket close {}. Reason: {}", code, reason);
429 WebSocketConnection.this.close();
433 public void onWebSocketError(@Nullable Throwable error) {
434 logger.info("Web Socket error", error);
436 WebSocketConnection.this.close();
440 public void sendPing() {
441 logger.debug("Send Ping");
442 WebSocketConnection.this.initPongTimeoutTimer();
443 sendMessage(encodePing());
446 String encodeNumber(long val) {
447 return encodeNumber(val, 8);
450 String encodeNumber(long val, int len) {
451 String str = Long.toHexString(val);
452 if (str.length() > len) {
453 str = str.substring(str.length() - len);
455 while (str.length() < len) {
461 long computeBits(long input, long len) {
462 long lenCounter = len;
464 for (value = toUnsignedInt(input); 0 != lenCounter && 0 != value;) {
465 value = (long) Math.floor(value / 2);
471 long toUnsignedInt(long value) {
474 result = 4294967295L + value + 1;
479 int computeChecksum(byte[] data, int exclusionStart, int exclusionEnd) {
480 if (exclusionEnd < exclusionStart) {
486 for (overflow = 0, sum = 0, index = 0; index < data.length; index++) {
487 if (index != exclusionStart) {
488 sum += toUnsignedInt((data[index] & 0xFF) << ((index & 3 ^ 3) << 3));
489 overflow += computeBits(sum, 32);
490 sum = toUnsignedInt((int) sum & (int) 4294967295L);
492 index = exclusionEnd - 1;
495 while (overflow != 0) {
497 overflow = computeBits(sum, 32);
498 sum = (int) sum & (int) 4294967295L;
500 long value = toUnsignedInt(sum);
504 byte[] encodeGWHandshake() {
505 // pubrelBuf = new Buffer('MSG 0x00000361 0x0e414e45 f 0x00000001 0xd7c62f29 0x0000009b INI 0x00000003 1.0
506 // 0x00000024 ff1c4525-c036-4942-bf6c-a098755ac82f 0x00000164d106ce6b END FABE');
508 String msg = "MSG 0x00000361 "; // Message-type and Channel = GW_HANDSHAKE_CHANNEL;
509 msg += this.encodeNumber(this.messageId) + " f 0x00000001 ";
510 int checkSumStart = msg.length();
511 msg += "0x00000000 "; // Checksum!
512 int checkSumEnd = msg.length();
513 msg += "0x0000009b "; // length content
514 msg += "INI 0x00000003 1.0 0x00000024 "; // content part 1
515 msg += UUID.randomUUID().toString();
517 msg += this.encodeNumber(new Date().getTime(), 16);
519 // msg = "MSG 0x00000361 0x0e414e45 f 0x00000001 0xd7c62f29 0x0000009b INI 0x00000003 1.0 0x00000024
520 // ff1c4525-c036-4942-bf6c-a098755ac82f 0x00000164d106ce6b END FABE";
521 byte[] completeBuffer = msg.getBytes(StandardCharsets.US_ASCII);
523 int checksum = this.computeChecksum(completeBuffer, checkSumStart, checkSumEnd);
524 String checksumHex = encodeNumber(checksum);
525 byte[] checksumBuf = checksumHex.getBytes(StandardCharsets.US_ASCII);
526 System.arraycopy(checksumBuf, 0, completeBuffer, checkSumStart, checksumBuf.length);
528 return completeBuffer;
531 byte[] encodeGWRegister() {
532 // pubrelBuf = new Buffer('MSG 0x00000362 0x0e414e46 f 0x00000001 0xf904b9f5 0x00000109 GWM MSG 0x0000b479
533 // 0x0000003b urn:tcomm-endpoint:device:deviceType:0:deviceSerialNumber:0 0x00000041
534 // urn:tcomm-endpoint:service:serviceName:DeeWebsiteMessagingService
535 // {"command":"REGISTER_CONNECTION"}FABE');
537 String msg = "MSG 0x00000362 "; // Message-type and Channel = GW_CHANNEL;
538 msg += this.encodeNumber(this.messageId) + " f 0x00000001 ";
539 int checkSumStart = msg.length();
540 msg += "0x00000000 "; // Checksum!
541 int checkSumEnd = msg.length();
542 msg += "0x00000109 "; // length content
543 msg += "GWM MSG 0x0000b479 0x0000003b urn:tcomm-endpoint:device:deviceType:0:deviceSerialNumber:0 0x00000041 urn:tcomm-endpoint:service:serviceName:DeeWebsiteMessagingService {\"command\":\"REGISTER_CONNECTION\"}FABE";
545 byte[] completeBuffer = msg.getBytes(StandardCharsets.US_ASCII);
547 int checksum = this.computeChecksum(completeBuffer, checkSumStart, checkSumEnd);
549 String checksumHex = encodeNumber(checksum);
550 byte[] checksumBuf = checksumHex.getBytes(StandardCharsets.US_ASCII);
551 System.arraycopy(checksumBuf, 0, completeBuffer, checkSumStart, checksumBuf.length);
553 String test = readString(completeBuffer, 0, completeBuffer.length);
555 return completeBuffer;
558 void encode(byte[] data, long b, int offset, int len) {
559 for (int index = 0; index < len; index++) {
560 data[index + offset] = (byte) (b >> 8 * (len - 1 - index) & 255);
564 byte[] encodePing() {
565 // MSG 0x00000065 0x0e414e47 f 0x00000001 0xbc2fbb5f 0x00000062
567 String msg = "MSG 0x00000065 "; // Message-type and Channel = CHANNEL_FOR_HEARTBEAT;
568 msg += this.encodeNumber(this.messageId) + " f 0x00000001 ";
569 int checkSumStart = msg.length();
570 msg += "0x00000000 "; // Checksum!
571 int checkSumEnd = msg.length();
572 msg += "0x00000062 "; // length content
574 byte[] completeBuffer = new byte[0x62];
575 byte[] startBuffer = msg.getBytes(StandardCharsets.US_ASCII);
577 System.arraycopy(startBuffer, 0, completeBuffer, 0, startBuffer.length);
579 byte[] header = "PIN".getBytes(StandardCharsets.US_ASCII);
580 byte[] payload = "Regular".getBytes(StandardCharsets.US_ASCII); // g = h.length
581 byte[] bufferPing = new byte[header.length + 4 + 8 + 4 + 2 * payload.length];
583 System.arraycopy(header, 0, bufferPing, 0, header.length);
584 idx += header.length;
585 encode(bufferPing, 0, idx, 4);
587 encode(bufferPing, new Date().getTime(), idx, 8);
589 encode(bufferPing, payload.length, idx, 4);
592 for (int q = 0; q < payload.length; q++) {
593 bufferPing[idx + q * 2] = (byte) 0;
594 bufferPing[idx + q * 2 + 1] = payload[q];
596 System.arraycopy(bufferPing, 0, completeBuffer, startBuffer.length, bufferPing.length);
598 byte[] buf2End = "FABE".getBytes(StandardCharsets.US_ASCII);
599 System.arraycopy(buf2End, 0, completeBuffer, startBuffer.length + bufferPing.length, buf2End.length);
601 int checksum = this.computeChecksum(completeBuffer, checkSumStart, checkSumEnd);
602 String checksumHex = encodeNumber(checksum);
603 byte[] checksumBuf = checksumHex.getBytes(StandardCharsets.US_ASCII);
604 System.arraycopy(checksumBuf, 0, completeBuffer, checkSumStart, checksumBuf.length);
605 return completeBuffer;