]> git.basschouten.com Git - openhab-addons.git/blob
2cc7bfd0d9cd705dd9603ea70f0ff8fd20a19f75
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.oppo.internal.handler;
14
15 import static org.openhab.binding.oppo.internal.OppoBindingConstants.*;
16 import static org.openhab.core.thing.Thing.*;
17
18 import java.math.BigDecimal;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.oppo.internal.OppoException;
29 import org.openhab.binding.oppo.internal.OppoStateDescriptionOptionProvider;
30 import org.openhab.binding.oppo.internal.communication.OppoCommand;
31 import org.openhab.binding.oppo.internal.communication.OppoConnector;
32 import org.openhab.binding.oppo.internal.communication.OppoDefaultConnector;
33 import org.openhab.binding.oppo.internal.communication.OppoIpConnector;
34 import org.openhab.binding.oppo.internal.communication.OppoMessageEvent;
35 import org.openhab.binding.oppo.internal.communication.OppoMessageEventListener;
36 import org.openhab.binding.oppo.internal.communication.OppoSerialConnector;
37 import org.openhab.binding.oppo.internal.communication.OppoStatusCodes;
38 import org.openhab.binding.oppo.internal.configuration.OppoThingConfiguration;
39 import org.openhab.core.io.transport.serial.SerialPortManager;
40 import org.openhab.core.library.types.DecimalType;
41 import org.openhab.core.library.types.NextPreviousType;
42 import org.openhab.core.library.types.OnOffType;
43 import org.openhab.core.library.types.PercentType;
44 import org.openhab.core.library.types.PlayPauseType;
45 import org.openhab.core.library.types.QuantityType;
46 import org.openhab.core.library.types.RewindFastforwardType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.library.unit.Units;
49 import org.openhab.core.thing.Channel;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.binding.BaseThingHandler;
55 import org.openhab.core.types.Command;
56 import org.openhab.core.types.State;
57 import org.openhab.core.types.StateOption;
58 import org.openhab.core.types.UnDefType;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * The {@link OppoHandler} is responsible for handling commands, which are sent to one of the channels.
64  *
65  * Based on the Rotel binding by Laurent Garnier
66  *
67  * @author Michael Lobstein - Initial contribution
68  */
69 @NonNullByDefault
70 public class OppoHandler extends BaseThingHandler implements OppoMessageEventListener {
71     private static final long RECON_POLLING_INTERVAL_SEC = 60;
72     private static final long POLLING_INTERVAL_SEC = 10;
73     private static final long INITIAL_POLLING_DELAY_SEC = 5;
74     private static final long SLEEP_BETWEEN_CMD_MS = 100;
75
76     private static final Pattern TIME_CODE_PATTERN = Pattern
77             .compile("^(\\d{3}) (\\d{3}) ([A-Z]{1}) (\\d{2}:\\d{2}:\\d{2})$");
78
79     private final Logger logger = LoggerFactory.getLogger(OppoHandler.class);
80
81     private @Nullable ScheduledFuture<?> reconnectJob;
82     private @Nullable ScheduledFuture<?> pollingJob;
83
84     private OppoStateDescriptionOptionProvider stateDescriptionProvider;
85     private SerialPortManager serialPortManager;
86     private OppoConnector connector = new OppoDefaultConnector();
87
88     private List<StateOption> inputSourceOptions = new ArrayList<>();
89     private List<StateOption> hdmiModeOptions = new ArrayList<>();
90
91     private long lastEventReceived = System.currentTimeMillis();
92     private String verboseMode = VERBOSE_2;
93     private String currentChapter = BLANK;
94     private String currentTimeMode = T;
95     private String currentPlayMode = BLANK;
96     private String currentDiscType = BLANK;
97     private boolean isPowerOn = false;
98     private boolean isUDP20X = false;
99     private boolean isBdpIP = false;
100     private boolean isVbModeSet = false;
101     private boolean isInitialQuery = false;
102     private Object sequenceLock = new Object();
103
104     /**
105      * Constructor
106      */
107     public OppoHandler(Thing thing, OppoStateDescriptionOptionProvider stateDescriptionProvider,
108             SerialPortManager serialPortManager) {
109         super(thing);
110         this.stateDescriptionProvider = stateDescriptionProvider;
111         this.serialPortManager = serialPortManager;
112     }
113
114     @Override
115     public void initialize() {
116         OppoThingConfiguration config = getConfigAs(OppoThingConfiguration.class);
117         final String uid = this.getThing().getUID().getAsString();
118
119         // Check configuration settings
120         String configError = null;
121         boolean override = false;
122
123         Integer model = config.model;
124         String serialPort = config.serialPort;
125         String host = config.host;
126         Integer port = config.port;
127
128         if (model == null) {
129             configError = "player model must be specified";
130             return;
131         }
132
133         if ((serialPort == null || serialPort.isEmpty()) && (host == null || host.isEmpty())) {
134             configError = "undefined serialPort and host configuration settings; please set one of them";
135         } else if (serialPort != null && (host == null || host.isEmpty())) {
136             if (serialPort.toLowerCase().startsWith("rfc2217")) {
137                 configError = "use host and port configuration settings for a serial over IP connection";
138             }
139         } else {
140             if (port == null) {
141                 if (model == MODEL83) {
142                     port = BDP83_PORT;
143                     override = true;
144                     this.isBdpIP = true;
145                 } else if (model == MODEL103 || model == MODEL105) {
146                     port = BDP10X_PORT;
147                     override = true;
148                     this.isBdpIP = true;
149                 } else {
150                     port = BDP20X_PORT;
151                 }
152             } else if (port <= 0) {
153                 configError = "invalid port configuration setting";
154             }
155         }
156
157         if (configError != null) {
158             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, configError);
159             return;
160         }
161
162         if (serialPort != null) {
163             connector = new OppoSerialConnector(serialPortManager, serialPort, uid);
164         } else if (port != null) {
165             connector = new OppoIpConnector(host, port, uid);
166             connector.overrideCmdPreamble(override);
167         } else {
168             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
169                     "Either Serial port or Host & Port must be specifed");
170             return;
171         }
172
173         if (config.verboseMode) {
174             this.verboseMode = VERBOSE_3;
175         }
176
177         if (model == MODEL203 || model == MODEL205) {
178             this.isUDP20X = true;
179         }
180
181         this.buildOptionDropdowns(model);
182         stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_SOURCE),
183                 inputSourceOptions);
184         stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_HDMI_MODE),
185                 hdmiModeOptions);
186
187         // remove channels not needed for this model
188         List<Channel> channels = new ArrayList<>(this.getThing().getChannels());
189
190         if (model == MODEL83) {
191             channels.removeIf(c -> (c.getUID().getId().equals(CHANNEL_SUB_SHIFT)
192                     || c.getUID().getId().equals(CHANNEL_OSD_POSITION)));
193         }
194
195         if (model == MODEL83 || model == MODEL103 || model == MODEL105) {
196             channels.removeIf(c -> (c.getUID().getId().equals(CHANNEL_ASPECT_RATIO)
197                     || c.getUID().getId().equals(CHANNEL_HDR_MODE)));
198         }
199
200         // no query to determine this, so set the default value at startup
201         updateChannelState(CHANNEL_TIME_MODE, currentTimeMode);
202
203         updateThing(editThing().withChannels(channels).build());
204
205         scheduleReconnectJob();
206         schedulePollingJob();
207
208         updateStatus(ThingStatus.UNKNOWN);
209     }
210
211     @Override
212     public void dispose() {
213         cancelReconnectJob();
214         cancelPollingJob();
215         closeConnection();
216         super.dispose();
217     }
218
219     /**
220      * Handle a command the UI
221      *
222      * @param channelUID the channel sending the command
223      * @param command the command received
224      *
225      */
226     @Override
227     public void handleCommand(ChannelUID channelUID, Command command) {
228         String channel = channelUID.getId();
229
230         if (getThing().getStatus() != ThingStatus.ONLINE) {
231             logger.debug("Thing is not ONLINE; command {} from channel {} is ignored", command, channel);
232             return;
233         }
234
235         if (!connector.isConnected()) {
236             logger.debug("Command {} from channel {} is ignored: connection not established", command, channel);
237             return;
238         }
239
240         synchronized (sequenceLock) {
241             try {
242                 String commandStr = command.toString();
243                 switch (channel) {
244                     case CHANNEL_POWER:
245                         if (command instanceof OnOffType) {
246                             connector.sendCommand(
247                                     command == OnOffType.ON ? OppoCommand.POWER_ON : OppoCommand.POWER_OFF);
248
249                             // set the power flag to false only, will be set true by QPW or UPW messages
250                             if (command == OnOffType.OFF) {
251                                 isPowerOn = false;
252                                 isInitialQuery = false;
253                             }
254                         }
255                         break;
256                     case CHANNEL_VOLUME:
257                         if (command instanceof PercentType) {
258                             connector.sendCommand(OppoCommand.SET_VOLUME_LEVEL, commandStr);
259                         }
260                         break;
261                     case CHANNEL_MUTE:
262                         if (command instanceof OnOffType) {
263                             if (command == OnOffType.ON) {
264                                 connector.sendCommand(OppoCommand.SET_VOLUME_LEVEL, MUTE);
265                             } else {
266                                 connector.sendCommand(OppoCommand.MUTE);
267                             }
268                         }
269                         break;
270                     case CHANNEL_SOURCE:
271                         if (command instanceof DecimalType) {
272                             int value = ((DecimalType) command).intValue();
273                             connector.sendCommand(OppoCommand.SET_INPUT_SOURCE, String.valueOf(value));
274                         }
275                         break;
276                     case CHANNEL_CONTROL:
277                         this.handleControlCommand(command);
278                         break;
279                     case CHANNEL_TIME_MODE:
280                         if (command instanceof StringType) {
281                             connector.sendCommand(OppoCommand.SET_TIME_DISPLAY, commandStr);
282                             currentTimeMode = commandStr;
283                         }
284                         break;
285                     case CHANNEL_REPEAT_MODE:
286                         if (command instanceof StringType) {
287                             // this one is lame, the response code when querying repeat mode is two digits,
288                             // but setting it is a 2-3 letter code.
289                             connector.sendCommand(OppoCommand.SET_REPEAT, OppoStatusCodes.REPEAT_MODE.get(commandStr));
290                         }
291                         break;
292                     case CHANNEL_ZOOM_MODE:
293                         if (command instanceof StringType) {
294                             // again why could't they make the query code and set code the same?
295                             connector.sendCommand(OppoCommand.SET_ZOOM_RATIO,
296                                     OppoStatusCodes.ZOOM_MODE.get(commandStr));
297                         }
298                         break;
299                     case CHANNEL_SUB_SHIFT:
300                         if (command instanceof DecimalType) {
301                             int value = ((DecimalType) command).intValue();
302                             connector.sendCommand(OppoCommand.SET_SUBTITLE_SHIFT, String.valueOf(value));
303                         }
304                         break;
305                     case CHANNEL_OSD_POSITION:
306                         if (command instanceof DecimalType) {
307                             int value = ((DecimalType) command).intValue();
308                             connector.sendCommand(OppoCommand.SET_OSD_POSITION, String.valueOf(value));
309                         }
310                         break;
311                     case CHANNEL_HDMI_MODE:
312                         if (command instanceof StringType) {
313                             connector.sendCommand(OppoCommand.SET_HDMI_MODE, commandStr);
314                         }
315                         break;
316                     case CHANNEL_HDR_MODE:
317                         if (command instanceof StringType) {
318                             connector.sendCommand(OppoCommand.SET_HDR_MODE, commandStr);
319                         }
320                         break;
321                     case CHANNEL_REMOTE_BUTTON:
322                         if (command instanceof StringType) {
323                             connector.sendCommand(commandStr);
324                         }
325                         break;
326                     default:
327                         logger.warn("Unknown Command {} from channel {}", command, channel);
328                         break;
329                 }
330             } catch (OppoException e) {
331                 logger.warn("Command {} from channel {} failed: {}", command, channel, e.getMessage());
332                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Sending command failed");
333                 closeConnection();
334                 scheduleReconnectJob();
335             }
336         }
337     }
338
339     /**
340      * Open the connection with the Oppo player
341      *
342      * @return true if the connection is opened successfully or false if not
343      */
344     private synchronized boolean openConnection() {
345         connector.addEventListener(this);
346         try {
347             connector.open();
348         } catch (OppoException e) {
349             logger.debug("openConnection() failed: {}", e.getMessage());
350         }
351         logger.debug("openConnection(): {}", connector.isConnected() ? "connected" : "disconnected");
352         return connector.isConnected();
353     }
354
355     /**
356      * Close the connection with the Oppo player
357      */
358     private synchronized void closeConnection() {
359         if (connector.isConnected()) {
360             connector.close();
361             connector.removeEventListener(this);
362             logger.debug("closeConnection(): disconnected");
363         }
364     }
365
366     /**
367      * Handle an event received from the Oppo player
368      *
369      * @param event the event to process
370      */
371     @Override
372     public void onNewMessageEvent(OppoMessageEvent evt) {
373         logger.debug("onNewMessageEvent: key {} = {}", evt.getKey(), evt.getValue());
374         lastEventReceived = System.currentTimeMillis();
375
376         String key = evt.getKey();
377         String updateData = evt.getValue().trim();
378         if (this.getThing().getStatus() == ThingStatus.OFFLINE) {
379             updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
380         }
381
382         synchronized (sequenceLock) {
383             try {
384                 switch (key) {
385                     case NOP: // ignore
386                         break;
387                     case UTC:
388                         // Player sent a time code update ie: 000 000 T 00:00:01
389                         // g1 = title(movie only; cd always 000), g2 = chapter(movie)/track(cd), g3 = time display code,
390                         // g4 = time
391                         Matcher matcher = TIME_CODE_PATTERN.matcher(updateData);
392                         if (matcher.find()) {
393                             // only update these when chapter/track changes to prevent spamming the channels with
394                             // unnecessary updates
395                             if (!currentChapter.equals(matcher.group(2))) {
396                                 currentChapter = matcher.group(2);
397                                 // for CDs this will get track 1/x also
398                                 connector.sendCommand(OppoCommand.QUERY_TITLE_TRACK);
399                                 // for movies shows chapter 1/x; always 0/0 for CDs
400                                 connector.sendCommand(OppoCommand.QUERY_CHAPTER);
401                             }
402
403                             if (!currentTimeMode.equals(matcher.group(3))) {
404                                 currentTimeMode = matcher.group(3);
405                                 updateChannelState(CHANNEL_TIME_MODE, currentTimeMode);
406                             }
407                             updateChannelState(CHANNEL_TIME_DISPLAY, matcher.group(4));
408                         } else {
409                             logger.debug("no match on message: {}", updateData);
410                         }
411                         break;
412                     case QTE:
413                     case QTR:
414                     case QCE:
415                     case QCR:
416                         // these are used with verbose mode 2
417                         updateChannelState(CHANNEL_TIME_DISPLAY, updateData);
418                         break;
419                     case QVR:
420                         thing.setProperty(PROPERTY_FIRMWARE_VERSION, updateData);
421                         break;
422                     case QPW:
423                         updateChannelState(CHANNEL_POWER, updateData);
424                         if (OFF.equals(updateData)) {
425                             currentPlayMode = BLANK;
426                             isPowerOn = false;
427                         } else {
428                             isPowerOn = true;
429                         }
430                         break;
431                     case UPW:
432                         updateChannelState(CHANNEL_POWER, ONE.equals(updateData) ? ON : OFF);
433                         if (ZERO.equals(updateData)) {
434                             currentPlayMode = BLANK;
435                             isPowerOn = false;
436                             isInitialQuery = false;
437                         } else {
438                             isPowerOn = true;
439                         }
440                         break;
441                     case QVL:
442                     case UVL:
443                     case VUP:
444                     case VDN:
445                         if (MUTE.equals(updateData) || MUT.equals(updateData)) { // query sends MUTE, update sends MUT
446                             updateChannelState(CHANNEL_MUTE, ON);
447                         } else if (UMT.equals(updateData)) {
448                             updateChannelState(CHANNEL_MUTE, OFF);
449                         } else {
450                             updateChannelState(CHANNEL_VOLUME, updateData);
451                             updateChannelState(CHANNEL_MUTE, OFF);
452                         }
453                         break;
454                     case QIS:
455                     case UIS:
456                         // example: 0 BD-PLAYER, split off just the number
457                         updateChannelState(CHANNEL_SOURCE, updateData.split(SPACE)[0]);
458                         break;
459                     case UPL:
460                         // we got the playback status update, throw it away and call the query because the text output
461                         // is better
462                         connector.sendCommand(OppoCommand.QUERY_PLAYBACK_STATUS);
463                         break;
464                     case QTK:
465                         // example: 02/10, split off both numbers
466                         String[] track = updateData.split(SLASH);
467                         if (track.length == 2) {
468                             updateChannelState(CHANNEL_CURRENT_TITLE, track[0]);
469                             updateChannelState(CHANNEL_TOTAL_TITLE, track[1]);
470                         }
471                         break;
472                     case QCH:
473                         // example: 03/03, split off the both numbers
474                         String[] chapter = updateData.split(SLASH);
475                         if (chapter.length == 2) {
476                             updateChannelState(CHANNEL_CURRENT_CHAPTER, chapter[0]);
477                             updateChannelState(CHANNEL_TOTAL_CHAPTER, chapter[1]);
478                         }
479                         break;
480                     case QPL:
481                         // if playback has stopped, we have to zero out Time, Title and Track info and so on manually
482                         if (NO_DISC.equals(updateData) || LOADING.equals(updateData) || OPEN.equals(updateData)
483                                 || CLOSE.equals(updateData) || STOP.equals(updateData)) {
484                             updateChannelState(CHANNEL_CURRENT_TITLE, ZERO);
485                             updateChannelState(CHANNEL_TOTAL_TITLE, ZERO);
486                             updateChannelState(CHANNEL_CURRENT_CHAPTER, ZERO);
487                             updateChannelState(CHANNEL_TOTAL_CHAPTER, ZERO);
488                             updateChannelState(CHANNEL_TIME_DISPLAY, UNDEF);
489                             updateChannelState(CHANNEL_AUDIO_TYPE, UNDEF);
490                             updateChannelState(CHANNEL_SUBTITLE_TYPE, UNDEF);
491                         }
492                         updateChannelState(CHANNEL_PLAY_MODE, updateData);
493
494                         // if switching to play mode and not a CD then query the subtitle type...
495                         // because if subtitles were on when playback stopped, they got nulled out above
496                         // and the subtitle update message ("UST") is not sent when play starts like it is for audio
497                         if (PLAY.equals(updateData) && !CDDA.equals(currentDiscType)) {
498                             connector.sendCommand(OppoCommand.QUERY_SUBTITLE_TYPE);
499                         }
500                         currentPlayMode = updateData;
501                         break;
502                     case QRP:
503                         updateChannelState(CHANNEL_REPEAT_MODE, updateData);
504                         break;
505                     case QZM:
506                         updateChannelState(CHANNEL_ZOOM_MODE, updateData);
507                         break;
508                     case UDT:
509                         // we got the disc type status update, throw it away
510                         // and call the query because the text output is better
511                         connector.sendCommand(OppoCommand.QUERY_DISC_TYPE);
512                     case QDT:
513                         currentDiscType = updateData;
514                         updateChannelState(CHANNEL_DISC_TYPE, updateData);
515                         break;
516                     case UAT:
517                         // we got the audio type status update, throw it away
518                         // and call the query because the text output is better
519                         connector.sendCommand(OppoCommand.QUERY_AUDIO_TYPE);
520                         break;
521                     case QAT:
522                         updateChannelState(CHANNEL_AUDIO_TYPE, updateData);
523                         break;
524                     case UST:
525                         // we got the subtitle type status update, throw it away
526                         // and call the query because the text output is better
527                         connector.sendCommand(OppoCommand.QUERY_SUBTITLE_TYPE);
528                         break;
529                     case QST:
530                         updateChannelState(CHANNEL_SUBTITLE_TYPE, updateData);
531                         break;
532                     case UAR: // 203 & 205 only
533                         updateChannelState(CHANNEL_ASPECT_RATIO, updateData);
534                         break;
535                     case UVO:
536                         // example: _480I60 1080P60 - 1st source res, 2nd output res
537                         String[] resolution = updateData.replace(UNDERSCORE, BLANK).split(SPACE);
538                         if (resolution.length == 2) {
539                             updateChannelState(CHANNEL_SOURCE_RESOLUTION, resolution[0]);
540                             updateChannelState(CHANNEL_OUTPUT_RESOLUTION, resolution[1]);
541                         }
542                         break;
543                     case U3D:
544                         updateChannelState(CHANNEL_3D_INDICATOR, updateData);
545                         break;
546                     case QSH:
547                         updateChannelState(CHANNEL_SUB_SHIFT, updateData);
548                         break;
549                     case QOP:
550                         updateChannelState(CHANNEL_OSD_POSITION, updateData);
551                         break;
552                     case QHD:
553                         if (this.isUDP20X) {
554                             updateChannelState(CHANNEL_HDMI_MODE, updateData);
555                         } else {
556                             handleHdmiModeUpdate(updateData);
557                         }
558                         break;
559                     case QHR: // 203 & 205 only
560                         updateChannelState(CHANNEL_HDR_MODE, updateData);
561                         break;
562                     default:
563                         logger.debug("onNewMessageEvent: unhandled key {}, value: {}", key, updateData);
564                         break;
565                 }
566             } catch (OppoException e) {
567                 logger.debug("Exception processing event from player: {}", e.getMessage());
568             }
569         }
570     }
571
572     /**
573      * Schedule the reconnection job
574      */
575     private void scheduleReconnectJob() {
576         logger.debug("Schedule reconnect job");
577         cancelReconnectJob();
578
579         reconnectJob = scheduler.scheduleWithFixedDelay(() -> {
580             if (!connector.isConnected()) {
581                 logger.debug("Trying to reconnect...");
582                 closeConnection();
583                 String error = null;
584                 synchronized (sequenceLock) {
585                     if (openConnection()) {
586                         try {
587                             long prevUpdateTime = lastEventReceived;
588
589                             connector.sendCommand(OppoCommand.QUERY_POWER_STATUS);
590                             Thread.sleep(SLEEP_BETWEEN_CMD_MS);
591
592                             // if the player is off most of these won't really do much...
593                             OppoCommand.QUERY_COMMANDS.forEach(cmd -> {
594                                 try {
595                                     connector.sendCommand(cmd);
596                                     Thread.sleep(SLEEP_BETWEEN_CMD_MS);
597                                 } catch (OppoException | InterruptedException e) {
598                                     logger.debug("Exception sending initial commands: {}", e.getMessage());
599                                 }
600                             });
601
602                             // prevUpdateTime should have changed if a message was received from the player
603                             if (prevUpdateTime == lastEventReceived) {
604                                 error = "Player not responding to status requests";
605                             }
606                         } catch (OppoException | InterruptedException e) {
607                             error = "First command after connection failed";
608                             logger.debug("{}: {}", error, e.getMessage());
609                         }
610                     } else {
611                         error = "Reconnection failed";
612                     }
613                     if (error != null) {
614                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, error);
615                         closeConnection();
616                     } else {
617                         updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
618                         isInitialQuery = false;
619                         isVbModeSet = false;
620                     }
621                 }
622             }
623         }, 1, RECON_POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
624     }
625
626     /**
627      * Cancel the reconnection job
628      */
629     private void cancelReconnectJob() {
630         ScheduledFuture<?> reconnectJob = this.reconnectJob;
631         if (reconnectJob != null) {
632             reconnectJob.cancel(true);
633             this.reconnectJob = null;
634         }
635     }
636
637     /**
638      * Schedule the polling job
639      */
640     private void schedulePollingJob() {
641         logger.debug("Schedule polling job");
642         cancelPollingJob();
643
644         // when the Oppo is off, this will keep the connection (esp Serial over IP) alive and
645         // detect if the connection goes down
646         pollingJob = scheduler.scheduleWithFixedDelay(() -> {
647             if (connector.isConnected()) {
648                 logger.debug("Polling the player for updated status...");
649
650                 synchronized (sequenceLock) {
651                     try {
652                         // Verbose mode 2 & 3 only do once until power comes on OR always for BDP direct IP
653                         if ((!isPowerOn && !isInitialQuery) || isBdpIP) {
654                             connector.sendCommand(OppoCommand.QUERY_POWER_STATUS);
655                         }
656
657                         if (isPowerOn) {
658                             // the verbose mode must be set while the player is on
659                             if (!isVbModeSet && !isBdpIP) {
660                                 connector.sendCommand(OppoCommand.SET_VERBOSE_MODE, this.verboseMode);
661                                 isVbModeSet = true;
662                                 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
663                             }
664
665                             // Verbose mode 2 & 3 only do once OR always for BDP direct IP
666                             if (!isInitialQuery || isBdpIP) {
667                                 isInitialQuery = true;
668                                 OppoCommand.QUERY_COMMANDS.forEach(cmd -> {
669                                     try {
670                                         connector.sendCommand(cmd);
671                                         Thread.sleep(SLEEP_BETWEEN_CMD_MS);
672                                     } catch (OppoException | InterruptedException e) {
673                                         logger.debug("Exception sending polling commands: {}", e.getMessage());
674                                     }
675                                 });
676                             }
677
678                             // for Verbose mode 2 get the current play back time if we are playing, otherwise just do
679                             // NO_OP
680                             if ((VERBOSE_2.equals(this.verboseMode) && PLAY.equals(currentPlayMode)) || isBdpIP) {
681                                 switch (currentTimeMode) {
682                                     case T:
683                                         connector.sendCommand(OppoCommand.QUERY_TITLE_ELAPSED);
684                                         break;
685                                     case X:
686                                         connector.sendCommand(OppoCommand.QUERY_TITLE_REMAIN);
687                                         break;
688                                     case C:
689                                         connector.sendCommand(OppoCommand.QUERY_CHAPTER_ELAPSED);
690                                         break;
691                                     case K:
692                                         connector.sendCommand(OppoCommand.QUERY_CHAPTER_REMAIN);
693                                         break;
694                                 }
695                                 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
696
697                                 // make queries to refresh total number of titles/tracks & chapters
698                                 connector.sendCommand(OppoCommand.QUERY_TITLE_TRACK);
699                                 Thread.sleep(SLEEP_BETWEEN_CMD_MS);
700                                 connector.sendCommand(OppoCommand.QUERY_CHAPTER);
701                             } else if (!isBdpIP) {
702                                 // verbose mode 3
703                                 connector.sendCommand(OppoCommand.NO_OP);
704                             }
705                         }
706
707                     } catch (OppoException | InterruptedException e) {
708                         logger.warn("Polling error: {}", e.getMessage());
709                     }
710
711                     // if the last event received was more than 1.25 intervals ago,
712                     // the player is not responding even though the connection is still good
713                     if ((System.currentTimeMillis() - lastEventReceived) > (POLLING_INTERVAL_SEC * 1.25 * 1000)) {
714                         logger.debug("Player not responding to status requests");
715                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
716                                 "Player not responding to status requests");
717                         closeConnection();
718                         scheduleReconnectJob();
719                     }
720                 }
721             }
722         }, INITIAL_POLLING_DELAY_SEC, POLLING_INTERVAL_SEC, TimeUnit.SECONDS);
723     }
724
725     /**
726      * Cancel the polling job
727      */
728     private void cancelPollingJob() {
729         ScheduledFuture<?> pollingJob = this.pollingJob;
730         if (pollingJob != null) {
731             pollingJob.cancel(true);
732             this.pollingJob = null;
733         }
734     }
735
736     /**
737      * Update the state of a channel
738      *
739      * @param channel the channel
740      * @param value the value to be updated
741      */
742     private void updateChannelState(String channel, String value) {
743         if (!isLinked(channel)) {
744             return;
745         }
746
747         if (UNDEF.equals(value)) {
748             updateState(channel, UnDefType.UNDEF);
749             return;
750         }
751
752         State state = UnDefType.UNDEF;
753
754         switch (channel) {
755             case CHANNEL_TIME_DISPLAY:
756                 String[] timeArr = value.split(COLON);
757                 if (timeArr.length == 3) {
758                     int seconds = (Integer.parseInt(timeArr[0]) * 3600) + (Integer.parseInt(timeArr[1]) * 60)
759                             + Integer.parseInt(timeArr[2]);
760                     state = new QuantityType<>(seconds, Units.SECOND);
761                 } else {
762                     state = UnDefType.UNDEF;
763                 }
764                 break;
765             case CHANNEL_POWER:
766             case CHANNEL_MUTE:
767                 state = ON.equals(value) ? OnOffType.ON : OnOffType.OFF;
768                 break;
769             case CHANNEL_SOURCE:
770             case CHANNEL_SUB_SHIFT:
771             case CHANNEL_OSD_POSITION:
772             case CHANNEL_CURRENT_TITLE:
773             case CHANNEL_TOTAL_TITLE:
774             case CHANNEL_CURRENT_CHAPTER:
775             case CHANNEL_TOTAL_CHAPTER:
776                 state = new DecimalType(value);
777                 break;
778             case CHANNEL_VOLUME:
779                 state = new PercentType(BigDecimal.valueOf(Integer.parseInt(value)));
780                 break;
781             case CHANNEL_PLAY_MODE:
782             case CHANNEL_TIME_MODE:
783             case CHANNEL_REPEAT_MODE:
784             case CHANNEL_ZOOM_MODE:
785             case CHANNEL_DISC_TYPE:
786             case CHANNEL_AUDIO_TYPE:
787             case CHANNEL_SUBTITLE_TYPE:
788             case CHANNEL_ASPECT_RATIO:
789             case CHANNEL_SOURCE_RESOLUTION:
790             case CHANNEL_OUTPUT_RESOLUTION:
791             case CHANNEL_3D_INDICATOR:
792             case CHANNEL_HDMI_MODE:
793             case CHANNEL_HDR_MODE:
794                 state = new StringType(value);
795                 break;
796             default:
797                 break;
798         }
799         updateState(channel, state);
800     }
801
802     /**
803      * Handle a button press from a UI Player item
804      *
805      * @param command the control button press command received
806      */
807     private void handleControlCommand(Command command) throws OppoException {
808         if (command instanceof PlayPauseType) {
809             if (command == PlayPauseType.PLAY) {
810                 connector.sendCommand(OppoCommand.PLAY);
811             } else if (command == PlayPauseType.PAUSE) {
812                 connector.sendCommand(OppoCommand.PAUSE);
813             }
814         } else if (command instanceof NextPreviousType) {
815             if (command == NextPreviousType.NEXT) {
816                 connector.sendCommand(OppoCommand.NEXT);
817             } else if (command == NextPreviousType.PREVIOUS) {
818                 connector.sendCommand(OppoCommand.PREV);
819             }
820         } else if (command instanceof RewindFastforwardType) {
821             if (command == RewindFastforwardType.FASTFORWARD) {
822                 connector.sendCommand(OppoCommand.FFORWARD);
823             } else if (command == RewindFastforwardType.REWIND) {
824                 connector.sendCommand(OppoCommand.REWIND);
825             }
826         } else {
827             logger.warn("Unknown control command: {}", command);
828         }
829     }
830
831     private void buildOptionDropdowns(int model) {
832         if (model == MODEL83 || model == MODEL103 || model == MODEL105) {
833             hdmiModeOptions.add(new StateOption("AUTO", "Auto"));
834             hdmiModeOptions.add(new StateOption("SRC", "Source Direct"));
835             if (!(model == MODEL83)) {
836                 hdmiModeOptions.add(new StateOption("4K2K", "4K*2K"));
837             }
838             hdmiModeOptions.add(new StateOption("1080P", "1080P"));
839             hdmiModeOptions.add(new StateOption("1080I", "1080I"));
840             hdmiModeOptions.add(new StateOption("720P", "720P"));
841             hdmiModeOptions.add(new StateOption("SDP", "480P"));
842             hdmiModeOptions.add(new StateOption("SDI", "480I"));
843         }
844
845         if (model == MODEL103 || model == MODEL105) {
846             inputSourceOptions.add(new StateOption("0", "Blu-Ray Player"));
847             inputSourceOptions.add(new StateOption("1", "HDMI/MHL IN-Front"));
848             inputSourceOptions.add(new StateOption("2", "HDMI IN-Back"));
849             inputSourceOptions.add(new StateOption("3", "ARC"));
850
851             if (model == MODEL105) {
852                 inputSourceOptions.add(new StateOption("4", "Optical In"));
853                 inputSourceOptions.add(new StateOption("5", "Coaxial In"));
854                 inputSourceOptions.add(new StateOption("6", "USB Audio In"));
855             }
856         }
857
858         if (model == MODEL203 || model == MODEL205) {
859             hdmiModeOptions.add(new StateOption("AUTO", "Auto"));
860             hdmiModeOptions.add(new StateOption("SRC", "Source Direct"));
861             hdmiModeOptions.add(new StateOption("UHD_AUTO", "UHD Auto"));
862             hdmiModeOptions.add(new StateOption("UHD24", "UHD24"));
863             hdmiModeOptions.add(new StateOption("UHD50", "UHD50"));
864             hdmiModeOptions.add(new StateOption("UHD60", "UHD60"));
865             hdmiModeOptions.add(new StateOption("1080P_AUTO", "1080P Auto"));
866             hdmiModeOptions.add(new StateOption("1080P24", "1080P24"));
867             hdmiModeOptions.add(new StateOption("1080P50", "1080P50"));
868             hdmiModeOptions.add(new StateOption("1080P60", "1080P60"));
869             hdmiModeOptions.add(new StateOption("1080I50", "1080I50"));
870             hdmiModeOptions.add(new StateOption("1080I60", "1080I60"));
871             hdmiModeOptions.add(new StateOption("720P50", "720P50"));
872             hdmiModeOptions.add(new StateOption("720P60", "720P60"));
873             hdmiModeOptions.add(new StateOption("576P", "567P"));
874             hdmiModeOptions.add(new StateOption("576I", "567I"));
875             hdmiModeOptions.add(new StateOption("480P", "480P"));
876             hdmiModeOptions.add(new StateOption("480I", "480I"));
877
878             inputSourceOptions.add(new StateOption("0", "Blu-Ray Player"));
879             inputSourceOptions.add(new StateOption("1", "HDMI IN"));
880             inputSourceOptions.add(new StateOption("2", "ARC"));
881
882             if (model == MODEL205) {
883                 inputSourceOptions.add(new StateOption("3", "Optical In"));
884                 inputSourceOptions.add(new StateOption("4", "Coaxial In"));
885                 inputSourceOptions.add(new StateOption("5", "USB Audio In"));
886             }
887         }
888     }
889
890     private void handleHdmiModeUpdate(String updateData) {
891         // ugly... a couple of the query hdmi mode response codes on the earlier models don't match the code to set it
892         // some of this protocol is weird like that...
893         if ("480I".equals(updateData)) {
894             updateChannelState(CHANNEL_HDMI_MODE, "SDI");
895         } else if ("480P".equals(updateData)) {
896             updateChannelState(CHANNEL_HDMI_MODE, "SDP");
897         } else if ("4K*2K".equals(updateData)) {
898             updateChannelState(CHANNEL_HDMI_MODE, "4K2K");
899         } else {
900             updateChannelState(CHANNEL_HDMI_MODE, updateData);
901         }
902     }
903 }