Skip to content

Commit

Permalink
[gce] File based items are not updated (openhab#13545)
Browse files Browse the repository at this point in the history
* [gce] Correcting non updated input channels

Signed-off-by: clinique <gael@lhopital.org>
  • Loading branch information
clinique authored and nemerdaud committed Feb 28, 2023
1 parent 7cc1f32 commit eeb8f2b
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,4 @@ public class GCEBindingConstants {
public static final String EVENT_SHORT_PRESS = "SHORT_PRESS";
public static final String EVENT_LONG_PRESS = "LONG_PRESS";
public static final String EVENT_PULSE = "PULSE";

// Adressable thing
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ private void disconnect() {
/**
* Stop the device thread
*/
public void destroyAndExit() {
public void dispose() {
interrupt();
disconnect();
}
Expand Down Expand Up @@ -161,7 +161,7 @@ public void run() {
try {
Thread.sleep(DEFAULT_RECONNECT_TIMEOUT_MS);
} catch (InterruptedException e) {
destroyAndExit();
dispose();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import java.util.concurrent.TimeUnit;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.gce.internal.action.Ipx800Actions;
import org.openhab.binding.gce.internal.config.AnalogInputConfiguration;
import org.openhab.binding.gce.internal.config.DigitalInputConfiguration;
Expand All @@ -56,7 +55,6 @@
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.thing.binding.builder.ChannelBuilder;
import org.openhab.core.thing.binding.builder.ThingBuilder;
import org.openhab.core.thing.type.ChannelKind;
import org.openhab.core.thing.type.ChannelTypeUID;
import org.openhab.core.types.Command;
Expand All @@ -78,14 +76,11 @@ public class Ipx800v3Handler extends BaseThingHandler implements Ipx800EventList

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

private @NonNullByDefault({}) Ipx800Configuration configuration;
private @NonNullByDefault({}) Ipx800DeviceConnector connector;
private @NonNullByDefault({}) StatusFileInterpreter statusFile;

private Optional<Ipx800DeviceConnector> connector = Optional.empty();
private Optional<M2MMessageParser> parser = Optional.empty();
private Optional<ScheduledFuture<?>> refreshJob = Optional.empty();

private final Map<String, @Nullable PortData> portDatas = new HashMap<>();
private final Map<String, PortData> portDatas = new HashMap<>();

private class LongPressEvaluator implements Runnable {
private final ZonedDateTime referenceTime;
Expand Down Expand Up @@ -115,70 +110,61 @@ public Ipx800v3Handler(Thing thing) {

@Override
public void initialize() {
configuration = getConfigAs(Ipx800Configuration.class);

logger.debug("Initializing IPX800 handler for uid '{}'", getThing().getUID());

statusFile = new StatusFileInterpreter(configuration.hostname, this);
Ipx800Configuration config = getConfigAs(Ipx800Configuration.class);
StatusFileInterpreter statusFile = new StatusFileInterpreter(config.hostname, this);

if (thing.getProperties().isEmpty()) {
discoverAttributes();
updateProperties(Map.of(Thing.PROPERTY_VENDOR, "GCE Electronics", Thing.PROPERTY_FIRMWARE_VERSION,
statusFile.getElement(StatusEntry.VERSION), Thing.PROPERTY_MAC_ADDRESS,
statusFile.getElement(StatusEntry.CONFIG_MAC)));
}

List<Channel> channels = new ArrayList<>(getThing().getChannels());
ThingBuilder thingBuilder = editThing();
PortDefinition.asStream().forEach(portDefinition -> {
int nbElements = statusFile.getMaxNumberofNodeType(portDefinition);
for (int i = 0; i < nbElements; i++) {
createChannels(portDefinition, i, channels);
ChannelUID portChannelUID = createChannels(portDefinition, i, channels);
portDatas.put(portChannelUID.getId(), new PortData());
}
});
thingBuilder.withChannels(channels);
updateThing(thingBuilder.build());

connector = new Ipx800DeviceConnector(configuration.hostname, configuration.portNumber, getThing().getUID());
parser = Optional.of(new M2MMessageParser(connector, this));
updateThing(editThing().withChannels(channels).build());

connector = Optional.of(new Ipx800DeviceConnector(config.hostname, config.portNumber, getThing().getUID()));
parser = Optional.of(new M2MMessageParser(connector.get(), this));

updateStatus(ThingStatus.UNKNOWN);

refreshJob = Optional.of(scheduler.scheduleWithFixedDelay(statusFile::read, 3000, configuration.pullInterval,
TimeUnit.MILLISECONDS));
refreshJob = Optional.of(
scheduler.scheduleWithFixedDelay(statusFile::read, 3000, config.pullInterval, TimeUnit.MILLISECONDS));

connector.start();
connector.get().start();
}

@Override
public void dispose() {
refreshJob.ifPresent(job -> job.cancel(true));
refreshJob = Optional.empty();

if (connector != null) {
connector.destroyAndExit();
}
connector.ifPresent(Ipx800DeviceConnector::dispose);
connector = Optional.empty();

parser = Optional.empty();

portDatas.values().stream().forEach(portData -> {
if (portData != null) {
portData.dispose();
}
});
portDatas.values().stream().forEach(PortData::dispose);
super.dispose();
}

protected void discoverAttributes() {
updateProperties(Map.of(Thing.PROPERTY_VENDOR, "GCE Electronics", Thing.PROPERTY_FIRMWARE_VERSION,
statusFile.getElement(StatusEntry.VERSION), Thing.PROPERTY_MAC_ADDRESS,
statusFile.getElement(StatusEntry.CONFIG_MAC)));
}

private void addIfChannelAbsent(ChannelBuilder channelBuilder, List<Channel> channels) {
Channel newChannel = channelBuilder.build();
if (channels.stream().noneMatch(c -> c.getUID().equals(newChannel.getUID()))) {
channels.add(newChannel);
}
}

private void createChannels(PortDefinition portDefinition, int portIndex, List<Channel> channels) {
private ChannelUID createChannels(PortDefinition portDefinition, int portIndex, List<Channel> channels) {
String ndx = Integer.toString(portIndex + 1);
String advancedChannelTypeName = portDefinition.toString()
+ (portDefinition.isAdvanced(portIndex) ? "Advanced" : "");
Expand Down Expand Up @@ -210,9 +196,12 @@ private void createChannels(PortDefinition portDefinition, int portIndex, List<C
.withLabel("Relay " + ndx).withType(channelType), channels);
break;
}

addIfChannelAbsent(ChannelBuilder.create(new ChannelUID(groupUID, ndx + "-duration"), "Number:Time")
.withType(new ChannelTypeUID(BINDING_ID, CHANNEL_LAST_STATE_DURATION))
.withLabel("Previous state duration " + ndx), channels);

return mainChannelUID;
}

@Override
Expand Down Expand Up @@ -258,7 +247,7 @@ public void dataReceived(String port, double value) {
return;
}
logger.debug("About to update port '{}' with data '{}'", port, value);
State state = UnDefType.UNDEF;
State state = UnDefType.NULL;
switch (portDefinition) {
case COUNTER:
state = new DecimalType(value);
Expand All @@ -268,7 +257,7 @@ public void dataReceived(String port, double value) {
break;
case ANALOG:
state = new DecimalType(value);
updateState(channelId + PROPERTY_SEPARATOR + CHANNEL_VOLTAGE,
updateIfLinked(channelId + PROPERTY_SEPARATOR + CHANNEL_VOLTAGE,
new QuantityType<>(value * ANALOG_SAMPLING, Units.VOLT));
break;
case CONTACT:
Expand Down Expand Up @@ -303,9 +292,9 @@ public void dataReceived(String port, double value) {
break;
}

updateState(channelId, state);
updateIfLinked(channelId, state);
if (!portData.isInitializing()) {
updateState(channelId + PROPERTY_SEPARATOR + CHANNEL_LAST_STATE_DURATION,
updateIfLinked(channelId + PROPERTY_SEPARATOR + CHANNEL_LAST_STATE_DURATION,
new QuantityType<>(sinceLastChange / 1000, Units.SECOND));
}
portData.setData(value, now);
Expand All @@ -317,6 +306,12 @@ public void dataReceived(String port, double value) {
}
}

private void updateIfLinked(String channelId, State state) {
if (isLinked(channelId)) {
updateState(channelId, state);
}
}

protected void triggerPushButtonChannel(Channel channel, String event) {
logger.debug("Triggering event '{}' on channel '{}'", event, channel.getUID());
triggerChannel(channel.getUID().getId() + PROPERTY_SEPARATOR + TRIGGER_CONTACT, event);
Expand All @@ -342,32 +337,10 @@ public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("Can not handle command '{}' on channel '{}'", command, channelUID);
}

@Override
public void channelLinked(ChannelUID channelUID) {
logger.debug("channelLinked: {}", channelUID);
final String channelId = channelUID.getId();
if (isValidPortId(channelUID)) {
Channel channel = thing.getChannel(channelUID);
if (channel != null) {
PortData data = new PortData();
portDatas.put(channelId, data);
}
}
}

private boolean isValidPortId(ChannelUID channelUID) {
return channelUID.getIdWithoutGroup().chars().allMatch(Character::isDigit);
}

@Override
public void channelUnlinked(ChannelUID channelUID) {
super.channelUnlinked(channelUID);
PortData portData = portDatas.remove(channelUID.getId());
if (portData != null) {
portData.dispose();
}
}

public void resetCounter(int counter) {
parser.ifPresent(p -> p.resetCounter(counter));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.regex.Pattern;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.gce.internal.handler.Ipx800DeviceConnector;
import org.openhab.binding.gce.internal.handler.Ipx800EventListener;
import org.slf4j.Logger;
Expand All @@ -35,11 +34,11 @@ public class M2MMessageParser {

private final Logger logger = LoggerFactory.getLogger(M2MMessageParser.class);
private final Ipx800DeviceConnector connector;
private final @Nullable Ipx800EventListener listener;
private final Ipx800EventListener listener;

private String expectedResponse = "";

public M2MMessageParser(Ipx800DeviceConnector connector, @Nullable Ipx800EventListener listener) {
public M2MMessageParser(Ipx800DeviceConnector connector, Ipx800EventListener listener) {
this.connector = connector;
this.listener = listener;
connector.setParser(this);
Expand Down Expand Up @@ -87,9 +86,7 @@ private void decodeDataLine(PortDefinition portDefinition, String data) {

private void setStatus(String port, double value) {
logger.debug("Received {} : {}", port, value);
if (listener != null) {
listener.dataReceived(port, value);
}
listener.dataReceived(port, value);
}

public void setExpectedResponse(String expectedResponse) {
Expand Down Expand Up @@ -125,9 +122,7 @@ public void resetCounter(int targetCounter) {

public void errorOccurred(Exception e) {
logger.warn("Error received from connector : {}", e.getMessage());
if (listener != null) {
listener.errorOccurred(e);
}
listener.errorOccurred(e);
}

public void resetPLC() {
Expand Down
Loading

0 comments on commit eeb8f2b

Please sign in to comment.