Skip to content

Commit

Permalink
[emotiva] Improve logging, retry job, static typing and type inferenc…
Browse files Browse the repository at this point in the history
…e. (openhab#17596)

* Add and improve logging when trying to map channel change to Emotiva Control Commands.
* Improve logging of notifications and keep alive job.
* Improve checking of retry job status.
* Improve static typing of previous state.
* Use type inference in selected places.

Signed-off-by: Espen Fossen <espenaf@junta.no>
Signed-off-by: Ciprian Pascu <contact@ciprianpascu.ro>
  • Loading branch information
espenaf authored and Ciprian Pascu committed Jan 2, 2025
1 parent 7a45a61 commit 29cca2c
Show file tree
Hide file tree
Showing 32 changed files with 358 additions and 220 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,6 @@ public class EmotivaBindingConstants {
*/
static final int DEFAULT_KEEP_ALIVE_IN_MILLISECONDS = 7500;

/** State name for storing keepAlive timestamp messages */
public static final String LAST_SEEN_STATE_NAME = "no-channel#last-seen";

/**
* Default Emotiva device considered list in milliseconds.
* {@link org.openhab.binding.emotiva.internal.dto.ControlDTO}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public static String getMenuPanelColumnLabel(int column) {

public static String updateProgress(double progressPercentage) {
final int width = 30;
StringBuilder sb = new StringBuilder();
var sb = new StringBuilder();

sb.append("[");
int i = 0;
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.openhab.binding.emotiva.internal.protocol.EmotivaControlCommands.band_fm;
import static org.openhab.binding.emotiva.internal.protocol.EmotivaControlCommands.channel_1;

import java.time.Instant;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
Expand All @@ -44,6 +45,7 @@ public class EmotivaProcessorState {
private EnumMap<EmotivaControlCommands, String> sourcesMainZone;
private EnumMap<EmotivaControlCommands, String> sourcesZone2;
private final EnumMap<EmotivaSubscriptionTags, String> modes;
private Instant lastSeen = Instant.EPOCH;

private EnumMap<EmotivaControlCommands, String> tunerChannels = new EnumMap<>(
Map.ofEntries(Map.entry(channel_1, channel_1.getLabel()),
Expand Down Expand Up @@ -146,4 +148,12 @@ public void updateModes(EmotivaSubscriptionTags tag, String value) {
public void removeChannel(String channel) {
channelStateMap.remove(channel);
}

public void updateLastSeen(Instant instant) {
lastSeen = instant;
}

public Instant getLastSeen() {
return lastSeen;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public EmotivaUdpBroadcastService(String broadcastAddress) throws IllegalArgumen
*/
public Optional<DiscoveryResult> discoverThings() {
try {
final DatagramPacket receivePacket = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
final var receivePacket = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
// No need to call close first, because the caller of this method already has done it.

discoverSocket = new DatagramSocket(
Expand All @@ -82,7 +82,7 @@ public Optional<DiscoveryResult> discoverThings() {

byte[] emotivaPingDTO = xmlUtils.marshallEmotivaDTO(new EmotivaPingDTO(PROTOCOL_V3.name()))
.getBytes(Charset.defaultCharset());
final DatagramPacket discoverPacket = new DatagramPacket(emotivaPingDTO, emotivaPingDTO.length, broadcast,
final var discoverPacket = new DatagramPacket(emotivaPingDTO, emotivaPingDTO.length, broadcast,
EmotivaBindingConstants.DEFAULT_PING_PORT);

DatagramSocket localDatagramSocket = discoverSocket;
Expand Down Expand Up @@ -146,7 +146,7 @@ public void closeDiscoverSocket() {
*/
private Optional<DiscoveryResult> thingDiscovered(DatagramPacket packet) {
final String ipAddress = packet.getAddress().getHostAddress();
String udpResponse = new String(packet.getData(), 0, packet.getLength() - 1, StandardCharsets.UTF_8);
final var udpResponse = new String(packet.getData(), 0, packet.getLength() - 1, StandardCharsets.UTF_8);

Object object;
try {
Expand All @@ -159,8 +159,7 @@ private Optional<DiscoveryResult> thingDiscovered(DatagramPacket packet) {
if (object instanceof EmotivaTransponderDTO answerDto) {
logger.trace("Processing Received '{}' with '{}' ", EmotivaTransponderDTO.class.getSimpleName(),
udpResponse);
final ThingUID thingUid = new ThingUID(
THING_PROCESSOR + AbstractUID.SEPARATOR + ipAddress.replace(".", ""));
final var thingUid = new ThingUID(THING_PROCESSOR + AbstractUID.SEPARATOR + ipAddress.replace(".", ""));
final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUid)
.withThingType(THING_PROCESSOR).withProperty("ipAddress", ipAddress)
.withProperty("controlPort", answerDto.getControl().getControlPort())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ private void listenUnhandledInterruption() throws InterruptedException {
final DatagramSocket localReceivingSocket = receivingSocket;
while (localListener != null && localReceivingSocket != null && receivingSocket != null) {
try {
final DatagramPacket answer = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
final var answer = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);

listenerNotifyActive = true;
localReceivingSocket.receive(answer); // receive packet (blocking call)
Expand Down Expand Up @@ -193,8 +193,8 @@ private void handleReceivedData(DatagramPacket answer, Consumer<EmotivaUdpRespon
executorService.execute(() -> {
if (answer.getAddress() != null && answer.getLength() > 0) {
logger.trace("Received data on port '{}'", answer.getPort());
EmotivaUdpResponse emotivaUdpResponse = new EmotivaUdpResponse(
new String(answer.getData(), 0, answer.getLength()), answer.getAddress().getHostAddress());
var emotivaUdpResponse = new EmotivaUdpResponse(new String(answer.getData(), 0, answer.getLength()),
answer.getAddress().getHostAddress());
localListener.accept(emotivaUdpResponse);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ private void handleReceivedData(DatagramPacket answer, Consumer<EmotivaUdpRespon
executorService.execute(() -> {
if (answer.getAddress() != null && answer.getLength() > 0) {
logger.trace("Received data on port '{}'", answer.getPort());
EmotivaUdpResponse emotivaUdpResponse = new EmotivaUdpResponse(
new String(answer.getData(), 0, answer.getLength()), answer.getAddress().getHostAddress());
var emotivaUdpResponse = new EmotivaUdpResponse(new String(answer.getData(), 0, answer.getLength()),
answer.getAddress().getHostAddress());
localListener.accept(emotivaUdpResponse);
}
});
Expand Down Expand Up @@ -183,17 +183,17 @@ public void send(String msg) throws IOException {

final InetAddress ipAddress = InetAddress.getByName(this.ipAddress);
byte[] buf = msg.getBytes(Charset.defaultCharset());
DatagramPacket packet = new DatagramPacket(buf, buf.length, ipAddress, sendingControlPort);
var packet = new DatagramPacket(buf, buf.length, ipAddress, sendingControlPort);

// make sure we are not interrupted by a disconnect while sending this message
synchronized (this) {
DatagramSocket localDatagramSocket = this.sendingSocket;
final DatagramPacket answer = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
final var answer = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
final Consumer<EmotivaUdpResponse> localListener = listener;
if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
localDatagramSocket.setSoTimeout(DEFAULT_UDP_SENDING_TIMEOUT);
localDatagramSocket.send(packet);
logger.debug("Sending successful");
logger.trace("Successfully sending to {}:{}", ipAddress, sendingControlPort);

localDatagramSocket.receive(answer);

Expand All @@ -209,4 +209,8 @@ public void send(String msg) throws IOException {
}
}
}

public boolean isConnected() {
return sendingSocket != null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public void setThingHandler(ThingHandler handler) {
for (EmotivaSubscriptionTags modeKey : modeKeys) {
options.add(new StateOption(modeKey.name(), modes.get(modeKey)));
}
logger.debug("Updated '{}' with '{}'", CHANNEL_MODE, options);
logger.trace("Updating OH channel '{}' with state options '{}'", CHANNEL_MODE, options);
setStateOptions(channel.getUID(), options);
}
}
Expand All @@ -100,7 +100,7 @@ private void setStateOptionsForSource(Channel channel, List<StateOption> options
options.add(new StateOption(sourceKey.name(), sourceKey.getLabel()));
}
}
logger.debug("Updated '{}' with '{}'", channel.getUID().getId(), options);
logger.trace("Updating OH channel '{}' with state options '{}'", channel.getUID().getId(), options);
setStateOptions(channel.getUID(), options);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public EmotivaCommandDTO(EmotivaControlCommands commandName, String value, Strin
* @return EmotivaCommandDTO with ack=yes always added
*/
public static EmotivaCommandDTO fromTypeWithAck(EmotivaControlCommands command) {
EmotivaCommandDTO emotivaCommandDTO = new EmotivaCommandDTO(command);
var emotivaCommandDTO = new EmotivaCommandDTO(command);
emotivaCommandDTO.setAck(DEFAULT_CONTROL_ACK_VALUE);
return emotivaCommandDTO;
}
Expand All @@ -82,7 +82,7 @@ public static EmotivaCommandDTO fromTypeWithAck(EmotivaControlCommands command)
* @return EmotivaCommandDTO with ack=yes always added
*/
public static EmotivaCommandDTO fromTypeWithAck(EmotivaControlCommands command, String value) {
EmotivaCommandDTO emotivaCommandDTO = new EmotivaCommandDTO(command);
var emotivaCommandDTO = new EmotivaCommandDTO(command);
if (value != null) {
emotivaCommandDTO.setValue(value);
}
Expand All @@ -99,7 +99,7 @@ public static EmotivaCommandDTO fromType(EmotivaSubscriptionTags command) {
}

public static EmotivaCommandDTO fromTypeWithAck(EmotivaSubscriptionTags command) {
EmotivaCommandDTO emotivaCommandDTO = new EmotivaCommandDTO(command);
var emotivaCommandDTO = new EmotivaCommandDTO(command);
emotivaCommandDTO.setAck(DEFAULT_CONTROL_ACK_VALUE);
return emotivaCommandDTO;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ public static EnumMap<EmotivaControlCommands, String> getCommandsFromType(Emotiv
EnumMap<EmotivaControlCommands, String> commands = new EnumMap<>(EmotivaControlCommands.class);
for (EmotivaControlCommands value : values()) {
if (value.getCommandType().equals(filter)) {
StringBuilder sb = new StringBuilder(value.name());
var sb = new StringBuilder(value.name());
sb.setCharAt(0, Character.toUpperCase(value.name().charAt(0)));
commands.put(value, sb.toString());
}
Expand Down
Loading

0 comments on commit 29cca2c

Please sign in to comment.