2 * Copyright (c) 2010-2021 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.magentatv.internal.handler;
15 import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.*;
16 import static org.openhab.binding.magentatv.internal.MagentaTVUtil.*;
18 import java.io.UnsupportedEncodingException;
19 import java.security.MessageDigest;
20 import java.security.NoSuchAlgorithmException;
21 import java.text.MessageFormat;
22 import java.util.HashMap;
23 import java.util.StringTokenizer;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.openhab.binding.magentatv.internal.MagentaTVException;
28 import org.openhab.binding.magentatv.internal.config.MagentaTVDynamicConfig;
29 import org.openhab.binding.magentatv.internal.network.MagentaTVHttp;
30 import org.openhab.binding.magentatv.internal.network.MagentaTVNetwork;
31 import org.openhab.binding.magentatv.internal.network.MagentaTVOAuth;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
36 * The {@link MagentaTVControl} implements the control functions for the
39 * @author Markus Michels - Initial contribution
42 public class MagentaTVControl {
43 private final Logger logger = LoggerFactory.getLogger(MagentaTVControl.class);
44 private final static HashMap<String, String> KEY_MAP = new HashMap<>();
46 private final MagentaTVNetwork network;
47 private final MagentaTVHttp http = new MagentaTVHttp();
48 private final MagentaTVOAuth oauth;
49 private final MagentaTVDynamicConfig config;
50 private boolean initialized = false;
51 private String thingId = "";
53 public MagentaTVControl() {
54 config = new MagentaTVDynamicConfig();
55 network = new MagentaTVNetwork();
56 oauth = new MagentaTVOAuth(new HttpClient());
59 public MagentaTVControl(MagentaTVDynamicConfig config, MagentaTVNetwork network, HttpClient httpClient) {
60 thingId = config.getFriendlyName();
61 this.network = network;
62 this.oauth = new MagentaTVOAuth(httpClient);
64 this.config.setTerminalID(computeMD5(network.getLocalMAC().toUpperCase() + config.getUDN()));
65 this.config.setLocalIP(network.getLocalIP());
66 this.config.setLocalMAC(network.getLocalMAC());
70 public boolean isInitialized() {
75 * Returns the thingConfig - the Control class adds various attributes of the
76 * discovered device (like the MR model)
80 public MagentaTVDynamicConfig getConfig() {
85 * Initiate OAuth authentication
87 * @param accountName T-Online user id
88 * @param accountPassword T-Online password
89 * @return true: successful, false: failed
91 * @throws MagentaTVException
93 public String getUserId(String accountName, String accountPassword) throws MagentaTVException {
94 return oauth.getUserId(accountName, accountPassword);
98 * Retries the device properties. This will result in an Exception if the device
101 * Response is returned in XMl format, e.g.:
102 * <?xml version="1.0"?> <root xmlns="urn:schemas-upnp-org:device-1-0">
103 * <specVersion><major>1</major><minor>0</minor></specVersion> <device>
104 * <UDN>uuid:70dff25c-1bdf-5731-a283-XXXXXXXX</UDN>
105 * <friendlyName>DMS_XXXXXXXXXXXX</friendlyName>
106 * <deviceType>urn:schemas-upnp-org:device:tvdevice:1</deviceType>
107 * <manufacturer>Zenterio</manufacturer> <modelName>MR401B</modelName>
108 * <modelNumber>R01A5</modelNumber> <productVersionNumber>" 334
109 * "</productVersionNumber> <productType>stb</productType>
110 * <serialNumber></serialNumber> <X_wakeOnLan>0</X_wakeOnLan> <serviceList>
111 * <service> <serviceType>urn:dial-multiscreen-org:service:dial:1</serviceType>
112 * <serviceId>urn:dial-multiscreen-org:service:dial</serviceId> </service>
113 * </serviceList> </device> </root>
115 * @return true: device is online, false: device is offline
116 * @throws MagentaTVException
118 public boolean checkDev() throws MagentaTVException {
119 logger.debug("{}: Check device {} ({}:{})", thingId, config.getTerminalID(), config.getIpAddress(),
122 String url = MessageFormat.format(CHECKDEV_URI, config.getIpAddress(), config.getPort(),
123 config.getDescriptionUrl());
124 String result = http.httpGet(buildHost(), url, "");
125 if (result.contains("<modelName>")) {
126 config.setModel(substringBetween(result, "<modelName>", "</modelName>"));
128 if (result.contains("<modelNumber>")) {
129 config.setHardwareVersion(substringBetween(result, "<modelNumber>", "</modelNumber>"));
131 if (result.contains("<X_wakeOnLan>")) {
132 String wol = substringBetween(result, "<X_wakeOnLan>", "</X_wakeOnLan>");
133 config.setWakeOnLAN(wol);
134 logger.debug("{}: Wake-on-LAN is {}", thingId, wol.equals("0") ? "disabled" : "enabled");
136 if (result.contains("<productVersionNumber>")) {
138 if (result.contains("<productVersionNumber>" ")) {
139 version = substringBetween(result, "<productVersionNumber>" ", " "</productVersionNumber>");
141 version = substringBetween(result, "<productVersionNumber>", "</productVersionNumber>");
143 config.setFirmwareVersion(version);
145 if (result.contains("<friendlyName>")) {
146 String friendlyName = result.substring(result.indexOf("<friendlyName>") + "<friendlyName>".length(),
147 result.indexOf("</friendlyName>"));
148 config.setFriendlyName(friendlyName);
150 if (result.contains("<UDN>uuid:")) {
151 String udn = result.substring(result.indexOf("<UDN>uuid:") + "<UDN>uuid:".length(),
152 result.indexOf("</UDN>"));
153 if (config.getUDN().isEmpty()) {
157 logger.trace("{}: Online status verified for device {}:{}, UDN={}", thingId, config.getIpAddress(),
158 config.getPort(), config.getUDN());
164 * Sends a SUBSCRIBE request to the MR. This also defines the local callback url
165 * used by the MR to return the pairing code and event information.
167 * Subscripbe to event channel a) receive the pairing code b) receive
168 * programInfo and playStatus events after successful paring
170 * SUBSCRIBE /upnp/service/X-CTC_RemotePairing/Event HTTP/1.1\r\n HOST:
171 * $remote_ip:$remote_port CALLBACK: <http://$local_ip:$local_port/>\r\n // NT:
172 * upnp:event\r\n // TIMEOUT: Second-300\r\n // CONNECTION: close\r\n // \r\n
174 * @throws MagentaTVException
176 public void subscribeEventChannel() throws MagentaTVException {
178 logger.debug("{}: Subscribe Event Channel (terminalID={}, {}:{}", thingId, config.getTerminalID(),
179 config.getIpAddress(), config.getPort());
180 String subscribe = MessageFormat.format(PAIRING_SUBSCRIBE, config.getIpAddress(), config.getPort(),
181 network.getLocalIP(), network.getLocalPort(), PAIRING_NOTIFY_URI, PAIRING_TIMEOUT_SEC);
182 String response = http.sendData(config.getIpAddress(), config.getPort(), subscribe);
183 if (!response.contains("200 OK")) {
184 response = substringBefore(response, "SERVER");
185 throw new MagentaTVException("Unable to subscribe to pairing channel: " + response);
187 if (!response.contains(NOTIFY_SID)) {
188 throw new MagentaTVException("Unable to subscribe to pairing channel, SID missing: " + response);
191 StringTokenizer tokenizer = new StringTokenizer(response, "\r\n");
192 while (tokenizer.hasMoreElements()) {
193 String str = tokenizer.nextToken();
194 if (!str.isEmpty()) {
195 if (str.contains(NOTIFY_SID)) {
196 sid = str.substring("SID: uuid:".length());
197 logger.debug("{}: SUBSCRIBE returned SID {}", thingId, sid);
205 * Send Pairing Request to the Media Receiver. The method waits for the
206 * response, but the pairing code will be received via the NOTIFY callback (see
209 * XML format for Pairing Request: <s:Envelope
210 * xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"
211 * <s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> <s:Body>\n
212 * <u:X-pairingRequest
213 * xmlns:u=\"urn:schemas-upnp-org:service:X-CTC_RemotePairing:1\">\n
214 * <pairingDeviceID>$pairingDeviceID</pairingDeviceID>\n
215 * <friendlyName>$friendlyName</friendlyName>\n <userID>$userID</userID>\n
216 * </u:X-pairingRequest>\n </s:Body> </s:Envelope>
218 * @returns true: pairing successful
219 * @throws MagentaTVException
221 public boolean sendPairingRequest() throws MagentaTVException {
222 logger.debug("{}: Send Pairing Request (deviceID={}, type={}, userID={})", thingId, config.getTerminalID(),
223 DEF_FRIENDLY_NAME, config.getUserId());
226 String soapBody = MessageFormat.format(PAIRING_SOAP_BODY, config.getTerminalID(), DEF_FRIENDLY_NAME,
228 String soapXml = MessageFormat.format(SOAP_ENVELOPE, soapBody);
229 String response = http.httpPOST(buildHost(), buildReceiverUrl(PAIRING_CONTROL_URI), soapXml,
230 PAIRING_SOAP_ACTION, CONNECTION_CLOSE);
232 // pairingCode will be received by the Servlet, is calls onPairingResult()
233 // Exception if request failed (response code != HTTP_OK)
234 if (!response.contains("X-pairingRequestResponse") || !response.contains("<result>")) {
235 throw new MagentaTVException("Unexpected result for pairing response: " + response);
238 String result = substringBetween(response, "<result>", "</result>");
239 if (!result.equals("0")) {
240 throw new MagentaTVException("Pairing failed, result=" + result);
243 logger.debug("{}: Pairing initiated (deviceID={}).", thingId, config.getTerminalID());
248 * Calculates the verifificationCode to complete pairing. This will be triggered
249 * as a result after receiving the pairing code provided by the MR. The
250 * verification code is the MD5 hash of <Pairing Code><Terminal-ID><User ID>
252 * @param pairingCode Pairing code received from the MR
253 * @return true: a new code has been generated, false: the code matches a
256 public boolean generateVerificationCode(String pairingCode) {
257 if (config.getPairingCode().equals(pairingCode) && !config.getVerificationCode().isEmpty()) {
258 logger.debug("{}: Pairing code ({}) refreshed, verificationCode={}", thingId, pairingCode,
259 config.getVerificationCode());
262 config.setPairingCode(pairingCode);
263 String md5Input = pairingCode + config.getTerminalID() + config.getUserId();
264 config.setVerificationCode(computeMD5(md5Input).toUpperCase());
265 logger.debug("{}: VerificationCode({}): Input={}, code={}", thingId, config.getTerminalID(), md5Input,
266 config.getVerificationCode());
271 * Send a pairing verification request to the receiver. This is important to
272 * complete the pairing process. You should see a message like "Connected to
273 * openHAB" on your TV screen.
275 * @return true: successful, false: a non-critical error occured, caller handles
277 * @throws MagentaTVException
279 public boolean verifyPairing() throws MagentaTVException {
280 logger.debug("{}: Verify pairing (id={}, code={}", thingId, config.getTerminalID(),
281 config.getVerificationCode());
282 String soapBody = MessageFormat.format(PAIRCHECK_SOAP_BODY, config.getTerminalID(),
283 config.getVerificationCode());
284 String soapXml = MessageFormat.format(SOAP_ENVELOPE, soapBody);
285 String response = http.httpPOST(buildHost(), buildReceiverUrl(PAIRCHECK_URI), soapXml, PAIRCHECK_SOAP_ACTION,
288 // Exception if request failed (response code != HTTP_OK)
289 if (!response.contains("<pairingResult>")) {
290 throw new MagentaTVException("Unexpected result for pairing verification: " + response);
293 String result = getXmlValue(response, "pairingResult");
294 if (!result.equals("0")) {
295 logger.debug("{}: Pairing failed or pairing no longer valid, result={}", thingId, result);
297 // let the caller decide how to proceed
301 if (!config.isMR400()) {
302 String enable4K = getXmlValue(response, "Enable4K");
303 String enableSAT = getXmlValue(response, "EnableSAT");
304 logger.debug("{}: Features: Enable4K:{}, EnableSAT:{}", thingId, enable4K, enableSAT);
311 * @return true if pairing is completed (verification code was generated)
313 public boolean isPaired() {
314 // pairing was completed successful if we have the verification code
315 return !config.getVerificationCode().isEmpty();
319 * Reset pairing information (e.g. when verification failed)
321 public void resetPairing() {
322 // pairing no longer valid
323 config.setPairingCode("");
324 config.setVerificationCode("");
328 * Send key code to the MR (via SOAP request). A key code could be send by it's
329 * code (0x.... notation) or with a symbolic namne, which will first be mapped
332 * XML format for Send Key
334 * <s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"
335 * s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> <s:Body>\n
337 * xmlns:u=\"urn:schemas-upnp-org:service:X-CTC_RemoteControl:1\">\n
338 * <InstanceID>0</InstanceID>\n
339 * <KeyCode>keyCode=$keyCode^$pairingDeviceID:$verificationCode^userID:$userID</KeyCode>\n
340 * </u:X_CTC_RemoteKey>\n </s:Body></s:Envelope>
343 * @return true: successful, false: failed, e.g. unkown key code
344 * @throws MagentaTVException
346 public boolean sendKey(String keyName) throws MagentaTVException {
347 String keyCode = getKeyCode(keyName);
348 logger.debug("{}: Send Key {} (keyCode={}, tid={})", thingId, keyName, keyCode, config.getTerminalID());
349 if (keyCode.length() <= "0x".length()) {
350 logger.debug("{}: Key {} is unkown!", thingId, keyCode);
354 String soapBody = MessageFormat.format(SENDKEY_SOAP_BODY, keyCode, config.getTerminalID(),
355 config.getVerificationCode(), config.getUserId());
356 String soapXml = MessageFormat.format(SOAP_ENVELOPE, soapBody);
357 logger.debug("{}: send keyCode={} to {}:{}", thingId, keyCode, config.getIpAddress(), config.getPort());
358 logger.trace("{}: sendKey terminalid={}, pairingCode={}, verificationCode={}, userId={}", thingId,
359 config.getTerminalID(), config.getPairingCode(), config.getVerificationCode(), config.getUserId());
360 http.httpPOST(buildHost(), buildReceiverUrl(SENDKEY_URI), soapXml, SENDKEY_SOAP_ACTION, CONNECTION_CLOSE);
361 // Exception if request failed (response code != HTTP_OK)
362 // pairingCode will be received by the Servlet, is calls onPairingResult()
367 * Select channel for TV
369 * @param channel new channel (a sequence of numbers, which will be send one by one)
370 * @return true:ok, false: failed
372 public boolean selectChannel(String channel) throws MagentaTVException {
373 logger.debug("{}: Select channel {}", thingId, channel);
374 for (int i = 0; i < channel.length(); i++) {
375 if (!sendKey("" + channel.charAt(i))) {
380 } catch (InterruptedException e) {
387 * Get key code to send to receiver
389 * @param key Key for which to get the key code
392 private String getKeyCode(String key) {
393 if (key.contains("0x")) {
397 String code = KEY_MAP.get(key);
398 return code != null ? code : "";
402 * Map playStatus code to string for a list of codes see
403 * http://support.huawei.com/hedex/pages/DOC1100366313CEH0713H/01/DOC1100366313CEH0713H/01/resources/dsv_hdx_idp/DSV/en/en-us_topic_0094619231.html
405 * @param playStatus Integer code parsed form json (see EV_PLAYCHG_XXX)
406 * @return playStatus as String
408 public String getPlayStatus(int playStatus) {
409 switch (playStatus) {
410 case EV_PLAYCHG_PLAY:
412 case EV_PLAYCHG_STOP:
414 case EV_PLAYCHG_PAUSE:
416 case EV_PLAYCHG_TRICK:
418 case EV_PLAYCHG_MC_PLAY:
419 return "playing (MC)";
420 case EV_PLAYCHG_UC_PLAY:
421 return "playing (UC)";
422 case EV_PLAYCHG_BUFFERING:
425 return Integer.toString(playStatus);
430 * Map runningStatus code to string for a list of codes see
431 * http://support.huawei.com/hedex/pages/DOC1100366313CEH0713H/01/DOC1100366313CEH0713H/01/resources/dsv_hdx_idp/DSV/en/en-us_topic_0094619523.html
433 * @param runStatus Integer code parsed form json (see EV_EITCHG_RUNNING_XXX)
434 * @return runningStatus as String
436 public String getRunStatus(int runStatus) {
438 case EV_EITCHG_RUNNING_NOT_RUNNING:
440 case EV_EITCHG_RUNNING_STARTING:
442 case EV_EITCHG_RUNNING_PAUSING:
444 case EV_EITCHG_RUNNING_RUNNING:
447 return Integer.toString(runStatus);
452 * builds url from the discovered IP address/port and the requested uri
454 * @param uri requested URI
455 * @return the complete URL
457 public String buildReceiverUrl(String uri) {
458 return MessageFormat.format("http://{0}:{1}{2}", config.getIpAddress(), config.getPort(), uri);
464 * @return formatted string (<ip_address>:<port>)
466 private String buildHost() {
467 return config.getIpAddress() + ":" + config.getPort();
471 * Given a string, return the MD5 hash of the String.
473 * @param unhashed The string contents to be hashed.
474 * @return MD5 Hashed value of the String. Null if there is a problem hashing
477 public static String computeMD5(String unhashed) {
479 byte[] bytesOfMessage = unhashed.getBytes(UTF_8);
481 MessageDigest md5 = MessageDigest.getInstance(HASH_ALGORITHM_MD5);
482 byte[] hash = md5.digest(bytesOfMessage);
483 StringBuilder sb = new StringBuilder(2 * hash.length);
484 for (byte b : hash) {
485 sb.append(String.format("%02x", b & 0xff));
488 return sb.toString();
489 } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
495 * Helper to parse a Xml tag value from string without using a complex XML class
497 * @param xml Input string in the format <tag>value</tag>
498 * @param tagName The tag to find
499 * @return Tag value (between <tag> and </tag>)
501 public static String getXmlValue(String xml, String tagName) {
502 String open = "<" + tagName + ">";
503 String close = "</" + tagName + ">";
504 if (xml.contains(open) && xml.contains(close)) {
505 return substringBetween(xml, open, close);
511 * Initialize key map (key name -> key code)
513 * for a list of valid key codes see
514 * http://support.huawei.com/hedex/pages/DOC1100366313CEH0713H/01/DOC1100366313CEH0713H/01/resources/dsv_hdx_idp/DSV/en/en-us_topic_0094619112.html
517 KEY_MAP.put("POWER", "0x0100");
518 KEY_MAP.put("MENU", "0x0110");
519 KEY_MAP.put("EPG", "0x0111");
520 KEY_MAP.put("TVMENU", "0x0454");
521 KEY_MAP.put("VODMENU", "0x0455");
522 KEY_MAP.put("TVODMENU", "0x0456");
523 KEY_MAP.put("NVODMENU", "0x0458");
524 KEY_MAP.put("INFO", "0x010C");
525 KEY_MAP.put("TTEXT", "0x0560");
526 KEY_MAP.put("0", "0x0030");
527 KEY_MAP.put("1", "0x0031");
528 KEY_MAP.put("2", "0x0032");
529 KEY_MAP.put("3", "0x0033");
530 KEY_MAP.put("4", "0x0034");
531 KEY_MAP.put("5", "0x0035");
532 KEY_MAP.put("6", "0x0036");
533 KEY_MAP.put("7", "0x0037");
534 KEY_MAP.put("8", "0x0038");
535 KEY_MAP.put("9", "0x0039");
536 KEY_MAP.put("SPACE", "0x0020");
537 KEY_MAP.put("POUND", "0x0069");
538 KEY_MAP.put("STAR", "0x006A");
539 KEY_MAP.put("UP", "0x0026");
540 KEY_MAP.put("DOWN", "0x0028");
541 KEY_MAP.put("LEFT", "0x0025");
542 KEY_MAP.put("RIGHT", "0x0027");
543 KEY_MAP.put("PGUP", "0x0021");
544 KEY_MAP.put("PGDOWN", "0x0022");
545 KEY_MAP.put("DELETE", "0x0008");
546 KEY_MAP.put("ENTER", "0x000D");
547 KEY_MAP.put("SEARCH", "0x0451");
548 KEY_MAP.put("RED", "0x0113");
549 KEY_MAP.put("GREEN", "0x0114");
550 KEY_MAP.put("YELLOW", "0x0115");
551 KEY_MAP.put("BLUE", "0x0116");
552 KEY_MAP.put("OPTION", "0x0460");
553 KEY_MAP.put("OK", "0x000D");
554 KEY_MAP.put("BACK", "0x0008");
555 KEY_MAP.put("EXIT", "0x045D");
556 KEY_MAP.put("PORTAL", "0x0110");
557 KEY_MAP.put("VOLUP", "0x0103");
558 KEY_MAP.put("VOLDOWN", "0x0104");
559 KEY_MAP.put("INTER", "0x010D");
560 KEY_MAP.put("HELP", "0x011C");
561 KEY_MAP.put("SETTINGS", "0x011D");
562 KEY_MAP.put("MUTE", "0x0105");
563 KEY_MAP.put("CHUP", "0x0101");
564 KEY_MAP.put("CHDOWN", "0x0102");
565 KEY_MAP.put("REWIND", "0x0109");
566 KEY_MAP.put("PLAY", "0x0107");
567 KEY_MAP.put("PAUSE", "0x0107");
568 KEY_MAP.put("FORWARD", "0x0108");
569 KEY_MAP.put("TRACK", "0x0106");
570 KEY_MAP.put("LASTCH", "0x045E");
571 KEY_MAP.put("PREVCH", "0x010B");
572 KEY_MAP.put("NEXTCH", "0x0107");
573 KEY_MAP.put("RECORD", "0x0461");
574 KEY_MAP.put("STOP", "0x010E");
575 KEY_MAP.put("BEGIN", "0x010B");
576 KEY_MAP.put("END", "0x010A");
577 KEY_MAP.put("REPLAY", "0x045B");
578 KEY_MAP.put("SKIP", "0x045C");
579 KEY_MAP.put("SUBTITLE", "0x236");
580 KEY_MAP.put("RECORDINGS", "0x045F");
581 KEY_MAP.put("FAV", "0x0119");
582 KEY_MAP.put("SOURCE", "0x0083");
583 KEY_MAP.put("SWITCH", "0x0118");
584 KEY_MAP.put("IPTV", "0x0081");
585 KEY_MAP.put("PC", "0x0082");
586 KEY_MAP.put("PIP", "0x0084");
587 KEY_MAP.put("MULTIVIEW", "0x0562");
588 KEY_MAP.put("F1", "0x0070");
589 KEY_MAP.put("F2", "0x0071");
590 KEY_MAP.put("F3", "0x0072");
591 KEY_MAP.put("F4", "0x0073");
592 KEY_MAP.put("F5", "0x0074");
593 KEY_MAP.put("F6", "0x0075");
594 KEY_MAP.put("F7", "0x0076");
595 KEY_MAP.put("F8", "0x0077");
596 KEY_MAP.put("F9", "0x0078");
597 KEY_MAP.put("F10", "0x0079");
598 KEY_MAP.put("F11", "0x007A");
599 KEY_MAP.put("F12", "0x007B");
600 KEY_MAP.put("F13", "0x007C");
601 KEY_MAP.put("F14", "0x007D");
602 KEY_MAP.put("F15", "0x007E");
603 KEY_MAP.put("F16", "0x007F");
605 KEY_MAP.put("PVR", "0x0461");
606 KEY_MAP.put("RADIO", "0x0462");
608 // Those key codes are missing and not included in the spec
609 // KEY_MAP.put("TV", "0x");
610 // KEY_MAP.put("RADIO", "0x");
611 // KEY_MAP.put("MOVIES", "0x");