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.openhab.binding.magentatv.internal.MagentaTVException;
27 import org.openhab.binding.magentatv.internal.config.MagentaTVDynamicConfig;
28 import org.openhab.binding.magentatv.internal.network.MagentaTVHttp;
29 import org.openhab.binding.magentatv.internal.network.MagentaTVNetwork;
30 import org.openhab.binding.magentatv.internal.network.MagentaTVOAuth;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * The {@link MagentaTVControl} implements the control functions for the
38 * @author Markus Michels - Initial contribution
41 public class MagentaTVControl {
42 private final Logger logger = LoggerFactory.getLogger(MagentaTVControl.class);
43 private final static HashMap<String, String> KEY_MAP = new HashMap<>();
45 private final MagentaTVNetwork network;
46 private final MagentaTVHttp http = new MagentaTVHttp();
47 private final MagentaTVOAuth oauth = new MagentaTVOAuth();
48 private final MagentaTVDynamicConfig config;
49 private boolean initialized = false;
50 private String thingId = "";
52 public MagentaTVControl() {
53 config = new MagentaTVDynamicConfig();
54 network = new MagentaTVNetwork();
57 public MagentaTVControl(MagentaTVDynamicConfig config, MagentaTVNetwork network) {
58 thingId = config.getFriendlyName();
59 this.network = network;
61 this.config.setTerminalID(computeMD5(network.getLocalMAC().toUpperCase() + config.getUDN()));
62 this.config.setLocalIP(network.getLocalIP());
63 this.config.setLocalMAC(network.getLocalMAC());
67 public boolean isInitialized() {
72 * Returns the thingConfig - the Control class adds various attributes of the
73 * discovered device (like the MR model)
77 public MagentaTVDynamicConfig getConfig() {
82 * Initiate OAuth authentication
84 * @param accountName T-Online user id
85 * @param accountPassword T-Online password
86 * @return true: successful, false: failed
88 * @throws MagentaTVException
90 public String getUserId(String accountName, String accountPassword) throws MagentaTVException {
91 return oauth.getUserId(accountName, accountPassword);
95 * Retries the device properties. This will result in an Exception if the device
98 * Response is returned in XMl format, e.g.:
99 * <?xml version="1.0"?> <root xmlns="urn:schemas-upnp-org:device-1-0">
100 * <specVersion><major>1</major><minor>0</minor></specVersion> <device>
101 * <UDN>uuid:70dff25c-1bdf-5731-a283-XXXXXXXX</UDN>
102 * <friendlyName>DMS_XXXXXXXXXXXX</friendlyName>
103 * <deviceType>urn:schemas-upnp-org:device:tvdevice:1</deviceType>
104 * <manufacturer>Zenterio</manufacturer> <modelName>MR401B</modelName>
105 * <modelNumber>R01A5</modelNumber> <productVersionNumber>" 334
106 * "</productVersionNumber> <productType>stb</productType>
107 * <serialNumber></serialNumber> <X_wakeOnLan>0</X_wakeOnLan> <serviceList>
108 * <service> <serviceType>urn:dial-multiscreen-org:service:dial:1</serviceType>
109 * <serviceId>urn:dial-multiscreen-org:service:dial</serviceId> </service>
110 * </serviceList> </device> </root>
112 * @return true: device is online, false: device is offline
113 * @throws MagentaTVException
115 public boolean checkDev() throws MagentaTVException {
116 logger.debug("{}: Check device {} ({}:{})", thingId, config.getTerminalID(), config.getIpAddress(),
119 String url = MessageFormat.format(CHECKDEV_URI, config.getIpAddress(), config.getPort(),
120 config.getDescriptionUrl());
121 String result = http.httpGet(buildHost(), url, "");
122 if (result.contains("<modelName>")) {
123 config.setModel(substringBetween(result, "<modelName>", "</modelName>"));
125 if (result.contains("<modelNumber>")) {
126 config.setHardwareVersion(substringBetween(result, "<modelNumber>", "</modelNumber>"));
128 if (result.contains("<X_wakeOnLan>")) {
129 String wol = substringBetween(result, "<X_wakeOnLan>", "</X_wakeOnLan>");
130 config.setWakeOnLAN(wol);
131 logger.debug("{}: Wake-on-LAN is {}", thingId, wol.equals("0") ? "disabled" : "enabled");
133 if (result.contains("<productVersionNumber>")) {
135 if (result.contains("<productVersionNumber>" ")) {
136 version = substringBetween(result, "<productVersionNumber>" ", " "</productVersionNumber>");
138 version = substringBetween(result, "<productVersionNumber>", "</productVersionNumber>");
140 config.setFirmwareVersion(version);
142 if (result.contains("<friendlyName>")) {
143 String friendlyName = result.substring(result.indexOf("<friendlyName>") + "<friendlyName>".length(),
144 result.indexOf("</friendlyName>"));
145 config.setFriendlyName(friendlyName);
147 if (result.contains("<UDN>uuid:")) {
148 String udn = result.substring(result.indexOf("<UDN>uuid:") + "<UDN>uuid:".length(),
149 result.indexOf("</UDN>"));
150 if (config.getUDN().isEmpty()) {
154 logger.trace("{}: Online status verified for device {}:{}, UDN={}", thingId, config.getIpAddress(),
155 config.getPort(), config.getUDN());
161 * Sends a SUBSCRIBE request to the MR. This also defines the local callback url
162 * used by the MR to return the pairing code and event information.
164 * Subscripbe to event channel a) receive the pairing code b) receive
165 * programInfo and playStatus events after successful paring
167 * SUBSCRIBE /upnp/service/X-CTC_RemotePairing/Event HTTP/1.1\r\n HOST:
168 * $remote_ip:$remote_port CALLBACK: <http://$local_ip:$local_port/>\r\n // NT:
169 * upnp:event\r\n // TIMEOUT: Second-300\r\n // CONNECTION: close\r\n // \r\n
171 * @throws MagentaTVException
173 public void subscribeEventChannel() throws MagentaTVException {
175 logger.debug("{}: Subscribe Event Channel (terminalID={}, {}:{}", thingId, config.getTerminalID(),
176 config.getIpAddress(), config.getPort());
177 String subscribe = MessageFormat.format(PAIRING_SUBSCRIBE, config.getIpAddress(), config.getPort(),
178 network.getLocalIP(), network.getLocalPort(), PAIRING_NOTIFY_URI, PAIRING_TIMEOUT_SEC);
179 String response = http.sendData(config.getIpAddress(), config.getPort(), subscribe);
180 if (!response.contains("200 OK")) {
181 response = substringBefore(response, "SERVER");
182 throw new MagentaTVException("Unable to subscribe to pairing channel: " + response);
184 if (!response.contains(NOTIFY_SID)) {
185 throw new MagentaTVException("Unable to subscribe to pairing channel, SID missing: " + response);
188 StringTokenizer tokenizer = new StringTokenizer(response, "\r\n");
189 while (tokenizer.hasMoreElements()) {
190 String str = tokenizer.nextToken();
191 if (!str.isEmpty()) {
192 if (str.contains(NOTIFY_SID)) {
193 sid = str.substring("SID: uuid:".length());
194 logger.debug("{}: SUBSCRIBE returned SID {}", thingId, sid);
202 * Send Pairing Request to the Media Receiver. The method waits for the
203 * response, but the pairing code will be received via the NOTIFY callback (see
206 * XML format for Pairing Request: <s:Envelope
207 * xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"
208 * <s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> <s:Body>\n
209 * <u:X-pairingRequest
210 * xmlns:u=\"urn:schemas-upnp-org:service:X-CTC_RemotePairing:1\">\n
211 * <pairingDeviceID>$pairingDeviceID</pairingDeviceID>\n
212 * <friendlyName>$friendlyName</friendlyName>\n <userID>$userID</userID>\n
213 * </u:X-pairingRequest>\n </s:Body> </s:Envelope>
215 * @returns true: pairing successful
216 * @throws MagentaTVException
218 public boolean sendPairingRequest() throws MagentaTVException {
219 logger.debug("{}: Send Pairing Request (deviceID={}, type={}, userID={})", thingId, config.getTerminalID(),
220 DEF_FRIENDLY_NAME, config.getUserId());
223 String soapBody = MessageFormat.format(PAIRING_SOAP_BODY, config.getTerminalID(), DEF_FRIENDLY_NAME,
225 String soapXml = MessageFormat.format(SOAP_ENVELOPE, soapBody);
226 String response = http.httpPOST(buildHost(), buildReceiverUrl(PAIRING_CONTROL_URI), soapXml,
227 PAIRING_SOAP_ACTION, CONNECTION_CLOSE);
229 // pairingCode will be received by the Servlet, is calls onPairingResult()
230 // Exception if request failed (response code != HTTP_OK)
231 if (!response.contains("X-pairingRequestResponse") || !response.contains("<result>")) {
232 throw new MagentaTVException("Unexpected result for pairing response: " + response);
235 String result = substringBetween(response, "<result>", "</result>");
236 if (!result.equals("0")) {
237 throw new MagentaTVException("Pairing failed, result=" + result);
240 logger.debug("{}: Pairing initiated (deviceID={}).", thingId, config.getTerminalID());
245 * Calculates the verifificationCode to complete pairing. This will be triggered
246 * as a result after receiving the pairing code provided by the MR. The
247 * verification code is the MD5 hash of <Pairing Code><Terminal-ID><User ID>
249 * @param pairingCode Pairing code received from the MR
250 * @return true: a new code has been generated, false: the code matches a
253 public boolean generateVerificationCode(String pairingCode) {
254 if (config.getPairingCode().equals(pairingCode) && !config.getVerificationCode().isEmpty()) {
255 logger.debug("{}: Pairing code ({}) refreshed, verificationCode={}", thingId, pairingCode,
256 config.getVerificationCode());
259 config.setPairingCode(pairingCode);
260 String md5Input = pairingCode + config.getTerminalID() + config.getUserId();
261 config.setVerificationCode(computeMD5(md5Input).toUpperCase());
262 logger.debug("{}: VerificationCode({}): Input={}, code={}", thingId, config.getTerminalID(), md5Input,
263 config.getVerificationCode());
268 * Send a pairing verification request to the receiver. This is important to
269 * complete the pairing process. You should see a message like "Connected to
270 * openHAB" on your TV screen.
272 * @return true: successful, false: a non-critical error occured, caller handles
274 * @throws MagentaTVException
276 public boolean verifyPairing() throws MagentaTVException {
277 logger.debug("{}: Verify pairing (id={}, code={}", thingId, config.getTerminalID(),
278 config.getVerificationCode());
279 String soapBody = MessageFormat.format(PAIRCHECK_SOAP_BODY, config.getTerminalID(),
280 config.getVerificationCode());
281 String soapXml = MessageFormat.format(SOAP_ENVELOPE, soapBody);
282 String response = http.httpPOST(buildHost(), buildReceiverUrl(PAIRCHECK_URI), soapXml, PAIRCHECK_SOAP_ACTION,
285 // Exception if request failed (response code != HTTP_OK)
286 if (!response.contains("<pairingResult>")) {
287 throw new MagentaTVException("Unexpected result for pairing verification: " + response);
290 String result = getXmlValue(response, "pairingResult");
291 if (!result.equals("0")) {
292 logger.debug("{}: Pairing failed or pairing no longer valid, result={}", thingId, result);
294 // let the caller decide how to proceed
298 if (!config.isMR400()) {
299 String enable4K = getXmlValue(response, "Enable4K");
300 String enableSAT = getXmlValue(response, "EnableSAT");
301 logger.debug("{}: Features: Enable4K:{}, EnableSAT:{}", thingId, enable4K, enableSAT);
308 * @return true if pairing is completed (verification code was generated)
310 public boolean isPaired() {
311 // pairing was completed successful if we have the verification code
312 return !config.getVerificationCode().isEmpty();
316 * Reset pairing information (e.g. when verification failed)
318 public void resetPairing() {
319 // pairing no longer valid
320 config.setPairingCode("");
321 config.setVerificationCode("");
325 * Send key code to the MR (via SOAP request). A key code could be send by it's
326 * code (0x.... notation) or with a symbolic namne, which will first be mapped
329 * XML format for Send Key
331 * <s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"
332 * s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> <s:Body>\n
334 * xmlns:u=\"urn:schemas-upnp-org:service:X-CTC_RemoteControl:1\">\n
335 * <InstanceID>0</InstanceID>\n
336 * <KeyCode>keyCode=$keyCode^$pairingDeviceID:$verificationCode^userID:$userID</KeyCode>\n
337 * </u:X_CTC_RemoteKey>\n </s:Body></s:Envelope>
340 * @return true: successful, false: failed, e.g. unkown key code
341 * @throws MagentaTVException
343 public boolean sendKey(String keyName) throws MagentaTVException {
344 String keyCode = getKeyCode(keyName);
345 logger.debug("{}: Send Key {} (keyCode={}, tid={})", thingId, keyName, keyCode, config.getTerminalID());
346 if (keyCode.length() <= "0x".length()) {
347 logger.debug("{}: Key {} is unkown!", thingId, keyCode);
351 String soapBody = MessageFormat.format(SENDKEY_SOAP_BODY, keyCode, config.getTerminalID(),
352 config.getVerificationCode(), config.getUserId());
353 String soapXml = MessageFormat.format(SOAP_ENVELOPE, soapBody);
354 logger.debug("{}: send keyCode={} to {}:{}", thingId, keyCode, config.getIpAddress(), config.getPort());
355 logger.trace("{}: sendKey terminalid={}, pairingCode={}, verificationCode={}, userId={}", thingId,
356 config.getTerminalID(), config.getPairingCode(), config.getVerificationCode(), config.getUserId());
357 http.httpPOST(buildHost(), buildReceiverUrl(SENDKEY_URI), soapXml, SENDKEY_SOAP_ACTION, CONNECTION_CLOSE);
358 // Exception if request failed (response code != HTTP_OK)
359 // pairingCode will be received by the Servlet, is calls onPairingResult()
364 * Select channel for TV
366 * @param channel new channel (a sequence of numbers, which will be send one by one)
367 * @return true:ok, false: failed
369 public boolean selectChannel(String channel) throws MagentaTVException {
370 logger.debug("{}: Select channel {}", thingId, channel);
371 for (int i = 0; i < channel.length(); i++) {
372 if (!sendKey("" + channel.charAt(i))) {
377 } catch (InterruptedException e) {
384 * Get key code to send to receiver
386 * @param key Key for which to get the key code
389 private String getKeyCode(String key) {
390 if (key.contains("0x")) {
394 return KEY_MAP.getOrDefault(key, "");
398 * Map playStatus code to string for a list of codes see
399 * http://support.huawei.com/hedex/pages/DOC1100366313CEH0713H/01/DOC1100366313CEH0713H/01/resources/dsv_hdx_idp/DSV/en/en-us_topic_0094619231.html
401 * @param playStatus Integer code parsed form json (see EV_PLAYCHG_XXX)
402 * @return playStatus as String
404 public String getPlayStatus(int playStatus) {
405 switch (playStatus) {
406 case EV_PLAYCHG_PLAY:
408 case EV_PLAYCHG_STOP:
410 case EV_PLAYCHG_PAUSE:
412 case EV_PLAYCHG_TRICK:
414 case EV_PLAYCHG_MC_PLAY:
415 return "playing (MC)";
416 case EV_PLAYCHG_UC_PLAY:
417 return "playing (UC)";
418 case EV_PLAYCHG_BUFFERING:
421 return Integer.toString(playStatus);
426 * Map runningStatus code to string for a list of codes see
427 * http://support.huawei.com/hedex/pages/DOC1100366313CEH0713H/01/DOC1100366313CEH0713H/01/resources/dsv_hdx_idp/DSV/en/en-us_topic_0094619523.html
429 * @param runStatus Integer code parsed form json (see EV_EITCHG_RUNNING_XXX)
430 * @return runningStatus as String
432 public String getRunStatus(int runStatus) {
434 case EV_EITCHG_RUNNING_NOT_RUNNING:
436 case EV_EITCHG_RUNNING_STARTING:
438 case EV_EITCHG_RUNNING_PAUSING:
440 case EV_EITCHG_RUNNING_RUNNING:
443 return Integer.toString(runStatus);
448 * builds url from the discovered IP address/port and the requested uri
450 * @param uri requested URI
451 * @return the complete URL
453 public String buildReceiverUrl(String uri) {
454 return MessageFormat.format("http://{0}:{1}{2}", config.getIpAddress(), config.getPort(), uri);
460 * @return formatted string (<ip_address>:<port>)
462 private String buildHost() {
463 return config.getIpAddress() + ":" + config.getPort();
467 * Given a string, return the MD5 hash of the String.
469 * @param unhashed The string contents to be hashed.
470 * @return MD5 Hashed value of the String. Null if there is a problem hashing
473 public static String computeMD5(String unhashed) {
475 byte[] bytesOfMessage = unhashed.getBytes(UTF_8);
477 MessageDigest md5 = MessageDigest.getInstance(HASH_ALGORITHM_MD5);
478 byte[] hash = md5.digest(bytesOfMessage);
479 StringBuilder sb = new StringBuilder(2 * hash.length);
480 for (byte b : hash) {
481 sb.append(String.format("%02x", b & 0xff));
484 return sb.toString();
485 } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
491 * Helper to parse a Xml tag value from string without using a complex XML class
493 * @param xml Input string in the format <tag>value</tag>
494 * @param tagName The tag to find
495 * @return Tag value (between <tag> and </tag>)
497 public static String getXmlValue(String xml, String tagName) {
498 String open = "<" + tagName + ">";
499 String close = "</" + tagName + ">";
500 if (xml.contains(open) && xml.contains(close)) {
501 return substringBetween(xml, open, close);
507 * Initialize key map (key name -> key code)
509 * for a list of valid key codes see
510 * http://support.huawei.com/hedex/pages/DOC1100366313CEH0713H/01/DOC1100366313CEH0713H/01/resources/dsv_hdx_idp/DSV/en/en-us_topic_0094619112.html
513 KEY_MAP.put("POWER", "0x0100");
514 KEY_MAP.put("MENU", "0x0110");
515 KEY_MAP.put("EPG", "0x0111");
516 KEY_MAP.put("TVMENU", "0x0454");
517 KEY_MAP.put("VODMENU", "0x0455");
518 KEY_MAP.put("TVODMENU", "0x0456");
519 KEY_MAP.put("NVODMENU", "0x0458");
520 KEY_MAP.put("INFO", "0x010C");
521 KEY_MAP.put("TTEXT", "0x0560");
522 KEY_MAP.put("0", "0x0030");
523 KEY_MAP.put("1", "0x0031");
524 KEY_MAP.put("2", "0x0032");
525 KEY_MAP.put("3", "0x0033");
526 KEY_MAP.put("4", "0x0034");
527 KEY_MAP.put("5", "0x0035");
528 KEY_MAP.put("6", "0x0036");
529 KEY_MAP.put("7", "0x0037");
530 KEY_MAP.put("8", "0x0038");
531 KEY_MAP.put("9", "0x0039");
532 KEY_MAP.put("SPACE", "0x0020");
533 KEY_MAP.put("POUND", "0x0069");
534 KEY_MAP.put("STAR", "0x006A");
535 KEY_MAP.put("UP", "0x0026");
536 KEY_MAP.put("DOWN", "0x0028");
537 KEY_MAP.put("LEFT", "0x0025");
538 KEY_MAP.put("RIGHT", "0x0027");
539 KEY_MAP.put("PGUP", "0x0021");
540 KEY_MAP.put("PGDOWN", "0x0022");
541 KEY_MAP.put("DELETE", "0x0008");
542 KEY_MAP.put("ENTER", "0x000D");
543 KEY_MAP.put("SEARCH", "0x0451");
544 KEY_MAP.put("RED", "0x0113");
545 KEY_MAP.put("GREEN", "0x0114");
546 KEY_MAP.put("YELLOW", "0x0115");
547 KEY_MAP.put("BLUE", "0x0116");
548 KEY_MAP.put("OPTION", "0x0460");
549 KEY_MAP.put("OK", "0x000D");
550 KEY_MAP.put("BACK", "0x0008");
551 KEY_MAP.put("EXIT", "0x045D");
552 KEY_MAP.put("PORTAL", "0x0110");
553 KEY_MAP.put("VOLUP", "0x0103");
554 KEY_MAP.put("VOLDOWN", "0x0104");
555 KEY_MAP.put("INTER", "0x010D");
556 KEY_MAP.put("HELP", "0x011C");
557 KEY_MAP.put("SETTINGS", "0x011D");
558 KEY_MAP.put("MUTE", "0x0105");
559 KEY_MAP.put("CHUP", "0x0101");
560 KEY_MAP.put("CHDOWN", "0x0102");
561 KEY_MAP.put("REWIND", "0x0109");
562 KEY_MAP.put("PLAY", "0x0107");
563 KEY_MAP.put("PAUSE", "0x0107");
564 KEY_MAP.put("FORWARD", "0x0108");
565 KEY_MAP.put("TRACK", "0x0106");
566 KEY_MAP.put("LASTCH", "0x045E");
567 KEY_MAP.put("PREVCH", "0x010B");
568 KEY_MAP.put("NEXTCH", "0x0107");
569 KEY_MAP.put("RECORD", "0x0461");
570 KEY_MAP.put("STOP", "0x010E");
571 KEY_MAP.put("BEGIN", "0x010B");
572 KEY_MAP.put("END", "0x010A");
573 KEY_MAP.put("REPLAY", "0x045B");
574 KEY_MAP.put("SKIP", "0x045C");
575 KEY_MAP.put("SUBTITLE", "0x236");
576 KEY_MAP.put("RECORDINGS", "0x045F");
577 KEY_MAP.put("FAV", "0x0119");
578 KEY_MAP.put("SOURCE", "0x0083");
579 KEY_MAP.put("SWITCH", "0x0118");
580 KEY_MAP.put("IPTV", "0x0081");
581 KEY_MAP.put("PC", "0x0082");
582 KEY_MAP.put("PIP", "0x0084");
583 KEY_MAP.put("MULTIVIEW", "0x0562");
584 KEY_MAP.put("F1", "0x0070");
585 KEY_MAP.put("F2", "0x0071");
586 KEY_MAP.put("F3", "0x0072");
587 KEY_MAP.put("F4", "0x0073");
588 KEY_MAP.put("F5", "0x0074");
589 KEY_MAP.put("F6", "0x0075");
590 KEY_MAP.put("F7", "0x0076");
591 KEY_MAP.put("F8", "0x0077");
592 KEY_MAP.put("F9", "0x0078");
593 KEY_MAP.put("F10", "0x0079");
594 KEY_MAP.put("F11", "0x007A");
595 KEY_MAP.put("F12", "0x007B");
596 KEY_MAP.put("F13", "0x007C");
597 KEY_MAP.put("F14", "0x007D");
598 KEY_MAP.put("F15", "0x007E");
599 KEY_MAP.put("F16", "0x007F");
601 KEY_MAP.put("PVR", "0x0461");
602 KEY_MAP.put("RADIO", "0x0462");
604 // Those key codes are missing and not included in the spec
605 // KEY_MAP.put("TV", "0x");
606 // KEY_MAP.put("RADIO", "0x");
607 // KEY_MAP.put("MOVIES", "0x");