]> git.basschouten.com Git - openhab-addons.git/blob
3d9a9f671690879343d6bba40cfe63326828d4b8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.magentatv.internal.handler;
14
15 import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.*;
16 import static org.openhab.binding.magentatv.internal.MagentaTVUtil.*;
17
18 import java.text.DateFormat;
19 import java.text.MessageFormat;
20 import java.text.ParseException;
21 import java.text.SimpleDateFormat;
22 import java.time.Instant;
23 import java.time.ZoneId;
24 import java.time.ZonedDateTime;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.TimeZone;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
31
32 import javax.measure.Unit;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.eclipse.jetty.client.HttpClient;
37 import org.openhab.binding.magentatv.internal.MagentaTVDeviceManager;
38 import org.openhab.binding.magentatv.internal.MagentaTVException;
39 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRPayEvent;
40 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRPayEventInstanceCreator;
41 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRProgramInfoEvent;
42 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRProgramInfoEventInstanceCreator;
43 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRProgramStatus;
44 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRProgramStatusInstanceCreator;
45 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRShortProgramInfo;
46 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.MRShortProgramInfoInstanceCreator;
47 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.OAuthAuthenticateResponse;
48 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.OAuthTokenResponse;
49 import org.openhab.binding.magentatv.internal.MagentaTVGsonDTO.OauthCredentials;
50 import org.openhab.binding.magentatv.internal.config.MagentaTVDynamicConfig;
51 import org.openhab.binding.magentatv.internal.config.MagentaTVThingConfiguration;
52 import org.openhab.binding.magentatv.internal.network.MagentaTVNetwork;
53 import org.openhab.core.config.core.Configuration;
54 import org.openhab.core.library.types.DateTimeType;
55 import org.openhab.core.library.types.DecimalType;
56 import org.openhab.core.library.types.NextPreviousType;
57 import org.openhab.core.library.types.OnOffType;
58 import org.openhab.core.library.types.PlayPauseType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.library.types.RewindFastforwardType;
61 import org.openhab.core.library.types.StringType;
62 import org.openhab.core.library.unit.Units;
63 import org.openhab.core.thing.ChannelUID;
64 import org.openhab.core.thing.Thing;
65 import org.openhab.core.thing.ThingStatus;
66 import org.openhab.core.thing.ThingStatusDetail;
67 import org.openhab.core.thing.binding.BaseThingHandler;
68 import org.openhab.core.types.Command;
69 import org.openhab.core.types.RefreshType;
70 import org.openhab.core.types.State;
71 import org.openhab.core.types.UnDefType;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 import com.google.gson.Gson;
76 import com.google.gson.GsonBuilder;
77
78 /**
79  * The {@link MagentaTVHandler} is responsible for handling commands, which are
80  * sent to one of the channels.
81  *
82  * @author Markus Michels - Initial contribution
83  */
84 @NonNullByDefault
85 public class MagentaTVHandler extends BaseThingHandler implements MagentaTVListener {
86     private final Logger logger = LoggerFactory.getLogger(MagentaTVHandler.class);
87
88     protected MagentaTVDynamicConfig config = new MagentaTVDynamicConfig();
89     private final Gson gson;
90     protected final MagentaTVNetwork network;
91     protected final MagentaTVDeviceManager manager;
92     private final HttpClient httpClient;
93     protected MagentaTVControl control = new MagentaTVControl();
94
95     private String thingId = "";
96     private volatile int idRefresh = 0;
97     private @Nullable ScheduledFuture<?> initializeJob;
98     private @Nullable ScheduledFuture<?> pairingWatchdogJob;
99     private @Nullable ScheduledFuture<?> renewEventJob;
100
101     /**
102      * Constructor, save bindingConfig (services as default for thingConfig)
103      *
104      * @param thing
105      * @param bindingConfig
106      */
107     public MagentaTVHandler(MagentaTVDeviceManager manager, Thing thing, MagentaTVNetwork network,
108             HttpClient httpClient) {
109         super(thing);
110         this.manager = manager;
111         this.network = network;
112         this.httpClient = httpClient;
113         gson = new GsonBuilder().registerTypeAdapter(OauthCredentials.class, new MRProgramInfoEventInstanceCreator())
114                 .registerTypeAdapter(OAuthTokenResponse.class, new MRProgramStatusInstanceCreator())
115                 .registerTypeAdapter(OAuthAuthenticateResponse.class, new MRShortProgramInfoInstanceCreator())
116                 .registerTypeAdapter(OAuthAuthenticateResponse.class, new MRPayEventInstanceCreator()).create();
117     }
118
119     /**
120      * Thing initialization:
121      * - initialize thing status from UPnP discovery, thing config, local network settings
122      * - initiate OAuth if userId is not configured and credentials are available
123      * - wait for NotifyServlet to initialize (solves timing issues on fast startup)
124      */
125     @Override
126     public void initialize() {
127         // The framework requires you to return from this method quickly. For that the initialization itself is executed
128         // asynchronously
129         String label = getThing().getLabel();
130         thingId = label != null ? label : getThing().getUID().toString();
131         resetEventChannels();
132         updateStatus(ThingStatus.UNKNOWN);
133         config = new MagentaTVDynamicConfig(getConfigAs(MagentaTVThingConfiguration.class));
134         try {
135             initializeJob = scheduler.schedule(this::initializeThing, 5, TimeUnit.SECONDS);
136         } catch (RuntimeException e) {
137             logger.warn("Unable to schedule thing initialization", e);
138         }
139     }
140
141     private void initializeThing() {
142         String errorMessage = "";
143         try {
144             if (config.getUDN().isEmpty()) {
145                 // get UDN from device name
146                 String uid = this.getThing().getUID().getAsString();
147                 config.setUDN(substringAfterLast(uid, ":"));
148             }
149             if (config.getMacAddress().isEmpty()) {
150                 // get MAC address from UDN (last 12 digits)
151                 String macAddress = substringAfterLast(config.getUDN(), "_");
152                 if (macAddress.isEmpty()) {
153                     macAddress = substringAfterLast(config.getUDN(), "-");
154                 }
155                 config.setMacAddress(macAddress);
156             }
157             control = new MagentaTVControl(config, network, httpClient);
158             config.updateNetwork(control.getConfig()); // get network parameters from control
159
160             // Check for emoty credentials (e.g. missing in .things file)
161             String account = config.getAccountName();
162             if (config.getUserId().isEmpty()) {
163                 if (account.isEmpty()) {
164                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
165                             "Credentials missing or invalid! Fill credentials into thing configuration or generate UID on the openHAB console - see README");
166                     return;
167                 }
168
169                 getUserId();
170             }
171
172             connectReceiver(); // throws MagentaTVException on error
173
174             // setup background device check
175             renewEventJob = scheduler.scheduleWithFixedDelay(this::renewEventSubscription, 2, 5, TimeUnit.MINUTES);
176
177             // change to ThingStatus.ONLINE will be done when the pairing result is received
178             // (see onPairingResult())
179         } catch (MagentaTVException e) {
180             errorMessage = e.toString();
181         } catch (RuntimeException e) {
182             logger.warn("{}: Exception on initialization", thingId, e);
183         } finally {
184             if (!errorMessage.isEmpty()) {
185                 logger.debug("{}: {}", thingId, errorMessage);
186                 setOnlineStatus(ThingStatus.OFFLINE, errorMessage);
187             }
188         }
189     }
190
191     /**
192      * This routine is called every time the Thing configuration has been changed
193      */
194     @Override
195     public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
196         logger.debug("{}: Thing config updated, re-initialize", thingId);
197         cancelAllJobs();
198         if (configurationParameters.containsKey(PROPERTY_ACCT_NAME)) {
199             @Nullable
200             String newAccount = (String) configurationParameters.get(PROPERTY_ACCT_NAME);
201             if ((newAccount != null) && !newAccount.isEmpty()) {
202                 // new account info, need to renew userId
203                 config.setUserId("");
204             }
205         }
206
207         super.handleConfigurationUpdate(configurationParameters);
208     }
209
210     /**
211      * Handle channel commands
212      *
213      * @param channelUID - the channel, which received the command
214      * @param command - the actual command (could be instance of StringType,
215      *            DecimalType or OnOffType)
216      */
217     @Override
218     public void handleCommand(ChannelUID channelUID, Command command) {
219         if (command == RefreshType.REFRESH) {
220             // currently no channels to be refreshed
221             return;
222         }
223
224         try {
225             if (!isOnline() || command.toString().equalsIgnoreCase("PAIR")) {
226                 logger.debug("{}: Receiver {} is offline, try to (re-)connect", thingId, deviceName());
227                 connectReceiver(); // reconnect to MR, throws an exception if this fails
228             }
229
230             logger.debug("{}: Channel command for device {}: {} for channel {}", thingId, config.getFriendlyName(),
231                     command, channelUID.getId());
232             switch (channelUID.getId()) {
233                 case CHANNEL_POWER: // toggle power
234                     logger.debug("{}: Toggle power, new state={}", thingId, command);
235                     control.sendKey("POWER");
236                     break;
237                 case CHANNEL_PLAYER:
238                     logger.debug("{}: Player command: {}", thingId, command);
239                     if (command instanceof OnOffType) {
240                         control.sendKey("POWER");
241                     } else if (command instanceof PlayPauseType) {
242                         if (command == PlayPauseType.PLAY) {
243                             control.sendKey("PLAY");
244                         } else if (command == PlayPauseType.PAUSE) {
245                             control.sendKey("PAUSE");
246                         }
247                     } else if (command instanceof NextPreviousType) {
248                         if (command == NextPreviousType.NEXT) {
249                             control.sendKey("NEXTCH");
250                         } else if (command == NextPreviousType.PREVIOUS) {
251                             control.sendKey("PREVCH");
252                         }
253                     } else if (command instanceof RewindFastforwardType) {
254                         if (command == RewindFastforwardType.FASTFORWARD) {
255                             control.sendKey("FORWARD");
256                         } else if (command == RewindFastforwardType.REWIND) {
257                             control.sendKey("REWIND");
258                         }
259                     } else {
260                         logger.debug("{}: Unknown media command: {}", thingId, command);
261                     }
262                     break;
263                 case CHANNEL_CHANNEL:
264                     String chan = command.toString();
265                     control.selectChannel(chan);
266                     break;
267                 case CHANNEL_MUTE:
268                     if (command == OnOffType.ON) {
269                         control.sendKey("MUTE");
270                     } else {
271                         control.sendKey("VOLUP");
272                     }
273                     break;
274                 case CHANNEL_KEY:
275                     if (command.toString().equalsIgnoreCase("PAIR")) { // special key to re-pair receiver (already done
276                                                                        // above)
277                         logger.debug("{}: PAIRing key received, reconnect receiver {}", thingId, deviceName());
278                     } else {
279                         control.sendKey(command.toString());
280                         mapKeyToMediateState(command.toString());
281                     }
282                     break;
283                 default:
284                     logger.debug("{}: Command {} for unknown channel {}", thingId, command, channelUID.getAsString());
285             }
286         } catch (MagentaTVException e) {
287             String errorMessage = MessageFormat.format("Channel operation failed (command={0}, value={1}): {2}",
288                     command, channelUID.getId(), e.getMessage());
289             logger.debug("{}: {}", thingId, errorMessage);
290             setOnlineStatus(ThingStatus.OFFLINE, errorMessage);
291         }
292     }
293
294     private void mapKeyToMediateState(String key) {
295         State state = null;
296         switch (key.toUpperCase()) {
297             case "PLAY":
298                 state = PlayPauseType.PLAY;
299                 break;
300             case "PAUSE":
301                 state = PlayPauseType.PAUSE;
302                 break;
303             case "FORWARD":
304                 state = RewindFastforwardType.FASTFORWARD;
305                 break;
306             case "REWIND":
307                 updateState(CHANNEL_PLAYER, RewindFastforwardType.REWIND);
308                 break;
309         }
310         if (state != null) {
311             logger.debug("{}: Setting Player state to {}", thingId, state);
312             updateState(CHANNEL_PLAYER, state);
313         }
314     }
315
316     /**
317      * Connect to the receiver
318      *
319      * @throws MagentaTVException something failed
320      */
321     protected void connectReceiver() throws MagentaTVException {
322         if (control.checkDev()) {
323             updateThingProperties();
324             manager.registerDevice(config.getUDN(), config.getTerminalID(), config.getIpAddress(), this);
325             control.subscribeEventChannel();
326             control.sendPairingRequest();
327
328             // check for pairing timeout
329             final int iRefresh = ++idRefresh;
330             pairingWatchdogJob = scheduler.schedule(() -> {
331                 if (iRefresh == idRefresh) { // Make a best effort to not run multiple deferred refresh
332                     if (config.getVerificationCode().isEmpty()) {
333                         setOnlineStatus(ThingStatus.OFFLINE, "Timeout on pairing request!");
334                     }
335                 }
336             }, 15, TimeUnit.SECONDS);
337         }
338     }
339
340     /**
341      * If userId is empty and credentials are given the Telekom OAuth service is
342      * used to query the userId
343      *
344      * @throws MagentaTVException
345      */
346     private void getUserId() throws MagentaTVException {
347         String userId = config.getUserId();
348         if (userId.isEmpty()) {
349             // run OAuth authentication, this finally provides the userId
350             logger.debug("{}: Login with account {}", thingId, config.getAccountName());
351             userId = control.getUserId(config.getAccountName(), config.getAccountPassword());
352
353             // Update thing configuration (persistent) - remove credentials, add userId
354             Configuration configuration = this.getConfig();
355             configuration.remove(PROPERTY_ACCT_NAME);
356             configuration.remove(PROPERTY_ACCT_PWD);
357             configuration.remove(PROPERTY_USERID);
358             configuration.put(PROPERTY_ACCT_NAME, "");
359             configuration.put(PROPERTY_ACCT_PWD, "");
360             configuration.put(PROPERTY_USERID, userId);
361             this.updateConfiguration(configuration);
362             config.setAccountName("");
363             config.setAccountPassword("");
364         } else {
365             logger.debug("{}: Skip OAuth, use existing userId {}", thingId, config.getUserId());
366         }
367         if (!userId.isEmpty()) {
368             config.setUserId(userId);
369         } else {
370             logger.warn("{}: Unable to obtain userId from OAuth", thingId);
371         }
372     }
373
374     /**
375      * Update thing status
376      *
377      * @param mode new thing status
378      * @return ON = power on, OFF=power off
379      */
380     public void setOnlineStatus(ThingStatus newStatus, String errorMessage) {
381         ThingStatus status = this.getThing().getStatus();
382         if (status != newStatus) {
383             if (newStatus == ThingStatus.ONLINE) {
384                 updateStatus(newStatus);
385                 updateState(CHANNEL_POWER, OnOffType.ON);
386             } else {
387                 if (!errorMessage.isEmpty()) {
388                     logger.debug("{}: Communication Error - {}, switch Thing offline", thingId, errorMessage);
389                     updateStatus(newStatus, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage);
390                 } else {
391                     updateStatus(newStatus);
392                 }
393                 updateState(CHANNEL_POWER, OnOffType.OFF);
394             }
395         }
396     }
397
398     /**
399      * A wakeup of the MR was detected (e.g. UPnP received)
400      *
401      * @throws MagentaTVException
402      */
403     @Override
404     public void onWakeup(Map<String, String> discoveredProperties) throws MagentaTVException {
405         if ((this.getThing().getStatus() == ThingStatus.OFFLINE) || config.getVerificationCode().isEmpty()) {
406             // Device sent a UPnP discovery information, trigger to reconnect
407             connectReceiver();
408         } else {
409             logger.debug("{}: Refesh device status for {} (UDN={}", thingId, deviceName(), config.getUDN());
410             setOnlineStatus(ThingStatus.ONLINE, "");
411         }
412     }
413
414     /**
415      * The pairing result has been received. The pairing code will be used to generate the verification code and
416      * complete pairing with the MR. Finally if pairing was completed successful the thing status will change to ONLINE
417      *
418      * @param pairingCode pairing code received from MR (NOTIFY event data)
419      * @throws MagentaTVException
420      */
421     @Override
422     public void onPairingResult(String pairingCode) throws MagentaTVException {
423         if (control.isInitialized()) {
424             if (control.generateVerificationCode(pairingCode)) {
425                 config.setPairingCode(pairingCode);
426                 logger.debug(
427                         "{}: Pairing code received (UDN {}, terminalID {}, pairingCode={}, verificationCode={}, userId={})",
428                         thingId, config.getUDN(), config.getTerminalID(), config.getPairingCode(),
429                         config.getVerificationCode(), config.getUserId());
430
431                 // verify pairing completes the pairing process
432                 if (control.verifyPairing()) {
433                     logger.debug("{}: Pairing completed for device {} ({}), Thing now ONLINE", thingId,
434                             config.getFriendlyName(), config.getTerminalID());
435                     setOnlineStatus(ThingStatus.ONLINE, "");
436                     cancelPairingCheck(); // stop timeout check
437                 }
438             }
439             updateThingProperties(); // persist pairing and verification code
440         } else {
441             logger.debug("{}: control not yet initialized!", thingId);
442         }
443     }
444
445     @Override
446     public void onMREvent(String jsonInput) {
447         logger.trace("{}: Process MR event for device {}, json={}", thingId, deviceName(), jsonInput);
448         boolean flUpdatePower = false;
449         String jsonEvent = fixEventJson(jsonInput);
450         if (jsonEvent.contains(MR_EVENT_EIT_CHANGE)) {
451             logger.debug("{}: EVENT_EIT_CHANGE event received.", thingId);
452
453             MRProgramInfoEvent pinfo = gson.fromJson(jsonEvent, MRProgramInfoEvent.class);
454             if (!pinfo.channelNum.isEmpty()) {
455                 logger.debug("{}: EVENT_EIT_CHANGE for channel {}/{}", thingId, pinfo.channelNum, pinfo.channelCode);
456                 updateState(CHANNEL_CHANNEL, new DecimalType(pinfo.channelNum));
457                 updateState(CHANNEL_CHANNEL_CODE, new DecimalType(pinfo.channelCode));
458             }
459             if (pinfo.programInfo != null) {
460                 int i = 0;
461                 for (MRProgramStatus ps : pinfo.programInfo) {
462                     if ((ps.startTime == null) || ps.startTime.isEmpty()) {
463                         logger.debug("{}: EVENT_EIT_CHANGE: empty event data = {}", thingId, jsonEvent);
464                         continue; // empty program_info
465                     }
466                     updateState(CHANNEL_RUN_STATUS, new StringType(control.getRunStatus(ps.runningStatus)));
467
468                     if (ps.shortEvent != null) {
469                         for (MRShortProgramInfo se : ps.shortEvent) {
470                             if ((ps.startTime == null) || ps.startTime.isEmpty()) {
471                                 logger.debug("{}: EVENT_EIT_CHANGE: empty program info", thingId);
472                                 continue;
473                             }
474                             // Convert UTC to local time
475                             // 2018/11/04 21:45:00 -> "2018-11-04T10:15:30.00Z"
476                             String tsLocal = ps.startTime.replace('/', '-').replace(" ", "T") + "Z";
477                             Instant timestamp = Instant.parse(tsLocal);
478                             ZonedDateTime localTime = timestamp.atZone(ZoneId.of("Europe/Berlin"));
479                             tsLocal = substringBeforeLast(localTime.toString(), "[");
480                             tsLocal = substringBefore(tsLocal.replace('-', '/').replace('T', ' '), "+");
481
482                             logger.debug("{}: Info for channel {} / {} - {} {}.{}, start time={}, duration={}", thingId,
483                                     pinfo.channelNum, pinfo.channelCode, control.getRunStatus(ps.runningStatus),
484                                     se.eventName, se.textChar, tsLocal, ps.duration);
485                             if (ps.runningStatus != EV_EITCHG_RUNNING_NOT_RUNNING) {
486                                 updateState(CHANNEL_PROG_TITLE, new StringType(se.eventName));
487                                 updateState(CHANNEL_PROG_TEXT, new StringType(se.textChar));
488                                 updateState(CHANNEL_PROG_START, new DateTimeType(localTime));
489
490                                 try {
491                                     DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
492                                     dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
493                                     Date date = dateFormat.parse(ps.duration);
494                                     long minutes = date.getTime() / 1000L / 60l;
495                                     updateState(CHANNEL_PROG_DURATION, toQuantityType(minutes, Units.MINUTE));
496                                 } catch (ParseException e) {
497                                     logger.debug("{}: Unable to parse programDuration: {}", thingId, ps.duration);
498                                 }
499
500                                 if (i++ == 0) {
501                                     flUpdatePower = true;
502                                 }
503                             }
504                         }
505                     }
506                 }
507             }
508         } else if (jsonEvent.contains("new_play_mode")) {
509             MRPayEvent event = gson.fromJson(jsonEvent, MRPayEvent.class);
510             if (event.duration == null) {
511                 event.duration = -1;
512             }
513             if (event.playPostion == null) {
514                 event.playPostion = -1;
515             }
516             logger.debug("{}: STB event playContent: playMode={}, duration={}, playPosition={}", thingId,
517                     control.getPlayStatus(event.newPlayMode), event.duration, event.playPostion);
518
519             // If we get a playConfig event there MR must be online. However it also sends a
520             // plyMode stop before powering off the device, so we filter this.
521             if ((event.newPlayMode != EV_PLAYCHG_STOP) && this.isInitialized()) {
522                 flUpdatePower = true;
523             }
524             if (event.newPlayMode != -1) {
525                 String playMode = control.getPlayStatus(event.newPlayMode);
526                 updateState(CHANNEL_PLAY_MODE, new StringType(playMode));
527                 mapPlayModeToMediaControl(playMode);
528             }
529             if (event.duration > 0) {
530                 updateState(CHANNEL_PROG_DURATION, new StringType(event.duration.toString()));
531             }
532             if (event.playPostion != -1) {
533                 updateState(CHANNEL_PROG_POS, toQuantityType(event.playPostion / 6, Units.MINUTE));
534             }
535         } else {
536             logger.debug("{}: Unknown MR event, JSON={}", thingId, jsonEvent);
537         }
538         if (flUpdatePower) {
539             // We received a non-stopped event -> MR must be on
540             updateState(CHANNEL_POWER, OnOffType.ON);
541         }
542     }
543
544     private void mapPlayModeToMediaControl(String playMode) {
545         switch (playMode) {
546             case "playing":
547             case "playing (MC)":
548             case "playing (UC)":
549             case "buffering":
550                 logger.debug("{}: Setting Player state to PLAY", thingId);
551                 updateState(CHANNEL_PLAYER, PlayPauseType.PLAY);
552                 break;
553             case "paused":
554             case "stopped":
555                 logger.debug("{}: Setting Player state to PAUSE", thingId);
556                 updateState(CHANNEL_PLAYER, PlayPauseType.PAUSE);
557                 break;
558         }
559     }
560
561     /**
562      * When the MR powers off it send a UPnP message, which is catched by the binding.
563      */
564     @Override
565     public void onPowerOff() throws MagentaTVException {
566         logger.debug("{}: Power-Off received for device {}", thingId, deviceName());
567         // MR was powered off -> update power status, reset items
568         resetEventChannels();
569     }
570
571     private void resetEventChannels() {
572         updateState(CHANNEL_POWER, OnOffType.OFF);
573         updateState(CHANNEL_PROG_TITLE, StringType.EMPTY);
574         updateState(CHANNEL_PROG_TEXT, StringType.EMPTY);
575         updateState(CHANNEL_PROG_START, StringType.EMPTY);
576         updateState(CHANNEL_PROG_DURATION, DecimalType.ZERO);
577         updateState(CHANNEL_PROG_POS, DecimalType.ZERO);
578         updateState(CHANNEL_CHANNEL, DecimalType.ZERO);
579         updateState(CHANNEL_CHANNEL_CODE, DecimalType.ZERO);
580     }
581
582     private String fixEventJson(String jsonEvent) {
583         // MR401: channel_num is a string -> ok
584         // MR201: channel_num is an int -> fix JSON formatting to String
585         if (jsonEvent.contains(MR_EVENT_CHAN_TAG) && !jsonEvent.contains(MR_EVENT_CHAN_TAG + "\"")) {
586             // hack: reformat the JSON string to make it compatible with the GSON parsing
587             logger.trace("{}: malformed JSON->fix channel_num", thingId);
588             String start = substringBefore(jsonEvent, MR_EVENT_CHAN_TAG); // up to "channel_num":
589             String end = substringAfter(jsonEvent, MR_EVENT_CHAN_TAG); // behind "channel_num":
590             String chan = substringBetween(jsonEvent, MR_EVENT_CHAN_TAG, ",").trim();
591             return start + "\"channel_num\":" + "\"" + chan + "\"" + end;
592         }
593         return jsonEvent;
594     }
595
596     private boolean isOnline() {
597         return this.getThing().getStatus() == ThingStatus.ONLINE;
598     }
599
600     /**
601      * Renew the event subscription. The periodic refresh is required, otherwise the receive will stop sending events.
602      * Reconnect if nessesary.
603      */
604     private void renewEventSubscription() {
605         if (!control.isInitialized()) {
606             return;
607         }
608         logger.debug("{}: Check receiver status, current state  {}/{}", thingId,
609                 this.getThing().getStatusInfo().getStatus(), this.getThing().getStatusInfo().getStatusDetail());
610
611         try {
612             // when pairing is completed re-new event channel subscription
613             if ((this.getThing().getStatus() != ThingStatus.OFFLINE) && !config.getVerificationCode().isEmpty()) {
614                 logger.debug("{}: Renew MR event subscription for device {}", thingId, deviceName());
615                 control.subscribeEventChannel();
616             }
617         } catch (MagentaTVException e) {
618             logger.warn("{}: Re-new event subscription failed: {}", deviceName(), e.toString());
619         }
620
621         // another try: if the above SUBSCRIBE fails, try a re-connect immediatly
622         try {
623             if ((this.getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.COMMUNICATION_ERROR)
624                     && !config.getUserId().isEmpty()) {
625                 // if we have no userId the OAuth is not completed or pairing process got stuck
626                 logger.debug("{}: Reconnect media receiver", deviceName());
627                 connectReceiver(); // throws MagentaTVException on error
628             }
629         } catch (MagentaTVException | RuntimeException e) {
630             logger.debug("{}: Re-connect to receiver failed: {}", deviceName(), e.toString());
631         }
632     }
633
634     public void updateThingProperties() {
635         Map<String, String> properties = new HashMap<String, String>();
636         properties.put(PROPERTY_FRIENDLYNAME, config.getFriendlyName());
637         properties.put(PROPERTY_MODEL_NUMBER, config.getModel());
638         properties.put(PROPERTY_DESC_URL, config.getDescriptionUrl());
639         properties.put(PROPERTY_PAIRINGCODE, config.getPairingCode());
640         properties.put(PROPERTY_VERIFICATIONCODE, config.getVerificationCode());
641         properties.put(PROPERTY_LOCAL_IP, config.getLocalIP());
642         properties.put(PROPERTY_TERMINALID, config.getLocalIP());
643         properties.put(PROPERTY_LOCAL_MAC, config.getLocalMAC());
644         properties.put(PROPERTY_WAKEONLAN, config.getWakeOnLAN());
645         updateProperties(properties);
646     }
647
648     public static State toQuantityType(@Nullable Number value, Unit<?> unit) {
649         return value == null ? UnDefType.NULL : new QuantityType<>(value, unit);
650     }
651
652     private String deviceName() {
653         return config.getFriendlyName() + "(" + config.getTerminalID() + ")";
654     }
655
656     private void cancelJob(@Nullable ScheduledFuture<?> job) {
657         if ((job != null) && !job.isCancelled()) {
658             job.cancel(true);
659         }
660     }
661
662     protected void cancelInitialize() {
663         cancelJob(initializeJob);
664     }
665
666     protected void cancelPairingCheck() {
667         cancelJob(pairingWatchdogJob);
668     }
669
670     protected void cancelRenewEvent() {
671         cancelJob(renewEventJob);
672     }
673
674     private void cancelAllJobs() {
675         cancelInitialize();
676         cancelPairingCheck();
677         cancelRenewEvent();
678     }
679
680     @Override
681     public void dispose() {
682         cancelAllJobs();
683         manager.removeDevice(config.getTerminalID());
684         super.dispose();
685     }
686 }