[Minor] Code cleanup

This commit is contained in:
Robert von Burg 2024-04-12 13:20:48 +02:00
parent d9f6f9daca
commit 5e2e139fcf
Signed by: eitch
GPG Key ID: 75DB9C85C74331F7
41 changed files with 1138 additions and 1157 deletions

View File

@ -212,7 +212,7 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
if (this.globalListener != null)
this.plc.setGlobalListener(this.globalListener);
logger.info("Reconfigured PLC with " + this.plcAddresses.size() + " addresses");
logger.info("Reconfigured PLC with {} addresses", this.plcAddresses.size());
return true;
} catch (Exception e) {
@ -239,7 +239,7 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
if (tx.getConfiguration().hasParameter(PARAM_VERBOSE)) {
boolean verboseOverride = tx.getConfiguration().getBoolean(PARAM_VERBOSE);
logger.info("Overriding XML verbose property from configuration resource to " + verboseOverride);
logger.info("Overriding XML verbose property from configuration resource to {}", verboseOverride);
this.verbose = verboseOverride;
}
@ -257,8 +257,8 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
try {
getContainer().getPrivilegeHandler().validateSystemSession(this.ctx);
} catch (Exception e) {
logger.error("PrivilegeContext for session " + this.ctx.getCertificate().getSessionId() +
" is not valid, reopening.", e);
logger.error("PrivilegeContext for session {} is not valid, reopening.",
this.ctx.getCertificate().getSessionId(), e);
this.ctx = getContainer().getPrivilegeHandler().openAgentSystemUserContext();
}
}
@ -284,7 +284,7 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
public void unregister(String resource, String action, PlcListener listener) {
PlcAddress plcAddress = this.plcAddresses.getElement(resource, action);
if (plcAddress == null) {
logger.warn("No PlcAddress exists for " + resource + "-" + action);
logger.warn("No PlcAddress exists for {}-{}", resource, action);
} else {
this.plc.unregister(plcAddress, listener);
}
@ -353,7 +353,7 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
String addressId = this.addressesToResourceId.get(address);
if (addressId == null) {
logger.error("No PlcAddress mapping for " + address);
logger.error("No PlcAddress mapping for {}", address);
return;
}
@ -377,11 +377,11 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
tx.update(addressRes);
tx.commitOnClose();
} catch (Exception e) {
logger.error("Failed to update PlcAddress " + addressId + " with new value " + value, e);
logger.error("Failed to update PlcAddress {} with new value {}", addressId, value, e);
}
if (this.verbose && (nanoTime() - s > MILLISECONDS.toNanos(SILENT_THRESHOLD)))
logger.info("async update " + address.toKey() + " took " + (formatNanoDuration(nanoTime() - s)));
logger.info("async update {} took {}", address.toKey(), formatNanoDuration(nanoTime() - s));
}
private void updateConnectionState(String id, ConnectionState state, String stateMsg) {
@ -405,11 +405,11 @@ public class DefaultPlcHandler extends StrolchComponent implements PlcHandler, P
tx.commitOnClose();
} catch (Exception e) {
logger.error("Failed to update state for connection " + id, e);
logger.error("Failed to update state for connection {}", id, e);
}
if (this.verbose)
logger.info("updateConnectionState took " + (formatNanoDuration(nanoTime() - s)));
logger.info("updateConnectionState took {}", formatNanoDuration(nanoTime() - s));
}
@Override

View File

