Skip to content

Commit

Permalink
Constants, Properties and fix for not storing key update in initializ…
Browse files Browse the repository at this point in the history
…ed handler.

Signed-off-by: Sebastian Prehn <[email protected]>
  • Loading branch information
sprehn committed Aug 26, 2019
1 parent 8943ef0 commit a983fe8
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,31 @@ public class WebOSBindingConstants {

public static final ServiceType UPNP_SERVICE_TYPE = new ServiceType("lge-com", "webos-second-screen", 1);

/*
* Config names must match property names in
* - WebOSConfiguration
* - parameter names in ESH-INF/config/config.xml
* - property names in ESH-INF/thing/thing-types.xml
*/
public static final String CONFIG_HOST = "host";
public static final String CONFIG_KEY = "key";

// List of all Channel ids. Values have to match ids in thing-types.xml
/*
* Property names must match property names in
* - property names in ESH-INF/thing/thing-types.xml
*/
public static final String PROPERTY_DEVICE_ID = "deviceId";
public static final String PROPERTY_DEVICE_OS = "deviceOS";
public static final String PROPERTY_DEVICE_OS_VERSION = "deviceOSVersion";
public static final String PROPERTY_DEVICE_OS_RELEASE_VERSION = "deviceOSReleaseVersion";
public static final String PROPERTY_LAST_CONNECTED = "lastConnected";
public static final String PROPERTY_MODEL_NAME = "modelName";
public static final String PROPERTY_MANUFACTURER = "manufacturer";

/*
* List of all Channel ids.
* Values have to match ids in thing-types.xml
*/
public static final String CHANNEL_VOLUME = "volume";
public static final String CHANNEL_POWER = "power";
public static final String CHANNEL_MUTE = "mute";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
*/
package org.openhab.binding.lgwebos.internal.discovery;

import static org.openhab.binding.lgwebos.internal.WebOSBindingConstants.THING_TYPE_WEBOSTV;
import static org.openhab.binding.lgwebos.internal.WebOSBindingConstants.*;

import java.time.Instant;
import java.util.Set;

import org.eclipse.jdt.annotation.NonNull;
Expand All @@ -26,7 +25,6 @@
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.jupnp.model.meta.RemoteDevice;
import org.openhab.binding.lgwebos.internal.WebOSBindingConstants;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -43,11 +41,10 @@
public class WebOSUpnpDiscoveryParticipant implements UpnpDiscoveryParticipant {

private final Logger logger = LoggerFactory.getLogger(WebOSUpnpDiscoveryParticipant.class);
private static final String DEVICE_ID = "deviceId";

@Override
public Set<@NonNull ThingTypeUID> getSupportedThingTypeUIDs() {
return WebOSBindingConstants.SUPPORTED_THING_TYPES_UIDS;
return SUPPORTED_THING_TYPES_UIDS;
}

@Override
Expand All @@ -59,22 +56,18 @@ public class WebOSUpnpDiscoveryParticipant implements UpnpDiscoveryParticipant {
}

return DiscoveryResultBuilder.create(thingUID).withLabel(device.getDetails().getFriendlyName())
.withProperty(DEVICE_ID, device.getIdentity().getUdn().getIdentifierString())
.withProperty(WebOSBindingConstants.CONFIG_HOST, device.getIdentity().getDescriptorURL().getHost())
.withProperty(PROPERTY_DEVICE_ID, device.getIdentity().getUdn().getIdentifierString())
.withProperty(CONFIG_HOST, device.getIdentity().getDescriptorURL().getHost())
.withLabel(device.getDetails().getFriendlyName())
.withProperty("modelName", device.getDetails().getModelDetails().getModelName())
.withProperty("modelNumber", device.getDetails().getModelDetails().getModelNumber())
.withProperty("descriptorUrl", device.getIdentity().getDescriptorURL())
.withProperty("serialNumber", device.getDetails().getSerialNumber())
.withProperty("manufacturer", device.getDetails().getManufacturerDetails().getManufacturer())
.withProperty("lastDetection", Instant.now().toString()).withRepresentationProperty(DEVICE_ID)
.withThingType(THING_TYPE_WEBOSTV).build();
.withProperty(PROPERTY_MODEL_NAME, device.getDetails().getModelDetails().getModelName())
.withProperty(PROPERTY_MANUFACTURER, device.getDetails().getManufacturerDetails().getManufacturer())
.withRepresentationProperty(PROPERTY_DEVICE_ID).withThingType(THING_TYPE_WEBOSTV).build();
}

@Override
public @Nullable ThingUID getThingUID(RemoteDevice device) {
logger.trace("Discovered remote device {}", device);
if (device.findService(WebOSBindingConstants.UPNP_SERVICE_TYPE) != null) {
if (device.findService(UPNP_SERVICE_TYPE) != null) {
logger.debug("Found LG WebOS TV: {}", device);
return new ThingUID(THING_TYPE_WEBOSTV, device.getIdentity().getUdn().getIdentifierString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*/
package org.openhab.binding.lgwebos.internal.discovery;

import static org.openhab.binding.lgwebos.internal.WebOSBindingConstants.*;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

Expand All @@ -21,7 +23,6 @@
import org.eclipse.smarthome.config.discovery.DiscoveryService;
import org.jupnp.UpnpService;
import org.jupnp.model.message.header.ServiceTypeHeader;
import org.openhab.binding.lgwebos.internal.WebOSBindingConstants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
Expand Down Expand Up @@ -51,7 +52,7 @@ public class WebOSUpnpDiscoverySearch extends AbstractDiscoveryService {
private @Nullable ScheduledFuture<?> searchJob;

public WebOSUpnpDiscoverySearch() {
super(WebOSBindingConstants.SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SECONDS, true);
super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SECONDS, true);
}

@Reference
Expand All @@ -64,8 +65,8 @@ public void unsetUpnpService(UpnpService upnpService) {
}

private void search() {
logger.trace("Sending Upnp Search Request for {}", WebOSBindingConstants.UPNP_SERVICE_TYPE);
upnpService.getControlPoint().search(new ServiceTypeHeader(WebOSBindingConstants.UPNP_SERVICE_TYPE));
logger.trace("Sending Upnp Search Request for {}", UPNP_SERVICE_TYPE);
upnpService.getControlPoint().search(new ServiceTypeHeader(UPNP_SERVICE_TYPE));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,10 @@ public class WebOSConfiguration {
String key; // name has to match LGWebOSBindingConstants.CONFIG_KEY
// String uuid;
// String mac; // mac address of TV, if set we can attempt wake on lan

@Override
public String toString() {
return "WebOSConfiguration [host=" + host + ", port=" + port + ", key=" + key + "]";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
*
* @author Sebastian Prehn - initial contribution
*/
public class WebOSHandler extends BaseThingHandler implements WebOSTVSocket.Config, WebOSTVSocketListener {
public class WebOSHandler extends BaseThingHandler implements WebOSTVSocket.ConfigProvider, WebOSTVSocketListener {

/*
* constants for device polling
Expand All @@ -65,7 +65,7 @@ public class WebOSHandler extends BaseThingHandler implements WebOSTVSocket.Conf
/*
* error messages
*/
private static final String MSG_MISSING_PARAM = "Missing parameter \"ipAddress\"";
private static final String MSG_MISSING_PARAM = "Missing parameter \"host\"";

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

Expand Down Expand Up @@ -99,7 +99,7 @@ public WebOSHandler(@NonNull Thing thing, WebSocketClient webSocketClient) {
@Override
public void initialize() {
config = getConfigAs(WebOSConfiguration.class);

logger.trace("Handler initialized with config {}", config);
if (config.host == null || config.host.isEmpty()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, MSG_MISSING_PARAM);
return;
Expand Down Expand Up @@ -137,11 +137,6 @@ private void stopReconnectJob() {
}
}

@Override
public void handleConfigurationUpdate(Map<@NonNull String, @NonNull Object> configurationParameters) {
super.handleConfigurationUpdate(configurationParameters);
}

public WebOSTVSocket getSocket() {
return socket;
}
Expand Down Expand Up @@ -171,19 +166,18 @@ public String getKey() {

@Override
public void storeKey(String key) {
config.key = key; // store it current in memory config, avoiding reinitialization via handleConfigurationUpdate
Configuration configuration = editConfiguration();
configuration.put(WebOSBindingConstants.CONFIG_KEY, key);
updateConfiguration(configuration);
}

/*
* @Override
* public void storeDeviceUUID(String uuid) {
* Configuration configuration = editConfiguration();
* configuration.put("uuid", uuid);
* updateConfiguration(configuration);
* }
*/
@Override
public void storeProperties(Map<String, String> properties) {
Map<@NonNull String, @NonNull String> map = editProperties();
map.putAll(properties);
updateProperties(map);
}

// Connectable Device Listener

Expand All @@ -204,14 +198,14 @@ public void onStateChanged(WebOSTVSocket.State old, WebOSTVSocket.State state) {
case DISCONNECTING:
break;
case REGISTERED:
stopReconnectJob(); // maybe give the user an option, not to pair it? This way we will keep asking
updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, "Connected");
channelHandlers.forEach((k, v) -> {
v.refreshSubscription(k, this);
v.onDeviceReady(k, this);
});
break;
case REGISTERING:
stopReconnectJob(); // maybe give the user an option, not to pair it? This way we will keep asking
updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE,
"Registering - You may need to confirm pairing on TV.");
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,18 @@
*/
package org.openhab.binding.lgwebos.internal.handler;

import static org.openhab.binding.lgwebos.internal.WebOSBindingConstants.*;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Queue;
Expand Down Expand Up @@ -100,7 +104,7 @@ public enum State {

private State state = State.DISCONNECTED;

private final Config configStore;
private final ConfigProvider config;
private final WebSocketClient client;
private @Nullable Session session;
private final URI destUri;
Expand All @@ -116,15 +120,15 @@ public enum State {

private Queue<ServiceCommand<?>> offlineBuffer = new LinkedList<>();

public WebOSTVSocket(WebSocketClient client, Config configStore, String ipAddress, int port) {
this.configStore = configStore;
public WebOSTVSocket(WebSocketClient client, ConfigProvider config, String host, int port) {
this.config = config;
this.client = client;
this.keyboardInput = new WebOSTVKeyboardInput(this);

try {
this.destUri = new URI("wss://" + ipAddress + ":" + port);
this.destUri = new URI("wss://" + host + ":" + port);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("IP Address or Host provided is invalid: " + ipAddress);
throw new IllegalArgumentException("IP Address or Host provided is invalid: " + host);
}
}

Expand Down Expand Up @@ -244,7 +248,7 @@ void sendRegister() {
manifest.add("permissions", GSON.toJsonTree(permissions));

JsonObject payload = new JsonObject();
String key = configStore.getKey();
String key = config.getKey();
if (key != null && !key.isEmpty()) {
payload.addProperty("client-key", key);
}
Expand Down Expand Up @@ -395,7 +399,14 @@ public void onMessage(String message) {
logger.warn("No payload in error message: {}", message);
break;
}
// configStore.storeDeviceUUID(response.getPayload().getAsJsonObject().get("deviceUUID").getAsString());
JsonObject deviceDescription = response.getPayload().getAsJsonObject();
Map<String, String> map = new HashMap<>();
map.put(PROPERTY_DEVICE_OS, deviceDescription.get("deviceOS").getAsString());
map.put(PROPERTY_DEVICE_OS_VERSION, deviceDescription.get("deviceOSVersion").getAsString());
map.put(PROPERTY_DEVICE_OS_RELEASE_VERSION,
deviceDescription.get("deviceOSReleaseVersion").getAsString());
map.put(PROPERTY_LAST_CONNECTED, Instant.now().toString());
config.storeProperties(map);
sendRegister();
break;
case "registered":
Expand All @@ -404,7 +415,7 @@ public void onMessage(String message) {
break;
}
this.requests.remove(response.getId());
configStore.storeKey(response.getPayload().getAsJsonObject().get("client-key").getAsString());
config.storeKey(response.getPayload().getAsJsonObject().get("client-key").getAsString());
setState(State.REGISTERED);

while (this.offlineBuffer.size() > 0) {
Expand Down Expand Up @@ -779,9 +790,11 @@ public void onError(String error) {

}

public interface Config {
public interface ConfigProvider {
void storeKey(@Nullable String key);

void storeProperties(Map<String, String> properties);

@Nullable
String getKey();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<config-description uri="thing-type:lgwebos:WebOSTV">
<parameter name="host" type="text" required="true">
<label>Host</label>
<description>Host or IP address of TV.</description>
<description>Hostname or IP address of TV.</description>
<context>network-address</context>
</parameter>
<parameter name="key" type="text" required="false">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,13 @@
</channels>

<properties>
<property name="ipAddress" />
<property name="friendlyName" />
<property name="deviceId" />
<property name="lastConnected" />
<property name="modelName" />
<property name="modelNumber" />
<property name="descriptorUrl" />
<property name="serialNumber" />
<property name="manufacturer" />
<property name="lastConnected" />
<property name="lastDetection" />
<property name="key" />
<property name="manufacturer" />
<property name="deviceOS" />
<property name="deviceOSVersion" />
<property name="deviceOSReleaseVersion" />
</properties>
<representation-property>deviceId</representation-property>

Expand Down

0 comments on commit a983fe8

Please sign in to comment.