2 * Copyright (c) 2010-2024 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.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;
28 import java.util.TimeZone;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
32 import javax.measure.Unit;
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;
75 import com.google.gson.Gson;
76 import com.google.gson.GsonBuilder;
79 * The {@link MagentaTVHandler} is responsible for handling commands, which are
80 * sent to one of the channels.
82 * @author Markus Michels - Initial contribution
85 public class MagentaTVHandler extends BaseThingHandler implements MagentaTVListener {
86 private final Logger logger = LoggerFactory.getLogger(MagentaTVHandler.class);
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();
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;
102 * Constructor, save bindingConfig (services as default for thingConfig)
109 public MagentaTVHandler(MagentaTVDeviceManager manager, Thing thing, MagentaTVNetwork network,
110 HttpClient httpClient) {
112 this.manager = manager;
113 this.network = network;
114 this.httpClient = httpClient;
115 gson = new GsonBuilder().registerTypeAdapter(OauthCredentials.class, new MRProgramInfoEventInstanceCreator())
116 .registerTypeAdapter(OAuthTokenResponse.class, new MRProgramStatusInstanceCreator())
117 .registerTypeAdapter(OAuthAuthenticateResponse.class, new MRShortProgramInfoInstanceCreator())
118 .registerTypeAdapter(OAuthAuthenticateResponse.class, new MRPayEventInstanceCreator()).create();
122 * Thing initialization:
123 * - initialize thing status from UPnP discovery, thing config, local network settings
124 * - initiate OAuth if userId is not configured and credentials are available
125 * - wait for NotifyServlet to initialize (solves timing issues on fast startup)
128 public void initialize() {
129 // The framework requires you to return from this method quickly. For that the initialization itself is executed
131 String label = getThing().getLabel();
132 thingId = label != null ? label : getThing().getUID().toString();
133 resetEventChannels();
134 updateStatus(ThingStatus.UNKNOWN);
135 config = new MagentaTVDynamicConfig(getConfigAs(MagentaTVThingConfiguration.class));
137 initializeJob = scheduler.schedule(this::initializeThing, 5, TimeUnit.SECONDS);
138 } catch (RuntimeException e) {
139 logger.warn("Unable to schedule thing initialization", e);
143 private void initializeThing() {
144 String errorMessage = "";
146 config.setFriendlyName(getThing().getLabel().toString());
147 if (config.getUDN().isEmpty()) {
148 // get UDN from device name
149 String uid = this.getThing().getUID().getAsString();
150 config.setUDN(substringAfterLast(uid, ":"));
152 if (config.getMacAddress().isEmpty()) {
153 // get MAC address from UDN (last 12 digits)
154 String macAddress = substringAfterLast(config.getUDN(), "_");
155 if (macAddress.isEmpty()) {
156 macAddress = substringAfterLast(config.getUDN(), "-");
158 config.setMacAddress(macAddress);
160 control = new MagentaTVControl(config, network, httpClient);
161 config.updateNetwork(control.getConfig()); // get network parameters from control
163 // Check for emoty credentials (e.g. missing in .things file)
164 String account = config.getAccountName();
165 if (config.getUserId().isEmpty()) {
166 if (account.isEmpty()) {
167 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
168 "Credentials missing or invalid! Fill credentials into thing configuration or generate UID on the openHAB console - see README");
175 connectReceiver(); // throws MagentaTVException on error
177 // setup background device check
178 renewEventJob = scheduler.scheduleWithFixedDelay(this::renewEventSubscription, 2, 5, TimeUnit.MINUTES);
180 // change to ThingStatus.ONLINE will be done when the pairing result is received
181 // (see onPairingResult())
182 } catch (MagentaTVException e) {
183 errorMessage = e.toString();
184 } catch (RuntimeException e) {
185 logger.warn("{}: Exception on initialization", thingId, e);
187 if (!errorMessage.isEmpty()) {
188 logger.debug("{}: {}", thingId, errorMessage);
189 setOnlineStatus(ThingStatus.OFFLINE, errorMessage);
195 * This routine is called every time the Thing configuration has been changed
198 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
199 logger.debug("{}: Thing config updated, re-initialize", thingId);
201 if (configurationParameters.containsKey(PROPERTY_ACCT_NAME)) {
203 String newAccount = (String) configurationParameters.get(PROPERTY_ACCT_NAME);
204 if ((newAccount != null) && !newAccount.isEmpty()) {
205 // new account info, need to renew userId
206 config.setUserId("");
210 super.handleConfigurationUpdate(configurationParameters);
214 * Handle channel commands
216 * @param channelUID - the channel, which received the command
217 * @param command - the actual command (could be instance of StringType,
218 * DecimalType or OnOffType)
221 public void handleCommand(ChannelUID channelUID, Command command) {
222 if (command == RefreshType.REFRESH) {
223 // currently no channels to be refreshed
228 if (!isOnline() || "PAIR".equalsIgnoreCase(command.toString())) {
229 logger.debug("{}: Receiver {} is offline, try to (re-)connect", thingId, deviceName());
230 connectReceiver(); // reconnect to MR, throws an exception if this fails
233 logger.debug("{}: Channel command for device {}: {} for channel {}", thingId, config.getFriendlyName(),
234 command, channelUID.getId());
235 switch (channelUID.getId()) {
236 case CHANNEL_POWER: // toggle power
237 logger.debug("{}: Toggle power, new state={}", thingId, command);
238 control.sendKey("POWER");
241 logger.debug("{}: Player command: {}", thingId, command);
242 if (command instanceof OnOffType) {
243 control.sendKey("POWER");
244 } else if (command instanceof PlayPauseType) {
245 if (command == PlayPauseType.PLAY) {
246 control.sendKey("PLAY");
247 } else if (command == PlayPauseType.PAUSE) {
248 control.sendKey("PAUSE");
250 } else if (command instanceof NextPreviousType) {
251 if (command == NextPreviousType.NEXT) {
252 control.sendKey("NEXTCH");
253 } else if (command == NextPreviousType.PREVIOUS) {
254 control.sendKey("PREVCH");
256 } else if (command instanceof RewindFastforwardType) {
257 if (command == RewindFastforwardType.FASTFORWARD) {
258 control.sendKey("FORWARD");
259 } else if (command == RewindFastforwardType.REWIND) {
260 control.sendKey("REWIND");
263 logger.debug("{}: Unknown media command: {}", thingId, command);
266 case CHANNEL_CHANNEL:
267 String chan = command.toString();
268 control.selectChannel(chan);
271 if (command == OnOffType.ON) {
272 control.sendKey("MUTE");
274 control.sendKey("VOLUP");
278 if ("PAIR".equalsIgnoreCase(command.toString())) { // special key to re-pair receiver (already done
280 logger.debug("{}: PAIRing key received, reconnect receiver {}", thingId, deviceName());
282 control.sendKey(command.toString());
283 mapKeyToMediateState(command.toString());
287 logger.debug("{}: Command {} for unknown channel {}", thingId, command, channelUID.getAsString());
289 } catch (MagentaTVException e) {
290 String errorMessage = MessageFormat.format("Channel operation failed (command={0}, value={1}): {2}",
291 command, channelUID.getId(), e.getMessage());
292 logger.debug("{}: {}", thingId, errorMessage);
293 setOnlineStatus(ThingStatus.OFFLINE, errorMessage);
297 private void mapKeyToMediateState(String key) {
299 switch (key.toUpperCase()) {
301 state = PlayPauseType.PLAY;
304 state = PlayPauseType.PAUSE;
307 state = RewindFastforwardType.FASTFORWARD;
310 updateState(CHANNEL_PLAYER, RewindFastforwardType.REWIND);
314 logger.debug("{}: Setting Player state to {}", thingId, state);
315 updateState(CHANNEL_PLAYER, state);
320 * Connect to the receiver
322 * @throws MagentaTVException something failed
324 protected void connectReceiver() throws MagentaTVException {
325 if (control.checkDev()) {
326 updateThingProperties();
327 control.setThingId(config.getFriendlyName());
328 manager.registerDevice(config.getUDN(), config.getTerminalID(), config.getIpAddress(), this);
329 control.subscribeEventChannel();
330 control.sendPairingRequest();
332 // check for pairing timeout
333 final int iRefresh = ++idRefresh;
334 pairingWatchdogJob = scheduler.schedule(() -> {
335 if (iRefresh == idRefresh) { // Make a best effort to not run multiple deferred refresh
336 if (config.getVerificationCode().isEmpty()) {
337 setOnlineStatus(ThingStatus.OFFLINE, "Timeout on pairing request!");
340 }, 15, TimeUnit.SECONDS);
345 * If userId is empty and credentials are given the Telekom OAuth service is
346 * used to query the userId
348 * @throws MagentaTVException
350 private void getUserId() throws MagentaTVException {
351 String userId = config.getUserId();
352 if (userId.isEmpty()) {
353 // run OAuth authentication, this finally provides the userId
354 logger.debug("{}: Login with account {}", thingId, config.getAccountName());
355 userId = control.getUserId(config.getAccountName(), config.getAccountPassword());
357 // Update thing configuration (persistent) - remove credentials, add userId
358 Configuration configuration = this.getConfig();
359 configuration.remove(PROPERTY_ACCT_NAME);
360 configuration.remove(PROPERTY_ACCT_PWD);
361 configuration.remove(PROPERTY_USERID);
362 configuration.put(PROPERTY_ACCT_NAME, "");
363 configuration.put(PROPERTY_ACCT_PWD, "");
364 configuration.put(PROPERTY_USERID, userId);
365 this.updateConfiguration(configuration);
366 config.setAccountName("");
367 config.setAccountPassword("");
369 logger.debug("{}: Skip OAuth, use existing userId {}", thingId, config.getUserId());
371 if (!userId.isEmpty()) {
372 config.setUserId(userId);
374 logger.warn("{}: Unable to obtain userId from OAuth", thingId);
379 * Update thing status
381 * @param newStatus new thing status
382 * @param errorMessage
384 public void setOnlineStatus(ThingStatus newStatus, String errorMessage) {
385 ThingStatus status = this.getThing().getStatus();
386 if (status != newStatus) {
387 if (newStatus == ThingStatus.ONLINE) {
388 updateStatus(newStatus);
389 updateState(CHANNEL_POWER, OnOffType.ON);
391 if (!errorMessage.isEmpty()) {
392 logger.debug("{}: Communication Error - {}, switch Thing offline", thingId, errorMessage);
393 updateStatus(newStatus, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage);
395 updateStatus(newStatus);
397 updateState(CHANNEL_POWER, OnOffType.OFF);
403 * A wakeup of the MR was detected (e.g. UPnP received)
405 * @throws MagentaTVException
408 public void onWakeup(Map<String, String> discoveredProperties) throws MagentaTVException {
409 if ((this.getThing().getStatus() == ThingStatus.OFFLINE) || config.getVerificationCode().isEmpty()) {
410 // Device sent a UPnP discovery information, trigger to reconnect
413 logger.debug("{}: Refesh device status for {} (UDN={}", thingId, deviceName(), config.getUDN());
414 setOnlineStatus(ThingStatus.ONLINE, "");
419 * The pairing result has been received. The pairing code will be used to generate the verification code and
420 * complete pairing with the MR. Finally if pairing was completed successful the thing status will change to ONLINE
422 * @param pairingCode pairing code received from MR (NOTIFY event data)
423 * @throws MagentaTVException
426 public void onPairingResult(String pairingCode) throws MagentaTVException {
427 if (control.isInitialized()) {
428 if (control.generateVerificationCode(pairingCode)) {
429 config.setPairingCode(pairingCode);
431 "{}: Pairing code received (UDN {}, terminalID {}, pairingCode={}, verificationCode={}, userId={})",
432 thingId, config.getUDN(), config.getTerminalID(), config.getPairingCode(),
433 config.getVerificationCode(), config.getUserId());
435 // verify pairing completes the pairing process
436 if (control.verifyPairing()) {
437 logger.debug("{}: Pairing completed for device {} ({}), Thing now ONLINE", thingId,
438 config.getFriendlyName(), config.getTerminalID());
439 setOnlineStatus(ThingStatus.ONLINE, "");
440 cancelPairingCheck(); // stop timeout check
443 updateThingProperties(); // persist pairing and verification code
445 logger.debug("{}: control not yet initialized!", thingId);
450 public void onMREvent(String jsonInput) {
451 logger.trace("{}: Process MR event for device {}, json={}", thingId, deviceName(), jsonInput);
452 boolean flUpdatePower = false;
453 String jsonEvent = fixEventJson(jsonInput);
454 if (jsonEvent.contains(MR_EVENT_EIT_CHANGE)) {
455 logger.debug("{}: EVENT_EIT_CHANGE event received.", thingId);
457 MRProgramInfoEvent pinfo = gson.fromJson(jsonEvent, MRProgramInfoEvent.class);
458 if (!pinfo.channelNum.isEmpty()) {
459 logger.debug("{}: EVENT_EIT_CHANGE for channel {}/{}", thingId, pinfo.channelNum, pinfo.channelCode);
460 updateState(CHANNEL_CHANNEL, new DecimalType(pinfo.channelNum));
461 updateState(CHANNEL_CHANNEL_CODE, new DecimalType(pinfo.channelCode));
463 if (pinfo.programInfo != null) {
465 for (MRProgramStatus ps : pinfo.programInfo) {
466 if ((ps.startTime == null) || ps.startTime.isEmpty()) {
467 logger.debug("{}: EVENT_EIT_CHANGE: empty event data = {}", thingId, jsonEvent);
468 continue; // empty program_info
470 updateState(CHANNEL_RUN_STATUS, new StringType(control.getRunStatus(ps.runningStatus)));
472 if (ps.shortEvent != null) {
473 for (MRShortProgramInfo se : ps.shortEvent) {
474 if ((ps.startTime == null) || ps.startTime.isEmpty()) {
475 logger.debug("{}: EVENT_EIT_CHANGE: empty program info", thingId);
478 // Convert UTC to local time
479 // 2018/11/04 21:45:00 -> "2018-11-04T10:15:30.00Z"
480 String tsLocal = ps.startTime.replace('/', '-').replace(" ", "T") + "Z";
481 Instant timestamp = Instant.parse(tsLocal);
482 ZonedDateTime localTime = timestamp.atZone(ZoneId.of("Europe/Berlin"));
483 tsLocal = substringBeforeLast(localTime.toString(), "[");
484 tsLocal = substringBefore(tsLocal.replace('-', '/').replace('T', ' '), "+");
486 logger.debug("{}: Info for channel {} / {} - {} {}.{}, start time={}, duration={}", thingId,
487 pinfo.channelNum, pinfo.channelCode, control.getRunStatus(ps.runningStatus),
488 se.eventName, se.textChar, tsLocal, ps.duration);
489 if (ps.runningStatus != EV_EITCHG_RUNNING_NOT_RUNNING) {
490 updateState(CHANNEL_PROG_TITLE, new StringType(se.eventName));
491 updateState(CHANNEL_PROG_TEXT, new StringType(se.textChar));
492 updateState(CHANNEL_PROG_START, new DateTimeType(localTime));
495 DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
496 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
497 Date date = dateFormat.parse(ps.duration);
498 long minutes = date.getTime() / 1000L / 60l;
499 updateState(CHANNEL_PROG_DURATION, toQuantityType(minutes, Units.MINUTE));
500 } catch (ParseException e) {
501 logger.debug("{}: Unable to parse programDuration: {}", thingId, ps.duration);
505 flUpdatePower = true;
512 } else if (jsonEvent.contains("new_play_mode")) {
513 MRPayEvent event = gson.fromJson(jsonEvent, MRPayEvent.class);
514 if (event.duration == null) {
517 if (event.playPostion == null) {
518 event.playPostion = -1;
520 logger.debug("{}: STB event playContent: playMode={}, duration={}, playPosition={}", thingId,
521 control.getPlayStatus(event.newPlayMode), event.duration, event.playPostion);
523 // If we get a playConfig event there MR must be online. However it also sends a
524 // plyMode stop before powering off the device, so we filter this.
525 if ((event.newPlayMode != EV_PLAYCHG_STOP) && this.isInitialized()) {
526 flUpdatePower = true;
528 if (event.newPlayMode != -1) {
529 String playMode = control.getPlayStatus(event.newPlayMode);
530 updateState(CHANNEL_PLAY_MODE, new StringType(playMode));
531 mapPlayModeToMediaControl(playMode);
533 if (event.duration > 0) {
534 updateState(CHANNEL_PROG_DURATION, new StringType(event.duration.toString()));
536 if (event.playPostion != -1) {
537 updateState(CHANNEL_PROG_POS, toQuantityType(event.playPostion / 6, Units.MINUTE));
540 logger.debug("{}: Unknown MR event, JSON={}", thingId, jsonEvent);
543 // We received a non-stopped event -> MR must be on
544 updateState(CHANNEL_POWER, OnOffType.ON);
548 private void mapPlayModeToMediaControl(String playMode) {
554 logger.debug("{}: Setting Player state to PLAY", thingId);
555 updateState(CHANNEL_PLAYER, PlayPauseType.PLAY);
559 logger.debug("{}: Setting Player state to PAUSE", thingId);
560 updateState(CHANNEL_PLAYER, PlayPauseType.PAUSE);
566 * When the MR powers off it send a UPnP message, which is catched by the binding.
569 public void onPowerOff() throws MagentaTVException {
570 logger.debug("{}: Power-Off received for device {}", thingId, deviceName());
571 // MR was powered off -> update power status, reset items
572 resetEventChannels();
575 private void resetEventChannels() {
576 updateState(CHANNEL_POWER, OnOffType.OFF);
577 updateState(CHANNEL_PROG_TITLE, StringType.EMPTY);
578 updateState(CHANNEL_PROG_TEXT, StringType.EMPTY);
579 updateState(CHANNEL_PROG_START, StringType.EMPTY);
580 updateState(CHANNEL_PROG_DURATION, DecimalType.ZERO);
581 updateState(CHANNEL_PROG_POS, DecimalType.ZERO);
582 updateState(CHANNEL_CHANNEL, DecimalType.ZERO);
583 updateState(CHANNEL_CHANNEL_CODE, DecimalType.ZERO);
586 private String fixEventJson(String jsonEvent) {
587 // MR401: channel_num is a string -> ok
588 // MR201: channel_num is an int -> fix JSON formatting to String
589 if (jsonEvent.contains(MR_EVENT_CHAN_TAG) && !jsonEvent.contains(MR_EVENT_CHAN_TAG + "\"")) {
590 // hack: reformat the JSON string to make it compatible with the GSON parsing
591 logger.trace("{}: malformed JSON->fix channel_num", thingId);
592 String start = substringBefore(jsonEvent, MR_EVENT_CHAN_TAG); // up to "channel_num":
593 String end = substringAfter(jsonEvent, MR_EVENT_CHAN_TAG); // behind "channel_num":
594 String chan = substringBetween(jsonEvent, MR_EVENT_CHAN_TAG, ",").trim();
595 return start + "\"channel_num\":" + "\"" + chan + "\"" + end;
600 private boolean isOnline() {
601 return this.getThing().getStatus() == ThingStatus.ONLINE;
605 * Renew the event subscription. The periodic refresh is required, otherwise the receive will stop sending events.
606 * Reconnect if nessesary.
608 private void renewEventSubscription() {
609 if (!control.isInitialized()) {
612 logger.debug("{}: Check receiver status, current state {}/{}", thingId,
613 this.getThing().getStatusInfo().getStatus(), this.getThing().getStatusInfo().getStatusDetail());
616 // when pairing is completed re-new event channel subscription
617 if ((this.getThing().getStatus() != ThingStatus.OFFLINE) && !config.getVerificationCode().isEmpty()) {
618 logger.debug("{}: Renew MR event subscription for device {}", thingId, deviceName());
619 control.subscribeEventChannel();
621 } catch (MagentaTVException e) {
622 logger.warn("{}: Re-new event subscription failed: {}", deviceName(), e.toString());
625 // another try: if the above SUBSCRIBE fails, try a re-connect immediatly
627 if ((this.getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.COMMUNICATION_ERROR)
628 && !config.getUserId().isEmpty()) {
629 // if we have no userId the OAuth is not completed or pairing process got stuck
630 logger.debug("{}: Reconnect media receiver", deviceName());
631 connectReceiver(); // throws MagentaTVException on error
633 } catch (MagentaTVException | RuntimeException e) {
634 logger.debug("{}: Re-connect to receiver failed: {}", deviceName(), e.toString());
638 public void updateThingProperties() {
639 Map<String, String> properties = new HashMap<String, String>();
640 properties.put(PROPERTY_FRIENDLYNAME, config.getFriendlyName());
641 properties.put(PROPERTY_MODEL_NUMBER, config.getModel());
642 properties.put(PROPERTY_DESC_URL, config.getDescriptionUrl());
643 properties.put(PROPERTY_PAIRINGCODE, config.getPairingCode());
644 properties.put(PROPERTY_VERIFICATIONCODE, config.getVerificationCode());
645 properties.put(PROPERTY_LOCAL_IP, config.getLocalIP());
646 properties.put(PROPERTY_TERMINALID, config.getLocalIP());
647 properties.put(PROPERTY_LOCAL_MAC, config.getLocalMAC());
648 properties.put(PROPERTY_WAKEONLAN, config.getWakeOnLAN());
649 updateProperties(properties);
652 public static State toQuantityType(@Nullable Number value, Unit<?> unit) {
653 return value == null ? UnDefType.NULL : new QuantityType<>(value, unit);
656 private String deviceName() {
657 return config.getFriendlyName() + "(" + config.getTerminalID() + ")";
660 private void cancelJob(@Nullable ScheduledFuture<?> job) {
661 if ((job != null) && !job.isCancelled()) {
666 protected void cancelInitialize() {
667 cancelJob(initializeJob);
670 protected void cancelPairingCheck() {
671 cancelJob(pairingWatchdogJob);
674 protected void cancelRenewEvent() {
675 cancelJob(renewEventJob);
678 private void cancelAllJobs() {
680 cancelPairingCheck();
685 public void dispose() {
687 manager.removeDevice(config.getTerminalID());