@ -28,7 +28,7 @@ class PlcConfigurator {
Map<PlcAddress, String> addressesToResourceId) throws Exception {
// instantiate Plc
logger.info("Configuring PLC " + plcClassName + "...");
logger.info("Configuring PLC {}...", plcClassName);
Plc plc = ClassHelper.instantiateClass(plcClassName);
// instantiate all PlcConnections
@ -44,10 +44,10 @@ class PlcConfigurator {
// first all addresses
for (Resource resource : logicalDevices) {
logger.info("Configuring PlcAddresses for PlcLogicalDevice " + resource.getId() + "...");
logger.info("Configuring PlcAddresses for PlcLogicalDevice {}...", resource.getId());
List<Resource> addresses = tx.getResourcesByRelation(resource, PARAM_ADDRESSES, true);
if (addresses.isEmpty()) {
logger.warn("\tNo PlcAddresses for " + resource.getId());
logger.warn("\tNo PlcAddresses for {}", resource.getId());
} else {
for (Resource addressRes : addresses) {
buildPlcAddress(plc, plcAddresses, addressesToResourceId, plcAddressesByHwAddress, addressRes);
@ -57,10 +57,10 @@ class PlcConfigurator {
// now telegrams
for (Resource logicalDevice : logicalDevices) {
logger.info("Configuring PlcTelegrams for PlcLogicalDevice " + logicalDevice.getId() + "...");
logger.info("Configuring PlcTelegrams for PlcLogicalDevice {}...", logicalDevice.getId());
List<Resource> telegrams = tx.getResourcesByRelation(logicalDevice, PARAM_TELEGRAMS, true);
if (telegrams.isEmpty()) {
logger.warn("\tNo PlcTelegrams for " + logicalDevice.getId());
logger.warn("\tNo PlcTelegrams for {}", logicalDevice.getId());
} else {
for (Resource telegramRes : telegrams) {
buildTelegramPlcAddress(plcAddresses, plcTelegrams, addressesToResourceId, plcAddressesByHwAddress,
@ -74,9 +74,9 @@ class PlcConfigurator {
private static void configureConnection(Plc plc, Resource connection) throws Exception {
String className = connection.getParameter(BAG_PARAMETERS, PARAM_CLASS_NAME, true).getValue();
logger.info("Configuring PLC Connection " + className + "...");
PlcConnection plcConnection = ClassHelper.instantiateClass(className,
new Class<?>[] { Plc.class, String.class }, new Object[] { plc, connection.getId() });
logger.info("Configuring PLC Connection {}...", className);
PlcConnection plcConnection = ClassHelper.instantiateClass(className, new Class<?>[]{Plc.class, String.class},
new Object[]{plc, connection.getId()});
plcConnection.initialize(connection.getParameterBag(BAG_PARAMETERS, true).toObjectMap());
plc.addConnection(plcConnection);
}
@ -121,14 +121,18 @@ class PlcConfigurator {
telegramRes.getLocator() + " is referencing non-existing address " + address);
if (valueP.getValueType() != existingAddress.valueType) {
throw new IllegalStateException(
telegramRes.getLocator() + " has valueType " + valueP.getValueType() + " but address "
+ existingAddress.address + " has type " + existingAddress.valueType);
throw new IllegalStateException(telegramRes.getLocator()
+ " has valueType "
+ valueP.getValueType()
+ " but address "
+ existingAddress.address
+ " has type "
+ existingAddress.valueType);
}
PlcAddress telegramAddress = new PlcAddress(PlcAddressType.Telegram, resource, action, address,
valueP.getValueType(), valueP.getValue(), false, remote);
logger.info("Adding " + telegramAddress + "...");
logger.info("Adding {}...", telegramAddress);
PlcAddress replaced = plcTelegrams.addElement(resource, action, telegramAddress);
if (replaced != null)
@ -139,9 +143,12 @@ class PlcConfigurator {
PlcAddress plcAddress = plcAddresses.getElement(existingAddress.resource, existingAddress.action);
if (plcAddress == null)
throw new IllegalStateException(
"PlcAddress for " + resource + "-" + action + " does not exist, so can not connect PlcTelegram "
+ telegramAddress);
throw new IllegalStateException("PlcAddress for "
+ resource
+ "-"
+ action
+ " does not exist, so can not connect PlcTelegram "
+ telegramAddress);
String addressId = addressesToResourceId.get(plcAddress);
if (addressId == null)
throw new IllegalStateException(

View File

@ -10,6 +10,8 @@ import li.strolch.policy.ReloadPrivilegeHandlerJob;
import li.strolch.runtime.configuration.RuntimeConfiguration;
import li.strolch.utils.helper.ExceptionHelper;
import static java.text.MessageFormat.format;
public class PlcPostInitializer extends SimplePostInitializer {
public PlcPostInitializer(ComponentContainer container, String componentName) {
@ -49,8 +51,9 @@ public class PlcPostInitializer extends SimplePostInitializer {
protected void notifyStart() {
if (!(getConfiguration().getBoolean("notifyStart", Boolean.FALSE) && getContainer()
.hasComponent(MailHandler.class)))
if (!(
getConfiguration().getBoolean("notifyStart", Boolean.FALSE) && getContainer().hasComponent(
MailHandler.class)))
return;
String recipients = getConfiguration().getString("notifyStartRecipients", "");
@ -61,20 +64,18 @@ public class PlcPostInitializer extends SimplePostInitializer {
StrolchAgent agent = getContainer().getAgent();
RuntimeConfiguration runtimeConfiguration = agent.getStrolchConfiguration().getRuntimeConfiguration();
String subject = runtimeConfiguration.getApplicationName() + ":" + runtimeConfiguration.getEnvironment()
+ " Startup Complete!";
String subject = format("{0}:{1} Startup Complete!", runtimeConfiguration.getApplicationName(),
runtimeConfiguration.getEnvironment());
String body = "Dear User\n\n" //
+ "The " + getConfiguration().getRuntimeConfiguration().getApplicationName()
+ " Server has just completed startup with version " //
+ agent.getVersion().getAppVersion().getArtifactVersion() //
+ "\n\n" //
+ "\tYour Server.";
String body = format(
"Dear User\n\nThe {0} Server has just completed startup with version {1}\n\n\tYour Server.",
getConfiguration().getRuntimeConfiguration().getApplicationName(),
agent.getVersion().getAppVersion().getArtifactVersion());
try {
getContainer().getComponent(MailHandler.class).sendMailAsync(subject, body, recipients);
} catch (Exception e) {
logger.error("Notifying of server startup failed: " + ExceptionHelper.getRootCause(e), e);
logger.error("Notifying of server startup failed: {}", ExceptionHelper.getRootCause(e), e);
}
}
}

View File

@ -296,7 +296,7 @@ public abstract class PlcService implements PlcListener {
* @param locator the locator of the message
*/
protected void disableMsg(Locator locator) {
logger.info("Disabling message for locator " + locator);
logger.info("Disabling message for locator {}", locator);
this.plcHandler.disableMsg(locator);
}
@ -544,6 +544,6 @@ public abstract class PlcService implements PlcListener {
* @param e the exception which occurred
*/
protected void handleFailedAsync(Exception e) {
logger.error("Failed to execute " + getClass().getSimpleName(), e);
logger.error("Failed to execute {}", getClass().getSimpleName(), e);
}
}

View File

@ -31,12 +31,12 @@ public abstract class PlcServiceInitializer extends StrolchComponent {
try {
plcService.stop();
} catch (Exception e) {
logger.error("Failed to stop PlcService " + plcService.getClass().getName(), e);
logger.error("Failed to stop PlcService {}", plcService.getClass().getName(), e);
}
try {
plcService.unregister();
} catch (Exception e) {
logger.error("Failed to unregister PlcService " + plcService.getClass().getName(), e);
logger.error("Failed to unregister PlcService {}", plcService.getClass().getName(), e);
}
});
super.stop();
@ -45,7 +45,7 @@ public abstract class PlcServiceInitializer extends StrolchComponent {
protected void startPlcServices() {
PlcHandler plcHandler = getComponent(PlcHandler.class);
if (plcHandler.getPlcState() != PlcState.Started) {
logger.error("Can not start PlcServices as PlcState is " + plcHandler.getPlcState());
logger.error("Can not start PlcServices as PlcState is {}", plcHandler.getPlcState());
return;
}
@ -54,7 +54,7 @@ public abstract class PlcServiceInitializer extends StrolchComponent {
try {
plcService.register();
} catch (Exception e) {
logger.error("Failed to register PlcService " + plcService.getClass().getName(), e);
logger.error("Failed to register PlcService {}", plcService.getClass().getName(), e);
}
}
@ -68,7 +68,7 @@ public abstract class PlcServiceInitializer extends StrolchComponent {
try {
plcService.start(tx);
} catch (Exception e) {
logger.error("Failed to register PlcService " + plcService.getClass().getName(), e);
logger.error("Failed to register PlcService {}", plcService.getClass().getName(), e);
}
}
}

View File

@ -1,12 +1,5 @@
package li.strolch.plc.core.hw;
import static java.util.stream.Collectors.toSet;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Stream;
import li.strolch.plc.model.PlcAddress;
import li.strolch.plc.model.PlcAddressKey;
import li.strolch.plc.model.PlcAddressType;
@ -15,6 +8,13 @@ import li.strolch.utils.collections.MapOfLists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toSet;
public class DefaultPlc implements Plc {
private static final Logger logger = LoggerFactory.getLogger(DefaultPlc.class);
@ -79,15 +79,15 @@ public class DefaultPlc implements Plc {
@Override
public void register(PlcAddress address, PlcListener listener) {
this.listeners.addElement(address, listener);
logger.info(address.toKeyAddress() + ": " + listener.getClass().getSimpleName());
logger.info("{}: {}", address.toKeyAddress(), listener.getClass().getSimpleName());
}
@Override
public void unregister(PlcAddress address, PlcListener listener) {
if (this.listeners.removeElement(address, listener)) {
logger.info(address + ": " + listener.getClass().getName());
logger.info("{}: {}", address, listener.getClass().getName());
} else {
logger.warn("Listener not registered with key " + address.toKeyAddress() + ": " +
logger.warn("Listener not registered with key {}: {}", address.toKeyAddress(),
listener.getClass().getSimpleName());
}
}
@ -105,7 +105,7 @@ public class DefaultPlc implements Plc {
private void doNotify(String address, Object value) {
PlcAddress plcAddress = this.notificationMappings.get(address);
if (plcAddress == null) {
logger.warn("No mapping to PlcAddress for hwAddress " + address);
logger.warn("No mapping to PlcAddress for hwAddress {}", address);
return;
}
@ -113,7 +113,7 @@ public class DefaultPlc implements Plc {
if (value instanceof Boolean)
value = !((boolean) value);
else
logger.error(plcAddress + " is marked as inverted, but the value is not a boolean, but a " +
logger.error("{} is marked as inverted, but the value is not a boolean, but a {}", plcAddress,
value.getClass());
}
@ -130,11 +130,11 @@ public class DefaultPlc implements Plc {
for (PlcListener listener : listeners) {
try {
if (this.verbose)
logger.info("Notifying " + plcAddress.toKey() + ": " + value + " @ " + listener);
logger.info("Notifying {}: {} @ {}", plcAddress.toKey(), value, listener);
listener.handleNotification(plcAddress, value);
} catch (Exception e) {
if (catchExceptions) {
logger.error("Failed to notify listener " + listener + " for address " + plcAddress, e);
logger.error("Failed to notify listener {} for address {}", listener, plcAddress, e);
} else {
throw e;
}
@ -157,7 +157,7 @@ public class DefaultPlc implements Plc {
logger.error("Interrupted!");
} catch (Exception e) {
if (task != null)
logger.error("Failed to perform notification for " + task.address + ": " + task.value, e);
logger.error("Failed to perform notification for {}: {}", task.address, task.value, e);
else
logger.error("Failed to get notification task", e);
}
@ -209,10 +209,10 @@ public class DefaultPlc implements Plc {
public void addConnection(PlcConnection connection) {
this.connections.put(connection.getId(), connection);
Set<String> addresses = connection.getAddresses();
logger.info("Adding connection " + connection.getId() + " " + connection.getClass().getName() + " with " +
addresses.size() + " addresses...");
logger.info("Adding connection {} {} with {} addresses...", connection.getId(), connection.getClass().getName(),
addresses.size());
for (String address : addresses) {
logger.info(" Adding " + address + "...");
logger.info(" Adding {}...", address);
this.connectionsByAddress.put(address, connection);
}
}
@ -268,23 +268,13 @@ public class DefaultPlc implements Plc {
throw new IllegalArgumentException(
"Replaced mapping for address " + address.address + " for key " + replaced + " with " + address);
logger.info("Registered " + address);
logger.info("Registered {}", address);
}
private void validateVirtualAddress(PlcAddress address) {
if (address.address.equals(VIRTUAL_BOOLEAN) || address.address.equals(VIRTUAL_BOOLEAN + ".")) {
throw new IllegalStateException(
"Virtual address " + address.address + " is missing sub component for " + address);
}
if (address.address.equals(VIRTUAL_STRING) || address.address.equals(VIRTUAL_STRING + ".")) {
throw new IllegalStateException(
"Virtual address " + address.address + " is missing sub component for " + address);
}
if (address.address.equals(VIRTUAL_INTEGER) || address.address.equals(VIRTUAL_INTEGER + ".")) {
throw new IllegalStateException(
switch (address.address) {
case VIRTUAL_BOOLEAN, VIRTUAL_BOOLEAN + ".", VIRTUAL_STRING, VIRTUAL_STRING + ".", VIRTUAL_INTEGER,
VIRTUAL_INTEGER + "." -> throw new IllegalStateException(
"Virtual address " + address.address + " is missing sub component for " + address);
}
}

View File

@ -11,10 +11,8 @@ public interface PlcListener {
/**
* Notifies the listener of the new value at the given address
*
* @param address
* the address at which the event was detected
* @param value
* the new value at the address
* @param address the address at which the event was detected
* @param value the new value at the address
*/
void handleNotification(PlcAddress address, Object value);
}

View File

@ -1,7 +1,7 @@
package li.strolch.plc.core.hw.connections;
import static li.strolch.plc.model.PlcConstants.PARAM_SIMULATED;
import static li.strolch.utils.helper.ExceptionHelper.getExceptionMessageWithCauses;
import li.strolch.plc.core.hw.Plc;
import li.strolch.utils.helper.AsciiHelper;
import java.io.IOException;
import java.io.InputStream;
@ -15,8 +15,9 @@ import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import li.strolch.plc.core.hw.Plc;
import li.strolch.utils.helper.AsciiHelper;
import static java.text.MessageFormat.format;
import static li.strolch.plc.model.PlcConstants.PARAM_SIMULATED;
import static li.strolch.utils.helper.ExceptionHelper.getExceptionMessageWithCauses;
public class DataLogicScannerConnection extends SimplePlcConnection {
@ -64,13 +65,13 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
this.addresses.add(this.addressTrigger);
this.addresses.add(this.addressBarcode);
logger.info("Configured DataLogic Scanner connection to " + this.address + ":" + this.port);
logger.info("Configured DataLogic Scanner connection to {}:{}", this.address, this.port);
}
@Override
public boolean connect() {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
return super.connect();
}
@ -80,7 +81,7 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
try {
this.socket = new Socket(this.address, this.port);
this.socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(this.readTimeout));
logger.info("Connected DataLogic Scanner connection to " + this.address + ":" + this.port);
logger.info("Connected DataLogic Scanner connection to {}:{}", this.address, this.port);
this.read = true;
this.readTask = this.plc.getExecutorPool().getSingleThreadExecutor(this.id).submit(this::read);
@ -98,7 +99,7 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
@Override
public void disconnect() {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
super.disconnect();
return;
}
@ -114,7 +115,7 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
}
if (this.socket != null) {
logger.warn("Closing socket to " + this.address + ":" + this.port);
logger.warn("Closing socket to {}:{}", this.address, this.port);
try {
this.socket.shutdownInput();
this.socket.shutdownOutput();
@ -150,7 +151,7 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
throw new IllegalStateException("Illegal Address " + address);
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
return;
}
@ -170,8 +171,8 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
} catch (IOException e) {
handleBrokenConnection(
"Failed to handle address " + address + " for " + this.address + ":" + this.port + ": "
+ getExceptionMessageWithCauses(e), e);
format("Failed to handle address {0} for {1}:{2}: {3}", address, this.address, this.port,
getExceptionMessageWithCauses(e)), e);
throw new IllegalStateException(
"Failed to handle address " + address + " for " + this.address + ":" + this.port, e);
@ -180,7 +181,7 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
private void read() {
logger.info("Reading from DataLogic Scanner at " + this.address + ":" + this.port + "...");
logger.info("Reading from DataLogic Scanner at {}:{}...", this.address, this.port);
while (this.read) {
try {
@ -215,7 +216,7 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
}
String barcode = sb.toString();
logger.info("Received barcode " + barcode);
logger.info("Received barcode {}", barcode);
notify(this.addressBarcode, barcode);
}
@ -226,27 +227,27 @@ public class DataLogicScannerConnection extends SimplePlcConnection {
try {
sendStopTrigger();
} catch (IOException ex) {
logger.error("Failed to send stop during timeout exception: " + ex.getMessage());
logger.error("Failed to send stop during timeout exception: {}", ex.getMessage());
}
internalDisconnect();
handleBrokenConnection(
"Timeout while reading from scanner at " + this.address + ":" + this.port + ": "
+ getExceptionMessageWithCauses(e), e);
format("Timeout while reading from scanner at {0}:{1}: {2}", this.address, this.port,
getExceptionMessageWithCauses(e)), e);
} else {
logger.warn("Timeout while reading from scanner at " + this.address + ":" + this.port
+ ". Disconnected.");
logger.warn("Timeout while reading from scanner at {}:{}. Disconnected.", this.address,
this.port);
notify(this.addressBarcode, NO_CONNECTION);
disconnect();
}
} else {
notify(this.addressBarcode, NO_CONNECTION);
internalDisconnect();
handleBrokenConnection("Failed to connect to " + this.address + ":" + this.port + ": "
+ getExceptionMessageWithCauses(e), e);
handleBrokenConnection(format("Failed to connect to {0}:{1}: {2}", this.address, this.port,
getExceptionMessageWithCauses(e)), e);
}
}
}
logger.info("Stopped reading from " + this.address + ":" + this.port);
logger.info("Stopped reading from {}:{}", this.address, this.port);
}
}

View File

@ -11,6 +11,6 @@ public class LoggerOutConnection extends SimplePlcConnection {
@Override
public void send(String address, Object value) {
assertConnected();
logger.info(address + " -> " + value);
logger.info("{} -> {}", address, value);
}
}

View File

@ -15,11 +15,11 @@ public class RandomStringConnection extends SimplePlcConnection {
@Override
public void send(String address, Object value) {
assertConnected();
PlcConnection.logger.info("Sending " + address + " => " + value);
PlcConnection.logger.info("Sending {} => {}", address, value);
byte[] data = new byte[8];
new SecureRandom().nextBytes(data);
String newValue = StringHelper.toHexString(data);
PlcConnection.logger.info("Generated random value " + newValue);
PlcConnection.logger.info("Generated random value {}", newValue);
this.plc.syncNotify(address, newValue);
}
}

View File

@ -19,12 +19,12 @@ public abstract class SimplePlcConnection extends PlcConnection {
@Override
public void initialize(Map<String, Object> parameters) throws Exception {
logger.info("Configured " + getClass().getSimpleName() + " " + this.id);
logger.info("Configured {} {}", getClass().getSimpleName(), this.id);
}
@Override
public boolean connect() {
logger.info(this.id + ": Is now connected.");
logger.info("{}: Is now connected.", this.id);
if (this.simulated)
logger.info("Running SIMULATED");
this.connectionState = ConnectionState.Connected;
@ -35,7 +35,7 @@ public abstract class SimplePlcConnection extends PlcConnection {
@Override
public void disconnect() {
logger.info(this.id + ": Is now disconnected.");
logger.info("{}: Is now disconnected.", this.id);
this.connectionState = ConnectionState.Disconnected;
this.connectionStateMsg = "-";
this.plc.notifyConnectionStateChanged(this);

View File

@ -18,7 +18,6 @@ import li.strolch.plc.core.hw.connections.SimplePlcConnection;
public class RaspiBcmGpioInputConnection extends SimplePlcConnection {
private boolean verbose;
private List<Integer> inputBcmAddresses;
private Map<String, Pin> pinsByAddress;
private Map<GpioPin, String> addressesByPin;
@ -33,18 +32,16 @@ public class RaspiBcmGpioInputConnection extends SimplePlcConnection {
public void initialize(Map<String, Object> parameters) {
this.simulated = parameters.containsKey(PARAM_SIMULATED) && (boolean) parameters.get(PARAM_SIMULATED);
@SuppressWarnings("unchecked")
List<Integer> bcmInputPins = (List<Integer>) parameters.get("bcmInputPins");
this.inputBcmAddresses = bcmInputPins;
@SuppressWarnings("unchecked") List<Integer> bcmInputPins = (List<Integer>) parameters.get("bcmInputPins");
this.pinsByAddress = new HashMap<>();
for (Integer address : this.inputBcmAddresses) {
for (Integer address : bcmInputPins) {
Pin pin = RaspiBcmPin.getPinByAddress(address);
if (pin == null)
throw new IllegalArgumentException("RaspiBcmPin " + address + " does not exist!");
String key = this.id + "." + address;
this.pinsByAddress.put(key, pin);
logger.info("Registered address " + key + " for RaspiBcmPin " + pin);
logger.info("Registered address {} for RaspiBcmPin {}", key, pin);
}
if (parameters.containsKey("pinPullResistance")) {
@ -56,14 +53,14 @@ public class RaspiBcmGpioInputConnection extends SimplePlcConnection {
this.verbose = parameters.containsKey("verbose") && (Boolean) parameters.get("verbose");
this.inverted = parameters.containsKey("inverted") && (boolean) parameters.get("inverted");
logger.info("Configured Raspi BCM GPIO Input for Pins " + this.inputBcmAddresses.stream().map(Object::toString)
.collect(joining(", ")));
logger.info("Configured Raspi BCM GPIO Input for Pins {}",
bcmInputPins.stream().map(Object::toString).collect(joining(", ")));
}
@Override
public boolean connect() {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
return super.connect();
}
@ -82,7 +79,7 @@ public class RaspiBcmGpioInputConnection extends SimplePlcConnection {
inputPin.addListener((GpioPinListenerDigital) this::handleInterrupt);
this.addressesByPin.put(inputPin, address);
logger.info("Provisioned input pin " + inputPin + " for address " + address);
logger.info("Provisioned input pin {} for address {}", inputPin, address);
}
return super.connect();
@ -95,19 +92,19 @@ public class RaspiBcmGpioInputConnection extends SimplePlcConnection {
private void handleInterrupt(GpioPinDigitalStateChangeEvent event) {
if (this.verbose)
logger.info(event.getPin() + " " + event.getState() + " " + event.getEdge());
logger.info("{} {} {}", event.getPin(), event.getState(), event.getEdge());
String address = this.addressesByPin.get(event.getPin());
PinState state = event.getState();
if (this.verbose)
logger.info(address + " has new state " + state);
logger.info("{} has new state {}", address, state);
notify(address, this.inverted ? state.isLow() : state.isHigh());
}
@Override
public void disconnect() {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
super.disconnect();
return;
}
@ -119,7 +116,7 @@ public class RaspiBcmGpioInputConnection extends SimplePlcConnection {
}
this.addressesByPin.clear();
} catch (Error e) {
logger.error("Failed to disconnect " + this.id, e);
logger.error("Failed to disconnect {}", this.id, e);
}
super.disconnect();

View File

@ -16,7 +16,6 @@ import li.strolch.plc.core.hw.connections.SimplePlcConnection;
public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
private boolean verbose;
private List<Integer> outputBcmAddresses;
private Map<String, Pin> pinsByAddress;
private Map<String, GpioPinDigitalOutput> gpioPinsByAddress;
private boolean inverted;
@ -29,25 +28,22 @@ public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
public void initialize(Map<String, Object> parameters) {
this.simulated = parameters.containsKey(PARAM_SIMULATED) && (boolean) parameters.get(PARAM_SIMULATED);
@SuppressWarnings("unchecked")
List<Integer> bcmOutputPins = (List<Integer>) parameters.get("bcmOutputPins");
this.outputBcmAddresses = bcmOutputPins;
@SuppressWarnings("unchecked") List<Integer> bcmOutputPins = (List<Integer>) parameters.get("bcmOutputPins");
this.pinsByAddress = new HashMap<>();
for (Integer address : this.outputBcmAddresses) {
for (Integer address : bcmOutputPins) {
Pin pin = RaspiBcmPin.getPinByAddress(address);
if (pin == null)
throw new IllegalArgumentException("RaspiBcmPin " + address + " does not exist!");
String key = this.id + "." + address;
this.pinsByAddress.put(key, pin);
logger.info("Registered address " + key + " for RaspiBcmPin " + pin);
logger.info("Registered address {} for RaspiBcmPin {}", key, pin);
}
this.verbose = parameters.containsKey("verbose") && (Boolean) parameters.get("verbose");
this.inverted = parameters.containsKey("inverted") && (boolean) parameters.get("inverted");
logger.info(
"Configured Raspi BCM GPIO Output for Pins " + this.outputBcmAddresses.stream().map(Object::toString)
.collect(joining(", ")));
logger.info("Configured Raspi BCM GPIO Output for Pins {}",
bcmOutputPins.stream().map(Object::toString).collect(joining(", ")));
}
@Override
@ -65,7 +61,7 @@ public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
Pin pin = this.pinsByAddress.get(address);
GpioPinDigitalOutput outputPin = gpioController.provisionDigitalOutputPin(pin);
this.gpioPinsByAddress.put(address, outputPin);
logger.info("Provisioned output pin " + outputPin + " for address " + address);
logger.info("Provisioned output pin {} for address {}", outputPin, address);
}
return super.connect();
@ -79,7 +75,7 @@ public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
@Override
public void disconnect() {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
super.disconnect();
return;
}
@ -91,7 +87,7 @@ public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
}
this.gpioPinsByAddress.clear();
} catch (Error e) {
logger.error("Failed to disconnect " + this.id, e);
logger.error("Failed to disconnect {}", this.id, e);
}
super.disconnect();
@ -100,7 +96,7 @@ public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
@Override
public void send(String address, Object value) {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
return;
}
@ -114,7 +110,7 @@ public class RaspiBcmGpioOutputConnection extends SimplePlcConnection {
PinState newState = high ? PinState.HIGH : PinState.LOW;
if (this.verbose)
logger.info("Setting pin " + outputPin + " to new state " + newState);
logger.info("Setting pin {} to new state {}", outputPin, newState);
outputPin.setState(newState);
}

View File

@ -1,15 +1,15 @@
package li.strolch.plc.core.hw.i2c;
import static li.strolch.utils.helper.StringHelper.toHexString;
import static li.strolch.utils.helper.StringHelper.toPrettyHexString;
import java.io.IOException;
import com.pi4j.io.i2c.I2CDevice;
import li.strolch.utils.communication.PacketObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static li.strolch.utils.helper.StringHelper.toHexString;
import static li.strolch.utils.helper.StringHelper.toPrettyHexString;
public class LoggingI2cDevice {
private static final Logger logger = LoggerFactory.getLogger(LoggingI2cDevice.class);
@ -45,12 +45,12 @@ public class LoggingI2cDevice {
sleepIfNecessary();
if (log)
logger.info(this.i2cAddressS + ": Writing: " + toHexString(data));
logger.info("{}: Writing: {}", this.i2cAddressS, toHexString(data));
this.i2cDevice.write(data);
if (this.packetObserver != null)
this.packetObserver.notifySent(new byte[] { data });
this.packetObserver.notifySent(new byte[]{data});
this.lastWriteNanos = System.nanoTime();
}
@ -58,7 +58,7 @@ public class LoggingI2cDevice {
sleepIfNecessary();
if (log)
logger.info(this.i2cAddressS + ": Writing: " + toPrettyHexString(buffer));
logger.info("{}: Writing: {}", this.i2cAddressS, toPrettyHexString(buffer));
this.i2cDevice.write(buffer);
@ -68,7 +68,7 @@ public class LoggingI2cDevice {
}
public void write(boolean log, int address, byte b) throws IOException, InterruptedException {
write(log, new byte[] { (byte) address, b });
write(log, new byte[]{(byte) address, b});
}
public void write(boolean log, int address, byte[] buffer) throws IOException, InterruptedException {
@ -82,7 +82,7 @@ public class LoggingI2cDevice {
sleepIfNecessary();
if (log)
logger.info(this.i2cAddressS + ": Writing: " + toPrettyHexString(writeBuffer));
logger.info("{}: Writing: {}", this.i2cAddressS, toPrettyHexString(writeBuffer));
int read = this.i2cDevice.read(writeBuffer, 0, writeBuffer.length, readBuffer, 0, readBuffer.length);
if (read != readBuffer.length)
@ -95,31 +95,31 @@ public class LoggingI2cDevice {
this.lastWriteNanos = System.nanoTime();
if (log)
logger.info(this.i2cAddressS + ": Read: " + toPrettyHexString(readBuffer));
logger.info("{}: Read: {}", this.i2cAddressS, toPrettyHexString(readBuffer));
}
public int read(boolean log) throws IOException {
int read = this.i2cDevice.read();
if (log)
logger.info(this.i2cAddressS + ": Read: " + toHexString((byte) read));
logger.info("{}: Read: {}", this.i2cAddressS, toHexString((byte) read));
if (this.packetObserver != null)
this.packetObserver.notifyReceived(new byte[] { (byte) read });
this.packetObserver.notifyReceived(new byte[]{(byte) read});
return read;
}
public int read(boolean log, byte address) throws IOException {
if (log)
logger.info(this.i2cAddressS + ": Writing: " + toHexString(address));
logger.info("{}: Writing: {}", this.i2cAddressS, toHexString(address));
int read = this.i2cDevice.read(address);
if (log)
logger.info(this.i2cAddressS + ": Read: " + toHexString((byte) read));
logger.info("{}: Read: {}", this.i2cAddressS, toHexString((byte) read));
if (this.packetObserver != null) {
this.packetObserver.notifySent(new byte[] { address });
this.packetObserver.notifyReceived(new byte[] { (byte) read });
this.packetObserver.notifySent(new byte[]{address});
this.packetObserver.notifyReceived(new byte[]{(byte) read});
}
return read;
@ -127,31 +127,31 @@ public class LoggingI2cDevice {
public void read(boolean log, byte[] buffer) throws IOException {
if (log)
logger.info(this.i2cAddressS + ": Reading: " + buffer.length + " bytes from last set address...");
logger.info("{}: Reading: {} bytes from last set address...", this.i2cAddressS, buffer.length);
int read = this.i2cDevice.read(buffer, 0, buffer.length);
if (read != buffer.length)
throw new IllegalStateException("Expected to read " + buffer.length + " bytes, but read " + read);
if (log)
logger.info(this.i2cAddressS + ": Read: " + toPrettyHexString(buffer));
logger.info("{}: Read: {}", this.i2cAddressS, toPrettyHexString(buffer));
if (this.packetObserver != null)
this.packetObserver.notifyReceived(new byte[] { (byte) read });
this.packetObserver.notifyReceived(new byte[]{(byte) read});
}
public void read(boolean log, byte address, byte[] buffer) throws IOException {
if (log)
logger.info(
this.i2cAddressS + ": Reading: " + buffer.length + " bytes from address " + toHexString(address));
logger.info("{}: Reading: {} bytes from address {}", this.i2cAddressS, buffer.length,
toHexString(address));
int read = this.i2cDevice.read(address, buffer, 0, buffer.length);
if (read != buffer.length)
throw new IllegalStateException("Expected to read " + buffer.length + " bytes, but read " + read);
if (log)
logger.info(this.i2cAddressS + ": Read: " + toPrettyHexString(buffer));
logger.info("{}: Read: {}", this.i2cAddressS, toPrettyHexString(buffer));
if (this.packetObserver != null) {
this.packetObserver.notifySent(new byte[] { address });
this.packetObserver.notifySent(new byte[]{address});
this.packetObserver.notifyReceived(buffer);
}
}
@ -180,6 +180,6 @@ public class LoggingI2cDevice {
this.ioWait = ioWait;
this.ioWaitNanos = ioWaitNanos;
logger.info("Using " + ioWait + " ms and " + ioWaitNanos + " ns for write sleep");
logger.info("Using {} ms and {} ns for write sleep", ioWait, ioWaitNanos);
}
}

View File

@ -41,7 +41,8 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
public abstract String getName();
public String getDescription() {
return "I2C Output " + getName() + " @ " + byteStream(this.addresses).map(b -> "0x" + toHexString(b))
return "I2C Output " + getName() + " @ " + byteStream(this.addresses)
.map(b -> "0x" + toHexString(b))
.collect(joining(", "));
}
@ -65,12 +66,11 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
this.inverted = parameters.containsKey("inverted") && (boolean) parameters.get("inverted");
this.reversed = parameters.containsKey("reversed") && (boolean) parameters.get("reversed");
logger.info("inverted: " + this.inverted);
logger.info("reversed: " + this.reversed);
logger.info("nrOfBits: " + this.nrOfBits);
logger.info("inverted: {}", this.inverted);
logger.info("reversed: {}", this.reversed);
logger.info("nrOfBits: {}", this.nrOfBits);
@SuppressWarnings("unchecked")
List<Integer> addressList = (List<Integer>) parameters.get("addresses");
@SuppressWarnings("unchecked") List<Integer> addressList = (List<Integer>) parameters.get("addresses");
this.addresses = new byte[addressList.size()];
for (int i = 0; i < addressList.size(); i++) {
this.addresses[i] = addressList.get(i).byteValue();
@ -79,26 +79,26 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
Map<String, int[]> positionsByAddress = new HashMap<>();
for (int i = 0; i < this.addresses.length; i++) {
for (int j = 0; j < this.nrOfBits; j++)
positionsByAddress.put(this.id + "." + i + "." + j, new int[] { i, j });
positionsByAddress.put(this.id + "." + i + "." + j, new int[]{i, j});
}
this.positionsByAddress = Collections.unmodifiableMap(positionsByAddress);
logger.info("Configured " + getDescription());
logger.info("Configured {}", getDescription());
}
@Override
public boolean connect() {
if (this.simulated) {
logger.warn(getName() + ": " + this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: {}: Running SIMULATED, NOT CONNECTING!", getName(), this.id);
return super.connect();
}
if (isConnected()) {
logger.warn(getName() + ": " + this.id + ": Already connected");
logger.warn("{}: {}: Already connected", getName(), this.id);
return true;
}
logger.info(getName() + ": " + this.id + ": Connecting...");
logger.info("{}: {}: Connecting...", getName(), this.id);
// initialize
try {
@ -114,7 +114,7 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
}
if (setup()) {
logger.info("Successfully connected " + this.outputDevices.length + " devices as " + getDescription());
logger.info("Successfully connected {} devices as {}", this.outputDevices.length, getDescription());
return super.connect();
}
@ -136,7 +136,7 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
byte address = this.addresses[index];
I2CDevice outputDevice = devices[index];
ok &= setup(address, index, outputDevice);
logger.info("Connected " + getDescription(address));
logger.info("Connected {}", getDescription(address));
}
if (ok)
@ -150,7 +150,7 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
@Override
public void disconnect() {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
super.disconnect();
return;
}
@ -169,7 +169,7 @@ public abstract class Multi8BitI2cOutputConnection extends SimplePlcConnection {
@Override
public void send(String address, Object value) {
if (this.simulated) {
logger.warn(this.id + ": Running SIMULATED, NOT CONNECTING!");
logger.warn("{}: Running SIMULATED, NOT CONNECTING!", this.id);
return;
}

View File

@ -1,19 +1,5 @@
package li.strolch.plc.core.hw.i2c;
import static com.pi4j.wiringpi.Gpio.HIGH;
import static com.pi4j.wiringpi.Gpio.LOW;
import static li.strolch.plc.model.PlcConstants.PARAM_SIMULATED;
import static li.strolch.utils.helper.ByteHelper.asBinary;
import static li.strolch.utils.helper.ByteHelper.isBitSet;
import static li.strolch.utils.helper.ExceptionHelper.getExceptionMessageWithCauses;
import static li.strolch.utils.helper.StringHelper.toHexString;
import static li.strolch.utils.helper.StringHelper.toPrettyHexString;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
@ -27,6 +13,21 @@ import li.strolch.plc.core.hw.gpio.PlcGpioController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static com.pi4j.wiringpi.Gpio.HIGH;
import static com.pi4j.wiringpi.Gpio.LOW;