Skip to content

Commit

Permalink
[pilight] Additional refactoring to resolve compiler warnings
Browse files Browse the repository at this point in the history
Signed-off-by: Niklas Dörfler <niklas@doerfler-el.de>
  • Loading branch information
niklasdoerfler committed Feb 16, 2021
1 parent a6be51b commit 945d9a4
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 84 deletions.
18 changes: 0 additions & 18 deletions bundles/org.openhab.binding.pilight/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,4 @@

<name>openHAB Add-ons :: Bundles :: Pilight Binding</name>

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.4</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -78,30 +78,33 @@ public void run() {

while (!Thread.currentThread().isInterrupted()) {
try {
final Socket socket = this.socket;
final @Nullable Socket socket = this.socket;
if (socket != null && !socket.isClosed()) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
String line = in.readLine();
while (!Thread.currentThread().isInterrupted() && line != null) {
if (!line.isEmpty()) {
logger.trace("Received from pilight: {}", line);
final ObjectMapper inputMapper = this.inputMapper;
if (line.startsWith("{\"message\":\"config\"")) {
callback.configReceived(inputMapper.readValue(line, Message.class).getConfig());
final @Nullable Message message = inputMapper.readValue(line, Message.class);
callback.configReceived(message.getConfig());
} else if (line.startsWith("{\"message\":\"values\"")) {
AllStatus status = inputMapper.readValue(line, AllStatus.class);
final @Nullable AllStatus status = inputMapper.readValue(line, AllStatus.class);
callback.statusReceived(status.getValues());
} else if (line.startsWith("{\"version\":")) {
Version version = inputMapper.readValue(line, Version.class);
final @Nullable Version version = inputMapper.readValue(line, Version.class);
callback.versionReceived(version);
} else if (line.startsWith("{\"status\":")) {
Response response = inputMapper.readValue(line, Response.class);
// currently unused
} else if (line.equals("1")) {
throw new IOException("Connection to pilight lost");
} else {
Status status = inputMapper.readValue(line, Status.class);
final @Nullable Status status = inputMapper.readValue(line, Status.class);
callback.statusReceived(Collections.singletonList(status));
}
}

line = in.readLine();
}
}
Expand Down Expand Up @@ -151,13 +154,13 @@ public void close() {
}

private void disconnect() {
final PrintStream printStream = this.printStream;
final @Nullable PrintStream printStream = this.printStream;
if (printStream != null) {
printStream.close();
this.printStream = null;
}

final Socket socket = this.socket;
final @Nullable Socket socket = this.socket;
if (socket != null) {
try {
socket.close();
Expand All @@ -169,7 +172,7 @@ private void disconnect() {
}

private boolean isConnected() {
final Socket socket = this.socket;
final @Nullable Socket socket = this.socket;
return socket != null && !socket.isClosed();
}

Expand All @@ -195,7 +198,7 @@ private void connect() throws InterruptedException {
PrintStream printStream = new PrintStream(socket.getOutputStream(), true);
printStream.println(outputMapper.writeValueAsString(identification));

Response response = inputMapper.readValue(socket.getInputStream(), Response.class);
final @Nullable Response response = inputMapper.readValue(socket.getInputStream(), Response.class);

if (response.getStatus().equals(Response.SUCCESS)) {
logger.debug("Established connection to pilight server at {}:{}", config.getIpAddress(),
Expand All @@ -209,7 +212,10 @@ private void connect() throws InterruptedException {
logger.debug("pilight client not accepted: {}", response.getStatus());
}
} catch (IOException e) {
this.printStream.close();
final @Nullable PrintStream printStream = this.printStream;
if (printStream != null) {
printStream.close();
}
logger.debug("connect failed: {}", e.getMessage());
callback.updateThingStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
}
Expand All @@ -225,14 +231,17 @@ private void connect() throws InterruptedException {
*/
public void sendAction(Action action) {
delayedActionQueue.add(action);
final @Nullable ScheduledFuture<?> delayedActionWorkerFuture = this.delayedActionWorkerFuture;

if (delayedActionWorkerFuture == null || delayedActionWorkerFuture.isCancelled()) {
delayedActionWorkerFuture = scheduler.scheduleWithFixedDelay(() -> {
this.delayedActionWorkerFuture = scheduler.scheduleWithFixedDelay(() -> {
if (!delayedActionQueue.isEmpty()) {
doSendAction(delayedActionQueue.poll());
} else {
delayedActionWorkerFuture.cancel(false);
delayedActionWorkerFuture = null;
if (delayedActionWorkerFuture != null) {
delayedActionWorkerFuture.cancel(false);
}
this.delayedActionWorkerFuture = null;
}
}, 0, config.getDelay(), TimeUnit.MILLISECONDS);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -84,39 +83,40 @@ protected void startScan() {
ssdp.send(sendPack);
ssdp.setSoTimeout(SSDP_WAIT_TIMEOUT);

final AtomicBoolean loop = new AtomicBoolean(true);
while (loop.get()) {
boolean loop = true;
while (loop) {
DatagramPacket recvPack = new DatagramPacket(new byte[1024], 1024);
ssdp.receive(recvPack);
byte[] recvData = recvPack.getData();

final Scanner scanner = new Scanner(new ByteArrayInputStream(recvData),
StandardCharsets.UTF_8);
scanner.findAll("Location:([0-9.]+):(.*)").forEach(matchResult -> {
loop = scanner.findAll("Location:([0-9.]+):(.*)").peek(matchResult -> {
final String server = matchResult.group(1);
final Integer port = Integer.parseInt(matchResult.group(2));
final String bridgeName = server.replace(".", "") + "" + port;

logger.debug("Found pilight daemon at {}:{}", server, port);

Map<String, Object> properties = new HashMap<>();
properties.put(PilightBindingConstants.PROPERTY_IP_ADDRESS, server);
properties.put(PilightBindingConstants.PROPERTY_PORT, port);
properties.put(PilightBindingConstants.PROPERTY_NAME, bridgeName);

ThingUID uid = new ThingUID(PilightBindingConstants.THING_TYPE_BRIDGE,
server.replace(".", "") + "" + port);
ThingUID uid = new ThingUID(PilightBindingConstants.THING_TYPE_BRIDGE, bridgeName);

DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties)
.withRepresentationProperty(PilightBindingConstants.PROPERTY_NAME)
.withLabel("Pilight Bridge (" + server + ")").build();

thingDiscovered(result);
loop.set(false);
});
}).count() == 0;
}
}
}
}
} catch (IOException e) {
if (!e.getMessage().equals("Receive timed out")) {
if (e.getMessage() != null && !"Receive timed out".equals(e.getMessage())) {
logger.warn("Unable to enumerate the local network interfaces {}", e.getMessage());
}
}
Expand All @@ -131,18 +131,20 @@ protected synchronized void stopScan() {
@Override
protected void startBackgroundDiscovery() {
logger.debug("Start Pilight device background discovery");
final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
if (backgroundDiscoveryJob == null || backgroundDiscoveryJob.isCancelled()) {
backgroundDiscoveryJob = scheduler.scheduleWithFixedDelay(this::startScan, 5,
this.backgroundDiscoveryJob = scheduler.scheduleWithFixedDelay(this::startScan, 5,
AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC, TimeUnit.SECONDS);
}
}

@Override
protected void stopBackgroundDiscovery() {
logger.debug("Stop Pilight device background discovery");
final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
if (backgroundDiscoveryJob != null) {
backgroundDiscoveryJob.cancel(true);
backgroundDiscoveryJob = null;
this.backgroundDiscoveryJob = null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,10 @@
import org.openhab.core.config.discovery.AbstractDiscoveryService;
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -45,7 +43,6 @@
* @author Niklas Dörfler - Initial contribution
*/
@NonNullByDefault
@Component(service = DiscoveryService.class, immediate = true, configurationPid = "discovery.pilight")
public class PilightDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {

private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = PilightHandlerFactory.SUPPORTED_THING_TYPES_UIDS;
Expand Down Expand Up @@ -79,7 +76,7 @@ protected void startScan() {
config.getDevices().forEach((deviceId, device) -> {
if (this.pilightBridgeHandler != null) {
final Optional<Status> status = allStatus.stream()
.filter(s -> deviceId.equals(s.getDevices().get(0))).findFirst();
.filter(s -> s.getDevices().contains(deviceId)).findFirst();

final ThingTypeUID thingTypeUID;
final String typeString;
Expand All @@ -106,29 +103,37 @@ protected void startScan() {
typeString = "Generic";
}

final ThingUID thingUID = new ThingUID(thingTypeUID,
this.pilightBridgeHandler.getThing().getUID(), deviceId);
final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
if (pilightBridgeHandler != null) {
final ThingUID thingUID = new ThingUID(thingTypeUID,
pilightBridgeHandler.getThing().getUID(), deviceId);

final Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_NAME, deviceId);
final Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_NAME, deviceId);

DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
.withThingType(thingTypeUID).withProperties(properties).withBridge(bridgeUID)
.withRepresentationProperty(deviceId)
.withLabel("Pilight " + typeString + " Device '" + deviceId + "'").build();
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
.withThingType(thingTypeUID).withProperties(properties).withBridge(bridgeUID)
.withRepresentationProperty(PROPERTY_NAME)
.withLabel("Pilight " + typeString + " Device '" + deviceId + "'").build();

thingDiscovered(discoveryResult);
thingDiscovered(discoveryResult);
}
}
});
});

pilightBridgeHandler.refreshConfigAndStatus();
final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
if (pilightBridgeHandler != null) {
pilightBridgeHandler.refreshConfigAndStatus();
}
}
}

@Override
protected synchronized void stopScan() {
super.stopScan();
configFuture.cancel(true);
statusFuture.cancel(true);
if (bridgeUID != null) {
removeOlderResults(getTimestampOfLastScan(), bridgeUID);
}
Expand All @@ -137,26 +142,31 @@ protected synchronized void stopScan() {
@Override
protected void startBackgroundDiscovery() {
logger.debug("Start Pilight device background discovery");
final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
if (backgroundDiscoveryJob == null || backgroundDiscoveryJob.isCancelled()) {
backgroundDiscoveryJob = scheduler.scheduleWithFixedDelay(this::startScan, 20,
this.backgroundDiscoveryJob = scheduler.scheduleWithFixedDelay(this::startScan, 20,
AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC, TimeUnit.SECONDS);
}
}

@Override
protected void stopBackgroundDiscovery() {
logger.debug("Stop Pilight device background discovery");
final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
if (backgroundDiscoveryJob != null) {
backgroundDiscoveryJob.cancel(true);
backgroundDiscoveryJob = null;
this.backgroundDiscoveryJob = null;
}
}

@Override
public void setThingHandler(final ThingHandler handler) {
if (handler instanceof PilightBridgeHandler) {
pilightBridgeHandler = (PilightBridgeHandler) handler;
bridgeUID = pilightBridgeHandler.getThing().getUID();
this.pilightBridgeHandler = (PilightBridgeHandler) handler;
final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
if (pilightBridgeHandler != null) {
bridgeUID = pilightBridgeHandler.getThing().getUID();
}
}
}

Expand All @@ -168,6 +178,7 @@ public void setThingHandler(final ThingHandler handler) {
@Override
public void activate() {
super.activate(null);
final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
if (pilightBridgeHandler != null) {
pilightBridgeHandler.registerDiscoveryListener(this);
}
Expand All @@ -179,6 +190,7 @@ public void deactivate() {
removeOlderResults(getTimestampOfLastScan(), bridgeUID);
}

final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
if (pilightBridgeHandler != null) {
pilightBridgeHandler.unregisterDiscoveryListener();
}
Expand All @@ -192,9 +204,7 @@ public void deactivate() {
* @param config config to get
*/
public void setConfig(Config config) {
if (!configFuture.isDone()) {
configFuture.complete(config);
}
configFuture.complete(config);
}

/**
Expand All @@ -203,9 +213,7 @@ public void setConfig(Config config) {
* @param status list of status objects
*/
public void setStatus(List<Status> status) {
if (!statusFuture.isDone()) {
statusFuture.complete(status);
}
statusFuture.complete(status);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public void handleCommand(ChannelUID channelUID, Command command) {
public void initialize() {
PilightBridgeConfiguration config = getConfigAs(PilightBridgeConfiguration.class);

final @Nullable PilightDeviceDiscoveryService discoveryService = this.discoveryService;
PilightConnector connector = new PilightConnector(config, new IPilightCallback() {
@Override
public void updateThingStatus(ThingStatus status, ThingStatusDetail statusDetail,
Expand Down Expand Up @@ -224,6 +225,7 @@ private void processConfig(Config config) {
}
}

final @Nullable PilightDeviceDiscoveryService discoveryService = this.discoveryService;
if (discoveryService != null) {
discoveryService.setConfig(config);
}
Expand Down
Loading

0 comments on commit 945d9a4

Please sign in to comment.