Skip to content

Commit

Permalink
[samsungtv] Fix checkAndCreateServices and tweak WOL
Browse files Browse the repository at this point in the history
Signed-off-by: Nick Waterton <n.waterton@outlook.com>
  • Loading branch information
NickWaterton committed Jan 6, 2022
1 parent 27bfbd1 commit 58aefe8
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public class SamsungTvHandler extends BaseThingHandler implements RegistryListen
private static final String HTTP_ENDPOINT_V2 = "/api/v2/";

// common Samsung TV remote control ports
private final List<Integer> ports = new ArrayList<>(List.of(55000, 1515, 7001, 7676, 15500));
private final List<Integer> ports = new ArrayList<>(List.of(55000, 1515, 7001, 15500));

private final Logger logger = LoggerFactory.getLogger(SamsungTvHandler.class);

Expand Down Expand Up @@ -186,29 +186,35 @@ public boolean send(String channel, Command command) {
logger.warn("{}: Cannot send WOL packet, MAC address invalid: {}", host, macAddress);
return false;
}
wolCount = 0;
this.channel = channel;
this.command = command;
cancel();
if (channel.equals(ART_MODE) && !getArtModeSupported()) {
logger.warn("{}: artMode is not yet detected on this TV - sending WOL anyway", host);
}
startWoljob();
return true;
}
return false;
}

private void startWoljob() {
int interval = 1000;
wolJob.ifPresentOrElse(job -> {
if (job.isCancelled()) {
wolJob = Optional.of(scheduler.scheduleWithFixedDelay(this::wolCheckPeriodic, 0, interval,
TimeUnit.MILLISECONDS));
} // else - scheduler is already running!
start();
} else {
logger.debug("{}: WOL job already running", host);
}
}, () -> {
wolJob = Optional.of(
scheduler.scheduleWithFixedDelay(this::wolCheckPeriodic, 0, interval, TimeUnit.MILLISECONDS));
start();
});
}

public void start() {
wolCount = 0;
wolJob = Optional
.of(scheduler.scheduleWithFixedDelay(this::wolCheckPeriodic, 0, 1000, TimeUnit.MILLISECONDS));
}

public synchronized void cancel() {
wolJob.ifPresent(job -> {
logger.info("{}: cancelling WOL Job", host);
Expand Down Expand Up @@ -255,6 +261,7 @@ private void wolCheckPeriodic() {
if (wolCount++ > WOL_SERVICE_CHECK_COUNT) {
logger.warn("{}: Service NOT found after {} attempts: stopping WOL attempts", host, wolCount);
cancel();
putOffline();
}
}
}
Expand Down Expand Up @@ -563,14 +570,6 @@ private void checkAndCreateServices() {

boolean isOnline = false;

// Websocket services and Smartthings service
if (configuration.isWebsocketProtocol()) {
createService(RemoteControllerService.SERVICE_NAME, "");
if (!configuration.getSmartThingsApiKey().isBlank()) {
createService(SmartThingsApiService.SERVICE_NAME, "");
}
}

// UPnP services
for (Device<?, ?, ?> device : upnpService.getRegistry().getDevices()) {
RemoteDevice rdevice = (RemoteDevice) device;
Expand All @@ -580,6 +579,14 @@ private void checkAndCreateServices() {
}
}

// Websocket services and Smartthings service
if (isOnline && configuration.isWebsocketProtocol()) {
createService(RemoteControllerService.SERVICE_NAME, "");
if (!configuration.getSmartThingsApiKey().isBlank()) {
createService(SmartThingsApiService.SERVICE_NAME, "");
}
}

if (isOnline) {
putOnline();
startPolling();
Expand Down Expand Up @@ -641,6 +648,9 @@ private synchronized Optional<SamsungTvService> createNewService(String type, St
break;
case RemoteControllerService.SERVICE_NAME:
try {
if (configuration.isWebsocketProtocol() && !udn.isEmpty()) {
throw new RemoteControllerException("config is websocket - ignoring UPNP service");
}
service = Optional
.of(new RemoteControllerService(host, configuration.getPort(), !udn.isEmpty(), this));
} catch (RemoteControllerException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ void sendCommand(String cmd) {
remoteControllerWebSocket.openConnection();
}
} catch (IOException | RemoteControllerException e) {
logger.warn("{}: {}: cannot send command", host, this.getClass().getSimpleName(), e);
logger.warn("{}: {}: cannot send command: {}", host, this.getClass().getSimpleName(), e.getMessage());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,13 +248,13 @@ protected Map<String, String> updateResourceState(String actionId) {
return updateResourceState(actionId, Map.of());
}

@SuppressWarnings("null")
protected synchronized Map<String, String> updateResourceState(String actionId, Map<String, String> inputs) {
Map<String, String> inputsMap = new LinkedHashMap<String, String>(Map.of("InstanceID", "0"));
if (actionId.contains("Volume") || actionId.contains("Mute")) {
inputsMap.put("Channel", "Master");
}
inputsMap.putAll(inputs);
@SuppressWarnings("null")
Map<String, String> result = service.invokeAction(this, "RenderingControl", actionId, inputsMap);
result.keySet().stream().filter(a -> !"Result".equals(a))
.forEach(a -> onValueReceived(a, result.get(a), "RenderingControl"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public List<String> getSupportedChannelNames(boolean refresh) {
if (getArtModeSupported()) {
supported.addAll(refresh ? refreshArt : supportedCommandsArt);
}
if (remoteController.noApps() && refresh) {
if (remoteController.noApps() && getPowerState() && refresh) {
supported.addAll(refreshApps);
}
if (!refresh) {
Expand Down Expand Up @@ -164,20 +164,13 @@ public boolean handleCommand(String channel, Command command) {
boolean result = false;
if (!remoteController.isConnected()) {
logger.warn("{}: RemoteController is not connected", host);
try {
remoteController.openConnection();
} catch (RemoteControllerException e) {
logger.warn("{}: Could not re-open connection {}", host, e.getMessage());
return result;
}
return false;
}

if (command == RefreshType.REFRESH) {
switch (channel) {
case SOURCE_APP:
if (getPowerState()) {
remoteController.updateCurrentApp();
}
remoteController.updateCurrentApp();
break;
case ART_IMAGE:
case ART_LABEL:
Expand Down Expand Up @@ -295,11 +288,9 @@ public boolean handleCommand(String channel, Command command) {

case ART_COLOR_TEMPERATURE:
if (command instanceof DecimalType) {
int value = ((DecimalType) command).intValue();
if (value >= -5 && value <= 5) {
remoteController.getArtmodeStatus("set_color_temperature", String.valueOf(value));
result = true;
}
int value = Math.max(-5, Math.min(((DecimalType) command).intValue(), 5));
remoteController.getArtmodeStatus("set_color_temperature", String.valueOf(value));
result = true;
}
break;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
</parameter>
<parameter name="port" type="integer" min="1" max="65535">
<label>TCP Port</label>
<description>TCP port of the Samsung TV (legacy: 1515, 7001, 7676, 15500, 55000 websockets: 8001, 8002).</description>
<description>TCP port of the Samsung TV (legacy: 1515, 7001, 15500, 55000 websockets: 8001, 8002).</description>
<default>55000</default>
</parameter>
<parameter name="macAddress" type="text">
Expand Down

0 comments on commit 58aefe8

Please sign in to comment.