Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] fix(18062): 🛠️ [huesync] Configuration (API Token) lost if device goes offline #18100

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
*/
package org.openhab.binding.huesync.internal.factory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.util.Collections;
import java.util.Set;

Expand All @@ -31,8 +28,6 @@
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* The {@link HueSyncHandlerFactory} is responsible for creating things and
Expand All @@ -44,9 +39,7 @@
@NonNullByDefault
@Component(configurationPid = "binding.huesync", service = ThingHandlerFactory.class)
public class HueSyncHandlerFactory extends BaseThingHandlerFactory {

private final HttpClientFactory httpClientFactory;
private final Logger logger = LoggerFactory.getLogger(HueSyncHandlerFactory.class);

@Activate
public HueSyncHandlerFactory(@Reference final HttpClientFactory httpClientFactory) throws Exception {
Expand All @@ -66,12 +59,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();

if (HueSyncConstants.THING_TYPE_UID.equals(thingTypeUID)) {
try {
return new HueSyncHandler(thing, this.httpClientFactory);
} catch (IOException | URISyntaxException | CertificateException e) {
this.logger.warn("It was not possible to create a handler for {}: {}", thingTypeUID.getId(),
e.getMessage());
}
return new HueSyncHandler(thing, this.httpClientFactory);
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,60 +73,67 @@ public class HueSyncHandler extends BaseThingHandler {
Map<String, @Nullable ScheduledFuture<?>> tasks = new HashMap<>();

private Optional<HueSyncDevice> deviceInfo = Optional.empty();
private Optional<HueSyncDeviceConnection> connection = Optional.empty();

private final HueSyncDeviceConnection connection;
private final HttpClient httpClient;

public HueSyncHandler(Thing thing, HttpClientFactory httpClientFactory)
throws CertificateException, IOException, URISyntaxException {
public HueSyncHandler(Thing thing, HttpClientFactory httpClientFactory) {
super(thing);

this.httpClient = httpClientFactory.getCommonHttpClient();
}

// #region override
@Override
protected Configuration editConfiguration() {
this.logger.debug("Configuration change detected.");

this.connection = new HueSyncDeviceConnection(this.httpClient, this.getConfigAs(HueSyncConfiguration.class));
return new Configuration(this.thing.getConfiguration().getProperties());
}
// #endregion

// #region private
private Runnable initializeConnection() {
return () -> {
this.deviceInfo = Optional.ofNullable(this.connection.getDeviceInfo());
this.deviceInfo.ifPresent(info -> {
setProperty(Thing.PROPERTY_SERIAL_NUMBER, info.uniqueId != null ? info.uniqueId : "");
setProperty(Thing.PROPERTY_MODEL_ID, info.deviceType);
setProperty(Thing.PROPERTY_FIRMWARE_VERSION, info.firmwareVersion);

setProperty(HueSyncHandler.PROPERTY_API_VERSION, String.format("%d", info.apiLevel));

try {
this.checkCompatibility();
} catch (HueSyncApiException e) {
this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
} finally {
this.startTasks();
}
});
try {
var connectionInstance = new HueSyncDeviceConnection(this.httpClient,
this.getConfigAs(HueSyncConfiguration.class));

this.connection = Optional.of(connectionInstance);

this.deviceInfo = Optional.ofNullable(connectionInstance.getDeviceInfo());
this.deviceInfo.ifPresent(info -> {
setProperty(Thing.PROPERTY_SERIAL_NUMBER, info.uniqueId != null ? info.uniqueId : "");
setProperty(Thing.PROPERTY_MODEL_ID, info.deviceType);
setProperty(Thing.PROPERTY_FIRMWARE_VERSION, info.firmwareVersion);

setProperty(HueSyncHandler.PROPERTY_API_VERSION, String.format("%d", info.apiLevel));

try {
this.checkCompatibility();
} catch (HueSyncApiException e) {
this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
} finally {
this.startTasks(connectionInstance);
}
});
} catch (CertificateException | URISyntaxException | IOException | NoSuchElementException ex) {
this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getLocalizedMessage());
}
};
}

private void stopTask(@Nullable ScheduledFuture<?> task) {
if (task == null || task.isCancelled() || task.isDone()) {
return;
}

task.cancel(true);
}

private @Nullable ScheduledFuture<?> executeTask(Runnable task, long initialDelay, long interval) {
return scheduler.scheduleWithFixedDelay(task, initialDelay, interval, TimeUnit.SECONDS);
}

private void startTasks() {
private void startTasks(HueSyncDeviceConnection connection) {
this.stopTasks();

this.connection.updateConfiguration(this.getConfigAs(HueSyncConfiguration.class));
connection.updateConfiguration(this.getConfigAs(HueSyncConfiguration.class));

Runnable task = null;
String id = this.connection.isRegistered() ? POLL : REGISTER;
String id = connection.isRegistered() ? POLL : REGISTER;

this.logger.debug("startTasks - [{}]", id);

Expand All @@ -140,8 +147,8 @@ private void startTasks() {

this.updateStatus(ThingStatus.ONLINE);

task = new HueSyncUpdateTask(this.connection, this.deviceInfo.get(),
deviceStatus -> this.handleUpdate(deviceStatus));
task = new HueSyncUpdateTask(connection, this.deviceInfo.get(),
deviceStatus -> this.handleUpdate(deviceStatus, connection));
}
case REGISTER -> {
initialDelay = HueSyncConstants.REGISTRATION_INITIAL_DELAY;
Expand All @@ -150,8 +157,8 @@ private void startTasks() {
this.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
"@text/thing.config.huesync.box.registration");

task = new HueSyncRegistrationTask(this.connection, this.deviceInfo.get(),
registration -> this.handleRegistration(registration));
task = new HueSyncRegistrationTask(connection, this.deviceInfo.get(),
registration -> this.handleRegistration(registration, connection));
}
}

Expand All @@ -171,7 +178,15 @@ private void stopTasks() {
"@text/thing.config.huesync.box.registration");
}

private void handleUpdate(@Nullable HueSyncUpdateTaskResult dto) {
private void stopTask(@Nullable ScheduledFuture<?> task) {
if (task == null || task.isCancelled() || task.isDone()) {
return;
}

task.cancel(true);
}

private void handleUpdate(@Nullable HueSyncUpdateTaskResult dto, HueSyncDeviceConnection connection) {
try {
HueSyncUpdateTaskResult update = Optional.ofNullable(dto).get();

Expand All @@ -184,14 +199,7 @@ private void handleUpdate(@Nullable HueSyncUpdateTaskResult dto) {
this.updateHdmiInformation(Optional.ofNullable(update.hdmiStatus).get());
this.updateExecutionInformation(Optional.ofNullable(update.execution).get());
} catch (NoSuchElementException e) {
Configuration configuration = this.editConfiguration();

configuration.put(HueSyncConstants.REGISTRATION_ID, "");
configuration.put(HueSyncConstants.API_TOKEN, "");

this.updateConfiguration(configuration);

this.startTasks();
this.startTasks(connection);
}
}

Expand Down Expand Up @@ -240,7 +248,7 @@ private void updateExecutionInformation(HueSyncExecution executionStatus) {
this.updateState(HueSyncConstants.CHANNELS.COMMANDS.BRIGHTNESS, new DecimalType(executionStatus.brightness));
}

private void handleRegistration(HueSyncRegistration registration) {
private void handleRegistration(HueSyncRegistration registration, HueSyncDeviceConnection connection) {
this.stopTasks();

setProperty(HueSyncConstants.REGISTRATION_ID, registration.registrationId);
Expand All @@ -252,7 +260,7 @@ private void handleRegistration(HueSyncRegistration registration) {

this.updateConfiguration(configuration);

this.startTasks();
this.startTasks(connection);
}

private void checkCompatibility() throws HueSyncApiException {
Expand Down Expand Up @@ -308,8 +316,8 @@ public void initialize() {

@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (thing.getStatus() != ThingStatus.ONLINE) {
this.logger.warn("Device status: {} - Command {} for chanel {} will be ignored",
if (thing.getStatus() != ThingStatus.ONLINE || this.connection.isEmpty()) {
this.logger.warn("Device status: {} - Command {} for channel {} will be ignored",
thing.getStatus().toString(), command.toFullString(), channelUID.toString());
return;
}
Expand All @@ -321,7 +329,7 @@ public void handleCommand(ChannelUID channelUID, Command command) {
return;
}

this.connection.executeCommand(channel, command);
this.connection.get().executeCommand(channel, command);
}

@Override
Expand All @@ -330,7 +338,7 @@ public void dispose() {

try {
this.stopTasks();
this.connection.dispose();
this.connection.get().dispose();
} catch (Exception e) {
this.logger.warn("{}", e.getMessage());
} finally {
Expand All @@ -342,7 +350,11 @@ public void dispose() {
public void handleRemoval() {
super.handleRemoval();

this.connection.unregisterDevice();
try {
this.connection.orElseThrow().unregisterDevice();
} catch (NoSuchElementException e) {

}
}

// #endregion
Expand Down