Skip to content

Commit

Permalink
[plugwise] Cleanup code (openhab#15688)
Browse files Browse the repository at this point in the history
The cleanup includes:

* Use lambdas
* Use enhanced switches
* Make abstract class constructors protected
* Fix typos

Signed-off-by: Wouter Born <github@maindrain.net>
  • Loading branch information
wborn authored Oct 2, 2023
1 parent 86f8bc9 commit 2bf2246
Show file tree
Hide file tree
Showing 21 changed files with 84 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ public class PlugwiseBindingConstants {
// List of all configuration properties
public static final String CONFIG_PROPERTY_MAC_ADDRESS = "macAddress";
public static final String CONFIG_PROPERTY_RECALIBRATE = "recalibrate";
public static final String CONFIG_PROPERTY_SERIAL_PORT = "serialPort";
public static final String CONFIG_PROPERTY_UPDATE_CONFIGURATION = "updateConfiguration";
public static final String CONFIG_PROPERTY_UPDATE_INTERVAL = "updateInterval";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,26 +60,23 @@ public class PlugwiseCommunicationContext {

public static final int MAX_BUFFER_SIZE = 1024;

private static final Comparator<? super @Nullable PlugwiseQueuedMessage> QUEUED_MESSAGE_COMPERATOR = new Comparator<@Nullable PlugwiseQueuedMessage>() {
@Override
public int compare(@Nullable PlugwiseQueuedMessage o1, @Nullable PlugwiseQueuedMessage o2) {
if (o1 == null || o2 == null) {
return -1;
}
int result = o1.getPriority().compareTo(o2.getPriority());
if (result == 0) {
result = o1.getDateTime().compareTo(o2.getDateTime());
}
return result;
private static final Comparator<? super @Nullable PlugwiseQueuedMessage> QUEUED_MESSAGE_COMPARATOR = (o1, o2) -> {
if (o1 == null || o2 == null) {
return -1;
}
int result = o1.getPriority().compareTo(o2.getPriority());
if (result == 0) {
result = o1.getDateTime().compareTo(o2.getDateTime());
}
return result;
};

private final Logger logger = LoggerFactory.getLogger(PlugwiseCommunicationContext.class);
private final BlockingQueue<@Nullable AcknowledgementMessage> acknowledgedQueue = new ArrayBlockingQueue<>(
MAX_BUFFER_SIZE, true);
private final BlockingQueue<@Nullable Message> receivedQueue = new ArrayBlockingQueue<>(MAX_BUFFER_SIZE, true);
private final PriorityBlockingQueue<@Nullable PlugwiseQueuedMessage> sendQueue = new PriorityBlockingQueue<>(
MAX_BUFFER_SIZE, QUEUED_MESSAGE_COMPERATOR);
MAX_BUFFER_SIZE, QUEUED_MESSAGE_COMPARATOR);
private final BlockingQueue<@Nullable PlugwiseQueuedMessage> sentQueue = new ArrayBlockingQueue<>(MAX_BUFFER_SIZE,
true);
private final ReentrantLock sentQueueLock = new ReentrantLock();
Expand Down Expand Up @@ -141,7 +138,7 @@ private SerialPortIdentifier findSerialPortIdentifier() throws PlugwiseInitializ
}

// Build exception message when port not found
String availablePorts = serialPortManager.getIdentifiers().map(id -> id.getName())
String availablePorts = serialPortManager.getIdentifiers().map(SerialPortIdentifier::getName)
.collect(Collectors.joining(System.lineSeparator()));

throw new PlugwiseInitializationException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,19 @@ public abstract class PlugwiseDeviceTask {

private @Nullable ScheduledFuture<?> future;

private Runnable scheduledRunnable = new Runnable() {
@Override
public void run() {
try {
lock.lock();
logger.debug("Running '{}' Plugwise task for {} ({})", name, deviceType, macAddress);
runTask();
} catch (Exception e) {
logger.warn("Error while running '{}' Plugwise task for {} ({})", name, deviceType, macAddress, e);
} finally {
lock.unlock();
}
private final Runnable scheduledRunnable = () -> {
try {
lock.lock();
logger.debug("Running '{}' Plugwise task for {} ({})", getName(), deviceType, macAddress);
runTask();
} catch (Exception e) {
logger.warn("Error while running '{}' Plugwise task for {} ({})", getName(), deviceType, macAddress, e);
} finally {
lock.unlock();
}
};

public PlugwiseDeviceTask(String name, ScheduledExecutorService scheduler) {
protected PlugwiseDeviceTask(String name, ScheduledExecutorService scheduler) {
this.name = name;
this.scheduler = scheduler;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public void notifyListeners(Message message) {
for (PlugwiseFilteredMessageListener filteredListener : filteredListeners) {
if (filteredListener.matches(message)) {
try {
filteredListener.getListener().handleReponseMessage(message);
filteredListener.getListener().handleResponseMessage(message);
} catch (Exception e) {
logger.warn("Listener failed to handle message: {}", message, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.TooManyListenersException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -159,9 +158,7 @@ private void processMessage(Message message) {
try {
context.getSentQueueLock().lock();

Iterator<@Nullable PlugwiseQueuedMessage> messageIterator = context.getSentQueue().iterator();
while (messageIterator.hasNext()) {
PlugwiseQueuedMessage queuedSentMessage = messageIterator.next();
for (PlugwiseQueuedMessage queuedSentMessage : context.getSentQueue()) {
if (queuedSentMessage != null
&& queuedSentMessage.getMessage().getSequenceNumber() == message.getSequenceNumber()) {
logger.debug("Removing from sentQueue: {}", queuedSentMessage.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class PlugwiseMessageSender {

private class MessageSenderThread extends Thread {

private int messageWaitTime;
private final int messageWaitTime;

public MessageSenderThread(int messageWaitTime) {
super("OH-binding-" + context.getBridgeUID() + "-message-sender");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ private void createDiscoveryResult(DiscoveredNode node) {
ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, mac);

thingDiscovered(DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID)
.withLabel("Plugwise " + node.deviceType.toString())
.withLabel("Plugwise " + node.deviceType)
.withProperty(PlugwiseBindingConstants.CONFIG_PROPERTY_MAC_ADDRESS, mac)
.withProperties(new HashMap<>(node.properties))
.withRepresentationProperty(PlugwiseBindingConstants.PROPERTY_MAC_ADDRESS).build());
Expand Down Expand Up @@ -215,7 +215,7 @@ private void handleInformationResponse(InformationResponseMessage message) {
}

@Override
public void handleReponseMessage(Message message) {
public void handleResponseMessage(Message message) {
switch (message.getType()) {
case ANNOUNCE_AWAKE_REQUEST:
handleAnnounceAwakeRequest((AnnounceAwakeRequestMessage) message);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ public static String upperUnderscoreToLowerCamel(String text) {
final String delimiter = "_";
StringBuilder upperCamelBuilder = new StringBuilder(text.length());
for (String str : text.split(delimiter)) {
if (upperCamelBuilder.isEmpty() && str.length() > 0) {
if (upperCamelBuilder.isEmpty() && !str.isEmpty()) {
upperCamelBuilder.append(str.substring(0, 1).toLowerCase());
} else if (str.length() > 0) {
} else if (!str.isEmpty()) {
upperCamelBuilder.append(str.substring(0, 1).toUpperCase());
}
if (str.length() > 1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public void start() {
private @Nullable LocalDateTime lastConfigurationUpdateSend;
private int unansweredPings;

public AbstractPlugwiseThingHandler(Thing thing) {
protected AbstractPlugwiseThingHandler(Thing thing) {
super(thing);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public abstract class AbstractSleepingEndDeviceHandler extends AbstractPlugwiseT

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

public AbstractSleepingEndDeviceHandler(Thing thing) {
protected AbstractSleepingEndDeviceHandler(Thing thing) {
super(thing);
}

Expand Down Expand Up @@ -72,12 +72,11 @@ protected void handleInformationResponse(InformationResponseMessage message) {
}

@Override
public void handleReponseMessage(Message message) {
public void handleResponseMessage(Message message) {
updateLastSeen();

switch (message.getType()) {
case ACKNOWLEDGEMENT_V1:
case ACKNOWLEDGEMENT_V2:
case ACKNOWLEDGEMENT_V1, ACKNOWLEDGEMENT_V2:
handleAcknowledgement((AcknowledgementMessage) message);
break;
case ANNOUNCE_AWAKE_REQUEST:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ public void runTask() {
if (deviceType == DeviceType.CIRCLE_PLUS) {
// The Circle+ real-time clock needs to be updated first to prevent clock sync issues
sendCommandMessage(new RealTimeClockSetRequestMessage(macAddress, LocalDateTime.now()));
scheduler.schedule(() -> {
sendCommandMessage(new ClockSetRequestMessage(macAddress, LocalDateTime.now()));
}, 5, TimeUnit.SECONDS);
scheduler.schedule(
() -> sendCommandMessage(new ClockSetRequestMessage(macAddress, LocalDateTime.now())), 5,
TimeUnit.SECONDS);
} else {
sendCommandMessage(new ClockSetRequestMessage(macAddress, LocalDateTime.now()));
}
Expand Down Expand Up @@ -467,12 +467,11 @@ private void handleRealTimeClockGetResponse(RealTimeClockGetResponseMessage mess
}

@Override
public void handleReponseMessage(Message message) {
public void handleResponseMessage(Message message) {
updateLastSeen();

switch (message.getType()) {
case ACKNOWLEDGEMENT_V1:
case ACKNOWLEDGEMENT_V2:
case ACKNOWLEDGEMENT_V1, ACKNOWLEDGEMENT_V2:
handleAcknowledgement((AcknowledgementMessage) message);
break;
case CLOCK_GET_RESPONSE:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,13 @@ protected void handleAcknowledgement(AcknowledgementMessage message) {
}

@Override
public void handleReponseMessage(Message message) {
public void handleResponseMessage(Message message) {
switch (message.getType()) {
case SENSE_REPORT_REQUEST:
handleSenseReportRequestMessage((SenseReportRequestMessage) message);
break;
default:
super.handleReponseMessage(message);
super.handleResponseMessage(message);
break;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,9 @@ private void handleNetworkStatusResponse(NetworkStatusResponseMessage message) {
}

@Override
public void handleReponseMessage(Message message) {
public void handleResponseMessage(Message message) {
switch (message.getType()) {
case ACKNOWLEDGEMENT_V1:
case ACKNOWLEDGEMENT_V2:
case ACKNOWLEDGEMENT_V1, ACKNOWLEDGEMENT_V2:
handleAcknowledgement((AcknowledgementMessage) message);
break;
case DEVICE_INFORMATION_RESPONSE:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@
@NonNullByDefault
public interface PlugwiseMessageListener {

void handleReponseMessage(Message message);
void handleResponseMessage(Message message);
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ public static ExtensionCode forValue(int value) {
return TYPES_BY_VALUE.get(value);
}

private int identifier;
private final int identifier;

private ExtensionCode(int value) {
ExtensionCode(int value) {
identifier = value;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public enum AwakeReason {
WAKEUP_BUTTON(5);

public static AwakeReason forValue(int value) {
return Arrays.stream(values()).filter(awakeReason -> awakeReason.id == value).findFirst().get();
return Arrays.stream(values()).filter(awakeReason -> awakeReason.id == value).findFirst().orElse(null);
}

private final int id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@ protected String payloadToHexString() {
String minutes = String.format("%04X",
(utcDateTime.getDayOfMonth() - 1) * 24 * 60 + (utcDateTime.getHour() * 60) + utcDateTime.getMinute());
// If we set logaddress to FFFFFFFFF then previous buffered data will be kept by the Circle+
String logaddress = "FFFFFFFF";
String logAddress = "FFFFFFFF";
String hour = String.format("%02X", utcDateTime.getHour());
String minute = String.format("%02X", utcDateTime.getMinute());
String second = String.format("%02X", utcDateTime.getSecond());
// Monday = 0, ... , Sunday = 6
String dayOfWeek = String.format("%02X", utcDateTime.getDayOfWeek().getValue() - 1);

return year + month + minutes + logaddress + hour + minute + second + dayOfWeek;
return year + month + minutes + logAddress + hour + minute + second + dayOfWeek;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,24 +84,16 @@ public int getYear() {
}

private DeviceType intToDeviceType(int i) {
switch (i) {
case 0:
return DeviceType.STICK;
case 1:
return DeviceType.CIRCLE_PLUS;
case 2:
return DeviceType.CIRCLE;
case 3:
return DeviceType.SWITCH;
case 5:
return DeviceType.SENSE;
case 6:
return DeviceType.SCAN;
case 9:
return DeviceType.STEALTH;
default:
return null;
}
return switch (i) {
case 0 -> DeviceType.STICK;
case 1 -> DeviceType.CIRCLE_PLUS;
case 2 -> DeviceType.CIRCLE;
case 3 -> DeviceType.SWITCH;
case 5 -> DeviceType.SENSE;
case 6 -> DeviceType.SCAN;
case 9 -> DeviceType.STEALTH;
default -> null;
};
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
*/
package org.openhab.binding.plugwise.internal.protocol;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import org.openhab.binding.plugwise.internal.protocol.field.MACAddress;
import org.openhab.binding.plugwise.internal.protocol.field.MessageType;
Expand Down Expand Up @@ -40,14 +40,7 @@ public static String getCRC(String string) {
int crc = 0x0000;
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)

byte[] bytes = new byte[0];
try {
bytes = string.getBytes("ASCII");
} catch (UnsupportedEncodingException e) {
return "";
}

for (byte b : bytes) {
for (byte b : string.getBytes(StandardCharsets.US_ASCII)) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7 - i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
Expand All @@ -69,11 +62,11 @@ public static String getCRC(String string) {

protected String payload;

public Message(MessageType messageType) {
protected Message(MessageType messageType) {
this(messageType, null, null, null);
}

public Message(MessageType messageType, Integer sequenceNumber, MACAddress macAddress, String payload) {
protected Message(MessageType messageType, Integer sequenceNumber, MACAddress macAddress, String payload) {
this.type = messageType;
this.sequenceNumber = sequenceNumber;
this.macAddress = macAddress;
Expand All @@ -84,19 +77,19 @@ public Message(MessageType messageType, Integer sequenceNumber, MACAddress macAd
}
}

public Message(MessageType messageType, Integer sequenceNumber, String payload) {
protected Message(MessageType messageType, Integer sequenceNumber, String payload) {
this(messageType, sequenceNumber, null, payload);
}

public Message(MessageType messageType, MACAddress macAddress) {
protected Message(MessageType messageType, MACAddress macAddress) {
this(messageType, null, macAddress, null);
}

public Message(MessageType messageType, MACAddress macAddress, String payload) {
protected Message(MessageType messageType, MACAddress macAddress, String payload) {
this(messageType, null, macAddress, payload);
}

public Message(MessageType messageType, String payload) {
protected Message(MessageType messageType, String payload) {
this(messageType, null, null, payload);
}

Expand Down
Loading

0 comments on commit 2bf2246

Please sign in to comment.