Skip to content

Commit

Permalink
fix(18062): 🛠️ work in progress ...
Browse files Browse the repository at this point in the history
... will be rebased and squashed once completed.

Signed-off-by: Patrik Gfeller <[email protected]>
  • Loading branch information
pgfeller committed Jan 12, 2025
1 parent be82a36 commit f1dfb75
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 65 deletions.
4 changes: 3 additions & 1 deletion bundles/org.openhab.binding.huesync/pom.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

Expand Down
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

0 comments on commit f1dfb75

Please sign in to comment.