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.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)
105 * @param bindingConfig
107 public MagentaTVHandler(MagentaTVDeviceManager manager, Thing thing, MagentaTVNetwork network,
108 HttpClient httpClient) {
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();
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)
126 public void initialize() {
127 // The framework requires you to return from this method quickly. For that the initialization itself is executed
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));
135 initializeJob = scheduler.schedule(this::initializeThing, 5, TimeUnit.SECONDS);
136 } catch (RuntimeException e) {
137 logger.warn("Unable to schedule thing initialization", e);
141 private void initializeThing() {
142 String errorMessage = "";
144 if (config.getUDN().isEmpty()) {
145 // get UDN from device name
146 String uid = this.getThing().getUID().getAsString();
147 config.setUDN(substringAfterLast(uid, ":"));
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(), "-");
155 config.setMacAddress(macAddress);
157 control = new MagentaTVControl(config, network, httpClient);
158 config.updateNetwork(control.getConfig()); // get network parameters from control
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");
172 connectReceiver(); // throws MagentaTVException on error
174 // setup background device check
175 renewEventJob = scheduler.scheduleWithFixedDelay(this::renewEventSubscription, 2, 5, TimeUnit.MINUTES);
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);
184 if (!errorMessage.isEmpty()) {
185 logger.debug("{}: {}", thingId, errorMessage);
186 setOnlineStatus(ThingStatus.OFFLINE, errorMessage);
192 * This routine is called every time the Thing configuration has been changed
195 public void handleConfigurationUpdate(Map<String, Object> configurationParameters) {
196 logger.debug("{}: Thing config updated, re-initialize", thingId);
198 if (configurationParameters.containsKey(PROPERTY_ACCT_NAME)) {
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("");
207 super.handleConfigurationUpdate(configurationParameters);
211 * Handle channel commands
213 * @param channelUID - the channel, which received the command
214 * @param command - the actual command (could be instance of StringType,
215 * DecimalType or OnOffType)
218 public void handleCommand(ChannelUID channelUID, Command command) {
219 if (command == RefreshType.REFRESH) {
220 // currently no channels to be refreshed
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
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");
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");
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");
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");
260 logger.debug("{}: Unknown media command: {}", thingId, command);
263 case CHANNEL_CHANNEL:
264 String chan = command.toString();
265 control.selectChannel(chan);
268 if (command == OnOffType.ON) {
269 control.sendKey("MUTE");
271 control.sendKey("VOLUP");
275 if (command.toString().equalsIgnoreCase("PAIR")) { // special key to re-pair receiver (already done
277 logger.debug("{}: PAIRing key received, reconnect receiver {}", thingId, deviceName());
279 control.sendKey(command.toString());
280 mapKeyToMediateState(command.toString());
284 logger.debug("{}: Command {} for unknown channel {}", thingId, command, channelUID.getAsString());
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);
294 private void mapKeyToMediateState(String key) {
296 switch (key.toUpperCase()) {
298 state = PlayPauseType.PLAY;
301 state = PlayPauseType.PAUSE;
304 state = RewindFastforwardType.FASTFORWARD;
307 updateState(CHANNEL_PLAYER, RewindFastforwardType.REWIND);
311 logger.debug("{}: Setting Player state to {}", thingId, state);
312 updateState(CHANNEL_PLAYER, state);
317 * Connect to the receiver
319 * @throws MagentaTVException something failed
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();
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!");
336 }, 15, TimeUnit.SECONDS);
341 * If userId is empty and credentials are given the Telekom OAuth service is
342 * used to query the userId
344 * @throws MagentaTVException
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());
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("");
365 logger.debug("{}: Skip OAuth, use existing userId {}", thingId, config.getUserId());
367 if (!userId.isEmpty()) {
368 config.setUserId(userId);
370 logger.warn("{}: Unable to obtain userId from OAuth", thingId);
375 * Update thing status
377 * @param mode new thing status
378 * @return ON = power on, OFF=power off
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);
387 if (!errorMessage.isEmpty()) {
388 logger.debug("{}: Communication Error - {}, switch Thing offline", thingId, errorMessage);
389 updateStatus(newStatus, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage);
391 updateStatus(newStatus);
393 updateState(CHANNEL_POWER, OnOffType.OFF);
399 * A wakeup of the MR was detected (e.g. UPnP received)
401 * @throws MagentaTVException
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
409 logger.debug("{}: Refesh device status for {} (UDN={}", thingId, deviceName(), config.getUDN());
410 setOnlineStatus(ThingStatus.ONLINE, "");
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
418 * @param pairingCode pairing code received from MR (NOTIFY event data)
419 * @throws MagentaTVException
422 public void onPairingResult(String pairingCode) throws MagentaTVException {
423 if (control.isInitialized()) {
424 if (control.generateVerificationCode(pairingCode)) {
425 config.setPairingCode(pairingCode);
427 "{}: Pairing code received (UDN {}, terminalID {}, pairingCode={}, verificationCode={}, userId={})",
428 thingId, config.getUDN(), config.getTerminalID(), config.getPairingCode(),
429 config.getVerificationCode(), config.getUserId());
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
439 updateThingProperties(); // persist pairing and verification code
441 logger.debug("{}: control not yet initialized!", thingId);
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);
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));
459 if (pinfo.programInfo != null) {
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
466 updateState(CHANNEL_RUN_STATUS, new StringType(control.getRunStatus(ps.runningStatus)));
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);
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', ' '), "+");
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));
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);
501 flUpdatePower = true;
508 } else if (jsonEvent.contains("new_play_mode")) {
509 MRPayEvent event = gson.fromJson(jsonEvent, MRPayEvent.class);
510 if (event.duration == null) {
513 if (event.playPostion == null) {
514 event.playPostion = -1;
516 logger.debug("{}: STB event playContent: playMode={}, duration={}, playPosition={}", thingId,
517 control.getPlayStatus(event.newPlayMode), event.duration, event.playPostion);
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;
524 if (event.newPlayMode != -1) {
525 String playMode = control.getPlayStatus(event.newPlayMode);
526 updateState(CHANNEL_PLAY_MODE, new StringType(playMode));
527 mapPlayModeToMediaControl(playMode);
529 if (event.duration > 0) {
530 updateState(CHANNEL_PROG_DURATION, new StringType(event.duration.toString()));
532 if (event.playPostion != -1) {
533 updateState(CHANNEL_PROG_POS, toQuantityType(event.playPostion / 6, Units.MINUTE));
536 logger.debug("{}: Unknown MR event, JSON={}", thingId, jsonEvent);
539 // We received a non-stopped event -> MR must be on
540 updateState(CHANNEL_POWER, OnOffType.ON);
544 private void mapPlayModeToMediaControl(String playMode) {
550 logger.debug("{}: Setting Player state to PLAY", thingId);
551 updateState(CHANNEL_PLAYER, PlayPauseType.PLAY);
555 logger.debug("{}: Setting Player state to PAUSE", thingId);
556 updateState(CHANNEL_PLAYER, PlayPauseType.PAUSE);
562 * When the MR powers off it send a UPnP message, which is catched by the binding.
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();
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);
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;
596 private boolean isOnline() {
597 return this.getThing().getStatus() == ThingStatus.ONLINE;
601 * Renew the event subscription. The periodic refresh is required, otherwise the receive will stop sending events.
602 * Reconnect if nessesary.
604 private void renewEventSubscription() {
605 if (!control.isInitialized()) {
608 logger.debug("{}: Check receiver status, current state {}/{}", thingId,
609 this.getThing().getStatusInfo().getStatus(), this.getThing().getStatusInfo().getStatusDetail());
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();
617 } catch (MagentaTVException e) {
618 logger.warn("{}: Re-new event subscription failed: {}", deviceName(), e.toString());
621 // another try: if the above SUBSCRIBE fails, try a re-connect immediatly
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
629 } catch (MagentaTVException | RuntimeException e) {
630 logger.debug("{}: Re-connect to receiver failed: {}", deviceName(), e.toString());
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);
648 public static State toQuantityType(@Nullable Number value, Unit<?> unit) {
649 return value == null ? UnDefType.NULL : new QuantityType<>(value, unit);
652 private String deviceName() {
653 return config.getFriendlyName() + "(" + config.getTerminalID() + ")";
656 private void cancelJob(@Nullable ScheduledFuture<?> job) {
657 if ((job != null) && !job.isCancelled()) {
662 protected void cancelInitialize() {
663 cancelJob(initializeJob);
666 protected void cancelPairingCheck() {
667 cancelJob(pairingWatchdogJob);
670 protected void cancelRenewEvent() {
671 cancelJob(renewEventJob);
674 private void cancelAllJobs() {
676 cancelPairingCheck();
681 public void dispose() {
683 manager.removeDevice(config.getTerminalID());