From 094d15de95406252239fc57627a727bc9cbf67d5 Mon Sep 17 00:00:00 2001 From: Miro Wengner Date: Tue, 8 Oct 2024 23:33:20 +0200 Subject: [PATCH] [69] logger add --- .../java/com/robo4j/hw/lego/ILegoSensor.java | 4 +- .../robo4j/hw/lego/wrapper/SensorWrapper.java | 4 +- robo4j-units-lego/pom.xml | 9 ++ .../lego/GripperSonicTankPlatformExample.java | 16 ++- .../lego/InfraPushTankPlatformExample.java | 23 ++-- .../robo4j/units/lego/InfraSensorExample.java | 60 ++++----- .../lego/controller/ReportController.java | 5 +- .../hw/lego/wrapper/MotorTestWrapper.java | 16 ++- .../hw/lego/wrapper/SensorTestWrapper.java | 65 ++++------ .../robo4j/units/lego/BrickButtonTests.java | 12 +- .../robo4j/units/lego/SimpleTankTestUnit.java | 6 +- .../robo4j/units/lego/SimpleTankUnitMock.java | 5 +- robo4j-units-rpi-http/pom.xml | 9 ++ ...raDecoratedImageProducerConsumerTests.java | 84 ++++++------ .../camera/CameraImageConsumerTestUnit.java | 98 +++++++------- .../CameraImageProducerConsumerTests.java | 87 ++++++------- robo4j-units-rpi/pom.xml | 15 ++- .../accelerometer/AccelerometerExample.java | 60 ++++----- .../accelerometer/AccelerometerProcessor.java | 26 ++-- .../rpi/bno/DataEventListenerExample.java | 90 ++++++------- .../rpi/bno/VectorEventListenerExample.java | 111 ++++++++-------- .../com/robo4j/units/rpi/gps/GPSExample.java | 72 ++++++----- .../robo4j/units/rpi/gps/GPSProcessor.java | 26 ++-- .../robo4j/units/rpi/gyro/GyroExample.java | 55 ++++---- .../robo4j/units/rpi/gyro/GyroProcessor.java | 26 ++-- .../led/AdafruitAlphanumericUnitExample.java | 80 ++++++------ .../led/AdafruitBiColor24BackpackExample.java | 62 ++++----- ...afruitBiColorMatrix8x8BackpackExample.java | 65 +++++----- .../rpi/lidarlite/LaserScanProcessor.java | 29 ++--- .../rpi/lidarlite/LaserScannerExample.java | 90 ++++++------- .../robo4j/units/rpi/pad/LF710PadExample.java | 40 +++--- .../units/rpi/pwm/CalibrationUtility.java | 107 ++++++++-------- .../units/rpi/pwm/ServoUnitExample.java | 121 +++++++++--------- .../rpi/roboclaw/RoboClawUnitExample.java | 108 ++++++++-------- .../robo4j/units/rpi/camera/RaspividUnit.java | 16 +-- .../src/main/java/module-info.java | 1 + 36 files changed, 881 insertions(+), 822 deletions(-) diff --git a/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/ILegoSensor.java b/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/ILegoSensor.java index 0d6a8e55..d5fdac9d 100644 --- a/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/ILegoSensor.java +++ b/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/ILegoSensor.java @@ -29,9 +29,9 @@ */ public interface ILegoSensor { - DigitalPortEnum getPort(); + DigitalPortEnum port(); - SensorTypeEnum getType(); + SensorTypeEnum type(); String getData(); diff --git a/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/wrapper/SensorWrapper.java b/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/wrapper/SensorWrapper.java index b2b18535..4650889a 100644 --- a/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/wrapper/SensorWrapper.java +++ b/robo4j-hw-lego/src/main/java/com/robo4j/hw/lego/wrapper/SensorWrapper.java @@ -53,12 +53,12 @@ public SensorWrapper(Sensor sensor, DigitalPortEnum port, SensorTypeEnum sensorT } @Override - public SensorTypeEnum getType() { + public SensorTypeEnum type() { return sensorType; } @Override - public DigitalPortEnum getPort() { + public DigitalPortEnum port() { return port; } diff --git a/robo4j-units-lego/pom.xml b/robo4j-units-lego/pom.xml index e5a2f387..3617e881 100644 --- a/robo4j-units-lego/pom.xml +++ b/robo4j-units-lego/pom.xml @@ -44,8 +44,17 @@ com.robo4j robo4j-socket-http + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-simple + test + org.junit.jupiter junit-jupiter-engine diff --git a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/GripperSonicTankPlatformExample.java b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/GripperSonicTankPlatformExample.java index a1097971..fb20e0cf 100644 --- a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/GripperSonicTankPlatformExample.java +++ b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/GripperSonicTankPlatformExample.java @@ -21,6 +21,8 @@ import com.robo4j.RoboReference; import com.robo4j.hw.lego.util.EscapeButtonUtil; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.InputStream; @@ -28,31 +30,31 @@ /** * GripperSonicTankPlatformExample is the simple example of tank platform based LegoEV3 device * - * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class GripperSonicTankPlatformExample { + private static final Logger LOGGER = LoggerFactory.getLogger(GripperSonicTankPlatformExample.class); public static void main(String[] args) throws Exception { - final String robo4jConfig= "robo4jGripperSonicTankPlatform.xml"; + final String robo4jConfig = "robo4jGripperSonicTankPlatform.xml"; InputStream settings = GripperSonicTankPlatformExample.class.getClassLoader().getResourceAsStream(robo4jConfig); if (args.length != 1) { - System.out.println(String.format("No file specified, using default %s", robo4jConfig)); + LOGGER.info("No file specified, using default {}", robo4jConfig); } else { settings = new FileInputStream(args[0]); } final RoboBuilder builder = new RoboBuilder(); - if(settings == null){ - System.out.println("Could not find the settings for test!"); + if (settings == null) { + LOGGER.warn("Could not find the settings for test!"); System.exit(2); } builder.add(settings); RoboContext system = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(system)); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(system)); system.start(); diff --git a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraPushTankPlatformExample.java b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraPushTankPlatformExample.java index 7613be00..9f2d7f40 100644 --- a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraPushTankPlatformExample.java +++ b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraPushTankPlatformExample.java @@ -21,9 +21,10 @@ import com.robo4j.RoboReference; import com.robo4j.hw.lego.util.EscapeButtonUtil; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.FileInputStream; -import java.io.InputStream; /** * InfraPushTankPlatformExample lego platform example with push and infra red sensor @@ -32,28 +33,28 @@ * @author Miroslav Wengner (@miragemiko) */ public class InfraPushTankPlatformExample { + private static final Logger LOGGER = LoggerFactory.getLogger(InfraPushTankPlatformExample.class); public static void main(String[] args) throws Exception { - final String robo4jSystem = "robo4jSystem.xml"; - final String robo4jConfig= "robo4jInfraPushTankPlatformExample.xml"; - final InputStream systemSystem = InfraSensorExample.class.getClassLoader().getResourceAsStream(robo4jSystem); - InputStream settings = GripperSonicTankPlatformExample.class.getClassLoader().getResourceAsStream(robo4jConfig); + final var robo4jSystem = "robo4jSystem.xml"; + final var robo4jConfig = "robo4jInfraPushTankPlatformExample.xml"; + final var systemSystem = InfraSensorExample.class.getClassLoader().getResourceAsStream(robo4jSystem); + var settings = GripperSonicTankPlatformExample.class.getClassLoader().getResourceAsStream(robo4jConfig); if (args.length != 1) { - System.out.println(String.format("No file specified, using default %s", robo4jConfig)); + LOGGER.info("No file specified, using default {}", robo4jConfig); } else { settings = new FileInputStream(args[0]); } - final RoboBuilder builder = new RoboBuilder(systemSystem); - if(settings == null){ - System.out.println("Could not find the settings for test!"); + final var builder = new RoboBuilder(systemSystem); + if (settings == null) { + LOGGER.warn("Could not find the settings for test!"); System.exit(2); } builder.add(settings); RoboContext system = builder.build(); - System.out.println(SystemUtil.printStateReport(system)); - + LOGGER.info(SystemUtil.printStateReport(system)); system.start(); diff --git a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraSensorExample.java b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraSensorExample.java index 0078bc59..caf5e104 100644 --- a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraSensorExample.java +++ b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/InfraSensorExample.java @@ -21,49 +21,51 @@ import com.robo4j.RoboReference; import com.robo4j.hw.lego.util.EscapeButtonUtil; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.FileInputStream; -import java.io.InputStream; /** * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class InfraSensorExample { + private static final Logger LOGGER = LoggerFactory.getLogger(InfraSensorExample.class); - public static void main(String[] args) throws Exception { - final String robo4jConfig = "robo4jInfraExample.xml"; - InputStream settings = InfraSensorExample.class.getClassLoader().getResourceAsStream(robo4jConfig); - if (args.length != 1) { - System.out.println(String.format("No file specified, using default %s", robo4jConfig)); - } else { - settings = new FileInputStream(args[0]); - } + public static void main(String[] args) throws Exception { + final var robo4jConfig = "robo4jInfraExample.xml"; + var settings = InfraSensorExample.class.getClassLoader().getResourceAsStream(robo4jConfig); + if (args.length != 1) { + LOGGER.info("No file specified, using default {}", robo4jConfig); + } else { + settings = new FileInputStream(args[0]); + } - final RoboBuilder builder = new RoboBuilder(); - if (settings == null) { - System.out.println("Could not find the settings for test!"); - System.exit(2); - } + final var builder = new RoboBuilder(); + if (settings == null) { + LOGGER.warn("Could not find the settings for test!"); + System.exit(2); + } - builder.add(settings); - RoboContext system = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(system)); + builder.add(settings); + RoboContext system = builder.build(); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(system)); - system.start(); + system.start(); - RoboReference lcd = system.getReference("lcd"); - lcd.sendMessage("Robo4J.io"); + RoboReference lcd = system.getReference("lcd"); + lcd.sendMessage("Robo4J.io"); - RoboReference infraSensor = system.getReference("infraSensor"); - infraSensor.sendMessage("start"); + RoboReference infraSensor = system.getReference("infraSensor"); + infraSensor.sendMessage("start"); - shutdown(system); - } + shutdown(system); + } - private static void shutdown(RoboContext system) { - EscapeButtonUtil.waitForPressAndRelease(); - system.shutdown(); - } + private static void shutdown(RoboContext system) { + EscapeButtonUtil.waitForPressAndRelease(); + system.shutdown(); + } } diff --git a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/controller/ReportController.java b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/controller/ReportController.java index 6236e9a0..84209b45 100644 --- a/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/controller/ReportController.java +++ b/robo4j-units-lego/src/examples/java/com/robo4j/units/lego/controller/ReportController.java @@ -18,12 +18,15 @@ import com.robo4j.RoboContext; import com.robo4j.RoboUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class ReportController extends RoboUnit { + private static final Logger LOGGER = LoggerFactory.getLogger(ReportController.class); public ReportController(RoboContext context, String id) { super(Object.class, context, id); @@ -31,6 +34,6 @@ public ReportController(RoboContext context, String id) { @Override public void onMessage(Object message) { - System.out.println(getClass().getSimpleName() + "report: " + message.toString()); + LOGGER.info("report: {}", message.toString()); } } diff --git a/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/MotorTestWrapper.java b/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/MotorTestWrapper.java index 2f6f5d84..3d6abee1 100644 --- a/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/MotorTestWrapper.java +++ b/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/MotorTestWrapper.java @@ -19,6 +19,8 @@ import com.robo4j.hw.lego.ILegoMotor; import com.robo4j.hw.lego.enums.AnalogPortEnum; import com.robo4j.hw.lego.enums.MotorTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Simple LegoMindstorm Mock Motor @@ -28,6 +30,8 @@ */ public class MotorTestWrapper implements ILegoMotor { + private static final Logger LOGGER = LoggerFactory.getLogger(MotorTestWrapper.class); + private final AnalogPortEnum port; private final MotorTypeEnum type; private boolean moving; @@ -52,25 +56,25 @@ public MotorTypeEnum getType() { @Override public void forward() { moving = true; - System.out.println(String.format("MotorTest.forward port:%s, type: %s, moving: %b ", port, type, moving)); + LOGGER.info("MotorTest.forward port:{}, type: {}, moving: {} ", port, type, moving); } @Override public void backward() { moving = true; - System.out.println(String.format("MotorTest.backward port:%s, type: %s, moving: %b ", port, type, moving)); + LOGGER.info("MotorTest.backward port:{}, type: {}, moving: {} ", port, type, moving); } @Override public void stop() { moving = false; - System.out.println(String.format("MotorTest.stop port:%s, type: %s, moving: %b ", port, type, moving)); + LOGGER.info("MotorTest.stop port:{}, type: {}, moving: {} ", port, type, moving); } @Override public void rotate(int val) { - System.out.println("rotate: " + val); + LOGGER.info("rotate: {}", val); } @Override @@ -80,14 +84,14 @@ public boolean isMoving() { @Override public void setSpeed(int speed) { - System.out.println("speed: " + speed); + LOGGER.info("speed: {}", speed); this.speed = speed; } @Override public void close() { moving = false; - System.out.println(String.format("MotorTest.close port:%s, type: %s, moving: %b ", port, type, moving)); + LOGGER.info("MotorTest.close port:{}, type: {}, moving: {} ", port, type, moving); } @Override diff --git a/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/SensorTestWrapper.java b/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/SensorTestWrapper.java index fd5b342f..f9bcefe1 100644 --- a/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/SensorTestWrapper.java +++ b/robo4j-units-lego/src/test/java/com/robo4j/hw/lego/wrapper/SensorTestWrapper.java @@ -19,6 +19,8 @@ import com.robo4j.hw.lego.ILegoSensor; import com.robo4j.hw.lego.enums.DigitalPortEnum; import com.robo4j.hw.lego.enums.SensorTypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Simple LegoMindstorm Mock Sensor @@ -26,45 +28,28 @@ * @author Marcus Hirt (@hirt) * @author Miro Wengner (@miragemiko) */ -public class SensorTestWrapper implements ILegoSensor { - - private final DigitalPortEnum port; - private final SensorTypeEnum type; - - public SensorTestWrapper(DigitalPortEnum port, SensorTypeEnum type) { - this.port = port; - this.type = type; - } - - @Override - public DigitalPortEnum getPort() { - return port; - } - - @Override - public SensorTypeEnum getType() { - return type; - } - - @Override - public String getData() { - System.out.println(String.format("SensorTest.getData port:%s, type: %s", port, type)); - return "data"; - } - - @Override - public void activate(boolean status) { - System.out.println(String.format("SensorTest.activate %s, port:%s, type: %s", status, port, type)); - } - - @Override - public void close() { - System.out.println(String.format("SensorTest.close port:%s, type: %s", port, type)); - } - - @Override - public String toString() { - return "SensorTestWrapper{" + "port=" + port + ", type=" + type + '}'; - } +public record SensorTestWrapper(DigitalPortEnum port, SensorTypeEnum type) implements ILegoSensor { + private static final Logger LOGGER = LoggerFactory.getLogger(SensorTestWrapper.class); + + @Override + public String getData() { + LOGGER.info("SensorTest.getData port:{}, type: {}", port, type); + return "data"; + } + + @Override + public void activate(boolean status) { + LOGGER.info("SensorTest.activate {}, port:{}, type: {}", status, port, type); + } + + @Override + public void close() { + LOGGER.info("SensorTest.close port:{}, type: {}", port, type); + } + + @Override + public String toString() { + return "SensorTestWrapper{" + "port=" + port + ", type=" + type + '}'; + } } diff --git a/robo4j-units-lego/src/test/java/com/robo4j/units/lego/BrickButtonTests.java b/robo4j-units-lego/src/test/java/com/robo4j/units/lego/BrickButtonTests.java index 78a72847..b80dc180 100644 --- a/robo4j-units-lego/src/test/java/com/robo4j/units/lego/BrickButtonTests.java +++ b/robo4j-units-lego/src/test/java/com/robo4j/units/lego/BrickButtonTests.java @@ -18,8 +18,8 @@ import com.robo4j.units.lego.enums.PlateButtonEnum; import org.junit.jupiter.api.Test; - -import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -30,11 +30,13 @@ * @author Miro Wengner (@miragemiko) */ class BrickButtonTests { + private static final Logger LOGGER = LoggerFactory.getLogger(BrickButtonTests.class); @Test - void basicButtonPlateTest(){ - Set buttonNames = PlateButtonEnum.getButtonNames(); - System.out.println("buttonNames: " + buttonNames); + void basicButtonPlateTest() { + var buttonNames = PlateButtonEnum.getButtonNames(); + + LOGGER.info("buttonNames: {}", buttonNames); assertNotNull(buttonNames); } diff --git a/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankTestUnit.java b/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankTestUnit.java index 2d7cb6dc..3798735d 100644 --- a/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankTestUnit.java +++ b/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankTestUnit.java @@ -23,6 +23,8 @@ import com.robo4j.hw.lego.enums.AnalogPortEnum; import com.robo4j.hw.lego.enums.MotorTypeEnum; import com.robo4j.hw.lego.wrapper.MotorTestWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Simple Tank Test Platform Unit @@ -31,10 +33,11 @@ * @author Miro Wengner (@miragemiko) */ public class SimpleTankTestUnit extends SimpleTankUnit { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTankTestUnit.class); public SimpleTankTestUnit(RoboContext context, String id) { super(context, id); - System.out.println(getClass().getSimpleName() + " constructor: id: " + id); + LOGGER.info(" constructor: id: {}", id); } @Override @@ -52,5 +55,4 @@ protected void onInitialization(Configuration configuration) throws Configuratio } - } diff --git a/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankUnitMock.java b/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankUnitMock.java index cb3f9a8f..145ad9de 100644 --- a/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankUnitMock.java +++ b/robo4j-units-lego/src/test/java/com/robo4j/units/lego/SimpleTankUnitMock.java @@ -23,12 +23,15 @@ import com.robo4j.hw.lego.enums.AnalogPortEnum; import com.robo4j.hw.lego.enums.MotorTypeEnum; import com.robo4j.hw.lego.wrapper.MotorTestWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Marcus Hirt (@hirt) * @author Miro Wengner (@miragemiko) */ public class SimpleTankUnitMock extends SimpleTankUnit { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTankUnitMock.class); public SimpleTankUnitMock(RoboContext context, String id) { super(context, id); @@ -45,7 +48,7 @@ protected void onInitialization(Configuration configuration) throws Configuratio @Override public void shutdown() { super.shutdown(); - System.out.println("executor is down"); + LOGGER.info("executor is down"); } @SuppressWarnings("unchecked") diff --git a/robo4j-units-rpi-http/pom.xml b/robo4j-units-rpi-http/pom.xml index b3d40fd3..f6140cf0 100644 --- a/robo4j-units-rpi-http/pom.xml +++ b/robo4j-units-rpi-http/pom.xml @@ -39,8 +39,17 @@ com.robo4j robo4j-units-rpi + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-simple + test + org.junit.jupiter junit-jupiter-engine diff --git a/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraDecoratedImageProducerConsumerTests.java b/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraDecoratedImageProducerConsumerTests.java index 36293516..38b8ddc4 100644 --- a/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraDecoratedImageProducerConsumerTests.java +++ b/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraDecoratedImageProducerConsumerTests.java @@ -17,14 +17,13 @@ package com.robo4j.units.rpi.http.camera; import com.robo4j.RoboBuilder; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.socket.http.codec.CameraMessage; import com.robo4j.socket.http.util.RoboHttpUtils; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.io.InputStream; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,55 +33,56 @@ * @author Miro Wengner (@miragemiko) */ class CameraDecoratedImageProducerConsumerTests { - - @Test - void decoratorProducerConsumerTest() throws Exception { - - RoboBuilder builderProducer = new RoboBuilder( - Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemProducer.xml")); - InputStream clientConfigInputStream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("robo_camera_producer_decorated_test.xml"); - builderProducer.add(clientConfigInputStream); - RoboContext producerSystem = builderProducer.build(); - - RoboBuilder builderConsumer = new RoboBuilder( - Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemConsumer.xml")); - InputStream serverConfigInputStream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("robo_camera_consumer_decorated_test.xml"); - builderConsumer.add(serverConfigInputStream); - RoboContext consumerSystem = builderConsumer.build(); - - long startTime = System.currentTimeMillis(); - consumerSystem.start(); - producerSystem.start(); - - RoboReference imageProducer = producerSystem.getReference("imageController"); + private static final Logger LOGGER = LoggerFactory.getLogger(CameraDecoratedImageProducerConsumerTests.class); + + @Test + void decoratorProducerConsumerTest() throws Exception { + + var builderProducer = new RoboBuilder( + Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemProducer.xml")); + var clientConfigInputStream = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("robo_camera_producer_decorated_test.xml"); + builderProducer.add(clientConfigInputStream); + var producerSystem = builderProducer.build(); + + var builderConsumer = new RoboBuilder( + Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemConsumer.xml")); + var serverConfigInputStream = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("robo_camera_consumer_decorated_test.xml"); + builderConsumer.add(serverConfigInputStream); + var consumerSystem = builderConsumer.build(); + + long startTime = System.currentTimeMillis(); + consumerSystem.start(); + producerSystem.start(); + + RoboReference imageProducer = producerSystem.getReference("imageController"); RoboReference imageConsumer = consumerSystem.getReference("imageProcessor"); - CountDownLatch startLatchConsumer = imageConsumer + var startLatchConsumer = imageConsumer .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_START_LATCH).get(); startLatchConsumer.await(5, TimeUnit.MINUTES); - CountDownLatch imagesLatchProducer = imageProducer - .getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_GENERATED_IMAGES_LATCH).get(); - imagesLatchProducer.await(5, TimeUnit.MINUTES); - Integer totalImagesProducer = imageProducer.getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_TOTAL_IMAGES) - .get(); + var imagesLatchProducer = imageProducer + .getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_GENERATED_IMAGES_LATCH).get(); + imagesLatchProducer.await(5, TimeUnit.MINUTES); + Integer totalImagesProducer = imageProducer.getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_TOTAL_IMAGES) + .get(); - CountDownLatch imagesLatchConsumer = imageConsumer - .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_IMAGES_LATCH).get(); - imagesLatchConsumer.await(5, TimeUnit.MINUTES); - Integer totalImagesConsumer = imageConsumer.getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_RECEIVED_IMAGES) - .get(); - RoboHttpUtils.printMeasuredTime(getClass(), "duration", startTime); + var imagesLatchConsumer = imageConsumer + .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_IMAGES_LATCH).get(); + imagesLatchConsumer.await(5, TimeUnit.MINUTES); + Integer totalImagesConsumer = imageConsumer.getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_RECEIVED_IMAGES) + .get(); + RoboHttpUtils.printMeasuredTime(getClass(), "duration", startTime); assertEquals(totalImagesProducer, totalImagesConsumer); - producerSystem.shutdown(); - consumerSystem.shutdown(); + producerSystem.shutdown(); + consumerSystem.shutdown(); - System.out.println("Press to quit!"); + LOGGER.info("Press to quit!"); - } + } } diff --git a/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageConsumerTestUnit.java b/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageConsumerTestUnit.java index a8704861..32a8d45b 100644 --- a/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageConsumerTestUnit.java +++ b/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageConsumerTestUnit.java @@ -16,13 +16,11 @@ */ package com.robo4j.units.rpi.http.camera; -import com.robo4j.AttributeDescriptor; -import com.robo4j.ConfigurationException; -import com.robo4j.DefaultAttributeDescriptor; -import com.robo4j.RoboContext; -import com.robo4j.RoboUnit; +import com.robo4j.*; import com.robo4j.configuration.Configuration; import com.robo4j.socket.http.codec.CameraMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Base64; import java.util.concurrent.CountDownLatch; @@ -33,34 +31,35 @@ * @author Miro Wengner (@miragemiko) */ public class CameraImageConsumerTestUnit extends RoboUnit { - public static final String ATTR_IMAGES_LATCH = "messagesLatch"; - public static final String ATTR_START_LATCH = "startLatch"; - public static final String ATTR_RECEIVED_IMAGES = "numberOfReceivedImages"; - public static final String PROP_TOTAL_NUMBER_MESSAGES = "totalNumberMessages"; + public static final String ATTR_IMAGES_LATCH = "messagesLatch"; + public static final String ATTR_START_LATCH = "startLatch"; + public static final String ATTR_RECEIVED_IMAGES = "numberOfReceivedImages"; + public static final String PROP_TOTAL_NUMBER_MESSAGES = "totalNumberMessages"; - public static final DefaultAttributeDescriptor DESCRIPTOR_IMAGES_LATCH = DefaultAttributeDescriptor - .create(CountDownLatch.class, ATTR_IMAGES_LATCH); + public static final DefaultAttributeDescriptor DESCRIPTOR_IMAGES_LATCH = DefaultAttributeDescriptor + .create(CountDownLatch.class, ATTR_IMAGES_LATCH); public static final DefaultAttributeDescriptor DESCRIPTOR_START_LATCH = DefaultAttributeDescriptor .create(CountDownLatch.class, ATTR_START_LATCH); - public static final AttributeDescriptor DESCRIPTOR_RECEIVED_IMAGES = new DefaultAttributeDescriptor<>( - Integer.class, ATTR_RECEIVED_IMAGES); + public static final AttributeDescriptor DESCRIPTOR_RECEIVED_IMAGES = new DefaultAttributeDescriptor<>( + Integer.class, ATTR_RECEIVED_IMAGES); + private static final Logger LOGGER = LoggerFactory.getLogger(CameraImageConsumerTestUnit.class); - private volatile AtomicInteger counter = new AtomicInteger(0); - private CountDownLatch startLatch = new CountDownLatch(1); + private final AtomicInteger counter = new AtomicInteger(0); + private final CountDownLatch startLatch = new CountDownLatch(1); private CountDownLatch messagesLatch; - public CameraImageConsumerTestUnit(RoboContext context, String id) { - super(CameraMessage.class, context, id); - } + public CameraImageConsumerTestUnit(RoboContext context, String id) { + super(CameraMessage.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { - int totalNumber = configuration.getInteger(PROP_TOTAL_NUMBER_MESSAGES, 0); - if (totalNumber > 0) { - messagesLatch = new CountDownLatch(totalNumber); - } - } + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { + int totalNumber = configuration.getInteger(PROP_TOTAL_NUMBER_MESSAGES, 0); + if (totalNumber > 0) { + messagesLatch = new CountDownLatch(totalNumber); + } + } @Override public void start() { @@ -69,35 +68,34 @@ public void start() { } @Override - public void onMessage(CameraMessage message) { - if (message.getImage() != null) { - final byte[] bytes = Base64.getDecoder().decode(message.getImage()); - System.out.println(getClass().getSimpleName() + " Delivered image: " + counter.incrementAndGet() + " size: " - + bytes.length + " imageSize: " + message.getImage().length()); - if (messagesLatch != null) { - messagesLatch.countDown(); - } - } else { - throw new IllegalStateException("no image view"); - } - } + public void onMessage(CameraMessage message) { + if (message.getImage() != null) { + final byte[] bytes = Base64.getDecoder().decode(message.getImage()); + LOGGER.info(" Delivered image: {} size: {} imageSize: {}", counter.incrementAndGet(), bytes.length, message.getImage().length()); + if (messagesLatch != null) { + messagesLatch.countDown(); + } + } else { + throw new IllegalStateException("no image view"); + } + } - @SuppressWarnings("unchecked") - @Override - protected synchronized R onGetAttribute(AttributeDescriptor descriptor) { - if (descriptor.getAttributeType() == Integer.class - && descriptor.getAttributeName().equals(ATTR_RECEIVED_IMAGES)) { - return (R) Integer.valueOf(counter.get()); - } - if (descriptor.getAttributeName().equals(ATTR_IMAGES_LATCH) - && descriptor.getAttributeType() == CountDownLatch.class) { - return (R) messagesLatch; - } + @SuppressWarnings("unchecked") + @Override + protected synchronized R onGetAttribute(AttributeDescriptor descriptor) { + if (descriptor.getAttributeType() == Integer.class + && descriptor.getAttributeName().equals(ATTR_RECEIVED_IMAGES)) { + return (R) Integer.valueOf(counter.get()); + } + if (descriptor.getAttributeName().equals(ATTR_IMAGES_LATCH) + && descriptor.getAttributeType() == CountDownLatch.class) { + return (R) messagesLatch; + } if (descriptor.getAttributeName().equals(ATTR_START_LATCH) && descriptor.getAttributeType() == CountDownLatch.class) { return (R) startLatch; } - return super.onGetAttribute(descriptor); - } + return super.onGetAttribute(descriptor); + } } diff --git a/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageProducerConsumerTests.java b/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageProducerConsumerTests.java index a050d946..2507975b 100644 --- a/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageProducerConsumerTests.java +++ b/robo4j-units-rpi-http/src/test/java/com/robo4j/units/rpi/http/camera/CameraImageProducerConsumerTests.java @@ -22,6 +22,8 @@ import com.robo4j.socket.http.codec.CameraMessage; import com.robo4j.socket.http.util.RoboHttpUtils; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.concurrent.CountDownLatch; @@ -34,59 +36,58 @@ * @author Miro Wengner (@miragemiko) */ class CameraImageProducerConsumerTests { + private static final Logger LOGGER = LoggerFactory.getLogger(CameraImageProducerConsumerTests.class); - @Test - void cameraImageProdConTest() throws Exception { + @Test + void cameraImageProdConTest() throws Exception { - RoboBuilder builderProducer = new RoboBuilder( - Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemProducer.xml")); - InputStream clientConfigInputStream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("robo_camera_producer_test.xml"); - builderProducer.add(clientConfigInputStream); - RoboContext producerSystem = builderProducer.build(); + RoboBuilder builderProducer = new RoboBuilder( + Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemProducer.xml")); + InputStream clientConfigInputStream = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("robo_camera_producer_test.xml"); + builderProducer.add(clientConfigInputStream); + RoboContext producerSystem = builderProducer.build(); - RoboBuilder builderConsumer = new RoboBuilder( - Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemConsumer.xml")); - InputStream serverConfigInputStream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("robo_camera_consumer_test.xml"); - builderConsumer.add(serverConfigInputStream); + RoboBuilder builderConsumer = new RoboBuilder( + Thread.currentThread().getContextClassLoader().getResourceAsStream("robo4jSystemConsumer.xml")); + InputStream serverConfigInputStream = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("robo_camera_consumer_test.xml"); + builderConsumer.add(serverConfigInputStream); - RoboContext consumerSystem = builderConsumer.build(); + RoboContext consumerSystem = builderConsumer.build(); - long startTime = System.currentTimeMillis(); - consumerSystem.start(); - producerSystem.start(); + long startTime = System.currentTimeMillis(); + consumerSystem.start(); + producerSystem.start(); RoboReference imageConsumer = consumerSystem.getReference("imageProcessor"); - RoboReference imageProducer = producerSystem.getReference("imageController"); + RoboReference imageProducer = producerSystem.getReference("imageController"); CountDownLatch startConsumerLatch = imageConsumer .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_START_LATCH).get(); startConsumerLatch.await(5, TimeUnit.MINUTES); - Integer totalImagesProducer = imageProducer.getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_TOTAL_IMAGES) - .get(); - CountDownLatch imageProducerLatch = imageProducer - .getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_GENERATED_IMAGES_LATCH).get(); - CountDownLatch imageConsumerLatch = imageConsumer - .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_IMAGES_LATCH).get(); - - System.out.println("LATCH"); - imageProducerLatch.await(5, TimeUnit.MINUTES); - System.out.println("ONE"); - imageConsumerLatch.await(5, TimeUnit.MINUTES); - System.out.println("TWO"); - - Integer receivedImagesConsumer = imageConsumer - .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_RECEIVED_IMAGES).get(); - assertEquals(totalImagesProducer, receivedImagesConsumer); - - RoboHttpUtils.printMeasuredTime(getClass(), "duration", startTime); - System.out.println("receivedImagesConsumer: " + receivedImagesConsumer); - producerSystem.shutdown(); - consumerSystem.shutdown(); - - System.out.println("Press to quit!"); - - } + Integer totalImagesProducer = imageProducer.getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_TOTAL_IMAGES) + .get(); + CountDownLatch imageProducerLatch = imageProducer + .getAttribute(CameraImageProducerDesTestUnit.DESCRIPTOR_GENERATED_IMAGES_LATCH).get(); + CountDownLatch imageConsumerLatch = imageConsumer + .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_IMAGES_LATCH).get(); + + LOGGER.info("LATCH"); + imageProducerLatch.await(5, TimeUnit.MINUTES); + LOGGER.info("ONE"); + imageConsumerLatch.await(5, TimeUnit.MINUTES); + LOGGER.info("TWO"); + + Integer receivedImagesConsumer = imageConsumer + .getAttribute(CameraImageConsumerTestUnit.DESCRIPTOR_RECEIVED_IMAGES).get(); + assertEquals(totalImagesProducer, receivedImagesConsumer); + + RoboHttpUtils.printMeasuredTime(getClass(), "duration", startTime); + LOGGER.info("receivedImagesConsumer: " + receivedImagesConsumer); + producerSystem.shutdown(); + consumerSystem.shutdown(); + + } } diff --git a/robo4j-units-rpi/pom.xml b/robo4j-units-rpi/pom.xml index f5fc5b2f..63c1b989 100644 --- a/robo4j-units-rpi/pom.xml +++ b/robo4j-units-rpi/pom.xml @@ -50,8 +50,17 @@ pi4j-plugin-linuxfs ${pi4j.version} + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-simple + test + org.junit.jupiter junit-jupiter-engine @@ -96,9 +105,11 @@ - + - com.robo4j.units.rpi.led.AdafruitAlphanumericUnitExample + com.robo4j.units.rpi.led.AdafruitAlphanumericUnitExample + diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerExample.java index 634e3ad3..22b29855 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerExample.java @@ -16,50 +16,52 @@ */ package com.robo4j.units.rpi.accelerometer; -import java.io.IOException; -import java.io.InputStream; - import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; /** * Runs the accelerometer continuously and always prints what it reads. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class AccelerometerExample { - private static final String ID_PROCESSOR = "processor"; + private static final String ID_PROCESSOR = "processor"; + private static final Logger LOGGER = LoggerFactory.getLogger(AccelerometerExample.class); - public static void main(String[] args) throws RoboBuilderException, IOException { - RoboBuilder builder = new RoboBuilder(); - InputStream settings = Thread.currentThread().getContextClassLoader() - .getResourceAsStream("accelerometerexample.xml"); - if (settings == null) { - System.out.println("Could not find the settings for the GyroExample!"); - System.exit(2); - } - builder.add(settings); - builder.add(AccelerometerProcessor.class, ID_PROCESSOR); - RoboContext ctx = builder.build(); + public static void main(String[] args) throws RoboBuilderException, IOException { + var builder = new RoboBuilder(); + var settings = Thread.currentThread().getContextClassLoader() + .getResourceAsStream("accelerometerexample.xml"); + if (settings == null) { + LOGGER.warn("Could not find the settings for the GyroExample!"); + System.exit(2); + } + builder.add(settings); + builder.add(AccelerometerProcessor.class, ID_PROCESSOR); + RoboContext ctx = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(ctx)); - ctx.start(); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - RoboReference accelerometer = ctx.getReference("accelerometer"); - RoboReference processor = ctx.getReference(ID_PROCESSOR); + RoboReference accelerometer = ctx.getReference("accelerometer"); + RoboReference processor = ctx.getReference(ID_PROCESSOR); - System.out.println("Press to start!"); - System.in.read(); - accelerometer.sendMessage(new AccelerometerRequest(processor, true, (Float3D) -> true)); - System.out.println("Will report angular changes indefinitely.\nPress to quit!"); - System.in.read(); - } + LOGGER.info("Press to start!"); + System.in.read(); + accelerometer.sendMessage(new AccelerometerRequest(processor, true, (Float3D) -> true)); + LOGGER.info("Will report angular changes indefinitely.\nPress to quit!"); + System.in.read(); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerProcessor.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerProcessor.java index ab9f8340..be3c2513 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerProcessor.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/accelerometer/AccelerometerProcessor.java @@ -20,25 +20,29 @@ import com.robo4j.RoboContext; import com.robo4j.RoboUnit; import com.robo4j.configuration.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Example recipient for testing the accelerometer. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class AccelerometerProcessor extends RoboUnit { - public AccelerometerProcessor(RoboContext context, String id) { - super(AccelerometerEvent.class, context, id); - } + private static final Logger LOGGER = LoggerFactory.getLogger(AccelerometerProcessor.class); + + public AccelerometerProcessor(RoboContext context, String id) { + super(AccelerometerEvent.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { - } + } - @Override - public void onMessage(AccelerometerEvent result) { - System.out.println("AccelerometerEvent: " + result.toString()); - } + @Override + public void onMessage(AccelerometerEvent result) { + LOGGER.info("AccelerometerEvent: {}", result.toString()); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/DataEventListenerExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/DataEventListenerExample.java index 655a284b..80db1e68 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/DataEventListenerExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/DataEventListenerExample.java @@ -18,11 +18,12 @@ package com.robo4j.units.rpi.bno; import com.robo4j.RoboBuilder; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.hw.rpi.imu.bno.DataEvent3f; import com.robo4j.units.rpi.imu.BnoRequest; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.InputStream; import java.nio.file.Files; @@ -38,57 +39,58 @@ * @author Miroslav Wengner (@miragemiko) */ public class DataEventListenerExample { + private static final Logger LOGGER = LoggerFactory.getLogger(DataEventListenerExample.class); - public static void main(String[] args) throws Exception { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + public static void main(String[] args) throws Exception { + var classLoader = Thread.currentThread().getContextClassLoader(); - final InputStream systemIS; - final InputStream contextIS; + final InputStream systemIS; + final InputStream contextIS; - switch (args.length) { - case 0: - systemIS = classLoader.getResourceAsStream("bno080DataSystemEmitterExample.xml"); - contextIS = classLoader.getResourceAsStream("bno080GyroExample.xml"); - System.out.println("Default configuration used"); - break; - case 1: - systemIS = classLoader.getResourceAsStream("bno080DataSystemEmitterExample.xml"); - Path contextPath = Paths.get(args[0]); - contextIS = Files.newInputStream(contextPath); - System.out.println("Robo4j config file has been used: " + args[0]); - break; - case 2: - Path systemPath2 = Paths.get(args[0]); - Path contextPath2 = Paths.get(args[1]); - systemIS = Files.newInputStream(systemPath2); - contextIS = Files.newInputStream(contextPath2); - System.out.println(String.format("Custom configuration used system: %s, context: %s", args[0], args[1])); - break; - default: - System.out.println("Could not find the *.xml settings for the CameraClient!"); - System.out.println("java -jar camera.jar system.xml context.xml"); - System.exit(2); - throw new IllegalStateException("see configuration"); - } + switch (args.length) { + case 0: + systemIS = classLoader.getResourceAsStream("bno080DataSystemEmitterExample.xml"); + contextIS = classLoader.getResourceAsStream("bno080GyroExample.xml"); + LOGGER.info("Default configuration used"); + break; + case 1: + systemIS = classLoader.getResourceAsStream("bno080DataSystemEmitterExample.xml"); + Path contextPath = Paths.get(args[0]); + contextIS = Files.newInputStream(contextPath); + LOGGER.info("Robo4j config file has been used: {}", args[0]); + break; + case 2: + Path systemPath2 = Paths.get(args[0]); + Path contextPath2 = Paths.get(args[1]); + systemIS = Files.newInputStream(systemPath2); + contextIS = Files.newInputStream(contextPath2); + LOGGER.info("Custom configuration used system: {}, context: {}", args[0], args[1]); + break; + default: + LOGGER.warn("Could not find the *.xml settings for the CameraClient!"); + LOGGER.warn("java -jar camera.jar system.xml context.xml"); + System.exit(2); + throw new IllegalStateException("see configuration"); + } - RoboBuilder builder = new RoboBuilder(systemIS); - builder.add(contextIS); - RoboContext ctx = builder.build(); + var builder = new RoboBuilder(systemIS); + builder.add(contextIS); + var ctx = builder.build(); - ctx.start(); + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - RoboReference bnoUnit = ctx.getReference("bno"); - RoboReference bnoListenerUnit = ctx.getReference("listener"); + var bnoUnit = ctx.getReference("bno"); + RoboReference bnoListenerUnit = ctx.getReference("listener"); - BnoRequest requestToRegister = new BnoRequest(bnoListenerUnit, BnoRequest.ListenerAction.REGISTER); - bnoUnit.sendMessage(requestToRegister); + BnoRequest requestToRegister = new BnoRequest(bnoListenerUnit, BnoRequest.ListenerAction.REGISTER); + bnoUnit.sendMessage(requestToRegister); - System.out.println("Press to start!"); - System.in.read(); - ctx.shutdown(); + LOGGER.info("Press to start!"); + System.in.read(); + ctx.shutdown(); - } + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/VectorEventListenerExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/VectorEventListenerExample.java index 79beaf40..661be4bc 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/VectorEventListenerExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/bno/VectorEventListenerExample.java @@ -18,13 +18,13 @@ package com.robo4j.units.rpi.bno; import com.robo4j.RoboBuilder; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.hw.rpi.imu.bno.DataEvent3f; -import com.robo4j.net.LookupService; import com.robo4j.net.LookupServiceProvider; import com.robo4j.units.rpi.imu.BnoRequest; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; @@ -40,67 +40,68 @@ * @author Miroslav Wengner (@miragemiko) */ public class VectorEventListenerExample { - public static void main(String[] args) throws Exception { - final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + private static final Logger LOGGER = LoggerFactory.getLogger(VectorEventListenerExample.class); - final InputStream systemIS; - final InputStream contextIS; + public static void main(String[] args) throws Exception { + final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - switch (args.length) { - case 0: - systemIS = classLoader.getResourceAsStream("bno080VectorSystemEmitterExample.xml"); - contextIS = classLoader.getResourceAsStream("bno080VectorExample.xml"); - System.out.println("Default configuration used"); - break; - case 1: - systemIS = classLoader.getResourceAsStream("bno080VectorSystemEmitterExample.xml"); - Path contextPath = Paths.get(args[0]); - contextIS = Files.newInputStream(contextPath); - System.out.println("Robo4j config file has been used: " + args[0]); - break; - case 2: - Path systemPath2 = Paths.get(args[0]); - Path contextPath2 = Paths.get(args[1]); - systemIS = Files.newInputStream(systemPath2); - contextIS = Files.newInputStream(contextPath2); - System.out.println(String.format("Custom configuration used system: %s, context: %s", args[0], args[1])); - break; - default: - System.out.println("Could not find the *.xml settings for the CameraClient!"); - System.out.println("java -jar camera.jar system.xml context.xml"); - System.exit(2); - throw new IllegalStateException("see configuration"); - } + final InputStream systemIS; + final InputStream contextIS; - if (systemIS == null && contextIS == null) { - System.out.println("Could not find the settings for the BNO080 Example!"); - System.exit(2); - } - RoboBuilder builder = new RoboBuilder(systemIS); - builder.add(contextIS); - RoboContext ctx = builder.build(); + switch (args.length) { + case 0: + systemIS = classLoader.getResourceAsStream("bno080VectorSystemEmitterExample.xml"); + contextIS = classLoader.getResourceAsStream("bno080VectorExample.xml"); + LOGGER.info("Default configuration used"); + break; + case 1: + systemIS = classLoader.getResourceAsStream("bno080VectorSystemEmitterExample.xml"); + Path contextPath = Paths.get(args[0]); + contextIS = Files.newInputStream(contextPath); + LOGGER.info("Robo4j config file has been used: {}", args[0]); + break; + case 2: + Path systemPath2 = Paths.get(args[0]); + Path contextPath2 = Paths.get(args[1]); + systemIS = Files.newInputStream(systemPath2); + contextIS = Files.newInputStream(contextPath2); + LOGGER.info("Custom configuration used system: {}, context: {}", args[0], args[1]); + break; + default: + LOGGER.warn("Could not find the *.xml settings for the CameraClient!"); + LOGGER.warn("java -jar camera.jar system.xml context.xml"); + System.exit(2); + throw new IllegalStateException("see configuration"); + } - ctx.start(); + if (systemIS == null && contextIS == null) { + LOGGER.info("Could not find the settings for the BNO080 Example!"); + System.exit(2); + } + var builder = new RoboBuilder(systemIS); + builder.add(contextIS); + var ctx = builder.build(); - LookupService service = LookupServiceProvider.getDefaultLookupService(); - try { - service.start(); - } catch (IOException e) { - e.printStackTrace(); - } + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + var service = LookupServiceProvider.getDefaultLookupService(); + try { + service.start(); + } catch (IOException e) { + LOGGER.error("error starting lookup service", e); + } - RoboReference bnoUnit = ctx.getReference("bno"); - RoboReference bnoListenerUnit = ctx.getReference("listener"); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - BnoRequest requestToRegister = new BnoRequest(bnoListenerUnit, BnoRequest.ListenerAction.REGISTER); - bnoUnit.sendMessage(requestToRegister); + RoboReference bnoUnit = ctx.getReference("bno"); + RoboReference bnoListenerUnit = ctx.getReference("listener"); - System.out.println("Press to start!"); - System.in.read(); - ctx.shutdown(); + BnoRequest requestToRegister = new BnoRequest(bnoListenerUnit, BnoRequest.ListenerAction.REGISTER); + bnoUnit.sendMessage(requestToRegister); - } + LOGGER.info("Press to start!"); + System.in.read(); + ctx.shutdown(); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSExample.java index 52834a32..458a4b68 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSExample.java @@ -16,61 +16,63 @@ */ package com.robo4j.units.rpi.gps; -import java.io.IOException; - import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.hw.rpi.gps.GPSEvent; import com.robo4j.units.rpi.gps.GPSRequest.Operation; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; /** * Runs the gyro continuously. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class GPSExample { - private static final String ID_PROCESSOR = "processor"; - private static final String ID_GPS = "gps"; + private static final Logger LOGGER = LoggerFactory.getLogger(GPSExample.class); + private static final String ID_PROCESSOR = "processor"; + private static final String ID_GPS = "gps"; - public static void main(String[] args) throws RoboBuilderException, IOException { - RoboBuilder builder = new RoboBuilder(); - builder.add(MtkGPSUnit.class, ID_GPS); - builder.add(GPSProcessor.class, ID_PROCESSOR); - RoboContext ctx = builder.build(); + public static void main(String[] args) throws RoboBuilderException, IOException { + var builder = new RoboBuilder(); + builder.add(MtkGPSUnit.class, ID_GPS); + builder.add(GPSProcessor.class, ID_PROCESSOR); + var ctx = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(ctx)); - ctx.start(); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - RoboReference gps = ctx.getReference(ID_GPS); - RoboReference processor = ctx.getReference(ID_PROCESSOR); + RoboReference gps = ctx.getReference(ID_GPS); + RoboReference processor = ctx.getReference(ID_PROCESSOR); - System.out.println("Press to start requesting events, then press enter again to stop requesting events!"); - System.in.read(); + LOGGER.info("Press to start requesting events, then press enter again to stop requesting events!"); + System.in.read(); - System.out.println("Requesting GPS events! Press to stop!"); - gps.sendMessage(new GPSRequest(processor, Operation.REGISTER)); - System.in.read(); + LOGGER.info("Requesting GPS events! Press to stop!"); + gps.sendMessage(new GPSRequest(processor, Operation.REGISTER)); + System.in.read(); - System.out.println("Ending requesting GPS events..."); - gps.sendMessage(new GPSRequest(processor, Operation.UNREGISTER)); - // Note that we can still get a few more events after this, and that is - // quite fine. ;) - System.out.println("All done! Press to quit!"); - System.in.read(); + LOGGER.info("Ending requesting GPS events..."); + gps.sendMessage(new GPSRequest(processor, Operation.UNREGISTER)); + // Note that we can still get a few more events after this, and that is + // quite fine. ;) + LOGGER.info("All done! Press to quit!"); + System.in.read(); - System.out.println("Exiting! Bye!"); - ctx.shutdown(); + LOGGER.info("Exiting! Bye!"); + ctx.shutdown(); - // Seems Pi4J keeps an executor with non-daemon threads around after - // we've used the serial port, even after closing it. :/ - System.exit(0); - } + // Seems Pi4J keeps an executor with non-daemon threads around after + // we've used the serial port, even after closing it. :/ + System.exit(0); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSProcessor.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSProcessor.java index 0bc520fa..f812761f 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSProcessor.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gps/GPSProcessor.java @@ -21,25 +21,29 @@ import com.robo4j.RoboUnit; import com.robo4j.configuration.Configuration; import com.robo4j.hw.rpi.gps.AbstractGPSEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Example recipient for GPS events. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class GPSProcessor extends RoboUnit { - public GPSProcessor(RoboContext context, String id) { - super(AbstractGPSEvent.class, context, id); - } + private static final Logger LOGGER = LoggerFactory.getLogger(GPSProcessor.class); + + public GPSProcessor(RoboContext context, String id) { + super(AbstractGPSEvent.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { - } + } - @Override - public void onMessage(AbstractGPSEvent result) { - System.out.println("GPSEvent: " + result.toString()); - } + @Override + public void onMessage(AbstractGPSEvent result) { + LOGGER.info("GPSEvent: {}", result.toString()); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroExample.java index 183d347b..e3add64f 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroExample.java @@ -18,49 +18,50 @@ import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.math.geometry.Tuple3f; import com.robo4j.units.rpi.gyro.GyroRequest.GyroAction; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; -import java.io.InputStream; /** * Runs the gyro continuously. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class GyroExample { - private static final String ID_PROCESSOR = "processor"; + private static final Logger LOGGER = LoggerFactory.getLogger(GyroExample.class); + private static final String ID_PROCESSOR = "processor"; - public static void main(String[] args) throws RoboBuilderException, IOException { - RoboBuilder builder = new RoboBuilder(); - InputStream settings = GyroExample.class.getClassLoader().getResourceAsStream("gyroexample.xml"); - if (settings == null) { - System.out.println("Could not find the settings for the GyroExample!"); - System.exit(2); - } - builder.add(settings); - builder.add(GyroProcessor.class, ID_PROCESSOR); - RoboContext ctx = builder.build(); + public static void main(String[] args) throws RoboBuilderException, IOException { + var builder = new RoboBuilder(); + var settings = GyroExample.class.getClassLoader().getResourceAsStream("gyroexample.xml"); + if (settings == null) { + LOGGER.warn("Could not find the settings for the GyroExample!"); + System.exit(2); + } + builder.add(settings); + builder.add(GyroProcessor.class, ID_PROCESSOR); + var ctx = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(ctx)); - ctx.start(); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - RoboReference gyro = ctx.getReference("gyro"); - RoboReference processor = ctx.getReference(ID_PROCESSOR); + RoboReference gyro = ctx.getReference("gyro"); + RoboReference processor = ctx.getReference(ID_PROCESSOR); - System.out.println("Let the gyro unit be absolutely still, then press enter to calibrate and start!"); - System.in.read(); - gyro.sendMessage(new GyroRequest(processor, GyroAction.CONTINUOUS, new Tuple3f(1.0f, 1.0f, 1.0f))); - System.out.println("Will report angular changes indefinitely.\nPress to quit!"); - System.in.read(); - } + LOGGER.info("Let the gyro unit be absolutely still, then press enter to calibrate and start!"); + System.in.read(); + gyro.sendMessage(new GyroRequest(processor, GyroAction.CONTINUOUS, new Tuple3f(1.0f, 1.0f, 1.0f))); + LOGGER.info("Will report angular changes indefinitely.\nPress to quit!"); + System.in.read(); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroProcessor.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroProcessor.java index 40431d51..efb3bcbf 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroProcessor.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/gyro/GyroProcessor.java @@ -20,25 +20,29 @@ import com.robo4j.RoboContext; import com.robo4j.RoboUnit; import com.robo4j.configuration.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Example recipient for gyro events. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class GyroProcessor extends RoboUnit { - public GyroProcessor(RoboContext context, String id) { - super(GyroEvent.class, context, id); - } + private static final Logger LOGGER = LoggerFactory.getLogger(GyroProcessor.class); + + public GyroProcessor(RoboContext context, String id) { + super(GyroEvent.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { - } + } - @Override - public void onMessage(GyroEvent result) { - System.out.println("GyroEvent: " + result.toString()); - } + @Override + public void onMessage(GyroEvent result) { + LOGGER.info("GyroEvent: {}", result.toString()); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitAlphanumericUnitExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitAlphanumericUnitExample.java index 43fa813c..8346df01 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitAlphanumericUnitExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitAlphanumericUnitExample.java @@ -17,69 +17,67 @@ package com.robo4j.units.rpi.led; -import java.io.InputStream; -import java.nio.charset.Charset; +import com.robo4j.RoboBuilder; +import com.robo4j.RoboReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.nio.charset.StandardCharsets; import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import com.robo4j.RoboBuilder; -import com.robo4j.RoboContext; -import com.robo4j.RoboReference; - /** * https://learn.adafruit.com/adafruit-led-backpack/0-54-alphanumeric - * + *

* demo: Continually sending defined String * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class AdafruitAlphanumericUnitExample { + private static final Logger LOGGER = LoggerFactory.getLogger(AdafruitAlphanumericUnitExample.class); + private static final byte[] MESSAGE = "HelloMAMAPAPAMAXIELLA".getBytes(StandardCharsets.US_ASCII); + private static final byte[] BUFFER = {' ', ' ', ' ', ' '}; - private static final byte[] MESSAGE = "HelloMAMAPAPAMAXIELLA".getBytes(StandardCharsets.US_ASCII); - private static final byte[] BUFFER = { ' ', ' ', ' ', ' ' }; - - public static void main(String[] args) throws Exception { - ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - InputStream settings = AdafruitBiColor24BackpackExample.class.getClassLoader().getResourceAsStream("alphanumericexample.xml"); - RoboContext ctx = new RoboBuilder().add(settings).build(); + public static void main(String[] args) throws Exception { + var executor = Executors.newSingleThreadScheduledExecutor(); + var settings = AdafruitBiColor24BackpackExample.class.getClassLoader().getResourceAsStream("alphanumericexample.xml"); + var ctx = new RoboBuilder().add(settings).build(); - ctx.start(); - RoboReference alphaUnit = ctx.getReference("alphanumeric"); - AtomicInteger textPosition = new AtomicInteger(); + ctx.start(); + RoboReference alphaUnit = ctx.getReference("alphanumeric"); + AtomicInteger textPosition = new AtomicInteger(); - executor.scheduleAtFixedRate(() -> { + executor.scheduleAtFixedRate(() -> { - if (textPosition.getAndIncrement() >= MESSAGE.length - 1) { - textPosition.set(0); - } + if (textPosition.getAndIncrement() >= MESSAGE.length - 1) { + textPosition.set(0); + } - alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_CLEAR); + alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_CLEAR); - byte currentChar = MESSAGE[textPosition.get()]; - adjustBuffer(currentChar); - alphaUnit.sendMessage(new AlphaNumericMessage(BackpackMessageCommand.PAINT, BUFFER.clone(), new boolean[4], 0)); - alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_DISPLAY); - }, 1, 500, TimeUnit.MILLISECONDS); + byte currentChar = MESSAGE[textPosition.get()]; + adjustBuffer(currentChar); + alphaUnit.sendMessage(new AlphaNumericMessage(BackpackMessageCommand.PAINT, BUFFER.clone(), new boolean[4], 0)); + alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_DISPLAY); + }, 1, 500, TimeUnit.MILLISECONDS); - System.out.println("Press enter to quit\n"); - System.in.read(); - alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_CLEAR); - alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_DISPLAY); - executor.shutdown(); - ctx.shutdown(); + LOGGER.info("Press enter to quit"); + System.in.read(); + alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_CLEAR); + alphaUnit.sendMessage(AlphaNumericMessage.MESSAGE_DISPLAY); + executor.shutdown(); + ctx.shutdown(); - } + } - private static void adjustBuffer(byte currentChar) { + private static void adjustBuffer(byte currentChar) { - BUFFER[3] = BUFFER[2]; - BUFFER[2] = BUFFER[1]; - BUFFER[1] = BUFFER[0]; - BUFFER[0] = currentChar; + BUFFER[3] = BUFFER[2]; + BUFFER[2] = BUFFER[1]; + BUFFER[1] = BUFFER[0]; + BUFFER[0] = currentChar; - } + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColor24BackpackExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColor24BackpackExample.java index bf927e8f..d6dbe428 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColor24BackpackExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColor24BackpackExample.java @@ -17,54 +17,56 @@ package com.robo4j.units.rpi.led; -import java.io.InputStream; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - import com.robo4j.RoboBuilder; import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.hw.rpi.i2c.adafruitbackpack.BiColor; import com.robo4j.hw.rpi.i2c.adafruitbackpack.BiColor24BarDevice; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.InputStream; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; /** * Adafruit Bi-Color 24 Bargraph example - * + *

* demo: Incrementally turning on a led light over 24 available diodes. The each * time with different Color {@link BiColor}. The color is changing circularly. - * + *

* https://learn.adafruit.com/adafruit-led-backpack/bi-color-24-bargraph * - * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class AdafruitBiColor24BackpackExample { + private static final Logger LOGGER = LoggerFactory.getLogger(AdafruitBiColor24BackpackExample.class); - public static void main(String[] args) throws Exception { - ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - InputStream settings = AdafruitBiColor24BackpackExample.class.getClassLoader().getResourceAsStream("bargraph24example.xml"); - RoboContext ctx = new RoboBuilder().add(settings).build(); + public static void main(String[] args) throws Exception { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + InputStream settings = AdafruitBiColor24BackpackExample.class.getClassLoader().getResourceAsStream("bargraph24example.xml"); + RoboContext ctx = new RoboBuilder().add(settings).build(); - ctx.start(); - RoboReference barUnit = ctx.getReference("bargraph"); - DrawMessage clearMessage = new DrawMessage(BackpackMessageCommand.CLEAR); - AtomicInteger position = new AtomicInteger(); - executor.scheduleAtFixedRate(() -> { - if (position.get() > BiColor24BarDevice.MAX_BARS - 1) { - position.set(0); - } - barUnit.sendMessage(clearMessage); - barUnit.sendMessage(new DrawMessage(BackpackMessageCommand.PAINT, new short[] { (short) position.getAndIncrement() }, - new short[] { 0 }, new BiColor[] { BiColor.getByValue(position.get() % 3 + 1) })); - }, 2, 1, TimeUnit.SECONDS); + ctx.start(); + RoboReference barUnit = ctx.getReference("bargraph"); + DrawMessage clearMessage = new DrawMessage(BackpackMessageCommand.CLEAR); + AtomicInteger position = new AtomicInteger(); + executor.scheduleAtFixedRate(() -> { + if (position.get() > BiColor24BarDevice.MAX_BARS - 1) { + position.set(0); + } + barUnit.sendMessage(clearMessage); + barUnit.sendMessage(new DrawMessage(BackpackMessageCommand.PAINT, new short[]{(short) position.getAndIncrement()}, + new short[]{0}, new BiColor[]{BiColor.getByValue(position.get() % 3 + 1)})); + }, 2, 1, TimeUnit.SECONDS); - System.out.println("Press enter to quit\n"); - System.in.read(); - executor.shutdown(); - ctx.shutdown(); + LOGGER.info("Press enter to quit"); + System.in.read(); + executor.shutdown(); + ctx.shutdown(); - } + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColorMatrix8x8BackpackExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColorMatrix8x8BackpackExample.java index c07b29e9..d2d82e62 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColorMatrix8x8BackpackExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/led/AdafruitBiColorMatrix8x8BackpackExample.java @@ -17,54 +17,55 @@ package com.robo4j.units.rpi.led; -import java.io.InputStream; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - import com.robo4j.RoboBuilder; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.hw.rpi.i2c.adafruitbackpack.BiColor; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; /** * Adafruit Bi-Color 8x8 Matrix example - * + *

* demo: Incrementally turning on a led light over the matrix diagonal. The each * time with different Color {@link BiColor}. The color is changing circularly. - * + *

* https://learn.adafruit.com/adafruit-led-backpack/bi-color-8x8-matrix - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class AdafruitBiColorMatrix8x8BackpackExample { - public static void main(String[] args) throws Exception { + private static final Logger LOGGER = LoggerFactory.getLogger(AdafruitBiColorMatrix8x8BackpackExample.class); + + public static void main(String[] args) throws Exception { - ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - InputStream settings = AdafruitBiColorMatrix8x8BackpackExample.class.getClassLoader().getResourceAsStream("matrix8x8example.xml"); - RoboContext ctx = new RoboBuilder().add(settings).build(); + var executor = Executors.newSingleThreadScheduledExecutor(); + var settings = AdafruitBiColorMatrix8x8BackpackExample.class.getClassLoader().getResourceAsStream("matrix8x8example.xml"); + var ctx = new RoboBuilder().add(settings).build(); - ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); - RoboReference matrixUnit = ctx.getReference("matrix"); - AtomicInteger position = new AtomicInteger(); - executor.scheduleAtFixedRate(() -> { - if (position.get() > 7) { - position.set(0); - } - matrixUnit.sendMessage(DrawMessage.MESSAGE_CLEAR); + ctx.start(); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); + RoboReference matrixUnit = ctx.getReference("matrix"); + AtomicInteger position = new AtomicInteger(); + executor.scheduleAtFixedRate(() -> { + if (position.get() > 7) { + position.set(0); + } + matrixUnit.sendMessage(DrawMessage.MESSAGE_CLEAR); - matrixUnit.sendMessage(new DrawMessage(BackpackMessageCommand.PAINT, new short[] { (short) position.get() }, - new short[] { (short) position.getAndIncrement() }, new BiColor[] { BiColor.getByValue(position.get() % 3 + 1) })); - }, 2, 1, TimeUnit.SECONDS); + matrixUnit.sendMessage(new DrawMessage(BackpackMessageCommand.PAINT, new short[]{(short) position.get()}, + new short[]{(short) position.getAndIncrement()}, new BiColor[]{BiColor.getByValue(position.get() % 3 + 1)})); + }, 2, 1, TimeUnit.SECONDS); - System.out.println("Press enter to quit\n"); - System.in.read(); - executor.shutdown(); - ctx.shutdown(); - } + LOGGER.info("Press enter to quit\n"); + System.in.read(); + executor.shutdown(); + ctx.shutdown(); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScanProcessor.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScanProcessor.java index 79220b2c..69ff884e 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScanProcessor.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScanProcessor.java @@ -16,8 +16,6 @@ */ package com.robo4j.units.rpi.lidarlite; -import java.util.concurrent.TimeUnit; - import com.robo4j.ConfigurationException; import com.robo4j.RoboContext; import com.robo4j.RoboReference; @@ -25,26 +23,27 @@ import com.robo4j.configuration.Configuration; import com.robo4j.math.geometry.ScanResult2D; +import java.util.concurrent.TimeUnit; + /** * Example controller for testing the laser scanner. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class LaserScanProcessor extends RoboUnit { - public LaserScanProcessor(RoboContext context, String id) { - super(ScanResult2D.class, context, id); - } + public LaserScanProcessor(RoboContext context, String id) { + super(ScanResult2D.class, context, id); + } - @Override - protected void onInitialization(Configuration configuration) throws ConfigurationException { + @Override + protected void onInitialization(Configuration configuration) throws ConfigurationException { - } + } - @Override - public void onMessage(ScanResult2D result) { - // System.out.println(result.toString()); - RoboReference controller = getContext().getReference("controller"); - getContext().getScheduler().schedule(controller, "scan", 5, 100, TimeUnit.SECONDS, 1); - } + @Override + public void onMessage(ScanResult2D result) { + RoboReference controller = getContext().getReference("controller"); + getContext().getScheduler().schedule(controller, "scan", 5, 100, TimeUnit.SECONDS, 1); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScannerExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScannerExample.java index 794adf5d..30282079 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScannerExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/lidarlite/LaserScannerExample.java @@ -16,67 +16,69 @@ */ package com.robo4j.units.rpi.lidarlite; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Paths; - import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.configuration.Configuration; import com.robo4j.configuration.ConfigurationBuilder; import com.robo4j.units.rpi.pwm.ServoUnitExample; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; /** * Runs the laser scanner, printing the max range and min range found on stdout. * (To see all data, run with JFR and dump a recording.) - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class LaserScannerExample { + private static final Logger LOGGER = LoggerFactory.getLogger(LaserScannerExample.class); - public static void main(String[] args) throws RoboBuilderException, IOException { - float startAngle = -45.0f; - float range = 90.0f; - float step = 1.0f; - InputStream settings; + public static void main(String[] args) throws RoboBuilderException, IOException { + float startAngle = -45.0f; + float range = 90.0f; + float step = 1.0f; + InputStream settings; - switch (args.length) { - case 1: - settings = Files.newInputStream(Paths.get(args[0])); - break; - case 3: - startAngle = Float.parseFloat(args[0]); - range = Float.parseFloat(args[1]); - step = Float.parseFloat(args[2]); - default: - settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("lidarexample.xml"); - } + switch (args.length) { + case 1: + settings = Files.newInputStream(Paths.get(args[0])); + break; + case 3: + startAngle = Float.parseFloat(args[0]); + range = Float.parseFloat(args[1]); + step = Float.parseFloat(args[2]); + default: + settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("lidarexample.xml"); + } - Configuration controllerConfiguration = new ConfigurationBuilder() - .addFloat(LaserScannerTestController.CONFIG_KEY_START_ANGLE, startAngle) - .addFloat(LaserScannerTestController.CONFIG_KEY_RANGE, range).addFloat(LaserScannerTestController.CONFIG_KEY_STEP, step) - .build(); + Configuration controllerConfiguration = new ConfigurationBuilder() + .addFloat(LaserScannerTestController.CONFIG_KEY_START_ANGLE, startAngle) + .addFloat(LaserScannerTestController.CONFIG_KEY_RANGE, range).addFloat(LaserScannerTestController.CONFIG_KEY_STEP, step) + .build(); - System.out.println(String.format("Running scans with startAngle=%2.1f, range=%2.1f and step=%2.1f", startAngle, range, step)); + LOGGER.info("Running scans with startAngle={}, range={} and step={}", startAngle, range, step); - RoboBuilder builder = new RoboBuilder(); - if (settings == null) { - System.out.println("Could not find the settings for the LaserScannerExample!"); - System.exit(2); - } - builder.add(settings).add(LaserScannerTestController.class, controllerConfiguration, "controller").add(LaserScanProcessor.class, - "processor"); - RoboContext ctx = builder.build(); - RoboReference tiltServo = ctx.getReference("laserscanner.tilt"); - tiltServo.sendMessage(Float.valueOf(0)); - RoboReference reference = ctx.getReference("controller"); - ctx.start(); - System.out.println("Starting scanning for ever\nPress to quit"); - reference.sendMessage("scan"); - System.in.read(); - } + var builder = new RoboBuilder(); + if (settings == null) { + LOGGER.warn("Could not find the settings for the LaserScannerExample!"); + System.exit(2); + } + builder.add(settings).add(LaserScannerTestController.class, controllerConfiguration, "controller").add(LaserScanProcessor.class, + "processor"); + var ctx = builder.build(); + RoboReference tiltServo = ctx.getReference("laserscanner.tilt"); + tiltServo.sendMessage(Float.valueOf(0)); + RoboReference reference = ctx.getReference("controller"); + ctx.start(); + LOGGER.info("Starting scanning for ever\nPress to quit"); + reference.sendMessage("scan"); + System.in.read(); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pad/LF710PadExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pad/LF710PadExample.java index 33c03f08..811741cc 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pad/LF710PadExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pad/LF710PadExample.java @@ -18,11 +18,11 @@ import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; -import com.robo4j.RoboContext; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; -import java.io.InputStream; /** * Logitech F710 Pad Example @@ -31,25 +31,25 @@ * @author Miro Wengner (@miragemiko) */ public class LF710PadExample { + private static final Logger LOGGER = LoggerFactory.getLogger(LF710PadExample.class); - public static void main(String[] args) throws RoboBuilderException, IOException { - InputStream settings = Thread.currentThread().getContextClassLoader().getResourceAsStream("logitechF710.xml"); - if (settings == null) { - System.out.println("Could not find the settings for the Gamepad!"); - System.exit(2); - } - RoboBuilder builder = new RoboBuilder(); - builder.add(settings); - RoboContext sytem = builder.build(); + public static void main(String[] args) throws RoboBuilderException, IOException { + var settings = Thread.currentThread().getContextClassLoader().getResourceAsStream("logitechF710.xml"); + if (settings == null) { + LOGGER.warn("Could not find the settings for the Gamepad!"); + System.exit(2); + } + var builder = new RoboBuilder(); + builder.add(settings); + var system = builder.build(); - System.out.println("... Gamepad buttons Example ..."); - sytem.start(); + LOGGER.info("... Gamepad buttons Example ..."); + system.start(); + LOGGER.info(SystemUtil.printStateReport(system)); - System.out.println(SystemUtil.printStateReport(sytem)); - - System.out.println("Press to quit!"); - System.in.read(); - sytem.shutdown(); - System.out.println("Bye!"); - } + LOGGER.info("Press to quit!"); + System.in.read(); + system.shutdown(); + LOGGER.info("Bye!"); + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/CalibrationUtility.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/CalibrationUtility.java index 61daf5d6..36cf43e6 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/CalibrationUtility.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/CalibrationUtility.java @@ -16,72 +16,73 @@ */ package com.robo4j.units.rpi.pwm; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.Scanner; - import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.Scanner; /** * Small calibration utility to help fine tune a servo. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class CalibrationUtility { - public static void main(String[] args) throws RoboBuilderException, FileNotFoundException { - InputStream settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("calibration.xml"); - if (args.length != 1) { - System.out.println("No file specified, using default calibration.xml"); - } else { - settings = new FileInputStream(args[0]); - } + private static final Logger LOGGER = LoggerFactory.getLogger(CalibrationUtility.class); + + public static void main(String[] args) throws RoboBuilderException, FileNotFoundException { + var settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("calibration.xml"); + if (args.length != 1) { + LOGGER.warn("No file specified, using default calibration.xml"); + } else { + settings = new FileInputStream(args[0]); + } - RoboBuilder builder = new RoboBuilder(); - if (settings == null) { - System.out.println("Could not find the settings for servo calibration test!"); - System.exit(2); - } - builder.add(settings); - RoboContext ctx = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(ctx)); - ctx.start(); + var builder = new RoboBuilder(); + if (settings == null) { + LOGGER.warn("Could not find the settings for servo calibration test!"); + System.exit(2); + } + builder.add(settings); + RoboContext ctx = builder.build(); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - String lastCommand; - Scanner scanner = new Scanner(System.in); - System.out.println( - "Type the servo to control and how much to move the servo, between -1 and 1. For example:\npan -1.0\nType q and enter to quit!\n"); - while (!"q".equals(lastCommand = scanner.nextLine())) { - lastCommand = lastCommand.trim(); - String[] split = lastCommand.split(" "); - if (split.length != 2) { - System.out.println("Could not parse " + lastCommand + ". Please try again!"); - continue; - } - RoboReference servoRef = ctx.getReference(split[0]); - if (servoRef == null) { - System.out.println("Could not find any robo unit named " + split[0] + ". Please try again!"); - continue; - } - try { - float value = Float.parseFloat(split[1]); - servoRef.sendMessage(value); - } catch (Exception e) { - System.out.println( - "Could not parse " + split[1] + " as a float number. Error message was: " + e.getMessage() + ". Please try again!"); - continue; - } - } - ctx.shutdown(); - scanner.close(); - } + String lastCommand; + Scanner scanner = new Scanner(System.in); + LOGGER.info( + "Type the servo to control and how much to move the servo, between -1 and 1. For example:\npan -1.0\nType q and enter to quit!\n"); + while (!"q".equals(lastCommand = scanner.nextLine())) { + lastCommand = lastCommand.trim(); + String[] split = lastCommand.split(" "); + if (split.length != 2) { + LOGGER.info("Could not parse {}. Please try again!", lastCommand); + continue; + } + RoboReference servoRef = ctx.getReference(split[0]); + if (servoRef == null) { + LOGGER.info("Could not find any robo unit named {}. Please try again!", split[0]); + continue; + } + try { + float value = Float.parseFloat(split[1]); + servoRef.sendMessage(value); + } catch (Exception e) { + LOGGER.error("Could not parse {} as a float number. Error message was: {}. Please try again!", split[1], e.getMessage()); + } + } + ctx.shutdown(); + scanner.close(); + } } \ No newline at end of file diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/ServoUnitExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/ServoUnitExample.java index 7b00b75a..bf01d2b4 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/ServoUnitExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/pwm/ServoUnitExample.java @@ -16,79 +16,82 @@ */ package com.robo4j.units.rpi.pwm; -import java.io.IOException; -import java.io.InputStream; - import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; -import com.robo4j.RoboContext; import com.robo4j.RoboReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; /** * Small example panning and tilting two servos in a pan/tilt setup. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class ServoUnitExample { - private static final int PAN_STEPS = 30; - private static final int TILT_STEPS = 10; + private static final Logger LOGGER = LoggerFactory.getLogger(ServoUnitExample.class); + private static final int PAN_STEPS = 30; + private static final int TILT_STEPS = 10; + + private static volatile boolean stop = false; - private static volatile boolean stop = false; + public static void main(String[] args) throws RoboBuilderException { + var builder = new RoboBuilder(); + var settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("servoexample.xml"); + if (settings == null) { + LOGGER.warn("Could not find the settings for the ServoUnitExample!"); + System.exit(2); + } + builder.add(settings); + var ctx = builder.build(); - public static void main(String[] args) throws RoboBuilderException { - RoboBuilder builder = new RoboBuilder(); - InputStream settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("servoexample.xml"); - if (settings == null) { - System.out.println("Could not find the settings for the ServoUnitExample!"); - System.exit(2); - } - builder.add(settings); - RoboContext ctx = builder.build(); + RoboReference panRef = ctx.getReference("pan"); + RoboReference tiltRef = ctx.getReference("tilt"); - RoboReference panRef = ctx.getReference("pan"); - RoboReference tiltRef = ctx.getReference("tilt"); + Thread thread = getThread(tiltRef, panRef); + thread.start(); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - float panDirection = 1.0f; - while (!stop) { - for (int tiltStep = 0; tiltStep < TILT_STEPS; tiltStep++) { - // Just move the tilt a quarter of max positive. - float tilt = tiltStep / (TILT_STEPS * 4.0f); - tiltRef.sendMessage(tilt); - for (int panStep = 0; panStep < PAN_STEPS; panStep++) { - if (stop) { - break; - } - float pan = (panStep * 2.0f / PAN_STEPS - 1.0f) * panDirection; - panRef.sendMessage(pan); - sleep(50); - } - panDirection *= -1; - } - } - } - }); - thread.setDaemon(true); - thread.start(); + LOGGER.info("Press to quit!"); + try { + System.in.read(); + } catch (IOException e) { + LOGGER.error("error:{}", e.getMessage(), e); + } + stop = true; + ctx.shutdown(); + } - System.out.println("Press to quit!"); - try { - System.in.read(); - } catch (IOException e) { - e.printStackTrace(); - } - stop = true; - ctx.shutdown(); - } + private static Thread getThread(RoboReference tiltRef, RoboReference panRef) { + Thread thread = new Thread(() -> { + float panDirection = 1.0f; + while (!stop) { + for (int tiltStep = 0; tiltStep < TILT_STEPS; tiltStep++) { + // Just move the tilt a quarter of max positive. + float tilt = tiltStep / (TILT_STEPS * 4.0f); + tiltRef.sendMessage(tilt); + for (int panStep = 0; panStep < PAN_STEPS; panStep++) { + if (stop) { + break; + } + float pan = (panStep * 2.0f / PAN_STEPS - 1.0f) * panDirection; + panRef.sendMessage(pan); + sleep(50); + } + panDirection *= -1; + } + } + }); + thread.setDaemon(true); + return thread; + } - private static void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + private static void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + LOGGER.error("error:{}", e.getMessage(), e); + } + } } diff --git a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/roboclaw/RoboClawUnitExample.java b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/roboclaw/RoboClawUnitExample.java index 1fda836c..eff5d100 100644 --- a/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/roboclaw/RoboClawUnitExample.java +++ b/robo4j-units-rpi/src/examples/java/com/robo4j/units/rpi/roboclaw/RoboClawUnitExample.java @@ -16,76 +16,76 @@ */ package com.robo4j.units.rpi.roboclaw; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.Scanner; - import com.robo4j.RoboBuilder; import com.robo4j.RoboBuilderException; import com.robo4j.RoboContext; import com.robo4j.RoboReference; import com.robo4j.units.rpi.pwm.ServoUnitExample; import com.robo4j.util.SystemUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.Scanner; /** * Small example for driving around a roboclaw controlled robot. - * + * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class RoboClawUnitExample { + private static final Logger LOGGER = LoggerFactory.getLogger(RoboClawUnitExample.class); - public static void main(String[] args) throws RoboBuilderException, FileNotFoundException { - InputStream settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("roboclawexample.xml"); - if (args.length != 1) { - System.out.println("No file specified, using default roboclawexample.xml"); - } else { - settings = new FileInputStream(args[0]); - } + public static void main(String[] args) throws RoboBuilderException, FileNotFoundException { + var settings = ServoUnitExample.class.getClassLoader().getResourceAsStream("roboclawexample.xml"); + if (args.length != 1) { + LOGGER.warn("No file specified, using default roboclawexample.xml"); + } else { + settings = new FileInputStream(args[0]); + } - RoboBuilder builder = new RoboBuilder(); - if (settings == null) { - System.out.println("Could not find the settings for test!"); - System.exit(2); - } - builder.add(settings); - RoboContext ctx = builder.build(); - System.out.println("State before start:"); - System.out.println(SystemUtil.printStateReport(ctx)); - ctx.start(); + var builder = new RoboBuilder(); + if (settings == null) { + LOGGER.warn("Could not find the settings for test!"); + System.exit(2); + } + builder.add(settings); + RoboContext ctx = builder.build(); + LOGGER.info("State before start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); + ctx.start(); - System.out.println("State after start:"); - System.out.println(SystemUtil.printStateReport(ctx)); + LOGGER.info("State after start:"); + LOGGER.info(SystemUtil.printStateReport(ctx)); - String lastCommand = ""; - Scanner scanner = new Scanner(System.in); - System.out.println( - "Type the roboclaw unit to control and the speed [-1, 1] and angular direction[-180, 180]. For example:\ntank 1 0\nType q and enter to quit!\n"); - while (!"q".equals(lastCommand = scanner.nextLine())) { - lastCommand = lastCommand.trim(); - String[] split = lastCommand.split(" "); - if (split.length != 3) { - System.out.println("Could not parse " + lastCommand + ". Please try again!"); - continue; - } - RoboReference servoRef = ctx.getReference(split[0]); - if (servoRef == null) { - System.out.println("Could not find any robo unit named " + split[0] + ". Please try again!"); - continue; - } - try { - float speed = Float.parseFloat(split[1]); - float direction = (float) Math.toRadians(Float.parseFloat(split[2])); - servoRef.sendMessage(new MotionEvent(speed, direction)); - } catch (Exception e) { - System.out.println( - "Could not parse " + split[1] + " as a float number. Error message was: " + e.getMessage() + ". Please try again!"); - continue; - } - } - ctx.shutdown(); - scanner.close(); - } + String lastCommand = ""; + Scanner scanner = new Scanner(System.in); + LOGGER.info( + "Type the roboclaw unit to control and the speed [-1, 1] and angular direction[-180, 180]. For example:\ntank 1 0\nType q and enter to quit!\n"); + while (!"q".equals(lastCommand = scanner.nextLine())) { + lastCommand = lastCommand.trim(); + String[] split = lastCommand.split(" "); + if (split.length != 3) { + System.out.println("Could not parse " + lastCommand + ". Please try again!"); + continue; + } + RoboReference servoRef = ctx.getReference(split[0]); + if (servoRef == null) { + System.out.println("Could not find any robo unit named " + split[0] + ". Please try again!"); + continue; + } + try { + float speed = Float.parseFloat(split[1]); + float direction = (float) Math.toRadians(Float.parseFloat(split[2])); + servoRef.sendMessage(new MotionEvent(speed, direction)); + } catch (Exception e) { + LOGGER.error("Could not parse {} as a float number. Error message was: {}. Please try again!", split[1], e.getMessage()); + } + } + ctx.shutdown(); + scanner.close(); + } } diff --git a/robo4j-units-rpi/src/main/java/com/robo4j/units/rpi/camera/RaspividUnit.java b/robo4j-units-rpi/src/main/java/com/robo4j/units/rpi/camera/RaspividUnit.java index 3d52e178..6d9236c6 100644 --- a/robo4j-units-rpi/src/main/java/com/robo4j/units/rpi/camera/RaspividUnit.java +++ b/robo4j-units-rpi/src/main/java/com/robo4j/units/rpi/camera/RaspividUnit.java @@ -21,22 +21,23 @@ import com.robo4j.RoboUnit; import com.robo4j.configuration.Configuration; import com.robo4j.hw.rpi.camera.RaspiDevice; -import com.robo4j.logging.SimpleLoggingUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Unit generates the video stream on desired socket - * + *

* https://www.raspberrypi.org/app/uploads/2013/07/RaspiCam-Documentation.pdf * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public class RaspividUnit extends RoboUnit { - public static final String NAME = "raspividUnit"; public static final String PROPERTY_SERVER_IP = "serverIp"; public static final String PROPERTY_SERVER_PORT = "serverPort"; + private static final Logger LOGGER = LoggerFactory.getLogger(RaspividUnit.class); private final RaspiDevice device = new RaspiDevice(); private String output; private String processId; @@ -62,27 +63,26 @@ protected void onInitialization(Configuration configuration) throws Configuratio @Override public void onMessage(RaspividRequest message) { - switch (message.getType()){ + switch (message.getType()) { case CONFIG: message.put(RpiCameraProperty.OUTPUT, output); processId = String.valueOf(device.executeCommandReturnPID(message.create())); break; case START: - SimpleLoggingUtil.info(getClass(), "not necessary start message: " + message); + LOGGER.info("not necessary start message: {}", message); break; case STOP: stop(); break; default: - SimpleLoggingUtil.error(getClass(), "message: " + message); + LOGGER.error("message: {}", message); } - } @Override public void stop() { super.stop(); device.executeCommand("kill " + processId); - System.out.println("stop raspivid : " + processId); + LOGGER.info("stop raspivid : {}", processId); } } diff --git a/robo4j-units-rpi/src/main/java/module-info.java b/robo4j-units-rpi/src/main/java/module-info.java index d52c835b..98708c5c 100644 --- a/robo4j-units-rpi/src/main/java/module-info.java +++ b/robo4j-units-rpi/src/main/java/module-info.java @@ -2,6 +2,7 @@ requires jdk.jfr; requires transitive robo4j.core; requires transitive robo4j.hw.rpi; + requires org.slf4j; exports com.robo4j.units.rpi.accelerometer; exports com.robo4j.units.rpi.camera;