diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/ErrorReporter.java b/src/org/rocketproplab/marginalstability/flightcomputer/ErrorReporter.java index 74be501..fbe000c 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/ErrorReporter.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/ErrorReporter.java @@ -1,9 +1,9 @@ package org.rocketproplab.marginalstability.flightcomputer; -import java.io.PrintStream; - import org.rocketproplab.marginalstability.flightcomputer.subsystems.Telemetry; +import java.io.PrintStream; + /** * A class to report errors which are encountered during the operation of the * flight computer. Errors get logged to a printstream and to the Telemetry @@ -13,9 +13,8 @@ * along with a copy of that print stream writing to stderr. That was * interactive applications can report errors instantly while all errors will be * recorded. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class ErrorReporter { @@ -23,7 +22,7 @@ public class ErrorReporter { /** * Instantiate the singleton if not already and return it. - * + * * @return A singleton of type ErrorReporter */ public static ErrorReporter getInstance() { @@ -36,7 +35,7 @@ public static ErrorReporter getInstance() { /** * Sets the singleton in case you want to output to a particular stream. This * should be called before any calls to {@link #getInstance()}. - * + * * @param reporter the new singleton */ public static void setInstance(ErrorReporter reporter) { @@ -57,7 +56,7 @@ public ErrorReporter() { /** * Error reporter that should print to the given print stream and send telemetry * to the given telemetry. - * + * * @param stream the stream to print to * @param telemetry the telemetry object to use to send telemetry. */ @@ -112,7 +111,7 @@ public void reportError(Exception exception, String extraInfo) { * Reports a given error, exception and extra info. The String gets sent to the * printstream along with the exception if present. The Errors enum gets * reported to telemetry. All parameters may be null. - * + * * @param error What error should be reported to the telemetry, may be null. * @param exception What exception caused the error, may be null. * @param extraInfo Additional useful text related to the error, may be null. @@ -122,7 +121,7 @@ public void reportError(Errors error, Exception exception, String extraInfo) { stream.print(extraInfo); stream.print("\n"); } - + if (error != null) { stream.print(error); stream.print("\n"); @@ -130,7 +129,7 @@ public void reportError(Errors error, Exception exception, String extraInfo) { telemetry.reportError(error); } } - + if (exception != null) { exception.printStackTrace(stream); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/Errors.java b/src/org/rocketproplab/marginalstability/flightcomputer/Errors.java index 9bc822b..0484a50 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/Errors.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/Errors.java @@ -3,25 +3,26 @@ public enum Errors { UNKNOWN_ERROR("Unexpected error occured!"), - TOP_LEVEL_EXCEPTION("Exception in main loop occured"), + TOP_LEVEL_EXCEPTION("Exception in main loop occured"), IMU_IO_ERROR("Unable to read IMU over SPI"), MAX14830_IO_ERROR("Unable to access /dev/spix.x via Pi4J"), LPS22HD_INITIALIZATION_ERROR("Unable to write from i2cDevice IO Exception"), LPS22HD_PRESSURE_IO_ERROR("Unable to read Pressure from i2cDevice IO Exception"); - + private String errorMessage; - + /** * Sets the error message in the error + * * @param errorMessage */ Errors(String errorMessage) { this.errorMessage = errorMessage; } - + @Override public String toString() { return this.errorMessage; } - + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/FlightComputer.java b/src/org/rocketproplab/marginalstability/flightcomputer/FlightComputer.java index b2da0a9..4d50e84 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/FlightComputer.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/FlightComputer.java @@ -1,27 +1,120 @@ package org.rocketproplab.marginalstability.flightcomputer; +import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRouter; +import org.rocketproplab.marginalstability.flightcomputer.comm.PacketSources; +import org.rocketproplab.marginalstability.flightcomputer.comm.SCMPacket; import org.rocketproplab.marginalstability.flightcomputer.looper.Looper; -import org.rocketproplab.marginalstability.flightcomputer.subsystems.Subsystem; -import org.rocketproplab.marginalstability.flightcomputer.subsystems.Telemetry; +import org.rocketproplab.marginalstability.flightcomputer.subsystems.*; + +import java.util.logging.Logger; public class FlightComputer { - private Telemetry telemetry; - private Time time; - private Looper looper; + private static FlightComputer instance; + /** + * Creates a FlightComputer instance, which can only be created once. + * + * @param args arguments to configure FightComputer settings + * @return new FlightComputer instance + */ + public static FlightComputer create(String[] args) { + if (instance != null) { + throw new RuntimeException("FlightComputer has already been created."); + } + instance = new FlightComputer(args); + return instance; + } - public FlightComputer(Telemetry telemetry, Time time) { - this.telemetry = telemetry; - this.time = time; - this.looper = new Looper(time); + /** + * Convenient method to create a FlightComputer instance without any arguments. + * + * @return new FlightComputer instance + */ + public static FlightComputer create() { + return create(new String[0]); } + /** + * Time used by all objects created in the FC. + */ + private final Time time; + + /** + * Looper used by objects created in the FC, e.g. subsystems. + */ + private final Looper looper; + + private PacketRouter packetRouter = new PacketRouter(); + private Telemetry telemetry = new Telemetry(Logger.getLogger("Telemetry"), packetRouter); + + /** + * Providers to provide singleton objects to higher level management objects. + */ + private SensorProvider sensorProvider; + + /** + * Private FlightComputer constructor to avoid multiple initializations. + * + * @param args arguments to configure FlightComputer settings + */ + private FlightComputer(String[] args) { + this.time = new Time(); + this.looper = new Looper(this.time); + initWithArgs(args); + } + + /** + * Initialize input/output devices and other settings based on arguments. + * + * @param args arguments for configuration + */ + private void initWithArgs(String[] args) { + ParseCmdLine cmd = new ParseCmdLine(args); + + // use real/fake sensors + sensorProvider = SensorProvider.create(cmd.useRealSensors); + } + + /** + * Allows subsystems to register events and callbacks with the looper. + * + * @param subsystem subsystem to register + */ public void registerSubsystem(Subsystem subsystem) { subsystem.prepare(this.looper); } - public Time getTime() { - return time; + /** + * After all input/output devices and settings are initialized, higher level objects can be created. + * Use objects provided by the providers, and simply inject all objects needed to create any higher level object. + */ + public void initHighLevelObjects() { + + // PacketRouter + PacketRouter packetRouter = new PacketRouter(); + + // Telemetry + Telemetry telemetry = new Telemetry(Logger.getLogger("Telemetry"), packetRouter); + + telemetry.logInfo(Info.INIT_SUBSYSTEMS_START); + + // ParachuteSubsystem + registerSubsystem(new ParachuteSubsystem(null, null, null, null)); + + // SensorSubsystem + SensorSubsystem sensorSubsystem = new SensorSubsystem(this.time); + // add sensors + telemetry.logInfo(Info.DONE_CREATING_SENSORS); + registerSubsystem(sensorSubsystem); + + // SCMCommandSubsystem + registerSubsystem(new SCMCommandSubsystem()); // TODO: should listen to PacketRouter + + // ValveStateSubsystem + packetRouter.addListener(new ValveStateSubsystem(packetRouter), SCMPacket.class, + PacketSources.EngineControllerUnit); + + telemetry.logInfo(Info.FINISH_SUBSYSTEM_START); } public void tick() { @@ -34,4 +127,113 @@ public void tick() { } }); } + + /** + * Builder class to create FlightComputer objects with more customization. + */ + public static class Builder { + private Telemetry telemetry; + private final FlightComputer fc; + + /** + * Creates a new Builder instance, which can be used to customize the FC. + * + * @param args arguments to configure FlightComputer settings. + */ + public Builder(String[] args) { + fc = FlightComputer.create(args); + } + + /** + * Convenient method to create a Builder instance without any arguments. + */ + public Builder() { + this(new String[0]); + } + + /** + * Set custom telemetry. + * + * @param telemetry customized telemetry + * @return this Builder + */ + public Builder withTelemetry(Telemetry telemetry) { + this.telemetry = telemetry; + return this; + } + + /** + * Customizations set programmatically in the Builder will override defaults and arguments. + * + * @return customized FlightComputer + */ + public FlightComputer build() { + if (telemetry != null) fc.telemetry = this.telemetry; + return fc; + } + } + + /** + * Defines command line options and possible arguments. + * Also prints help and exits if invalid arguments are detected. + */ + private static class ParseCmdLine { + /** + * CLI argument names and descriptions + */ + private static final String + HELP = "--help", + HELP_DESC = "print help menu", + REAL_SENSORS = "--real-sensors", + REAL_SENSORS_DESC = "use real sensors"; + + /** + * Real sensor flag + */ + private boolean useRealSensors = false; + + /** + * Constructs a new object to parse CLI arguments + * + * @param args arguments to parse + */ + private ParseCmdLine(String[] args) { + parse(args); + } + + /** + * Checks arguments against each setting + * + * @param args + */ + private void parse(String[] args) { + // help + if (args.length == 1 && args[0].equals("--help")) { + printHelp(); + System.exit(0); + } + + // settings + int i = 0; + while (i < args.length) { + String arg = args[i]; + if (arg.equals(REAL_SENSORS)) { + useRealSensors = true; + System.out.println(REAL_SENSORS_DESC); + } else { + System.out.println("Invalid argument: " + arg); + printHelp(); + System.exit(1); + } + i++; + } + } + + private void printHelp() { + System.out.println("Usage:\n" + + HELP + ": " + HELP_DESC + "\n" + + REAL_SENSORS + ": " + REAL_SENSORS_DESC + ); + } + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/Info.java b/src/org/rocketproplab/marginalstability/flightcomputer/Info.java index 7edd808..3fda0e1 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/Info.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/Info.java @@ -4,13 +4,13 @@ public enum Info { INIT_SUBSYSTEMS_START("Starting Subsystems."), FINISH_SUBSYSTEM_START("Subsystems started."), DONE_CREATING_SENSORS("Finished creating sensors."); - + private String description; - - Info(String description){ + + Info(String description) { this.description = description; } - + public String getDescription() { return this.description; } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/Main.java b/src/org/rocketproplab/marginalstability/flightcomputer/Main.java index ef8dbb8..889e5a9 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/Main.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/Main.java @@ -1,10 +1,5 @@ package org.rocketproplab.marginalstability.flightcomputer; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRouter; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketSources; -import org.rocketproplab.marginalstability.flightcomputer.comm.SCMPacket; -import org.rocketproplab.marginalstability.flightcomputer.subsystems.*; - /** * The main file contains the entry point to the software stack. It is * responsible for instantiating the @@ -14,7 +9,7 @@ * Subsystems}, and registering subsystems with the * {@link org.rocketproplab.marginalstability.flightcomputer.comm.PacketRouter * Packet Router}. - * + *

* The application is split up into three main sections. *

*/ public class Main { - public static void main(String[] args) { - Time time = new Time(); - FlightComputer flightComputer = new FlightComputer(Telemetry.getInstance(), time); - Main.registerSubsystems(flightComputer); - Main.registerPacketListeners(); + FlightComputer flightComputer = FlightComputer.create(args); + flightComputer.initHighLevelObjects(); // while(true) { // flightComputer.tick(); // } } - - private static void registerSubsystems(FlightComputer flightComputer) { - Telemetry telemetry = Telemetry.getInstance(); - - telemetry.logInfo(Info.INIT_SUBSYSTEMS_START); - - flightComputer.registerSubsystem(ParachuteSubsystem.getInstance()); - ValveStateSubsystem.getInstance(); - - SensorSubsystem sensorSubsystem = new SensorSubsystem(flightComputer.getTime()); - Main.addSensors(sensorSubsystem); - flightComputer.registerSubsystem(sensorSubsystem); - - SCMCommandSubsystem scmCommandSubsystem = SCMCommandSubsystem.getInstance(); - flightComputer.registerSubsystem(scmCommandSubsystem); // TODO: should listen to PacketRouter - - telemetry.logInfo(Info.FINISH_SUBSYSTEM_START); - } - - private static void addSensors(SensorSubsystem sensorSubsystem) { - Telemetry telemetry = Telemetry.getInstance(); - - telemetry.logInfo(Info.DONE_CREATING_SENSORS); - } - - private static void registerPacketListeners() { - PacketRouter packetRouter = PacketRouter.getInstance(); - - packetRouter.addListener(ValveStateSubsystem.getInstance(), SCMPacket.class, - PacketSources.EngineControllerUnit); - } - } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/SensorProvider.java b/src/org/rocketproplab/marginalstability/flightcomputer/SensorProvider.java new file mode 100644 index 0000000..3f5aff1 --- /dev/null +++ b/src/org/rocketproplab/marginalstability/flightcomputer/SensorProvider.java @@ -0,0 +1,55 @@ +package org.rocketproplab.marginalstability.flightcomputer; + +import org.rocketproplab.marginalstability.flightcomputer.hal.LPS22HD; + +/** + * A provider to provide singleton sensor instances. + * + * @author Chi Chow + */ +public abstract class SensorProvider { + + abstract LPS22HD getPressureSensor(); + + private static SensorProvider instance; + + /** + * Create singleton SensorProvider. + * + * @param useRealSensors whether to use real sensors or simulators + * @return new SensorProvider instance + */ + public static SensorProvider create(boolean useRealSensors) { + if (instance != null) { + throw new RuntimeException("SensorProvider has already been created."); + } + if (useRealSensors) { + instance = new RealSensorProvider(); + } else { + instance = new SimulatorProvider(); + } + return instance; + } + + /** + * SensorProvider that returns simulators + */ + private static class SimulatorProvider extends SensorProvider { + @Override + public LPS22HD getPressureSensor() { + // TODO: implement methods to get different simulators + throw new RuntimeException("Not implemented!"); + } + } + + /** + * SensorProvider that returns real sensors + */ + private static class RealSensorProvider extends SensorProvider { + @Override + public LPS22HD getPressureSensor() { + // TODO: implement methods to get different real sensors + throw new RuntimeException("Not implemented!"); + } + } +} diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/SettingSectionHeader.java b/src/org/rocketproplab/marginalstability/flightcomputer/SettingSectionHeader.java index e6cd8b4..de5e749 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/SettingSectionHeader.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/SettingSectionHeader.java @@ -1,11 +1,11 @@ package org.rocketproplab.marginalstability.flightcomputer; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target(FIELD) public @interface SettingSectionHeader { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/Settings.java b/src/org/rocketproplab/marginalstability/flightcomputer/Settings.java index c4f862c..204414b 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/Settings.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/Settings.java @@ -31,11 +31,11 @@ public class Settings { */ @UserSetting(comment = "Time threshold needed to exceed to deploy the main chute", units = "s") public static double MAIN_CHUTE_PRESSURE_TIME_THRESHOLD = 10; // TODO: set time exceeding the threshold needed to - // deploy main chute + // deploy main chute - public static boolean[] ENGINE_ON_VALVE_STATES = { true, true, true, true, true }; + public static boolean[] ENGINE_ON_VALVE_STATES = {true, true, true, true, true}; - public static boolean[] ENGINE_ABORT_VALVE_STATES = { true, true, true, true, true }; + public static boolean[] ENGINE_ABORT_VALVE_STATES = {true, true, true, true, true}; // Unit conversions @@ -57,16 +57,16 @@ public class Settings { @SettingSectionHeader(name = "PT Quadratic Regression") @UserSetting(comment = "'a' constant for quadratic regression for pressure transducers", units = "hPa / V^2") - public static double[] A_PT_CONSTANTS = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0 }; + public static double[] A_PT_CONSTANTS = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0}; @UserSetting(comment = "'b' constant for quadratic regression for pressure transducers", units = "hPa / V") - public static double[] B_PT_CONSTANTS = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0 }; + public static double[] B_PT_CONSTANTS = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0}; @UserSetting(comment = "'c' constant for quadratic regression for pressure transducers", units = "hPa") - public static double[] C_PT_CONSTANTS = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, - 0.0 }; + public static double[] C_PT_CONSTANTS = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, + 0.0}; @UserSetting(comment = "Phone number to text position to", units = "1xxxyyyyyyy") public static String PHONE_NUMBER = "13150001111"; @@ -198,7 +198,7 @@ protected static Map getFieldNameValueMap(List config) { } protected static void setFieldDoubleArray(Field field, String line) - throws IllegalArgumentException, IllegalAccessException { + throws IllegalArgumentException, IllegalAccessException { line = line.trim().replace("[", "").replace("]", ""); String[] newValues = line.split(","); double[] fieldValues = (double[]) field.get(null); @@ -212,7 +212,7 @@ protected static void setFieldDoubleArray(Field field, String line) } protected static void setFieldDouble(Field field, String line) - throws IllegalArgumentException, IllegalAccessException { + throws IllegalArgumentException, IllegalAccessException { line = line.trim(); double value = Double.parseDouble(line); field.set(null, value); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/Time.java b/src/org/rocketproplab/marginalstability/flightcomputer/Time.java index bb76dd1..de79841 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/Time.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/Time.java @@ -3,16 +3,15 @@ /** * A class to get the current rocket time. At the moment its implementation * passed through to System.currentTimeMillis but this might change. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class Time { /** * Get the rocket time, this might change at some point in the future. This * value should be used for all interpolations. - * + * * @return the current rocket time */ public double getSystemTime() { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/UserSetting.java b/src/org/rocketproplab/marginalstability/flightcomputer/UserSetting.java index 0a64c3c..64e6cb4 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/UserSetting.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/UserSetting.java @@ -1,12 +1,12 @@ package org.rocketproplab.marginalstability.flightcomputer; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target(FIELD) @Documented @@ -18,18 +18,21 @@ public @interface UserSetting { /** * The name to use for the settings config file. If "" then the field name should be used. + * * @return the name to use for the settings file, "" if field name should be used */ String name() default ""; - + /** * The comment to display in the settings config file. "" will not be written to the file. + * * @return the comment for the settings file */ String comment(); - + /** * The units to display in the settings file. "" will not be written to the file. + * * @return the units for the settings file */ String units(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/FramedSCM.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/FramedSCM.java index 57d6694..564253c 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/FramedSCM.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/FramedSCM.java @@ -1,10 +1,10 @@ package org.rocketproplab.marginalstability.flightcomputer.comm; +import org.rocketproplab.marginalstability.flightcomputer.events.PacketListener; + import java.util.LinkedList; import java.util.Queue; -import org.rocketproplab.marginalstability.flightcomputer.events.PacketListener; - /** * A message to handle the framing of extra long SCM packets. The format for an * extra long SCM packet is as follows.
@@ -26,11 +26,11 @@ * @author Max Apodaca */ public class FramedSCM implements PacketListener { - private Queue outputQueue; - private String activeString; - private int frameLength; - private PacketRelay sCMOutput; - private FramedPacketProcessor framedPacketOutput; + private Queue outputQueue; + private String activeString; + private int frameLength; + private PacketRelay sCMOutput; + private FramedPacketProcessor framedPacketOutput; /** * Create a new SCM de-framer. SCMOutput is used to send replied to incoming SCM @@ -105,7 +105,7 @@ private SCMPacket processX0Packet(SCMPacket incomingPacket) { activeString += SCMmessagesplit[0]; frameLength = Integer.parseInt(activeString); activeString = SCMmessagesplit[1]; - // TODO Similar to XS, where if the frameLength is still less than 0 or + // TODO Similar to XS, where if the frameLength is still less than 0 or // does not split into several indices } else if (lengthofframeleft < incomingPacket.getData().length()) { activeString += incomingPacket.getData().substring(0, lengthofframeleft); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSPacket.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSPacket.java index 3e82323..08ad3be 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSPacket.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSPacket.java @@ -26,7 +26,7 @@ public class GPSPacket { /** * Create a new GPS Packet based on the NEMA String - * + * * @param nEMA the nema to make the packet of */ public GPSPacket(String nEMA) { @@ -36,7 +36,7 @@ public GPSPacket(String nEMA) { /** * Internally parses the NEMA for the packet - * + * * @param nEMA the nema to assign this packet to */ private void parseNEMA(String nEMA) { @@ -102,7 +102,7 @@ public double getTime() { /** * Used as debug information for how many satellite vehicles (SVs) are connected * to the GPS. - * + * * @return the number of satellite vehicles connected to the GPS */ public int getSVCount() { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSTransceiver.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSTransceiver.java index 4b5e157..b78a571 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSTransceiver.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/GPSTransceiver.java @@ -1,23 +1,21 @@ package org.rocketproplab.marginalstability.flightcomputer.comm; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; -import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.events.SerialListener; /** * A class to handle the sending and receiving information from the GPS. It will * Listener to a serial port and every time a valid full NMEA packet is received * it will parse the packet and send it to the packet router. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class GPSTransceiver implements SerialListener { private PacketRouter router; /** * Create a new GPS Transceiver that - * + * * @param router the router to use to route packets */ public GPSTransceiver(PacketRouter router) { @@ -31,7 +29,7 @@ public void onSerialData(String data) { router.recivePacket(packet, PacketSources.GPS); } else { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Got invalid packet " + data + "!\""; + String errorMsg = "Got invalid packet " + data + "!\""; errorReporter.reportError(errorMsg); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketDirection.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketDirection.java index bf7733e..8761ad7 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketDirection.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketDirection.java @@ -2,18 +2,18 @@ /** * The different ways a packet can be transmitted, either sending or receiving - * @author Max Apodaca * + * @author Max Apodaca */ public enum PacketDirection { - /** - * The packet is being sent to the other component - */ - SEND, - - /** - * The packet is coming to the flight computer - */ - RECIVE + /** + * The packet is being sent to the other component + */ + SEND, + + /** + * The packet is coming to the flight computer + */ + RECIVE } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRelay.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRelay.java index 23823a5..f488cd7 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRelay.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRelay.java @@ -2,17 +2,17 @@ /** * This interface has the ability to send a packet to a given location - * @author Max Apodaca * + * @author Max Apodaca */ public interface PacketRelay { /** * Sends a packet to the associated listeners. - * + * * @param o the packet to send (must be of packet type) * @param source where the packet is coming from */ public void sendPacket(Object o, PacketSources source); - + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRouter.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRouter.java index e12e0ed..cda00fc 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRouter.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketRouter.java @@ -1,12 +1,11 @@ package org.rocketproplab.marginalstability.flightcomputer.comm; -import java.util.ArrayList; -import java.util.HashMap; - import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; -import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.events.PacketListener; +import java.util.ArrayList; +import java.util.HashMap; + /** * Routes packets of any type to their destination.
* The routing works by having a Map between the type and source of the packet @@ -19,19 +18,10 @@ * class of the object) and source. See * {@link #dispatchPacket(Object, PacketSources, PacketDirection)} for more * information. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class PacketRouter implements PacketRelay { - private static PacketRouter instance; - - public static PacketRouter getInstance() { - if (instance == null) { - instance = new PacketRouter(); - } - return instance; - } private HashMap>> listenerMap; @@ -49,7 +39,7 @@ public void sendPacket(Object o, PacketSources source) { /** * Send a packet to all of the receivers - * + * * @param o the packet which is being sent (must be of packet type) * @param source */ @@ -61,12 +51,12 @@ public void recivePacket(Object o, PacketSources source) { * Dispatch a packet with the given direction to all of the appropriate * listeners. The packet listeners are looked up based off of a combination * between the direction and class hash. - * + * * @param o The packet to be transmitted * @param source the sender of the packet * @param direction what direction the packet is being sent in */ - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) private void dispatchPacket(Object o, PacketSources source, PacketDirection direction) { try { LookupTuple lookup = new LookupTuple(o.getClass(), source); @@ -77,7 +67,7 @@ private void dispatchPacket(Object o, PacketSources source, PacketDirection dire } } catch (ClassCastException classExecption) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Packet " + o + " is not of suitable type"; + String errorMsg = "Packet " + o + " is not of suitable type"; errorReporter.reportError(null, classExecption, errorMsg); } @@ -86,7 +76,7 @@ private void dispatchPacket(Object o, PacketSources source, PacketDirection dire /** * Add a listener for a specific type of packet. Note that the listeners are * mapped using the hash of the Class object associated with that packet. - * + * * @param listener the packet listener listening to this packet * @param type the class which will be hashed to make lookup easier * @param source what source to listen from @@ -102,9 +92,8 @@ public void addListener(PacketListener listener, Class type, PacketSources /** * A class to get a nice hash code for the lookup map - * - * @author Max Apodaca * + * @author Max Apodaca */ private class LookupTuple { @@ -112,7 +101,7 @@ private class LookupTuple { /** * Create a new LookupTuple for the type and source - * + * * @param type the type of packet to look for * @param source the origin of the packet */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketSources.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketSources.java index 6b9ad4f..2ceec21 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketSources.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/PacketSources.java @@ -2,29 +2,28 @@ /** * The different places packets can go and come from. - * - * @author Max Apodaca * + * @author Max Apodaca */ public enum PacketSources { - /** - * The packet is coming from or going to the Engine Controller Unit (ECU) - */ - EngineControllerUnit, + /** + * The packet is coming from or going to the Engine Controller Unit (ECU) + */ + EngineControllerUnit, + + /** + * The packet is coming from or going to the command box + */ + CommandBox, - /** - * The packet is coming from or going to the command box - */ - CommandBox, + /** + * The packet is coming from or going to the GPS + */ + GPS, - /** - * The packet is coming from or going to the GPS - */ - GPS, - - /** - * This packet is coming from or going to the Auxiliary GPS - */ - AUX_GPS + /** + * This packet is coming from or going to the Auxiliary GPS + */ + AUX_GPS } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacket.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacket.java index a14299a..d9b02b6 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacket.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacket.java @@ -1,19 +1,18 @@ package org.rocketproplab.marginalstability.flightcomputer.comm; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; -import org.rocketproplab.marginalstability.flightcomputer.Errors; /** * A packet for the SCMProtocol to convert between the object and string * representation.
* The Simple Checksum Messaging (SCM) protocol consists of three sections. The * id, data and checksum organized as a plaintext string.
- * + * *
  * {@code | Id | Data  | Checksum |}
  * {@code   AA , BBBBB ,    FF    ;}
  * 
- * + *

* An example of a heartbeat packet would be {@code HB,12345,81;} where the ID * is HB, data is 12345 and checksum is 81.
* The checksum is calculated by summing the char code of each character up the @@ -21,9 +20,8 @@ * a character sequence from 00 to 99 and then a semicolon is appended. See * {@link #calculateChecksum(String)} for implementation details of the checksum * algorithm. - * - * @author Daniel Walder, Max Apodaca * + * @author Daniel Walder, Max Apodaca */ public class SCMPacket { @@ -38,7 +36,7 @@ public class SCMPacket { /** * Constructor that passes the packet into it's components - * + * * @param packet the packet to be processed */ public SCMPacket(String packet) { @@ -47,7 +45,7 @@ public SCMPacket(String packet) { /** * Create a new packet based off of the ID and data - * + * * @param id the id of the packet * @param data the data which the packet holds */ @@ -60,7 +58,7 @@ public SCMPacket(SCMPacketType id, String data) { /** * Takes the packet assigns its id and data to the instance variables Also calls * verifyChecksum to confirm packet accuracy - * + * * @param packet the received packet to work with */ private void parsepacket(String packet) { @@ -123,7 +121,7 @@ private void validate() { /** * Helper method for verifyChecksum for calculating the strChecksum - * + * * @param packet the packet in question * @return the checksum of the packet */ @@ -143,7 +141,7 @@ private static int calculateChecksum(String packet) { /** * Gets the ID of this packet. Only valid if {@link SCMPacket#isValid()} returns * true. - * + * * @return the id of the packet */ public SCMPacketType getID() { @@ -153,7 +151,7 @@ public SCMPacketType getID() { /** * Get the data in this packet. Only valid if {@link SCMPacket#isValid()} * returns true. - * + * * @return the data in this packet */ public String getData() { @@ -162,7 +160,7 @@ public String getData() { /** * Get whether or not this packet is valid. If invalid nothing is guarantee. - * + * * @return if the data in the packet is valid */ public boolean isValid() { @@ -172,7 +170,7 @@ public boolean isValid() { /** * Encodes id and data into a packet string. Will attempt to encode even with an * invalid state. - * + * * @return the packet as String */ @Override diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacketType.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacketType.java index 321043d..d606994 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacketType.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMPacketType.java @@ -5,20 +5,20 @@ public enum SCMPacketType { * Change the state of the valves, each index in data is a 1 or 0 that * Specifies valve 0-4. */ - V0("Valve State"), - + V0("Valve State"), + /** * Change the state of the valves, each index in data is a 1 or 0 that * Specifies valve 5-7. */ V1("Valve State"), - - V2("Valve State"), - - V3("Valve State"), - + + V2("Valve State"), + + V3("Valve State"), + HB("HB"), // TODO fill this packet in - + /** * Position of the GPS x coordinate. Bits are hex integer value (m) @@ -99,12 +99,12 @@ public enum SCMPacketType { * Reading of pressure transducer 4. Bits are integer value (PSI) */ P4("Pressure Transducer 4"), - + /** * Reading of pressure transducer 5. Bits are integer value (PSI) */ P5("Pressure Transducer 5"), - + /** * Reading of pressure transducer 6. Bits are integer value (PSI) */ @@ -114,47 +114,47 @@ public enum SCMPacketType { * Reading of pressure transducer 7. Bits are integer value (PSI) */ P7("Pressure Transducer 7"), - + /** * Reading of pressure transducer 8. Bits are integer value (PSI) */ P8("Pressure Transducer 8"), - + /** * Reading of pressure transducer 9. Bits are integer value (PSI) */ P9("Pressure Transducer 9"), - + /** * Reading of pressure transducer 10. Bits are integer value (PSI) */ PA("Pressure Transducer 10"), - + /** * Reading of pressure transducer 11. Bits are integer value (PSI) */ PB("Pressure Transducer 11"), - + /** * Reading of pressure transducer 12. Bits are integer value (PSI) */ PC("Pressure Transducer 12"), - + /** * Reading of pressure transducer 13. Bits are integer value (PSI) */ PD("Pressure Transducer 13"), - + /** * Reading of pressure transducer 14. Bits are integer value (PSI) */ PE("Pressure Transducer 14"), - + /** * Reading of pressure transducer 15. Bits are integer value (PSI) */ PF("Pressure Transducer 15"), - + /** * Error. The bits are the error code */ @@ -164,37 +164,37 @@ public enum SCMPacketType { * Warning. The bits are the warning code */ WA("Warning"), VS("VS"), - + /** * Drogue Chute Deploy */ DD("Drogue Chute Deploy"), - + /** * Main Chute Deploy */ MD("Main Chute Deploy"), - + /** * A packet to indicate the start of an extra long transmission, @see {@link FramedSCM} */ XS("Start extra long transmission"), - + /** * Indicates data for the extra long transmission, @see {@link FramedSCM} */ X0("Extra long data frame zero"), - + /** * Indicates data for the extra long transmission, @see {@link FramedSCM} */ X1("Extra long data frame one"), - + /** * Acknowledges the receipt of the {@link #X0} packet */ XA("Extra long ack to X0"), - + /** * Acknowledges the receipt of the {@link #X1} packet */ @@ -205,7 +205,7 @@ public enum SCMPacketType { /** * Create a new SCMPacketType enum element with the appropriate name to print * when relevant - * + * * @param name the full name of the packet type */ SCMPacketType(String name) { @@ -214,6 +214,7 @@ public enum SCMPacketType { /** * Returns the human readable name of the packet type + * * @return the human readable name of this packet type */ public String getName() { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMTransceiver.java b/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMTransceiver.java index e1bb4fd..5fc531c 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMTransceiver.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/comm/SCMTransceiver.java @@ -1,7 +1,6 @@ package org.rocketproplab.marginalstability.flightcomputer.comm; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; -import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.events.PacketListener; import org.rocketproplab.marginalstability.flightcomputer.events.SerialListener; import org.rocketproplab.marginalstability.flightcomputer.hal.SerialPort; @@ -13,9 +12,8 @@ * chunk it will notify the packet router of the new packet. It uses the * specified source for this as we can have multiple SCM packet sources. See * {@link PacketSources} for more info about packet sources. - * - * @author Max Apodaca, Antonio * + * @author Max Apodaca, Antonio */ public class SCMTransceiver implements SerialListener, PacketListener { private SerialPort serialPort; @@ -25,7 +23,7 @@ public class SCMTransceiver implements SerialListener, PacketListener /** * Create a new SCM Transceiver that will use this serial port to send and * receive data. - * + * * @param serialPort The serial port to send data to * @param router the router to use to route packets * @param source where the SCM is connected to @@ -43,7 +41,7 @@ public void onSerialData(String data) { router.recivePacket(packet, this.source); } else { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Got invalid packet " + data + "!"; + String errorMsg = "Got invalid packet " + data + "!"; errorReporter.reportError(null, null, errorMsg); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/AbortCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/AbortCommand.java index 35c0a96..da44ebe 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/AbortCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/AbortCommand.java @@ -3,36 +3,36 @@ import org.rocketproplab.marginalstability.flightcomputer.subsystems.EngineSubsystem; import org.rocketproplab.marginalstability.flightcomputer.subsystems.Subsystem; -public class AbortCommand implements Command{ - private EngineSubsystem enginesubsystem; - - AbortCommand(EngineSubsystem enginesubsystem){ - this.enginesubsystem = enginesubsystem; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public void execute() { - enginesubsystem.deactivateEngine(); - } - - @Override - public void start() { - - } - - @Override - public void end() { - - } - - @Override - public Subsystem[] getDependencies() { - return new Subsystem[0]; - } +public class AbortCommand implements Command { + private EngineSubsystem enginesubsystem; + + AbortCommand(EngineSubsystem enginesubsystem) { + this.enginesubsystem = enginesubsystem; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public void execute() { + enginesubsystem.deactivateEngine(); + } + + @Override + public void start() { + + } + + @Override + public void end() { + + } + + @Override + public Subsystem[] getDependencies() { + return new Subsystem[0]; + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/Command.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/Command.java index 741c60c..8dbe663 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/Command.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/Command.java @@ -5,12 +5,11 @@ /** * This is the super class for all commands. All commands will implement this * class. - * + *

* Basic capabilities of this class include executing, starting, and stopping * commands. Additionally, it can check whether the command is finished or not. - * - * @author Hemanth Battu, Enlil Odisho * + * @author Hemanth Battu, Enlil Odisho */ public interface Command { /** @@ -35,7 +34,7 @@ public interface Command { /** * Retrieves a list of dependencies - * + * * @return array of subsystems */ public Subsystem[] getDependencies(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/HeartbeatCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/HeartbeatCommand.java index 76e4bc5..29e3525 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/HeartbeatCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/HeartbeatCommand.java @@ -9,20 +9,19 @@ * This is the Heartbeat Command class that implements the Command interface. * The main capabilities of this class includes checking the start time and * sending a periodic "heartbeat" signal every second. - * - * @author Hemanth Battu * + * @author Hemanth Battu */ public class HeartbeatCommand implements Command { private static final Subsystem[] EMPTY_ARRAY = {}; - private int HBcounter; - private double startTime; - private Time time; - private Telemetry telemetry; + private int HBcounter; + private double startTime; + private Time time; + private Telemetry telemetry; /** * Creates a new HeartbeatCommand object using Time and Telemetry objects. - * + * * @param time the Time object to use for checking time * @param telemetry the Telemetry object used to send heartbeat */ @@ -33,7 +32,7 @@ public HeartbeatCommand(Time time, Telemetry telemetry) { /** * Setter method to set the start time. - * + * * @param startTime input to set start time with */ private void setStartTime(double startTime) { @@ -62,7 +61,7 @@ public void execute() { } } else { if (currentTime - - startTime >= ((HBcounter + 1) * (Settings.HEARTBEAT_THRESHOLD))) { + - startTime >= ((HBcounter + 1) * (Settings.HEARTBEAT_THRESHOLD))) { telemetry.sendHeartbeat(); HBcounter += 1; } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/LaunchCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/LaunchCommand.java index c8c1d34..c539fec 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/LaunchCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/LaunchCommand.java @@ -3,36 +3,36 @@ import org.rocketproplab.marginalstability.flightcomputer.subsystems.EngineSubsystem; import org.rocketproplab.marginalstability.flightcomputer.subsystems.Subsystem; -public class LaunchCommand implements Command{ - private EngineSubsystem enginesubsystem; - - LaunchCommand(EngineSubsystem enginesubsystem){ - this.enginesubsystem = enginesubsystem; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public void execute() { - enginesubsystem.activateEngine(); - } - - @Override - public void start() { - - } - - @Override - public void end() { - - } - - @Override - public Subsystem[] getDependencies() { - return new Subsystem [0]; - } +public class LaunchCommand implements Command { + private EngineSubsystem enginesubsystem; + + LaunchCommand(EngineSubsystem enginesubsystem) { + this.enginesubsystem = enginesubsystem; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public void execute() { + enginesubsystem.activateEngine(); + } + + @Override + public void start() { + + } + + @Override + public void end() { + + } + + @Override + public Subsystem[] getDependencies() { + return new Subsystem[0]; + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenDrogueChuteCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenDrogueChuteCommand.java index 2e4e9c4..1271586 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenDrogueChuteCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenDrogueChuteCommand.java @@ -8,49 +8,51 @@ import org.rocketproplab.marginalstability.flightcomputer.subsystems.Subsystem; public class OpenDrogueChuteCommand implements Command { - private ParachuteSubsystem parachuteSubsystem; - private PacketRelay relay; - - private OpenDrogueChuteCommand(ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { - this.parachuteSubsystem = parachuteSubsystem; - this.relay = relay; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public void execute() { - boolean success = parachuteSubsystem.attemptDrogueChuteOpen(); - relay.sendPacket(new SCMPacket( - SCMPacketType.DD, success? " 1" : " 0"), - PacketSources.CommandBox); - } - - @Override - public void start() { } - - @Override - public void end() { } - - @Override - public Subsystem[] getDependencies() { - return new Subsystem[] {parachuteSubsystem}; - } - - public static class OpenDrogueChuteFactory { - /** - * Get a new OpenDrogueChuteCommand - * - * @param parachuteSubsystem the ParachuteSubsystem this command will operate on - * @param relay the PacketRelay to send the success status packet through - * @return a new OpenDrogueChuteCommand - */ - public static OpenDrogueChuteCommand getOpenDrogueChuteCommand( - ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { - return new OpenDrogueChuteCommand(parachuteSubsystem, relay); - } + private ParachuteSubsystem parachuteSubsystem; + private PacketRelay relay; + + private OpenDrogueChuteCommand(ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { + this.parachuteSubsystem = parachuteSubsystem; + this.relay = relay; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public void execute() { + boolean success = parachuteSubsystem.attemptDrogueChuteOpen(); + relay.sendPacket(new SCMPacket( + SCMPacketType.DD, success ? " 1" : " 0"), + PacketSources.CommandBox); + } + + @Override + public void start() { + } + + @Override + public void end() { + } + + @Override + public Subsystem[] getDependencies() { + return new Subsystem[]{parachuteSubsystem}; + } + + public static class OpenDrogueChuteFactory { + /** + * Get a new OpenDrogueChuteCommand + * + * @param parachuteSubsystem the ParachuteSubsystem this command will operate on + * @param relay the PacketRelay to send the success status packet through + * @return a new OpenDrogueChuteCommand + */ + public static OpenDrogueChuteCommand getOpenDrogueChuteCommand( + ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { + return new OpenDrogueChuteCommand(parachuteSubsystem, relay); } + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenMainChuteCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenMainChuteCommand.java index 0f202ad..1002569 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenMainChuteCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/OpenMainChuteCommand.java @@ -8,50 +8,52 @@ import org.rocketproplab.marginalstability.flightcomputer.subsystems.Subsystem; public class OpenMainChuteCommand implements Command { - private ParachuteSubsystem parachuteSubsystem; - private PacketRelay relay; - - private OpenMainChuteCommand(ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { - this.parachuteSubsystem = parachuteSubsystem; - this.relay = relay; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public void execute() { - boolean success = parachuteSubsystem.attemptMainChuteOpen(); - relay.sendPacket(new SCMPacket( - SCMPacketType.MD, success? " 1" : " 0"), - PacketSources.CommandBox); - } - - @Override - public void start() { } - - @Override - public void end() { } - - @Override - public Subsystem[] getDependencies() { - return new Subsystem[] {parachuteSubsystem}; - } - - public static class OpenMainChuteFactory { - /** - * Get a new OpenMainChuteCommand - * - * @param parachuteSubsystem the ParachuteSubsystem this command will operate on - * @param relay the PacketRelay to send the success status packet through - * @return a new OpenMainChuteCommand - */ - public static OpenMainChuteCommand getOpenMainChuteCommand( - ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { - return new OpenMainChuteCommand(parachuteSubsystem, relay); - } + private ParachuteSubsystem parachuteSubsystem; + private PacketRelay relay; + + private OpenMainChuteCommand(ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { + this.parachuteSubsystem = parachuteSubsystem; + this.relay = relay; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public void execute() { + boolean success = parachuteSubsystem.attemptMainChuteOpen(); + relay.sendPacket(new SCMPacket( + SCMPacketType.MD, success ? " 1" : " 0"), + PacketSources.CommandBox); + } + + @Override + public void start() { + } + + @Override + public void end() { + } + + @Override + public Subsystem[] getDependencies() { + return new Subsystem[]{parachuteSubsystem}; + } + + public static class OpenMainChuteFactory { + /** + * Get a new OpenMainChuteCommand + * + * @param parachuteSubsystem the ParachuteSubsystem this command will operate on + * @param relay the PacketRelay to send the success status packet through + * @return a new OpenMainChuteCommand + */ + public static OpenMainChuteCommand getOpenMainChuteCommand( + ParachuteSubsystem parachuteSubsystem, PacketRelay relay) { + return new OpenMainChuteCommand(parachuteSubsystem, relay); } + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/SetValveCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/SetValveCommand.java index 516df67..fa9d046 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/SetValveCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/SetValveCommand.java @@ -27,7 +27,7 @@ public void execute() { valves.setValve(getValveID(), valveState); } catch (IllegalArgumentException dataOnOffException) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Data from SCMPacket was not On or Off. Data was actually: " + scmpacket.getData(); + String errorMsg = "Data from SCMPacket was not On or Off. Data was actually: " + scmpacket.getData(); errorReporter.reportError(null, dataOnOffException, errorMsg); } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/commands/UpdateSettingCommand.java b/src/org/rocketproplab/marginalstability/flightcomputer/commands/UpdateSettingCommand.java index 957102c..adbad11 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/commands/UpdateSettingCommand.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/commands/UpdateSettingCommand.java @@ -6,31 +6,37 @@ import java.util.Collections; public class UpdateSettingCommand implements Command { - private final String setting; - - UpdateSettingCommand(String setting) { - this.setting = setting; - } - - public static UpdateSettingCommand getUpdateSettingCommand(String setting) { - return new UpdateSettingCommand(setting); - } - - @Override - public boolean isDone() { return true; } - - @Override - public void execute() { - Settings.readSettingsFromConfig(Collections.singletonList(setting)); - } - - @Override - public void start() { } - - @Override - public void end() { } - - @Override - public Subsystem[] getDependencies() { return new Subsystem[0]; } + private final String setting; + + UpdateSettingCommand(String setting) { + this.setting = setting; + } + + public static UpdateSettingCommand getUpdateSettingCommand(String setting) { + return new UpdateSettingCommand(setting); + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public void execute() { + Settings.readSettingsFromConfig(Collections.singletonList(setting)); + } + + @Override + public void start() { + } + + @Override + public void end() { + } + + @Override + public Subsystem[] getDependencies() { + return new Subsystem[0]; + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/EngineEventListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/EngineEventListener.java index 1b83e63..b8badef 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/EngineEventListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/EngineEventListener.java @@ -14,7 +14,7 @@ public interface EngineEventListener { /** * Called when new engine data is received - * + * * @param type the type of data which was received * @param value the value of the data which was received */ @@ -22,15 +22,16 @@ public interface EngineEventListener { /** * The different types of data which relate to the engine - * - * @author Max Apodaca * + * @author Max Apodaca */ public enum EngineDataType { /** * Temperature of the engine bell */ Temperature - }; + } + + ; } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/FlightStateListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/FlightStateListener.java index 9497805..9eaa514 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/FlightStateListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/FlightStateListener.java @@ -6,8 +6,9 @@ public interface FlightStateListener { /** * Called when the flight mode changes + * * @param newMode the new flight mode we are in */ public void onFlightModeChange(FlightMode newMode); - + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/PacketListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/PacketListener.java index 0090366..8a5cbe2 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/PacketListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/PacketListener.java @@ -4,14 +4,13 @@ /** * Listens for a particular type of packet in a particular direction - * - * @author Max Apodaca * * @param The type of packet to listen for (should be GPSPacket or * SCMPacket) + * @author Max Apodaca */ public interface PacketListener { - public void onPacket(PacketDirection direction, E packet); + public void onPacket(PacketDirection direction, E packet); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/ParachuteListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/ParachuteListener.java index c35e815..3ac5a4f 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/ParachuteListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/ParachuteListener.java @@ -2,8 +2,8 @@ /** * A listener for changes in the parachute state. - * @author Max Apodaca * + * @author Max Apodaca */ public interface ParachuteListener { @@ -11,15 +11,15 @@ public interface ParachuteListener { * Called when the drogue chute opens */ public void onDrogueOpen(); - + /** * Called when the drogue chute is cut */ public void onDrougeCut(); - + /** * Called when the main chute opens. */ public void onMainChuteOpen(); - + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/PositionListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/PositionListener.java index 69c0cda..10a23f8 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/PositionListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/PositionListener.java @@ -4,15 +4,14 @@ /** * An interface for listening to new position estimations - * - * @author Max Apodaca * + * @author Max Apodaca */ public interface PositionListener { /** * Called when new estimate is available - * + * * @param positionEstimate the new position estimate */ public void onPositionEstimate(InterpolatingVector3 positionEstimate); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/SerialListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/SerialListener.java index 0f32a92..f08e9ac 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/SerialListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/SerialListener.java @@ -3,15 +3,14 @@ /** * A listener for the serial port. It is notified when the serial port receives * a new message. - * - * @author Max Apodaca, Antonio * + * @author Max Apodaca, Antonio */ public interface SerialListener { - + /** * Called each time the serial port receives a string - * + * * @param data the data that was received */ public void onSerialData(String data); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/events/VelocityListener.java b/src/org/rocketproplab/marginalstability/flightcomputer/events/VelocityListener.java index 80d09ac..b8a264d 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/events/VelocityListener.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/events/VelocityListener.java @@ -4,16 +4,17 @@ /** * Listens for updates in the velocity - * @author Max Apodaca * + * @author Max Apodaca */ public interface VelocityListener { /** * Called when a new velocity measurement is recorded + * * @param velocity the velocity which was recorded - * @param time the time at which the measurement was recorded + * @param time the time at which the measurement was recorded */ public void onVelocityUpdate(Vector3 velocity, double time); - + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelGyroReading.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelGyroReading.java index 4bb2c08..cd66622 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelGyroReading.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelGyroReading.java @@ -6,15 +6,14 @@ * An AccelGyroReading is the accelerometer and gyroscope data read by an * IMU at an instant. It consists of an acceleration vector as well as a * rotation difference.
- * + *

* The rotation vector specified how many radians were rotated in the last * timestep in the local reference frame.
* The acceleration vector is the acceleration felt by the IMU in the local * reference frame in meters / second^2. If the IMU is lying flat on a table it * would read (0, 0, 9.81). - * - * @author Max Apodaca * + * @author Max Apodaca */ public class AccelGyroReading { @@ -23,7 +22,7 @@ public class AccelGyroReading { /** * Construct a new AccelGyroReading to store the acceleration and rotation. - * + * * @param acc * @param rotation */ @@ -34,7 +33,7 @@ public AccelGyroReading(Vector3 acc, Vector3 rotation) { /** * Get the rotation delta in the given reference frame in radians. - * + * * @return the difference in rotation from the last reading. */ public Vector3 getXYZRotation() { @@ -43,7 +42,7 @@ public Vector3 getXYZRotation() { /** * Get the acceleration at the given sample time in m/s^2. - * + * * @return the acceleration in m/s^2 as a 3 component x y z vector */ public Vector3 getXYZAcceleration() { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelerometerGyroscope.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelerometerGyroscope.java index 8140984..53ecf74 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelerometerGyroscope.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/AccelerometerGyroscope.java @@ -5,16 +5,15 @@ * this interface will give an iterable list of AccelGyroReadings. If hasNext * returns true there will be at least another accelerometer and gyroscope * reading. - * - * @author max * + * @author max */ public interface AccelerometerGyroscope { /** * Read the next accelerometer and gyroscope reading, returns null if * {@link #hasNext()} returns false. - * + * * @return the next accelerometer and gyroscope reading or null. */ public AccelGyroReading getNext(); @@ -22,7 +21,7 @@ public interface AccelerometerGyroscope { /** * Determines if there is another reading from the accelerometer/gyroscope * that can be read with {@link #getNext()} - * + * * @return true if {@link #getNext()} will return a new accelerometer and * gyroscope reading, false otherwise. */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Barometer.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Barometer.java index 7cf555e..84d36af 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Barometer.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Barometer.java @@ -3,7 +3,7 @@ public interface Barometer { /** * Get the pressure in hPa - * + * * @return get the pressure in hPa */ public double getPressure(); @@ -11,21 +11,21 @@ public interface Barometer { /** * Returns if the pressure is in a usable range. If the sensor is in too low or * too high air pressure the data we get might be garbage. - * + * * @return if the current pressure is in a usable range */ public boolean inUsableRange(); /** * Gets the time at which the last measurement was made - * + * * @return the time of the last measurements */ public double getLastMeasurementTime(); /** * Returns an instance to a standard samplable sensor - * + * * @return the standard samplable sensor */ public SamplableSensor getSamplable(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/DummyPiCommandsImu.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/DummyPiCommandsImu.java index ecefaba..e53468a 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/DummyPiCommandsImu.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/DummyPiCommandsImu.java @@ -1,18 +1,18 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; public class DummyPiCommandsImu { - - private byte altX; - private byte altY; - private byte alyZ; - - - /** - * This is for receiving packages. Basically a dummy pi command set. - * I loved it. - */ - public void DummyPiCommands() { - } + + private byte altX; + private byte altY; + private byte alyZ; + + + /** + * This is for receiving packages. Basically a dummy pi command set. + * I loved it. + */ + public void DummyPiCommands() { + } } /* * i2c has registers which store data generally for things like altitude it's diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/LPS22HD.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/LPS22HD.java index 4670a79..9957604 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/LPS22HD.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/LPS22HD.java @@ -1,19 +1,17 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; -import java.io.IOException; - +import com.pi4j.io.i2c.I2CDevice; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.Time; -import com.pi4j.io.i2c.I2CDevice; +import java.io.IOException; /** * The LPS22HD HAL implementation. Refer to the datasheet for specification https://www.st.com/resource/en/datasheet/lps22hd.pdf - * - * @author Clara Chun, Max Apodaca * + * @author Clara Chun, Max Apodaca */ public class LPS22HD implements Barometer, PollingSensor { @@ -39,7 +37,7 @@ public class LPS22HD implements Barometer, PollingSensor { * Create a new LPS22HD with the given i2cDevice and time. Time will be used to * determine the {@link #getLastMeasurementTime()} return value.
* The i2cDevice parameter is not checked for a valid address. - * + * * @param i2cDevice the device which should be used to communicate via i2c * @param time the time to use when reporting measurement time. */ @@ -58,7 +56,7 @@ public void init() { i2cDevice.write(CTRL_REG1, (byte) (ODR_25HZ | LOW_PASS_ENABLE | LOW_PASS_20TH | KEEP_REGISTERS_SYCHONISED_BDU)); } catch (IOException e) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Unable to write from i2cDevice IO Exception"; + String errorMsg = "Unable to write from i2cDevice IO Exception"; errorReporter.reportError(Errors.LPS22HD_INITIALIZATION_ERROR, e, errorMsg); } } @@ -93,7 +91,7 @@ public void poll() { /** * Read the current pressure form the sensor using a one shot read method. - * + *

* MSB LSB Complete 24-bit word: | buffer[2] | buffer[1] | buffer[0] | * Registers: | 0x2A | 0x29 | 0x28 | */ @@ -101,7 +99,7 @@ private void readPressure() { // TODO Read at once so we don't read high on sample 1 and low on sample 2. As // in if the sample changes while we are reading. try { - byte[] buffer = { 0, 0, 0 }; + byte[] buffer = {0, 0, 0}; i2cDevice.read(REG_PRESSURE_EXTRA_LOW, buffer, 0, 3); // Out of range if MSB = 1 @@ -112,11 +110,11 @@ private void readPressure() { } int rawPressure = (Byte.toUnsignedInt(buffer[2]) << 16) + (Byte.toUnsignedInt(buffer[1]) << 8) - + Byte.toUnsignedInt(buffer[0]); + + Byte.toUnsignedInt(buffer[0]); pressure = rawPressure / (double) SCALING_FACTOR; } catch (IOException e) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Unable to read Pressure from i2cDevice IO Exception"; + String errorMsg = "Unable to read Pressure from i2cDevice IO Exception"; errorReporter.reportError(Errors.LPS22HD_PRESSURE_IO_ERROR, e, errorMsg); } sampleTime = clock.getSystemTime(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1AccelGyro.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1AccelGyro.java index 18377ff..7097fb1 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1AccelGyro.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1AccelGyro.java @@ -1,23 +1,22 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayDeque; -import java.util.Arrays; - +import com.pi4j.io.i2c.I2CDevice; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.Settings; import org.rocketproplab.marginalstability.flightcomputer.math.Vector3; -import com.pi4j.io.i2c.I2CDevice; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayDeque; +import java.util.Arrays; /** * The HAL implementation for the LSM9DS1 accelerometer and gyroscope sensors. * Datasheet can be found here: https://www.st.com/resource/en/datasheet/lsm9ds1.pdf
- * + *

* Every time poll is called this sensor will acquire as many samples as * possible from the LSM9DS1's internal FIFO buffer. This is done by reading the * number of samples in the FIFO and then reading the FIFO output registers @@ -26,9 +25,8 @@ * {@link #getNext()} method. Whether or not the queue is empty can be read * using the {@link #hasNext()} method. It is recommended to call * {@link #hasNext()} before each call of {@link #getNext()}. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class LSM9DS1AccelGyro implements PollingSensor, AccelerometerGyroscope { private static final int ODR_MASK = 0b111; @@ -43,17 +41,17 @@ public class LSM9DS1AccelGyro implements PollingSensor, AccelerometerGyroscope { private static final int FIFO_MODE_LSB_POS = 5; private static final int FIFO_THRESHOLD_MASK = 0b11111; private static final int FIFO_THRESHOLD_LSB_POS = 0; - public static final int FIFO_THRESHOLD_MAX = 31; - public static final int FIFO_THRESHOLD_MIN = 0; - public static final int FIFO_OVERRUN_POS = 6; - public static final int FIFO_THRESHOLD_STATUS_POS = 7; - public static final int FIFO_SAMPLES_STORED_MASK = 0b111111; - - private static final int BYTES_PER_FIFO_LINE = 12; - - public static final double ACCELEROMETER_OUTPUT_TO_MPS_SQUARED = 9.81; // factor to multiply acc output by to - // convert sensor output to m/s^2 - private static final double ONE_DEGREE_IN_RADIANS = Math.PI / 180.0; + public static final int FIFO_THRESHOLD_MAX = 31; + public static final int FIFO_THRESHOLD_MIN = 0; + public static final int FIFO_OVERRUN_POS = 6; + public static final int FIFO_THRESHOLD_STATUS_POS = 7; + public static final int FIFO_SAMPLES_STORED_MASK = 0b111111; + + private static final int BYTES_PER_FIFO_LINE = 12; + + public static final double ACCELEROMETER_OUTPUT_TO_MPS_SQUARED = 9.81; // factor to multiply acc output by to + // convert sensor output to m/s^2 + private static final double ONE_DEGREE_IN_RADIANS = Math.PI / 180.0; /** * All the registers that can be found in the LSM9DS1 imu for the accelerometer @@ -120,7 +118,7 @@ public enum Registers { /** * Read the address of a register, this is not necessarily the same as the * ordinal and should be used for I2C access. - * + * * @return the I2C address of the register. */ public int getAddress() { @@ -165,6 +163,7 @@ public int getValueLSBPos() { return ACCELEROMETER_SCALE_LSB_POS; } } + /** * The current accelerometer scale the sensor is set to. * Initialize to default value as specified in sensor datasheet. @@ -191,6 +190,7 @@ public int getValueLSBPos() { return GYRO_SCALE_LSB_POS; } } + /** * The current gyroscope scale the sensor is set to. * Initialize to default value as specified in sensor datasheet. @@ -225,13 +225,13 @@ public int getValueLSBPos() { } } - private I2CDevice i2c; + private I2CDevice i2c; private ArrayDeque samples = new ArrayDeque<>(); /** * Create a new LSM9DS1AccelGyro on the given {@link I2CDevice}. There is no * validation for the {@link I2CDevice} address. - * + * * @param device the device to use for I2C communication */ public LSM9DS1AccelGyro(I2CDevice device) { @@ -240,7 +240,7 @@ public LSM9DS1AccelGyro(I2CDevice device) { /** * Sets the output data rate of the sensor - * + * * @throws IOException if unable to read */ public void setODR(ODR odr) throws IOException { @@ -249,7 +249,7 @@ public void setODR(ODR odr) throws IOException { /** * Sets the scale of the accelerometer - * + * * @param scale the scale of the accelerometer data * @throws IOException if we are unable to access the i2c device */ @@ -257,9 +257,10 @@ public void setAccelerometerScale(AccelerometerScale scale) throws IOException { modifyRegister(Registers.CTRL_REG6_XL, scale); accelScale = scale; } - + /** * Returns the scale of the accelerometer + * * @return the set accelerometer scale */ public AccelerometerScale getAccelerometerScale() { @@ -268,7 +269,7 @@ public AccelerometerScale getAccelerometerScale() { /** * Sets the scale of the Gyroscope - * + * * @param scale the scale of the gyroscope data * @throws IOException if we are unable to access the i2c device */ @@ -276,9 +277,10 @@ public void setGyroscopeScale(GyroScale scale) throws IOException { modifyRegister(Registers.CTRL_REG1_G, scale); gyroScale = scale; } - + /** * Returns the scale of the gyroscope + * * @return the set gyroscope scale */ public GyroScale getGyroscopeScale() { @@ -287,7 +289,7 @@ public GyroScale getGyroscopeScale() { /** * Enable or disable the FIFO by setting CTRL_REG9 - * + * * @param enabled whether or not to enable the fifo * @throws IOException if we are unable to access the i2c device */ @@ -299,7 +301,7 @@ public void setFIFOEnabled(boolean enabled) throws IOException { /** * Set the FIFOMode to the new mode - * + * * @param mode the new FIFOMode to use * @throws IOException if we are unable to access the i2c device */ @@ -309,7 +311,7 @@ public void setFIFOMode(FIFOMode mode) throws IOException { /** * Set the threshold at which we should signal that the FIFO is full. - * + * * @param threshold the number of samples at which we start signaling * @throws IOException if we are unable to access the i2c device */ @@ -328,7 +330,7 @@ public void setFIFOThreshold(int threshold) throws IOException { /** * Returns if the FIFO buffer's data has been exceeded. This means that data was * lost. - * + * * @return if the FIFO overflowed * @throws IOException if we are unable to access the i2c device */ @@ -341,7 +343,7 @@ public boolean hasFIFOOverrun() throws IOException { /** * Are we at the FIFO threshold yet. See {@link #setFIFOThreshold(int)} on how * to set the threshold. - * + * * @return if we are at the FIFO threshold * @throws IOException if we are unable to access the i2c device */ @@ -353,7 +355,7 @@ public boolean isFIFOThresholdReached() throws IOException { /** * Read how many samples are in the FIFO at the current time. - * + * * @return the number of samples in the FIFO * @throws IOException if we are unable to access the i2c device */ @@ -365,7 +367,7 @@ public int getSamplesInFIFO() throws IOException { /** * Write a register value to a register. - * + * * @param register the register to write to * @param value the value to write, uses all of the values in * {@link RegisterValue} @@ -385,7 +387,7 @@ private void modifyRegister(Registers register, RegisterValue value) throws IOEx * anding with toMask.
*
* Note: No values in newData are masked out. - * + * * @param toMask the value to mask * @param newData the value to replace the masked areas of to mask * @param lsbPos how far to the left the masked value is in toMask @@ -428,7 +430,7 @@ private void readFromSensor() { this.parseReadings(data, samplesRead); } catch (IOException e) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Unable to read from IMU IO Exception"; + String errorMsg = "Unable to read from IMU IO Exception"; errorReporter.reportError(Errors.IMU_IO_ERROR, e, errorMsg); } } @@ -437,16 +439,16 @@ private void readFromSensor() { * Take the raw data read and split it into chunks of BYTES_PER_FIFO_LINE bytes * to correspond to each IMU reading. Then feed those into * {@link #buildReading(byte[])}. - * + * * @param data the raw data to parse * @param bytesRead how many bytes were read. */ private void parseReadings(byte[] data, int bytesRead) { int samplesRead = bytesRead / BYTES_PER_FIFO_LINE; for (int i = 0; i < samplesRead; i++) { - int start = i * BYTES_PER_FIFO_LINE; - int end = (i + 1) * BYTES_PER_FIFO_LINE; - byte[] samples = Arrays.copyOfRange(data, start, end); + int start = i * BYTES_PER_FIFO_LINE; + int end = (i + 1) * BYTES_PER_FIFO_LINE; + byte[] samples = Arrays.copyOfRange(data, start, end); AccelGyroReading reading = this.buildReading(samples); this.samples.add(reading); } @@ -455,7 +457,7 @@ private void parseReadings(byte[] data, int bytesRead) { /** * Parse a set of BYTES_PER_FIFO_LINE bytes into an AccelGyroReading.
* Use range to normalize to m/s^2 - * + * * @param data the set of six bytes representing a reading * @return the AccelGyroReading which the six bytes belong to. */ @@ -478,13 +480,13 @@ public AccelGyroReading buildReading(byte[] data) { * Converts the input bytes to shorts where it assumes that the first byte of * the tuple is less significant.
* The array looks like {@code [L,H,L,H, ..., L, H]}. - * + * * @param data byte array of little-endian shorts * @return array of the shorts */ private int[] getData(byte[] data) { ByteBuffer byteBuffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN); - int[] results = new int[data.length / 2]; + int[] results = new int[data.length / 2]; for (int i = 0; i < data.length / 2; i++) { results[i] = byteBuffer.getShort(i * 2); // i * 2 = index of low byte } @@ -500,9 +502,10 @@ public AccelGyroReading getNext() { public boolean hasNext() { return !samples.isEmpty(); } - + /** * Converts accelerometer readings to m/s^2. Uses the current accelerometer scale setting. + * * @param accX x-axis reading from accelerometer * @param accY y-axis reading from accelerometer * @param accZ z-axis reading from accelerometer @@ -511,35 +514,36 @@ public boolean hasNext() { public Vector3 computeAcceleration(int accX, int accY, int accZ) { // Get the accelerometer sensitivity. double sensitivity; - switch(accelScale) { - case G_2: - sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_2G; - break; - case G_4: - sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_4G; - break; - case G_8: - sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_8G; - break; - case G_16: - sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_16G; - break; - default: - throw new IllegalStateException("Sensor has an unknown accelerometer scale."); + switch (accelScale) { + case G_2: + sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_2G; + break; + case G_4: + sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_4G; + break; + case G_8: + sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_8G; + break; + case G_16: + sensitivity = Settings.LSM9DS1_SENSITIVITY_ACCELEROMETER_16G; + break; + default: + throw new IllegalStateException("Sensor has an unknown accelerometer scale."); } - + // This factor converts accelerometer readings to m/s^2 double conversionFactor = sensitivity * ACCELEROMETER_OUTPUT_TO_MPS_SQUARED; - + return new Vector3( - accX * conversionFactor, - accY * conversionFactor, - accZ * conversionFactor + accX * conversionFactor, + accY * conversionFactor, + accZ * conversionFactor ); } - + /** * Converts gyroscope readings to radians per second. Uses the current gyroscope scale setting. + * * @param gyroX x-axis reading from gyroscope * @param gyroY y-axis reading from gyroscope * @param gyroZ z-axis reading from gyroscope @@ -548,27 +552,27 @@ public Vector3 computeAcceleration(int accX, int accY, int accZ) { public Vector3 computeAngularAcceleration(int gyroX, int gyroY, int gyroZ) { // Get the gyroscope sensitivity. double sensitivity; - switch(gyroScale) { - case DPS_245: - sensitivity = Settings.LSM9DS1_SENSITIVITY_GYROSCOPE_245DPS; - break; - case DPS_500: - sensitivity = Settings.LSM9DS1_SENSITIVITY_GYROSCOPE_500DPS; - break; - case DPS_2000: - sensitivity = Settings.LSM9DS1_SENSITIVITY_GYROSCOPE_2000DPS; - break; - default: - throw new IllegalStateException("Sensor has an unknown gyroscope scale."); + switch (gyroScale) { + case DPS_245: + sensitivity = Settings.LSM9DS1_SENSITIVITY_GYROSCOPE_245DPS; + break; + case DPS_500: + sensitivity = Settings.LSM9DS1_SENSITIVITY_GYROSCOPE_500DPS; + break; + case DPS_2000: + sensitivity = Settings.LSM9DS1_SENSITIVITY_GYROSCOPE_2000DPS; + break; + default: + throw new IllegalStateException("Sensor has an unknown gyroscope scale."); } - + // This factor converts gyroscope readings to radians per second double conversionFactor = sensitivity * ONE_DEGREE_IN_RADIANS; - + return new Vector3( - gyroX * conversionFactor, - gyroY * conversionFactor, - gyroZ * conversionFactor + gyroX * conversionFactor, + gyroY * conversionFactor, + gyroZ * conversionFactor ); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1Mag.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1Mag.java index cb3fd16..b2d9d42 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1Mag.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/LSM9DS1Mag.java @@ -1,46 +1,44 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.ArrayDeque; - +import com.pi4j.io.i2c.I2CDevice; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.Settings; import org.rocketproplab.marginalstability.flightcomputer.math.Vector3; -import com.pi4j.io.i2c.I2CDevice; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.ArrayDeque; /** * The HAL implementation for the LSM9DS1 magnetometer sensor. Datasheet can be * found here: https://www.st.com/resource/en/datasheet/lsm9ds1.pdf
- * + *

* Every time poll is called, this sensor will acquire 1 sample from the LSM9DS1 * magnetometer registers. Each sample gets put into a queue which can be accessed * with the {@link #getNext()} method. Whether or not the queue is empty can be * read using the {@link #hasNext()} method. It is recommended to call * {@link #hasNext()} before each call of {@link #getNext()}. - * - * @author Enlil Odisho * + * @author Enlil Odisho */ public class LSM9DS1Mag implements PollingSensor, Magnetometer { - private static final int ODR_MASK = 0b111; - private static final int ODR_LSB_POS = 2; - private static final int SCALE_MASK = 0b11; - private static final int SCALE_LSB_POS = 5; - private static final int MODE_MASK = 0b11; - private static final int MODE_LSB_POS = 0; - private static final int PERFORMANCE_MASK = 0b11; - private static final int PERFORMANCE_XY_LSB_POS = 5; - private static final int PERFORMANCE_Z_LSB_POS = 2; - private static final int TEMP_COMPENSATE_MASK = 0b1; - private static final int TEMP_COMPENSATE_POS = 7; - private static final int BLOCK_DATA_UPDATE_MASK = 0b1; - private static final int BLOCK_DATA_UPDATE_POS = 6; - private static final int NEW_XYZ_DATA_AVAILABLE_POS = 3; - + private static final int ODR_MASK = 0b111; + private static final int ODR_LSB_POS = 2; + private static final int SCALE_MASK = 0b11; + private static final int SCALE_LSB_POS = 5; + private static final int MODE_MASK = 0b11; + private static final int MODE_LSB_POS = 0; + private static final int PERFORMANCE_MASK = 0b11; + private static final int PERFORMANCE_XY_LSB_POS = 5; + private static final int PERFORMANCE_Z_LSB_POS = 2; + private static final int TEMP_COMPENSATE_MASK = 0b1; + private static final int TEMP_COMPENSATE_POS = 7; + private static final int BLOCK_DATA_UPDATE_MASK = 0b1; + private static final int BLOCK_DATA_UPDATE_POS = 6; + private static final int NEW_XYZ_DATA_AVAILABLE_POS = 3; + private static final int BYTES_PER_SAMPLE = 6; private static final int BITS_PER_BYTE = 8; @@ -72,24 +70,26 @@ public enum Registers { INT_SRC_M(0x31), INT_THS_L(0x32), INT_THS_H(0x33); - + final int address; - + Registers(int address) { this.address = address; } - + /** * Read the address of a register, this is not necessarily the same as the * ordinal and should be used for I2C access. - * + * * @return the I2C address of the register. */ public int getAddress() { return this.address; } - }; - + } + + ; + public enum ODR implements RegisterValue { ODR_0_625, ODR_1_25, @@ -109,9 +109,9 @@ public int getValueMask() { public int getValueLSBPos() { return ODR_LSB_POS; } - + } - + public enum SCALE implements RegisterValue { GAUSS_4, GAUSS_8, @@ -128,17 +128,18 @@ public int getValueLSBPos() { return SCALE_LSB_POS; } } + /** * The current scale the magnetometer is set to. * Initialized to the default value that was specified in the datasheet. */ private SCALE scale = SCALE.GAUSS_4; - + public enum MODE implements RegisterValue { CONTINUOUS_CONVERSION, SINGLE_CONVERSION, POWER_DOWN; - + @Override public int getValueMask() { return MODE_MASK; @@ -149,13 +150,13 @@ public int getValueLSBPos() { return MODE_LSB_POS; } } - + public enum PERFORMANCE_XY implements RegisterValue { LOW, MEDIUM, HIGH, ULTRA; - + @Override public int getValueMask() { return PERFORMANCE_MASK; @@ -166,13 +167,13 @@ public int getValueLSBPos() { return PERFORMANCE_XY_LSB_POS; } } - + public enum PERFORMANCE_Z implements RegisterValue { LOW, MEDIUM, HIGH, ULTRA; - + @Override public int getValueMask() { return PERFORMANCE_MASK; @@ -183,33 +184,33 @@ public int getValueLSBPos() { return PERFORMANCE_Z_LSB_POS; } } - - private I2CDevice i2c; + + private I2CDevice i2c; private ArrayDeque samples = new ArrayDeque<>(); - + /** * Create a new LSM9DS1Mag on the given {@link I2CDevice}. There is no * validation for the {@link I2CDevice} address. - * + * * @param device the device to use for the I2C communication */ public LSM9DS1Mag(I2CDevice device) { this.i2c = device; } - + /** * Sets the output data rate of the sensor - * + * * @param odr the rate to set sensor to * @throws IOException if we are unable to access the i2c device */ public void setODR(ODR odr) throws IOException { modifyRegister(Registers.CTRL_REG1_M, odr); } - + /** * Sets the scale of the sensor - * + * * @param newScale the scale of the magnetometer data * @throws IOException if we are unable to access the i2c device */ @@ -217,49 +218,49 @@ public void setScale(SCALE newScale) throws IOException { modifyRegister(Registers.CTRL_REG2_M, newScale); scale = newScale; } - + /** * Returns the scale of the magnetometer. + * * @return the set magnetometer scale */ - public SCALE getScale() - { + public SCALE getScale() { return scale; } - + /** * Sets the operating mode of the magnetometer sensor - * + * * @param mode Operating mode of sensor * @throws IOException if we are unable to access the i2c device */ public void setMode(MODE mode) throws IOException { modifyRegister(Registers.CTRL_REG3_M, mode); } - + /** * Sets the performance of the sensor for x and y magnetometer data - * + * * @param performance the performance of the magnetometer sensor for xy data * @throws IOException if we are unable to access the i2c device */ public void setXYPerformance(PERFORMANCE_XY performance) throws IOException { modifyRegister(Registers.CTRL_REG1_M, performance); } - + /** * Sets the performance of the sensor for z magnetometer data - * + * * @param performance the performance of the magnetometer sensor for z data * @throws IOException if we are unable to access the i2c device */ public void setZPerformance(PERFORMANCE_Z performance) throws IOException { modifyRegister(Registers.CTRL_REG4_M, performance); } - + /** * Enable or disable temperature compensation for magnetometer sensor - * + * * @param enabled whether or not to enable temperature compensation * @throws IOException if we are unable to access the i2c device */ @@ -268,11 +269,11 @@ public void setTemperatureCompensationEnabled(boolean enabled) throws IOExceptio int result = mask(registerValue, enabled ? 1 : 0, TEMP_COMPENSATE_POS, TEMP_COMPENSATE_MASK); this.i2c.write(Registers.CTRL_REG1_M.getAddress(), (byte) result); } - + /** * Whether or not to block the magnetic data from updating until all LSB and * MSB are read for the current sample. - * + * * @param enabled whether or not to enable BDU feature * @throws IOException if we are unable to access the i2c device */ @@ -281,7 +282,7 @@ public void setBlockDataUpdateUntilAllReadEnabled(boolean enabled) throws IOExce int result = mask(registerValue, enabled ? 1 : 0, BLOCK_DATA_UPDATE_POS, BLOCK_DATA_UPDATE_MASK); this.i2c.write(Registers.CTRL_REG5_M.getAddress(), (byte) result); } - + /** * @return whether new x/y/z data is available or not. * @throws IOException if we are unable to access the i2c device @@ -291,10 +292,10 @@ public boolean isNewXYZDataAvailable() throws IOException { int masked = (1 << NEW_XYZ_DATA_AVAILABLE_POS) & statusRegValue; return masked != 0; } - + /** * Write a register value to a register. - * + * * @param register the register to write to * @param value the value to write, uses all of the values in * {@link RegisterValue} @@ -305,7 +306,7 @@ private void modifyRegister(Registers register, RegisterValue value) throws IOEx int result = mask(registerValue, value.ordinal(), value.getValueLSBPos(), value.getValueMask()); this.i2c.write(register.getAddress(), (byte) result); } - + /** * Masks the value in toMask with the given parameters. newData is the data to * replace the masked bits. LSBPos is how many bits to the left newData is in @@ -314,7 +315,7 @@ private void modifyRegister(Registers register, RegisterValue value) throws IOEx * anding with toMask.
*
* Note: No values in newData are masked out. - * + * * @param toMask the value to mask * @param newData the value to replace the masked areas of to mask * @param lsbPos how far to the left the masked value is in toMask @@ -327,12 +328,12 @@ private int mask(int toMask, int newData, int lsbPos, int valueMask) { int result = newData << lsbPos | (toMask & notMask); return result; } - + @Override public void poll() { this.readFromSensor(); } - + /** * Read one sample from the sensor. This method will read the sample by * reading BYTES_PER_SAMPLE number of bytes from the register OUT_X_L_M. @@ -342,59 +343,59 @@ private void readFromSensor() { if (!isNewXYZDataAvailable()) { return; } - int dataLength = BYTES_PER_SAMPLE; - byte[] data = new byte[dataLength]; - int bytesRead = this.i2c.read(Registers.OUT_X_L_M.getAddress(), data, 0, dataLength); + int dataLength = BYTES_PER_SAMPLE; + byte[] data = new byte[dataLength]; + int bytesRead = this.i2c.read(Registers.OUT_X_L_M.getAddress(), data, 0, dataLength); if (bytesRead != BYTES_PER_SAMPLE) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Incorrect number of bytes for magnetometer read from IMU."; + String errorMsg = "Incorrect number of bytes for magnetometer read from IMU."; errorReporter.reportError(Errors.IMU_IO_ERROR, errorMsg); return; } - MagReading reading = this.buildReading(data); + MagReading reading = this.buildReading(data); this.samples.add(reading); - } catch(IOException e) { + } catch (IOException e) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Unable to read from IMU IO Exception"; + String errorMsg = "Unable to read from IMU IO Exception"; errorReporter.reportError(Errors.IMU_IO_ERROR, e, errorMsg); } } - + /** * Parse a set of BYTES_PER_SAMPLE bytes into an MagReading. * Normalzie to gauss - * + * * @param data the set of six bytes representing a reading * @return the MagReading which the six bytes belong to */ public MagReading buildReading(byte[] data) { int[] results = this.getData(data); - + int xMag = results[0]; int yMag = results[1]; int zMag = results[2]; - + Vector3 magVec = computeMagneticField(xMag, yMag, zMag); return new MagReading(magVec); } - + /** * Converts the input bytes to shorts where it assumes that the first byte of * the tuple is less significant.
* The array looks like {@code [L,H,L,H, ..., L, H]}. - * + * * @param data byte array of little-endian shorts * @return array of the shorts */ private int[] getData(byte[] data) { ByteBuffer byteBuffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN); - int[] results = new int[data.length / 2]; + int[] results = new int[data.length / 2]; for (int i = 0; i < data.length / 2; i++) { results[i] = byteBuffer.getShort(i * 2); // i * 2 = index of low byte } return results; } - + @Override public MagReading getNext() { return samples.pollFirst(); @@ -404,9 +405,10 @@ public MagReading getNext() { public boolean hasNext() { return !samples.isEmpty(); } - + /** * Converts magnetometer readings to gauss. Uses the current magnetometer scale setting. + * * @param magX x-axis reading from magnetometer * @param magY y-axis reading from magnetometer * @param magZ z-axis reading from magnetometer @@ -415,28 +417,28 @@ public boolean hasNext() { public Vector3 computeMagneticField(int magX, int magY, int magZ) { // Get the sensitivity of the sensor double sensitivity; - switch(scale) { - case GAUSS_4: - sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_4GAUSS; - break; - case GAUSS_8: - sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_8GAUSS; - break; - case GAUSS_12: - sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_12GAUSS; - break; - case GAUSS_16: - sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_16GAUSS; - break; - default: - throw new IllegalStateException("Sensor has an unknown scale."); + switch (scale) { + case GAUSS_4: + sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_4GAUSS; + break; + case GAUSS_8: + sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_8GAUSS; + break; + case GAUSS_12: + sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_12GAUSS; + break; + case GAUSS_16: + sensitivity = Settings.LSM9DS1_SENSITIVITY_MAGNETOMETER_16GAUSS; + break; + default: + throw new IllegalStateException("Sensor has an unknown scale."); } - + // Compute magnetic field in gauss return new Vector3( - magX * sensitivity, - magY * sensitivity, - magZ * sensitivity); + magX * sensitivity, + magY * sensitivity, + magZ * sensitivity); } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX14830.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX14830.java index 9ea745f..5ba4886 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX14830.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX14830.java @@ -1,29 +1,26 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; -import java.io.IOException; -import java.nio.charset.Charset; - +import com.pi4j.io.spi.SpiDevice; import org.rocketproplab.marginalstability.flightcomputer.ErrorReporter; import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.Settings; -import com.pi4j.io.spi.SpiDevice; +import java.io.IOException; +import java.nio.charset.Charset; /** * A class that implements the SPI protocol for the MAX14830, it contains the * code to emit serial port events to any listeners listening to ports provided * by the MAX14830. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class MAX14830 implements PollingSensor { /** * The list of ports which we can access on the MAX14830 - * - * @author Max Apodaca * + * @author Max Apodaca */ public enum Port { UART0, @@ -34,9 +31,8 @@ public enum Port { /** * The list of registers found on the MAX14830 - * - * @author Max Apodaca * + * @author Max Apodaca */ public enum Registers { // FIFO DATA @@ -120,7 +116,7 @@ public byte address() { /** * Create the MAX14830 and initialize the event handlers with * {@link SerialPortAdapter}. TODO Use chipselect via gpio - * + * * @param spi the Spi device to use, no validation is done */ public MAX14830(SpiDevice spi) { @@ -140,7 +136,7 @@ public MAX14830(SpiDevice spi) { /** * Read the length of the transmit buffer for a given port. This will return how * many bytes can currently be written. - * + * * @param port which of the four uart channels to read from * @return the number of free bytes in the FIFO buffer * @throws IOException if we are unable to access /dev/spix.x via Pi4J @@ -154,7 +150,7 @@ protected int getTXBufferLen(Port port) throws IOException { /** * Read the receive buffer length for a given port. This reports the number of * bytes in the receive buffer that can be currently read. - * + * * @param port which of the four uart channels to read for. * @return the number of bytes that can be read from the given FIFO buffer. * @throws IOException if we are unable to access /dev/spix.x via Pi4J @@ -179,13 +175,13 @@ protected int getRXBufferLen(Port port) throws IOException { * above 0x1F (31) are currently not supported as they are read in a different * way. * - * + * * @param command the command to write * @return -1 on failure or the value of the register * @throws IOException if we are unable to access /dev/spix.x via Pi4J */ private int readRegister(byte command) throws IOException { - byte[] data = { command, 0 }; + byte[] data = {command, 0}; byte[] readData = this.spi.write(data); if (readData.length < 2) { return -1; @@ -204,7 +200,7 @@ private int readRegister(byte command) throws IOException { * {@link #getTXBufferLen(Port)} and therefore it is possible to loose data if * too many bytes are sent.. If there are too few bytes in the * {@link #uartBufferArray} then the remaining bytes are written. - * + * * @param port Which UART channel to use * @param charCount how many bytes to write at most * @return how many bytes were actually written. @@ -230,7 +226,7 @@ protected int writeToTxFifo(Port port, int charCount) throws IOException { /** * Try to read from the RX FIFO buffer for the specified UART channel. This * method does not check if the buffer actually has enough data. - * + * * @param port which channel to read from * @param charCount how many characters to read * @return the characters as a byte stream. @@ -247,7 +243,7 @@ protected byte[] readFromRxFifo(Port port, int charCount) throws IOException { /** * Get a serial port interface compatible representation of the given port. This * can be used as any other serial port would be. - * + * * @param port which UART interface to use * @return the serial port created for the UART interface. */ @@ -257,7 +253,7 @@ public SerialPort getPort(Port port) { /** * Queue the string to be written to the specified port as soon as possible. - * + * * @param port which UART interface to write to * @param data the string to write. Will wait until previous stirngs have been * written. @@ -269,7 +265,7 @@ public void writeToPort(Port port, String data) { /** * Get the string buffer acting as a queue for the given port. - * + * * @param port which UART buffer to select. * @return the string buffer acting as a queue */ @@ -284,7 +280,7 @@ private StringBuffer selectBuffer(Port port) { * The length is cached to prevent unnecessary calls to * {@link #getTXBufferLen(Port)}. If we see that there is enough space from the * last call to {@link #getTXBufferLen(Port)} we write to it. - * + * * @param port Which port to select * @param length How many characters to write, must be >= 0 * @throws IOException if we are unable to access /dev/spix.x via Pi4J @@ -306,7 +302,7 @@ private void writeToPort(Port port, int length) throws IOException { /** * Read from the given port and call the SerilPort callbacks. Length must be * smaller or equal to the number of bytes in the RX FIFO. - * + * * @param port which port to read * @param length how many bytes to read, passed directly to * {@link #readFromRxFifo(Port, int)} @@ -325,7 +321,7 @@ private void readFromPort(Port port, int length) throws IOException { * the data.
* Then check if we have data to receive in the RX buffer. If so receive it and * emit events. - * + * * @param port which UART port to read * @throws IOException if we are unable to access /dev/spix.x via Pi4J */ @@ -349,7 +345,7 @@ public void poll() { } } catch (IOException e) { ErrorReporter errorReporter = ErrorReporter.getInstance(); - String errorMsg = "Unable to access /dev/spix.x via Pi4J"; + String errorMsg = "Unable to access /dev/spix.x via Pi4J"; errorReporter.reportError(Errors.MAX14830_IO_ERROR, e, errorMsg); } @@ -363,8 +359,8 @@ public void poll() { * {@link Settings#MAX14830_F_REF}. All math is integer math so fREF must be an * integer multiple of 16 * BaudRate or the actual baud rate will differ from the * requested. - * - * @param port the UART channel to use + * + * @param port the UART channel to use * @param baudrate the baud rate in baud * @throws IOException if we are unable to access /dev/spix.x via Pi4J */ @@ -378,7 +374,7 @@ public void setBaudRate(Port port, int baudrate) throws IOException { byte command = (byte) (uartSelect | WRITE | Registers.BRGConfig.address()); byte leastSignificantBits = (byte) (d & 0xFF); byte mostSignificantBits = (byte) ((d >> BITS_PER_BYTE) & 0xFF); - byte[] data = { command, 0, leastSignificantBits, mostSignificantBits }; + byte[] data = {command, 0, leastSignificantBits, mostSignificantBits}; this.spi.write(data); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX31856.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX31856.java index 2932cde..7f4ae58 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX31856.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/MAX31856.java @@ -1,43 +1,41 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; -import java.io.IOException; - +import com.pi4j.io.spi.SpiDevice; import org.rocketproplab.marginalstability.flightcomputer.Time; -import com.pi4j.io.spi.SpiDevice; +import java.io.IOException; /** * Implements SPI protocol for the MAX31856, contains code to read and quantify * linearized thermocouple temperature data. - * - * @author Rudy Thurston * + * @author Rudy Thurston */ public class MAX31856 implements Thermocouple, PollingSensor { - private SpiDevice spi; - private double temp; - private long sampleTime; - private Time clock; + private SpiDevice spi; + private double temp; + private long sampleTime; + private Time clock; - private static final byte REG_TC_TEMP = 0x0C; - private static final double ZERO_TIME = 0.0; + private static final byte REG_TC_TEMP = 0x0C; + private static final double ZERO_TIME = 0.0; private static final double SCALING_FACTOR = 128.0; - private static final double MINIMUM_RANGE = -200.0; - private static final double MAXIMUM_RANGE = 1372.0; - private static final double TEMP_ERROR = 2048.0; + private static final double MINIMUM_RANGE = -200.0; + private static final double MAXIMUM_RANGE = 1372.0; + private static final double TEMP_ERROR = 2048.0; /** * Create instance of MAX31856 with given SpiDevice. Time will be used to * determine the {@link #getLastMeasurementTime()} return value. - * - * @param spi SpiDevice communicating with MAX31856, no validation check - * @param time the time to use when reporting measurement time. + * + * @param spi SpiDevice communicating with MAX31856, no validation check + * @param time the time to use when reporting measurement time. */ public MAX31856(SpiDevice spi, Time time) { - this.spi = spi; - this.clock = time; - this.temp = TEMP_ERROR; + this.spi = spi; + this.clock = time; + this.temp = TEMP_ERROR; } @Override @@ -53,7 +51,7 @@ public double getLastMeasurementTime() { return ZERO_TIME; } } - + @Override public boolean inUsableRange() { if ((temp >= MINIMUM_RANGE) && (temp <= MAXIMUM_RANGE)) { @@ -78,53 +76,53 @@ public void poll() { * Read the linearized thermocouple temperature from the sensor using a * multi-byte read. Read/Write register memory map, * https://datasheets.maximintegrated.com/en/ds/MAX31856.pdf - * + *

* 0x0C (readData[1]) : | Sign | 2^10 | 2^9 | 2^8 | 2^7 | 2^6 | 2^5 | 2^4 | * 0x0D (readData[2]) : | 2^3 | 2^2 | 2^1 | 2^0 | 2^-1| 2^-2| 2^-3| 2^-4| * 0x0E (readData[3]) : | 2^-5 | 2^-6 | 2^-7| X | X | X | X | X | - * + * * @throws IOException */ private void readTemp() throws IOException { byte[] data = {REG_TC_TEMP, 0, 0, 0}; - byte[] readData = this.spi.write(data); - if (readData.length < 4) { - return; - } - - // Perform 2's complement if rawData is negative - byte sign = 0; - byte mask = (byte) 0b10000000; - if ((readData[1] & mask) != 0) { - sign = 1; - readData[1] = (byte)~readData[1]; - readData[2] = (byte)~readData[2]; - readData[3] = (byte)~readData[3]; - } - - // Store 24 bit temperature read into integer placeholder - int rawData = (Byte.toUnsignedInt(readData[1])<<16) + - (Byte.toUnsignedInt(readData[2])<<8) + - Byte.toUnsignedInt(readData[3]) + sign; - - // Returns magnitude of temperature read with correct sign - temp = tempCalc(rawData) * Math.pow(-1, sign); + byte[] readData = this.spi.write(data); + if (readData.length < 4) { + return; + } + + // Perform 2's complement if rawData is negative + byte sign = 0; + byte mask = (byte) 0b10000000; + if ((readData[1] & mask) != 0) { + sign = 1; + readData[1] = (byte) ~readData[1]; + readData[2] = (byte) ~readData[2]; + readData[3] = (byte) ~readData[3]; + } + + // Store 24 bit temperature read into integer placeholder + int rawData = (Byte.toUnsignedInt(readData[1]) << 16) + + (Byte.toUnsignedInt(readData[2]) << 8) + + Byte.toUnsignedInt(readData[3]) + sign; + + // Returns magnitude of temperature read with correct sign + temp = tempCalc(rawData) * Math.pow(-1, sign); } - + /** * Calculates magnitude of temperature from raw thermocouple read. - * + *

* data : | X | X | X | X | X | X | X | X | - * | 0 | 2^10 | 2^9 | 2^8 | 2^7 | 2^6 | 2^5 | 2^4 | - * | 2^3 | 2^2 | 2^1 | 2^0 | 2^-1| 2^-2| 2^-3| 2^-4| - * | 2^-5 | 2^-6 | 2^-7| X | X | X | X | X | - * + * | 0 | 2^10 | 2^9 | 2^8 | 2^7 | 2^6 | 2^5 | 2^4 | + * | 2^3 | 2^2 | 2^1 | 2^0 | 2^-1| 2^-2| 2^-3| 2^-4| + * | 2^-5 | 2^-6 | 2^-7| X | X | X | X | X | + * * @param data the 24 bit thermocouple read * @return Magnitude of linearized temperature */ private double tempCalc(int data) { - data = data >>> 5; - return data/SCALING_FACTOR; + data = data >>> 5; + return data / SCALING_FACTOR; } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/MagReading.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/MagReading.java index 77c80c2..821a0f1 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/MagReading.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/MagReading.java @@ -8,23 +8,22 @@ * strength of the magnetic field at the current location. * Note that the magnetic field vector from the magnetometer is in the body * frame (measured x, y, and z are relative to the orientation of the sensor). - * - * @author Enlil Odisho * + * @author Enlil Odisho */ public class MagReading { - + private Vector3 magField; - + /** * Construct a new MagReading to store the magnetic field vector. - * + * * @param magField the magnetic field vector measured from the IMU */ public MagReading(Vector3 magField) { this.magField = magField; } - + /** * @return the magnetic field vector */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Magnetometer.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Magnetometer.java index 0ea563f..e606a5c 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Magnetometer.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Magnetometer.java @@ -4,16 +4,15 @@ * An interface for a magnetometer sensor. A sensor implementing this interface * will give an iterable list of MagReadings. If hasNext returns true there will * be at least another magnetometer reading. - * - * @author max * + * @author max */ public interface Magnetometer { /** * Read the next magnetometer reading, returns null if {@link #hasNext()} * returns false. - * + * * @return the next magnetometer reading or null. */ public MagReading getNext(); @@ -21,7 +20,7 @@ public interface Magnetometer { /** * Determines if there is another reading from the magnetometer that can be * read with {@link #getNext()} - * + * * @return true if {@link #getNext()} will return a new magnetometer reading, * false otherwise. */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingGroup.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingGroup.java index adf7f18..df0c69a 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingGroup.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingGroup.java @@ -5,9 +5,8 @@ * to poll a gyroscope and magnetometer on the same chip.
*
* Each time the group is polled each sensor gets polled in series. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class PollingGroup implements PollingSensor { @@ -15,7 +14,7 @@ public class PollingGroup implements PollingSensor { /** * Create a new polling group for the given set of sensors. - * + * * @param pollingSensors the sensors to poll simultaneously */ public PollingGroup(PollingSensor... pollingSensors) { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingSensor.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingSensor.java index adeb3a7..6ef7f94 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingSensor.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/PollingSensor.java @@ -2,9 +2,8 @@ /** * A sensor that can be polled. - * - * @author Max Apodaca * + * @author Max Apodaca */ public interface PollingSensor { /** diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/RegisterValue.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/RegisterValue.java index e3a6316..3c506b5 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/RegisterValue.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/RegisterValue.java @@ -5,9 +5,8 @@ * {@link #getValueMask()} returns a bitmask of what section of the register * should be read and the {@link #getValueLSBPos()} method returns how many bits * to the left of the LSB the LSB of the value is. - * - * @author Max Apodaca * + * @author Max Apodaca */ public interface RegisterValue { @@ -16,7 +15,7 @@ public interface RegisterValue { * cover the specified value.
* For instance a register with three values aabbbccc would mean that value a * has a mask of 0b11000000; - * + * * @return the mask for this value for its register */ public int getValueMask(); @@ -28,9 +27,9 @@ public interface RegisterValue { * value b would be 3 as the LSB of b is three bits to the left of the LSB of * the register as a whole. The LSBPos of c would be 0 and the LSBPos of a would * be 6. - * + * * @return how many bits to the left of the register's LSB the LSB of the value - * is + * is */ public int getValueLSBPos(); @@ -45,9 +44,9 @@ public interface RegisterValue { * must be ordered correctly to yield a correct return value for ordinal. If the * enum has 2 members A_0 and A_1 and A_0 should have value 0 then A_0 must be * the first element in the enum. - * + * * @return the value of this value */ public int ordinal(); - + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SMSSender.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SMSSender.java index 9fdbfd4..f52c248 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SMSSender.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SMSSender.java @@ -1,5 +1,5 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; public interface SMSSender { - void sendTextMessage(String number, String message); + void sendTextMessage(String number, String message); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SamplableSensor.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SamplableSensor.java index 7d393c3..0b52cab 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SamplableSensor.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SamplableSensor.java @@ -2,16 +2,15 @@ /** * Sensor that exposes a standardized samplable interface - * - * @author Max * * @param The type that the sensor returns + * @author Max */ public interface SamplableSensor { /** * If the sensor has new data to sample - * + * * @return if the sensor has new data */ public boolean hasNewData(); @@ -19,7 +18,7 @@ public interface SamplableSensor { /** * Get the next datum from the sensor. This can either be a queue or the latest * measurement. - * + * * @return The next datum */ public E getNewData(); @@ -27,7 +26,7 @@ public interface SamplableSensor { /** * Return when the datum that was last returned by {@link #getNewData()} was * captured. - * + * * @return the capture time of the datum returned by {@link #getNewData()} */ public double getLastSampleTime(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SaraSMSSender.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SaraSMSSender.java index fe5382a..efbe218 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SaraSMSSender.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SaraSMSSender.java @@ -4,60 +4,58 @@ import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRouter; import org.rocketproplab.marginalstability.flightcomputer.comm.PacketSources; import org.rocketproplab.marginalstability.flightcomputer.events.SerialListener; -import org.rocketproplab.marginalstability.flightcomputer.hal.*; -import java.util.*; public class SaraSMSSender implements SMSSender, SerialListener { - - SerialPort saraSerialPort; - String phoneNumber; - String at; - String message; - int messageIndex; - private PacketRouter router; - GPSPacket packet; - - public SaraSMSSender(SerialPort saraSerialPort) { - this.saraSerialPort = saraSerialPort; - messageIndex = 0; - router = new PacketRouter(); //should this be set to a specific packet router? - - saraSerialPort.write("AT\n"); - saraSerialPort.write("AT+CMGF=1\n"); - } - - @Override - public void sendTextMessage(String number, String data) { - //TODO: Add in a listener that would allow us to check if the AT - //is on, if it's been switched the SMS mode, and if the message - //was sent. - if (number.length() != 11 || data.length() > 160) { - throw new IllegalArgumentException(); - } else { - saraSerialPort.write("AT+CMGS=\"+" + number + "\"\n"); - saraSerialPort.write(data + "\r\n"); - } - } - - public void getGPSInfo() { - saraSerialPort.write("AT+UGPS=1\n"); //turns the gps on. - saraSerialPort.write("AT+UGGGA?\r\n"); - } - - @Override //this re - public void onSerialData(String data) { - int index = data.indexOf(","); - String subData = data.substring(index+1); - - packet = new GPSPacket(subData); - router.recivePacket(packet, PacketSources.AUX_GPS); - //should this throw an error if null data is sent? - //or should it just be thrown to the wayside? - // - } - - //we need to figure out a way to send a message to the - //sara, but so taht it can differentiate between texting - // and not texting - + + SerialPort saraSerialPort; + String phoneNumber; + String at; + String message; + int messageIndex; + private PacketRouter router; + GPSPacket packet; + + public SaraSMSSender(SerialPort saraSerialPort) { + this.saraSerialPort = saraSerialPort; + messageIndex = 0; + router = new PacketRouter(); //should this be set to a specific packet router? + + saraSerialPort.write("AT\n"); + saraSerialPort.write("AT+CMGF=1\n"); + } + + @Override + public void sendTextMessage(String number, String data) { + //TODO: Add in a listener that would allow us to check if the AT + //is on, if it's been switched the SMS mode, and if the message + //was sent. + if (number.length() != 11 || data.length() > 160) { + throw new IllegalArgumentException(); + } else { + saraSerialPort.write("AT+CMGS=\"+" + number + "\"\n"); + saraSerialPort.write(data + "\r\n"); + } + } + + public void getGPSInfo() { + saraSerialPort.write("AT+UGPS=1\n"); //turns the gps on. + saraSerialPort.write("AT+UGGGA?\r\n"); + } + + @Override //this re + public void onSerialData(String data) { + int index = data.indexOf(","); + String subData = data.substring(index + 1); + + packet = new GPSPacket(subData); + router.recivePacket(packet, PacketSources.AUX_GPS); + //should this throw an error if null data is sent? + //or should it just be thrown to the wayside? + // + } + + //we need to figure out a way to send a message to the + //sara, but so taht it can differentiate between texting + // and not texting + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Sensor.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Sensor.java index 8e1bb43..4ba0f3e 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Sensor.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Sensor.java @@ -1,5 +1,5 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; public interface Sensor { - public void init(); + public void init(); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SensorPoller.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SensorPoller.java index 9ff9f71..684068f 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SensorPoller.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SensorPoller.java @@ -2,9 +2,8 @@ /** * A class to poll a {@link PollingSensor} at a fixed rate. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class SensorPoller { @@ -16,7 +15,7 @@ public class SensorPoller { /** * Initialize a sensor poller that will poll the given sensor every rate * seconds. - * + * * @param sensor the sensor to poll * @param rate the rate at which to poll in seconds */ @@ -29,7 +28,7 @@ public SensorPoller(PollingSensor sensor, double rate) { /** * Update the poller, if enough time has passed the sensor will be polled. - * + * * @param time the current time in seconds */ public void update(double time) { @@ -46,7 +45,7 @@ public void update(double time) { /** * Determine if we should poll the sensor at this time - * + * * @param time the current time * @return if the sensor needs to be polled */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPort.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPort.java index 56e6cf6..8a9460c 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPort.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPort.java @@ -3,17 +3,19 @@ import org.rocketproplab.marginalstability.flightcomputer.events.SerialListener; public interface SerialPort { - - /** - * Register a serial port as a listener - * @param listener the listener to register - */ - public void registerListener(SerialListener listener); - /** - * Send data over serial port - * @param data the string to send - */ - public void write(String data); + /** + * Register a serial port as a listener + * + * @param listener the listener to register + */ + public void registerListener(SerialListener listener); + + /** + * Send data over serial port + * + * @param data the string to send + */ + public void write(String data); } \ No newline at end of file diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPortAdapter.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPortAdapter.java index d9fe673..6214d82 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPortAdapter.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/SerialPortAdapter.java @@ -1,15 +1,14 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; +import org.rocketproplab.marginalstability.flightcomputer.events.SerialListener; + import java.util.HashSet; import java.util.Set; -import org.rocketproplab.marginalstability.flightcomputer.events.SerialListener; - /** * A relay for a serial port. Simply buffers a message without any processing. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class SerialPortAdapter implements SerialPort { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Solenoid.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Solenoid.java index 016ba55..03b707a 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Solenoid.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Solenoid.java @@ -2,21 +2,20 @@ /** * An on off style solenoid that can be used for a variety of purposes - * - * @author Max Apodaca * + * @author Max Apodaca */ public interface Solenoid { /** * Gets if the solenoid is currently in an active state - * + * * @return if the solenoid is active */ public boolean isActive(); /** * Sets the state of the solenoid, either active or not - * + * * @param active whether or not the solenoid is active */ public void set(boolean active); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Thermocouple.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Thermocouple.java index e257456..8f281fd 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Thermocouple.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Thermocouple.java @@ -3,21 +3,21 @@ public interface Thermocouple { /** * Get the temperature in celsius - * + * * @return the temperature in celsius */ public double getTemperature(); /** * Gets the time at which the last measurement was made - * + * * @return the time of the last measurements */ public double getLastMeasurementTime(); - + /** * Checks if temperature is within logical bounds of the sensor - * + * * @return if temperature is in usable range */ public boolean inUsableRange(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/TimeBasedSensorSampler.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/TimeBasedSensorSampler.java index 86a44af..799a109 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/TimeBasedSensorSampler.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/TimeBasedSensorSampler.java @@ -3,10 +3,9 @@ /** * Provides checks for the given samplable sensor to allow sampling every time * new data exists. - * - * @author Max * * @param The type which the sensor returns + * @author Max */ public class TimeBasedSensorSampler implements SamplableSensor { @@ -14,16 +13,15 @@ public class TimeBasedSensorSampler implements SamplableSensor { /** * A free function, see {@link #getLastMeasurementTime()} for details. - * - * @author Max * + * @author Max */ public interface LastReadTimeFunction { /** * Get the last time a sample was captured with the guarantees from * {@link SamplableSensor#getLastSampleTime()}. - * + * * @return The time the last measurement was taken. */ public double getLastMeasurementTime(); @@ -31,10 +29,9 @@ public interface LastReadTimeFunction { /** * A free function, see {@link #getNewData()} for details. - * - * @author Max * * @param The type of data returned + * @author Max */ public interface GetNewDataFunction { @@ -42,7 +39,7 @@ public interface GetNewDataFunction { * Get the new datum, this can either be a queue or the most recent one but * should be the same as the time returned in * {@link LastReadTimeFunction#getLastMeasurementTime()}. - * + * * @return The new datum */ public E getNewData(); @@ -55,7 +52,7 @@ public interface GetNewDataFunction { /** * Create a new sampler the samples the given data function - * + * * @param newDataFunction used to get the latest datum * @param lastReadTimeFunction used to get the time of the latest datum */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Valves.java b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Valves.java index a67de1a..0677042 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/hal/Valves.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/hal/Valves.java @@ -1,5 +1,5 @@ package org.rocketproplab.marginalstability.flightcomputer.hal; public interface Valves { - public void setValve(int index, boolean active) ; + public void setValve(int index, boolean active); } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/looper/GenericEvent.java b/src/org/rocketproplab/marginalstability/flightcomputer/looper/GenericEvent.java index aa9049a..d35bdc8 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/looper/GenericEvent.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/looper/GenericEvent.java @@ -15,8 +15,8 @@ public class GenericEvent implements EventCallback, EventCondition { public GenericEvent(EventCondition condition, EventCallback callback, Time time) { this.condition = condition; - this.callback = callback; - this.time = time; + this.callback = callback; + this.time = time; } @Override diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/looper/Looper.java b/src/org/rocketproplab/marginalstability/flightcomputer/looper/Looper.java index 3fa2f49..bb3ffe5 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/looper/Looper.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/looper/Looper.java @@ -21,15 +21,6 @@ * @author Chi Chow, Enlil Odisho */ public class Looper { - private static Looper mainLooper; - - public static Looper getInstance() { - if (mainLooper == null) { - mainLooper = new Looper(new Time()); - } - return mainLooper; - } - private final Time time; private final HashMap callbackMap; /** @@ -54,10 +45,10 @@ public static Looper getInstance() { * @param time the time all events in this Looper will use. */ public Looper(Time time) { - this.time = time; - callbackMap = new HashMap<>(); - active = new ArrayList<>(); - queue = new ArrayList<>(); + this.time = time; + callbackMap = new HashMap<>(); + active = new ArrayList<>(); + queue = new ArrayList<>(); busySubsystems = new HashMap<>(); } @@ -81,8 +72,8 @@ private void handleEvents(LooperErrorListener errorListener) { Iterator> entryIterator = callbackMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry entry = entryIterator.next(); - Object tag = entry.getKey(); - GenericEvent event = entry.getValue(); + Object tag = entry.getKey(); + GenericEvent event = entry.getValue(); try { if (event.shouldEmit()) { event.onLooperCallback(tag, this); @@ -112,7 +103,7 @@ private void handleCommands() { Iterator queueIterator = queue.iterator(); while (queueIterator.hasNext()) { // Get next command in queue and it's dependencies. - Command command = queueIterator.next(); + Command command = queueIterator.next(); List dependencies = Arrays.asList(command.getDependencies()); // Check if command has no dependencies that are in-use. diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/math/InterpolatingVector3.java b/src/org/rocketproplab/marginalstability/flightcomputer/math/InterpolatingVector3.java index 231474d..b4e60d9 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/math/InterpolatingVector3.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/math/InterpolatingVector3.java @@ -4,6 +4,7 @@ public interface InterpolatingVector3 { /** * Gets the interpolated vector at the given time + * * @param time the time to get the vector at * @return the best guess vector at the given time */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/math/Quaternion.java b/src/org/rocketproplab/marginalstability/flightcomputer/math/Quaternion.java index 8efaa60..7125da8 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/math/Quaternion.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/math/Quaternion.java @@ -2,9 +2,8 @@ /** * Quaternion class. - * - * @author Enlil Odisho * + * @author Enlil Odisho */ public class Quaternion { @@ -29,7 +28,7 @@ public Quaternion(double w, double x, double y, double z) { /** * Adds two quaternions together. - * + * * @param other Quaternion to add to this quaternion. * @return Result of addition. */ @@ -44,7 +43,7 @@ public Quaternion add(Quaternion other) { /** * Subtracts another quaternion from this quaternion. - * + * * @param other The quaternion to subtract. * @return Result of subtraction. */ @@ -59,22 +58,22 @@ public Quaternion subtract(Quaternion other) { /** * Multiplies this quaternion with another quaternion. - * + * * @param other Quaternion to multiply with this quaternion. * @return Result of multiplication. */ public Quaternion multiply(Quaternion other) { Quaternion result = new Quaternion(); - result.w = this.w*other.w - this.x*other.x - this.y*other.y - this.z*other.z; - result.x = this.w*other.x + this.x*other.w + this.y*other.z - this.z*other.y; - result.y = this.w*other.y - this.x*other.z + this.y*other.w + this.z*other.x; - result.z = this.w*other.z + this.x*other.y - this.y*other.x + this.z*other.w; + result.w = this.w * other.w - this.x * other.x - this.y * other.y - this.z * other.z; + result.x = this.w * other.x + this.x * other.w + this.y * other.z - this.z * other.y; + result.y = this.w * other.y - this.x * other.z + this.y * other.w + this.z * other.x; + result.z = this.w * other.z + this.x * other.y - this.y * other.x + this.z * other.w; return result; } /** * Scale this quaternion by multiplying it with a scalar. - * + * * @param scalar to multiply with quaternion. * @return Result of multiplication. */ @@ -104,15 +103,15 @@ public Quaternion conjugate() { */ public Quaternion inverse() { double magnitude = this.getMagnitude(); - return this.conjugate().multiply(1.0 / (magnitude*magnitude)); + return this.conjugate().multiply(1.0 / (magnitude * magnitude)); } /** * @return the magnitude of this quaternion */ public double getMagnitude() { - return Math.sqrt(this.w*this.w + this.x*this.x + this.y*this.y + - this.z*this.z); + return Math.sqrt(this.w * this.w + this.x * this.x + this.y * this.y + + this.z * this.z); } /** @@ -151,9 +150,9 @@ public boolean equals(Object other) { final double EQUAL_TOLERANCE = 0.00001; // TODO may need adjusting Quaternion otherQuaternion = (Quaternion) other; return (Math.abs(this.w - otherQuaternion.w) < EQUAL_TOLERANCE) && - (Math.abs(this.x - otherQuaternion.x) < EQUAL_TOLERANCE) && - (Math.abs(this.y - otherQuaternion.y) < EQUAL_TOLERANCE) && - (Math.abs(this.z - otherQuaternion.z) < EQUAL_TOLERANCE); + (Math.abs(this.x - otherQuaternion.x) < EQUAL_TOLERANCE) && + (Math.abs(this.y - otherQuaternion.y) < EQUAL_TOLERANCE) && + (Math.abs(this.z - otherQuaternion.z) < EQUAL_TOLERANCE); } @Override diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticArray.java b/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticArray.java index bc9bb10..149d355 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticArray.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticArray.java @@ -3,9 +3,8 @@ /** * Array to place statistics into that returns only statistical values. It * provides support for validators to determine if the contained data is valid. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class StatisticArray { @@ -15,7 +14,7 @@ public class StatisticArray { public interface StatisticValidator { /** * Returns if the statistic array is valid - * + * * @param array the current state of the array * @return true if the array is valid */ @@ -35,7 +34,7 @@ public StatisticArray(int maxCount) { /** * Adds a sample to the array - * + * * @param sample the sample to add * @param time the time when the sample was taken */ @@ -45,7 +44,7 @@ public void addSample(double sample, double time) { /** * Returns the mean of the previous samples. For zero samples zero is returned. - * + * * @return the mean of the previous samples */ public double getMean() { @@ -55,7 +54,7 @@ public double getMean() { /** * Returns the mean for the samples taken in the previous seconds - * + * * @param previousSeconds how many seconds to look back * @return the mean of the samples */ @@ -65,7 +64,7 @@ public double getMean(double previousSeconds) { /** * Returns the mean of the last N samples - * + * * @param lastN how many samples to look at * @return the mean of the samples, 0 if lastN is negative */ @@ -79,7 +78,7 @@ public double getMean(int lastN) { /** * implementation of the mean algorithm used by both {@link #getMean(int)} and * {@link #getMean(double)}. - * + * * @param iterator the iterator to grab the samples from * @return the mean of the samples returned by the iterator */ @@ -98,15 +97,15 @@ private double getMean(TimedRingBuffer.RingBufferIterator iterator) { /** * Returns the variance of the inserted samples. Variance is given by - * + * *

    *       Sum (x_i - x_mean)^2
    * S^2 = --------------------
    *              n - 1
    * 
- * + *

* For fewer than two samples 0 is returned. - * + * * @return the variance of the samples */ public double getVariance() { @@ -117,7 +116,7 @@ public double getVariance() { /** * Returns the variance for samples taken within the last previousSeconds. See * {@link #getVariance()} for details. - * + * * @param previousSeconds the time to look back in * @return the variance of the samples taken in the previous seconds */ @@ -130,7 +129,7 @@ public double getVariance(double previousSeconds) { /** * Returns the variance for the last n samples. See {@link #getVariance()} for * details. - * + * * @param lastN how many samples to look at * @return the variance of the previous n samples */ @@ -144,7 +143,7 @@ public double getVariance(int lastN) { /** * Inner implementation constant to all three types of variance calculation - * + * * @param mean the mean of the sample set * @param iterator the iterator to get the samples * @return the variance of the samples @@ -156,7 +155,7 @@ private double getVariance(double mean, TimedRingBuffer.RingBufferIterat sumSquared += Math.pow(sample - mean, 2); samplesCounted++; } - if(samplesCounted < 2) { + if (samplesCounted < 2) { return 0; } double variance = sumSquared / (samplesCounted - 1); @@ -165,7 +164,7 @@ private double getVariance(double mean, TimedRingBuffer.RingBufferIterat /** * Get the number of samples which are contained in this array - * + * * @return the number of samples in this array */ public int getNumberOfSamples() { @@ -174,7 +173,7 @@ public int getNumberOfSamples() { /** * Returns if the array is valid. The default validator always returns true. - * + * * @return if the array is valid */ public boolean isValid() { @@ -183,7 +182,7 @@ public boolean isValid() { /** * Sets the validator to use for data validation. Must not be null. - * + * * @param validator the new validator to use */ public void setValidator(StatisticValidator validator) { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticReporter.java b/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticReporter.java index 403d15d..0987145 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticReporter.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/math/StatisticReporter.java @@ -8,9 +8,8 @@ /** * A Class to report statistics to the telemetry subsystem. - * - * @author Max * + * @author Max */ public class StatisticReporter implements EventCallback { @@ -24,7 +23,7 @@ public class StatisticReporter implements EventCallback { /** * Create a new reporter which only reports the mean - * + * * @param sensor what sensor to report * @param telem the telemetry to log to * @param meanType the packet type to use for the mean @@ -35,19 +34,19 @@ public StatisticReporter(SamplableSensor sensor, Telemetry telem, SCMPac /** * Create a new reporter which logs both mean and variance - * + * * @param sensor what sensor to report * @param telem the telemetry to log to * @param meanType the packet type to use for the mean * @param varianceType the packet type to use for the variance */ public StatisticReporter(SamplableSensor sensor, Telemetry telem, SCMPacketType meanType, - SCMPacketType varianceType) { + SCMPacketType varianceType) { this(sensor, telem, meanType, true, varianceType); } private StatisticReporter(SamplableSensor sensor, Telemetry telem, SCMPacketType meanType, - boolean reportVariance, SCMPacketType varianceType) { + boolean reportVariance, SCMPacketType varianceType) { this.telemetry = telem; this.meanType = meanType; this.array = new StatisticArray(1); @@ -99,7 +98,7 @@ public void sample() { /** * Should we call sample, useful for looper constructions with * {@link org.rocketproplab.marginalstability.flightcomputer.looper.Looper#emitIf()} - * + * * @return if data is ready to be sampled */ public boolean shouldSample() { @@ -108,7 +107,7 @@ public boolean shouldSample() { /** * Set the maximum number of samples to store. - * + * * @param size the number of samples to store */ public void setWindowSize(int size) { @@ -118,7 +117,7 @@ public void setWindowSize(int size) { /** * Set the amount of time to look back, by default all samples up to the maximum * count are used. - * + * * @param time how far to look back in seconds */ public void setLookbackTime(double time) { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/math/TimedRingBuffer.java b/src/org/rocketproplab/marginalstability/flightcomputer/math/TimedRingBuffer.java index 3f4255e..9c27680 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/math/TimedRingBuffer.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/math/TimedRingBuffer.java @@ -7,19 +7,17 @@ /** * A ring buffer that allows you to iterate based on time - * - * @author Max Apodaca * * @param The type which the buffer is of + * @author Max Apodaca */ public class TimedRingBuffer implements Iterable { /** * An iterator for the ring buffer, will iterate section of ring buffer in * increasing add time. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class RingBufferIterator implements Iterator, Iterable { private Iterator sublistIterator; @@ -28,7 +26,7 @@ public class RingBufferIterator implements Iterator, Iterable { /** * Create a new ring buffer iterator that will iterate the first iterator then * the second - * + * * @param sublistIterator first iterator to iterate * @param nextSublistIterator next iterator to iterate */ @@ -66,7 +64,7 @@ public Iterator iterator() { /** * Create a new timed ring buffer with the given capacity - * + * * @param capacity how many elements to store at most */ public TimedRingBuffer(int capacity) { @@ -78,7 +76,7 @@ public TimedRingBuffer(int capacity) { /** * Add a new element to the buffer and specifies the time - * + * * @param value the element to add * @param time the time at which the element was added, must be greater than or * equal to the previous time @@ -96,7 +94,7 @@ public void add(E value, double time) { /** * Get how many elements are in the buffer - * + * * @return the number of elements in the buffer */ public int size() { @@ -105,7 +103,7 @@ public int size() { /** * Get an iterator for the whole buffer. Iterates in increasing time - * + * * @return an iterator for the whole buffer */ public RingBufferIterator get() { @@ -121,7 +119,7 @@ public RingBufferIterator get() { /** * Takes the mathematical definition of modulo so that -1 mod 5 = 4 - * + * * @param numerator the numerator in the modulo division * @param divisor the divisor in the modulo division * @return numerator modulo divisor @@ -138,12 +136,12 @@ private int trueMod(int numerator, int divisor) { * Get the most recent n elements from the ring buffer. If n is larger than the * number of elements all the elements are returned. The elements are iterated * in increasing order of time. - * + *

* Returns size if n > size. - * - * @throws IndexOutOfBoundsException if n < 0. + * * @param n the number of elements to get * @return an iterator for the most recent n elements + * @throws IndexOutOfBoundsException if n < 0. */ public RingBufferIterator get(int n) { if (n < 0) { @@ -169,7 +167,7 @@ public RingBufferIterator get(int n) { /** * Get an iterator for the elements within the last pastTime seconds. - * + * * @param pastTime how far in the past to look * @return an iterator for the elements added within the last pastTime seconds. */ diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/math/Vector3.java b/src/org/rocketproplab/marginalstability/flightcomputer/math/Vector3.java index 84a564a..d063d18 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/math/Vector3.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/math/Vector3.java @@ -4,9 +4,8 @@ /** * A vector class - * - * @author Max Apodaca * + * @author Max Apodaca */ public class Vector3 { @@ -54,8 +53,8 @@ public boolean equals(Object other) { } Vector3 otherVector = (Vector3) other; return (Math.abs(this.x - otherVector.x) < Settings.EQUALS_EPSILON) && - (Math.abs(this.y - otherVector.y) < Settings.EQUALS_EPSILON) && - (Math.abs(this.z - otherVector.z) < Settings.EQUALS_EPSILON); + (Math.abs(this.y - otherVector.y) < Settings.EQUALS_EPSILON) && + (Math.abs(this.z - otherVector.z) < Settings.EQUALS_EPSILON); } @Override diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/mockPi4J/DummyGpioPinImpl.java b/src/org/rocketproplab/marginalstability/flightcomputer/mockPi4J/DummyGpioPinImpl.java index 7d2b910..4140f83 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/mockPi4J/DummyGpioPinImpl.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/mockPi4J/DummyGpioPinImpl.java @@ -1,206 +1,200 @@ package org.rocketproplab.marginalstability.flightcomputer.mockPi4J; +import com.pi4j.io.gpio.*; +import com.pi4j.io.gpio.event.GpioPinListener; + import java.util.Collection; import java.util.List; import java.util.Map; -import com.pi4j.io.gpio.GpioPin; -import com.pi4j.io.gpio.GpioPinShutdown; -import com.pi4j.io.gpio.GpioProvider; -import com.pi4j.io.gpio.Pin; -import com.pi4j.io.gpio.PinMode; -import com.pi4j.io.gpio.PinPullResistance; -import com.pi4j.io.gpio.PinState; -import com.pi4j.io.gpio.event.GpioPinListener; +public class DummyGpioPinImpl implements GpioPin { + + @Override + public void addListener(GpioPinListener... arg0) { + + } + + @Override + public void addListener(List arg0) { + + } + + @Override + public void clearProperties() { + + } + + @Override + public void export(PinMode arg0) { + + } + + @Override + public void export(PinMode arg0, PinState arg1) { + + } + + public PinState getState() { + return null; + } + + @Override + public Collection getListeners() { + return null; + } + + @Override + public PinMode getMode() { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public Pin getPin() { + return null; + } + + @Override + public Map getProperties() { + return null; + } + + @Override + public String getProperty(String arg0) { + return null; + } + + @Override + public String getProperty(String arg0, String arg1) { + return null; + } + + @Override + public GpioProvider getProvider() { + return null; + } + + @Override + public PinPullResistance getPullResistance() { + return null; + } + + @Override + public GpioPinShutdown getShutdownOptions() { + return null; + } + + @Override + public Object getTag() { + return null; + } + + @Override + public boolean hasListener(GpioPinListener... arg0) { + return false; + } + + @Override + public boolean hasProperty(String arg0) { + return false; + } + + @Override + public boolean isExported() { + return false; + } + + @Override + public boolean isMode(PinMode arg0) { + return false; + } + + @Override + public boolean isPullResistance(PinPullResistance arg0) { + return false; + } + + @Override + public void removeAllListeners() { + + } + + @Override + public void removeListener(GpioPinListener... arg0) { + + } + + @Override + public void removeListener(List arg0) { + + } + + @Override + public void removeProperty(String arg0) { + + } + + @Override + public void setMode(PinMode arg0) { + + } + + @Override + public void setName(String arg0) { + + } + + @Override + public void setProperty(String arg0, String arg1) { + + } + + @Override + public void setPullResistance(PinPullResistance arg0) { + + } + + @Override + public void setShutdownOptions(GpioPinShutdown arg0) { + + } + + @Override + public void setShutdownOptions(Boolean arg0) { + + } + + @Override + public void setShutdownOptions(Boolean arg0, PinState arg1) { + + } + + @Override + public void setShutdownOptions(Boolean arg0, PinState arg1, PinPullResistance arg2) { + + } + + @Override + public void setShutdownOptions(Boolean arg0, PinState arg1, PinPullResistance arg2, PinMode arg3) { + + } + + @Override + public void setTag(Object arg0) { + + } + + @Override + public void unexport() { + + } + + public void setState(PinState solenoidState) { -public class DummyGpioPinImpl implements GpioPin{ - - @Override - public void addListener(GpioPinListener... arg0) { - - } - - @Override - public void addListener(List arg0) { - - } - - @Override - public void clearProperties() { - - } - - @Override - public void export(PinMode arg0) { - - } - - @Override - public void export(PinMode arg0, PinState arg1) { - - } - - public PinState getState() { - return null; - } - - @Override - public Collection getListeners() { - return null; - } - - @Override - public PinMode getMode() { - return null; - } - - @Override - public String getName() { - return null; - } - - @Override - public Pin getPin() { - return null; - } - - @Override - public Map getProperties() { - return null; - } - - @Override - public String getProperty(String arg0) { - return null; - } - - @Override - public String getProperty(String arg0, String arg1) { - return null; - } - - @Override - public GpioProvider getProvider() { - return null; - } - - @Override - public PinPullResistance getPullResistance() { - return null; - } - - @Override - public GpioPinShutdown getShutdownOptions() { - return null; - } - - @Override - public Object getTag() { - return null; - } - - @Override - public boolean hasListener(GpioPinListener... arg0) { - return false; - } - - @Override - public boolean hasProperty(String arg0) { - return false; - } - - @Override - public boolean isExported() { - return false; - } - - @Override - public boolean isMode(PinMode arg0) { - return false; - } - - @Override - public boolean isPullResistance(PinPullResistance arg0) { - return false; - } - - @Override - public void removeAllListeners() { - - } - - @Override - public void removeListener(GpioPinListener... arg0) { - - } - - @Override - public void removeListener(List arg0) { - - } - - @Override - public void removeProperty(String arg0) { - - } - - @Override - public void setMode(PinMode arg0) { - - } - - @Override - public void setName(String arg0) { - - } - - @Override - public void setProperty(String arg0, String arg1) { - - } - - @Override - public void setPullResistance(PinPullResistance arg0) { - - } - - @Override - public void setShutdownOptions(GpioPinShutdown arg0) { - - } - - @Override - public void setShutdownOptions(Boolean arg0) { - - } - - @Override - public void setShutdownOptions(Boolean arg0, PinState arg1) { - - } - - @Override - public void setShutdownOptions(Boolean arg0, PinState arg1, PinPullResistance arg2) { - - } - - @Override - public void setShutdownOptions(Boolean arg0, PinState arg1, PinPullResistance arg2, PinMode arg3) { - - } - - @Override - public void setTag(Object arg0) { - - } - - @Override - public void unexport() { - - } - - public void setState(PinState solenoidState) { - - } + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/EngineSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/EngineSubsystem.java index 6b68314..71171e0 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/EngineSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/EngineSubsystem.java @@ -1,50 +1,51 @@ package org.rocketproplab.marginalstability.flightcomputer.subsystems; -import java.util.HashSet; -import java.util.Set; - import org.rocketproplab.marginalstability.flightcomputer.Settings; import org.rocketproplab.marginalstability.flightcomputer.events.EngineEventListener; import org.rocketproplab.marginalstability.flightcomputer.hal.Valves; +import java.util.HashSet; +import java.util.Set; + public class EngineSubsystem { - private Valves valves; - private Set listeners; - - EngineSubsystem(Valves valves){ - this.valves = valves; - this.listeners = new HashSet<>(); - } - public void activateEngine() { - this.setValveBasedOnSettings(Settings.ENGINE_ON_VALVE_STATES); - this.notifyEngineActivation(); - } - - public void deactivateEngine() { - this.setValveBasedOnSettings(Settings.ENGINE_ABORT_VALVE_STATES); - this.notifyEngineDeactivation(); - } - - private void setValveBasedOnSettings(boolean[] EngineValveStates) { - for (int index = 0; index < EngineValveStates.length; index++) { - valves.setValve(index, EngineValveStates[index]); - } - } - - private void notifyEngineActivation() { - for(EngineEventListener listener : this.listeners) { - listener.onEngineActivation(); - } - } - - private void notifyEngineDeactivation() { - for(EngineEventListener listener : this.listeners) { - listener.onEngineShutdown(); - } - } - - public void registerEngineListener(EngineEventListener listener) { - this.listeners.add(listener); - } - + private Valves valves; + private Set listeners; + + EngineSubsystem(Valves valves) { + this.valves = valves; + this.listeners = new HashSet<>(); + } + + public void activateEngine() { + this.setValveBasedOnSettings(Settings.ENGINE_ON_VALVE_STATES); + this.notifyEngineActivation(); + } + + public void deactivateEngine() { + this.setValveBasedOnSettings(Settings.ENGINE_ABORT_VALVE_STATES); + this.notifyEngineDeactivation(); + } + + private void setValveBasedOnSettings(boolean[] EngineValveStates) { + for (int index = 0; index < EngineValveStates.length; index++) { + valves.setValve(index, EngineValveStates[index]); + } + } + + private void notifyEngineActivation() { + for (EngineEventListener listener : this.listeners) { + listener.onEngineActivation(); + } + } + + private void notifyEngineDeactivation() { + for (EngineEventListener listener : this.listeners) { + listener.onEngineShutdown(); + } + } + + public void registerEngineListener(EngineEventListener listener) { + this.listeners.add(listener); + } + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/GPSMessageSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/GPSMessageSubsystem.java index 764adfd..3c98150 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/GPSMessageSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/GPSMessageSubsystem.java @@ -4,48 +4,47 @@ import org.rocketproplab.marginalstability.flightcomputer.comm.GPSPacket; import org.rocketproplab.marginalstability.flightcomputer.comm.PacketDirection; import org.rocketproplab.marginalstability.flightcomputer.events.PacketListener; -import org.rocketproplab.marginalstability.flightcomputer.tracking.FlightMode; import org.rocketproplab.marginalstability.flightcomputer.tracking.FlightState; public class GPSMessageSubsystem implements PacketListener { - - String message; - double lastTime; - double thisTime; - GPSPacket packet; - FlightState currentState; - - private static final double TIME_BETWEEN = 0; - - public GPSMessageSubsystem() { - lastTime = 0; - thisTime = 0; - currentState = new FlightState(); - } - - public String createMessage() { - double latitude = this.packet.getLatitude(); - double longitude = this.packet.getLongitude(); - - message = "The longitude is: " + longitude + "\nThe latitude" - + " is: " + latitude; - - return message; - // how do we get message into string(data) if the phone number - //is passed in the method call and we don't necessarily have - //the phone number yet? - } - - @Override - public void onPacket(PacketDirection direction, Object packet) { - if (direction == PacketDirection.RECIVE) { - //should include, but i can't test with that in - //&& currentState.getFlightMode() == FlightMode.Landed - thisTime = (new Time()).getSystemTime(); - if (thisTime - lastTime > TIME_BETWEEN) { - this.packet = (GPSPacket)packet; - } - } - } + + String message; + double lastTime; + double thisTime; + GPSPacket packet; + FlightState currentState; + + private static final double TIME_BETWEEN = 0; + + public GPSMessageSubsystem() { + lastTime = 0; + thisTime = 0; + currentState = new FlightState(); + } + + public String createMessage() { + double latitude = this.packet.getLatitude(); + double longitude = this.packet.getLongitude(); + + message = "The longitude is: " + longitude + "\nThe latitude" + + " is: " + latitude; + + return message; + // how do we get message into string(data) if the phone number + //is passed in the method call and we don't necessarily have + //the phone number yet? + } + + @Override + public void onPacket(PacketDirection direction, Object packet) { + if (direction == PacketDirection.RECIVE) { + //should include, but i can't test with that in + //&& currentState.getFlightMode() == FlightMode.Landed + thisTime = (new Time()).getSystemTime(); + if (thisTime - lastTime > TIME_BETWEEN) { + this.packet = (GPSPacket) packet; + } + } + } } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/PTSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/PTSubsystem.java index da89f76..b1f67ab 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/PTSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/PTSubsystem.java @@ -9,19 +9,6 @@ * @author Clara Chun, Chi Chow */ public class PTSubsystem { - private static PTSubsystem instance; - - /** - * Singleton instance of PTSubsystem - * - * @return a PTSubsystem instance - */ - public static PTSubsystem getInstance() { - if (instance == null) { - instance = new PTSubsystem(null); - } - return instance; - } private AnalogDigitalConverter adc; diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ParachuteSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ParachuteSubsystem.java index 7d88688..9114e36 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ParachuteSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ParachuteSubsystem.java @@ -23,15 +23,7 @@ public class ParachuteSubsystem implements FlightStateListener, PositionListener, Subsystem { - private static final String MAIN_CHUTE_TAG = "MainChute"; - private static ParachuteSubsystem instance; - - public static ParachuteSubsystem getInstance() { - if (instance == null) { - instance = new ParachuteSubsystem(null, null, null, null); - } - return instance; - } + private static final String MAIN_CHUTE_TAG = "MainChute"; private Solenoid mainChute; private Solenoid drogueChute; @@ -81,8 +73,8 @@ private boolean shouldDrogueChuteOpenByFlightMode(FlightMode flightMode) { private boolean shouldMainChuteOpenByPressure() { Vector3 currentPos = this.position.getAt(time.getSystemTime()); - boolean b1 = currentPos.getZ() < Settings.MAIN_CHUTE_HEIGHT; - boolean b2 = barometer.getPressure() < Settings.MAIN_CHUTE_PRESSURE; + boolean b1 = currentPos.getZ() < Settings.MAIN_CHUTE_HEIGHT; + boolean b2 = barometer.getPressure() < Settings.MAIN_CHUTE_PRESSURE; return b1 && b2; // return currentPos.getZ() < Settings.MAIN_CHUTE_HEIGHT && // barometer.getPressure() >= Settings.MAIN_CHUTE_PRESSURE; @@ -128,12 +120,12 @@ private void mainChuteOpen() { /** * Attempt to open the main chute * - * @return if the deployment was successful + * @return if the deployment was successful */ public boolean attemptMainChuteOpen() { /* TODO: Find a better way to check if the drogue chute is currently open, and if the main chute deployed successfully */ - if(drogueChute.isActive()) + if (drogueChute.isActive()) mainChuteOpen(); else { return false; @@ -145,7 +137,7 @@ public boolean attemptMainChuteOpen() { /** * Attempt to open the drogue chute * - * @return if the deployment was successful + * @return if the deployment was successful */ public boolean attemptDrogueChuteOpen() { drogueChuteOpen(); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SCMCommandSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SCMCommandSubsystem.java index 846d9b8..efc4f84 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SCMCommandSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SCMCommandSubsystem.java @@ -19,14 +19,6 @@ */ public class SCMCommandSubsystem implements Subsystem, PacketListener, FramedPacketProcessor { - private static SCMCommandSubsystem instance; - - public static SCMCommandSubsystem getInstance() { - if (instance == null) { - instance = new SCMCommandSubsystem(); - } - return instance; - } private Looper looper; @@ -44,7 +36,7 @@ public static SCMCommandSubsystem getInstance() { * Creates a new SCMCommandSubsystem */ public SCMCommandSubsystem() { - SCMMap = new HashMap<>(); + SCMMap = new HashMap<>(); framedSCMMap = new HashMap<>(); } @@ -96,7 +88,7 @@ public void onPacket(PacketDirection direction, SCMPacket packet) { */ @Override public void processFramedPacket(String framedPacket) { - String data = extractFramedSCMData(framedPacket); + String data = extractFramedSCMData(framedPacket); FramedSCMCommandFactory factory = framedSCMMap.get(data); if (factory != null) { Command commandToSchedule = factory.getCommandByFramedSCM(data); diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SensorSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SensorSubsystem.java index cc59392..a912bde 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SensorSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/SensorSubsystem.java @@ -1,19 +1,18 @@ package org.rocketproplab.marginalstability.flightcomputer.subsystems; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import org.rocketproplab.marginalstability.flightcomputer.Time; import org.rocketproplab.marginalstability.flightcomputer.hal.PollingSensor; import org.rocketproplab.marginalstability.flightcomputer.hal.SensorPoller; import org.rocketproplab.marginalstability.flightcomputer.looper.Looper; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + /** * A subsystem to handle ticking the sensors at a fixed rate. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class SensorSubsystem implements Subsystem { private List sensorPollers; diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/StatsSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/StatsSubsystem.java index cfb60ac..d346d3a 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/StatsSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/StatsSubsystem.java @@ -1,21 +1,20 @@ package org.rocketproplab.marginalstability.flightcomputer.subsystems; -import java.util.ArrayList; -import java.util.List; - import org.rocketproplab.marginalstability.flightcomputer.looper.Looper; import org.rocketproplab.marginalstability.flightcomputer.math.StatisticReporter; +import java.util.ArrayList; +import java.util.List; + /** * Subsystem that contains all of the sensors that are only used to provide * statistics, also listens for events to provide statistics. - * + *

* Contains all the Thermocouple Sensors, the Barometer, and the Pressure * Transducer Subsystem. Listens for parachute deployment, state change, and * navigation updates. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class StatsSubsystem implements Subsystem { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Subsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Subsystem.java index 2ba749b..b40a1b3 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Subsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Subsystem.java @@ -4,9 +4,8 @@ /** * The basic super class of a subsystem. - * - * @author Max Apodaca, Chi Chow * + * @author Max Apodaca, Chi Chow */ public interface Subsystem { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Telemetry.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Telemetry.java index 2e56304..8f85396 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Telemetry.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/Telemetry.java @@ -1,33 +1,22 @@ package org.rocketproplab.marginalstability.flightcomputer.subsystems; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.rocketproplab.marginalstability.flightcomputer.Errors; import org.rocketproplab.marginalstability.flightcomputer.Info; import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRelay; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRouter; import org.rocketproplab.marginalstability.flightcomputer.comm.PacketSources; import org.rocketproplab.marginalstability.flightcomputer.comm.SCMPacket; import org.rocketproplab.marginalstability.flightcomputer.comm.SCMPacketType; +import java.util.logging.Level; +import java.util.logging.Logger; + /** * A reporter for telemetry. It will sends the packet periodically to the * Command Box with the information given. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class Telemetry { - private static Telemetry instance; - - public static Telemetry getInstance() { - if (instance == null) { - instance = new Telemetry(Logger.getLogger("Telemetry"), PacketRouter.getInstance()); - } - return instance; - } - public static final int BASE_10 = 10; public static final int BASE_16 = 16; public static final int MAX_PACKET_BASE_10 = (int) Math.round(Math.pow(BASE_10, SCMPacket.DATA_LENGTH)) - 1; @@ -36,8 +25,8 @@ public static Telemetry getInstance() { public static final int MIN_PACKET_BASE_10 = (int) -Math.round(Math.pow(BASE_10, SCMPacket.DATA_LENGTH - 1)) + 1; public static final int MIN_PACKET_BASE_16 = (int) -Math.round(Math.pow(BASE_16, SCMPacket.DATA_LENGTH - 1)) + 1; - public static final String INFINITY = "INF "; - public static final String NEG_INFINITY = "-INF "; + public static final String INFINITY = "INF "; + public static final String NEG_INFINITY = "-INF "; private static final String INT_FORMAT = "%0" + SCMPacket.DATA_LENGTH + "d"; private static final String HEX_FORMAT = "%0" + SCMPacket.DATA_LENGTH + "x"; private static final String DOUBLE_FORMAT = "%0" + SCMPacket.DATA_LENGTH + "f"; @@ -48,7 +37,7 @@ public static Telemetry getInstance() { /** * Creates a new telemetry subsystem that logs to the given logger and uses the * given packet reply to send its packets. - * + * * @param logger the logger to use for info output * @param relay the relay to use for sending packets */ @@ -59,7 +48,7 @@ public Telemetry(Logger logger, PacketRelay relay) { /** * Reports a double to the command box - * + * * @param type the packet type to send with the double * @param data the double to send */ @@ -85,7 +74,7 @@ public void reportTelemetry(SCMPacketType type, double data) { /** * Reports an integer to the command box in base 16 to allow for greater data to * be set. - * + * * @param type the data type to send * @param data the data to send, must fit in 5 characters */ @@ -97,7 +86,7 @@ public void reportTelemetryHex(SCMPacketType type, int data) { /** * Reports an integer to the command box. If greater than max then infinity is * sent. - * + * * @param type the type of data to send * @param data the data to be sent, must fit in 5 character */ @@ -108,7 +97,7 @@ public void reportTelemetry(SCMPacketType type, int data) { /** * Internally report the integer value using the given constraints - * + * * @param type the type of packet to send * @param data the integer to be sent * @param format the format string to print this integer @@ -128,7 +117,7 @@ private void reportTelemetry(SCMPacketType type, int data, String format, int ma /** * Send the error to the Command Box - * + * * @param error the error to inform the command box of */ public void reportError(Errors error) { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ValveStateSubsystem.java b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ValveStateSubsystem.java index b258780..0c5bbb8 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ValveStateSubsystem.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/subsystems/ValveStateSubsystem.java @@ -1,109 +1,96 @@ package org.rocketproplab.marginalstability.flightcomputer.subsystems; -import org.rocketproplab.marginalstability.flightcomputer.Settings; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketDirection; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRelay; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketRouter; -import org.rocketproplab.marginalstability.flightcomputer.comm.PacketSources; -import org.rocketproplab.marginalstability.flightcomputer.comm.SCMPacket; -import org.rocketproplab.marginalstability.flightcomputer.comm.SCMPacketType; +import org.rocketproplab.marginalstability.flightcomputer.comm.*; import org.rocketproplab.marginalstability.flightcomputer.events.PacketListener; /* - * * - * - * + * + * + * * @author Clara Chun * */ public class ValveStateSubsystem implements PacketListener { - private static ValveStateSubsystem instance; - public static ValveStateSubsystem getInstance() { - if(instance == null) { - instance = new ValveStateSubsystem(PacketRouter.getInstance()); + + private SCMPacket packet; + private int[] valveStates = {-1, -1, -1, -1, -1, -1, -1, -1}; + private String data; + private SCMPacketType id; + private PacketRelay relay; + + public ValveStateSubsystem(PacketRelay relay) { + this.relay = relay; + } + + public void onPacket(PacketDirection direction, SCMPacket packet) { + this.packet = packet; + this.data = packet.getData(); + this.id = packet.getID(); + setStates(); + } + + private void setStates() { + int trackArray = 0; //the value we're starting at on the valveStates array + int maxNum = 5; //what number to end at on the array + int trackString = 0; //what position on the data string we're at. + if (id == SCMPacketType.V1) { + trackArray = 5; + maxNum = 8; + } + + while (trackArray < maxNum) { + if (data.substring(trackString, trackString + 1).equals("0")) { + valveStates[trackArray] = 0; + } else if (data.substring(trackString, trackString + 1).equals("1")) { + valveStates[trackArray] = 1; + } else { + //TODO: report as error if occurs + valveStates[trackArray] = -1; + } + trackString++; + trackArray++; } - return instance; + sendPacket(id); + } + + public void setValve(int valve, int state) { + valveStates[valve - 1] = state; + sendPacket(valve); } - - private SCMPacket packet; - private int[] valveStates = {-1, -1, -1, -1, -1, -1, -1, -1}; - private String data; - private SCMPacketType id; - private PacketRelay relay; - - public ValveStateSubsystem(PacketRelay relay) { - this.relay = relay; - } - - public void onPacket(PacketDirection direction, SCMPacket packet) { - this.packet = packet; - this.data = packet.getData(); - this.id = packet.getID(); - setStates(); - } - - private void setStates() { - int trackArray = 0; //the value we're starting at on the valveStates array - int maxNum = 5; //what number to end at on the array - int trackString = 0; //what position on the data string we're at. - if (id == SCMPacketType.V1) { - trackArray = 5; - maxNum = 8; - } - - while (trackArray < maxNum) { - if (data.substring(trackString, trackString + 1).equals("0")) { - valveStates[trackArray] = 0; - } else if (data.substring(trackString, trackString + 1).equals("1")) { - valveStates[trackArray] = 1; - } else { - //TODO: report as error if occurs - valveStates[trackArray] = -1; - } - trackString++; - trackArray++; - } - sendPacket(id); - } - - public void setValve(int valve, int state) { - valveStates[valve - 1] = state; - sendPacket(valve); - } - - private void sendPacket(int valve) { - if (valve < 5) { - sendPacket(SCMPacketType.V0); - } else { - sendPacket(SCMPacketType.V1); - } - } - - private void sendPacket(SCMPacketType type) { - SCMPacketType id = type; - String data = ""; - SCMPacket packet; - - int endValue = 5; //value on the valveStates array to stop at when creating a data string - int beginValue = 0; // value on the valveStates array to begin at when creating a data string - if (id == SCMPacketType.V1) { - endValue = 8; - beginValue = 5; - } - for (; beginValue < endValue; beginValue++) { - if (valveStates[beginValue] == -1) { - return; - } - data += "" + valveStates[beginValue]; - } - if (id == SCMPacketType.V1) { - data += "00"; - } - - packet = new SCMPacket(id, data); - this.relay.sendPacket(packet, PacketSources.EngineControllerUnit); - } - - + + private void sendPacket(int valve) { + if (valve < 5) { + sendPacket(SCMPacketType.V0); + } else { + sendPacket(SCMPacketType.V1); + } + } + + private void sendPacket(SCMPacketType type) { + SCMPacketType id = type; + String data = ""; + SCMPacket packet; + + int endValue = 5; //value on the valveStates array to stop at when creating a data string + int beginValue = 0; // value on the valveStates array to begin at when creating a data string + if (id == SCMPacketType.V1) { + endValue = 8; + beginValue = 5; + } + for (; beginValue < endValue; beginValue++) { + if (valveStates[beginValue] == -1) { + return; + } + data += "" + valveStates[beginValue]; + } + if (id == SCMPacketType.V1) { + data += "00"; + } + + packet = new SCMPacket(id, data); + this.relay.sendPacket(packet, PacketSources.EngineControllerUnit); + } + + } diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightMode.java b/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightMode.java index 0971de4..3a13d3b 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightMode.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightMode.java @@ -2,9 +2,8 @@ /** * The different states which the rocket can be in while flying - * - * @author Max Apodaca * + * @author Max Apodaca */ public enum FlightMode { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightState.java b/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightState.java index 90f21fb..0c5ad45 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightState.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/tracking/FlightState.java @@ -8,23 +8,22 @@ /** * A class that keeps track of the flight state of the rocket. - * + *

* It looks at different characteristics to determine which flight mode we are * in. - * + *

* We look at the engine activation and shutdown to determine if we are burning * or coasting. - * + *

* We look at the velocity updates to determine if we are in apogee, falling or * landed. - * + *

* We look at the parachute deploying to determine if we are in descending. - * - * @author Max Apodaca * + * @author Max Apodaca */ public class FlightState - implements EngineEventListener, VelocityListener, ParachuteListener { + implements EngineEventListener, VelocityListener, ParachuteListener { private FlightMode currentFlightMode; @@ -37,7 +36,7 @@ public FlightState() { /** * Get the current flight mode which the rocket is in. - * + * * @return the current flight mode */ public FlightMode getFlightMode() { @@ -63,7 +62,7 @@ public void onVelocityUpdate(Vector3 velocity, double time) { /** * Checks if the rocket should transition into the apogee state - * + * * @param velocity the current velocity */ private void checkForApogee(Vector3 velocity) { @@ -78,7 +77,7 @@ private void checkForApogee(Vector3 velocity) { /** * Checks if the rocket should transition from apogee to falling - * + * * @param velocity the current velocity */ private void checkForFalling(Vector3 velocity) { @@ -95,7 +94,7 @@ private void checkForFalling(Vector3 velocity) { /** * Checks if the rocket should transition into the landed state - * + * * @param velocity the current velocity */ private void checkForLanded(Vector3 velocity) { diff --git a/src/org/rocketproplab/marginalstability/flightcomputer/tracking/VelocityCalculator.java b/src/org/rocketproplab/marginalstability/flightcomputer/tracking/VelocityCalculator.java index 4085cf7..c8042f3 100644 --- a/src/org/rocketproplab/marginalstability/flightcomputer/tracking/VelocityCalculator.java +++ b/src/org/rocketproplab/marginalstability/flightcomputer/tracking/VelocityCalculator.java @@ -13,16 +13,16 @@ public void onVelocityUpdate(Vector3 velocity, double time) { } public static Vector3 getVelocity(GPSPacket prevGPSPacket, - GPSPacket curGPSPacket) { - double deltaLat = curGPSPacket.getLatitude() - prevGPSPacket.getLatitude(); - double deltaLon = curGPSPacket.getLongitude() - prevGPSPacket.getLongitude(); - double deltaTime = curGPSPacket.getTime() - prevGPSPacket.getTime(); + GPSPacket curGPSPacket) { + double deltaLat = curGPSPacket.getLatitude() - prevGPSPacket.getLatitude(); + double deltaLon = curGPSPacket.getLongitude() - prevGPSPacket.getLongitude(); + double deltaTime = curGPSPacket.getTime() - prevGPSPacket.getTime(); double angVelocityX = deltaLon / deltaTime; double angVelocityY = deltaLat / deltaTime; - int radiusEarth = 6378100; - double velocityX = angVelocityX * radiusEarth; - double velocityY = angVelocityY * radiusEarth; - double velocityZ = curGPSPacket.getAltitude() - prevGPSPacket.getAltitude(); + int radiusEarth = 6378100; + double velocityX = angVelocityX * radiusEarth; + double velocityY = angVelocityY * radiusEarth; + double velocityZ = curGPSPacket.getAltitude() - prevGPSPacket.getAltitude(); return new Vector3(velocityX, velocityY, velocityZ); } diff --git a/test/org/rocketproplab/marginalstability/flightcomputer/FlightComputerTest.java b/test/org/rocketproplab/marginalstability/flightcomputer/FlightComputerTest.java index 3978fdb..1a00b24 100644 --- a/test/org/rocketproplab/marginalstability/flightcomputer/FlightComputerTest.java +++ b/test/org/rocketproplab/marginalstability/flightcomputer/FlightComputerTest.java @@ -1,110 +1,171 @@ package org.rocketproplab.marginalstability.flightcomputer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import java.lang.reflect.Field; +import java.security.Permission; import java.util.ArrayList; import java.util.logging.Logger; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.rocketproplab.marginalstability.flightcomputer.looper.Looper; import org.rocketproplab.marginalstability.flightcomputer.subsystems.Subsystem; import org.rocketproplab.marginalstability.flightcomputer.subsystems.Telemetry; +import static org.junit.Assert.*; + public class FlightComputerTest { - private Telemetry telemetry; - private ArrayList errorList; - private boolean throwErrorOnError; - - private class MockSubsystem implements Subsystem { - public boolean hasUpdateCalled = false; - public boolean throwError = false; - - @Override - public void prepare(Looper looper) { - looper.emitAlways(this, (tag, from) -> { - this.hasUpdateCalled = true; - if (this.throwError) { - throw new RuntimeException(); + private Telemetry telemetry; + private ArrayList errorList; + private boolean throwErrorOnError; + private SecurityManager securityManager; // to test if System exits + + private class MockSubsystem implements Subsystem { + public boolean hasUpdateCalled = false; + public boolean throwError = false; + + @Override + public void prepare(Looper looper) { + looper.emitAlways(this, (tag, from) -> { + this.hasUpdateCalled = true; + if (this.throwError) { + throw new RuntimeException(); + } + }); } - }); } - } - - - @Before - public void beforeEach() { - this.throwErrorOnError = false; - errorList = new ArrayList<>(); - this.telemetry = new Telemetry(Logger.getLogger("Dummy"), null) { - @Override - public void reportError(Errors error) { - errorList.add(error); - if (throwErrorOnError) { - throw new RuntimeException(); - } - } - }; - } - - @Test - public void flightComputerCallsSubsystemUpdateOnTick() { - FlightComputer flightComputer = new FlightComputer(this.telemetry, null); - MockSubsystem mockSubsystem = new MockSubsystem(); - flightComputer.registerSubsystem(mockSubsystem); - flightComputer.tick(); - assertTrue(mockSubsystem.hasUpdateCalled); - } - - @Test - public void flightComputerRecoversFromException() { - FlightComputer flightComputer = new FlightComputer(this.telemetry, null); - MockSubsystem mockSubsystem = new MockSubsystem(); - mockSubsystem.throwError = true; - flightComputer.registerSubsystem(mockSubsystem); - flightComputer.tick(); - mockSubsystem.hasUpdateCalled = false; - mockSubsystem.throwError = false; - flightComputer.tick(); - assertTrue(mockSubsystem.hasUpdateCalled); - } - - @Test - public void flightComputerReportsErrorToTelemetry() { - FlightComputer flightComputer = new FlightComputer(this.telemetry, null); - MockSubsystem mockSubsystem = new MockSubsystem(); - mockSubsystem.throwError = true; - flightComputer.registerSubsystem(mockSubsystem); - flightComputer.tick(); - assertEquals(1, this.errorList.size()); - assertEquals(Errors.TOP_LEVEL_EXCEPTION, this.errorList.get(0)); - } - - @Test - public void errorInReportErrorAllowContinuedExecution() { - FlightComputer flightComputer = new FlightComputer(this.telemetry, null); - MockSubsystem mockSubsystem = new MockSubsystem(); - mockSubsystem.throwError = true; - this.throwErrorOnError = true; - flightComputer.registerSubsystem(mockSubsystem); - flightComputer.tick(); - mockSubsystem.hasUpdateCalled = false; - mockSubsystem.throwError = false; - flightComputer.tick(); - assertTrue(mockSubsystem.hasUpdateCalled); - } - - @Test - public void errorAllowContinuedExecutionInSameTick() { - FlightComputer flightComputer = new FlightComputer(this.telemetry, null); - MockSubsystem mockSubsystem1 = new MockSubsystem(); - mockSubsystem1.throwError = true; - flightComputer.registerSubsystem(mockSubsystem1); - MockSubsystem mockSubsystem2 = new MockSubsystem(); - mockSubsystem2.throwError = false; - flightComputer.registerSubsystem(mockSubsystem2); - flightComputer.tick(); - assertTrue(mockSubsystem2.hasUpdateCalled); - } + + + @Before + public void beforeEach() { + this.throwErrorOnError = false; + errorList = new ArrayList<>(); + this.telemetry = new Telemetry(Logger.getLogger("Dummy"), null) { + @Override + public void reportError(Errors error) { + errorList.add(error); + if (throwErrorOnError) { + throw new RuntimeException(); + } + } + }; + } + + @After + public void resetSingletonFields() throws Exception { + // use reflection to reset singleton fields + Field fcInstance = FlightComputer.class.getDeclaredField("instance"); + fcInstance.setAccessible(true); + fcInstance.set(null, null); + Field sensorInstance = SensorProvider.class.getDeclaredField("instance"); + sensorInstance.setAccessible(true); + sensorInstance.set(null, null); + } + + @Before + public void customSecurityManager() { + securityManager = System.getSecurityManager(); + System.setSecurityManager(new SecurityManager() { + @Override + public void checkExit(int status) { + super.checkExit(status); + throw new SecurityException("Overriding shutdown..."); + } + + @Override + public void checkPermission(Permission perm) { + // do nothing + } + }); + } + + @After + public void resetSecurityManager() { + System.setSecurityManager(securityManager); + } + + @Test + public void flightComputerCallsSubsystemUpdateOnTick() { + FlightComputer flightComputer = new FlightComputer.Builder() + .withTelemetry(telemetry) + .build(); + MockSubsystem mockSubsystem = new MockSubsystem(); + flightComputer.registerSubsystem(mockSubsystem); + flightComputer.tick(); + assertTrue(mockSubsystem.hasUpdateCalled); + } + + @Test + public void flightComputerRecoversFromException() { + FlightComputer flightComputer = new FlightComputer.Builder() + .withTelemetry(telemetry) + .build(); + MockSubsystem mockSubsystem = new MockSubsystem(); + mockSubsystem.throwError = true; + flightComputer.registerSubsystem(mockSubsystem); + flightComputer.tick(); + mockSubsystem.hasUpdateCalled = false; + mockSubsystem.throwError = false; + flightComputer.tick(); + assertTrue(mockSubsystem.hasUpdateCalled); + } + + @Test + public void flightComputerReportsErrorToTelemetry() { + FlightComputer flightComputer = new FlightComputer.Builder() + .withTelemetry(telemetry) + .build(); + MockSubsystem mockSubsystem = new MockSubsystem(); + mockSubsystem.throwError = true; + flightComputer.registerSubsystem(mockSubsystem); + flightComputer.tick(); + assertEquals(1, this.errorList.size()); + assertEquals(Errors.TOP_LEVEL_EXCEPTION, this.errorList.get(0)); + } + + @Test + public void errorInReportErrorAllowContinuedExecution() { + FlightComputer flightComputer = new FlightComputer.Builder() + .withTelemetry(telemetry) + .build(); + MockSubsystem mockSubsystem = new MockSubsystem(); + mockSubsystem.throwError = true; + this.throwErrorOnError = true; + flightComputer.registerSubsystem(mockSubsystem); + flightComputer.tick(); + mockSubsystem.hasUpdateCalled = false; + mockSubsystem.throwError = false; + flightComputer.tick(); + assertTrue(mockSubsystem.hasUpdateCalled); + } + + @Test + public void errorAllowContinuedExecutionInSameTick() { + FlightComputer flightComputer = new FlightComputer.Builder() + .withTelemetry(telemetry) + .build(); + MockSubsystem mockSubsystem1 = new MockSubsystem(); + mockSubsystem1.throwError = true; + flightComputer.registerSubsystem(mockSubsystem1); + MockSubsystem mockSubsystem2 = new MockSubsystem(); + mockSubsystem2.throwError = false; + flightComputer.registerSubsystem(mockSubsystem2); + flightComputer.tick(); + assertTrue(mockSubsystem2.hasUpdateCalled); + } + + @Test(expected = Test.None.class) + public void runOnGoodArguments() { + FlightComputer flightComputer = FlightComputer.create(new String[]{"--real-sensors"}); + } + + @Test(expected = SecurityException.class) + public void exitOnBadArguments() { + FlightComputer flightComputer = FlightComputer.create(new String[]{"--fake-arguments"}); + } + + @Test(expected = SecurityException.class) + public void exitOnHelp() { + FlightComputer flightComputer = FlightComputer.create(new String[]{"--help"}); + } } diff --git a/test/org/rocketproplab/marginalstability/flightcomputer/SensorProviderTest.java b/test/org/rocketproplab/marginalstability/flightcomputer/SensorProviderTest.java new file mode 100644 index 0000000..8e9499d --- /dev/null +++ b/test/org/rocketproplab/marginalstability/flightcomputer/SensorProviderTest.java @@ -0,0 +1,30 @@ +package org.rocketproplab.marginalstability.flightcomputer; + +import org.junit.After; +import org.junit.Test; + +import java.lang.reflect.Field; + + +public class SensorProviderTest { + @After + public void afterEach() throws Exception { + Field sensorInstance = SensorProvider.class.getDeclaredField("instance"); + sensorInstance.setAccessible(true); + sensorInstance.set(null, null); + } + + @Test(expected = RuntimeException.class) + public void switchToRealSensors() { + // TODO: replace with real sensor checks when RealSensorProvider is implemented + SensorProvider sensorProvider = SensorProvider.create(true); + sensorProvider.getPressureSensor(); + } + + @Test(expected = RuntimeException.class) + public void switchToSimulators() { + // TODO: replace with simulator checks when SimulatorProvider is implemented + SensorProvider sensorProvider = SensorProvider.create(true); + sensorProvider.getPressureSensor(); + } +} diff --git a/test/org/rocketproplab/marginalstability/flightcomputer/looper/TestLooper.java b/test/org/rocketproplab/marginalstability/flightcomputer/looper/TestLooper.java index 966ee79..a716ee3 100644 --- a/test/org/rocketproplab/marginalstability/flightcomputer/looper/TestLooper.java +++ b/test/org/rocketproplab/marginalstability/flightcomputer/looper/TestLooper.java @@ -46,21 +46,6 @@ public double getSystemTime() { } - @Test - public void checkSingletonInstance() { - // get an instance of command scheduler - Looper singletonInstance = Looper.getInstance(); - - // instance should never be null - assertNotNull(singletonInstance); - - // create a new command scheduler - Looper differentScheduler = new Looper(new Time()); - - // new command scheduler must be different than singleton instance - assertNotEquals(differentScheduler, singletonInstance); - } - @Test public void testScheduleSameCommandMultipleTimes() { Looper looper = new Looper(new Time()); diff --git a/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestPTSubsystem.java b/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestPTSubsystem.java index 1efc57f..97f8949 100644 --- a/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestPTSubsystem.java +++ b/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestPTSubsystem.java @@ -30,7 +30,7 @@ public class TestPTSubsystem { @Test(expected = NullPointerException.class) public void nullADCInDefaultInstance() { - PTSubsystem ptSubsystem = PTSubsystem.getInstance(); + PTSubsystem ptSubsystem = new PTSubsystem(null); ptSubsystem.getPTValue(PTSubsystem.ChannelIndex.CH0); } diff --git a/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestSCMCommandSubsystem.java b/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestSCMCommandSubsystem.java index 4bbe9f5..3ed4f2a 100644 --- a/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestSCMCommandSubsystem.java +++ b/test/org/rocketproplab/marginalstability/flightcomputer/subsystems/TestSCMCommandSubsystem.java @@ -109,5 +109,6 @@ public void scheduleCommandWithFramedSCM() { looper.tick(); assertTrue(factory.getCommandByFramedSCM(framedSCMData).isDone()); +// fail(); } } \ No newline at end of file