The `RobotState::GetRobotMode()` API returns this enum class, but
`DriverStationSim` was using the `HAL_RobotMode` enum instead. This
commonizes the two APIs to return the same `RobotMode` enum class.
This difference in the APIs also affected Python, as the `hal.RobotMode`
and `hal._wpiHal._RobotMode` types are not compatible with each other.
Store DriverStation-owned GenericHID and Gamepad instances in Java and
C++, and expose the cached objects to Python bindings.
Move hand-written command gamepad and joystick wrappers to compose
cached CommandGenericHID instances plus typed HID wrappers, including a
Python CommandGamepad.
This will let us remove UserControls, while helping ensure that we don't
have state smashing between GenericHID objects.
Another bonus is without inheritance, intellisense will no longer show a
bunch of annoying methods, and instead just what actually exists.
---------
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
@AustinSchuh's `rules_cc` patches have all been merged upstream. This
updates `rules_cc` to include the relevant patches, removing the need to
patch it here.
This also squashes this warning on every build:
> WARNING: For repository 'rules_cc', the root module requires module
version rules_cc@0.2.13, but got rules_cc@0.2.14 in the resolved
dependency graph. Please update the version in your MODULE.bazel or set
--check_direct_dependencies=off
This fixes simulation WaitForProgramStart(true) potentially advancing
due to a stale or pre-start notifier created before SetProgramStarted()
was called.
Using MrcLib on the robot is going to be the plan for the future, to
make things easier.
MrcLib is how sim is supported going forward. The desktop version of
mrclib can act as a robot server.
This is set up where the mrclib interface is in shared code. On robot,
that is the only backend used. On desktop, a default sim backend is
used. However, the sim plugin can switch that to the real robot backend,
so the robot code will exactly look like a real robot.
Fix SetPeriod() valuePos handling when an ID moves between period queues
In SendValue(), don't append older values, and fix the total size
accounting for the underflow case when a smaller value replaces a larger
value.
Add comprehensive unit tests.
This is increasingly difficult to maintain, and has very limited
benefit. Modern coprocessors with enough horsepower to run Java
applications can use the Gradle or Bazel build systems instead.
Useful for catching bad behavior when doing math or configuring ratios
with integers. Errors can be turned off with
`@SuppressWarnings("IntegerDivision")`
```java
double kV = 12 / 6000; // error: integer division in a floating-point context
double kV = 12. / 6000; // OK
double kV = 12 / 6000.; // OK
int kV = 12 / 6000; // OK, but evaluates to 0
double ratio = 42 / 12; // error: integer division in a floating-point context
@SuppressWarnings("IntegerDivision")
double ratio = 42 / 12; // OK, evaluates to 2
```
```
Execution failed for task ':developerRobot:compileJava'.
> Compilation failed; see the compiler output below.
/Users/sam/code/wpilib/allwpilib/developerRobot/src/main/java/wpilib/robot/Robot.java:10: error: integer division in a floating-point context
double kV = 12 / 6000;
^
1 error
```
Also adds the compiler plugin as a dependency to the developerRobot
project for dev testing
The original implementation was `m_gyroOffset + (rotation -
m_pose.Rotation())`, which means the first `RotateBy` should be using
`-m_pose.Rotation()` (see `ResetPose()`). Java is already correct. This
also adds new tests to catch this particular error.
When the bazel remote cache was switched from buildbuddy to a self
hosted server in #8342, I asked that the buildbuddy hooks be remain so
that I could still use their caching service for local builds.
The downside of this was that my forks builds aren't leveraging
buildbuddy, so if I'm fiddling with something heavy like a wpimath
robotpy thing, my CI builds never update a cache and never are warm when
I push fixups.
This PR combines the `setup-bazel-remote` and `setup-build-buddy`
actions which set up the bazel remote cache. Rather than having two
different version, the correct one will be choosen in the following
order:
1. Use wpi's server with write access if the `bazel_remote` information
is set (This basically would only happen on main branch in
`wpilibsuite/allwpilib` since secrets aren't accessible from builds
originating in forks)
2. Use buildbuddy if the key it is present (This would work for my fork
builds)
3. Fall back to the readonly version of wpi's server
As seen
[here](https://github.com/bzlmodRio/allwpilib/actions/runs/25777428163/job/75712863120#step:7:28)
the build in my fork will run with buildbuddy, and my PR's build here
should fall back to readonly mode.
This also updates the bazel scripts to behave more like the C++ and Java
examples, and updates the copybara scripts to be able to sync up
`mostrobotpy`
These two functions were changed to return new objects instead of
modifying in-place, so the `const` qualifier should be added. Otherwise,
users with a const reference to a `SwerveModuleVelocity` need to make a
temporary copy first.
`added ^ removed` (XOR) is incorrect for the update guard.
Both `added` and `removed` can be true simultaneously (e.g. subscription
options change), and XOR would incorrectly skip the period update. Fixed
to `added || removed`.
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This addresses a race condition caused by TimedRobot and other
frameworks not creating their first notifier alarm until after signaling
program start.
Default this to true because it's the most common desired use case when
combined with TimedRobot.
The FTC DS had a deadband. Additionally, the FRC one had an implicit
deadband due to the only 8 bit resolution. We need a deadband by default
now with the high resolution gamepads.
If a `ClientMessageQueue` is at a
memory limit, `ClientMessageQueueImpl::ClientSetValue` will still
increment `m_valueSize.size` even though no element has actually been
actually been added.
This quickly results in things like topics completely shutting down
under high load, as no new elements can be added as `m_valueSize.size`
explodes to infinity unless `ClearQueue()` is explicitly called. You can
see this pretty easily with the following code, be it in sim or on a
robot:
```cpp
#include "wpi/framework/TimedRobot.hpp"
#include "wpi/smartdashboard/SmartDashboard.hpp"
class Robot : public wpi::TimedRobot {
public:
// ...
uint64_t value{0};
/**
* This function is called periodically during all modes
*/
void RobotPeriodic() override {
for (int i = 0; i < 1'000'000; i++) {
value += 1;
wpi::SmartDashboard::PutNumber("value", value);
}
}
}
```
Connecting via your favorite dashboard quickly reveals that no new
values get added after a while. However, with this patch implemented,
values do still continue to increment as updates gradually get serviced.
Generate an `update` method for any logged Robot class, not just
TimedRobot
Continue to generate a `bind` method for TimedRobot subclasses
Also removes unnecessary import statements for generated loggers, since
they're using fully-qualified names in the generated Epilogue class now.
Use [pattern matching switch
expressions](https://docs.oracle.com/en/java/javase/17/language/pattern-matching-switch.html)
where possible. This is a JVM 21+ feature which wasn't available until
recently.
If you look at the Java bytecode, this improves performance from an O(n)
runtime check of literally each of the `if (x instanceof y)` checks to
instead be an O(1) tableswitch.
---------
Signed-off-by: Jonah Snider <jonah@jonahsnider.com>
Since Servo has been removed from WPILib, add a RomiServo to replace it
(similar to XRPServo).
For Romi, move allocation of PWM channels to OnBoardIO since Motor and
Servo share channels.
`Trigger.multiPress(N, T)` creates a trigger that fires when there are
at least N rising edges within the last T timespan, eg `multiPress(3,
Seconds.of(1.25))` for 3 rising edges within the last 1.25 seconds.
`Trigger.retryWhileTrue` and `retryWhileFalse` will continuously attempt
to schedule a command while the binding condition is met. This is
similar to `whileTrue` and `whileFalse`, but will reschedule the command
if it ends or is canceled while the binding condition is still met,
rather than requiring a new rising edge to reschedule it.
As discussed in the discord. lb-in^2 is the common imperial MOI unit,
e.g. Onshape uses it.
Also, improved the Java docstring for `KilogramMetersSquaredPerSecond`
to explain what it represents.
---------
Co-authored-by: Benjamin Hall <bhall@ctr-electronics.com>
This pulls in the `mrclib` maven repository as shared libraries, as a
prereq for #8858.
Alternative to #8869, which avoids the unnecessary lockfile entry. This
should be a one-to-one replacement for that PR.
Closes#8869
---------
Co-authored-by: PJ Reiniger <pj.reiniger@gmail.com>
Since there is no longer a requirement for Subsystems/Mechanisms to be
registered to the command scheduler via a register() call, Mechanism can
be changed to an interface instead to allow for more flexible
inheritance structures.
Specifically, this would allow compatibility with CTRE swerve (which
previously required implementing Subsystem so that it could extend
CTRE's base class).
This updates gamepad trigger naming from cardinal-style face buttons
(`northFace/southFace/eastFace/westFace` and
`NorthFace/SouthFace/EastFace/WestFace`) to directional naming
(`faceUp/faceDown/faceRight/faceLeft` and
`FaceUp/FaceDown/FaceRight/FaceLeft`) to match the requested API shape.
The change is applied across Java and C++ HID/command layers, along with
related examples and binding metadata.
- **API surface updates (Java)**
- Renamed trigger/event methods in:
- `wpilibj` `Gamepad`
- `commandsv2` `CommandGamepad`
- `commandsv3` `CommandGamepad`
- Mapping preserved:
- `southFace` → `faceDown`
- `eastFace` → `faceRight`
- `westFace` → `faceLeft`
- `northFace` → `faceUp`
- **API surface updates (C++)**
- Renamed trigger/event methods in:
- `wpilibc` `Gamepad`
- `commandsv2` `CommandGamepad`
- Mapping preserved:
- `SouthFace` → `FaceDown`
- `EastFace` → `FaceRight`
- `WestFace` → `FaceLeft`
- `NorthFace` → `FaceUp`
- **Python semiwrap updates**
- Updated `wpilibc/src/main/python/semiwrap/Gamepad.yml` method mappings
to the renamed C++ method names (`FaceDown/FaceRight/FaceLeft/FaceUp`).
- **Callsite migration**
- Updated Java examples/template code and C++ examples/template code to
use the new method names so samples remain aligned with the API rename.
- **Docs/comments alignment**
- Updated related Javadoc/reference text and example comments to use
directional terminology.
```java
// Before
driverController.southFace().onTrue(command);
driverController.eastFace().onTrue(command);
// After
driverController.faceDown().onTrue(command);
driverController.faceRight().onTrue(command);
```
```cpp
// Before
driverController.SouthFace().OnTrue(command);
driverController.EastFace().OnTrue(command);
// After
driverController.FaceDown().OnTrue(command);
driverController.FaceRight().OnTrue(command);
```
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ThadHouse <7727148+ThadHouse@users.noreply.github.com>
`SetNowImpl` is used somewhat often in unit tests. It is a little bit
goofier to wrap because it takes a C function, so a little bit more work
has to be done to get that wrapped in pybind.
Claude helped.
The initial build file generation for robotpy projects was relatively
naive and purpose built to get `allwpilib` compiling, without supporting
all the available features.
This modifies the generation scripts to be able to support multiple
embedded libraries, which will be necessary for #8858, since `mrclib.so`
will need to be bundled along with the hal libraries. In addition some
cleanup was done to get the wheels looking more like what is in pypi.
Based on discord comments I assume we don't want to support a Nix shell
or flake for use with building allwpilib so we should just ignore these
files so users can have their own
This provides an API for writing a finite state machine compatible with
the commands v3 framework. Individual states in the state machine are
wrappers around command objects (which may themselves be state
machines). Transitions between states are defined with a staged builder
DSL similar to command builders, and uses `@NoDiscard` to catch
partially configured transitions.
The FSM API is meant to handle highly complex cases that the fluent
command chaining DSL and coroutine-based imperative commands cannot
easily represent; specifically, where a command sequence may want to go
back to an arbitrary previous state or skip forward to an arbitrary
future state.
Here's an example from the design doc for a command that will drive to a
known scoring location, aim at a scoring target, and repeatedly shoot
balls until a storage hopper is empty. It also has conditions to stop
shooting and move back to the scoring location if it's jostled away, and
then automatically resume firing.
```java
public Command autoWithStateMachine() {
// Declare the state machine
StateMachine stateMachine = new StateMachine("Auto With State Machine");
// Define states
State getInPosition = stateMachine.addState(drivetrain.driveToScoringLocation());
State aiming = stateMachine.addState(turret.aimAtGoal());
State scoring = stateMachine.addState(shooter.fireOnce());
State celebrating = stateMachine.addState(leds.celebrate());
// Set the initial state. Neglecting this will cause a runtime exception when the state machine starts.
// Teams using the WPILib compiler plugin will get a compiler error if they do not set this
stateMachine.setInitialState(getInPosition);
// Switch to aiming when we reach the scoring location.
getInPosition.switchTo(aiming).whenComplete();
// Set the swerve wheels in an X shape after reaching the scoring location to resist being pushed away.
getInPosition.onExit(() -> Scheduler.getDefault().fork(drivetrain.setX()));
// Then start scoring once the turret is aimed at the goal.
aiming.switchTo(scoring).when(turret::aimedAtGoal);
// Loop the scoring state as long as the hopper has a ball.
scoring.switchTo(scoring).whenCompleteAnd(() -> hopper.hasBall());
// Automatically interrupt any part of the aiming or scoring sequence if
// the robot is moved away from the scoring location and move back into position.
stateMachine.switchFromAny(aiming, scoring).to(getInPosition).when(atScoringLocation.negate());
// Start celebrating once the final ball has been scored.
scoring.switchTo(celebrating).whenCompleteAnd(() -> !hopper.hasBall());
return stateMachine;
}
```
A compiler check is added to detect object construction that's not
followed by post-construction initializer methods (as defined by the
class by placing `@PostConstructionInitializer` on such methods).
`StateMachine.setInitialState` uses this to detect team code that
creates a state machine but does not set its initial state.
`Trigger.getAsBoolean()` behavior has been changed from passing through
the underlying boolean supplier to returning the latest cached signal as
determined by the most recent call to `poll()`. This allows rising and
falling edge triggers to have a consistent return value over an entire
polling cycle, rather than only being high for the _first_ check in a
cycle.
Closes#8309
This provides the ability to simulate parts of the Onboard IMU at the
HAL level. This allows team to use and simulate the IMU in code, and a
follow up PR could be made to the halsim_gui to add a new widget to view
and modify the data graphically.
Since the C++ IMU uses radians for angles that is what I did for the
simulator.
Partially deals with #8845
There's no real need to manually check the `runs-on`, as `runner.os`
provides a universally identifiable string for checking this anyways.
Signed-off-by: crueter <crueter@eden-emu.dev>
Javadoc now includes 4 MB of fonts for every Javadoc JAR, which we have
18 of, which causes unnecessary bloat to the installer size. This
disables the inclusion of those fonts, using the built-in fallback
included in the Javadoc stylesheet. This also increases the default font
size by 10% after polling the FTC Discord resulted in people asking for
a bigger font.
There were 3 cases failing before.
1. An OpModeRobot with no annotation.
2. An OpModeRobot with an annotation but a parameterless constructor.
3. An OpMode with a UserControls constructor
This PR solves both of these issues. The first one is solved by adding
the null check before setting the user controls instance. That one will
never have an opmode instance.
The second one is solved by falling back to a parameterless constructor
if one with a parameter is not found.
The 3rd one is solved by using the annotation type rather than the
instance for constructor lookup.
Also fixes ExpansionHubSample's missing annotations.
Right now, the `zipBaseName` variable in various publish.gradle files
contains the group ID and artifact ID for use by the combiner, however,
they are also duplicated in `artifactGroupId` and `baseArtifactId`,
leading to potential mistakes if they aren't updated together. This
fixes that by adding a new utility function `makeZipBaseName` to
automatically create the right name given a group ID and artifact ID.
This also fixes publishing for thirdparty subprojects, which didn't
update `zipBaseName`.
Adds a section on design philosophy so we have something to point to
when people suggest features that aren't compatible with the way WPILib
is designed. Fixes some missed reorg changes (although the native-utils
link intentionally points to main as to be up-to-date in the future) and
generally cleans up any outdated information. Also includes wording
about supporting FTC. Per discussion in Slack, the LabVIEW wording has
been removed, and anything to do with LabVIEW is going to have to be
NI's job. And pursuant to #2757 and #5331, additional (light) developer
documentation has been added to some subprojects, mostly being a quick
summary of the what the project does and what it's for (or not for).
---------
Co-authored-by: sciencewhiz <sciencewhiz@users.noreply.github.com>
Co-authored-by: Joseph Eng <91924258+KangarooKoala@users.noreply.github.com>
I've been running my copybara syncs from this branch for a long time.
Finally deciding to PR it.
The biggest update was due to `mostrobotpy` absorbing the commands,
examples, and pyfrc libraries, but I also added in hooks to "enable" the
flakey `xfail` tests on the allwpilib side, and the ability to run
verbose or force push updates.
This lets us remove the unmaintained StackWalker library and its hacky
upstream_utils script.
@Gold856 reported that StackWalker gives blank stacktraces:
https://discord.com/channels/176186766946992128/368993897495527424/1261940029287301150.
They also reported an earlier version of this PR giving the following
stacktrace instead:
```
D:\allwpilib\developerRobot\src\main\native\cpp\Robot.cpp(18): developerRobotCpp!Robot::RobotInit+0xB6
D:\allwpilib\wpilibc\src\main\native\cpp\TimedRobot.cpp(22): wpilibcd!frc::TimedRobot::StartCompetition+0x4F
D:\allwpilib\wpilibc\src\main\native\include\frc\RobotBase.h(36): developerRobotCpp!frc::impl::RunRobot<Robot>+0xC8
D:\allwpilib\wpilibc\src\main\native\include\frc\RobotBase.h(106): developerRobotCpp!frc::StartRobot<Robot>+0x17E
D:\allwpilib\developerRobot\src\main\native\cpp\Robot.cpp(60): developerRobotCpp!main+0xB
D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(79): developerRobotCpp!invoke_main+0x39
D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(288): developerRobotCpp!__scrt_common_main_seh+0x132
D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(331): developerRobotCpp!__scrt_common_main+0xE
D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_main.cpp(17): developerRobotCpp!mainCRTStartup+0xE
KERNEL32!BaseThreadInitThunk+0x1D
ntdll!RtlUserThreadStart+0x28
```
People generally have expressed a dislike for the Hungarian notation
used in member variables, especially in examples/templates, and our
styleguide shouldn't be forced on downstream consumers, so this removes
all Hungarian notation from the examples/templates.
There are _some_ benefits to Hungarian for private member variables
(like knowing what's a member vs. local in a PR review) so we'll keep
private member variables the same for now, but public variables should
no longer use Hungarian notation, since it looks much worse. A new PMD
XPath rule has been added to accomplish this goal. Some other
non-compliant variables were fixed for the new rule.
There were complaints about no patch files being created from CI when
the examples pre-gen fails for people who don't build with bazel. This
adds a new action step to run just the non-robotpy pregen.
I also added an argument to the diff tests to make it a unified diff,
which might make it easier to hand fix.
Since we currently have both a Bazel build and Gradle build, we need to
keep the Doxygen versions in sync between the two.
40188d9cc6/docs/build.gradle (L71)
It's awkward that these are in very disjoint parts of the repo. This
puts them in the same directory so it's more obvious it should be kept
in sync.
This removes the confusion of the `ExpansionHubServo` class serving both
purposes, and thus having a `set` method that functions as `setPosition`
when in servo mode and `setThrottle` when not in continuous mode. It
also removes the `setContinuousRotationMethod` which could be confused
for a method that switches the actual servo firmware itself from servo
to continuous mode, which is not a thing that is physically possible I
think.
---------
Signed-off-by: Zach Harel <zach@zharel.me>
Part of the `semiwrap` process that hasn't been ported over yet is
generating pyi stubs. It is possible to not have your semiwrap setup
correctly and "leak" native types into the generated python docstrings,
which causes the process to
[fail](https://github.com/pjreiniger/mostrobotpy/actions/runs/24618640845/job/71985311682#step:12:3652).
semiwrap also has a tool you can run, 'create-imports' that will read
the symbols from a build pybind library and automatically create and
sort the imports in the `__init__.py` file. This step is not enforced by
CI, which is why it hasn't been failing in `mostrobotpy` land.
This PR fixes the stubgen problems and runs reorganizes the imports. I
will have a follow up PR that can bring these automatically into the
build system after this lands. I'd do a fancy new `gh stack` but I can't
figure out if it works on forks.
The "Utility" name better matches its intended generic use case and
avoids overloaded terminology with unit testing (e.g. the need to name
the opmode annotation `@TestOpMode`).
The driver station will also be updated to reflect this change.
```
CMake Warning (dev) at /usr/share/cmake/Modules/UseJava.cmake:716 (cmake_parse_arguments):
The OUTPUT_DIR keyword was followed by an empty string or no value at all.
Policy CMP0174 is not set, so cmake_parse_arguments() will unset the
_add_jar_OUTPUT_DIR variable rather than setting it to an empty string.
Call Stack (most recent call first):
cmake/modules/CreateSourceJar.cmake:29:EVAL:1 (add_jar)
cmake/modules/CreateSourceJar.cmake:29 (cmake_language)
wpiannotations/CMakeLists.txt:29 (add_source_jar)
This warning is for project developers. Use -Wno-dev to suppress it.
CMake Warning (dev) at /usr/share/cmake/Modules/UseJava.cmake:716 (cmake_parse_arguments):
The OUTPUT_DIR keyword was followed by an empty string or no value at all.
Policy CMP0174 is not set, so cmake_parse_arguments() will unset the
_add_jar_OUTPUT_DIR variable rather than setting it to an empty string.
Call Stack (most recent call first):
cmake/modules/CreateSourceJar.cmake:29:EVAL:1 (add_jar)
cmake/modules/CreateSourceJar.cmake:29 (cmake_language)
wpiunits/CMakeLists.txt:25 (add_source_jar)
This warning is for project developers. Use -Wno-dev to suppress it.
```
Also revamp SetLastError et al; Instead of taking status by pointer,
take by value and return new status instead. Rename from SetLast to Make
to make this new usage obvious.
Also move declarations for the error functions from duplicated in the
per-target HALInternal.hpp to a common ErrorHandling.hpp.
Closes#8018
- Adds the 2024-2025 and 2025-2026 FTC field image data
- Used a better naming scheme of `<year> F{R,T}C <gamename>`
* Also removed generic `field` verbiage from PNG file names
- JSON and PNG files moved into respective `frc` and `ftc` directories
- Rotated fields for the new red-left scheme
Signed-off-by: crueter <swurl@swurl.xyz>
Originally started with just swerve, but expanded to diff and mecanum
(docs only) for parity across the drivetrains. Return value checks are
applied when possible to make migration easier and to error loudly if
people forget.
---------
Co-authored-by: Joseph Eng <91924258+KangarooKoala@users.noreply.github.com>
We will want a better API for higher level devices that expect to be on
motioncore, but for ones that are not expected to be, it'll be really
nice to have an API that can let us map the motioncore can bus to its
HAL index.
Commands v3 had a few changes due to the upgrade:
- Java 24 removed the Pinned: MONITOR IllegalStateException when
yielding in a synchronized block, so we no longer need to special case
for it
- Lambda method name generation was tweaked, requiring tests to be
updated
- Bazel java_rules needed to be bumped to support Java 25
Closes#8425
```
mold: error: undefined symbol: wpi::fields::GetFields()
>>> referenced by Field2D.cpp
>>> /home/tav/frc/wpilib/allwpilib/glass/build/libs/glass/static/linuxx86-64/debug/libglassd.a(Field2D.o):((anonymous namespace)::FieldInfo::DisplaySettings())
>>> referenced by Field2D.cpp
>>> /home/tav/frc/wpilib/allwpilib/glass/build/libs/glass/static/linuxx86-64/debug/libglassd.a(Field2D.o):((anonymous namespace)::FieldInfo::LoadImage())
collect2: error: ld returned 1 exit status
```
The issue seems to stem from libglass linking to the shared version of
fields, whereas wpical requires static linkage.
This primarily fixes up the bazel publishing to match the gradle
publishing again, as some new libraries were added but not hooked up to
the maven publishing.
During the process, I noticed that the 3rd party libraries (googletest,
catch2, and imgui_suite) were still getting published on the old
`edu.wpi` namespace. I tried to clean up all the other references to
that that I could. Note: opencv and libssh are handled outside
`allwpilib` so they need to be updated separately.
Clang 21 catches returning `0` from `GetOpMode` as returning `null`.
Since this state is very momentary and all comparisons inside WPILib are
done against `GetOpModeId` instead, I changed it to return an empty
string.
Jackson is a very heavy library; it supports loads of features that we
don't need, and historically has caused issues due to long class loading
times (a little over 2 seconds to load AprilTagFieldLayout). This often
manifests as a help request in the form of "my robot disables when I do
X, but doesn't disable when doing X in subsequent attempts until code
restart." While SC has brought down Jackson loading times significantly,
with AprilTagFieldLayout loads taking only 330 milliseconds, that's
still a rather long delay, and while libraries should handle any JSON
loading ahead of time to prevent delays in auto/teleop, it would still
be good to make the worst case better to reduce user frustration.
Benchmarks indicate using [Avaje
Jsonb](https://github.com/avaje/avaje-jsonb) to load AprilTagFieldLayout
only takes ~70 ms, a fair chunk of which isn't actually in Avaje Jsonb
(~4 ms is spent on using getResourceAsStream to retrieve the JSON file,
~8 ms is spent on just loading the AprilTag class and its dependencies).
Note that all times listed are end-to-end, meaning nothing else was done
except for the operation being benchmarked, and doing arithmetic on them
can be flawed due to some classes being loaded twice, i.e.,
getResourceAsStream and `new AprilTag()` likely load some of the same
JDK classes and so subtracting both from the Avaje Jsonb load time is
likely slightly incorrect because class loading is being double counted.
For our purposes, it's likely accurate enough and is mostly just for
contextualization.
Benchmarks were run on a Raspberry Pi CM5 with 2 GB of RAM. Source code
for the
[results](https://github.com/user-attachments/files/26471452/benchmark.txt)
can be found in the "Fastjson2" commit
(2456d15ca8ebd17635e607cd40bf8816e77869a1).
Avaje Jsonb uses code generation via annotation processors to generate
the classes needed to do JSON serde and uses service providers to find
them, which will require downstream changes in robot projects, as the
different service providers in each library must be merged together for
Avaje Jsonb to function. We will use the Gradle shadow plugin, as its
already used by the installer and therefore adds zero additional
dependencies.
1. Make the OpMode interface itself periodic; this means the only
differences between `OpMode` and `PeriodicOpMode` are the latter's
methods to add sideloaded periodic callbacks
2. Make OpModeRobot process callbacks in a similar fashion to TimedRobot
and
3. Add some lifecycle functions (discussed below)
4. Pull the callback priority queue from TimedRobot to a new class
called `PeriodicPriorityQueue` so that `TimedRobot` and `OpModeRobot`
have less duplication
5. Fix a typo in the DriverStationJNI class that causes a memory leak
when certain driver station sim calls
6. Port the C++ OpModeRobot tests to Java
`OpModeRobot` now possesses some `IterativeRobotBase`-stye lifecycle
functions; these functions
1. `robotPeriodic`
2. `simulationInit` and `simulationPeriodic`
3. `disabledInit`, `disabledPeriodic`, and `disabledExit`
(note that `simulationInit` and `disabledInit` may be renamed to match
wpilibsuite#8719)
`OpModeRobot` also now processes `OpMode` changes (by the Driver
Station) in its `loopFunc` method, similar to
`IterativeRobotBase.loopFunc` processing game mode changes; `loopFunc`
is, similarly to `TimedRobot`, provided as a default `Callback`
---------
Signed-off-by: Zach Harel <zach@zharel.me>
Co-authored-by: Joseph Eng <91924258+KangarooKoala@users.noreply.github.com>
When downloading a patch to fix linting errors, it's annoying to have to
unzip it, particularly when it's a single file. This PR updates the
`upload-artifact` action to v7, which allows for uploading an artifact
without zipping it. It also sets archive to false for all patches
generated by linting.
Commands are no longer able to outlive their schedule-site's scope,
regardless of how they were scheduled (set as a default command, bound
to a trigger, or manually scheduled)
As a consequence, default commands need better tracking so the default
command setting can be released when their scope exits and the next-most
appropriate default command can be rescheduled (eg, an opmode sets a
default command, then the globally-scoped default is restored when the
opmode exits). Some complexity is required here to make it work well for
edge cases.
Like `schedule()`, `setDefaultCommand()` will immediately start the new
default command if called inside of another command to avoid 1-loop
delays. However, this does not apply when called by the _current_
default command, as it would result in attempting to cancel the default
command while it's mounted (which is impossible and would throw an
exception)
```java
class Robot extends OpModeRobot {
final Drive drive = new Drive();
final CommandXboxController controller = new CommandXboxController(1);
public Robot() {
// global default command, active unless overridden in an opmode or command
drive.setDefaultCommand(drive.stop());
// global trigger binding, always active
controller.rightBumper().onTrue(drive.setX());
}
}
@Teleop
class ExampleOpMode extends PeriodicOpMode {
public ExampleOpMode(Robot robot) {
// opmode-specific default command
robot.drive.setDefaultCommand(robot.drive.operatorControl(robot.controller));
// opmode-specific binding
robot.controller.leftBumper().whileTrue(robot.drive.stop());
// opmode-specific binding that takes precedence over the global binding
// because it happens last; it "wins out" over the `setX()` binding
robot.controller.rightBumper().onTrue(robot.drive.selfTest());
}
@Override
public void periodic() {
Scheduler.getDefault().run();
}
}
```
`Color::FromHSV` didn't match the Java `Color.fromHSV` in some saturated
edge cases, introducing an off-by-one error when the HSV color should
correspond complete saturation of one or two of the primary colors.
Example:
- Java: `Color.fromHSV(0, 255, 255) -> (255, 0, 0)`
- C++: `Color::FromHSV(0, 255, 255) -> (255, 1, 1)`
This also means the following methods are also transitively affected:
- `AddressableLED::LEDData::SetHSV`
- `LEDPattern::Rainbow`
This off-by-one error is introduced by a rounding error from the chroma
calculation, which was dividing by 256 rather than the appropriate
maximum value of 255 like in Java:
7ca35e5678/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/Color.java (L176-L177)
Also port appropriate tests from Java to C++ to catch this bug.
I found this bug when I tried to port `AddressableLEDBuffer` to RobotPy.
Codex found the root cause :)
There's changes to the diagnostic output and a performance improvement
for autodiff setup. I also updated Java's Options docs to more closely
match upstream.
```
> Task :javacPlugin:javadoc
/home/tav/frc/wpilib/allwpilib/javacPlugin/src/main/java/org/wpilib/javacplugin/OpModeAnnotationValidator.java:31: warning: invalid input: '<'
* <li>Name must be <= 32 characters
^
/home/tav/frc/wpilib/allwpilib/javacPlugin/src/main/java/org/wpilib/javacplugin/OpModeAnnotationValidator.java:32: warning: invalid input: '<'
* <li>Group must be <= 12 characters
^
/home/tav/frc/wpilib/allwpilib/javacPlugin/src/main/java/org/wpilib/javacplugin/OpModeAnnotationValidator.java:33: warning: invalid input: '<'
* <li>Description must be <= 64 characters
^
3 warnings
```
These weren't caught by the `docs:generateJavaDocs` task because the
javacPlugin docs aren't included there.
Since sched_setscheduler() requires non-RT priorities to be 0, we can
use that as a sentinel value for disabling RT and condense the Java API
to just two functions with fewer parameters. The thread priority setter
is deprecated since only experts should use it.
The HAL Notifier thread priority setter was replaced with setting the
priority in the thread itself.
The C++ Notifier non-RT and RT constructors were deduplicated.
The real-time scheduler was changed from SCHED_FIFO to SCHED_RR, which
is SCHED_FIFO with threads allowed to run for a maximum time quantum
before yielding (100 ms by default).
Each Bazel Windows CI job is currently redundantly evaluating the build
actions for both the `opt` and `dbg` compilation modes.
If we group the debug artifact builds together (instead of grouping by
the shared/static library artifacts), the `dbg` compilation mode actions
no longer need to be executed across multiple CI jobs in the matrix.
(Yes, the CI jobs are sharing the Bazel cache, but there's still
overhead in checking the action cache for each action. It's also
possible that two jobs will race to execute the same action.)
| Total actions per job | [Before] | After |
|----------------------------|---------:|------:|
| Windows x86-64 | 12277 | 10179 |
| Windows x86-64 Static | 11947 | n/a |
| Windows x86-64 Debug | n/a | 9895 |
| Windows ARM64 | 5518 | 3420 |
| Windows ARM64 Static | 5304 | n/a |
| Windows ARM64 Debug | n/a | 3272 |
| Windows System Core | 4836 | 2916 |
| Windows System Core Static | 4576 | n/a |
| Windows System Core Debug | n/a | 2916 |
[Before]:
https://github.com/wpilibsuite/allwpilib/actions/runs/23781230818
This should hopefully translate to shorter wall-clock time Windows CI
jobs.
The wrapper includes reverse mode autodiff, the Problem DSL, and the
optimal control problem API. I wrote it by directly translating the
upstream
[API](https://github.com/SleipnirGroup/Sleipnir/tree/main/include/sleipnir)
and [tests](https://github.com/SleipnirGroup/Sleipnir/tree/main/test) to
Java (i.e., copy-paste-modify).
I replaced the ArmFeedforward and Ellipse2d JNIs with implementations
using the Sleipnir Java bindings. Switching dev binary JNIs to release
by default sped up wpimath test runs from several minutes to 7 seconds.
In https://github.com/wpilibsuite/allwpilib/issues/8681 we discovered
that multicast service types need to be valid (end with _tcp or _udp),
or else errors are silently swallowed. Let's make our C++ unit test use
a valid name and also check that it works. I think if we
should/shouldn't do this is up for debate still.
I also discovered two bugs in the JNI code that lead to incorrect
results being returned
- Return array index was always 0
- Use of JLocal for the return value seems to mean that the array will
always be NULL in java
#7695, #7696, #7697, #7701, #7724, #7753, #7861 removed various features
from the HAL, but forgot to clean up the handles, the WS API, or both.
Additionally, since AnalogInput is the only remaining analog I/O,
AnalogJNI was renamed to the more specific AnalogInputJNI.
Some discussion with the tech team showed that there were some real
advantages to being able to pass a 2nd type. It allows separating the DS
and Robot. Additionally, we can make the DriverStationBase class
actually usable instead of the existing DriverStation class which is
impossible to handle in intellisense because it has too much.
This won't fully be doable in C++, but we will need to implement
something similar in python.
The epoch() function, zero() function, and min_time member are all not
part of the std::chrono clock interface.
The default constructor of time_point is
[documented](https://en.cppreference.com/w/cpp/chrono/time_point/time_point.html)
to initialize to the clock's epoch.
I ran the following locally:
```bash
gradle generateCompileCommands
./.github/workflows/fix_compile_commands.py build/TargetedCompileCommands/linuxx86-64release/compile_commands.json
wpiformat -default-branch 2027 -no-format -tidy-all -compile-commands=build/TargetedCompileCommands/linuxx86-64release
```
The `HeaderFilterRegex` option is used to filter out warnings from
thirdparty headers.
- Remove status return from HAL level (clock getting should never fail)
- Remove 32-bit timestamp expand function
- Make monotonic_clock.hpp (formerly fpga_clock.hpp) header-only and
move to root hal include directory
Move various "examples" into snippets. Several examples that were less
than a full mechanism or robot were moved to snippets. `arcadedrive` and
`tankdrive` were removed in favor of their Gamepad variants. `hidrumble`
was removed due to being too simple. `potentiometerpid` was removed
because of low utility. `gyromecanum` replaced `mecanumdrive` for
deduplication and because very few teams run holonomic drivetrains
without gyros.
Makes Java `Alert.Level.ERROR`, `Alert.Level.WARNING`, and
`Alert.Level.INFO` proper aliases (instead of separate enum constants
with the same value).
Cleans up Python tests.
Makes the Alert tests more consistent between languages.
Useful for eg OpModes, where names have a maximum length
Also includes validations for values in opmode annotations like
`@Autonomous(name = "...")`; name, group, and description all have
maximum allowable lengths
I left "free speed" alone since that's the technical term for it. In
general, velocity is a vector quantity, and speed is a magnitude (i.e.,
a strictly positive value).
This PR also replaces the speed verbiage in MotorController with duty
cycle.
Fixes#8423.
This hooks up the bazel build to the robotpyExamples. It can use the
(formly pyfrc or whatever) automatic unit tests for an example, as well
as exposing the ability to run the example in simulation, with or
without `halsim_gui` with a command such as `bazel run
//robotpyExamples:AddressableLED-sim`
This required building and using wheels instead of just a normal
`py_library`, so that things like `ENTRY_POINTS` can be used. I took a
bare bones approach to building and naming the wheels (for example the
native ones don't have the OS info or python version in them, so they
wouldn't be suitable publish to pypi, but that can always be updated
later.
Avoids boxing to reduce allocations, combines for loops as an
optimization, and removes massive switch statement because Java's
generics are type erased, so the different type parameters make no
difference.
[Libuv docs](https://docs.libuv.org/en/v1.x/tcp.html) states:
> Enable / disable TCP keep-alive. delay is the initial delay in
seconds, ignored when enable is zero.
But we used std::milli, leading to being off by a factor of 1000.
Linear OpModes have several major downsides with no obvious solutions:
- Some things stop working automatically--e.g. in a linear opmode,
simulation will not work out-of-the-box; the user must explicitly call
sim themselves. there's a few other things we do periodically, but this
is the big one (it also forces some decisions on other parts of the
library—eg if we want Tunable to work in linear without the user
manually calling refresh, we have to run it on a background thread,
which means it must be thread safe throughout). We can help in some
areas (e.g. have sleep functions call background things), but if the
user is writing a loop that waits to drive a certain distance with no
sleep, it's an easy footgun
- Writing code with no sleeps is easy to do, and can hog an entire
processing core easily--yes, there's more than one core, but it could
still easily impact e.g. vision processing
- Many people I've talked to want robot-level periodic and periodic sim
functions. Given linear opmodes, we have two options, neither of which
is great: (1) don't provide robot-level periodic functions, and the
users who want those must set those up themselves and remember to call
them explicitly from every periodic opmode, or (2) provide them, but
only call them automatically from periodic opmodes, which could be
confusing for linear opmode users (they'd have to call them manually if
they wanted them). Currently we do (1) but someone in the community
already opened a change to do (2).
- Restarting the robot program fixes the "stuck in auto for the rest of
the match" problem but still feels like an ugly hack because the startup
time is not unlikely to make the robot not immediately ready for teleop
Removing LinearOpMode resolves these issues by moving to a periodic-only
structure. We can address the few notable use cases of LinearOpMode
(e.g. very basic autonomous sequences) in other ways such as Blocks
generated code, better state machine tutorials/documentation, etc.
The Listener installed by Preferences was referencing m_typePublisher which could be modified by a future call to setNetworkTableInstance(). Instead, reference a local.
Also made Topic.m_handle final, to guarantee that Topic.equals() is thread-safe, and still work after the publisher has been closed.
In NetworkServer::SavePersistent, if the save is interrupted (by robot
power loss, etc), the networktables.json file may be left in an
unhandled state where the file consumed by
NetworkServer::LoadPersistent is not found, but the backup file exists.
In this case, we should attempt to recover the backup file to avoid
losing all persistent data.
Fixes#8631
Documents that it will return immediately if FMS isn't attached or DS
isn't in practice mode.
Related to change in DS match time behavior that was documented in #8606
#8626 needs to switch to using reflection to load the robot class. Do
that with this PR so it's separate.
Also, remove the duplicated main files from the template, and instead
fixup vscode to handle this properly.
Also fixes the google compile-testing library to 0.23.0 (the latest
available at time of writing) instead of a wildcard
Jackson versions were inconsistent across projects; most were on 2.19.2,
but the fields subproject was on 2.15.2. All projects are now on 2.19.2
for consistency
This PR fixes the magnitude units in `MutableMeasure#mut_acc` and
`MutableMeasure#mut_plus`.
Previously, both `mut_acc` and `mut_plus` were setting the base
magnitude using the unit-ed magnitude value. While this would work fine
for base units where `magnitude == baseUnitMagnitude`, this was creating
issues with derived units.
This PR also adds missing tests for the `MutableMeasure` class.
Text frames were being queued while binary frames were sent immediately.
Change NetworkOutgoingQueue to send text frames immediately on local
connections. Add asserts since local connections should now not be
queueing at all.
In C++, we use a diagonal matrix to avoid an expensive matrix
multiplication. EJML doesn't have a diagonal matrix type, so in Java, we
use a double array and implement the multiplication manually.
Currently the only name for this unit is `RPM`. This caused a bit of
confusion for a couple of my team members when we failed to find an RPM
unit, assuming it would be named `RotationsPerMinute` as is the standard
for almost all other units, such as `RotationsPerSecond`.
No corresponding changes have been made to wpilibc as it seems to
already work this way, with `rpm` being the abbreviation for
`revolutions_per_minute`.
Robotpy dropped support for 3.10 recently, so this updates to the next
lowest version. This will be helpful when the examples get merged into
`mostrobotpy`
There's not really a specific reason why I just jumped to 3.11 instead
of a newer version. If anybody suggests otherwise I will gladly bump it
higher.
The existing code takes 750ms to start per resolver. This is too long,
especially in mrccomm where we start 4 on initialize, and 3 any time the
team number changes.
Solve this by handling the async setup more correctly. Assuming it
returns pending, we're assuming the announcer is good. Then on stop(),
we cancel the register in case its still pending, wait for the callback,
and then deregister.
Easier then the last one that put everything in a sub namespace. By
prefixing the name less things break, and intellisense will be less
confusing to new users during the transition.
Fixes local clients receiving inconsistent data updates. Data was only
flushed to local clients on incoming websocket data (or when explicitly
flushed), so local clients on a quiet server would stop receiving
updates.
Revert some changes from #7997.
Instead of relying on periodic sends, always immediately send local data
updates to the wire for lower latency. This means that on local clients,
the periodic update rate and sendAll settings will be ignored, as all
data updates will be sent immediately.
Fixed a typo in the description of the getLoopStartTime function in both
C++ and Java TimedRobot class.
---------
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Add a simple tap counting filter for boolean streams.
The filter activates when the input has risen (transitioned from false
to true, like when a button is tapped) the required number of times
within the time window after the first rising edge. Once activated, the
output remains true as long as the input is true. The tap count resets
when the time window expires or when the input goes false after
activation.
Example usage:
```java
xbox.a()
.multiPress(2, 0.2) // Detect a double tap within 0.2 seconds
.onTrue(Commands.print("Double tapped A button"));
xbox.y()
.multiPress(2, 0.5) // Detect a double tap within 0.5 seconds
.whileTrue(Commands.print("Y held after tap").repeatedly());
```
This is not a noise reduction and/or input smoothing filter, but it is
similar in usage to debounce, so I believe it could be considered a
filter, but am open to a better location.
I believe this would be a useful addition, as double/triple tapping a
button is a common control option in games, yet is not often utilized by
newer FRC teams. I believe adding it to WPILib in a standard way will
allow more teams to make the most out of their controls.
Documents the extrinsic vs intrinsic semantics of `plus()` and
`minus()`. (`rotateBy()` was documented in [a previous
PR](https://github.com/wpilibsuite/allwpilib/pull/5508))
Fixes usage of `plus()` and `minus()` in `Rotation3d.interpolate()`.
(Fixes#8523)
Fixes incorrect usages of `plus()`, `minus()`, and `rotateBy()`
throughout `Odometry3d`.
Adds explanatory comments for some `plus()`, `minus()`, and `rotateBy()`
operations.
Fixes `TimeInterpolatableBuffer` not using twists for `Pose3d` (this was
just because I happened to notice it, it isn't really related to the PR)
To check all of our usages of `plus()`, `minus()`, and `rotateBy()`, I
marked them as deprecated, checked compile errors from `./gradlew
compileJava`, and then undeprecated them. You can see all of the spots
that showed up (at least on the Java side) by viewing the diff for
241109c.
I wanted to present this alternative to #8526 because the change has its
own quirks, there's little time before kickoff, and there would be no
code-side warning to teams (and mentors) already used to the current
behavior.
Used Gemini to convert the C++ tests in wpimath/.../kinematics to
pytest. For ease of use required a better constructor for
`MecanumDriveWheelPositions`
I did this conversion months ago (before robotpy landed and before the
reorg), so new tests might be missing. At least its better than nothing
🤷
Broke the huge pr that does almost everything into parts so its easier
to review.
---------
Co-authored-by: David Vo <auscompgeek@users.noreply.github.com>
This anecdotally fixes a problem that occurs when building with bzlmod.
At least for me this fixes the problem, and now that there is a function
for it it can be easier to deal with any other special casing that needs
to happen (windows, remote execution, etc). It is still a bit naive, but
should fix the major problem at the moment.
Semiwrap / meson / robotpy define `NDEBUG` when building their software
in all modes, while `allwplib` only does it when building debug. This
causes the size of `DenseMap` to differ between the shared libraries
built here, and the extension modules built in `mostrobotpy`, causing
segfaults when you try to execute code that uses `DenseMap`. This is not
a problem with the robotpy code in `allwpilib`, because bazel uses the
exact same compiler flags when building the shared libraries and
pybind11 extensions.
wpical was unable to use wpimath and its dependent libraries because
Ceres was compiled with a different version of Eigen. Now that the Ceres
build has been redone and shipped in #8151, we can now use wpimath and
our C++ apriltag wrapper in wpical, allowing for major refactors. This
includes:
* Using `to_json` and `from_json` specializations to concisely serialize
and deserialize all JSON files instead of manually handling JSON.
* Removal of the `Fieldmap` and `Pose` classes, which were duplicates of
the `AprilTagFieldLayout` and `Pose3d` classes respectively.
* Using `AprilTagDetector` instead of the raw libapriltag library.
* Using `Pose3d` instead of raw Eigen matrices.
In addition, several other refactors were made to make the code more
readable and to fix several UX issues and crashes. This includes:
* Eagerly parsing every JSON file when selected by the user. This means
JSON files are only parsed once on selection, instead of every time a
downstream function wants to use the data. This also means invalid JSON
can be detected upfront and a specific error shown immediately instead
of a catch all error when trying to calibrate.
* Using `std::optional` to indicate a calibration failed instead of
status codes.
* Processing videos on separate threads to not block the UI thread and
take advantage of parallelization for camera calibration. (2x speedup on
my laptop)
* Removing the OpenCV calibration option, since mrcal should be better
in every scenario.
* Showing a progress bar for camera calibration.
* Breaking up the massive `DisplayGui` function into separate functions
which contain code for different popups. This also allowed for better
organization and scoping of static variables.
* Renaming variables to make their purpose more clear.
* Displaying the tags present in a field layout when trying to combine
multiple field layouts.
Fixes#7722.
Resync with `mostrobotpy`
This mostly involves the big "ignore almost everything in the HAL
project" and some fixups for the Addressable LED classes.
Required two small hand fixes to get it building over here with bazel,
and with more compiler warnings on.
I also manually zeroed out the `repo_url` field in the toml files to
avoid unnecessary churn whenever it goes from a release build to a
development build. I already did this with `version` field in there, and
will do a follow up PR that updates the copybara script to do it
automatically.
---------
Co-authored-by: Default email <default@default.com>
This adds a type caster for `WPI_String` so that pybind11 can more
easily auto-convert between that and strings. This helps remove the need
to do things like
[this](f1d77244c3)
in the opmodes fixup
This is a high churn change whenever `mostrobotpy` switches from
pointing to `release-2027` to `development-2027`. The value isn't used
by the bazel build scripts, so there is no reason to have a zero impact
change on ~11 files muddying up the synchronization diffs.
In the `allwpilib -> mostrobotpy` direction, we update [this
](https://github.com/robotpy/mostrobotpy/blob/main/rdev.toml) config
file and run
[this](https://github.com/robotpy/mostrobotpy/blob/main/rdev.sh) script
which updates it in that repo during.
I manually did this change in #8503, but this will do it automatically
in the future
I tried to sync `mostrobotpy` with `allwpilib` and was getting a
compilation error I had not seen before when it tried to do the stub
generation (which `allwpilib` does not do).
Luckily, I was able to debug it here by writing some unit tests (i.e.,
having Gemini convert the C++ tests into python) that failed in a
similar way. The main problem was needing to write a custom constructor
for the class and adding a `force_type_casters`. I used `ChassisSpeed`
as my main example, but I did not copy all of the other custom code like
overriding the index operator, `__repr__` operator, feet helpers, etc. I
can gladly add those in.
In the future, we should start enforce a policy that if you add a C++ or
Java unit test, you also have to add a python test. That developer might
have gotten more stuck on the minutia of how to fix it, but this problem
would have at least been caught earlier before it landed.
This makes error messages point directly at the variable use, instead of
on the enclosing AST node:
```
error: `outerCoroutine` may not be in scope
outerCoroutine.yield()
^
error: `outerCoroutine` may not be in scope
consume(x, outerCoroutine);
^
```
instead of
```
error: `outerCoroutine` may not be in scope
outerCoroutine.yield()
^
error: `outerCoroutine` may not be in scope
consume(x, outerCoroutine);
^
```
Sequential group builder had an inverted if condition causing NPEs
Parallel group builder was building parallel groups using an old ctor
signature and creating groups that didn't match what was specified in
the builder
Test coverage has been added for both builder types
Supports Doxygen 1.14, and should be better with Doxygen 1.15 that we
use, compared to the current version.
Improves, but does not fix#8486. The sidebar now covers the search
results, rather then both bleeding through
<img width="1206" height="1969" alt="image"
src="https://github.com/user-attachments/assets/e8c0cefd-a72a-4c41-a5bf-c191752250f4"
/>
We need to wait, or otherwise OpModeRobot will immediately reinstantiate
and re-run the opmode, which is generally undesirable (e.g. for
autonomous).
Fixes#8475.
This got missed in the reorg, and these values aren't actually used for
anything when building in `allwpilb`, but we might as well fix them here
to make the copybara process easier.
Fixes https://github.com/wpilibsuite/allwpilib/issues/8284.
If we have vision updates at the time of the `Reset*` call, we can
correct the translation/rotation of the new odometry pose by adding a
new vision update where:
- `ResetTranslation`: the translation is hard-coded to the new
translation, and the rotation components are set to those of the latest
vision update (prior to clearing the map).
- `ResetRotation`: the rotation is hard-coded to the new rotation, and
the translation components are set to those of the latest vision update
(prior to clearing the map).
Looks like a build failure got lost in the landing order of python
commands and the big opmode change. This makes it compile again, based
on the java / C++ changes from the opmode PR.
User code:
- OpModeRobot used as the robot base class
- LinearOpMode and PeriodicOpMode are provided opmode base classes
- In Java, annotations can be used to automatically register opmode classes
Additional user code functionality:
- OpMode (string) is available in addition to the overall
auto/teleop/test robot mode
- OpMode does not indicate enable (enable/disable is still separate)
- The HAL API uses integer UIDs; these are exposed at the user API level
as well for faster checks
- User code creates opmodes on startup (these have name, category,
description, etc).
DS:
- DS will present opmode selection lists for auto and teleop for
match/practice. During a match, the DS will automatically activate the
selected opmode in the corresponding match period.
- For testing, an overall mode is selected (e.g. teleop/auto/test) and a
single opmode is selected
Future work:
- Command framework support/integration
- Python annotation support
- Unit tests (needs race-free DS sim updates)
- Porting of examples
Co-authored-by: Joseph Eng <91924258+KangarooKoala@users.noreply.github.com>
These are the scripts I've been using to sync between mostrobotpy and
here. I debated putting it in the "source of truth" that is
`mostrobotpy` , but I think it makes more sense here since it already
has bazel set up, and I've also recently added the ability to sync the
`commands-v2` repository, so having it all in one copybara script makes
sense.
This includes a helper python script to make it a little bit easier to
run.
Adding an ack parameter to both set and cancel is cleaner than adding
all the set alarm parameters to the ack function. It also provides an
ack-and-cancel method.
ChassisAccelerations and the drivetrain acceleration types are added in
both Java and C++. `ChassisAccelerations` is basically just
`ChassisSpeeds` but for accelerations!
`DifferentialDriveWheelAccelerations`, `MecanumDriveWheelAccelerations`,
and `SwerveModuleAccelerations` are the acceleration equivalent of the
drivetrain speeds types.
In Java, the `Kinematics` interface now has an additional generic
parameter `A` which represents the accelerations, and
`toChassisAccelerations` and `toWheelAccelerations` methods, which are
implemented the same way as `toChassisSpeeds` and `toWheelSpeeds`.
Protobuf and struct classes were also added for all four classes in Java
and C++.
---------
Signed-off-by: Zach Harel <zach@zharel.me>
Co-authored-by: Joseph Eng <91924258+KangarooKoala@users.noreply.github.com>
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Was caused by checking assignability like`Protobuf<Scheduler,
ProtoMessage>` instead of `Protobuf<Scheduler, ? extends
ProtoMessage<?>>`
This epilogue bug would have also applied to other protobuf-serializable
types
#8385 changed gamepad types to follow SDL_GamepadType, so 20 and 21
(previously `kHIDJoystick` and `kHIDGamepad`, respectively) are no
longer valid constants. This meant that after leaving the disconnected
state of the sim GUI, `GamepadType.getGamepadType()` would return null
(since it didn't match any constants). Since there aren't analogous
generic joystick and gamepad constants anymore, this PR changes
GlfwSystemJoystick and KeyboardJoystick to both unconditionally report
as kStandard.
This also updates the GenericHID.SetRumble doc comment to reflect the
two new types of rumble and changes some switch labeled statement groups
to use switch rules instead. If we want to keep on using switch labeled
statement groups (e.g. for consistency with C++, though
GenericHID::SetRumble currently uses if-else), then I could drop the
last change- I just made it since GenericHID.setRumble() previously used
switch rules and general switch rules are nice since there's no risk of
fall-through.
It was possible for the alarm to fire between the set alarm and ack,
resulting in a hang on next wait. It's not possible to ack before set
alarm due to a race in sim step timing, so the fix is to provide an
atomic ack and set alarm; the easiest way to implement this in the API
was to change ack to optionally also set the alarm again.
This changes the HAL notifier interface to:
- Use wpiutil signal objects. This means waiting is done through the
`WPI_WaitObject` API instead of a dedicated function and allows for
higher level code to simultaneously wait on notifiers and other events.
- Interval timers are supported at the HAL layer
- Handlers are now required to acknowledge notifications. This is
invisible to users unless they're directly using the HAL API.
- For interval timers, an overrun count is maintained to detect if the
handler didn't acknowledge
The underlying implementation still uses condition variables for the
actual waiting. In basic testing using this approach seemed to be lower
jitter than timerfd.
Currently, the simulation and systemcore implementations are nearly
identical except for a few additional sim hook bits. This could be
refactored, but keeping them separate may make sense to keep the
systemcore implementation easy to read and reason about, or if we ever
choose to use a different underlying timer implementation on systemcore.
The simulation side API is unchanged in form but does change in
function--waiting for notifiers now only waits for currently running (or
newly signaled) notifiers to acknowledge. To avoid a race condition in
sim stepTiming, users of the low level API must make any alarm updates
(especially for one-shot alarms) prior to acknowledging the previous
alarm.
The only current use of the interval timer feature is the `Notifier`
class. The `TimedRobot` implementation still uses a single notifier and
its own interval timing logic to ensure consistent callback order. Using
separate notifiers for each user-level interval would substantially
increase complexity. `Watchdog` also doesn't use the interval timer, as
it's looking for an amount of time since the last `set` call rather than
a recurring interval time.
To reduce flicker, the sim GUI uses a fade out when a timeout goes from
set to unset.
This fixes tsan for wpilib and commands, and also fixes some spurious
test failures.
* Moved makeWhiteNoiseVector() to random.Normal.normal()
* Moved isControllable() and isDetectable() to system.LinearSystemUtil
* Renamed makeCostMatrix() to costMatrix() (Java)
* Renamed makeCovarianceMatrix() to covarianceMatrix() (Java)
* Renamed MakeCostMatrix() to CostMatrix() (C++)
* Renamed MakeCovMatrix() to CovarianceMatrix() (C++)
* Removed deprecated poseTo3dVector(), poseTo4dVector(), poseToVector()
* Removed clampInputMaxMagnitude()
* We don't use it, and Eigen has this functionality built in via `u =
u.array().min(u_max.array()).max(u_min.array());`
* Simplified implementation of desaturateInputVector()
#8363 split all the cross-compilation into separate jobs, however these
jobs are still also building the world (including the tests) targeting
the host.
Since `//:publish` and its dependencies are transitioned to target the
desired platforms for each artifact, `bazel build //:publish` in the CI
jobs that aren't running tests to only build what we actually care about
in these jobs.
This saves around 1 to 1.5 minutes for each cross-compile job with 100%
cache hit rates.
Now rgb() and color constants are supported.
Changed from constructor to fromString() factory function to enable
directly returning color constant values.
I'm not entirely sure why Java header compilation is disabled for the
macOS build. But this option will be causing rebuilds to happen more
often than strictly necessary.
[Turbine](https://github.com/google/turbine) takes Java class sources
and spits out .class files with all method bodies, and private fields
and methods stripped. This provides a .jar with sufficient information
on the classpath to build dependent Java libraries without depending on
the implementation in the build graph.
`--local_ram_resources=value` and `--local_cpu_resources=value` have
been replaced by `--local_resources=[memory|cpu]=value`, so the Bazel
README is updated to recommend the new form.
The update yaml step _might_ cause changes that would affect the build
file generation. Since `bazel run //:write_robotpy_update_yaml_files`
runs them all at once, user that was using the github action to fix
their python stuff would end up having to run it twice.
By running the steps individually in series, this should be able to get
it in one swoop.
These were added in Windows 10 1703. Technically Windows 10 in general
is out of support, but versions of Windows 10 older than that are _well_
out of support. And we do directly link to other APIs that are newer. So
no need to do the dynamic linking.
The order of the Swerve Modules in the m_odometry.Update call needs to
match the order they are defined in the creation of the kDriveKinematics
object.
Fixes#8386
Was already working on this when more people started hitting issues so I
prioritized getting this PR up. This updates the wrapper script to look
for the 3 biggest categories of "everything should be fine if you run
this step first" tool failures.
Co-authored-by: Gold856 <117957790+Gold856@users.noreply.github.com>
Co-authored-by: David Vo <auscompgeek@users.noreply.github.com>
Support joystick outputs, including Rumble and LEDs.
Also requires an update to Joystick descriptors, as that has also
changed in mrccomm to support showing what outputs are supported.
Squashes the following warning:
```
DEBUG: /home/buildbuddy/workspace/output-base/external/rules_jvm_external/private/rules/coursier.bzl:775:18:
Found duplicate artifact versions
com.google.code.gson:gson has multiple versions 2.13.1, 2.10.1
Please remove duplicate artifacts from the artifact list so you do not get unexpected artifact versions
```
After replacing the remaining include guards with `#pragma once`, I was
able to merge all the wpiformat configs into one file in the repo root.
This should make the config easier to reason about and maintain in the
future.
We are running out of disk space. If we split the
build up more in parallel, that'll use less space in each build.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Offline conversations have pointed out that the bazel output is very noisy upon a failure. The -k that was there for a while was recently deleted in another PR, and this one removes --verbose_failures. --verbose_failures prints all of the command line arguments, which can be quite lengthy and make it harder to find the actual compiler error.
This also removes the -vv from the clang-tidy step. I have found it very hard to find the actual errors when its printing out all of the debug information.
This uses all the infrastructure we put together earlier to actually build and publish all the artifacts.
We might still want to adjust what is built by default to control CI times.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Co-authored-by: PJ Reiniger <pj.reiniger@gmail.com>
Co-authored-by: David Vo <auscompgeek@users.noreply.github.com>
This is owned by WPI, so we can make it as big or small as we want.
This lets us check in more of the bazel build.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
The spiraling issue occurs when the vision rotation standard deviation is very high relative to the odometry rotation standard deviation and the vision measurements have a large rotation error. (Scaling the rotation component of a twist without scaling the translation component causes the direction of overall translation to change, leading to spiraling around (either towards or away) the vision measurement instead of moving towards it.) Using a transform instead of a twist avoids this issue.
In general, scaling twist components is more mathematically correct than scaling transform components. However, although twists are correct for modeling uncertainty in an odometry-only pose estimate, they are not correct for the difference between the odometry-only pose estimate and a vision measurement. Since neither twists nor transforms are completely correct (and the pose estimator as a whole is not mathematically correct), but using transforms can guarantee that the pose estimate approaches the vision measurement (instead of potentially spiraling away), they are the least bad option.
These are out of date, and nothing uses them in allwpilib; wpilibpi used
them but a more major upgrade is needed there.
While we may in the future add integrated support for e.g. an integrated
NT viewer, it's unlikely we would use these versions.
CoroutineYieldInLoopDetector
This checks for while loops where coroutines are in scope but without calling a blocking method on at least one of those coroutines:
```
drivetrain.run(theCoroutine -> {
while (drivetrain.getDistance() < 10) { // ERROR: "Missing call to `theCoroutine.yield()` inside loop"
drivetrain.setSpeed(1);
}
});
```
Note that, because we assume most looping constructs in commands will use while loops, we don't check for-loops, for-each loops, or do-while loops.
This check can be disabled with `@SuppressWarnings("CoroutineYieldInLoop")`
CodeAfterCoroutineParkDetector
Essentially acts like the Java compiler's check for code after a while (true) loop, but for coroutine.park():
```
drivetrain.run(theCoroutine -> {
drivetrain.setSpeed(1.0);
theCoroutine.park();
drivetrain.setSpeed(0.0); // ERROR: "Unreachable statement: `theCoroutine.park()` will never exit"
});
```
This check can be disabled with `@SuppressWarnings("CodeAfterCoroutinePark")`
IncorrectCoroutineUseDetector
Checks for usage of captured (outer) coroutine parameters and assignments to fields.
```
drivetrain.run(outer -> {
outer.await(arm.run(inner -> {
outer.yield(); // ERROR: "Coroutine `outer` may not be in scope. Consider using `inner`"
}))
});
```
This check can be disabled with `@SuppressWarnings("CoroutineMayNotBeInScope")`
```
private Coroutine coroutineField;
drivetrain.run(co -> coroutineField = co); // ERROR: "Captured coroutines may not be stored in fields"
```
This check can be disabled with `@SuppressWarnings("CoroutineCapture")`
clang-format 21 made some formatting changes. Since wpiformat's stdlib
task was removed, I removed NOLINT comments for it and removed some
std:: prefixes it added to comments.
Adds snippets demonstrating ProfiledPIDController usage with
SimpleMotorFeedforward using the two-parameter calculate() method
(currentVelocity, nextVelocity).
These snippets will be used in frc-docs to document the recommended
feedforward pattern with ProfiledPIDController.
Co-authored-by: sciencewhiz <sciencewhiz@users.noreply.github.com>
Instead of just having a max count for joystick values, there's an available mask of values. This is because in the future we're expecting there to be holes in the list of available buttons and axes. This updates everything to support that scenario.
Also, Joystick buttons, axes, and POVs all now start at 0 instead of 1.
* [bazel] Package headers in ntcoreffi correctly
The original package includes headers from ntcore and wpiutil, so
include those too.
* Merge in new 2027
GitOrigin-RevId: ac60fd3cf4a24023184376687da28373d14b781a
This mirrors the robotpy files for the following projects:
- apriltag
- datalog
- hal
- ntcore
- romiVendordep
- wpilibc
- wpimath
- xrpVendordep
This excludes cscore and the halsim wrappers for at this time.
NOTE: This does not hook these projects up to the build system, just simply mirrors the files. The building will take place in a follow up PR to make it easier to review the changes necessary to build.
The framework fundamentally relies on the continuation API added in Java 21 (which is currently internal to the JDK). Continuations allow for call stacks to be saved to the heap and resumed later.
The async framework allows command bodies to be written in an imperative style. However, an async command will need to be actively cooperative and periodically call coroutine.yield() in loops to yield control back to the command scheduler to let it process other commands.
There are also some other additions like priority levels (as opposed to a blanket yes/no for ignoring incoming commands), factories requiring names be provided for commands, and the scheduler tracking all running commands and not just the highest-level groups. However, those changes aren't unique to an async framework, and could just as easily be used in a traditional command framework.
Caused by the doxygen gradle plugin attempting to download 1.10.0 (presumably its default version) from artifactory because the 1.12.0 config is only applied on x86_64 platforms. Just fixing that isn't enough, however; on mac, the plugin would fail to extract the dmg. We need to fall back to a global installation on the PATH for the plugin to find, preferentially using that instead of a failed attempt to download and extract the dmg.
Upstream no longer seems to have the commit we were pointing to. We'll
just use the tag since that hasn't changed since the official release
announcement.
Adds a `@NoDiscard` annotation that can be placed on methods to guarantee their return values are used and on types to guarantee that any method returning that type uses the return value.
Methods that call `@NoDiscard`-annotated functions can add a `@SuppressWarnings("NoDiscard")` or `@SuppressWarnings("all")` annotation (or annotation on the class declaring that method) to silence the compiler error warnings.
SystemCore doesn't directly support Servos. It would be possible to still use a Servo Power Module, but those are fairly rare, and we should probably use a different class for that case, so users don't attempt to hook a servo directly up to systemcore. That will depend on what happens with the rules in 2027.
Rev Servo Hubs are a current working replacement for systemcore users.
We build docs in three different places, which is annoying to deal with, and it means we build docs two more times than necessary. Now, docs are built just once in the main Gradle workflow, with warnings promoted to errors, eliminating the need for the separate job in lint-format.yml. The uploaded docs artifact is then unpacked and commited to the GitHub Pages repo like normal.
The deprecation message was:
```
The `archives` configuration added by the `base` plugin has been
deprecated and will be removed in Gradle 10.0.0. Adding artifacts to the
`archives` configuration will now result in a deprecation warning. If
you want the artifact built when running the `assemble` task, you should
add the artifact (or the task that produces it) as a dependency of the
`assemble` task directly.
val specialJar = tasks.register<Jar>("specialJar") {
archiveBaseName.set("special")
from("build/special")
}
tasks.named("assemble") {
dependsOn(specialJar)
}
```
For parity with struct-serializable types.
Change struct serialization to only apply to types with a public static final <type> struct field, instead of relying only on the marker interface (which is not always followed). Doing this allows fallthrough to the protobuf handler for types with dynamic structs but static protobuf serializers.
In the recent gradle or gradle dependencies update, the documentation
zips were being published as documentation-version-unspecified, where
the unspecified was coming from archiveVersion. It looks like we use a
different method of setting the version, so make sure that
archiveVersion is empty
libprotobuf is a very annoying dependency to deal with, and with the switch to nanopb for generated C++ code, libprotobuf is only used for dynamic decode in the GUI apps. libprotobuf has been swapped out with upb, a much smaller C-based library that supports reflection and can therefore do dynamic decode. This means we can remove the libprotobuf dependency and stop dealing with build issues because of it.
Unlike armv7, aarch64 doesn't have alignment assertions for SIMD instructions. The compiler output between the aligned and unaligned variants is the same.
The UKF test was calling `.value()` on an implicit
`units::millisecond_t` type assuming it was `units::second_t`.
I normalized the rest of the dt declarations while I was at it.
I upgraded all plugins I could see except org.ysb33r.doxygen. 2.0 made
breaking changes, and I couldn't figure out how to migrate.
Most of the changes are for suppressing new linter purification rites.
```
> Task :wpilibcExamples:checkCommands
Script '/home/tav/frc/wpilib/allwpilib/shared/examplecheck.gradle': line 135
Invocation of Task.project at execution time has been deprecated. This will fail with an error in Gradle 10.0. This API is incompatible with the configuration cache, which will become the only mode supported by Gradle in a future release. Consult the upgrading guide for further information: https://docs.gradle.org/8.14.3/userguide/upgrading_version_7.html#task_project
at examplecheck_4wsg1s37eigy9vs5arzst20ga$_run_closure5$_closure16$_closure17.doCall$original(/home/tav/frc/wpilib/allwpilib/shared/examplecheck.gradle:135)
(Run with --stacktrace to get the full stack trace of this deprecation warning.)
```
Moving the project access outside the doLast block makes it occur at
confguration time instead.
It is useful when programmatically interacting with DataLogs to be able to retrieve an record's associated metadata (entry name, type, and metadata string), but the only reference to an entry that a record contains is the id. DataLogReaderThread already builds a map of id->DataLogReaderEntry, but it was unexposed until now.
This pulls down the prebuilt ceres libraries and uses them with Bazel to
build and test wpical.
Do note that bazel looks up artifacts used for testing differently than
the other build systems. It wants you to use its runfiles API to find
the dependencies reliably. Add a function to look up the paths for
files, and use runfiles only when building with Bazel to maintain
compatibility with other languages.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
This makes it so rules_jvm_external also doesn't package up all the
opencv class files into the final published packages. And is simpler to
maintain.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
We've got javadocs for each module, but wpilib has 1 for everything.
Build that too using rules_jvm_external.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Windows is proving to be a *lot* slower than everything else. I supect
this is because we are building both arm64 and x86 every time, which
ends up being twice the work. Leave those builds in place, but skip
doing them in CI. This should be a 2x speedup when building Windows
code.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Tested a bazel build of //... on a (relatively) clean Debian system.
It feels like there is a more pricnipled list we could provide (e.g.,
libglfw3-dev), although I think most of those would also end up
installing more than necessarily required.
I could have sworn that we were only splitting debug symbols on x86.
The most recent tests I have done suggest that is backwards. This is
easy to reconfigure later if needed.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
This adds shortcuts for static only, shared only, and binary projects.
The end result is that it is pretty easy from here to publish all the
arifacts needed.
Adds methods to compute the dot and cross products between Translation2ds and Translation3ds, as well as methods to compute the square of Distance and Norm, which allows avoiding some calls to sqrt in many cases.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
This sets us up to properly depend on opencv, by introducing the new
helpers, @rules_bzlmodrio_toolchains//cc:cc_shared_import.bzl to import
the shared libraries correctly from opencv.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
This follows the gradle build accurately. Gradle copies debug symbols
into a second file (libfoo.so.debug) and links it back into the .so
file. Disable this behavior when gradle doesn't do it today.
Also, name everything correctly. When building debug builds, most
libraries get a 'd' at the end of them. Do that here too.
wpimath otherwise quickly gets too many symbols. Instead, gradle
exports only some of the symbols from protobuf files automatically, and
then manually exports the math operations. Do that here too.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Since they are in different directories, they need to be special cased
This is needed to support wpilibsuite/WPILibInstaller-Avalonia#492,
since those are currently handled by special scripts.
Gradle publishing does not capture all of the source files that are used during a build. This should get most of them, and get it equivalent to what bazel pushes out.
Adds S3SigmaPoints based on MerweScaledSigmaPoints. In addition, restructures UnscentedKalmanFilter to support different sigma point generators and provides MerweUKF and S3UKF for convenience when working with either kind of filter.
S3UKFTest is copied from MerweUKFTest (which is a rename of UnscentedKalmanFilterTest). Curiously, however, in Java the original tolerance used in MerweUKFTest.testDriveConvergence() for the final rotation was too low for S3UKFTest, so the tolerance is increased from 0.000005 (5e-6) radians to 0.00015 (1.5e-4) radians. However, the C++ version still uses the original tolerance. (This difference is probably because Java uses a final rotation of 5.846 degrees while C++ uses a final rotation of 5.846 radians)
Closes#8072.
Breaking changes:
- (C++) UnscentedKalmanFilter has a new template parameter for the sigma point generator type.
- (Java) UnscentedKalmanFilter has an additional parameter to every constructor providing an instance of a sigma point generator.
- (C++) int MerweScaledSigmaPoints.NumSigmas() has been replaced with constexpr int MerweScaledSigmaPoints::NumSigmas.
- (C++) The second parameter of SquareRootUnscentedTransform has been changed from States to NumSigmas.
The generator was calling a binary of the wrong architecture and failing
internally, but passing the build (incorrectly). Explode right away.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Pull in some of the fixes merged into the various dependencies. While
we are here, move all the downloads up to the top of the file so they
download in parallel.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
Thad says this is a compiler bug, rather than fight it, let's use a new
code path through the compiler.
ERROR: /home/austin/local/allwpilib3/wpilibcExamples/BUILD.bazel:50:12: Compiling wpilibcExamples/src/main/cpp/examples/I2CCommunication/cpp/Robot.cpp failed: (Exit 1): gcc failed: error executing CppCompile command (from target //wpilibcExamples:I2CCommunication-test) /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG -ffunction-sections ... (remaining 234 arguments skipped)
Use --sandbox_debug to see verbose messages from the sandbox and retain the sandbox build root for debugging
In file included from /usr/include/c++/12/ios:40,
from /usr/include/c++/12/istream:38,
from /usr/include/c++/12/sstream:38,
from /usr/include/c++/12/chrono:41,
from bazel-out/k8-opt/bin/wpilibc/_virtual_includes/wpilibc.static/frc/TimedRobot.h:7,
from bazel-out/k8-opt/bin/wpilibcExamples/_virtual_includes/I2CCommunication-examples-headers/Robot.h:10,
from wpilibcExamples/src/main/cpp/examples/I2CCommunication/cpp/Robot.cpp:5:
In static member function 'static constexpr std::char_traits<char>::char_type* std::char_traits<char>::copy(char_type*, const char_type*, std::size_t)',
inlined from 'static constexpr void std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::_S_copy(_CharT*, const _CharT*, size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' at /usr/include/c++/12/bits/basic_string.h:423:21,
inlined from 'static constexpr void std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::_S_copy(_CharT*, const _CharT*, size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' at /usr/include/c++/12/bits/basic_string.h:418:7,
inlined from 'constexpr std::__cxx11::basic_string<_CharT, _Traits, _Allocator>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::_M_replace(size_type, size_type, const _CharT*, size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' at /usr/include/c++/12/bits/basic_string.tcc:532:22,
inlined from 'constexpr std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::assign(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' at /usr/include/c++/12/bits/basic_string.h:1647:19,
inlined from 'constexpr std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]' at /usr/include/c++/12/bits/basic_string.h:815:28,
inlined from 'virtual void Robot::RobotPeriodic()' at wpilibcExamples/src/main/cpp/examples/I2CCommunication/cpp/Robot.cpp:27:77:
/usr/include/c++/12/bits/char_traits.h:431:56: error: 'void* __builtin_memcpy(void*, const void*, long unsigned int)' accessing 9223372036854775810 or more bytes at offsets -4611686018427387902 and [-4611686018427387903, 4611686018427387904] may overlap up to 9223372036854775813 bytes at offset -3 [-Werror=restrict]
431 | return static_cast<char_type*>(__builtin_memcpy(__s1, __s2, __n));
| ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
cc1plus: all warnings being treated as errors
It's only syntactic sugar over the CommandScheduler's schedule method and creates a footgun because it’s too obvious to try to use in incorrect places.
Co-authored-by: Starlight220 <53231611+Starlight220@users.noreply.github.com>
* `-Wfixed-enum-extension` was replaced with `-Wc23-extensions`
* Removed unused private variables in SysId
* Suppressed `-Wnontrivial-memcall` in imgui.h and imgui_internal.h
Ensures java deprecated notation is paired with javadoc and vice versa.
Adds javadoc deprecation for MecanumControllerCommand, ArmFeedForward,
ElevatorFeedforward, and MecanumDriveMotorVoltages
Fixes#7736
Supersedes #7737
Co-authored-by: Joseph Eng <91924258+KangarooKoala@users.noreply.github.com>
SimpleMotorFeedforward::calculate(velocity) was not updated to account for the removal of calculate(velocity, acceleration), so it would pass currentVelocity = velocity and nextVelocity = 0, resulting in negative outputs in many scenarios.
A noteworthy change is the replacement of the `dp.startswith(os.path.join(".", "subdir"))` pattern. pathlib doesn't offer something with similar semantics besides `match` and `full_match`, so there's now a helper function that replicates the behavior.
Other notable changes include the addition of type annotations to ensure code correctness, using == to check file names instead of `endswith` for clarity (`endswith` is still used to check extensions), manual walking and copying being refactored in googletest, json, memory, nanopb, protobuf, and sleipnir to use `walk_cwd_and_copy_if`, and matching functions being shortened to the point where they can just be inlined into the lambda.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Co-authored-by: David Vo <auscompgeek@users.noreply.github.com>
These were apparently a meme about state being hard to manage rather
than a statement about the code itself. I spent a while trying to find
some complex logic this comment was alluding to that would indicate why
it's "a nightmare to manage".
This reverts commit 3dee19a435.
This was merged without sufficient review or discussion as to whether these units are value-add for the Java units library.
Addresses an issue where certain USB cameras, specifically the ArduCam OV9281, would freeze when attempting to stream on macOS.
The previous logic started the AVCaptureSession (startRunning) before locking the device for configuration (lockForConfiguration). While this works for many cameras, it causes the OV9281 to become unresponsive.
Further investigation revealed:
- Moving startRunning to after unlockForConfiguration resulted in macOS overriding the custom format and frame rate settings applied within the lock.
- The reliable solution, inspired by findings shared in the community (e.g., Stack Overflow), is to lock the device, apply the configuration, start the session, and then unlock the device.
This commit reorders the operations within deviceStreamOn in UsbCameraImplObjc.mm to follow the sequence: lockForConfiguration -> apply settings -> startRunning -> unlockForConfiguration. This ensures the desired camera configuration is applied correctly without causing device freezes on problematic hardware like the OV9281.
This has the same effect but makes it so any user code returning CommandPtr can't discard a returned command.
Signed-off-by: Eric Ward <ezeward4@gmail.com>
When adding struct schemas, the current logic is to add the parent/outer schema, and then add the schemas for any nested inner schemas. This reverses that order to make it easier for tools to process.
Matches C++ logic.
Reduces nesting by returning when the value is within the deadband.
Adjusts the algorithm to handle large values of maxMagnitude naturally (instead of needing a separate check).
Reformats the math comments.
This enables frc-docs to use RLIs for things that are currently in-line
code blocks, and ensures they compile, which is important with the 2027
breaking changes coming. They are kept separate from the examples to
ensure they don't polute the VSCode examples finder.
Adds the Encoder snippets used in the frc-docs Encoder article as the
first instance of this.
Adds a Kaitai Struct definition for the WPILOG format. This can be used to generate code to read/write data log files without needing to build out a parser/serializer by hand. Or just an additional resource for readers to help understand the WPILOG format.
Throughout the code the state sqrt covariance S and innovation covariance Sy are maintained as upper triangular cholesky factors of those covariance matrices. The original paper defines P=S*S', so S should be lower triangular. The functions in the paper reflect this. In the code implementation, the sqrt covariance matrices are upper triangular, but the algorithm expects them to be lower triangular.
This bug was likely missed because the incorrect version of the filter is able to converge for some systems where all the states are observed, and the test case is set up such that all states are observed.
To fix the bug, a couple things needed to be changed:
all instances of rankUpdate() needed to be changed to use the lower triangular cholesky factor,
In the unscented transform, when S is found via QR decomposition, we need to take the transpose because R is upper triangular,
P() and SetP() functions need to be modified to be P=S*S' instead of P=S'*S, and P.llt().matrixL() instead of P.llt().matrixU() respectively.
Each part of the algorithm has also had the comments changed to clarify exactly which equation from the paper it implements.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Currently the major DataLog backend API (reading and writing) is split between wpiutil and glass. In the interest of allowing code that wants to use these APIs to not need to link to glass and declutter wpiutil, all of those APIs are moved to a new library named "datalog".
Signed-off-by: Jade Turner <spacey-sooty@proton.me>
Co-authored-by: Jade Turner <spacey-sooty@proton.me>
Co-authored-by: Gold856 <117957790+Gold856@users.noreply.github.com>
A Discord user reported that StackWalker gives blank stacktraces.
MSVC's C++23 support is unstable, so we can't use std::stacktrace yet.
In the meantime, we can just return an empty string and remove the
unmaintained StackWalker library and its hacky upstream_utils script.
I was getting:
external/arm_frc_linux_gnueabi_repo/bin/../arm-nilrt-linux-gnueabi/sysroot/usr/lib/gcc/arm-nilrt-linux-gnueabi/12/../../../../../../../arm-nilrt-linux-gnueabi/bin/ld: bazel-out/k8-opt--roborio/bin/external/com_github_wpilibsuite_allwpilib/wpinet/libwpinet.static.a(fs.o): undefined reference to symbol 'dlsym@@GLIBC_2.4'
external/arm_frc_linux_gnueabi_repo/bin/../arm-nilrt-linux-gnueabi/sysroot/usr/lib/gcc/arm-nilrt-linux-gnueabi/12/../../../../../../../arm-nilrt-linux-gnueabi/bin/ld: external/arm_frc_linux_gnueabi_repo/bin/../arm-nilrt-linux-gnueabi/sysroot/lib/libdl.so.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
This fixes that error for me.
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
The magic static adds yet another thing that needs to be reset if you
want to run a unit test with a completely reset wpilib state. Use the
existing Sendable static map to store the data instead.
This leaks memory if ResetSmartDashboardInstance is called.
* Move units into API docs instead because suffixes make user code verbose and hard to read
* Rename trackWidth to trackwidth
* Make ultrasonic classes use meters instead of a mix of m, cm, mm, ft,
and inches
Many LED strips use different color order (GRB in particular is common).
This makes the change at the HAL level. This solves 2 problems; first, no code needs to change in the high level drivers, which was challenging for C++, and second, simulation will behave properly as no conversion is needed. The HAL will accept an array of data objects in the same order no matter what the selected output order is, and will convert before sending it to the FPGA for output.
To accomplish this, NEON bulk load/interleave instructions are utilized. The low level implementation (load, store, and alignment functions) come from the Simd Library. The high level implementations are inspired by the image conversion functions in the simd library, but have diverged significantly.
Much of the implementation uses templates and inlined functions rather than runtime parameters; This is a trade off between the size of the generated code and the amount of function calls done at runtime. Currently, the entire conversion operation is inlined.
Small values of kₐ make the iterative solver ill-conditioned. This
change reverts to the constant-acceleration feedforward in that case. It
gives _very_ bad results (hence why we added the iterative solver in the
first place), but it's better than hanging.
```
TEST(ArmFeedforwardTest, CalculateIllConditioned) {
constexpr auto Ks = 0.5_V;
constexpr auto Kv = 20_V / 1_rad_per_s;
constexpr auto Ka = 1e-2_V / 1_rad_per_s_sq;
constexpr auto Kg = 0_V;
frc::ArmFeedforward armFF{Ks, Kg, Kv, Ka};
// Calculate(currentAngle, currentVelocity, nextAngle, dt)
CalculateAndSimulate(armFF, 0_rad, 0_rad_per_s, 2_rad_per_s, 20_ms);
}
```
This produces 1 V and doesn't accelerate the system at all. Using
nextVelocity instead of currentVelocity in the feedforward outputs 41 V
and still only accelerates to 0.4 rad/s of the requested 2 rad/s.
I picked the kₐ cutoff by increasing kₐ until the iterative solver
started converging.
Fixes#7743.
Instead of only providing per(TimeUnit)
Useful for making conversion factors easier, eg `Inches.of(10).per(Rotation)` vs `Inches.of(10).per(Rotation.one())`
Update VelocityUnit.one() and VelocityUnit.zero() to return Velocity objects instead of generic Measure<? extends VelocityUnit<D>>; VelocityUnit is final, so the wildcard generic is unnecessary, and this makes the generated `per` functions possible for this type
This new feature allows users to combine multiple Apriltag layouts. This can be useful for fields where the apriltags are split into two or more sections: (red/blue side, grouped together by task, etc.)
This reverts commit 469bb3290d.
The approach used has issues due to the fact unit symbols often have a literal / in them,
which causes issues with NT topic visualization.
A better approach would be to use topic metadata.
Column in Field Drawings is labeled X-Rotation, but I believe it should be Y-Rotation so have reflected that here. We'll fix in a TU if this is correct.
This changes the way deferred proxy is implemented to not use the
deprecated ProxyCommand constructor.
This function serves a good purpose that should be kept IMO. The
constructor was confusing but this is just good syntactic sugar over
`defer(() -> supplier.get().asProxy())`.
Signed-off-by: Jade Turner <spacey-sooty@proton.me>
This ensures that complete uniformity in how the generation scripts are run. All dependencies and scripts are set up in the exact same way, each time. The old pregen_all script has been removed and moved into the composite action to ensure failed scripts will always fail the job.
This makes the logic clearer in the actual binding methods and will hopefully make it less annoying to make changes such as allowing control over initial edges.
Also changes Java to use previous and current to match C++.
ProceduralStructGenerator's genRecord and genEnum were package-private, and only extractClassStruct was made public.
However, this package private visibility rendered them unable to be used by the rest of wpilib(and advanced users).
Here, ProceduralStructGenerator is split into 2 classes: StructGenerator(which generates structs) and StructFetcher(the new namespace for extractClassStruct). In addition, genRecord and genEnum have been made public methods.
It now uses SQP for problems without inequality constraints, which is
faster.
main:
```
[ RUN ] Ellipse2dTest.DistanceToPoint
0.203 ms
[ OK ] Ellipse2dTest.DistanceToPoint (0 ms)
[ RUN ] Ellipse2dTest.FindNearestPoint
0.019 ms
[ OK ] Ellipse2dTest.FindNearestPoint (0 ms)
```
upgrade:
```
[ RUN ] Ellipse2dTest.DistanceToPoint
0.197 ms
[ OK ] Ellipse2dTest.DistanceToPoint (0 ms)
[ RUN ] Ellipse2dTest.FindNearestPoint
0.015 ms
[ OK ] Ellipse2dTest.FindNearestPoint (0 ms)
```
This is easier to type and follows the naming of Pose2d::Nearest().
Since Ellipse2d and Rectangle2d were added for the 2025 season, we don't
need to add deprecation notices.
The Raspberry Pi 5 is fast enough that we no longer need it.
```
Running ./build/DAREBench
Run on (4 X 2400 MHz CPU s)
CPU Caches:
L1 Data 64 KiB (x4)
L1 Instruction 64 KiB (x4)
L2 Unified 512 KiB (x4)
L3 Unified 2048 KiB (x1)
Load Average: 0.47, 0.72, 0.45
***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
-------------------------------------------------------------------------------
Benchmark Time CPU Iterations
-------------------------------------------------------------------------------
DARE_WPIMath_Dynamic 34.4 us 34.4 us 20315
DARE_WPIMath_NoPrecondChecks_Dynamic 21.7 us 21.7 us 32266
DARE_WPIMath_Static 15.2 us 15.2 us 45878
DARE_WPIMath_NoPrecondChecks_Static 7.84 us 7.84 us 89316
DARE_SLICOT 79.4 us 79.4 us 8789
DARE_Drake 34.9 us 34.9 us 20074
```
Support custom loggers for generic types
Improve error messaging for custom loggers with generic type arguments
Consistently start all epilogue processor prints with "[EPILOGUE]"
Was causing bugs when combined with patterns that need to read back from the buffer (eg masks and overlays)
Co-authored-by: Joseph Eng <s-engjo@bsd405.org>
This reverts commit d1de7663d3.
Intellisense is still broken on Windows Athena target with the error
`incomplete type "Eigen::Matrix<double, 3, 3, 0, 3, 3>" is not allowed`.
Due to how submessages are encoded (with a length prefix), nanopb currently does the encoding twice. It encodes once to get the length to write, then writes the length, then reencodes the entire message a 2nd time.
This results in a requirement that each encode always encodes the same. Generally, this is fine, but it'd be nice to not make this a requirement.
The double encode also requires going through the entire set of fields again, which has the possibility to be slow.
Instead of doing this, write to a temporary SmallVector. Then we can just encode the length of that buffer, and do a memcpy into primary stream. Theoretically in most cases, this should be much faster.
The Google C++ protobuf implementation has issues with dynamic linkage across DLL boundaries because it uses global variables. It also has a compile-time dependency because the protoc version must exactly match the libprotobuf version. Using nanopb with a customized generator fixes both of these issues.
Co-authored-by: Gold856 <117957790+Gold856@users.noreply.github.com>
This refactors Alert in both c++ and java to fix the issues with the current c++ implementation and improve performance.
Currently, constructing an Alert adds it to a list of Alerts with the same group and type. Activating an alert sets a flag on the alert. When the SendableAlerts is polled (GetStrings), the entire list is iterated over, filtered, and the filtered list is sorted by timestamp. This leads to a worst case O(m + nlog(n)) time complexity for GetStrings, where m and n are the count of total constructed alerts active alerts respectively. It also allocates intermediate data structures to hold the active alert strings for sorting.
This changes the implementation to improve the performance of GetStrings, by shifting the sorting overhead to Alert.Set
Constructing the Alert only initializes the alert's initial state, and initializes the SendableAlerts for the group if it is not already initialized.
Activating or deactivating an alert sets an internal flag for state tracking, and inserts or removes a structure containing the timestamp and text into a self-sorting data structure (std::set, TreeSet) containing other active alerts with the same group and type. (worst case O(log(n))
Now, SendableAlerts.GetStrings only has to iterate over the structure and copy the strings to the returned array. (amortized O(n))
This also fixes the c++ implementation by removing the need for SendableAlerts to directly access the Alert.
This also adds a helper method to SendableRegistry to force initialization of the instance to prevent static initialization ordering issues.
These test fixtures were adding complexity while only saving one line of
object initialization per test. Our other tests like this just make the
object at the top of each test.
After a struct-type field descriptor had offsets calculated more than once, IsBitField would return true, causing the second call to CalculateOffsets to calculate incorrect offsets.
We were building huge amounts with bazel we were already building
otherwise. We've been getting heavily backlogged in CI because of the amount
of CI jobs we are running versus our maximum runners quota (particularly on Mac), so this really isn't worth it right now.
As string_view operations on std::map<std::string> won't be integrated
until C++26, placeholder implementations are used which are less efficient
in a couple of situations (e.g. insert with hint).
Previously users would have to keep track of dynamically created CommandPtrs. This adds an ownership-taking version of schedule which places the command in a temporary store in the scheduler. The command will be freed when the command's lifecycle ends.
Instead of only logging based on the declared type, loggers will be smarter and do instanceof checks to determine what logger should be used.
Note that diamond inheritance may cause unexpected behavior for non-logged classes that implement multiple logged interfaces.
eg "getFoo()" will now be logged as "Foo", or "m_leftMotor" as "Left Motor"
It is now a compilation error to reuse the same logged name for multiple elements (since whatever is declared last would overwrite anything logged before it)
Do not log record fields (just use the accessors). This also fixes an issue where records could never be logged due to identical member and accessor names
Also skips toString, hashCode, and clone methods when generating loggers
Splitting the files didn't help readability or save compilation time and
it confused contributors. Merging them is also in line with how C++
modules will be written.
The changes in #7189 caused an ambiguity between multi-subscribers and
normal subscribers, because the handle type no longer is sent to the network.
Multi-subscribers now go to the network with negative UIDs, normal
subscribers are positive UIDs. UID 0 is never used.
Each client has an incoming queue of ClientMessage.
In the read callback:
- Parse and process only ping messages and a limited number of messages;
anything else will get put into the queue and not processed
- If we queued some messages, we tell the network we stopped reading; this will
result in back-pressure if we are reading too slowly. We also start an idle
handle to process the queued messages.
In the idle handle callback:
- For each client, process just a few pending messages. This is performed in
round-robin fashion across all clients with pending messages
- When a client's queue becomes empty, we re-enable the network read
- When all client queues are empty, we stop the idle handle (so we don't spin)
For local client processing, we use round-robin processing for most cases (including FlushLocal),
but still do batch processing of all local changes for explicit network Flush() calls.
There are still some examples we'd like to remove here (eg Hatchbot
traditional) but this is a good start with not too many changes required
in frc-docs.
The stream can close (e.g. due to an error) while in the middle of writing. The close callback would immediately destroy the connection object, resulting in the writing code having a use-after-free. Fix this by deferring the deletion to the loop main using a single-shot timer.
An empty path isn't valid on it's own, so fs::space always returns an error. This results in UINT_MAX bytes being used instead of the actual free space, which means a default constructed DataLogBackgroundWriter won't stop for low space.
Using "." instead makes the directory path the current working directory, which is the desired behavior
A pregen_all Python script was added that calls all the other pregen scripts. This prevents the generated file checks and pregen command from falling out of sync. This is meant to only run in CI, since the script is not portable across platforms.
The SysId icon has a bunch of weird artifacting and it's not transparent on Windows. Some of the other icons have issues as well and all of them are inconsistent. GIMP was used to regenerate all the icons from the PNGs, using PNG compression on all the layers.
Instead of hardcoding to use the project name after edu_wpi_first, which broke epilogue publishing
This did not affect local maven publishing, since it does not use those specially named and configured artifacts
Currently, users can only invoke Epilogue via Epilogue.bind(TimedRobot). This PR adds a new method Epilogue.update(TimedRobot) so that Epilogue can manually called, in case a user is seeking more deterministic timing of their logs in reference to their control loops.
Previously, both wpi/expected and JSON's cpp_future.h would define enable_if_t and conjunction in wpi::detail, leading to conflicts if both were included in the same cpp source file. By renaming the namespace wpi/expected uses, there is no longer a conflict.
Java generics are too limited to do what we need. This refactors generic code previously in Unit and Measure into unit-specific classes that can have unit-safe math operations (notably, times and divide) that can return values in known units instead of a wildcarded Measure<?>.
Unit-specific measure implementations are automatically generated by ./wpiunits/generate_units.py, which generates generic interfaces and mutable and immutable implementations of those interfaces. These make up the bulk of the diff of this PR (approximately 9300 LOC).
This also adds units for angular and linear velocities, accelerations, and momenta; moment of inertia; and torque.
Adds a close function pointer template parameter to hal::Handle. This allows default destructors in many places.
The status parameter has been removed from close functions; in most places it was not used. Where it was, an error is printed instead.
4324 is issued at /W4 if alignas forces padding. Makes it impossible to use SmallVector from something compiled in /W4. Add it to the warning exclusion list.
Group memory doxygen into one module.
Remove concept alias and add doxygen definitions for foonathan memory.
\concept was added as a doxygen command in 1.9.2 and is meant to be applied to concepts. Inserting them into standard comment paragraphs causes doxygen to interpret the following text as a concept name and add it to the documentation, as well as remove the text from the paragraph.
In the upstream repo, this alias links to markdown documentation, so it's not usable for us anyways.
That, plus adding the doxygen definitions/aliases from upstream cleans up most of the errors/weird output from doxygen for foonathan memory.
The hacks we needed to do to get the existing commands required cmake 3.28. We didn't want that, so just make a local slimmed down copy of the function just for our use. Even better, its much simpler in what it does, no weird hacks.
Reading exported data from shared objects on windows is broken. It requires __declspec(dllimport). However, this is problematic, as we use the same static libraries both from a shared and static context. So we can't just blindly apply dllimport.
The linker should have caught this, as data members are exported in a different way. However, due to a bug in native-utils, data member symbols were exposed directly. However, interacting with those data member was completely broken.
The only way we can really solve this is to just not use static data members. We're pretty good about this in WPILib itself. However, protobuf is absolutely terrible at this. There are a ton of inline functions that access global data. For the protobuf library itself, we can solve this easily enough.
However, for the generated protobuf code, this is much more problematic. The member needed to bypass the global data is private. This means using just the stock protobuf code, this problem is not solvable. But, protobuf generated code has insertion points. Those insertion points let us add our own code into the generated code via a protoc plugin. And it just so happens that an insertion point exists to add extra public methodsto the generated protobuf header. There is also an insertion point to let us add to the cpp file.
The methods we need are the getters, for unpacking protobufs. For any protobuf that has a message as a member, we generate a new wpi_x() getter (the existing one is just x(), where x is the field name). We then implement this in the cpp file. A trick we can use is in the cpp file, we can safely call the x() function, as the cpp file is in the same library as the global. Thus we can call that inline method, and not actually need to directly access any internal private state of the protobuf object.
TL;DR, all protobuf classes that have messages as fields now have a wpi_x() accessor that must be used instead of x() if you want the code to work on windows. After wpilibsuite/native-utils#212, the bad code will fail to link, rather then just fail at runtime.
The new upstream_utils command-line API has been nice, but the
copy-upstream-to-thirdparty command has been annoying to type. Since it
already has documentation, we can shorten it to make it easier to
remember and type.
On some Linux systems, installing the OpenCV package will actually install a debug version with a d postfix. Try loading that version if the first load attempt failed.
Fixes error when >3 are constructed- in java, m_filterAllocated[index] would be evaluated before the bounds check and throw IndexOutOfBounds, in c++ a vague assertion error would be thrown.
Makes DoAdd static in c++
Makes the error message when HAL_SetFilterSelect fails consistent with java
By default on Windows 11, power throttling will increase timer resolution
if a window is occluded. Disable that behavior. Also enable high QOS to
achieve maximum performance and turn off power saving.
Also use internal APIs to set timer precision to 500 us if available.
If the interrupt edge tests are running while under heavy CPU load (like building wpilib) they are prone to failure since the interrupt thread doesn't have enough time to set up callbacks. The interrupt edge tests now copy the original AsynchronousInterrupt test, which has a 0.5s delay after the interrupt is enabled. Running the new interrupt tests while building allwpilib causes far less failures than the old tests.
That behavior has not been present since PR #4158 was merged more than 2 years ago and imo should not be added back because it was surprising and not consistent with the most common use case of registering a callback permanently.
This makes it easier to define schemas when the type name is non-trivial (e.g., templated structs).
This is breaking for a) custom struct implementations and b) anything calling `wpi::Struct<T>::GetTypeString(info...)` in C++ directly. In both cases, it's a simple translation: For A, rename `GetTypeString()` to `GetTypeName()` and remove the struct: at the beginning, and for B, use `wpi::GetStructTypeString<T>(info...)` instead.
Update() checks/updates the last value and appends only if changed.
GetLastValue() gets the last value.
Also add OutputStream support to Java DataLogWriter.
If one of the *Init() functions takes several multiples of the nominal
loop time, the callbacks after that will run, then increment their
expiration time by the nominal loop time. Since the new expiration time
is still in the past, this will cause the callback to get repeatedly run
in quick succession until its expiration time catches up with the
current time.
This change keeps incrementing the expiration time until it's in the
future, which will avoid repeated runs. This doesn't delay other
callbacks, so they'll get a chance to run once before their expiration
times are corrected.
The other option is correcting all the expiration times at once, which
would starve the other callbacks even longer so that the callback
scheduling returns to a regular cadence sooner. The problem with this
approach is if a previous callback overruns the start of the next
callback, the next callback could potentially never get a chance to run.
Currently, a max iteration heuristic is used to determine when a spline
is malformed. Instead, we can report a failure immediately if dx and dy
are too small, because the heading won't be accurate either.
Fixes#6826.
Explicitly list required components when using FindJava and FindJNI
Consolidate find_package calls for Java, JNI, and OpenCV into the root CMakeLists.txt file
Remove references to main_lib_dest
Install missing generated headers
Flatten some if statements
Use LinkMacOSGUI macro instead of hand rolling it
Stop installing OpenCV libraries and an extra ntcorejni library; OpenCV JAR will still be installed to make it easy to use
Only print platform version on Windows
Prevent GUI modules from being built when wpimath is off, which would otherwise cause a build failure
Simplify build configuration checks
Clean up fieldImages JAR creation
Place built JARs in the same subdir as installed JARs
Remove unnecessary JAR includes
Remove extra directories in target_include_directories
Improve CMake docs
The XRP firmware has been updated to provide the
encoder period along with the encoder count.
This change allows WPILIB to use the encoder period
data from the XRP so that the GetRate function can
be used to determine the motor speed.
Reverts #6609 since that fix didn't Just Work(tm) on Windows. (edit: or Ubuntu. Seems to have broken everything except macOS.) This PR configures CMake to try and find protobuf-config.cmake first, which allows protobuf to pull in abseil for us. If protobuf-config.cmake is not available (coprocessors which don't have a new enough protobuf installed are a common case), it will fallback to CMake's built-in FindProtobuf module, which is what we were using before.
Add wpi::CreateMessage, a wrapper with an ifdef to switch between Arena::CreateMessage and Arena::Create, since the former is deprecated in newer versions of protobuf. This allows forward compatibility with newer versions of protobuf.
This can catch breaking changes earlier.
- Builds linux only for speed
- Builds and publishes artifacts in this file as it was actually faster
then reusing the artifacts from the gradle file as those need the
combiner run on them. It uploads the artifacts to Actions with a 1 day
retention, because that allows the tools to be built in parallel, which
overall sped things up. This also only allows relevant tasks in wpilib
to be run
- The tool builds are uploaded with a shorter retention time in case
someone wants to do more extensive tests.
Add LEDReader and LEDWriter helper interfaces to facilitate composing simple patterns into more complex ones, e.g. LEDPattern.solid(Color.kBlue).breathe(Seconds.of(0.75)). Pattern composition relies on changing out the write behavior; for example, offsetBy increments the indexes to write to; while blink will switch between playing a base pattern and turning off all the LEDs.
Add a view class for splitting a single large buffer into smaller distinct sections, which is useful for dealing with long chained LED strips mounted on different parts of a robot. Views cannot be written directly to an LED strip (in fact, trying to do so won't even compile).
Adds some utility methods to the Color class for interpolating between two colors, and support color representations with 32-bit integers to avoid object allocations.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Uses enhanced instanceof (and simplify equals methods)
Uses switch expressions and arrow labels
Seal and finalize some Shuffleboard classes
Co-authored-by: Sam Carlberg <sam@slfc.dev>
This is to allow 3rd party sim providers (eg vendors) to subclass this class so that the register methods of their sim classes can return CallbackStores like the builtin sims.
Although it was already possible to create such a subclass but passing dummy parameters to one of the other constructors, this eliminates the need to pass such dummy parameters and makes it clearer that subclassing is allowed.
This is a cleanup of the FlywheelSim class with a few added features.
- One FlywheelSim constructor that takes a plant, DCMotor, and a optional number of measurementStdDevs. The documentation now states how to construct the plant either through LinearSystemId.createFlywheelSystem or identifyVelocitySystem.
- The gearbox, gearing and moment of Inertia (J) are now private final fields. The gearing is determined from the plant in the constructor as well as the moment of inertia. There are getter methods that allow the flywheelSim to return the gearbox, gearing, and moment of inertia.
- The getCurrentDrawAmps function now uses m_x instead of getAngularVelocityRadPerSec in accordance with more accuracy and matches the patter in other sims.
- Added getter methods for the InputVoltage, angularAcceleration and torque
- (Java only) A third getter method for returning the AngularVelocity of the flywheel using a MutableMeasure as a backing field that is set when getAngularVelocity is called. This summarily returns the angularVelocity as just a Measure object. This allows the user of this class to handle unit conversions with less numerical manipulation. Alterations in C++ for this feature were not needed.
Previously, the overload took a span<double>. However, m_inputs and m_outputs store type T, so the function could not be called for any T that does not have an implicit constructor from double.
Modified Java constructors to take a variable number of measurement std devs argument with checks in place to make sure the right amount (or none) are passed into the constructor. All changes passed down to classes utilizing LinearSystemSim.
Removed excess constructors
Removed Java and C++ CurrentDrawAmps method as it doesn't belong in a generic (non electrical) linear system. Kept a non override version in all derived electrical classes.
Also LinearSystemSim has now been made agnostic to electrical systems. Inputs don't have to be voltage. BatteryVoltage clamp function has been pushed down to electrical subclasses.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Currently in the entire C API of WPILib we have ~8 different ways of handling strings. The C API actually isn't built for pure C callers (We don't actually have any of those). Instead, they're built for interop between languages like LabVIEW and C# which can talk to C API's directly.
For output parameters, the choice was fairly obvious. An output struct containing a const string pointer and a length makes the most sense. Its easy to use these from most other languages, and doesn't require special null termination handling. Freeing these is also easy, as if you ever receive one of these string structures, theres just a single function call to free it.
Input parameters are a bit more complex. To be used from pure C, and from LabVIEW, a null terminated string is the best in most cases. However, null terminated strings in general have a lot of downsides. Additionally, from LabVIEW there are other considerations around encoding that having a wrapper struct helps make a bit easier. From a language like C#, a wrapper struct is by far the easiest, as custom marshalling can make it trivial to marshal both UTF8 and UTF16 strings down.
The final consideration is its nice to have an identical concept for both input and output. It makes the rules fairly easy to understand.
WPILib will not have any APIs that manipulate a string allocated externally. This means WPI_String can be const, as across the boundary it is always const.
If a WPILib API takes a const WPI_String*, WPILib will not manipulate or attempt to free that string, and that string is treated as an input. It is up to the caller to handle that memory, WPILib will never hold onto that memory longer than the call.
If a WPILib API takes a WPI_String*, that string is an output. WPILib will allocate that API with WPI_AllocateString(), fill in the string, and return to the caller. When the caller is done with the string, they must free it with WPI_FreeString().
If an output struct contains a WPI_String member, that member is considered read only, and should not be explicitly freed. The caller should call the free function for that struct.
If an array of WPI_Strings are returned, each individual string is considered read only, and should not be explicitly freed. The free function for that array should be called by the caller.
If an input struct containing a WPI_String, or an input array of WPI_Strings is passed to WPILib, the individual strings will not be manipulated or freed by WPILib, and the caller owns and should free that memory.
Callbacks also follow these rules. The most common is a callback either getting passed a const WPI_String* or a struct containing a WPI_String. In both of these cases, the callback target should consider these strings read only, and not attempt to free them or manipulate them.
DataLog is now a base class, with DataLogBackgroundWriter being the
background thread version and DataLogWriter being a non-threaded version.
Also split the C header into a separate file to make it more wpiformat friendly.
We now use a wrapper (wpi::print) to catch exceptions since we can't patch
std::print() to not throw when we ultimately migrate to it.
fmtlib and std format/print throw the same exceptions and always have. We previously patched fmt::print() to not throw a write failure exception, but we can't do that for std::print(); wpi::print() is the migration plan.
Unit objects now have a reference to the base unit from which they're derived. Constructing a unit object without specifying a base unit implicitly signifies that it's its own base unit, eg new Angle(null, 1, "Radian", "rad") would be the base angle unit of radians, while new Angle(Radians, 2 * PI, "Rotation", "R") would be a new angle unit based on radians.
This fixes much of the hacky code surrounding the derived unit types Velocity, Per, and Mult, but is a breaking change for any user code that defines custom unit classes or uses the anonymous unit type.
C++ doesn't need this because it supports value types, which are much
cheaper to construct. constexpr is also available to make construction
zero-cost.
Flattens parameter from a `std::optional<std::function<...>>` to just a `std::function<...>`. This is a breaking change but a trivial one for teams to fix.
LTVUnicycleController is a drop-in replacement with better tuning knobs.
The RamseteCommand examples were removed instead of retrofitted with
LTVUnicycleController because we're planning on removing the command
controller classes anyway, so it would be wasted effort. The
SimpleDifferentialDriveSimulation example shows direct
LTVUnicycleController usage.
Uses getUsableSpace in Java, matching how C++ determines available space (C++ calls it available, but they mean the same thing.) This fixes a bug where logs wouldn't get deleted due to incorrect available space detection.
The DataLog thread now also checks if the state was marked as stopped after a call to StartLogFile.
When low on space, a log file won't be created. This is detected as a "deletion", and the DataLog thread will continously try to create a log, fail to do so because of low space, detect it as a "deletion", and do so in a loop.
If there's not enough space, the DataLog will be marked as stopped, preventing this infinite loop. Calls to start() will hit this code path and mark it as stopped again.
LinearSystemId's linear system factories throw on negative feedforward
gains, but SysId can compute the feedback gains just fine in that case.
Now we construct the system manually instead.
Fixes#6423.
On Rio, we simply want to restart the robot program as quickly as possible,
and don't want to risk a hang somewhere that will keep that from happening.
The main downside of this is it won't wait for threads to finish (e.g. data logs won't get a final flush).
Eventually we want to get to a point where we can remove OpenCV from the internals of cscore. The start to doing that is converting the existing CvSource and CvSink methods to RawFrame.
For CvSource, this is 100% a free operation. We can do everything the existing code could have done (with one small exception we can fairly easily fix).
For CvSink, by defaut this change would incur one extra copy, but no extra allocations. A set of direct methods were added to CvSink to add a method to avoid this extra copy.
* Reorder functions so they match between languages
* Copy more complete JavaDocs to C++
* Fix incorrect description for time parameter of
TrapezoidProfile.calculate()
Previously, this used mechanism.m_subsystem.getName(), instead of mechanism.m_name, meaning differently named SysId routines from the same subsystem would clobber each other when logged.
The default state for the DS in the simulated HAL is changed to disconnected.
The FMS view is now only editable in DS disconnected state.
This enables more robot and field-like testing of robot code, as the
alliance color and other parameters start in invalid states and are
only set when the DS connects.
Due to something weird in the FPGA, calling strobeLoad() with a string length of 0 causes both CPUs to spin at 100%, basically shutting down everything else on the robot.
If a 0 length string happens to be passed, just bail out early.
Add "remote close:" to messages coming from the remote end.
Previously it was impossible to tell if the error was on the local side
or communicated by the remote side.
Dynamic structs had a few major issues.
In C++, if the string was the last definition in the schema, attempting to set a string would trigger an assertion. This has been fixed
Setting a string value could truncate the string actually stored in the struct, if the definition was shorter than the string to set.
There was no way to detect if this case occurred. The set string function now returns a bool if the string was fully written or not.
Reading a string that had a value shorter than the schema definition would result in embedded trailing nulls in the string. This would make comparing string equality basically impossible, as those embedded nulls count for the length of the string.
The above truncating didn't take into account UTF8 code points. This means a truncation could happen in the middle of a unicode character. Depending on the language this had different behavior, but unpaired code points are problematic to detect in any case. On the decoding side, detect if a split UTF8 code point has occurred by the writer, and if so just ignore it and treat it as not part of the string. Doing this on the receive side means a newer receive side is all that is needed to fix this, which is generally a better option then requiring all senders to update.
Actual DynamicStruct instances have 0 units tests for them. Added a bunch of unit tests around strings to ensure things work properly.
Currently the analysis portion only supports quasistatic and dynamic,
forward and reverse. Check for anything not matching and remove it,
along with providing diagnostics of what is being loaded.
This avoids needing add redundant JavaDocs to them, and better reflects
how we design our modern classes (the classes modified here were around
with minimal changes since 2008 or so).
This does not deprecate any current functionality, but prepares the way for future deprecation.
The drive classes now accept void(double) functions, which makes them more flexible.
The C++ API ended up a bit more verbose, but the Java API is really concise with method references, which is >80% of our userbase. For example:
`DifferentialDrive drive = new DifferentialDrive(m_leftMotor::set, m_rightMotor::set);`
Lambdas can be passed to interoperate with vendor motor controller APIs that don't have e.g., set(double), so CTRE doesn't have to maintain their WPI_ classes anymore.
MotorControllerGroup was replaced with PWMMotorController.addFollower() for PWM motor controllers. Users of CAN motor controllers should use their vendor's follower functionality.
These are the warnings being disabled:
```
== clang-tidy /__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp ==
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:51:16: warning: avoid using "_" in test name "NonInvertibleA_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
51 | TEST(DARETest, NonInvertibleA_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:67:16: warning: avoid using "_" in test name "NonInvertibleA_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
67 | TEST(DARETest, NonInvertibleA_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:89:16: warning: avoid using "_" in test name "InvertibleA_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
89 | TEST(DARETest, InvertibleA_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:101:16: warning: avoid using "_" in test name "InvertibleA_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
101 | TEST(DARETest, InvertibleA_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:118:16: warning: avoid using "_" in test name "FirstGeneralizedEigenvalueOfSTIsStable_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
118 | TEST(DARETest, FirstGeneralizedEigenvalueOfSTIsStable_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:132:16: warning: avoid using "_" in test name "FirstGeneralizedEigenvalueOfSTIsStable_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
132 | TEST(DARETest, FirstGeneralizedEigenvalueOfSTIsStable_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:151:16: warning: avoid using "_" in test name "IdentitySystem_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
151 | TEST(DARETest, IdentitySystem_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:163:16: warning: avoid using "_" in test name "IdentitySystem_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
163 | TEST(DARETest, IdentitySystem_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:176:16: warning: avoid using "_" in test name "MoreInputsThanStates_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
176 | TEST(DARETest, MoreInputsThanStates_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:188:16: warning: avoid using "_" in test name "MoreInputsThanStates_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
188 | TEST(DARETest, MoreInputsThanStates_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:201:16: warning: avoid using "_" in test name "QNotSymmetricPositiveSemidefinite_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
201 | TEST(DARETest, QNotSymmetricPositiveSemidefinite_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:210:16: warning: avoid using "_" in test name "QNotSymmetricPositiveSemidefinite_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
210 | TEST(DARETest, QNotSymmetricPositiveSemidefinite_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:220:16: warning: avoid using "_" in test name "RNotSymmetricPositiveDefinite_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
220 | TEST(DARETest, RNotSymmetricPositiveDefinite_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:232:16: warning: avoid using "_" in test name "RNotSymmetricPositiveDefinite_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
232 | TEST(DARETest, RNotSymmetricPositiveDefinite_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:245:16: warning: avoid using "_" in test name "ABNotStabilizable_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
245 | TEST(DARETest, ABNotStabilizable_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:254:16: warning: avoid using "_" in test name "ABNotStabilizable_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
254 | TEST(DARETest, ABNotStabilizable_ABQRN) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:264:16: warning: avoid using "_" in test name "ACNotDetectable_ABQR" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
264 | TEST(DARETest, ACNotDetectable_ABQR) {
| ^
/__w/allwpilib/allwpilib/wpimath/src/test/native/cpp/DARETest.cpp:273:16: warning: avoid using "_" in test name "ACNotDetectable_ABQRN" according to Googletest FAQ [google-readability-avoid-underscore-in-googletest-name]
273 | TEST(DARETest, ACNotDetectable_ABQRN) {
| ^
```
This removes a build dependency on the quickbuf generator being available for the build platform.
It's safe to generate Java because the quickbuf version is defined by the project.
C++ protobufs can't be committed because the protoc version must
match the library version (this is a particular issue for cmake builds).
There hasn't been a release in 2.5 years.
There's performance improvements for some NEON instructions, UB fixes, a lot of internal cleanup with the jump from C++11 to C++14, and more constexpr.
This required changing the constant values (e.g. kSize) into functions
(e.g. GetSize()).
Fixed implementations of ForEachNested to be inline (as these are actually
templates).
Also added a ntcore Struct test.
This implements de/serialization for the types that aren't templated (SwerveDriveKinematics) in C++ or where there is no trivial way to go round-trip (Splines) for the messages.
To reduce the need for users to manually perform unit conversions, this allows Measure objects from wpiunits to be passed into most places in wpimath that currently expect doubles in terms of SI units like meters.
For example, users would need to know that unit conversion is required - and what the correct units are. Using units would be more difficult to write code for than just hardcoding a value or using Units.inchesToMeters.
Now, using units has no more developer overhead than using raw numbers.
ProfiledPIDController and ExponentialProfile use current, then goal.
This isn't a breaking change because this overload of calculate() is
new for 2024.
Restarting a stopped log results in creating a new log file with fresh copies of the same start records and schema data records.
Also check to see if the file has been deleted or if the log file exceeds 1.8 GB, and start a new one.
The previous fix didn't handle all cases correctly. Instead, add a new
function to raw_ostream (SetNumBytesInBuffer) to allow always using the
full buffer size, and revamp write_impl to more cleanly handle all
cases.
On Windows, TryWrite will always return 0 if there is a Write in progress. The previous behavior for SendFrames and SendControl just used a normal Write, which caused issues with code that combined these with TrySendFrames. Instead, have SendFrames and SendControl also use TryWrite under the hood if possible, and create write requests if not. The implementation preserves the priority of SendControl against an existing write request with multiple frames.
- Add builtin registry baseline (fixes building locally with msvc builtin vcpkg)
- Add protobuf as an explicit dependency (previously was installed as a dependency of opencv)
- In windows CI, checkout repository before running vcpkg (silences warning that vcpkg.json was not found)
This adds support for two serialization formats for complex data types:
- Protobuf for complex objects with variable length internals that need forward and backward wire compatibility (lower speed, more flexible)
- Raw struct (ByteBuffer-style) for fixed-length objects (higher speed, less flexible)
Deserialization can be done either by creating a new object (for immutable objects) or overwriting the contents of an existing object (for mutable objects).
Implementing classes should provide inner classes that implement the Protobuf or Struct interface (in Java) or specialize the wpi::Protobuf or wpi::Struct struct (in C++). It is possible for classes to implement both. If the class itself does not implement serialization, it's possible for third parties/users to provide an implementation instead.
Uses the Google protobuf implementation for C++ and the QuickBuffers alternative protobuf implementation for Java.
The object was being destroyed due to the error handling path.
Instead, defer to the next loop cycle using a one-shot timer.
Properly handle error return values from Send functions.
Fix UB in accessing one past the end of a vector.
The goal of this addition is to allow LinearSystemId.createDCMotorSystem to use kV and KA instead of the moment of inertia, DCMotor object, and gearing.
Adds overloads for Transform2d() constructor to accept x, y, and heading and for Transform3d() to accept x, y, z and rotation as a shorthand for the normal constructors.
std::remove_if() is destructive--it can assume the removed elements are
not used, but NetworkOutgoingQueue needs them to stay intact to be moved
to a different queue. Use std::stable_partition() instead.
- Utilize TrySend to properly backpressure network traffic
- Split updates into reasonable sized frames using WS fragmentation
- Use WS pings for network aliveness (requires 4.1 protocol revision)
- Measure RTT only at start of connection, rather than periodically
(this avoids them being affected by other network traffic)
- Refactor network queue
- Refactor network ping, ping from server as well
- Improve meta topic performance
- Implement unified approach for network value updates (currently client and server use very different approaches) that respects requested subscriber update frequency
This adds a new protocol version (4.1) due to WS bugs in prior versions.
It takes 30 minutes, and the artifacts aren't used. The combine step
changes so infrequently that it's unlikely to break in PRs, so it's a
net benefit to speed up PR builds.
Putting an early exit if statement at the top instead of wrapping the
whole file contents unbreaks unit test configs, as was discovered for
SysId. It reduces nesting as well.
Unused plugins were removed from the beginnings of files as well.
This takes advantage of the underlying byte-level TryWrite() functionality to minimize blocking behavior and enable higher layers to do things smartly when the network blocks.
Also:
- Fix handling of control packets in middle of fragmented
- Clean up debugging features
In C++ each example is a separate source set, but in Java they were one source set and tested as one with the test task. Example-specific test tasks exist for Java, but they weren't used.
This modifies the test task to exclude the example tests, instead depending on each example's test task. The advantage of this is that each example is tested in a separate environment, so leftover state from one example isn't carried over.
fmtlib uses consteval format string processing, which makes it more
efficient than std::snprintf().
snprintf()s in libuv, mpack, processstarter, and wpigui were left alone.
processstarter uses stdlib only, and wpigui only depends on imgui.
fmt::format_to_n() is analogous to std::format_to_n()
(https://en.cppreference.com/w/cpp/utility/format/format_to_n)
wpi::format_to_n_c_str() is a wrapper which adds the trailing NUL.
Provides an implementation of a XRP-specific plugin that sends binary messages over UDP (to account for the less performant hardware on the XRP).
This plugin leverages the work already done for the WebSocket protocol and does a translation to/from JSON/binary.
CMake's file(DOWNLOAD) function fails silently, leading to an error occurring due to a missing file later in the build. This fails quickly and produces a better error message.
endswith() leaves files out from subdirectories, which means projects
that add new subdirectories won't have those files included when they
probably should be.
FetchContent requires CMake 3.11 (released Mar 28, 2018).
Fixed this warning:
```
CMake Warning (dev) at /usr/share/cmake/Modules/FetchContent.cmake:1316 (message):
The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy CMP0135 is
not set. The policy's OLD behavior will be used. When using a URL
download, the timestamps of extracted files should preferably be that of
the time of extraction, otherwise code that depends on the extracted
contents might not be rebuilt if the URL changes. The OLD behavior
preserves the timestamps from the archive instead, but this is usually not
what you want. Update your project to the NEW behavior or specify the
DOWNLOAD_EXTRACT_TIMESTAMP option with a value of true to avoid this
robustness issue.
Call Stack (most recent call first):
imgui/CMakeLists.txt:23 (FetchContent_Declare)
```
Previously this was unlimited, which could result in holding on to a
large amount of memory if the connection got backlogged or a burst of
data transmission occurred.
The following source code changes were required:
* Whitespace changes from spotless
* PMD warning suppressions for utility class tests
* PMD warning rename from "BeanMembersShouldSerialize" to
"NonSerializableClass"
* Declared more class members as final
Destructing either of the multicast objects during process shutdown will result in a crash due to attempting to start a task on the non-existent thread pool.
Solve this by just leaking all the handles upon destruction of the static multicast manager. This won't solve the case where the user statically allocates the object, but solves Java and C access, and most cases wouldn't be statically allocating the service announcer anyway in C++.
Made JNI modifications to expose the faster function, made the API use
the typesafe Matrix API, and synchronized the documentation with C++.
Sped up C++ LTV diff drive test from 20 ms to 15 ms.
Sped up C++ LTV unicycle test from 15 ms to 10 ms.
Both seem to work, but the SDA algorithm is specifically recommended for
solving DAREs as opposed to P-DAREs.
The QR decomposition was replaced with a partial pivoting LU
decomposition at the recommendation of section 2.4 of the paper.
More tests and a separate JNI function for each DARE solver variant were
added.
This avoids allocation overhead on construction. times() was also
rewritten to not allocate any temporary objects.
Getter calls in the C++ Quaternion class were modified for parity.
Current timestamp read code uses FPGA register reads. Through testing,
this read was slower then clock_gettime by about 4-5x. However, another
method of reading the FPGA time is available, using HMB. HMB
is memory mapped IO from RAM to the FPGA. So to code side,
reading the value is just a memory barrier and a memory read.
There is some latency on the write side, so a very small artifical delay
(5us) is added to avoid register reads such as interrupts being ahead
of current timestamps, which could cause issues.
Below is read times for 1000 calls to clock_gettime, register reads and
hmb reads.
```
Clock: Rise 1.72939400 s Fall 1.72990700 s Delta 0.00051300 s
FPGA : Rise 1.72999000 s Fall 1.73429300 s Delta 0.00430300 s
HMB : Rise 1.73466800 s Fall 1.73481900 s Delta 0.00015100 s
```
Also add full HMB struct to HAL for future usage.
15 m/s is about 50 ft/s, which is way above what FRC robots should be
able to achieve. This limit lets us catch user errors from bad unit
conversions immediately instead of the LUT generation in the LTV
controllers hanging for a really long time.
Fixes#5027.
This works around an exit race with wpi::Now() on Rio; it was overridden
to call HAL_GetFPGATime(), which calls chipobject, but on exit, because
there was not a library dependency, the chipobject could be destroyed
prior to wpiutil/wpinet being shut down.
# Background
Unit safety has always been a problem in WPILib. Any value corresponding to a physical measurement, such as current draw or distance traveled, is represented by a bare number with no unit tied to it; it's up to the programmer to know what units they're working and take care to remember that while working on their robot program. This leads to bugs when programmers accidentally mix units without knowing, or measure something (such as a wheel diameter) in one unit and program using another. `wpiunits` is intended to eliminate that class of bugs.
Another source of friction is the controllers and models in `wpimath` that expect all inputs to be in terms of SI units (meter, kilogram, and so on), while most FRC teams are US-based and most commonly use imperial units. wpimath does a good job of noting unit types in method names and argument names; however, it still relies on users properly converting values (and knowing they even have to do so).
# API
There are really only two core classes in this library: `Unit` and `Measure`. A `Unit` represents some dimension like distance or time. `Unit` is subclassed to define specific dimensions (eg `Distance` and `Time`) and those subclasses are instantiated to defined particular units in those dimensions, such as `Meters` and `Feet` being instances of the `Distance` class.
A `Measure` is a value tied to a particular dimension like distance and knows what unit that value is tied to. `Measure` has two implementations - one immutable and one mutable. The `Measure` interface only defines *read-only* operations; any API working with measurements should use the interface. The default implementation is `ImmutableMeasure`, which only implements those read-only operations and is useful for tracking constants. `MutableMeasure` also adds some methods that will allow for mutation of its internal state; this class is intended for use for things like sensors and controllers that track internal state and don't want to allocate new `Measure` objects every time something like `myEncoder.getDistance()` is called. However, the APIs for those methods should still only expose the read-only `Measure` interface so users can't (without casting or reflection) change the internal values.
A `Units` class provides convenient definitions for most of the commonly used unit types, such as `Meters`, `Feet`, and `Milliseconds`. I recommend static importing these units eg `import static edu.wpi.first.units.Units.Meters`) so they can be used like `Meters.of(1.234)` instead of `Units.Meters.of(1.234)`
# Examples
These examples are admittedly contrived. Users shouldn't be interacting much with measure objects themselves, since wpimath and wpilibj classes will be updated to support working with them; users will often just have to take a `Measure` output from one place (such as an encoder) and feed it as input to something else (such as a PID controller or kinematics model)
```java
// Using raw units
Encoder encoder = ...
int kPulsesPerRev = 2048;
double kWheelDiameterMeters = Units.inchesToMeters(6);
double kGearRatio = 10.86;
// always have to remember this encoder will output in meters!
encoder.setDistancePerPulse(kWheelDiameterMeters * Math.PI / (kGearRatio * kPulsesPerRev));
Command driveDistance(double distance) {
// have to know the distance argument needs to be in meters!
return run(this::driveStraight).until(() -> encoder.getDistance() >= distance);
}
// Oops! This will go 16 feet, not 5!
Command driveFiveFeet = driveDistance(5);
Command driveOneMeter = driveDistance(1);
```
```java
// Using wpiunits
Encoder encoder = ...
int kPulsesPerRev = 2048;
Measure<Distance> kWheelDiameter = Inches.of(6);
double kGearRatio = 10.86;
encoder.setDistancePerPulse(kWheelDiameter.times(Math.PI).divide(kGearRatio * kPulsesPerRev));
Command driveDistance(Measure<Distance> distance) {
// Measure#gte automatically handles unit conversions
return run(this::driveStraight).until(() -> encoder.getDistance().gte(distance));
}
// Users HAVE to be explicit about their units
Command driveFiveFeet = driveDistance(Feet.of(5));
Command driveOneMeter = driveDistance(Meters.of(1));
```
```java
SmartDashboard.putNumber("Temperature (C)", pdp.getTemperature().in(Celsius));
SmartDashboard.putNumber("Temperature (F)", pdp.getTemperature().in(Fahrenheit));
```
```java
var InchSecond = Inch.mult(Second); // new combined unit types can be user-defined
var InchPerSecond = Inch.per(Second);
PIDController<Distance, ElectricPotential> heightController = new PIDController<>(
/* kP */ Volts.of(0.2).per(Inch),
/* kI */ Volts.of(0.002).per(InchSecond),
/* kD */ Volts.of(0.008).per(InchPerSecond)
);
var elevatorTop = Feet.of(4).plus(Inches.of(6.125));
elevatorMotor.setVoltage(heightController.calculate(encoder.getDistance(), elevatorTop));
```
Many teams have issues trying to read the DS too early. By switching to an optional, we cause teams to check 2 things. Either 1) they explicitly check, and their code is correct, or 2) they just read .value() and their code reboots in a loop. However, because the DS will eventually connect, this 2nd case is ok, and should theoretically be undetectable on the field.
The problem is that you have to use a different pkg-config file if you want to use a static variant of libuv, but the buildsystem should not care which variant of libuv should be used. This is not a problem with the cmake config.
Accelerometer is hyper-specific to ADXL accelerometers, and Gyro is
less useful now that 3D IMUs are prevalent, and if those IMUs want to
support the Gyro interface, they also need to provide a way to set the
axis used for the Gyro interface, which is confusing. Higher-order
functions (e.g., lambdas) are a more flexible interface boundary than
interfaces, but they didn't exist when these interfaces were
created.
Taking the joystick inputs from -1 to 1, multiply them by the max speed (as defined in Constants.java) to get the target speed, rather than using the unitless raw joystick inputs.
Moves all CommandBase functionality into Command and deprecates CommandBase for removal.
Moves all SubsystemBase functionality into Subsystem and deprecates SubsystemBase for removal.
Adds a function to CommandScheduler to remove all registered Subsystems.
Setting one will set the others, like it does in real hardware.
Add tests for boundary conditions and conversions.
Update PWM sendable implementation to include all forms.
Fixes#5264Fixes#3606
This method is used to check if the given value matches an expected value within a certain tolerance.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Co-authored-by: Ryan Blue <ryanzblue@gmail.com>
Adds a reset method where teams can pass in module headings for the kinematics object to use if it gets an all-zero ChassisSpeeds while converting ChassisSpeeds to module states. Also removes internal states array, replacing it with an internal headings array.
```
CMake Warning (dev) at CMakeLists.txt:14 (project):
cmake_minimum_required() should be called prior to this top-level project()
call. Please see the cmake-commands(7) manual for usage documentation of
both commands.
This warning is for project developers. Use -Wno-dev to suppress it.
```
I timed the DARE unit tests, and the new solver is 0 to 100% faster in
all cases (that is, it's at least as fast as Drake's and up to 2x faster
in some cases).
The new solver is also much simpler, takes less time to compile, and
drops the libwpimath.so size from 325 MB to 301 MB.
I think most of the compilation time is coming from the eigenvalue
decompositions used to enforce argument preconditions.
HAL_SetAddressableLEDBitTiming swapped high and low timings for whatever
was written to it. This fixes that bug.
Additionally, the API has been updated to take high time first, and then
low time. This is due to this being the physical data format, so having
the API match is clearer.
Additionally, update the docs with the defaults.
Was logging relative to cached value rather than previously logged value.
Was also logging cached value instead of current loop value.
C++ implementation is correct.
There can be duplicate addresses coming out of name resolution; if we
already started connecting to an address, don't start another connection
attempt.
The algorithm being used for scanning outgoing messages was O(n^2)
because it did a full linear search and then appended. This scan is
performed for each client. If there is a burst of outgoing changes, the
outgoing queue can get quite deep all at once and this scan can be very
slow. Replacing with a map fixes this.
Previously, the comment would end at any quote, escaped or unescaped. This allows UnescapeCString to handle the unescaping of quotes and properly end the string.
There's a spec difference between NT4 and datalog for integers; NT4 uses
"int", datalog uses "int64". We were using "int" for datalog as well.
Also add backwards compatibility support to datalogtool for treating
"int" as "int64".
There's no signal from NetComm as to when it is valid, and 1 second
seems to be marginal. Increase to 6 seconds for just DS, 5 seconds for
FMS attached.
HAL_GetRuntimeType used to be a free call before the roboRIO2 was added. However, nLoadOut::getTargetClass() is not a free call, and it may hit the IPC layer. Cache this value so it is not called every time.
This makes it possible to mock the timestamp for wpimath without affecting the rest of the library.
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
GetInstance() is required to start the event listener that creates the
network table entries.
This is a C++ only change; Java uses static's and thus doesn't need this.
The right fix is to implement cscore's AddListener() immediate notification,
but that's much too invasive of a change to do this year.
This fixes the common use cases, but doesn't fix all cases, as e.g. creating
a UsbCamera manually before calling any CameraServer functions will still
have the issue, but there's an easy workaround--call
CameraServer::SetSize() prior to creating any cameras.
This provides the closed callback with the real reason for the
connection being closed. Keep closed from being called twice by adding
a check in SetClosed().
Previously the timeout was 10 times the update rate, so with low update
rates it could be as small as 50 ms, causing spurious disconnects when
large or many topics were published.
Limiting with vsync is apparently unreliable on a number of systems;
this resulted in high CPU/GPU usage.
Also add current actual frame rate to about dialog of GUI tools.
This would previously just write past the end of the buffer, smashing
the stack. It's only called in the case when a non-file or block device
is used as the file.
Previously, a setDefault() on the server could override a client doing a
real set() if the time offset between client and server was negative,
resulting in a negative timestamp from the client. This is a not
uncommon situation with robot code, as the robot code always starts at
time 0, so any clients that set values earlier (in real time) would have
negative timestamps.
Also improve special casing of 0 in the transmit side to make sure a
normal timestamp will never get sent as 0.
Previously this wouldn't send the last value on the value subscribe if a
topics only subscription already existed.
Also start adding server implementation unit tests.
This avoids the warning appearing on every startup when persistent
values aren't used.
Also add note to message saying it can be ignored if persistent values
aren't expected.
This PR updates the existing differentialdriveposeestimator example to include computer vision pose estimation and latency compensation.
The example generates a simulated cameraToTarget transformation, which is then fed into ComputerVisionUtil.objectToRobotPose() to compute the robot's field-relative position exclusively from vision measurements. The vision measurements are applied through DifferentialDrivePoseEstimator.addVisionMeasurement().
The updated example constructs an AprilTagFieldLayout from JSON. This requires a deploy directory, something which isn't currently supported in wpilibjExamples and wpilibcExamples.
During HAL_Initialize, wait up to 100ms for a DS packet to be received. Then in RobotBase, right after calling HAL_Initialize, call each language's RefreshData function to force a high level DS update. If the DS is connected, will get joystick data. If there is no data, nothing different will happen, but in that case there's no joysticks anyway.
This does the same thing as right clicking, but provides a visual indicator.
The icon disappears if the window is too small or docked (right click keeps working).
RKDP is strictly better in terms of accuracy per unit of work. We used
RKF45 for sim physics in the 2021 season, but we transitioned to RKDP
before the 2022 season.
This provides a consistent class-based interface to the underlying C
library from both C++ and Java.
Co-authored-by: Matt <matthew.morley.ca@gmail.com>
The main restriction is there must be an event loop running on the main thread.
No special action is required for GUI applications, but for non-GUI applications, a
RunOsxRunLoop() function is provided that needs to be called from the main thread.
Using an atomic here means we are never going against a lock that is touchable from user code. That should make reading the DS data from the DS callback even safer.
If UpdateClients() was called in the same update batch as an entry
removal, it could crash in GetEntry() due to a null entry caused by
deletion before a removal erase pass was made.
Java was missing the motor safety thread entirely
C++ accidentally used a manual reset event, causing the motor safety thread to spin.
C++ PWMMotorController would not feed the watch kitty.
Both languages would call feed() from the StopMotor call, causing some ping ponging.
Reverts "[wpimath] Constrain Rotation2d range to -pi to pi (#4611)"
This reverts commit d1d458db2b.
This broke multiple teams code in beta. It is also easier to limit the angle externally, then reconstruct a larger angle that got limited. This additionally adds comments to clarify the behavior and retains tests that were added in the reverted commit, and fixes a javadoc comment angle reference.
The CAN Stream API allows defining an buffer to receive an
arbitrary set of CAN messages, based on an ID and a mask. Messages
are added to this queue separate of other CAN APIs. This means the
messages can be receive without impacting other APIs such as
vendor APIs.
This enables things like detection of what devices are on the
bus, or custom decoding, without using vendor APIs.
Co-authored-by: Thad House <thadhouse1@gmail.com>
Move the command group checking functionality from CommandGroupBase into CommandScheduler.
Update references to grouping as composition for clarity (because explicitly grouping isn't the only way to do it).
Deprecate the static factory methods parallel, race, and deadline in CommandGroupBase in favor of the identical ones in Commands.
The ComputerVisionUtil class was added before AprilTag support was
announced. Now that it has, the functions for estimating a pose from
range and yaw are no longer needed; it's just better to get the pose
directly from the AprilTag.
The coordinate system on some function arguments was confusing or didn't
match the NWU convention the rest of the library uses. It's easier to
remove the functions now and add them back after they're fixed since the
fixes aren't trivial.
The range function was removed because it uses pitch and yaw in the
camera's spherical coordinate system, which is obsoleted by AprilTags.
AprilTags give you a 6DOF pose directly, so range can be obtained via
Pose2d.getTranslation().getDistance().
Fixes#4757.
For PWM motor controllers, this is going to be the fastest way to stop the motor,
as disabling the PWM output will have a small delay due to the motor controller
needing to detect the missing signal.
Note Set(0) is not a safe approach for CAN motor controllers, which may have closed
loop operation, non-% output set() calls, etc.
No longer stores a temporary setpoint in PIDSubsystem, instead
immediately sending to PIDController. This fixes an issue where the
setpoint didn't take effect until the Subsystem Periodic method ran, and
could cause commands to finish early if they were scheduled after the
subsystem periodic method ran because it used the old setpoint.
This fixes the following compilation errors:
```
/home/tav/frc/wpilib/allwpilib/wpilibcExamples/src/main/cpp/examples/UnitTest/cpp/subsystems/Intake.cpp:5:10: fatal error: subsystems/Intake.h: No such file or directory
5 | #include "subsystems/Intake.h"
| ^~~~~~~~~~~~~~~~~~~~~
/home/tav/frc/wpilib/allwpilib/wpilibcExamples/src/test/cpp/examples/UnitTest/cpp/subsystems/IntakeTest.cpp:11:10: fatal error: Constants.h: No such file or directory
11 | #include "Constants.h"
| ^~~~~~~~~~~~~
```
This effectively replaces the Unscented Kalman Filter used for Pose Estimation with the Odometry model, and uses a recalculable Kalman gain matrix to update pose estimations whenever a vision measurement is added.
Notably, this change removes the need for the confusing generics used in Java, and the C++ implementation got quite a bit less complex as well.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Also update rapidreactcommandbot example factories to fit this convention (as in #4655).
C++ does not need an update as CommandPtr already uses CommandBase (#4677).
The Color algorithm was tweaked to:
a) not produce incorrect values if the user happens to input a hue outside the [0, 180) range, and
b) more accurately convert the hue remainder from range 0-30 to 0-255. The current conversion vastly overshoots the multiplier (converts 0-30 to 0-270) and relies on clamping the value when constructing the Color object to produce a slightly incorrect result.
Trigger was refactored to use BooleanEvent when it was introduced in #4104.
This reverts to the original implementation until edge-based BooleanEvents can be fixed.
Refactor some examples to use newer features, such as HID factories, library-provided command factories, CommandPtr (C++), as well as new idioms such as static/instance command factories.
Comparison operators which compared against every class member variable
now use C++20's default comparison operators.
Also remove operator!= that in C++20 is now auto-generated from operator==.
These are similar, but not quite identical to, the NT3 NetworkTable
table listeners.
Also add table topic-only multi-subscriber to ensure functions like
getKeys() work properly regardless of other subscriptions.
Previously, only the first subscriber was actually matched to a topic
when a topic was created; this was a problem when later publishing
values as a client could have both a topic-only subscriber and a normal
subscriber, and only the first one would end up being subscribed to the
topic.
Since m_windows is sorted using the ascii, when "Plot <10>" is reached it will be before "Plot <2>" in `m_windows` which makes it so it will not add a new plot after the id 10 is reached. This also fixes a potential issue of someone manually changing an id in the file, which would break adding a new plot in some circumstances.
Currently, the server rejects duplicate client IDs. As we want to make
the client implementation as simple as possible, instead deduplicate the
name on the server side by appending "@" and a count.
NT4 spec has been updated for this change.
This is needed to avoid a conflict with Object.wait() when using static imports.
C++ doesn't have this issue, and has units, so Wait() still makes sense there.
The signing step does not get passed the username and password to the server, so it will just read from the build cache. Then to make sure the tasks are all updated correctly, use if developerid exists as a property to all sign tasks, so it will see the new variable value, and relink. Additionally only update the archives during signing, which will speed up signing.
This leaves the file format as a list, but internally will transform the collection of tags into a map on de/serialization. The serialization will probably happen once on startup, but the tag lookup can happen 100s of times a second. This honestly probably doesn't make too much of a performance hit since N is small, but this is a simple O(n) -> O(1) change for lookups.
* NetworkTableInstance: set handle to 0 after destroy
* Fix multiple notifications of local values
* Detect mismatch between handles
* Server: fix setting min period when no topics
* Limit maximum number of subscribers/publishers/listeners
This helps find resource leaks and prevents them from causing excessive
slowdowns/crashes. The limit on each is currently set to 512.
* Don't use std::swap in move operation
This is an API for looking up a Pose3d from a tag id, and includes functionality to load that map from a JSON file.
This also adds JSON support to Pose3d, Rotation3d. Translation3d, and Quaternion.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Co-authored-by: AMereBagatelle <themerebagatelle@gmail.com>
Motivation
Feedback from 2022 showed that the Trigger API is rather confusing, mostly due to the following:
- duplicate Trigger and Button APIs were available; users were confused searching for a nonexistent difference between them.
- the when terminology was ambiguous and unclear whether it refers to the high state or specifically the rising edge.
- the Active terminology didn't unambiguously refer to the high state; it wasn't unintuitive to understand it as "when the binding is active/polled".
- whileHeld vs whenHeld was very confusing, and the difference between them wasn't obvious. The parallel Trigger verbs, whileActiveContinuously and whileActiveOnce are much less confusing.
Solution
Deprecating Button and its binding methods. The rationale for deprecating Button (and not Trigger) is because Button uses terminology that is needlessly more specific and restricting to the button use case, making the use case of arbitrary trigger conditions unintuitive.
After consideration, deprecation of Button's subclasses was decided against:
- NetworkButton (a trigger condition based on a boolean NT entry/topic) is a use case that is not necessarily intuitive for teams to implement themselves, so it is an abstraction that should be provided in the library. A parallel class for the BooleanEvent level, NetworkBooleanEvent, was also added as part of NT4. NT listeners were considered as a alternative solution, but they require attention to thread safety, and aren't interoperable with the EventLoop API.
- JoystickButton/POVButton provide abstractions around HID buttons. The new Trigger-returning factories on the HID classes are an equal (if not more concise) alternative, but there is no reason not to keep them for those who find their use preferable.
At a later date in the deprecation cycle (perhaps for 2024), when Button is removed, these subclasses should be changed to inherit directly from Trigger.
Trigger's bindings are changed to use True/False terminology, as it should be unambiguous. Each binding type has both True and False variants; for brevity, only the True variants are listed here:
- onTrue (replaces whenActive): schedule on rising edge.
- whileTrue (replaces whileActiveOnce): schedule on rising edge, cancel on falling edge.
- toggleOnTrue (replaces toggleWhenActive): on rising edge, schedule if unscheduled and cancel if scheduled.
Two binding types are completely deprecated:
- cancelWhenActive: this is a fairly niche use case which is better described as having the trigger's rising edge (Trigger.rising()) as an end condition for the command (using Command.until()).
- whileActiveContinuously: however common, this relied on the no-op behavior of scheduling an already-scheduled command. The more correct way to repeat the command if it ends before the falling edge is using Command.repeatedly/RepeatCommand or a RunCommand -- the only difference is if the command is interrupted, but that is more likely to result in two commands perpetually canceling each other than achieve the desired behavior. Manually implementing a blindly-scheduling binding like whileActiveContinuously is still possible, though might not be intuitive.
Notes
It was considered to share BooleanEvent's digital signal terminology; however, once it was decided that Trigger should not inherit from BooleanEvent (due to overload incompatibility) the common terminology was not worth the unintuitiveness stemming from users' unfamiliarity with the signal processing terms.
All trigonometric functions and vector classes assume North-West-Up axes
convention, so using North-East-Down convention with them is really
error-prone. We've broken something every time we touched the drive
classes.
We originally used North-East-Down to match the joystick convention, but
the volume of long-lived bugs has made this not worth it in retrospect.
The rest of WPILib also uses North-West-Up, so this makes things
consistent.
KilloughDrive was removed since no one uses it.
- In both C++ and Java, add listener functions to Instance class (same as NT3 provided)
- Add WaitForListenerQueue functions (same as NT3 provided)
- Move Java non-poller implementation to Instance (previously only handled single instance)
- Change C++ listeners to take non-const references for subscribers etc to help avoid footguns from use of temporary objects (also add doc comment)
- Fix Preferences making .type persistent
This avoids the need for explicit value() calls (as compared to using
DoubleTopic). The unit name is published as the "unit" property.
Implementation note: the test needs to be in wpilibc because ntcore does
not depend on wpimath.
Theres is now a built in HMB api, but you have to dlopen it to access it. Moved our existing infrastructure for this to its own class, added the new functions, then updated interrupts and LEDs to use it.
* TopicListener: Fix Add() return values
* Update PubSubOption poll storage documentation
* Update NetworkTableEntry::GetValue() doc
* Add documentation regarding asynchronous callbacks
* Unpublish entry: set publisher to nullptr
* Implement ValueListenerPoller default constructor
* Remove SetNetworkIdentity, make parameter to StartClient
* URI-escape client ID, improve error message
* Add connected message with client id; also improve disconnected message a bit
* Handle SetServers either before or after StartClient
* Fix client use-after-free; also delay reconnect after disconnect to rate limit
* Don't re-announce to already subscribed client; we especially don't want to send the last value again
* Always accept in-order sets, only use timestamp for tiebreak
* Fix LocalStorage::StartNetwork race
* Remove unused/unimplemented function
Also:
* [glass] Remove debug print
* [glass] Fix mpack string decoding
* [cameraserver] Fix up startclient
The current DS thread model has some pretty major issues. It makes it difficult to know if all data is from the same remote packet, and if the data changes while the robot loop is running. Additionally, the DS thread is used for a few other things (MotorSafety and State Tracking for EducationalRobot). This also makes sim difficult, as user code has to wait for the thread to know it has new data.
This change completely rethinks how threading works in the driver station model.
First, the DS HAL system receives a new data callback, either from Netcomm or DriverStationSim. Inside the context of this callback, all the low latency data is read and put into a cache. Doing some investigation on the robot side, this is perfectly safe to do, and also ensures a ds packet will not be parsed before we finish reading the current packet data.
After all data is read, the cache is swapped with a 2nd buffer. This buffer just stores the data, none of the HAL DS calls read from this buffer. An event is then fired, stating there is new data ready to go.
Robot code calls HAL_UpdateDSData(). This swaps the 2nd buffer with a 3rd buffer, which always contains the current data. This data will not be updated until HAL_UpdateDSData is called again. Which solves the state problem.
The high level driver station classes have. an updateData() call, which calls HAL_UpdateDSData, and then update button state variables, then data log and update the NT FMS data table (Java also caches across the JNI boundary here, but that could trivially be removed). An extra event provider is provided, allowing other threads to know when this call has been completed.
IterativeRobotBase calls DS.updateData() at the beginning of each loop, and only once per loop. This means all commands will always have the same state.
All of this means there is no longer a DS thread. Everything happens synchronously. This means Sim and testing is easier, as you can just call DriverStationSim.NotifyNewData(), and then DriverStation.UpdateData(), and you can guarantee that all the DriverStation.*** data is up to date.
As for Motor Safety and Educational Robot State Handling, those can all be handled by their own threads. The Educational Thread only needs to run under EducationalRobot, and MotorSafety will only be started if there is a motor safety object enabled.
For system installs, `DESTDIR=/usr cmake --install buildfolder` installs
libraries to `/usr/lib` with the correct rpath. Example structure:
```
/usr/include/wpimath/frc/controller/LinearQuadraticRegulator.h
/usr/lib/libwpimath.so
```
Users need to provide `-I/usr/include/wpimath` in their projects. This
is an artifact of the install() commands being in the subdirectory CMake
files.
For other locations, `DESTDIR=/opt/wpilib cmake --install buildfolder`
installs libraries to `/opt/wpilib/lib`. Example structure:
```
/opt/wpilib/include/wpimath/frc/controller/LinearQuadraticRegulator.h
/opt/wpilib/lib/libwpimath.so
```
-DUSE_SYSTEM_EIGEN now only removes include paths for Eigen instead of
drake as well.
The USE_VCPKG flags were renamed to USE_SYSTEM since they seem general
enough for that to work (the find_package() commands work the same way
on Arch).
The system libuv CMake build now works with Linux libuv as well.
This is enabled by the C++20 __VA_OPT__ feature.
Uses of "{}" format string were updated.
Some warning suppressions were required for older clang versions.
Also improve codegen of wpi::Logger::Log(), frc::ReportError(), and frc::MakeError();
these generate better and less redundant code if they use fmt::string_view for the
format string instead of templating on it.
* Use explicit this capture required by C++20
* Use C++20 span
* Replace wpi::numbers with std::numbers
* Fix C++20 clang-tidy warning false positive in fmt
* Remove ciso646 include since C++20 removed that header
* Fix global-buffer-overflow asan warnings in ntcore tests
* Add DIOSetProxy constructor to HAL
* Upgrade MSVC compiler to 2022
* Bump native-utils to 2023.2.7 (changes to std=c++20)
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
* Fix C++ Publisher and Subscriber move assignment
* Fix Publisher comment typo.
* Publish: check that properties is an object.
Print a warning, but still publish, just with empty properties.
Add error print for unassigned type publish.
* Return boolean from SetProperties
* Document exception-throw in Java for invalid JSON.
The existing raw time has an issue where it jumps around, as in the FPGA if the frequency is not a multiple or divisor of 25 Mhz it jumps around by 1 every second. While waiting on an FPGA change, update the API to make raw output give nanoseconds rather then a scaled value. This does a longer read cycle to get the correct value, but in the future if a fast FPGA function is added this can be easily changed.
Add a CommandPtr with an internal unique_ptr to enable not needing to move the underlying classes, which is error-prone due to the potential for lambda captures.
I also refactored Pose3d's conversion implementation to use the
Translation3d and Rotation3d conversions, thereby giving Translation3d
and Rotation3d test coverage. No changes were made to the expected
values of the Pose3d conversion tests.
The expected values of the Transform3d conversion tests were copied from
the Pose3d conversion tests without modification.
Checkstyle naming conventions were changed to allow most of what's in
wpimath. Naming rules were disabled completely in wpimath since almost
all suppressions are for math notation.
SPI Mode setting was very broken. MSB and LSB sets did not work (MSB is the only one supported)
and if LSB was set (which was the default) the ioct to set clock phase would fail. This
deprecates all the individual functions, the LSB/MSB functions, and adds an SPI mode selection
function. This is usually more understandable, and shows up in a lot more documentation
The controller gain matrix K should be computed from the solution to the
DARE, but this constructor does not do that. It effectively violates a
postcondition enforced by the other constructors by letting the user
throw in a controller gain matrix that didn't come from an LQR.
Removing this constructor is a breaking change, but it never should have
been included in the class in the first place. There's also no valid
reason to use it. I assume it was originally added for debugging the
class internals.
This constructor does not exist in C++.
Replace ⊤ with \u22a4, since Unicode references are supported
but HTML5 entities are not. Should be fixed if JDK is ever
moved forward.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
until() was recently added as a more intuitive alias for this. At this point, keeping this decorator will just cause confusion, given the functionally-equivalent until() alias and the similarly-named getInterruptionBehavior/withInterruptBehavior
Force the status to be 0 (no error) upon initialization of the REV PneumaticHub.
This prevents a program crash in the case of a robot code restart with no CAN Bus present.
This causes setVoltage to be called on the lower level motor contollers,
which is benefical in cases when they are smart motor controllers.
Previously, the default implementation (using the bus voltage and
calling set()) was used in this case.
This does slightly pessimize the case when the lower level motor
controllers use the default setVoltage implementation, but given the
prevalence of smart motor controllers, this seems like an overall win.
The FPGA API takes microseconds directly, instead of a scaled value. Also add a new HAL level API to trigger multiple DIOs with the same pulse at once.
Added an Eigen::SparseMatrix formatter.
Also modified the Eigen::Matrix formatter to support Eigen::MatrixXd.
Eigen::MatrixXd sets both dimension template arguments to -1, so they
can't be used for iteration. rows() and cols() are now used instead.
rows() and cols() are constexpr for statically sized matrices, so
there's no performance loss there.
This is useful in some debugging scenarios. System.err is separately buffered, so when e.g. debugging test cases it doesn't interleave correctly with the C++ stdout/stderr logging. Even using flush() doesn't seem to help, I think because Gradle does its own buffering.
For RPATH on MacOS use '@loader_path' instead of '$ORIGIN' to reference the directory where the executable is located. The latter is the mechanism used on Linux.
I think this was exposed due to newer OS X ignoring $DYLD_LIBRARY_PATH for security reasons.
* Root folder variable names are now more descriptive
* clone_repo() now restores the current working directory
* Removed setup_upstream_repo() since it's now identical to clone_repo()
* Moved am_patches()'s for loop into user scripts so the filename prefix
doesn't need to be included in every patch filename
* Renamed am_patches() to git_am() since its only job now is to run "git am"
* Removed unused apply_patches() function
* Fixed typo in git_am()'s ignore_whitespace arg name
The warnings included recommendations of braces for if statement
readability, a recommendation for default initialization of an int
array, and include-what-you-use (indirectly through clang-tidy reporting
undefined symbols).
We migrated to magic statics for lazy construction like the following:
```cpp
class Singleton {
static Singleton& GetSingleton() {
static Singleton instance;
return instance;
}
};
```
Now, implicit narrowing conversions are only used with wpi::Now(). This
also fixes clang-tidy warnings about C-style casts. For example:
```
== clang-tidy /__w/allwpilib/allwpilib/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.inc ==
/__w/allwpilib/allwpilib/wpilibNewCommands/src/main/native/include/frc2/command/SwerveControllerCommand.inc:95:18: warning: C-style casts are discouraged; use static_cast/const_cast/reinterpret_cast [google-readability-casting]
auto curTime = units::second_t(m_timer.Get());
^
```
In that case at least, the cast was removed entirely since Get() already
returns a units::second_t.
fmt removed fmt::make_args_checked since it's no longer needed for
constexpr format string checks.
fmt deprecated implicit conversions from enums to integers in format
arguments, so I added explicit static casts.
This reduces commit noise when other git versions are used. The version
was removed by passing `--no-signature` to `git format-patch` which is
now documented in the readme.
Fixes several cases where calling scheduler operations from a command callback could result in NPEs or other issues.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
GCC's static analyzer is correctly reporting that resize() requires an
unsigned integer, but the argument provided in the JNI function could be
negative since it's a signed byte. Throwing an exception if the argument
is negative fixes the warning.
The original idea of LiveWindow telemetry was to automatically make
telemetry data visible to users. This has proved increasingly
problematic in recent years due to the "spooky action at a distance"
of telemetry happening for objects that are only constructed but not
used, and blocking or slow object reads resulting in hard-to-debug
loop overrun conditions.
This allows us to error out on deprecation warnings for thirdparty
libraries and standard library features.
Co-authored-by: Starlight220 <53231611+Starlight220@users.noreply.github.com>
In addition to m_prevError and m_totalError, m_positionError and
m_velocityError need to be reset to 0 when reset() is called.
Otherwise, the next time calculate() is called, the old values will be
used as the previous error, but this is inaccurate since the caller
wanted to reset the state of the PID controller.
* Calculated swerve module states now stored in a member variable
* If ChassisSpeeds(0, 0, 0) is converted to module speeds, the
previously calculated module angle will be conserved, with forward speed
set to 0
* New tests added
This adds a unicycle controller that's a drop-in replacement for Ramsete
and a differential drive controller that controls the full pose and
outputs voltages. The main benefit is LQR-like tuning knobs using a
system model.
The previous documentation suggested that `triggerTime` is the interval until the next alarm, but the implementation is that it is the absolute alarm time.
PMD requires that variables only initialized in the constructor be
final. The compiler errors if those final variables aren't guaranteed to
be initialized, so extra else branches were added to ensure that.
PMD also requires that classes with only private constructors be final.
The equivalent C++ classes were finalized as well, except for
TimeInterpolatableBuffer because it doesn't expose factory functions.
This previously always returned false; the get method it inherited was not used in the getAsBoolean defined in the Trigger class. The fix is to swap get() and getAsBoolean() implementations in the Trigger class.
- Add InterpolatedTreeMap for Java from team 254's 2016 MIT licensed code
- Add InterpolatedMap for C++ from team 3512's code with @calcmogul (original author) permission
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
The Joseph form of the error covariance update equation is more
numerically stable when the Kalman gain isn't optimal. Numerical
instability and filter divergence can occur if the user goes long time
periods between updates and the error covariance becomes ill-conditioned
(the ratio between the largest and smallest eigenvalue gets too large).
The existing implementation will produce a cost of NaN if a tolerance of
infinity is entered, but the limit approaches zero. Being able to
specify that a state has no cost is useful, so this change adds support for
that.
This sets the workflow concurrency to 1 for all workflows. For PRs this means if you push an additional commit older jobs will be cancelled.
The documentation workflow already only runs on tags or merges to main. For this, we cancel previous runs if they are to the same destination (tag or main) but still prevent 2 jobs from running at once if they are spawned from different refs.
This creates a default log file that captures NT changes and
automatically renames the log file based on time and match info.
DriverStation joystick logging will be implemented by the DriverStation
class instead.
When trying to set the tolerance of a ProfiledPID, it fails if you don't give it a velocity value. It was missing a conversion from double to the appropiate unit.
SetPositionOffset was added. Been requested multiple times, and easy to implement.
The javadocs mentioned GetPositionInRotation. It has tripped up many people how to get the absolute position from the encoder (You currently have to have precreated the DutyCycle object). Add this method (as GetAbsolutePostition) to make this easier to do.
The checks for making sure a matching set of values was read was doing direct double comparisions. This worked ok in the DutyCycle case, but has problems in the analog case. Solve this by using an epsilon comparison.
And finally, scale AnalogEncoders analog input to 0-1 instead of 0-5. This was reported a few years ago, but the issue was missed. This caused the encoder to count from 0-5, then 1-6, then 2-7 etc. This is solved and now works correctly.
Closes#3188Closes#4046Closes#4051
And fixes the following issue on CD
https://www.chiefdelphi.com/t/wpilib-analogencoder-java/372649
If xSpeed == -0.0 and zRotation > 0, the algorithm assumes it's in the
third quadrant instead of the first since +0.0 == -0.0.
Also added tests for inverse kinematic functions, fixed some
MecanumDrive test bugs, and added Java MecanumDrive.driveCartesianIK()
and KilloughDrive.driveCartesianIK() overloads with defaulted gyro angle
that C++ already had.
Fixes#4022.
The real robot has match time set to -1.0 until it's enabled, and then
counts down. Disabling the robot sets the time to -1.0.
The sim GUI has been updated to add preset buttons for auto and teleop
match times. The enable match timing checkbox has been removed as it's
no longer required.
The DS socket plugin has also been fixed to properly initialize
matchTime to -1.0 and reset it to -1.0 on disable.
Most of these were unused, the IMU ones were just debug messages.
The only one that wasn't removed is in portable-file-dialogs.cpp since
the replacement looks less trivial.
2K was sufficient for simulation because it's possible to pause time,
but isn't quite enough for looking at real robot data. 20K points
is 400 seconds at 50 Hz which should make pausing plots much more
useful.
As every point is looped over, this does increase CPU utilization
somewhat but doesn't seem to have much of an impact for typical
use cases. Increasing this further will necessitate some greater
optimizations (e.g. an initial cull using binary search).
This can be called in a delayed manner, so it's possible for
m_size to already be at maximum, which results in writing past
the end of the array. Instead, just call AppendValue().
This shows more real world usage then hardcoding the setpoint and PID
gains. There were no current examples using Preferences. This will also
be used to update frc-docs article for Preferences.
While the number doesn't matter, it being old is confusing a lot of
people. We never increment the internal vendordep versions, so using a year
version number was a poor choice.
Closes#3921.
Since the CAN bus can easily become disconnected, we don't want this to crash. Instead, we just want this to report errors. This matches previous behavior.
Changed turnOutput from var to double in SwerveModule. It doesn't make sense for driveOutput and turnOutput to have different types so they should both be doubles.
It seems like the JVM does not handle recursive calls to object monitor based locks correctly. A few bugs in the past have been reported to have caused deadlocks if this occurs. It looks like the version of Java we use is fixed, but there could be other bugs, and it seems like this area of the code isn't tested much. Based on the stacks reported in #3896, it really seems like this is occurring. So we're going to attempt to switch to explicit mutex based classes, which shouldn't have bugs like this, and we will see if that fixes the issue.
It would crash in C++ if the global measurement was sooner than all the
snapshots.
Align Java with the changes and better document computation approach.
It was using the continuous B matrix to compute the feedback gain
instead of the discrete B matrix.
Tests were added for the matrix constructor overloads.
The changes to PneumaticsBase.cpp were to fix errors like the following
from enum classes not being formattable:
```
allwpilib/wpilibc/src/main/native/cpp/PneumaticsBase.cpp:36:9: required from here
allwpilib/wpiutil/src/main/native/fmtlib/include/fmt/core.h:2672:12: error: use of deleted function ‘fmt::v8::detail::fallback_formatter<T, Char, Enable>::fallback_formatter() [with T = frc::PneumaticsModuleType; Char = char; Enable = void]’
2672 | auto f = conditional_t<has_formatter<mapped_type, context>::value,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2673 | formatter<mapped_type, char_type>,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2674 | fallback_formatter<T, char_type>>();
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
Adds HAL layer warning for #3842. This is needed in the case when a
vendor uses the HAL directly rather than using the WPILib I2C class.
This should not result in a duplicate warning for WPILib I2C users due
to the duplicate message checking performed in HAL_SendError().
We don't want to remove the WPILib I2C warning because it gives stack
trace information while the HAL layer one can't.
The angular rate is treated somewhat like an angle during calibration,
but the datasheet says it's angular rate. The variables were renamed to
make this clearer.
This adds the REV Analog Pressure Sensor PSI to volt (and vice versa) conversion to allow setting the compressor config in PSI and getting the sensor reading in PSI. Also adds input validation for pressure values at the higher level.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
It was only being used for fs::remove() (added in #3463), which is easily
replaced by std::remove().
The code change does not affect the WPILib tools, as this code is not used when JSON save files are used.
These classes are useful for storing previous robot positions to use in conjunction with the upcoming pose estimators.
Co-authored-by: Prateek Machiraju <prateek.machiraju@gmail.com>
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Co-authored-by: cttew <cttewari@gmail.com>
Fixes#3827
Adds MotorController inversion for right side, removes inversion in
setVoltage methods.
Also fixes various XboxController negations (was inconsistent throughout examples).
This avoids stack-use-after-scope bugs in code like the following when
the original argument goes out of scope:
```cpp
frc2::Command* RobotContainer::GetAutonomousCommand() {
// Create a voltage constraint to ensure we don't accelerate too fast
frc::DifferentialDriveVoltageConstraint autoVoltageConstraint(
frc::SimpleMotorFeedforward<units::meters>(
DriveConstants::ks, DriveConstants::kv, DriveConstants::ka),
DriveConstants::kDriveKinematics, 10_V);
```
We don't currently support cameras in glass, but it's something we want to do in the future. However, when we do this, glass will completely stop working on N builds of windows, and it would fail to load at all with no messages. To solve this, we can delayload the media foundation dlls that are missing. The executable will then launch even without the dlls present, and we can attempt to load them at runtime and dynamically disable camera support.
When we get around to implementing it, we can just call HasCameraSupport, and dynamically hide all camera related code behind that flag.
More functionality was implemented at the HAL level, so expose that to the wpilib level.
This also does units changes for all the PH related functionality.
shared_from_this will assert if the shared pointer is in the middle of being destructed. Because we access shared_from_this in the message pump, this can easily occur. The solution is to grab the weak pointer, manually attempt to lock it, and only continue if that succeeds. The message pump is already synchronized to the usb camera being destructed, so this is a fine behavior.
With the change from GetInstance to static functions, many functions
don't call DriverStation::GetInstance(), so the DS thread wasn't
getting started by default. Call InDisabled() to make sure this
happens.
Add the remaining HAL functions needed to fully support the Pneumatic Hub and its latest firmware.
- Clear sticky faults
- Get device voltage
- Get 5v supply voltage (used for analog to PSI calculation)
- Get solenoid voltage
- Get solenoid current
- Get device firmware and hardware version
Some minor refactoring was done for naming of some internal functions for consistency purposes.
Refactors retrieving the faults from the device to match the implementation that we have for the Pneumatic Hub. Instead of having a getter function for each fault, there is a single function to get all faults (sticky or normal) for use with the higher level API
Renames functions to be consistent
Removes some functions that don't need to be included in wpilib:
- Identify device - this just flashes the module LED on the device and has no use in wpilib
- Is PDH enabled - the PDH does not change state depending on robot enabled state
PDH frame and signal names were updated in our DBC, and this PR makes use of the newly generated CAN frame helper functions
This also makes the Gradle build work with JDK 17.
The extra JVM args in gradle.properties works around a bug with spotless
and JDK 17: https://github.com/diffplug/spotless/issues/834
PMD.CloseResource was ignored because it's almost always a false
positive, and there are many of them.
- Remove duplicate motor port (2) from C++ SwerveBot/SwerveDrivePoseEstimator
Java has the correct motor ports.
- Fix duplicate port allocation in C++ RomiReference by correcting if/else check
Java logic was already correct, and confirms this change.
UpdateEntries() and Flush() are called from methods that lock the mutex,
so locking it again will cause deadlocks. This also updates the Java
code to make MechanismObject2d::update synchronized like in the C++
version.
As the sensor needs to maintain an actual duty cycle, it can't go all
the way from 0-100, so provide a way to set the min and max and linearly
map between the two.
The root cause of #3747 is CommandScheduler's ds state checks are behind iterative robots checks. This means that the iterative robot state could return enabled, but the DS cache could still be reporting disabled. This results in a race in the Disabled -> Enabled transition, which manifests in commands not running.
Previously, iterative robot base pulled from the DS cache. This meant that the ds cache was always updated before an iterative robot base loop could run. This still had a race, but this could only occur on the Enabled -> Disable transition, which is much less noticeable and would usually just result in a command running for an extra loop.
We can move back to the old behavior by grabbing the new iterative robot base check variables to use the DS cache.
Unlike std::string and std::string_view, this substr() allows a start
greater than the length of the string, in which case an empty string
is returned. This matches llvm::StringRef behavior.
Storage is now nested.
Separate "roots" can be configured which save to separate files.
In particular, this is used to save wpigui and ImGui window position
to a -window.json file.
ImGui's ini (for window position) is mapped to JSON.
You can optionally specify a directory to load from on the command line.
If one isn't provided, it uses the global system directory.
Any changes made are automatically saved here.
Workspace | Open: select directory, the current layout is replaced with that
workspace, and future auto-saves also switch to that location. The main
window size/location is not changed, only the contents.
Workspace | Save As: select directory, the current layout is saved there,
and future auto-saves also switch to that location.
Workspace | Reset: window locations are preserved, but all other settings
are reset to default (including e.g. removing plot windows). This will also
end up clearing the current save file. as with load, the main window
size/location is not changed.
Workspace | Save As Global: "save as" to the global system location
Notably, the main window size/location is only loaded at startup, but is
auto-saved as part of the current workspace.
If something happens with the PD connection, these would have spammed messages continuously.
This wasn't the case previously, and we don't want this behavior now.
The template argument order for UnscentedTransform was reversed to match
all the other UKF classes. Since UnscentedTransform is intended as a
class for internal use only, this shouldn't cause much breakage.
These enable more consistent use of synchronization across the
native libraries. Users can create Event and Semaphore primitives, but
in addition, libraries can set up any handle as an Event-type signal.
Similar to the PCM, we're going to make the PH not do anything with the compressor until the PH HAL object has been initialized. The mechanism we're going to use to signal to the PH that that has happened is to begin sending the state of the solenoids (which will all be set to off at this point).
These relied on the OnStart and OnExit callbacks which were not present
in the wpiutil common CallbackManager code. Add support for these and
fix up other use cases.
Also fixes notifications to correctly filter on event kind.
This fixes a breakage caused by #3133.
This fixes the following warning.
The member function operator== only works in C++17, and the friend operator== only works in C++20.
```
/Users/runner/.gradle/caches/transforms-2/files-2.1/c671f5a5dff922b8870f4eb33f4c8e2a/wpiutil-cpp-2022.1.1-alpha-3-1-g4e3fd7d-headers/wpi/json.h:1847:46: warning: ISO C++20 considers use of overloaded operator '==' (with operand types 'const typename json::object_t::iterator' (aka 'const StringMapIterator<wpi::json>') and 'const typename json::object_t::iterator') to be ambiguous despite there being a unique best viable function [-Wambiguous-reversed-operator]
return (m_it.object_iterator == other.m_it.object_iterator);
~~~~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/runner/.gradle/caches/transforms-2/files-2.1/c671f5a5dff922b8870f4eb33f4c8e2a/wpiutil-cpp-2022.1.1-alpha-3-1-g4e3fd7d-headers/wpi/json.h:1863:20: note: in instantiation of member function 'wpi::detail::iter_impl<const wpi::json>::operator==' requested here
return not operator==(other);
^
/Users/runner/.gradle/caches/transforms-2/files-2.1/c671f5a5dff922b8870f4eb33f4c8e2a/wpiutil-cpp-2022.1.1-alpha-3-1-g4e3fd7d-headers/wpi/json.h:5008:20: note: in instantiation of member function 'wpi::detail::iter_impl<const wpi::json>::operator!=' requested here
if (it != end())
^
/Users/runner/.gradle/caches/transforms-2/files-2.1/c671f5a5dff922b8870f4eb33f4c8e2a/wpiutil-cpp-2022.1.1-alpha-3-1-g4e3fd7d-headers/wpi/json.h:5025:16: note: in instantiation of function template specialization 'wpi::json::value<std::basic_string<char>, 0>' requested here
return value(key, std::string(default_value));
^
/Users/runner/.gradle/caches/transforms-2/files-2.1/c671f5a5dff922b8870f4eb33f4c8e2a/wpiutil-cpp-2022.1.1-alpha-3-1-g4e3fd7d-headers/wpi/StringMap.h:442:8: note: ambiguity is between a regular call to this operator and a call with the argument order reversed
bool operator==(const DerivedTy &RHS) const { return Ptr == RHS.Ptr; }
^
```
We originally moved to setuid admin so user programs could do other
things requiring admin if they wanted. However, these things, like
setting RT priorities of other processes, can usually be done instead as
admin during the GradleRIO 2022 deploy process, or adding commands to
the robotCommand script. By going back to setcap, we can simplify the
HAL code.
Timer reports a negative duration if the sim timing is restarted. This
can be worked around by calling Reset(). Other options included:
1. Have RestartTiming() call Timer::Reset() on a list of instantiated
Timers.
2. Have Timer::Get() reset the timer if it notices time went backwards.
This requires dropping const qualification though, which is a
breaking change that only fixes a minor edge case.
Closes#2732.
I generated lists of includes and uses via
`rg -l deprecated.h | sort -u` and `rg -l WPI_DEPRECATED | sort -u`
respectively. If a file was in the first list but not the second, the
include was unused. If a file was in the second list but not the first,
the include needed to be added.
I started with the output of styleguide#217, then renamed a few classes
to fix compilation.
ntcore's StorageTest needed some manual renaming since it put the Test
word in the middle instead of at the end.
One limitation of wpiformat is test cases that were only named "Test"
were unmodified, and an error was generated. These test cases were
manually given more descriptive names:
* TimedRobotTest mode test cases had "Mode" appended to the name. Java
tests were renamed to match.
* UvAsyncTest and UvAsyncFunctionTest cases were given alternate names
Supersedes #2358 with updates and cleanups.
Closes#2482 and closes#2487 because we shouldn't support both
time-based and count-based debouncing approaches.
Co-authored-by: oblarg <emichaelbarnett@gmail.com>
- Correct several comments that referenced elevator
- Changed noise to be 1 encoder tick instead of half a degree
- Changed gear ratio and PID value to be better tuned
- Updated bounds to be similar to a single jointed arm
Inconsistent names were found using the following regular expressions.
* `rg "TEST(_F|_P)?\(\w+,\s+\w+Test\)"`
* `rg "TEST(_F|_P)?\(\w+,\s+Test\w+\)"`
* `rg "TEST(_F|_P)?\(\w+Tests,\s+\w+\)"`
Fixes#3495.
* Replace Matrix<> with Vector<> where vectors are explicitly intended.
I found these via `rg "Eigen::Matrix<double, \w+, 1>"`.
* Pass all Eigen matrices by const reference. I found these via `rg
"\(Eigen"` on main (the initializer list constructors make more false
positives).
* Replace MakeMatrix() and operator<< usage with initializer list
constructors. I found these via `rg MakeMatrix` and `rg "<<"`
respectively.
* Deprecate MakeMatrix()
Now that there are only 16 instances, store them all statically.
Make tests more reliable by using different ports for each connection in listener tests.
Having PCM as a singleton is a problem, as multiple things need to use it, and that gets really ugly. This changes PCM's to be a reference counted object, that can be passed around and constructed from multiple places.
In Java, this is using a map to hold a data store with a ref count, and allocating new objects any time a duplicate is requested.
In C++, this uses a trick constructor to store a PCM instance in the data store itself. This instance can then be passed to base objects using std::shared_ptr's aliasing constructor, which means constructing a solenoid from a PCM is not allocating after the 1st one.
This did require removing sendable from PCM. A compressor class was added back in to act as sendable for the PCM.
After this change is finished, the only change RobotBuilder and Team Code would require is passing a module type to solenoid constructors.
Co-authored-by: sciencewhiz <sciencewhiz@users.noreply.github.com>
* Address sanitizer uses -DCMAKE_BUILD_TYPE=Asan
* Thread sanitizer uses -DCMAKE_BUILD_TYPE=Tsan
* Undefined behavior sanitizer uses -DCMAKE_BUILD_TYPE=Ubsan
Only ubsan is enabled in CI for now because asan and tsan report
failures.
The standard Java package is missing BooleanConsumer as well as Float classes.
Update SendableBuilder to use it instead of internal BooleanConsumer
interface.
In some cases, knowing roborio 2 might be useful. This also creates a higher level enum that might be usable later for the discussion on more complex runtime types.
Internal headers are no longer allowed as of
https://gitlab.com/libeigen/eigen/-/merge_requests/631. Based on
benchmarking I conducted in that thread, there doesn't seem to be a
performance penalty for including the full headers anymore.
The move ctor is trying to cast from e.g. SendableHelper to PIDController before PIDController has been constructed, which is potentially UB. We don't actually use anything in PIDController though, so it's OK in our case.
This upgrade uncovered two issues:
ntcore wasn't forcing C++17, which caused a linker error with googletest
Matcher symbols:
```
undefined reference to `testing::Matcher<std::basic_string_view<char, std::char_traits<char> > >::Matcher(std::basic_string_view<char, std::char_traits<char> >)'
```
test_span.cpp wasn't including <algorithm> to use std::sort() and
std::is_sorted().
This is an alternative to #2344 that handles arbitrary order derivatives
of arbitrary precision. The downside is that since it's part of
LinearFilter, it can't utilize the units type system in the same way to
make Calculate()'s input type different from its output type.
The HAL Notifier thread is started when the first Notifier is created
and stopped when the last Notifier is destroyed. Currently,
HAL_SetNotifierThreadPriority() will cause a segfault if the Notifier thread
hasn't been started yet (that is, if no Notifier have been created yet).
This change makes HAL_SetNotifierThreadPriority() store the RT and
priority setting. If the thread has already been started, it will set
the priority immediately. If it hasn't, HAL_InitializeNotifier() will
set the priority when it starts the thread.
This PR gives the Notifier HAL thread RT priority 40 in RobotBase after
HAL initialization and before the user code is run. This drastically
improves scheduling jitter for TimedRobot's AddPeriodic() functions (in
3512's experience).
It's too risky to set user code as RT because badly behaved code
will lock up the Rio (potentially requiring safe mode to recover).
This needs the user program to be setuid admin to succeed.
- GenericHID is now concrete, and has only getRawAxis/Button(int) functionality
- getXxx() has been moved into Joystick as that's the only place where it makes sense
- Hand (and therefore getXxx(Hand)) has been removed, replaced by specific getLeft/RightXxx() methods in XboxController and the new PS4Controller class
- C++ ::Button:: and ::Axis:: enums have been converted to identically-namespaced static constexpr ints
This saves time in CI spent performing the same source-level checks in
every build job. Checkstyle, PMD, and Spotless are now run once in the
"Lint and Format" job.
The -PskipPMD flag was replaced with a -PskipJavaFormat flag that
disables Checkstyle, PMD, and Spotless.
They don't provide much utility for the end user. A print at the call to
HAL_ObserveUserProgramStarting() was added in their place so it's still
clear when constructors have finished running.
Currently, we have functions like TeleopInit() for running code on mode
entry, but no such functions for running code on mode exit, and it's
cumbersome to add those in user code without making a custom robot
class. This PR adds exit functions to TimedRobot.
Some example use cases include DisabledExit() for operations when the
robot enables (whether that be into teleop, autonomous, or test) and
AutonomousExit() for disabling feedback controllers.
This is a basic C++ example that demonstrates a simple differential drive implementation using “tank”-style controls through the DifferentialDrive class and an ordinary joystick.
* Rename Butcher tableau sections in NumericalIntegration such that
top-left is c, top-right is A, and bottom-right is b
* Move edu.wpi.first.math.Discretization to
edu.wpi.first.math.system.Discretization
* Sort Java Discretization to match C++ function order
* Add tests for Java Discretization
* Required adding Runge-Kutta time-varying impl to tests
* Move C++ Runge-Kutta time-varying impl to tests only
* Users don't need it
Our patches for the DARE and [[noreturn]] attributes were merged
upstream. We missed their monthly release window by a day, so we'll use
a commit hash for now.
The current 2021.3.1 release refers to `java/lang/IOException` which causes the following exception when using `toPathweaverJson` or `fromPathweaverJson`:
```
java.lang.NoClassDefFoundError: java/lang/IOException
at edu.wpi.first.math.WPIMathJNI.fromPathweaverJson(Native Method)
at edu.wpi.first.wpilibj.trajectory.TrajectoryUtil.fromPathweaverJson(TrajectoryUtil.java:79)
```
Also refactored RKF45 implementation to match the new style, which is
easier to read.
The tests were switched from RKF45 to RKDP since it's more accurate.
This reverts commit d068fb321f (#3420).
The 18.04 docker images now use GCC 8, which was the original reason for
updating. 20.04 uses a much more recent libc, so staying with 18.04
enables more Linux platforms to use the binaries.
The non-NT portion has been moved to wpiutil.
The NT portion has been moved to ntcore (as NTSendable).
SendableBuilder similarly split and moved.
SendableRegistry moved to wpiutil.
In C++, SendableHelper also moved to wpiutil.
This enables use of Sendable from wpimath and also enables
moving several classes from wpilib to wpimath.
Some valid warnings like throwing NullPointerException or using a for
loop instead of System.arraycopy() were fixed.
Abstract classes marked with PMD.AbstractClassWithoutAbstractMethod were
made concrete because they already had protected constructors.
Fixes#1697.
This also fixes a member function name inconsistency between languages
and adds missing documentation to C++'s KalmanFilterLatencyCompensator.
Fixes#3229.
- Twine, StringRef, Format, and NativeFormatting have been removed
- Logging now uses fmtlib style formatting
- Nearly all uses of wpi::outs/errs have been replaced with fmt::print() or
std::puts()/std::fputs() (for unformatted strings).
- A wpi/fmt/raw_ostream.h header has been added to enable
fmt::print() with wpi::raw_ostream
This allows sim modules to be statically linked into an executable to
create a "perfectly static" simulated desktop program. The entry point
was changed to be unique when building static libraries to avoid symbol
collisions.
The implementation of wpi::circular_buffer has been effectively replaced
with a dynamically sized copy of wpi::static_circular_buffer with a
resize() member function.
The units for angular Kv and Ka were inconsistent with the derivation. A
second factory function overload was added for angular units that uses a
trackwidth to convert to the other form.
Notice how section 15.2 of https://file.tavsys.net/control/controls-engineering-in-frc.pdf
defines the angular feedforward as u = Kv,angular v instead of u = Kv,angular + omega.
The units cancel for elements of A but not B, so just the B matrix was incorrect in our code.
This breaks existing C++ code since the units are part of the function
signature.
Use ghc::filesystem as fill on older GCC (e.g. RoboRIO).
This can be removed once all GCC platforms have upgraded to 8.1 or later.
File open functionality has been retained from LLVM but moved to "fs" namespace
and tweaked for improved consistency with std::filesystem (e.g. error_code is
passed by reference instead of returned).
Also update WPILibC's Filesystem functions to return std::string.
The command and shuffleboard integration tests were removed because
their unit tests counterparts already provide adequate coverage. Java
already removed these.
A lot of these are breaking changes. frc::Timer was replaced with the
contents of frc2::Timer. The others were in-place argument changes or
removing deprecated non-unit overloads.
frc/Base.h isn't the first header included basically anywhere, so the
compiler will fail on C++17 things before the asserts in this header are
processed.
This reverts commit a79faace1b.
This change will be superseded in a non-breaking way by changing to static functions and deprecating GetInstance() entirely.
This version incorporated the patch we were manually applying, so we're
synced back up with upstream now except for some minor #include changes
to reduce header bloat.
Substantially improves Mechanism2d by moving it to NetworkTables and adding
a robot API to create the mechanism elements, instead of requiring a JSON file.
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
The Drive Subsystem was supplying an incorrectly constructed
Rotation2d to the odometry update method. Rotation2d constructor
was being called with heading in degrees, not radians as required.
Also deprecate SpeedController in favor of motorcontrol.MotorController and
SpeedControllerGroup in favor of motorcontrol.MotorControllerGroup.
The MotorController interface is derived from the SpeedController interface
so that code such as SpeedController x = new VictorSP(1) continues to
compile (just with a warning).
SpeedControllerGroup and MotorControllerGroup are independent classes;
both implement the MotorController interface.
This enables use of types that have a no-args constructor rather than one that takes an explicit zero value.
For numeric types, value initialization will result in a zero value, so this is not a functional change.
This sensor has had zero usage for many years and was last in the KOP
over a decade ago. There are much better rotation sensors available,
and it's no longer worth maintaining this class.
- Add raw support for pose lists > 255/3 in length
- Improve drag selection, especially with closely overlapping objects
- Drag selection of corner also highlights center of object with smaller circle
- Multiple styles (box, line, closed line, track)
- Configurable line and arrow settings (color, weight)
- Add tooltip for object name, index, x, y, rotation
- Context menu for pose edit/add/remove
- View/edit in feet or inches as well as meters
- Configurable object selectability
Implementation: use vector of Pose2d internally, use units
Previously the following sequence was broken:
- Add two plot windows (creates Plot<0> and Plot<1>)
- Delete Plot<0>
- Try to create a plot window
This failed because it would try to create Plot<1>, which already existed.
It was necessary to also destroy Plot<1> before another plot could be added.
This change fixes this case by trying all 0-N cases.
Improves consistency across all classes.
Affects Preferences, LiveWindow, and CameraServer.
Old commands Scheduler::GetInstance() was not updated as this is already
deprecated.
This function relies on the behavior of snprintf returning an error value
when the buffer is too small. By default, _snprintf_s aborts on Windows
instead of returning an error value.
This caused Glass to fail when trying to print a large NT value to a string.
On some systems, StopClient et al can take a long time to execute.
Instead run these on a separate thread to avoid blocking the GUI.
Also add option to get IP from DS (default on).
The gyro offset should be determined from the desired initial pose, not the current pose. This fix reflects the behavior of the odometry classes and the C++ holonomic pose estimators.
The atReference() method previously used the rotation error between the
desired trajectory state and the current pose. This was a bug because we
allow teams to use custom rotation setpoints and that wasn't being taken
into account.
This was already removed from C++ in the offseason and replaced with
MathUtil.inputModulus(). We just neglected to do that for Java; it was
never intended to see a season release. Its implementation is incorrect
compared to inputModulus() as well.
See https://github.com/wpilibsuite/allwpilib/issues/3168 for discussion.
Because of Java's type system, it is actually literally impossible to check for this cast at runtime. So instead, the only option is to suppress it. Only suppressed for the specific function.
This fixes an issue with scaling on Retina displays where the frame
buffer size was double that of the window size, resulting in a content
scale factor of 2. This scale factor caused elements to appear too
large, even on the smallest zoom setting.
This change does not affect external monitors on macOS because the
reported content scale was 1 anyway.
The ranges and which value was specified as highest were incorrect on
some of them. On Linux, the range is 1 to 99 with 99 being highest.
From `man 7 sched`:
```
Processes scheduled under one of the real-time policies (SCHED_FIFO,
SCHED_RR) have a sched_priority value in the range 1 (low) to 99 (high).
```
Also clean up the relevant javadoc and doxygen comments.
Instead of "/SmartDashboard/name" they now default to "name (SmartDashboard)".
This allows for smaller windows while preserving the name without requiring
user customization.
The wpimath APIs use std::array, which doesn't do size checking. Passing
an array with the wrong size can result in uninitialized elements
instead of a compilation error.
This is a breaking change but is worthwhile to avoid hard-to-debug errors.
- Remove sim checkstyle suppression
- Add [[nodiscard]] to C++ register callback functions
- Add a couple of missing sim functions
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
Co-authored-by: Starlight220 <yotamshlomi@gmail.com>
This also shifts the trajectory up and to the right so that the robot is
always visible in the Field GUI during traversal. Some drive constants
and trajectory constraints were also synced between the two languages.
This modifies the mecanum drive, differential drive, speed controller,
and PID controller widgets to only be writeable when .controllable is
set to true.
The stall torque, stall current, and free current are now multiplied by
the number of motors instead of just the stall torque. This produces the
same values for Kt and Kv regardless of the number of motors; the motor
resistance still affects the system response.
For an elevator model, the response should be the same as before since a
factor of "number of motors" shows up in the same place in the
acceleration calculation, but the current calculation will also be
correct now.
Using the plant output means that measurement noise can be incorporated.
SingleJointedArmSim (in C++ and Java) and ElevatorSim (in C++) used the
state instead of the measurement.
Closes#3042
Flip the TeleopArcadeDrive axis directions so that positive
values for x-axis speed result in the Romi driving forward (in the
direction of the Raspberry Pi USB ports).
frc::NormalizeAngle(), units::math::NormalizeAngle(), and
frc::GetModulusError() were replaced with frc::InputModulus() and
frc::AngleModulus().
They were placed in wpimath/src/main/native/include/frc/MathUtil.h for
C++ and wpimath/src/main/java/edu/wpi/first/wpiutil/math/MathUtil.java
for Java.
* Add .clang-tidy configuration.
* A separate .clang-tidy is used for hal includes to suppress modernize-use-using
(as these are C headers).
* Add NOLINT where necessary for a clean run.
* Add clang-tidy job to lint-format workflow. This workflow is now only run on PRs.
To reduce runtime, clang-tidy is only run on files changed in the PR.
Two wpilibc changes; both are unlikely to break user code:
* BuiltInAccelerometer: Make SetRange() final
* Counter: Make SetMaxPeriod() final
After these cleanups, the only file that does not run cleanly is
cscore_raw_cv.h due to it not being standalone.
Updated the RomiReference example to have autonomous example.
Updated RomiReference and both Romi templates to use Encoder.getDistance().
Removed motor inversion.
A few virtual functions are called by constructors or destructors, which is
dangerous in C++ (as an overridden virtual impl won't be called, only the
one in the current class). Fix by either marking the function final or
not calling at all (if possible).
Also update Checkstyle to 8.38.
Google changed their style guide from the last time we imported it. This PR brings in those naming changes. The change they made is allowing single letter member, parameter, and local variable names. They also added a lambda naming scheme and I thought it would be good to bring that in too.
This makes code easier to read and more consistent between C++ and Java.
Also update clang-format settings to always add a line break (even if no braces are used).
This adds an overload of UnscentedKalmanFilter::Correct() that takes a
custom measurement covariance but uses default mean and residual
calculation functions.
Closes#2965.
This is a breaking change to the WebSockets layer to align it with
recent specification documentation work.
To support this, HAL SimValue changed readonly to a direction enum.
This allows specifying bidirectional in addition to input and output.
The SimValue change is specifically designed to avoid API and ABI breakage.
This is completely transparent in C++; in Java a new callback class was added,
and the old readonly functions have been marked deprecated.
A new SimValue creation function for enums allows specifying double values
for each enum value, not just strings. This allows mapping enum values to
doubles in the WebSockets layer.
A ":" in the SimDevice name now maps it to different WebSocket types (e.g.
"Accel:Name" becomes type "Accel", device "Name"). The type is hidden
in the GUI.
Other WebSockets changes:
* Implemented match_time and game_data
* Added joystick rumble data
* Added builtin accelerometer support
* SimValue enums are mapped to string and double value on WS interface
* Added WebSockets protocol specification
* Added READMEs
If the strncpy() bound is equal to the destination size and the source
string is longer than 256 bytes, strncpy() won't write a null terminator
for the destination string.
This allows joystick testing without a physical joystick.
Comes with a default set of keyboard mappings, but these are fully customizable by the user.
Up to 4 virtual joysticks are supported.
Default keyboard mappings:
Joystick 0: axis 0: AD, axis 1: WS, axis 2: ER, buttons ZXCV, POV on numeric keypad
Joystick 1: axis 0: JL, axis 1: IK, buttons M,./
Joystick 2: axis 0: left/right arrow, axis 1: up/down arrow, buttons insert/home/pgup/del/end/pgdn
Also adds support for DS-style hotkeys of []\ enable, Enter disable, and spacebar disable.
All of these are disabled by default and must be explicitly enabled by the user.
Currently, Encoder.reset() must make a round trip to the sensor and back
in order for the count to be updated for the user program. As the sim layer
also resets the internal encoder count, this creates a race condition (a WS
message with a new count can be "in flight" during a reset and update the
count).
This changes the WS layer to not put reset on the wire, but instead keep an
offset count internal to the robot program. The value on the wire is not
reset, but rather all sends and receives are adjusted as necessary to the
internal robot count.
This approach is straightforward, but does result in the value on the wire
not matching the value in the user program. A future improvement will fix
this, but this change fixes the immediate race condition problem.
The change to SendableBuilder to add GetTable() added a virtual function
early in the class definition. This is an ABI break for vendor libraries.
Attempt to workaround this breakage by moving GetTable() to the end of the
class definition.
This will make is so we can get the right artifact to the installer, and we can do it automatically and its guaranteed to match what built the artifacts.
This reuses many pieces of the current simulation GUI. The common pieces have
been refactored into the libglass library.
The libglass library is designed to be usable for other standalone data
visualization applications (e.g. viewing data logs).
The name "glass" comes from "glass cockpit", as the application features
several multi-function displays that can be adjusted to display robot
information as needed.
Pose and state estimators can filter latency-compensated global measurements and fuse them with state-space drivetrain model information to estimate robot position. They are drop-in replacements for the existing odometry classes.
Co-authored-by: Declan Freeman-Gleason <declanfreemangleason@gmail.com>
Co-authored-by: Prateek Machiraju <prateek.machiraju@gmail.com>
Co-authored-by: Claudius Tewari <cttewari@gmail.com>
Co-authored-by: Matt <matthew.morley.ca@gmail.com>
This makes AtSetpoint() return false after the setpoint is changed with
SetSetpoint().
Closes#2821.
Co-authored-by: Prateek Machiraju <prateek.machiraju@gmail.com>
This fixes an issue with some commands not correctly requiring their
subsytems. Furthermore, an execute() method was added to the
DriveDistance command to continuously update the voltage command.
Also deletes object files.
Both of these things are only done on the build server (-PbuildServer flag).
This will remove all test folders, which removes lots of copies of dependencies.
This also fixes an issue where gtest exectubables were installed for cross builds, even though they should not have been.
This bumps the version number of thirdparty-imgui in Gradle and adds
imgui_stdlib.cpp into the sources in CMake, as well as adding a new
include directory.
This issue only existed on the initial iteration. When timing is paused and stepped,
initialize() and execute() get called with the same timestamp the first time, which
would result in a divide by zero. All subsequent steps advance timing and only
call execute() so the time deltas are all set correctly.
There were three options for where to put this function:
1. A free function in LinearQuadraticRegulator.h. Returning a K matrix
means the user can't use the LinearQuadraticRegulator in a loop
anymore.
2. A default argument added to ctors in LinearQuadraticRegulator for a
time delay (default of 0). This has the smallest API footprint from
the user perspective, but it bloats the already substantial
constructor overload set of LinearQuadraticRegulator.
3. A member function in LinearQuadraticRegulator that modifies the
internal K. This would still have to take in a LinearSystem or (A, B)
pair because the ctor doesn't store it. Storing it internally feels
like paying for what we don't use most of the time.
I went with option 3.
I verified the tests's expected values in Python with
scipy.linalg.fractional_matrix_power().
Closes#2877.
If a Sendable like SendableChooser is destroyed and recreated, it leaves
a stale object in the Sendable registry. Using this object results in a
crash. This patch avoids using the stale object.
We should remove stale objects from the global registry upon object
destruction, but this fixes the crashing issue for now.
Closes#2818.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Previously this sent just the raw analog value; the scaled value is likely what users expect.
Co-authored-by: Corey Applegate <coreya@centralmcgowan.com>
- Add link to code of conduct
- Update clang version used to 10 to match CI
- Update pull request format to match current practice
- Change Azure references to Actions
This address some problems with the LinearSystemLoop class that were discovered through testing.
The initial state estimate of the observer was set to the provided initial state rather than zero as previously, a non zero initial state passed into reset() would lead to a discrepancy between the current state estimate and the actual system state.
The CMake enable/disable flags as currently structured are a confusing mix of
WITH, WITHOUT, and USE with odd defaults. This changes the flags to consistently
use WITH and default the build options to everything enabled.
Currently, StepTiming() advances the time by the given delta, then runs
any Notifiers that expired within that timeframe until their expiration
times are in the future. This doesn't reflect how the Notifiers would
actually run on a real robot. For example, if a Notifier measures the
time between calls for state-space model advancement, it would measure
a large jump in time once, then zero for subsequent runs until the
Notifier was caught up to the current time.
With this change, the time is incremented by the full delta or until the
soonest Notifier, whichever has the smaller delta, then Notifiers set to
expire at that time are run. This is repeated until the time has been
advanced by the full delta. For the state-space model Notifier situation
mentioned before, it would measure multiple small time jumps instead of
one big one.
Currently, teams have to make a Notifier to run feedback controllers
more often than the TimedRobot loop period of 20ms (running TimedRobot
more often than this is not advised). This lets users add callbacks to
the main robot loop that run at a user-defined period. This allows
running feedback controllers more often, but does so synchronously with
TimedRobot so there aren't any thread safety issues.
To make the tests reliable, the synchronization in simulation Notifiers
had to be reworked. StepTiming() now waits for all Notifiers to reach
HAL_WaitForNotifierAlarm(), then steps the time, then lets any expired
Notifiers run.
While there, we made some variable names more descriptive and added more
comments.
There were three bugs:
1. The input range variables used in ProfiledPIDController::Calculate()
weren't being updated
2. The modulus error calculation was incorrect.
3. The setpoint wasn't being wrapped like the goal, so the invariant
that the error remains less than half the input range was violated.
(Thanks to @CptJJ for pointing this out and suggesting a fix.)
By storing the previous dt, it can be moved into Correct() where it is
actually used. This lets us take the continuous R as an argument in the
user-provided R overload.
This does not introduce any breaking changes for teams that used the TrajectoryGenerator API for
quintic splines with poses.
The GetQuinticControlVectorsFromWaypoints() method was removed because it is not possible for us (or
would require breaking changes to the shape of the splines) to generate only one quintic control vector
per Pose2d. Users who actually have control vectors directly (i.e. not from Pose2d objects, but a
dashboard such as PathWeaver) should have the number of control vectors correspond to the number of
"waypoints" and can call GetQuinticSplinesFromControlVectors() directly.
Based on run of include-what-you-use.org to identify unused include files in various .h and .cpp files.
The changes mostly fall into 3 categories:
- Actually unused includes - copy-paste errors, not removing includes after cleaning up code, etc
- A too-broad include used where a more specific (and hopefully smaller) header will do
- Interface .h files including headers only needed by the .cpp implementation - moving from .h to .cpp
will mean that code which uses the .h doesn't pay the price of processing the header file they don't need
Old behavior is available via StepTimingAsync.
This makes it significantly easier to use simulation timing with notifiers.
Also update tests to use simulation framework. This also speeds up the
timing-dependent tests by using simulation timing. ResourceLock is used
in the Java tests to prevent parallel execution.
While we're here, tweak HAL Notifier implementation:
- Use wait_for instead of wait_until in WaitForNotifierAlarm
- Check for triggerTime = UINT64_MAX in UpdateNotifierAlarm
If the model is unstable, it will almost always diverge within 10
seconds, and the results are rather dramatic. We're also reducing the
threshold to 100 meters because the drivetrain is moving in a small
circle. The translation norm is also used for this reason; the X
component alone regularly crosses zero since the drivetrain moves in a
circle.
This isn't appropriate for a RAII class. In particular, it can cause
foot-shooting in simulation mode if the result of
HALSIM_GetSimDeviceHandle is passed instead of HAL_CreateSimDevice.
Some vestigial functions were never removed, and C++ single-jointed arm
sim was missing a flag for disabling gravity simulation. This is useful
for mechanisms like turrets.
Fixes#2738.
The Gradle heap size is currently set to 1G, and that's becoming too
small for our Linux build.
Developers who want to override this without editing the project's
build.gradle can override these settings with gradle.properties in
GRADLE_USER_HOME (see
https://docs.gradle.org/current/userguide/build_environment.html for
details).
In the second constructor, a new LinearSystem is created and set to
m_plant. This takes a const ref though, so it's storing a reference to a
temporary object. After the constructor finishes, m_plant points to an
invalid object. When Update() is called, it will crash with a
segmentation fault.
This patch fixes the use-after-free by making m_plant a LinearSystem
value type. The first constructor will generate a copy, but that only
happens once.
This includes physics simulation support for arms/elevator models, as well as differential drivetrains.
Swerve might be added at a later date.
Co-authored-by: Claudius Tewari <cttewari@gmail.com>
Co-authored-by: Prateek Machiraju <prateek.machiraju@gmail.com>
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
This helps reduce compilation overhead. I tried slimming down includes
of <Eigen/QR>, but the householderQr() function we use from there
requires including dependency headers from Eigen that don't fit with
lexographic ordering. It didn't seem worth the effort to work around.
This won't affect user code at all since all the Eigen feature usage
here is internal only; users generally only need <Eigen/Core>.
It was added as part of Bryson's rule described in
https://file.tavsys.net/control/controls-engineering-in-frc.pdf. It
doesn't really simplify usage though, and the same thing can be
replicated by multiplying the elements of Q by rho manually. It's easier
to do it that way, it's how 3512 has been doing controller debugging for
a while, and it's probably what other teams will do as well instead of
using the "more structured" way.
Removing these unhelpful overloads also simplifies the LQR interface.
The uid was getting incremented by 1 during registration but not decremented
by 1 during cancellation, so cancellation didn't work correctly.
As the underlying registration ensures a non-zero result, don't increment
the result.
I didn't notice a performance difference between the original
implementation and this one for a flywheel simulation, so this
simplifies a lot of internals.
This class can no longer implement KalmanTypeFilter because that class
allows setting the error covariance for use in the
KalmanFilterLatencyCompensator class. This won't impact the holonomic pose
estimators that use KalmanFilterLatencyCompensator because they all use an EKF.
The platform-specific code now only has create, update, and delete texture.
Image reading functions have been moved to common code.
Also add pixel data functions and image data functions in addition to image
file loading.
SourceLink embeds the git repo and hash into the pdbs, which allows VS to get the source files exactly matching a pdb directly from github.
Only VS and WinDbg are supported currently, but there are issues in the vscode tools repo to enable it there.
This avoids users having to call both IsOperatorControl() and IsEnabled() to figure out if their robot is
enabled and in the teleop state. The expression above involves calling two methods that each have their
own lock.
These new methods should only involve locking one mutex, since only one call is made to HAL_GetControlWord().
These hide the platform specifics behind a common C++ API. Platforms:
- Windows: DirectX 11 (with 10 backwards compatibility)
- Linux: OpenGL 3
- Mac: Metal
This allows access to HAL-level simulation data via a WebSocket connection.
The server additionally serves local files.
The following environment variables can be used for configuration:
HALSIMWS_USERROOT (server) - local directory to use for file serving for /user/ URIs, defaults to ./sim/user
HALSIMWS_SYSROOT (server) - local directory to use for file serving for all other URIs, defaults to ./sim
HALSIMWS_URI (client or server) - WebSocket URI, defaults to /wpilibws
HALSIMWS_PORT (client or server) - port number, defaults to 8080
HALSIMWS_HOST (client) - host to connect to, defaults to localhost
Co-authored-by: Zhiquan Yeo <zyeo8@bloomberg.net>
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
Co-authored-by: jpokornyiii <jpokornyiii@gmail.com>
Testing Actions
use home env variable
Use ~ instead of home
update upload-artifact to v2
Do not specifiy branch glob
Fix architecture typo
Simplify on block
Add apt-get update step
Revert tolerance increase
Add publishing
Add vcpkg
The wpimath library is a new library designed to separate the reusable math functionality
from the common utility library (wpiutil) and the hardware-dependent library (wpilibc/j).
Package names / include file names were NOT changed to minimize breakage. In a future year
it would be good to revamp these for a more uniform user experience and to reduce the risk
of accidental naming conflicts.
While theoretically all of this functionality could be placed into wpiutil, several pieces
of this library (e.g. DARE) are very time-consuming to compile, so it's nice to avoid this
expense for users who only want cscore or ntcore. It also allows for easy future separation
of build tasks vs number of workers on memory-constrained machines.
This moves the following functionality from wpiutil into wpimath:
- Eigen
- ejml
- Drake
- DARE
- wpiutil.math package (Matrix etc)
- units
And the following functionality from wpilibc/j into wpimath:
- Geometry
- Kinematics
- Spline
- Trajectory
- LinearFilter
- MedianFilter
- Feed-forward controllers
Drake is a collection of tools for analyzing robot dynamics and building control systems.
See https://drake.mit.edu/ for details.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
The Gradle heap size default is 512M, and that's becoming too small for our builds.
Developers who want to override this without editing the project's build.gradle can
override these settings with gradle.properties in GRADLE_USER_HOME (see
https://docs.gradle.org/current/userguide/build_environment.html for details).
Currently, these two tests take several seconds to complete and fail
intermittently in Windows CI. This is caused by relying on wall clock
time.
Sampling the trajectory with wall clock time means the simulation must
run for several seconds to reach the end of the trajectory. Also, the
controller can become unstable when Windows CI experiences process
scheduling delays of several hundred milliseconds. Feedback controllers
don't cope well with large delays on systems with fast dynamics.
This patch uses the mocking functionality of frc::Timer to advance the
clock by 5ms at every timestep instead of using the wall clock time.
This has two benefits:
1. The tests complete much faster because the simulation can step
forward faster than real time.
2. The controller is more stable because the sample period is uniform,
which should fix the occasional failures.
Remove WaitForCachedData as it's no longer required.
Also properly handle caching / transition detection logic that occurs at the
WPILib level.
This also changes DriverStation::IsNewControlData() to check for WPILib-level
caching instead of wrapping the HAL function.
The new getRotation2d() method in the Gyro interface was passing
an angle in degrees to a constructor that accepts radians.
Use fromDegrees() factory function instead.
Using GetAverageVoltage will reduce the noise in potentiometer reading. Potentiometers are unlikely to be used where the minimal lag averaging introduces would impact control loop stability.
This makes it much more user-friendly to use simulation classes without needing
to ifdef for C++ to avoid linker errors or be very careful about construction
to avoid runtime errors in Java.
This is a derived class of HttpServerConnection that implements the
WebSocket upgrade pieces. This combination is pretty common so is
worth refactoring here.
When not direct mapped, make index constructors private and add factory
functions for channel and index.
Co-authored-by: GabrielDeml <gabrielddeml@gmail.com>
This allows disabling/enabling SimDevices via prefix matching. This can be
used to force devices that normally use SimDevice in simulation mode to
instead talk directly to the hardware as in normal operation.
pose.Translation().X() and pose.Translation.Y() are common operations,
so shortening them to pose.X() and pose.Y() would be convenient.
Java uses the getX() convention so that is used instead of X() for Java.
We already have predefined linear acceleration units and angular
velocity units. This makes defining acceleration constraints for angular
trapezoid profiles more convenient.
No tests were added for this because the base unit conversions are
already tested. Angular acceleration just adds another time dimension.
With the new extraction method, we would need to provide an opencv. However, all of our tools that use opencv use an alternate version of OpenCV, so that would interfere.
This adds an artifact where opencv is statically linked into cscore, but wpiutil is a shared dependency. This solves some shared state hacks, and the extraction works so much better, so its worth making this change to allow that
Also move some things in HAL for consistency.
WAS:
C++:
- C APIs: #include "mockdata/AccelerometerData.h"
- User side class: #include "simulation/AccelerometerSim.h"
Java:
- JNI APIs: hal.sim.mockdata.AccelerometerData (and a few classes in hal.sim)
- User side classes: hal.sim.AccelerometerSim
IS:
C++:
- C APIs: #include "hal/simulation/AccelerometerData.h"
- C++ class: #include "frc/simulation/AccelerometerSim.h"
Java:
- JNI APIs: hal.simulation.AccelerometerData
- User side class: wpilibj.simulation.AccelerometerSim
* Add new combined native class loader
Allows us to extract a list of binaries that depend on each other, and load them successfully
It is correct that there is no implementation in wpiutil for the new native method. That is a requirement, because its needed to load the libraries, and we cant load the wpiutiljni native library since it depends on wpiutil. Instead we have a separate library built with the tools plugin that handles everything
Previously this would list ALL /dev/video* devices. In recent versions of
Linux this leads to listing duplicate devices, as many USB cameras provide
both a video device and a metadata device, and only the video device can
actually be used for streaming.
The most common mistake users (including contributors to WPILib) seem to make while creating new constraints is ignoring some sort of edge case that causes the calculated minimum acceleration to be greater than the calculated maximum acceleration.
This specialized exception, with its detailed error message, should make it easier and quicker for said users to debug and fix bugs within their constraints.
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
If the 64 bit FPGA timer rolls over, a 32 bit value is added for
the rollover, an artifact of when it was a 32 bit timer.
The 64 bit microsecond timer won't rollover for 500k years so remove the
check for simplicity.
Fixes#2504
Valgrind caught this one. If you default initialize a Trajectory, it
doesn't initialize m_totalTime. This means a subsequent call to
Trajectory::TotalTime() returns the value of an uninitialized variable.
3512's software was using 0_s as a sentinel value for when a trajectory
was empty. We didn't notice a problem before because Linux zero-inits
memory.
Using this overload makes the thread backing the Notifier run at
real-time priority. This improves scheduling jitter substantially (5ms
+- 2ms down to 5ms +- 1ms).
A version isn't provided for Java because making threads real-time can
cause GC deadlocks.
This is an inline decorator for setting the name of a command
(equivalent to calling setName()).
It's not possible to implement this for C++, as it would slice the derived
class to return it by value.
The DutyCycleEncoder class initializes AnalogTrigger, which is not supported in simulation.
To avoid this, do not use AnalogTrigger (or Counter) in simulation mode.
Fixes#2367
Co-authored-by: Peter Johnson <johnson.peter@gmail.com>
This was caused by m_epochs storing the timestamps as nanoseconds while
the epoch printing code expects microseconds. Adding a duration cast
fixes this.
Java stores the epoch timestamps in a double as microseconds, so it
doesn't exhibit this bug. The comments were updated to make this more
obvious.
Fixes#2392.
Previously, it could take the long way around. This recomputes the
profile goal with the shortest error, thus taking the shortest path.
Also removed the setpoint clamping from PIDController::SetSetpoint()
because it's unnecessary to make PIDController behave correctly for
a modular arithmetic input, and it breaks the setpoint calculation in
ProfiledPIDController otherwise.
Fixes#2277.
This is useful for undoing transformations. One application my FRC team
found was converting perspective n-point data from a "camera to target"
coordinate frame transformation to a "target to camera" coordinate frame
transformation.
A typedef for units::dimensionless::dimensionless is defined, which
conflicted with the namespace when we added "using namespace
dimensionless". This patch reverts the "using namespace" directive.
"using" directives were added to pull three of the four relevant
typedefs but avoid the "dimensionless" type conflict.
This issue was first introduced in #2301.
What would happen is the Stop() call would happen between the notifier loop being triggered and calling UpdateAlarm(). This would cause the Update to overwrite the stop.
The CMake option OPENCV_JAVA_INSTALL_DIR can be set to the location
to search for the jar file. Note that the file name cannot be
changed, as, after checking several Linux package repositories,
that seems to be constant across all of them.
Fixes#2346.
The current hasPeriodPassed() function is confusing. In preparation for deprecating it,
add new advanceIfElapsed() function with same functionality and hasElapsed() function
which only checks that the time period has elapsed and does not advance the timer.
Also fix a couple of incorrect usages of hasPeriodPassed().
The field image and robot image can be loaded or just a wireframe used.
The robot can be moved and rotated with a mouse click + drag.
The robot position is settable in robot code via the Field2d class.
This allows users to right click on just about any name in the GUI (e.g. "PWM[0]") and rename it (e.g. "Left Motor [0]"). The index portion is not editable. The name is saved into imgui.ini so it's persistent.
C++ JoystickButton and POVButton were both nonfunctional due to slicing when trigger passes itself by value to the button scheduler it creates.
Fix is to remove the virtual Get() method entirely and use only the m_isActive functor; since the subclass now passes the button condition back as a functor to the base class, in which it's stored as a member, it will now still work after being sliced.
This PR changes the spline parameterizer to use an explicit stack instead of recursion. This is motivated by the fact that splines with adjacent waypoints with approximately opposite headings will never parameterize. In this case the parameterizer subdivides these malformed splines fine for a while, and then gets stuck parameterizing infinitely on some interval. In the recursive approach, this would lead to a stack overflow. We could implement a recursion depth counter (this is what my team did on our similar trajectory code last season), but it's hard to choose a good number for max depth because the initial amount of stack used varies based on how the user calls Parameterize.
A good solution for this is converting the recursion to an "explicit stack," which basically simulates recursion, but allows us to have a much larger maximum stack size. Because we avoid the stack overflow, we can instead throws a more informative MalformedSplineException. If the user is using the TrajectoryGenerator instead of the SplineParameterizer directly then the TrajectoryGenerator will go ahead and catch the exception, return a harmless empty trajectory, and report and error to the driver station.
Both floating point and 8-bit integer classes are included, as well as a wide selection of color constants.
Co-authored-by: Austin Shalit <austinshalit@gmail.com>
Add a Sendable* overload so pointers to sendable objects work appropriately.
Otherwise an AddLW(this) in a child (which is a Sendable*) could be a
different pointer than a void* to the same object.
For example:
AnalogInput constructor calls AddLW(this)
AnalogPotentiometer constructor calls AddChild(analog input pointer)
Also add handling for the child object moving (if it's Sendable).
This is extremely useful for implementing various "ramping" functions
(such as voltage ramps, setpoint ramps, etc). Usage is straightforward;
it behaves like all of our other filter classes. C++ version is unit-safe.
This is to allow suppressing an ugly stack trace/error message in a unit test in #2197. It doesn't support the full HALSIM_SetSendError callback stuff (i.e. you can only suppress, not intercept, stack traces with this).
- new CommandScheduler
- kinematics and odometry classes
- new PIDController
- ProfiledPIDController
- TrapezoidProfile (reported in Constraints class)
Also update instances.txt to match latest NI version.
One side effect is that a couple of classes are no longer constexpr.
With the addition of stall configuration, its not very clear how it works, and seems like it would be different
per use. So adding ways to manually get them, so the functionality can be figured out how to be used.
* Attempt to build testbench tests online inorder to improve speed
* Fix contianer reference
* Start to remove jenkins shell script
* Change job names
* Remove sshpass
* Remove teststand code
* Copy test results back
* Fix build by using athena container
* Fail if any command fails
* Remove jenkins test script
* Remove name argument
* Fix param count
* Add build display name
* Fix scp to copy into dir
* Update display names
* Update stage name
* Fix test results scp
* Create local test report dir
* Remove commented out old code
* Remove force pseudo-terminal allocation
* Remove extra variables
* Update readme
* Remove old test runs
* Update license header
LED displays connect the LEDs in various ways (column major vs row major,
different starting locations, serpentine connection order), so add
configuration parameters for these options.
It doesn't make sense to continue to provide a less accurate method of performing odometry
when a more accurate method using distances exists.
This also removes the need to pass DifferentialDriveKinematics to the constructor.
This kind of filter is extremely useful for signals that are susceptible to sudden
outliers - ultrasonics, 1-D LIDAR, and results from vision processing are all
good use-cases.
This also modifies the existing ultrasonic examples accordingly.
Improves the APIs for various prebuilt subsystems (PIDSubsystem, TrapezoidProfileSubsystem, ProfiledPIDSubsystem). Addresses #2128, and also changes the rather cumbersome getSetpoint API to a more intuitive setSetpoint one. Updates examples to match.
The odometry classes previously took in the robot angle as an argument, meaning that users had to take care of offsetting the gyro themselves to accurately report the robot angle. This change will make it so that users will not have to worry about resetting gyros and adding offsets themselves, as this will be handled by the odometry classes.
This shows the FPGA time and notifier timing, and has buttons to
start/pause/step the simulation.
The GUI also pauses DS new data notifications when paused. This could be
done globally instead by blocking NotifyNewData at the HAL level?
Calling HALSIM_PauseTiming pauses the FPGA clock and notifiers.
Calling HALSIM_ResumeTiming resumes the FPGA clock and notifiers.
Calling HALSIM_StepTiming steps the FPGA clock and runs applicable notifiers.
This will effectively pause TimedRobot and any other notifier-based events,
but of course will not pause user threads that do not use the notifier (e.g.
image processing).
This changes the C++ HALUsageReporting enums to have an
explicit type which matches the HAL_Report parameter
types. In practice this shouldn't change much except
for tooling that might be parsing this header.
Assorted improvements to the ergonomics of declaring requirements in the new
command framework. C++ requirements list parameters have been defaulted
to an empty list, some missing C++ requirements list parameters have been
added, and both C++ and Java have been given requirements list params in
various InstantCommand wrapper methods (#2049), whose value is
forwarded to the command.
This is useful for both cleanly exiting from simulation and for unit testing
at a framework level.
This change required removing move constructor/assignment from IterativeRobot.
- Remove use of std::set. The only place std::set was actually used was in ParallelRaceGroup,
but this was of minimal utility as ParallelRaceGroup checked for duplicate subsystem
requirements, so it would be very unusual to end up with duplicate commands
in any case; replaced it with a vector.
- Remove use of std::unordered_map except for SelectCommand. Replaced with vector.
- Use pImpl idiom for CommandScheduler
- Minimize include files (remove unnecessary ones)
- Reformat include file order for consistency
Add a voltage-compensated setVoltage method to SpeedController, which is sorely needed to help teams use feedforward-based controls effectively. Also uses correct units on the cpp side.
Also update relevant examples.
Changes Command decorators to return actual implementation classes rather than Commands. Previously, decorated commands were not Sendable, which was a problem. Also, there's no real reason not to expose the implementation details here, as we're extremely unlikely to change the implementations in the future.
Add user setting for scaling on top of DPI scaling.
Add user setting for visual style (light/dark/normal).
Save window position, size, maximized state, scale, and style to ini file.
These were incorrect and exhibited as warnings on more recent versions of
clang (notably on Mac).
- Use pointers instead of references internally in GenericHID and *Drive
- Leave PIDBase, PIDController, and Resource non-moveable
- Remove the atomic from m_disabled in NidecBrushless
- Make Timer and Trigger copyable as well as moveable
- Implement custom move constructor/assignment for SendableChooserBase
Also comment out some unused variables that caused clang warnings.
Add an overload for the generateTrajectory method that accepts a DifferentialDriveKinematics instance instead of a list of constraints. This instance is used to automatically create a DifferentialDriveKinematicsConstraint behind the scenes, saving the user some verbosity.
Passing command groups as lvalue-references to other command groups should be illegal, as their copy constructors have been deleted. However, copy constructors are const-qualified. This led to a very obscure bug where passing a command group by lvalue to another command group would result in a valid template expansion 'looking like' a copy constructor, and being preferred to the deleted copy constructor. This would result in constructor recursion (the expanded constructor would, in an attempt to call the copy constructor, call itself), and an eventual segfault when the stack inevitably overflowed.
This fixes the problem by explicitly deleting the problematic constructor signature - attempting to do this now (correctly) generates a compilation error.
The current index would be set to -1 by the execute method of ParallelRaceGroup,
and then an index out of bounds exception would be thrown by the end() method of
SequentialCommandGroup. This change bound checks the current command index as well
as only calls end at the end of parallel race group rather than during execute.
This uses Dear Imgui to provide a cross-platform integrated GUI for robot
simulation. The GUI provides fully integrated DS and joystick support so it's
not necessary to run the official DS.
This allows high-level library classes to implement enhanced simulation
support even if no low-level corresponding simulation library exists, and
avoids the need for bit-banging complex interfaces like SPI or CAN.
Default behavior is still to run the robot main loop in the main thread.
The ability to run the robot main loop in a separate thread and add a hook
for running a different function in the main thread is needed for simulation
GUI support on some platforms.
This class provides an easy way to forward local ports to another host/port.
This is primarily useful to provide a way to access Ethernet-connected devices
from a computer tethered to the RoboRIO USB port.
The most natural spot to put the shared implementation of this class was into
wpiutil, so a wpiutilJNI library has been added.
This removes the name and subsystem from individual objects, and instead
puts this data into a new singleton class, SendableRegistry. Much of
LiveWindow has been refactored into SendableRegistry.
In C++, a new CRTP helper class, SendableHelper, has been added to provide
move and destruction functionality.
Shims for GetName, SetName, GetSubsystem, and SetSubsystem have been added
to Command and Subsystem (both old and new), and also to SendableHelper to
prevent code breakage.
This deprecates SendableBase in preparation for future removal.
It only works with a specific sensor that isn't available anymore, the
class is a trivial wrapper around a Counter, and no one uses this class
according to FMS usage reporting.
If users are attempting to use the output range to limit the controller
action, they should use ProfiledPIDController instead. If they actually
intended to clamp the output, they should use std::clamp().
It breaks the unit system badly; the tolerance member variable has
different units depending on percent vs absolute. Absolute tolerance is
a lot more natural than percent tolerance anyway.
Since there is a new version of GearsBot using the new command-based
API, the old GearsBot is just removed.
PR #1842 is being included to verify this PR is correct.
This is the C++ version of #1682.
The old command framework is still available, but will be deprecated.
Due to name conflicts, the new framework is in the frc2 namespace.
Eventually (after the old command framework is removed in a future year)
it will be moved into the main frc namespace.
A templated hal::Handle class is used to wrap handles to make them move-only.
This eliminates a lot of boilerplate move constructor/assignment code
in the main WPILib classes. HAL_SPIPort and HAL_I2CPort are also wrapped.
The wrapper class does not implement destruction. This would require the
wrapper class to be handle-specific (rather than generic) and would result
in more code added than it removed, plus would add header dependencies on
more HAL headers. In addition, some HAL handle release functions are more
complex (e.g. have return values) and can't be easily mapped to a destructor.
The old command framework is still available, but will be deprecated.
Due to name conflicts, the new framework is in the wpilibj2 package.
Eventually (after the old command framework is removed in a future year)
it will be moved into the main wpilibj package.
This adds a wrapper over EJML's SimpleMatrix that uses generated classes representing numbers to encode the dimensions of each matrix at compile time, and to check operations between matrices for validity at compile time, rather than failing with an exception at runtime. This is required for the Java implementation of state-space control.
Additions to the wpiutil gradle script, and a python script at the wpiutil root are used to generate numeric types from a template at build time for both gradle and cmake. Users will be able to access types through functions on the Nat class.
Add unit-taking overloads to the following classes:
- IterativeRobotBase
- LinearFilter
- Notifier
- TimedRobot
- Timer (HasPeriodPassed only)
- frc2::PIDController
The corresponding non-units-taking functions have been deprecated.
The return value of TimedRobot::GetPeriod() was updated.
This is a breaking change, users should use to<double> to get the value in seconds.
Other return values, e.g. Timer::Get(), have NOT been updated due to much wider use.
Was only there for mac usb cam support, but we likely won't get to it this summer anyway,
and its causing a breakage in the backing libraries with cross builds
Teams that wish to use it asynchronously may still do so - they simply need to handle the thread safety themselves (it is not that difficult, and can be done more cleanly in the calling code anyway).
The main change in OpenCV 4 was removing its C APIs from OpenCV 1. If
the user has OpenCV 4, they have no way of obtaining the correct
arguments for cscore functions that require the C API. Therefore, we can
fix the build by just not compiling in functions reliant on the C API if
OpenCV 4 is being used.
OpenCV 3 builds should continue to work with this change.
Instead of being called asynchronously by NetworkTables, they are now called by updateValues() synchronously with the main loop, just like the getters.
The mutexes in PIDControllerRunner are declared after the Notifier, and
when the PIDControllerRunner object is destructed, the member object
destructors are called in the reverse order in which they are declared.
The mutexes are destructed first, then the Notifier destructor is called
which stops the Notifier.
There's a window between those destructor calls during which the
Notifier can run the callable and attempt to lock a mutex that no longer
exists.
Declaring the Notifier after all the variables its callable uses fixes
this issue, as it ensures the Notifier is destructed first.
Add EJML as the Java library for linear algebra for use in wpilib. This is equivalent to Eigen for C++.
The EJML dependency is downloaded in cmake and pulled in via maven in the gradle build.
It drastically increases compile times and is bad style. C++ users
should be including what they use. We don't necessarily have to remove
WPILib.h, but it should at least be deprecated.
This imports Eigen 3.3.7, which will be used by the wpilibc implementation of
state-space control and mecanum/swerve forward kinematics (the forward
kinematics requires least-squares solutions via a matrix pseudoinverse).
While Eigen has parts licensed under BSD, MINPACK, and MPL2, the files we need
are only MPL2.
These classes introduce ways to represent poses and provide easy ways to transform, rotate, and translate poses across 2d space. This classes will be especially useful for a planned odometry and kinematics suite.
Furthermore, these classes can also be used to simply represent waypoints on a field, do superstructure motion planning, etc.
Using std::function<void()> directly makes it much clearer to the user
what kind of function Notifier expects. The Doxygen comments already say
what the function is used for, so the typedef just discards useful
information.
This is a move-only variant of std::function to support move-only captures.
Imported from LLVM with some small tweaks (changed to 4 pointer internal storage, warnings fixes).
SampleRobot provides no benefits over RobotBase to advanced teams and
TimedRobot is recommended for everyone else.
A skeleton template for RobotBase was added.
std::scoped_lock was introduced in C++17 and is strictly better than
std::lock_guard as it supports locking any number of mutexes safely.
It's also easier to use than std::lock for locking multiple mutexes at
once.
Timer didn't have working move semantics because mutexes aren't
moveable, meaning the default implementations were ill-formed.
MotorSafety wasn't locking its mutex.
Originally, PIDController used PIDSource with its "PIDSourceType" to
determine whether a class should return position or velocity to the
controller. However, the supported languages have changed a lot over 10
years and now support lambdas. Instead of using PIDSource and PIDOutput,
users can pass in doubles to the Calculate() function synchronously.
This makes the controller much more flexible for team's needs as they no
longer have to make a separate PIDSource-inheriting class just to
provide a custom input.
The built-in feedforward was removed. Since PIDController is synchronous
now, they can add their own feedforward on top of what Calculate()
returns.
To facilitate running the controller asynchronously, there is a
PIDControllerRunner class that handles that. By separating the loop from
the control law, PIDController can now be composed with others and be
used to control a drivetrain (a multiple input, multiple output system
that requires summing the results from two controllers) much easier.
Also, motion profiling can be used to set the reference over time.
All the classes related to the old PIDController are now deprecated. The
new classes are in an experimental namespace to avoid name conflicts.
While this is a large change, I think it is a necessary one for growth.
The old PIDController design was created in a time when languages only
supported OOP, and we have more tools at our disposal now to solve
problems. This more versatile implementation can be used in more places
like as a replacement for Pathfinder's "EncoderFollower" class.
There has been hesitation to add lambda support to WPILib for a while
now out of concerns for requiring teams to learn more features of C++ or
Java. In my opinion, this change makes PIDController easier to use, not
harder. The concept of a function is a building block of OOP and should
be learned before classes. The ability to store functions as first-class
objects and invoke them just like variables is rather natural.
Note that PID constants for the new controller will be different from
the old one. The original controller didn't take the discretization
period into account. To fix this, teams should just have to divide their
Ki gain by 0.05 and multiply their Kd gain by 0.05 where 0.05 is the
original default period.
This can be dangerous as it refers to a temporary, and GCC 9.0 warns about
its use. Instead add std::initializer_list overloads to common places it
was used in an initializer_list sense.
* Renamed LinearDigitalFilter to LinearFilter
* Filter base class removed since it wasn't useful
* C++: std::shared_ptr<> replaced with double parameter
* ErrorBase: Use magic static singleton for globals
* ErrorBase: Add testability features for global errors
* Make WPIError definitions inline functions
(This works around cross-DLL variable issues on Windows)
Fixes#1726.
The current versions of the RoboRIO and Raspbian compilers support the flag but have
minimal actual C++17 support. Changing the flag is the first step.
* Update MSVC arguments
* Fix json allocator
* Fix simulation diamond
* Bump gtest
* Remove empty varargs in unit tests
* Replace test case with test suite
* Remove deprecation warning in optional
* Remove need for NOMIXMAX to be defined in wpilib headers
In some cases, we don't want the cv requirement to get an image, for instance interop with other versions of opencv
This enables getting a raw image, and handling conversions from the user side.
The functions in Threads.h are in the frc namespace. `using namespace frc;` in
Threads.cpp doesn't put their implementations in the frc namespace, so linker
errors occur when attempting to use them in robot programs.
To fix this, one can either wrap them in a namespace block or prepend
`frc::` to the implementation's signature. Based on past discussion, I
opted for the namespace block.
LabView only accepts %20 instead of + for parameters, only sends '\n' at the boundaries,
and includes the -- when sending the initial boundary. This solves those parts.
This is not fully enough to fix shuffleboard and others, as the NT format for paths is not the correct path.
This adds a new function "addSwitchedCamera" that creates and publishes a
virtual camera where the published stream information is consistent even if
the mjpeg server source is switched to a different camera.
Previously, changing the source of the mjpeg server resulted in updating the
stream information published for that source.
* Fix C++ ShuffleboardComponent template type
* Fix `WithWidget(WidgetType&)`not being properly capitalized
* Fix data members across dll boundaries by using enum for built in types
When there is more than one ultrasonic sensor, only the last sensor
instantiated would work due to incorrect array index management. This
replaces the previous approach with range-based for loops like the C++
implementation.
Supersedes #1589.
Resetting the flag should only occur in Enable() and Reset().
IterativeRobotBase needs the flag to remain set to print epochs after
disabling the Watchdog.
This is primarily for use on Linux to get by-id or by-path device names.
This information is now part of UsbCameraInfo.
A new entry point was added to UsbCamera to get that camera's UsbCameraInfo.
The alternate paths are also returned in EnumerateUsbCameras.
Add a Sendable wrapper for VideoSource objects.
Add convenience methods for adding video sources directly to containers
so users won't have to manually wrap video sources.
HAL_GetFPGATime returns 0 if it starts with a non zero status.
Always use monotonic clock for CAN times, rather then trying to sync FPGA.
Change timeout from 50 ms to 100 ms.
Otherwise, it is required to be set manually, which isn't obvious.
This is because the HighLevel DS classes check that the ds is attached before enabling
This function is intended for use when the content is a static const variable.
It allows gzipped static data, but doesn't provide the functionality to ungzip
it if the client doesn't support gzip. This is because it would add a
dependency on zlib and basically all clients support gzip.
Change extraHeader on all Send functions to include the final newline,
this makes it easier to build up extra headers incrementally.
Expose sig::Connection for messageComplete and headerConn to allow them to
be disconnected by users of the class. This is commonly needed for things
like WebSocket upgrades.
The 2019 FPGA image switched the output of auto SPI from plain bytes to a
sequence of 32-bit words (timestamp, then words with the byte values in the
least significant byte of each word).
In addition to changing the HAL and simulators to reflect this, add piecewise
integration support to wpilibc/wpilibj SPI to take advantage of the timestamps
and use it in the ADXRS450 gyro.
Adds debug stripping to executables.
Copies .debug and .pdb files to install directories to ease debugging.
Update to v0.5 of doxygen, which fixes the download location.
Notifier has one thread per instance because the callbacks must be
asynchronous. Watchdog callbacks can be synchronous, so this overhead
can be done away with via a scheduler thread akin to what the HAL
Notifier does.
The size of the directory_entry was different between translation units.
This was caused by the FILE_OFFSET_BITS macro when building wpiutil.
Removing that fixes the issue.
Should fix NavX USB issues.
Imported from https://github.com/akrzemi1/Optional with minor changes:
- Compiler conditional simplifications (we only use recent versions)
- Move from std::experimental to wpi namespace
- Change tests to integrate with Google Test
Update LLVM use cases.
Most of the MotorSafety implementation was moved into the MotorSafety base
class. SafePWM's inheritance of MotorSafety was moved into PWM to
eliminate Java needing a helper class.
In Java, a helper class for Sendable (SendableImpl) was added due to
lack of multiple inheritance.
HAL_ReadInterruptRisingTimestamp and HAL_ReadInterruptFallingTimestamp
return time as a double. Instead, keep the raw integer count and move the
double conversion into the C++ and Java code. This enables comparison of the
time with other timers.
PR #1300 supersedes it, but won't be merged until the 2020 season. Since
SynchronousPID hasn't been used during a season, it would be best to
just remove it to avoid breakage when we deprecate and remove it again.
This allows save and restore of camera settings. The restore is a bit
smarter than the save.
* Fix mime types in mjpeg server
* wpiutil: WPI_LOG: Make sure level is an unsigned int
This is set to the FPGA clock by HAL_Initialize. Note this change means
that libuv loops should not be started until after HAL_Initialize is called (on the Rio).
Non-Rio functionality is unchanged.
Static destruction order is not well defined, so it was possible for outs()
or errs() return value to be destroyed even while other code was running,
resulting in a crash. Instead dynamically allocate the static so the
destructor never runs. While this technically leaks, valgrind generally
supresses such leaks as the data is still "reachable" from the static pointer.
This avoids a number of shutdown use-after-free races by controlling the
destruction order. It also is a prerequisite to making the internal
interfaces mockable for unit testing.
The static condition variable was getting destroyed before the DS thread exited,
resulting in a deadlock on program exit when the DS thread tried to notify it.
This change moves the condition variable into the DS thread to avoid the race.
The next line adds a null terminator, but it's cleaner to just do a
std::memcpy() since the code already assumes a null terminator exists in
the source string.
- Build both debug and release binaries
- Append "d" to debug libraries in the style of opencv
- Split shared and static classifiers
- Add raspbian support
Originally, the command was restarted every time the scheduler was
executed if the button was pressed. #1340 changed this behavior in a
breaking manner.
Other handles can only be used within the loop itself, but Async is intended
to be used from another thread. This introduces the possibility of a race
condition between the loop being destroyed and the Async being destroyed.
Change Async to keep a weak reference to a loop and check it before performing
libuv operations.
This allows the called function to pass along the promise to another
asynchronous callback.
To avoid memory allocations, add a home-rolled, simplified, non-allocating
version of std::promise and std::future as wpi::promise and wpi::future.
Since https://github.com/wpilibsuite/allwpilib/issues/786 has been
closed as not a legitimate concern, there is now no reason to use
IterativeRobot over TimedRobot. It's a drop-in replacement that's
strictly an improvement in terms of execution jitter.
To migrate, one simply has to replace the IterativeRobot subclass in
their robot code with TimedRobot.
Make wpi::condition_variable typedef to std::condition_variable_any if
wpi::mutex typedefs to priority_mutex.
priority_condition_variable was originally intended as a copy of
std::condition_variable_any that also returned the internal handle like
std::condition_variable. This was needed because NetComm required a
pthread_cond_t. We no longer use it anywhere.
Its args were specialized for priority_mutex, but
std::condition_variable_any supports this and more through
templatization.
This is necessary for modularization.
Move the wpilibj CameraServer classes to the cameraserver package.
Move the edu.wpi.first.wpilibj.vision package to edu.wpi.first.vision.
To avoid code breakage, add deprecated copies of the wpilibj classes to the wpilibj jar.
This allows HAL_CloseI2C() and HAL_CloseSPI() to be noops, which makes
enabling move semantics in the I2C and SPI wpilibc classes easier and
cleaner.
Fixes#1328.
This makes callback registration completely thread safe.
This patch also uses templates and macros to dramatically reduce the amount of
manual boilerplate.
Makes configuration easier when you can associate the items with a name
instead of just a port number. Important if there is a GUI added at some
point.
This is a breaking change as it makes Async a template (e.g. Async<> must
be used instead of just Async). When data parameters are provided, an
internal mutex and vector is used to hold the parameter packs until the loop
runs.
By default, sources automatically manage their connection based on whether
any sinks are connected. This change allows the user to keep a connection
open or force it closed regardless of the number of connected sinks.
This fixes two real bugs:
- TimedRobot had a m_period that was hiding the IterativeRobotBase m_period
and was not getting initialized.
- PDPSim was swapping two parameters to getCurrent()
A hash is stored for each native library with the name libraryName.hash.
If the library is not found on the system search path, it is extracted to a cache directory.
Extracted libraries are named with the hash appended, so the library will not be
re-extracted if one with the same hash already exists.
Hashing without the hash file requires double traversing if the file is not in the cache,
but it is still faster than creating a new file in most cases. This won't be needed
after opencv is updated to provide a hash as well.
JavaDoc cannot handle redirects so HTTP link does not work anymore.
It also looks like javadoc.options was the wrong thing to set.
Options properly connects external docs to ours.
Re-enabled warnings so these things will pop out if they turn up again.
SendableBuilder.setActuator() sets the .actuator key in the network table
so dashboards can change behavior on the client side if desired, and also
sets a local flag (retrievable via isActuator()).
Both make drive bases actuators and call setSafeState on them.
This echos back the "selected" value to the "active" key to enable dashboards
to display positive feedback to the user that the value is actually set on
the robot side.
Also fixes SendableChooser so it can be safely added to multiple tables.
Changes to "selected" in any table will result in all "active" values being
updated.
Now that adding SendableChooser to multiple tables is supported, an ".instance"
key enables dashboards to treat the same SendableChooser as a common instance
if desired.
This indicates whether or not the Sendable listeners are installed.
It is set to true when SendableBuilder.startListeners() starts the listeners,
and set to false when SendableBuilder.stopListeners() stops the listeners.
This allows dashboards to choose to change their widget display based on
whether or not the value is actually controllable.
This allows two streams with different compression levels, and also allows
a stream to receive a different compression level than provided by a JPEG
camera (decompress and recompress).
Some cameras will accept a different resolution as the mode but then provide
JPEG images of a different size. Trust the JPEG image size if available.
This also validates the JPEG image is actually JPEG.
The old headers were moved into folders because doing so avoids polluting
the system include directories.
Folder names were also normalized to lowercase.
This implements enough of the UDP and TCP protocol used by the FRC
driver station to allow us to talk to either QDriverStation or to the
real Driver Station.
This was inspired by a similar function in Toast by Jaci, and also
uses a lot of the research found in the QDriverStation project.
* Fix bugs in PacGoat Java example that prevent it from working.
We have conflicting ports in use, each of which causes a crash
at startup. These changes fix those issues.
* Change to avoid a crash in Visual C++ when running simulated code.
Without this change, we would get a crash in SendableRobotBase when
constructing a Twine from the 'kOptions' constant string;
we'd get an unable to access memory exception.
Also switch eventName and gameSpecificData to fixed 64-byte arrays to avoid mallocs and
extra NetComm calls. This behavior matches 2018 LabView.
The DS caching is kept in Java to avoid JNI and/or massive amounts of allocations.
This does not increase latency because Java still only hits NetComm once.
Moving the DS caching benefits all languages other than Java, because it avoids the need
for individual implementations. If caching is ever added to NetComm, it will then only be
necessary to remove it from the HAL and Java rather than all languages.
It is much more reliable than the old approach, as it no longer depends on a magic string
in a manifest file, and if the user changes their main class, or makes it not import from
something RobotBase, it will fail to compile instead of failing at runtime.
With requiring an importer, we should be able to automate this in the importer.
4.9 will be needed for some things being added to a few of our plugins. It adds the new lazy configuration tasks which help a good amount in some cases.
I don't have a good way to ensure this always works, so this is going to be a documentation issue.
But initializeHardwareConfiguration is now reentrant, so we can just have all tests call it.
Also fix the return type of HAL_IsNewControlData() and HAL_MatchType's type.
Since UsageReporting is intended to be namespaced, it is hidden when this is being used in C.
Fixes: #476Closes: #535
Ref: #1122
The models and meshes are not included. We will need
to find an alternate way to reintegrate these and use them.
* Add simulation/gz_msgs back, and build with Gradle.
* Add back in the frc simulation plugins for gazebo.
* Add a new shared library, halsim_gazebo.
This library will become the interface between the
HAL sim layer and gazebo.
* Preserve the first channel number used in created Encoders in the Sim MockData.
This allows us to use the DIO channel number to connect with simulated encoders.
* Have the HAL Simulator set the reverse direction on creation.
This enables a simulator to be aware of the direction.
* Add a drive_motor plugin.
This is a bit of a 'magic' motor, which allows us to build robot
models that drive in a more realistic fashion. It does this
by apply forces directly to the chassis, rather than relying on
the complex motion dynamics of a driven wheel.
This in turn allows the model to reduce wheel friction,
reducing scrub, and allowing for a more natural driving experience.
This optimizes the common case of a single simple callback (e.g. std::function
or lambda) so no additional allocation is required. As a Connection return
value is not possible in this case, provide a separate connect_connection()
function to provide that.
Imported from https://github.com/palacaze/sigslot
Classes were renamed from lowercase_me to UppercaseMe style, primarily
to avoid conflicting with the C standard library "signal" function. They
were also moved to the "wpi::sig" namespace.
The implementation of ConvertToC for arrays was broken. Also change it
to be templated on the returned array type, rather than passing the array.
This makes the uses a bit more clean.
In order for this to properly work, we need to remove the main code.
Then the test component will actually have the main in it. Example tests will be added later.
Making Travis run wpilibj_frcnetcomm.py will help avoid bitrot in
FRCNetComm.java in the future. Formatting was also enabled on Python
source files and FRCNetComm.java was added back to the generated files
list.
Also checks that all items in the json file have a matching example
One was missing from C++, that example was added (The one in eclipse was completely wrong)
Instead of defining NAMESPACED_WPILIB to remove the "using namespace frc"
shim in Base.h, instead require NO_NAMESPACED_WPILIB be defined to add it.
Fix up various examples to use correct namespacing.
Also change header guards to WPI header guards.
Remove StringRef::c_str() customization, replacing the handful of uses with Twine or SmallString.
TCPStream: Include errno.h and make Windows includes lowercase for consistency.
Upstream LLVM version: eb4186cca7924fb1706357545311a2fa3de40c59
This fixes DriverStation in WPILibJ to check the existence of buttons and hold the data mutex in getStickButtonPressed() and getStickButtonReleased(), as the corresponding methods in WPILibC do.
For mac, 32 bit will never be supported. Apple has dropped all support.
For 32 bit linux, vscode explicitly does not support it, and it is difficult to find anybody using a 32 bit os.
The anonymous namespace was renamed due to -Wsubobject-linkage complaining
about a field created in a GTest template class (CborRoundtripTestParam)
being defined in an anonymous namespace. See
https://stackoverflow.com/a/37723265.
These generate a warning when included, then include the old header.
Note for GCC, #warning is used; this requires -std=gnu++14 instead of
-std=c++14 (otherwise the warning is treated as an error because #warning is
a GNU extension). On MSVC, #pragma message is used, which is a bit
unsatisfactory as the message doesn't say where it was included from.
The llvm shim headers also include a llvm namespace shim.
During shared library loading, a different libLLVM can be pulled in, causing
llvm symbols from dependent libraries to resolve to that library instead of
this one. This has been seen in the wild with the Mesa OpenGL implementation
in JavaFX applications (see wpilibsuite/shuffleboard#361).
This is clearly a very breaking change. For some level of backwards
compatibility, a namespace alias from llvm to wpi is performed in the "llvm"
headers. Unfortunately, forward declarations of llvm classes will still break,
but compilers seem to generate clear error messages in those cases
("namespace alias 'llvm' not allowed here, assuming 'wpi'").
This change also moves all the wpiutil headers to a single "wpi" subdirectory
from the previously split "llvm", "support", "tcpsockets", and "udpsockets".
Shim headers will be added for backwards compatibility in a later commit.
It was using array indexing to map the return value of
DriverStation.getJoystickType() to HIDType when the enum should instead be
constructed from the int value. C++ already does this.
Fixes#968.
Previously these functions ignored SOF if they came immediately after
the SOI (e.g. bytes 2 and 3 of the file). A handful of cameras generate
images like this.
SendableChooser::InitSendable() is written such that it saves the table
being used in an instance variable. This doesn't work if the chooser is
added to both LiveWindow and SmartDashboard. Normally it is not added to
LiveWindow because the name is empty, but if setName() is called this could
still happen. Note adding the same SendableChooser to SmartDashboard with
two different names is also not currently supported, for the same reason.
The correct solution will be to remove the instance variable, but this is
too high risk to implement mid-season, so instead just remove from LiveWindow.
Reset() is the only function without a null check around it. We call the function on startup, which means if it is unplugged the robot crashes.
Also added an accessor for checking if it is connected, as some teams (us) would like to handle the case where it was not connected on startup.
Both could occur if a client and server write to the same key and the server
disconnects/reconnects (or restarts).
Bug 1: the client did not properly update the sequence number in this case,
so later server updates could be ignored until the sequence number wrapped.
Bug 2: the client did not properly set the id and sequence number for the
update message back to the server, so the server would ignore the message.
This normalizes within -1..1 to avoid clipping and maintain the ratio between
wheel speeds, since that ratio determines the center of rotation.
Fixes#923.
Also provide wpi::mutex and wpi::condition_variable as wrappers for these
on Linux (where they're available), and for std::mutex and
std::condition_variable on other platforms.
The original synchronization behavior was troublesome for two reasons:
- It had unpredictable behavior for updated values
- It brought back to life deleted values
Instead of relying on the server to inform the client regarding reconnections,
the client keeps track of what values have been modified by user code on the
client. When the client connects to the server, the following occurs.
For entries that have been modified by user code on the client:
- If the entry is not persistent, the server value is overwritten with the
client value
- If the entry does not exist on the server, the client sends an assignment
to the server to recreate it on the server
For entries that have not been modified by user code on the client:
- The client value is overwritten with the server value
- If the entry does not exist on the server, the client deletes the entry
Fixes#8.
Previously, most of the classes were implemented as singletons so only one
instance was possible.
This change adds an instance handle-based API. In Java, this API is located
in a different package than the old API (edu.wpi.first.networktables).
Backwards compatibility with ITable and the old NetworkTable API is largely
maintained, but a handful of classes have moved to the new package in Java
(ConnectionInfo and PersistentException), and the old JNI has been completed
replaced.
Also:
- Move SetTeam implementation to Dispatcher.
- Consistently pass time through Java and C++ Value API.
- Rename nt_Value.h to NetworkTableValue.h for consistency with Java.
- Improve documentation
- Make C++ and Java APIs more consistent
- Document RPC functions and support RPC in Java.
- Add polling features for entry and connection listeners and use them to
move callback threads to Java level.
- Remove thread start and stop hooks (as polling is available).
- Make Notifiers, RpcServer, Dispatcher, and Storage mockable.
- Set NOTIFY_NEW on immediate entry notifications.
- Make GetTable("/") and GetTable("") equivalent.
- Generate local notification for flags update when loading persistent file.
And many unit test updates/changes:
- Use InitGoogleMock instead of InitGoogleTest in test main.
- Move test printers to TestPrinter.h/cpp.
- Provide printers for StringRef, EntryNotifier, and Handle.
- StorageTest: Check notifications.
- Add entry notifier unit tests.
- Storage: Add test for incoming entry assignment.
- Update connection listener tests.
- Add entry listener unit tests.
Fixes#11, #140, #189, #190, #192, #193, #221
This keeps indexes from being instantly reused and reduces the risk of
accidentally using an old index.
Also change erase and emplace_back to return 0-based instead of 1-based
indexes.
This is a breaking change, but a noisy one due to the template parameter
change.
The Frame destructor calls back into SourceImpl, locking m_poolMutex, so
it's necessary to destroy m_frame before m_poolMutex. Reverse destruction
order to member definition order is guaranteed by the C++ standard.
Better then the old desktop zips because it will include all artifacts
built, not just specifically the desktop ones. Also, the individual
artifacts are published as well so users can decide which artifacts they
specifically want, and can help decrease download sizes. The cpp plugin
will continue using the individual artifacts.
Better then the old desktop zips because it will include all artifacts
built, not just specifically the desktop ones. Also, the individual
artifacts are published as well so users can decide which artifacts they
specifically want, and can help decrease download sizes. The cpp plugin
will continue using the individual artifacts.
This is a modified version of https://github.com/nlohmann/json.
It's been moved into the wpi namespace as many of the changes are not
compatible. The amount of template code has been significantly reduced,
enabling many functions to be moved out-of-line, and for the result to
build on older compiler versions (in particular GCC 4.8).
Gradle needs to produce a platform path of "Linux/i386" when targeting a Linux 32-bit Intel platform. Otherwise, it doesn't match Java's os.name/os.arch when loading the ntcore library in NetworkTablesJNI.java. Windows uses "x86" but Linux uses "i386". (http://lopica.sourceforge.net/os.html)
MjpegServer uses the timeout to generate keep-alives to any clients
(which helps detect disconnects and avoid stale client threads).
CvSink GrabFrame now defaults to a timeout, but the timeout can be
changed by the user, or the old no-timeout version is now available
as GrabFrameNoTimeout.
When the page is loaded, if properties can be found they will
automatically be created on screen. They are currently not auto
updating. Raw values are currently disabled because of this.
Currently if using a separate compiler prefix, it would get published to
the arm classifier. This modifies so the output suffix can now be
specified (e.g. "hf" for armhf).
Currently if using a separate compiler prefix, it would still get published
to the arm classifier. This modifies so a classifier suffix can be used to
disambiguate arm from armhf.
This makes them available for both UsbCamera and HttpCamera / AxisCamera.
To avoid virtual functions in the public-facing interface, move the
implementation of the camera settings functions to the core library.
Similarly, use InetPton rather than WSAStringToAddress.
The WSAAddressToString function is intended to provide a user-readable
string and thus includes the port number. This breaks some use cases
on Windows which expect to get just the IP address.
Note: The InetPton and InetNtop functions are available only in Vista or above.
Similarly, use InetPton rather than WSAStringToAddress.
The WSAAddressToString function is intended to provide a user-readable
string and thus includes the port number. This breaks some use cases
on Windows which expect to get just the IP address.
Note: The InetPton and InetNtop functions are available only in Vista or above.
This takes hosts (IP or DNS name) rather than URLs, making it easier
to use.
Also add more overloads to resolve ambiguities encountered when using
std::string and const char*, and also add overloads for
std::initializer_list<T> so braced initializer lists can be used.
The Frame constructor calls back into SourceImpl (the passed this reference),
and when in-place constructed in the SourceImpl constructor, SourceImpl
is only partially constructed.
The code now automatically resizes as required.
This change also disconnects camera resolution settings from MJPEG
stream connections; setting the camera resolution can now only be done
via code.
Also add checking for "would block" errors in send() and receive().
Check for set nonblocking failures in TCPConnector as well (generate warnings rather than errors)
Also add checking for "would block" errors in send() and receive().
Check for set nonblocking failures in TCPConnector as well (generate warnings rather than errors)
Also take CS_EventKind rather than RawEvent::Kind.
Still provide the handle methods for the basic events (this is particularly
useful for create and destroy events).
This makes these functions easier to use from within the implementation.
The StringRef class does not ensure the string is null terminated. As there is
no defined way to actually check for a null terminator, we determine
if it is null terminated based on the constructor type. Then if on c_str
it is not known to be null terminated, we use a passed in buffer to copy
the string and ensure null termination.
The StringRef class does not ensure the string is null terminated. As there is
no defined way to actually check for a null terminator, we determine
if it is null terminated based on the constructor type. Then if on c_str
it is not known to be null terminated, we use a passed in buffer to copy
the string and ensure null termination.
The 2017 FRC Driver Station supports getting the robot IP via a TCP
connection that returns JSON. Use this to support overriding the
server IP address used for client connections.
Default to using this approach for client connections in the NetworkTable
interfaces.
Add support for setting the server address without stopping and
restarting the client.
SetTeam now also round-robins by default.
Previously once the client fell back once to NT2, it would never try
connecting as NT3 even if the server was replaced with a NT3-capable
one.
Fixes#142.
During testing, I was seeing a lot of unnecessary code (and allocations
in Java/C#) when appending the path separator to the base path. That
technically is a constant, so this computes this constant during class
construction.
This is a breaking change to dependencies that use the static ntcore
library. Unless the wpiutil library is also linked, linker errors will
result. This does not affect the shared ntcore library.
This is a breaking change to dependencies that use the static ntcore
library. Unless the wpiutil library is also linked, linker errors will
result. This does not affect the shared ntcore library.
* Revert "Fully asigns the ConnectionInfo struct (#113)"
This reverts commit 9a3100b221.
* Revert "Passes the ConnectionInfo of the Rpc client on server callback (#112)"
This reverts commit 7e9754acff.
For functions where a SmallVector is passed to be used as a stack buffer for
the return value, have the return value be the appropriate StringRef or
ArrayRef type. This allows for both more natural usage and enables directly
returning (rather than copying) a permanently stored or constant string.
This will allow dependencies such as wpilibc to update to use wpiutil
without breaking "normal" ntcore static library use in the meantime.
This commit also restructures the gradle files by creating a new
(placeholder) wpiutil project, and moving the ntcore project into
a separate gradle file. Added toolchains/native.gradle (refactored from
ntcore).
Also fixes ntcore skipJava on Windows by providing an alternate .def file
for this case.
This will allow dependencies such as wpilibc to update to use wpiutil
without breaking "normal" ntcore static library use in the meantime.
This commit also restructures the gradle files by creating a new
(placeholder) wpiutil project, and moving the ntcore project into
a separate gradle file. Added toolchains/native.gradle (refactored from
ntcore).
Also fixes ntcore skipJava on Windows by providing an alternate .def file
for this case.
Moving these headers from src to include enables other libraries to use the
functionality provided.
* tcpsockets
* atomic_static
* raw_istream
* timestamp
* SafeThread
* Base64
* LEB128
* ConcurrentQueue
The classes have been moved into the wpi namespace as they're generic.
There was no way to atomically check for a key in the table,
and then setting if it if non existant. Back before persistent
this was not a problem, however now it is, as its possible for
values to be added before team's robot programs start. This makes
the old method of calling Put*** methods in RobotInit invalid.
This adds SetDefault methods, which do this atomically.
Without a GCC installation that can build both 32 and 64 bit executables, the native build will fail on 64 bit Linux machines with an error about unsigned __int128 being undefined. GCC does not support __int128 on 32 bit targets, and GCC was using it via a standard library implementation header intended for 64 bit machines.
Instances of "arm" were replaced with "ARM" where the acronym was intended.
Since we now get ConnectionInfo when setting a connection listener,
there is some good information in there that teams could use.
Implemented using default interface methods, so teams should see no
change if they don't implement the Ex methods.
I noticed that the connection listener methods don't exist at all in
C++, so they did not get added there.
There's a lot of buzz going around the internet about people trying to
get ntcore working on other devices. One of the things that makes it
harder is having to have a separate jar for each platform. What this
change does is if the loading of the extracted library fails, it will
attempt to load ntcore from the path. This means that a program like
GRIP can just provide the libntcore.so and not have to worry about
compiling different versions for different platforms.
Trying to build with the android standalone compiler, and these 2 things
were causing errors. I don't know what an equivalent to basename would
be, because I don't really know what it does.
For consistency with Java NetworkTable; also makes these data types easier
to use (although they are less efficient as they require a memory allocation
and data copy).
JavaGlobal was unconditionally attaching to (okay) and detaching from (bad)
the current thread during destruction. We don't want to do this if the
destructor gets called from an attached thread. Instead, use GetEnv to
first try to get the environment, and only attach and detach if it returns
an error saying the thread is detached.
Also, make sure notifier callbacks appropriately free Java locals to avoid
running out of local variable space.
During JVM shutdown, some JNI calls may not return, so it's not possible to
reliably perform a join() during static variable destruction (which occurs
as the JVM unloads the JNI module).
Also, due to static variable destruction, it's not safe to use any members
of a static class instance from a separate thread of execution.
SafeThread is a templated thread class and a related owner class that's
designed for safe operation and shutdown of threads in the presence of
callbacks that may not return. It also passes ownership of variables from
the static instance to the thread, so the thread can safely operate until
it exits (the last operation of the thread being to destroy its instance).
Notifiers, RpcServer, and Logger now use SafeThread to ensure race-free
destruction in both C++ and Java.
All Java callback threads are now marked as Java daemon threads so they
don't keep the JVM running after main() terminates.
All Java callback threads are now named so their purpose is more easily
identified in a debugger.
Add SetRpcServerOnStart and SetRpcServerOnExit (similar to Listener).
The previous use of a timeout resulting in thread detach instead of thread
join resulted in a race condition on Mac between destruction and thread
closeout. This commit removes the detach functionality and uses dup2() to
on Linux/Mac and connecting to itself on Windows to try to ensure accept()
exits.
Each call to AttachCurrentThread results in a new Java thread object being
created. This is inefficient and also causes debugging issues with Eclipse
due to constant creation and removal of threads. Now AttachCurrentThread is
only called once for (all) listeners and once for logging (if used).
Previously this would always return false due to how explicit bool is
evaluated in a return context.
Also add a test for this function.
Reported by: jcreigh
This is safe because of the way writes are performed: for each transmission,
all outgoing messages are concatenated in memory and only a single write()
syscall is made.
These are good to have for backwards compatibility, but discouraged for new
development (default-taking functions should be used instead). The reason
is that the exceptions must be explicitly handled and may initially work but
then fail at an inopportune moment.
Mark the similar Java functions as deprecated as well for the same reason.
Update all the docs for consistency.
Mark overridden functions as such in both C++ and Java.
Make IsPersistent and GetFlags const in C++.
no-unused-private-field for Mac builds. Gradle also now works
with the classifier-based dependency system, rather than having
separate repos for every level.
Change-Id: I2eb87391181e91b5675e3e982e4d915be83e14ea
The Value::MakeStringArray methods were not setting the size of the
arr_string. This was causing the NT_Value struct called from the C
entry listener callback to not have the array size, which would then
cause the GetValueStringArray method to fail the malloc.
current platform by default, and only builds tests when building for the
current platform. Mac builds and VS2015 builds are fixed.
The other big change in this update is the introduction of Debug and
Release builds. Debug builds are built with -O0 and -g. Release builds are
built with -O2 and -g. For GCC-based builds, the resulting shared object
is copied, stripped of debug information, and a debug link is set up to
the copied shared object. This allows the release build to clock in at
around 600 KB. On Windows, the debug info is already stored in a separate
PDB file, so this copy and strip is not necessary.
ntcore is being separated out from the rest of allwpilib. All other
builds will consume a published maven dependency from this project.
There are 4 possible publishing targets now: release, stable, beta, and
development. These are specified on the command line via -Prepo=<repo
name>.
Change-Id: Ie8cb21f910953e09b80a5192317033eb0866cb70
Under certain situations (notably JNI shutdown), it's possible to get
deadlock when using thread join(). To avoid this, implement a timeout.
Normally we try to simply join the thread, but if it times out, we
detach the thread instead.
This enables listeners to be notified of not only value updates, but also flag
changes and deletions by using a bitmask to specify what notifications are
desired. The old API (which only provided a new/not new) flag is still
supported. This also subsumes the feature to listen to local changes (that's
one of the bitmask options).
Before the server has assigned the id, the client doesn't generate flags
update messages. This behavior is correct, but the client must then send
the appropriate flags update message when the id is finally assigned by
the server.
The default behavior is to only notify remote changes, but for some
applications (e.g. GUI's) it's advantageous to know about local
changes as well.
This is (slightly) optimized in that local changes only result in
additional resources being consumed if (any) local listeners have been
created.
This matches the implementation provided by Java NetworkTable, with the
exception that the subtable is not provided (because it's not a value).
The listener still can get access to the subtable by calling
source->getSubTable(key).
- Ignore no-op calls to setServerMode() / setClientMode().
- Duplicate calls to initialize() act as a restart.
- shutdown() silently does nothing if not running.
The JVM doesn't always do a good job of telling JNI modules that the JVM
is going away, which results in a crash in the JavaGlobal and/or
JavaWeakGlobal destructors as they try to delete the associated references
after the JVM has already gone away.
To protect against this, the Notifier now has a static variable that's set
when the Notifier instance (a singleton) is destroyed. This is used by
JavaGlobal and JavaWeakGlobal to detect when a process exit is in process.
vs2015 is detecting, and printing an error that actually makes sense if it
is not. Finally, added a .gitreview file, so that git-review will be able
to autodetect the host and project for ntcore automatically.
Change-Id: I3cb9910d03d4742619770c91c06e3d5d1ee0f031
Previously they returned references to the strings/arrays within the passed
NT_Value, which is different from the GetEntry* functions and risks
double-frees.
Starting to add Getters, Setters, and Allocators to the C interface
Because of the union in the NT_Value structure, some languages would
have a difficult time with the interop. This commit adds individual
getters and setters to the C interface to make interop easier.
In addition, some languages cannot allocate native memory in the same
heap that the C code would use. This adds allocation functions to make
sure that all our memory is allocated and can be freed properly from the
same heap.
The reason the getters are not individual get functions are because that
would require the calling code to first get the type, and then call the
specific getter for that type. Doing combined get functions causes
interop code to only have to cross interop boundaries once to get the
value instead of twice, for a light performance increase. However, this
could be changed without much work.
NT getters and setters round 2
Fixed some of the code based on the comments in the pull request.
Creates individual getters.
Should work better then 1 single getter.
Fixes end of file new line, and fixes function nameing
SetNTValue... made less sense then SetEntry... Matches the getter
naming.
Fixed methods to be less leaky.
Fixed Formatting, Fixed return values on Bool and Double. Added Contains Key
Changed ContainsKey to GetType. Also renamed Arr to Array
In public functions, I think I like Array better then Arr. Also, make
the getters that use value check for a null value, which should prevent
segfaults.
Fixes C++ Type functions to work properly
NTString Set functions still do not work properly though. I need some
help on there. Error message is in the pull request.
Changes Get functions to return status and have pointer to data passed in to be set.
Fixes NT_Strings
Added new functions to ntcore.def
Fixes NT_PostRpcResponse in the def file
Was NT_PostRpcRepsonse, which was failing the build.
Removed unused parameter from setters
Since we were forcing exports in the cmake build, they were seen in
windows, but since the header didnt match the implementation they
wouldn't export on linux. So fixed that. Linux builds now work properly,
tested on a physical RIO.
Added a DisposeEntryInfoArray method.
There was no way to free the array returned from GetEntryInfo
Adds NT_DisposeEntryInfoArray to the def file.
Implement automatic persistent saves.
Also loads persistent file on server start.
Update TODO.
raw_istream and kin: a few cleanups.
anchor() doesn't seem to change compiler output in current compilers, so
remove it. Use default where appropriate rather than empty bodies.
Clean up trailing whitespace.
Dispatcher: Move several fixed initial values to header.
Uninline constructors to reduce GetInstance() inlined code size.
Logger: Move m_min_level init to header.
Replaced time.h with std::chrono
This implementation returns the same values as the previous one on both a Linux machine and the roboRIO.
Value: Use variant of enable_if to fix MakeString/MakeRaw in GCC.
Tested on GCC 4.8, GCC 4.9, and clang 3.6.
Don't dispose in ConvertToC for NT_String and NT_Value.
Fixes#16.
Fixed Gradle build to actually export proper functions
Finishes fixes in pull request
Changes array setters to be const
To build RPC, needed a way to allocate a Char Array
Since after the callback, the C code explicitly frees, a way to make
sure to allocate the callback return string from the same heap was
needed.
Adds const to NTString setters.
Removes Const from NTString setters
The JNI bindings are built directly into the shared library. In the gradle
build, all built shared libraries are embedded into the generated jar.
Java bindings may be disabled via -DWITHOUT_JAVA (cmake) or -PskipJava=true
(gradle).
TODO:
- getEntryInfo() and RPC are not yet implemented.
- The cmake build doesn't integrate the built objects into the jar.
- The Java client and server tests are not built (but have been manually
tested).
This has not yet been tested on Windows.
Also only perform immediate notification to the callback actually
requesting the notification, not all existing callbacks.
Offset returned uids by 1 so uid=0 can be used to indicate immediate
notification.
Windows returns WSAEWOULDBLOCK on a connect() attempt on a nonblocking socket.
Also wrap socket error handling so errors are correctly reported on Windows.
Fixes#19.
- Missing header file callouts in some cases (library deltas)
- Lack of support for auto parameters in lambdas
- Defining of ERROR by windows.h
- Dispatcher::Connection needs a move constructor (default not generated)
- Need explicit enable_if on std::string move template in Value to avoid trying to move const char[] (string literal)
- Compile flags
This makes it difficult to test. Instead, store reference as member variable,
and populate it at constuction (with an alternate constructor available for
test purposes).
Updates are merged or themselves updated as user code changes. This avoids
the need for the dispatcher to do this and also avoids the need for disabling
updates when the dispatcher isn't running, because there's no risk of memory
usage piling up.
Previously, setters were locally but not globally atomic because they
used GetEntry() (globally atomic) in conjunction with locally atomic
gets/sets to the StorageEntry. To support synchronizing network handshakes
they need to be globally atomic.
GetEntry() has been removed due to this issue, so a helper was added to
StorageTest instead.
On the callback function, is_new indicates the value is newly added.
On adding a callback function, immediate_notify indicates the callback
should be called once (with is_new=true) for each matching entry that
already exists.
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
2. ...
- Link to code:
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. Windows 11]
- Project Information: [In Visual Studio Code, press the WPILib button and choose WPILib: Open Project Information. Press the copy button and paste the data here. If not using VS Code, please include WPILib version, Gradle version, Java version, C++ version (if applicable), and any third party libraries and versions]
- name:Add untracked files to index so they count as changes
run:git add -A
- name:Check output
run:|
set +e
git --no-pager diff --exit-code HEAD ':!*.bazel'
git_exit_code=$?
if test "$git_exit_code" -ne "0"; then
echo "::error ::upstream_utils check failed. This is usually caused by a bad script or the copied files differing from what the script outputs. You can learn more about using upstream_utils to modify thirdparty libraries at https://github.com/wpilibsuite/allwpilib/blob/main/upstream_utils/README.md"
As members, contributors, and leaders, we commit to fostering a community where everyone feels safe, respected, and valued. We are dedicated to ensuring that participation in this community is harassment-free, inclusive, and welcoming, regardless of age, body type, abilities (visible or invisible), ethnicity, gender identity or expression, sexual orientation, socioeconomic background, education, nationality, personal appearance, race, or religion.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Positive and respectful behavior is essential to creating a thriving community. This includes:
* Practicing **Gracious Professionalism®** at all times. Gracious Professionalism
is a way of doing things that encourages high-quality work, emphasizes the
value of others, and respects individuals and the community.
* Showing empathy, kindness, and patience.
* Respecting diverse perspectives and experiences.
* Giving and receiving constructive feedback with openness and humility.
* Owning mistakes, apologizing when necessary, and learning from them.
* Prioritizing the well-being and success of the entire community over individual interests.
Unacceptable behavior include:
* Using sexualized language, imagery, or making inappropriate advances
* Trolling, insulting or derogatory comments, and personal or political attacks
* Harassment in any form, whether public or private.
* Sharing private information (e.g., email or physical addresses) without explicit consent.
* Any behavior that is unprofessional, harmful, or exclusionary.
## Enforcement Responsibilities
Community leaders are responsible for maintaining these standards and will take appropriate action to address any behavior deemed harmful, threatening, or inappropriate. Actions may include removing content, issuing warnings, or, when necessary, banning individuals. Moderation decisions will be communicated transparently where appropriate.
## Scope
This Code of Conduct applies to all community spaces, events, and instances where individuals represent the community (e.g., official email accounts, social media posts, or in-person/virtual events).
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[wpilib@wpi.edu](mailto:wpilib@wpi.edu).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## A Note on Kindness
Building a community isn’t just about rules—it’s about connection. Every interaction is an opportunity to be understanding, compassionate, and supportive. Being a good human is the key to our ethos.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
So you want to contribute your changes back to WPILib. Great! We have a few contributing rules that will help you make sure your changes will be accepted into the project. Please remember to follow the rules written here, and behave with Gracious Professionalism.
So you want to contribute your changes back to WPILib. Great! We have a few contributing rules that will help you make sure your changes will be accepted into the project. Please remember to follow the rules in the [code of conduct](https://github.com/wpilibsuite/allwpilib/blob/main/CODE_OF_CONDUCT.md), and behave with Gracious Professionalism.
@@ -12,45 +14,68 @@ So you want to contribute your changes back to WPILib. Great! We have a few cont
## General Contribution Rules
- Everything in the library must work for the 3000+ teams that will be using it.
- Everything in the library must work for the 14000+ teams that will be using it.
- We need to be able to maintain submitted changes, even if you are no longer working on the project.
- Tool suite changes must be generally useful to a broad range of teams
- Excluding bug fixes, changes in one language generally need to have corresponding changes in other languages.
- Some features, such the addition of C++11 for WPILibC or Functional Interfaces for WPILibJ, are specific to that version of WPILib only.
- Substantial changes often need to have corresponding LabVIEW changes. To do this, we will work with NI on these large changes.
- Some features, such the addition of C++26 for WPILibC or Functional Interfaces for WPILibJ, are specific to that version of WPILib only. New language features added to C++ must be wrappable in Python for [RobotPy](https://github.com/robotpy).
- Changes should have tests.
- Code should be well documented.
- This often involves ScreenSteps. To add content to ScreenSteps, we will work with you to get the appropriate articles written.
- This involves writing tutorials and/or usage guides for your submitted feature. These articles are then hosted on the [WPILib](https://docs.wpilib.org/) documentation website. See the [wpilib-docs repository](https://github.com/wpilibsuite/wpilib-docs) for more information.
## What to Contribute
- Bug reports and fixes
- We will generally accept bug fixes without too much question. If they are only implemented for one language, we will implement them for any other necessary languages. Bug reports are also welcome, please submit them to our GitHub issue tracker.
- While we do welcome improvements to the API, there are a few important rules to consider:
- Features must be added to both WPILibC and WPILibJ, with rare exceptions.
-During competition season, we will not merge any new feature additions. We want to ensure that the API is stable during the season to help minimize issues for teams.
-Ask about large changes before spending a bunch of time on them! You can create a new issue on our GitHub tracker for feature request/discussion and talk about it with us there.
- Features must be added to Java (WPILibJ), C++ (WPILibC), and Python with rare exceptions.
-Most of Python (RobotPy) is created by wrapping WPILibC with pybind11 via semiwrap. In general, new user-facing functions or classes should have the proper wrapper configs updated, typically located in a YAML file with the same name as the header. See the [in-repo RobotPy README](./README-RobotPy.md) for more info and how to partially auto-update the configs. However, the command framework is reimplemented in Python, and requires code to be ported instead of being wrapped via semiwrap.
-During competition season, we will not merge any new feature additions or removals. We want to ensure that the API is stable during the season to help minimize issues for teams.
- Ask about large changes before spending a bunch of time on them! See [Contribution Process](#contribution-process) for where to ask.
- Features that make it easier for teams with less experience to be more successful are more likely to be accepted.
- Features in WPILib should be broadly applicable to all teams. Anything that is team specific should not be submitted.
- As a rule, we are happy with the general structure of WPILib. We are not interested in major rewrites of all of WPILib. We are open to talking about ideas, but backwards compatibility is very important for WPILib, so be sure to keep this in mind when proposing major changes.
-Generally speaking, we do not accept code for specific sensors. We have to be able to test the sensor in hardware on the WPILib test bed. Additionally, hardware availability for teams is important. Therefore, as a general rule, the library only directly supports hardware that is in the Kit of Parts. If you are a company interested in getting a sensor into the Kit of Parts, please contact FIRST directly at frcparts@firstinspires.org.
-While the library may contain support for specific sensors, these are typically items contained in the FIRST Robotics Competition Kit of Parts or commonly used hardware identified by FIRST or core WPILib Developers. If you think a certain sensor should be supported in WPILib, you may submit an issue justifying the reasons why it should be supported and approval will be determined by FIRST or core WPILib Developers. If you are a company interested in getting a sensor into the Kit of Parts, please contact FIRST directly at frcparts@firstinspires.org.
## Design Philosophy
WPILib's general design philosophy strays far away from the traditional Object-Oriented Programming architectures dominant in enterprise codebases. The general points to follow for WPILib are as follows:
- Prefer functions and composition over inheritance. Inheritance is rigid and often prevents evolution, as adding or removing methods from an inherited class risks breakage. For similar reasons, functional interfaces (`std::function` in C++) are preferred over actual interfaces.
- Avoid opaque black-boxes of functionality. Classes like RamseteCommand or HolonomicDriveController (both removed in 2027) are good examples of this. While they look like a good abstraction that helps beginners, the black-box nature means they are [difficult to debug](https://github.com/wpilibsuite/allwpilib/issues/3350) and it's impossible to instrument the internals to figure out what's going on, or they are extremely clunky to use compared to composing the individual components (thus defeating the point of abstracting it away; SwerveControllerCommand construction was [a huge pile of opaque arguments glued together](https://github.com/wpilibsuite/allwpilib/blob/v2026.2.2/wpilibjExamples/src/main/java/edu/wpi/first/wpilibj/examples/swervecontrollercommand/RobotContainer.java#L104-L114)). Composition is strongly preferred, with strong documentation and examples describing how to do that composition.
- Error at compile time, not runtime. Despite our best efforts, there will always be people who don't read stack traces (understandable for beginner programmers). Compile time errors show up in builds and in an IDE, which is much easier and faster for people to pinpoint and debug. Use language features to make invalid code impossible to build.
- The Matrix class in Java is an example of this. While clunky due to Java's weak generics system, it enforces correct Matrix dimensions at compile time, with the MatBuilder factory method throwing if the array passed in is the wrong size, which leads to the next point:
- Try to only throw exceptions at code startup, and only for things that are obviously incorrect. Robots shouldn't quit, and it's a real "feels bad" moment when yours does, especially in a match. It's oftentimes better to have a robot continue running when it sees nonsensical state as opposed to outright crashing, since other components are often still functional. If you can't make invalid code a compile time error, throwing at the start of the robot program is the next best solution, but avoid throwing in functions likely to be called throughout a robot's runtime.
- Sometimes the behavior of functions are just incorrect if invalid data is passed in, and throwing is one of the only options. This is a judgement call, but if there are no other options, throwing can be okay.
- An alternative to throwing is logging an error, typically with [the Alerts framework](https://docs.wpilib.org/en/latest/docs/software/telemetry/persistent-alerts.html); this is a good choice for runtime errors. Also see https://github.com/wpilibsuite/allwpilib/issues/6766 for an example of not throwing exceptions, but simply logging an error on invalid data.
- Note that hardware configuration issues such as a sensor not existing isn't necessarily obviously incorrect; it could be that the wrong port was specified, but it could also be unplugged due to external factors. Throwing just because it's unplugged can make for a "feels bad" moment, and should be avoided.
## Contribution Process
Have an idea to make WPILib better? Here's some steps to go from idea to implementation:
1. (Optional) **Discuss it in the Discord.** The programming discussion channel in the [Unofficial FIRST Robotics Competition Discord Server](https://discord.com/invite/frc) is a popular choice for initial discussion about ideas because many WPILib developers are active there and the live messaging nature of the platform is well suited for initial discussion (particularly for smaller changes). Note that the unofficial Discord server is not a mandatory step in the development process and is not endorsed by FIRST®.
2. (Recommended) **Open a GitHub issue.** GitHub issues are another way to get initial feedback about an idea before working on an implementation. Compared to the unofficial Discord server, GitHub issues have much wider visibility and are better suited for serious discussions about major changes. Getting feedback about an idea (whether in the unofficial Discord server or in a GitHub issue) before working on the implementation is recommended to avoid working on a change that will be rejected, though some ideas are pretty safe.
3. (Rare) **Create a design document in GitHub.** Sometimes, a change is so large that a design document is necessary to fully flesh out the details (and get feedback on them) before starting on an implementation. This is done through a pull request that adds the design document (as a Markdown file) to the repository. This is extremely rare, and it is sometimes done concurrently with the implementation if the change doesn't need much debate but is large enough to require a design document.
4. (Mandatory) **Create a GitHub pull request.** This is how you implement the changes, and is the focus of most of the rest of this document.
## Coding Guidelines
WPILib uses modified Google style guides for both C++ and Java, which can be found in the [styleguide repository](https://github.com/wpilibsuite/styleguide). Autoformatters are available for many popular editors at https://github.com/google/styleguide. Running wpiformat is required for all contributions and is enforced by our continuous integration system.
While the library should be fully formatted according to the styles, additional elements of the style guide were not followed when the library was initially created. All new code should follow the guidelines. If you are looking for some easy ramp-up tasks, finding areas that don't follow the style guide and fixing them is very welcome.
## Submitting Changes
### Pull Request Format
Changes should be submitted as a Pull Request against the master branch of WPILib. For most changes, we ask that you squash your changes down to a single commit. For particularly large changes, multiple commits are ok, but assume one commit unless asked otherwise. No change will be merged unless it is up to date with the current master. We will also not merge any changes with merge commits in them; please rebase off of master before submitting a pull request. We do this to make sure that the git history isn't too cluttered.
Changes should be submitted as a Pull Request against the main branch of WPILib. For most changes, commits will be squashed upon merge. For particularly large changes, multiple commits are ok, but assume one commit unless asked otherwise. We may ask you to break a PR into multiple standalone PRs or commits for rebase within one PR to separate unrelated changes. No change will be merged unless it is up to date with the current main branch. We do this to make sure that the git history isn't too cluttered.
Particularly large and/or breaking changes should be targeted to the 2027 branch, which targets the [Systemcore Robot Controller](https://community.firstinspires.org/introducing-the-future-mobile-robot-controller). The intent is minimize changes for 2026, to allow development to focus on preparing for 2027.
### Merge Process
When you first submit changes, Travis-CI will attempt to run `./gradlew check` on your change. If this fails, you will need to fix any issues that it sees. Once Travis passes, we will begin the review process in more earnest. One or more WPILib team members will review your change. This will be a back-and-forth process with the WPILib team and the greater community. Once we are satisfied that your change is ready, we will allow our Jenkins instance to test it. This will run the full gamut of checks, including integration tests on actual hardware. Once all tests have passed and the team is satisfied, we will merge your change into the WPILib repository.
When you first submit changes, GitHub Actions will attempt to run `./gradlew check` on your change. If this fails, you will need to fix any issues that it sees. Once Actions passes, we will begin the review process in more earnest. One or more WPILib team members will review your change. This will be a back-and-forth process with the WPILib team and the greater community. Once we are satisfied that your change is ready, we will allow our hosted instance to test it. This will run the full gamut of checks, including integration tests on actual hardware. Once all tests have passed and the team is satisfied, we will merge your change into the WPILib repository.
## Licensing
By contributing to WPILib, you agree that your code will be distributed with WPILib, and licensed under the license for the WPILib project. You should not contribute code that you do not have permission to relicense in this manner. This includes code that is licensed under the GPL that you do not have permission to relicense, as WPILib is not released under a copyleft license. Our license is the 3-clause BSD license, which you can find [here](license.txt).
By contributing to WPILib, you agree that your code will be distributed with WPILib, and licensed under the license for the WPILib project. You should not contribute code that you do not have permission to relicense in this manner. This includes code that is licensed under the GPL that you do not have permission to relicense, as WPILib is not released under a copyleft license. Our license is the 3-clause BSD license, which you can find [here](LICENSE.md).
This article contains instructions on building projects using a development build and a local WPILib build.
**Note:** This only applies to Java/C++ teams.
> [!WARNING]
> **There are no stability or compatibility guarantees for builds outside of [tagged releases](https://github.com/wpilibsuite/allwpilib/releases). Changes may not be fully documented. Use them at your own risk!**
>
> Development builds may be non-functional between the end of the season and the start of beta testing. Development builds are also likely to be incompatible with vendor libraries during this time.
## Development Build
Development builds are the per-commit build hosted every time a commit is pushed to the [allwpilib](https://github.com/wpilibsuite/allwpilib/) repository. These builds are then hosted on [artifactory](https://frcmaven.wpi.edu/artifactory/webapp/#/home).
To build a project using a development build, find the build.gradle file and open it. Then, add the following code below the plugin section and replace YEAR with the year of the development version. It is also necessary to use a 2027 GradleRIO version, ie `2027.0.0-alpha-5`
```groovy
wpi.maven.useLocal=false
wpi.maven.useDevelopment=true
wpi.versions.wpilibVersion='YEAR.+'
```
The top of your ``build.gradle`` file should now look similar to the code below. Ignore any differences in versions.
Java
```groovy
plugins {
id "java"
id "org.wpilib.GradleRIO" version "2027.0.0-alpha-5"
}
wpi.maven.useLocal = false
wpi.maven.useDevelopment = true
wpi.versions.wpilibVersion = '2027.+'
```
C++
```groovy
plugins {
id "cpp"
id "google-test-test-suite"
id "org.wpilib.GradleRIO" version "2027.0.0-alpha-5"
Building with a local build is very similar to building with a development build. Ensure you have built and published WPILib by following the instructions attached [here](https://github.com/wpilibsuite/allwpilib#building-wpilib). Next, find the ``build.gradle`` file in your robot project and open it. Then, add the following code below the plugin section and replace ``YEAR`` with the year of the local version.
Java
```groovy
plugins {
id "java"
id "org.wpilib.GradleRIO" version "2027.0.0-alpha-5"
}
wpi.maven.useLocal = false
wpi.maven.useWpilibMavenLocalDevelopment = true
wpi.versions.wpilibVersion = 'YEAR.424242.+'
```
C++
```groovy
plugins {
id "cpp"
id "google-test-test-suite"
id "org.wpilib.GradleRIO" version "2027.0.0-alpha-5"
}
wpi.maven.useLocal = false
wpi.maven.useWpilibMavenLocalDevelopment = true
wpi.versions.wpilibVersion = 'YEAR.424242.+'
```
# Systemcore Development
See the [developerRobot](developerRobot/README.md) subproject.
WPILib extensively uses [metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming#Code_generation) to generate code that would otherwise be tedious and error-prone to maintain. We use [Jinja](https://jinja.palletsprojects.com), a templating engine with a Python API, alongside JSON files that contain data to generate code. This document explains how to maintain these generated files and create new ones.
## File hierarchy
The Python script used to generate a subproject's files will always be located in the subproject's directory, e.g. wpilibc. It will always be called `generate_<thing>.py` where `<thing>` is the name for what you're generating.
The templates will be located under `subproject/src/generate/main`, and generated files will be located under `subproject/src/generated/main`.
If the generated file is for C++, the hierarchy should be symmetrical, so if a generated header is located under `subproject/src/generated/main/native/include/wpi/header.h`, the template to generate it should be located under `subproject/src/generate/main/native/include/wpi/template.h.jinja`. You should pretend like `subproject/src/generate/main` is just like `subproject/src/main`, in that the file hierarchy must make sense if the files weren't generated, e.g, headers that would go in `subproject/src/main/native/include/blah` should be in `subproject/src/generated/main/native/include/blah`.
If the generated file is for Java, templates should be located under `subproject/src/generate/main/java`, and the hierarchy for output files should reflect the declared package of the output Java files. For example, a Jinja template at `subproject/src/main/java/template.java.jinja` with the package `org.wpilib.wpilibj` would be used to generate Java files located at `subproject/src/generated/main/java/org/wpilib/wpilibj`
The JSON files live under `subproject/src/generate` since they apply to both languages. One unique case is JSON files that are used by multiple subprojects, currently only JSON files shared by wpilibc and wpilibj. In that specific case, the JSON files will always be located in wpilibj since Java is the most used language.
## Using code generation
If you've identified a set of files which are extremely similar, one file with lots of repetitive code, or both, you can create Jinja templates, a JSON file, and a Python script to automatically generate the code instead.
### Preparing files for codegen
Once you've identified the files you want to codegen, you will need to identify parts of code that are similar, and extract the data that's different. Code needs to go into your Jinja template, while data that will be used to fill in the template goes into a JSON file. Using game controllers as an example, they have lots of similar methods to read the value of a button, check if a button has been pressed since the last check, and check if a button has been released since the last check. Those methods are code that goes in a Jinja template, with the specific button replaced with a Jinja expression. The buttons, both the name and value, go into a JSON file.
### Writing a Python script
To maintain consistency with other Python scripts, copy an existing `generate_*.py` script. [generate_pwm_motor_controllers.py](./wpilibj/generate_pwm_motor_controllers.py) is a good start, since it's relatively basic. Modify the script to reference your templates and JSON file, modify the paths so the files end up in the right place, and rename the functions so they match what you're generating. An important part of the script is to give the files the correct name. Depending on files you're generating, this could be the name of the template itself (see [ntcore/generate_topics.py](./ntcore/generate_topics.py)) or it could be part of the data in the JSON file.
### (Re)Generating files and committing them
Once your Python script is complete, you can run `python generate_<thing>.py` to generate the files. Once you're finished with your files, commit these files to Git. If you regenerated the files and Git indicates the files have changed, but the diff doesn't show any changes, only the line endings have changed. If you expected changes to the generated code, you didn't correctly make changes. If you didn't expect changes, you can ignore this and discard the changes. Also ensure that you've marked the Python script as executable, since this is necessary for CI workflows to run your scripts. To add your script to the CI workflows, edit [.github/workflows/pregen_all.py](.github/workflows/pregen_all.py), and add your script alongside the rest of the scripts.
#### (Re)Generating QuickBuffers files
Regenerating QuickBuffers files requires the Protocol Buffers compiler (protoc), and the QuickBuffers plugin, which can be found on [their releases page](https://github.com/HebiRobotics/QuickBuffers/releases). Once you have both, you can pass their paths into the generation scripts with `--protoc` and `--quickbuf_plugin` and regenerate the files.
Currently the 3rd party external deps are opencv, libssh, ceres, and gtsam.
For publishing these dependencies, the version needs to be manually updated in the publish.gradle file of their respective repository.
Then, upload a new tag for the dependency you want to build for, which will automatically start a build.
The CI workflow should set `RUN_AZURE_ARTIFACTORY_RELEASE` to `true` on tagged runs. Then when the pipeline gets started, the final build outputs will be uploaded to artifactory.
To use newer versions of C++ dependencies, in `shared/config.gradle`, update the version related to the specific dependency.
For Java dependencies, there is likely a file related to the specific dependency in the shared folder. Update the version in there.
Note, changing artifact locations requires updating the `native-utils` plugin; specifically, the `configureDependencies` method in the `WPINativeUtilsExtension` class.
## Publishing allwpilib
allwpilib publishes to the development repo on every push to main. To publish a release build, upload a new tag, and a release will automatically be built and published.
### Adding a new robot code dependency/subproject
If a new subproject has been added that is meant for use from robot code, both GradleRIO and the `native-utils` plugin need to be updated. `native-utils` is updated in the same way as 3rd party dependencies. For GradleRIO, update the `WPIJavaDepsExtension` to contain your new subproject's artifacts.
## Publishing VS Code
Before publishing, make sure to update the GradleRIO version in `vscode-wpilib/resources/gradle/version.txt`. Also make sure the Gradle Wrapper version matches the wrapper required by GradleRIO.
Upon pushing a tag, a release will be built, and the files will be uploaded to the releases on GitHub.
## Publishing GradleRIO
Before publishing, make sure to update the version in build.gradle. Publishing must happen locally, using the command `./gradlew publishPlugin`. This does require your API key for publishing to be set.
## Building the installer
Update the GradleRIO version in gradle.properties, and in the scripts folder in vscode, update the vscode extension. To publish a release build, upload a new tag, and a release will automatically be built and published to artifactory and cloudflare.
WPILib publishes its built artifacts to our Maven server for use by downstream projects. This document explains these locations, and the meanings of artifact names, classifiers, and versions.
## Repositories
We provide two repositories. These repositories are:
The release repository is where official WPILib releases are pushed.
The development repository is where development releases of every commit to [main](https://github.com/wpilibsuite/allwpilib/tree/main) is pushed.
## Artifact classifiers
We provide two base types of artifacts.
The first types are Java artifacts. These are usually published as `jar` files. Usually, the actual jar file is published with no classifier. The sources are published with the `-sources` classifier, and the javadocs are published with the `-javadoc` classifier. These artifacts are published with the base artifact name as their artifact ID, with a `-java` extension.
Example:
```
org.wpilib.wpilibj:wpilibj-java:version
```
The second types are native artifacts. These are usually published as `zip` files. The `-sources` and `-headers` classifiers contain the sources and headers respectively for the library. Each artifact also contains a classifier for each platform we publish. This platform is in the format `{os}{arch}`. The full list of supported platforms can be found in [native-utils in the Platforms nested class](https://github.com/wpilibsuite/native-utils/blob/main/src/main/java/org/wpilib/nativeutils/WPINativeUtilsExtension.java). If the library is built statically, it will have `static` appended to the classifier. Additionally, if the library was built in debug mode, `debug` will be appended to the classifier. The platform artifact only contains the binaries for a specific platform. Note that the binary artifacts never contain the headers, you always need the `-headers` classifier to get those.
If the library is Java and C++ and has a JNI component, the native artifact will have a shared library containing JNI entrypoints alongside the C++ shared library. This JNI shared library will have a `jni` suffix in the file name.
Native artifacts are published with the base artifact name as their artifact ID, with a `-cpp` extension.
WPILib is normally built with Gradle, but [Bazel](https://www.bazel.build/) can also be used to increase development speed due to the superior caching ability and the ability to use remote caching and remote execution (on select platforms).
## Prerequisites
- Install [Bazelisk](https://github.com/bazelbuild/bazelisk/releases) and add it to your path. Bazelisk is a wrapper that will download the correct version of Bazel specified in the repository. Note: You can alias/rename the binary to `bazel` if you want to keep the familiar `bazel build` vs `bazelisk build` syntax.
## Building
To build the entire repository, simply run `bazel build //...`. To run all of the unit tests, run `bazel test //...`
Other examples:
-`bazel build //wpimath/...` - Builds every target in the wpimath folder
-`bazel test //wpiutil:wpiutil-cpp-test` - Runs only the cpp test target in the wpiutil folder
-`bazel coverage //wpiutil/...` - (*Nix only) - Runs a code coverage report for both C++ and Java on all the targets under wpiutil
## User settings
When invoking Bazel, it will check if `user.bazelrc` exists for additional, user specified flags. You can use these settings to do things like always ignore builds in a specific folder, or limiting the CPU/RAM usage during a build.
Examples:
-`build --build_tag_filters=-wpi-example` - Do not build any targets tagged with `wpi-example` (Currently all of the targets in wpilibcExamples and wpilibjExamples contain this tag)
-`build -c opt` - Always build optimized targets. The default compiler flags were chosen to build as fast as possible, and thus don't contain many optimizations
-`build -k` - `-k` is analogous to the MAKE flag `--keep-going`, so the build will not stop on the first error.
- ```
build --local_resources=memory=HOST_RAM*.5 # Don't use more than half my RAM when building
build --local_resources=cpu=HOST_CPUS-1 # Leave one core alone
```
Bazel's RAM usage estimation is simplistic and hardcoded, so limiting the allowed number of CPU cores is the best way to reduce memory usage if it becomes a problem.
The default settings build all the release artifact variants relevant for your platform. The overall list of options ends up being, essentially, all the variants of (linux, osx, windows) x (debug, release) x (static, shared) x (aarch64, x86). OSX and Windows are hard to compile for from any other OS, so we by default build for your local OS and the system core, with all the variants.
This can be a bit expensive. If you would like to build a subset, you can specify the repo environmental variable, `WPI_PUBLISH_CLASSIFIER_FILTER`, and pick what you build for. The default is, in the .bazelrc file,
```
common --repo_env="WPI_PUBLISH_CLASSIFIER_FILTER=headers,sources,linuxsystemcore,linuxsystemcoredebug,linuxsystemcorestatic,linuxsystemcorestaticdebug,linuxx86-64,linuxx86-64debug,linuxx86-64static,linuxx86-64staticdebug,osxuniversal,osxuniversaldebug,osxuniversalstatic,osxuniversalstaticdebug,windowsarm64,windowsarm64debug,windowsarm64static,windowsarm64staticdebug,windowsx86-64,windowsx86-64debug,windowsx86-64static,windowsx86-64staticdebug"
```
Modify this to your likings if you want to build less.
## Pregenerating Files
allwpilib uses extensive use of pre-generating files that are later used to build C++ / Java libraries that are tracked by version control. Quite often,
these pre-generation scripts use some configuration file to create multiple files inside of an output directory. While this process could be accomplished
with a `genrule` that would require an explicit listing of every output file, which would be tedious to maintain as well as potentially confusing to people
adding new features those libraries. Therefore, we use `@aspect_bazel_lib` and their `write_source_files` feature to generate these directories. In the event that the generation process creates more than a small handful of predictable files, a custom rule is written to generate the directory.
## Remote Caching
One of the huge benefits of Bazel is its remote caching ability. However, due to Bazel's strict build definitions, it is hard to share remote cache artifacts between different computers unless our toolchains are fully hermetic, which means you are unlikely to be able to reuse the cache artifacts published from the `main` branch on your local machine like you might be able to with the `gradle` or `cmake` caches. Luckily, the GitHub Actions CI machines are generally stable between runs and can reuse cache artifacts, and your local machine should remain stable, so if you set up a free buildbuddy account you can have your fork's CI actions be able to use a personalized cache, as well as your local machine.
For the main `allwpilib` upstream, the cache is only updated on the main branch; pull requests from forks will not be able to modify the cache. However, you can set up your fork to enable its own cache by following the steps below.
### Setting Up API keys
Follow the [buildbuddy authentication](https://www.buildbuddy.io/docs/guide-auth) guide to create keys. For your local machine, it is recommended that you place the following configuration line in either a `user.bazelrc` or `bazel_auth.rc` file in the repositories root directory.
```
build --remote_header=<your api key>
```
To get your forks CI actions using your own buildbuddy cache, follow [GitHub's](https://docs.github.com/en/actions/how-tos/security-for-github-actions/security-guides/using-secrets-in-github-actions) documentation for setting up a repository secret. The secrets key should be `BUILDBUDDY_API_KEY`, and the value should be your buildbuddy API key.
WPILib is normally built with Gradle, however for some systems, such as Linux based coprocessors, Gradle doesn't work correctly, especially if cscore is needed, which requires OpenCV. Furthermore, the CMake build can be used for C++ development because it provides better build caching compared to Gradle. We provide the CMake build for these cases. Although macOS is supported, these docs will only go over Linux and Windows builds, but should mostly work for macOS as well. If you are stuck, you can look at the GitHub workflows for any OS to see how it works. The CMake build does not build Java or Python, only C++.
## Libraries that get built
* apriltag
* cameraserver
* commandsv2
* cscore
* datalog
* fields
* hal (simulation HAL only)
* ntcore
* romiVendordep
* simulation extensions
* wpigui
* wpilib (wpilibc, wpilibj, and developerRobot)
* wpimath
* wpinet
* wpiutil
* xrpVendordep
## GUI apps that get built
* datalogtool
* glass
* outlineviewer
* sysid
* wpical
* halsim_gui (if simulation extensions are enabled)
By default, all libraries get built with a default CMake setup. The libraries are built as shared libraries. Data Log Tool is only built if libssh is available.
## Prerequisites
OpenCV needs to be findable by CMake. On systems like the Jetson, this is installed by default. Otherwise, you will need to build OpenCV from source and install it.
## Build Options
The following build options are available:
*`BUILD_SHARED_LIBS` (ON Default)
* This option will cause CMake to build static libraries instead of shared libraries.
*`WITH_CSCORE` (ON Default)
* This option will cause cscore to be built. Turning this off will implicitly disable cameraserver. If this is off, the OpenCV build requirement is removed.
*`WITH_EXAMPLES` (OFF Default)
* This option will build C++ examples.
*`WITH_GUI` (ON Default)
* This option will build GUI items. If this is off, and `WITH_SIMULATION_MODULES` is on, the simulation GUI will not be built.
*`WITH_NTCORE` (ON Default)
* This option will cause ntcore to be built. Turning this off will implicitly disable wpinet, and will cause an error if `WITH_WPILIB` is enabled.
*`WITH_SIMULATION_MODULES` (ON Default)
* This option will build simulation modules.
*`WITH_TESTS` (ON Default)
* This option will build C++ unit tests. These can be run via `ctest -C <config>`, where `<config>` is the build configuration, e.g. `Debug` or `Release`.
*`WITH_WPILIB` (ON Default)
* This option will build the HAL and wpilibc during the build. The HAL is the simulation HAL, unless the external HAL options are used. The CMake build has no capability to build for Systemcore.
*`WITH_WPIMATH` (ON Default)
* This option will build the wpimath library. This option must be on to build wpilib.
*`NO_WERROR` (OFF Default)
* This option will disable the `-Werror` compilation flag for non-MSVC builds.
*`WPILIB_TARGET_WARNINGS`
* Add compiler flags to this option to customize compiler options like warnings.
## Build Setup
The WPILib CMake build does not allow in source builds. Because the `build` directory is used by Gradle, we recommend a `build-cmake` directory in the root. This folder is included in the gitignore. We support building with Ninja; other options like Makefiles may be broken.
Once you have a build folder, run CMake configuration in the root directory with the following command.
```
cmake --preset default
```
If you want to change any of the options, add `-DOPTIONHERE=VALUE` to the `cmake` command. This will check for any dependencies. If everything works properly this will succeed. If not, please check out the troubleshooting section for help.
If you want, you can also use `ccmake` in order to visually set these properties as well. [Here](https://cmake.org/cmake/help/v3.0/manual/ccmake.1.html) is the link to the documentation for that program. On Windows, you can use `cmake-gui` instead.
## Presets
The WPILib CMake setup has a variety of presets for common configurations and options used. The default sets the generator to Ninja and build directory to `build-cmake`. The other preset is `sccache` (sets the C/C++ compiler launcher to sccache).
## Building
Once you have CMake setup. run `cmake --build .` from the directory you configured CMake in. This will build all libraries possible. We recommend running `cmake --build .` with multiple jobs. For allwpilib, a good rule of thumb is one worker for every 2 GB of available RAM. To run a multi-job build, run the following command with x being the number of jobs you want.
```
cmake --build . --parallel x
```
Note: wpimath takes gigabytes of RAM to compile. Because of this, the compilers may crash while building due to a lack of memory and your computer may slow down. If you have less than 16 GB of RAM available, you may want to consider building it separately first by adding `--target wpimath` and running it with ~3 jobs to prevent crashes from running out of memory.
To build with a certain configuration, like `Debug` or `Release`, add `--config <config>`, where `<config>` is the name of the configuration you want to build with.
## Installing
After build, the easiest way to use the libraries is to install them. Run the following command to install the libraries. This will install them so that they can be used from external CMake projects.
```
sudo cmake --build . --target install
```
## Preparing to use the installed libraries
On Windows, make sure the directories for the libraries you built are on PATH. For wpilib, the default install location is `C:\Program Files (x86)\allwpilib`. If you built other libraries like OpenCV from source, install them, and add the install directories to PATH. This ensures CMake can locate the libraries.
You will also want to add the directories where the DLLs are located (usually the `bin` subdirectory of the install directory) to PATH so they can be loaded by your program.
## Using the installed libraries for C++.
Using the libraries from C++ is the easiest way to use the built libraries.
To do so, create a new folder to contain your project. Add the following code below to a `CMakeLists.txt` file in that directory.
```cmake
cmake_minimum_required(VERSION3.11)
project(vision_app)# Project Name Here
find_package(wpilibREQUIRED)
add_executable(my_vision_appmain.cpp)# executable name as first parameter
If you want to use other libraries or are building a robot program, `wpilibc` and `hal` should be added in the `target_link_libraries` function, along with any other libraries you plan on using, e.g. `wpimath`.
Add a `main.cpp` file to contain your code, and create a build folder. Move into the build folder, and run
```
cmake /path/to/folder/containing/CMakeLists
```
After that, run `cmake --build .`. That will create your executable. Then you should be able to run `./my_vision_app` to run your application.
## Using vendordeps
Vendordeps are not included as part of the `wpilib` CMake package. However, if you want to use a vendordep, you need to use `find_package(VENDORDEP)`, where `VENDORDEP` is the name of the vendordep (case-sensitive), like `xrpVendordep` or `romiVendordep`. Note that commandsv2, while a vendordep in normal robot projects, is not built as a vendordep in CMake, and is instead included as part of the `wpilib` CMake package. After you used `find_package`, you can reference the vendordep library like normal (using `target_link_libraries`).
## Troubleshooting
Below are some common issues that are run into when building.
#### Missing OpenCV
If you are missing OpenCV, you will get an error message similar to this.
```
CMake Error at cscore/CMakeLists.txt:3 (find_package):
By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "OpenCV", but
CMake did not find one.
Could not find a package configuration file provided by "OpenCV" with any
of the following names:
OpenCVConfig.cmake
opencv-config.cmake
Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
"OpenCV_DIR" to a directory containing one of the above files. If "OpenCV"
provides a separate development package or SDK, be sure it has been
installed.
```
If you get that, you need make sure OpenCV was installed, and then reattempt to configure. If that doesn't work, set the `OpenCV_DIR` variable to the directory where you built OpenCV.
allwpilib hosts a mirror of RobotPy that can be built with Bazel on Linux. The intent of the mirror is to have breaking changes identified early and fixed by the PR creator so that when WPILib releases are made, there is much less work required to release a RobotPy version that wraps it. It is not a goal for allwpilib to replace the RobotPy repo; it will still be considered the "source of truth" for Python builds and will be responsible for building against all of the applicable architectures and multiple versions of Python.
## Build Process
The upstream RobotPy repository uses TOML configuration files and semiwrap to produce Meson build scripts. The allwpilib fork uses these TOML configuration files to auto-generate Bazel build scripts. In general, each project (wpiutil, wpimath, etc) defines two pybind extensions; one that simply wraps the native library, and another that adds extension(s) that and contains all of the Python files for the library. Both of these subprojects have auto-generated build files; a `robotpy_native_build_info.bzl` for the native wrapper and `robotpy_pybind_build_info.bzl` which defines the extensions and Python library.
## Disabling RobotPy builds
Building the RobotPy software on top of the standard C++/Java software can result in more than doubling the amount of time it takes to compile. To skip building the RobotPy tooling, you can add `--config=skip_robotpy` to the command line or to your `user.bazelrc`.
# Syncing with RobotPy
[Copybara](https://github.com/google/copybara) is used to maintain synchronization between the upstream RobotPy repositories and the allwpilib mirror. GitHub Actions can be manually run, which will create pull requests that will update all of the RobotPy files between the two repositories. The ideal process is that the allwpilib mirror is always building in CI, and once a release is created, the RobotPy team can run the `wpilib -> robotpy` Copybara task, make any fine tuned adjustments and create their release. In the event that additional changes are made on the RobotPy side, they can run the `robotpy -> wpilib` task to push the updates back to the mirror. However, the goal of the mirroring the software here is to be able to more rapidly test changes and will hopefully overwhelmingly eliminate the need for syncs in this direction.
## Creating a user config
The Copybara scripts needs to know information about what repositories it will be pushing the synced changes to. These can be specified on the command line, or you can create a `shared/bazel/copybara/.copybara.json` config file to save your personalized settings to avoid having to type things out every time. To run the full suite of migrations, you need a fork of [allwpilib](https://github.com/wpilibsuite/allwpilib), a fork of [mostrobotpy](https://github.com/robotpy/mostrobotpy), and a fork of RobotPy's [commands-v2](https://github.com/robotpy/robotpy-commands-v2). If you only wish to run a subset of commands (i.e. not sync the commands project), you do not need to include that in your user config.
This process is slightly more complicated, because you will almost certainly also need to update the Maven artifacts that mostrobopy is using. Because of this, you must also specify the version number that has been published to WPILib's Maven repository. If you are trying to get an early, non-released development build pushed over, you can also add the `--development_build` flag:
The build process is highly automated and automatically parses C++ header files to generate pybind11 bindings. Some of these steps here are considered "pregeneration" steps, and the Bazel build system will update build files as necessary. If a new header is added, or if the contents of a header file has changed, some of the pregeneration scripts might need to be run. If you encounter an error building `robotpy` code, it is recommended that you go through these steps to make sure everything is set up correctly. The examples are for `wpilibc`, but similar build tasks and tests exist for each wrapped project.
## 1. scan-headers
This can be the first source of problems if a new header file has been added. `semiwrap` will look through all of the headers for a library and notify you if a file is not covered by the projects `pyproject.toml` file. Bazel has a test case to ensure the files are up to date.
An example test failure when a new header being introduced. You can run the test with the following command:
To fix this, you can copy the lines from the console, and add them to the pyproject.toml file, located here `wpilibc/src/main/python/pyproject.toml`
## 2. update-yaml
This process parses all of the header files, and creates a representation of the classes / enums / etc in YAML. Occasionally, some functions might be ignored or need custom pybind code, which can be added to these files by the user.
There is a Bazel task that you can run to automatically update the files:
`bazel run //wpilibc:write_robotpy-wpilib-update-yaml`
## 3. generate-build-info
This step takes the yaml files, and auto-generates a Bazel build script for the library.
There is a Bazel task that you can run to automatically update the files:
`bazel run //wpilibc:robotpy-wpilib-generator.generate_build_info`
## semiwrap errors
If all of the above steps go smoothly and have their tests pass, but the generated cpp files still won't compile, it is possible that either an update needs to be made to the semiwrap tool to handle the new complex functionality, the new functionality can be ignored, or the new functionality might be better handled with a custom pybind11 implementation. In any case, it is best to reach out to the RobotPy team for guidance.
## Running multiple projects at once
Each project has its own `scan-headers` and various pregeneration tools, but you can run all of them at once with the following commands. Note: Sometimes if something in the dependency chain for a library fails, these amalgamation commands will also fail. If that happens, fix your way up the dependency chain project by project.
```
# Scan Headers
bazel test //... -k --test_tag_filters=robotpy_scan_headers --build_tests_only
Welcome to the WPILib project. This repository contains the HAL, WPILibJ, and WPILibC projects. These are the core libraries for creating robot programs for the roboRIO.
Welcome to the WPILib project. This repository contains the HAL, CameraServer, Commands (v2 and v3), NTCore, WPIMath, and WPILib projects. These are the core libraries for creating robot programs for Systemcore.
- [WPILib Mission](#wpilib-mission)
- [WPILib Project](#wpilib-project)
- [WPILib Mission](#wpilib-mission)
- [Building WPILib](#building-wpilib)
- [Requirements](#requirements)
- [Setup](#setup)
- [Building](#building)
- [Publishing](#publishing)
- [Structure and Organization](#structure-and-organization)
- [Contributing to WPILib](#contributing-to-wpilib)
- [Requirements](#requirements)
- [Setup](#setup)
- [Building](#building)
- [Faster builds](#faster-builds)
- [Using Development Builds](#using-development-builds)
- [Running examples in simulation](#running-examples-in-simulation)
- [Publishing](#publishing)
- [Structure and Organization](#structure-and-organization)
- [Contributing to WPILib](./CONTRIBUTING.md)
## WPILib Mission
The WPILib Mission is to enable FIRST Robotics teams to focus on writing game-specific software rather than focussing on hardware details - "raise the floor, don't lower the ceiling". We work to enable teams with limited programming knowledge and/or mentor experience to be as successful as possible, while not hampering the abilities of teams with more advanced programming capabilities. We support Kit of Parts control system components directly in the library. We also strive to keep parity between major features of each language (Java, C++, and NI's LabVIEW), so that teams aren't at a disadvantage for choosing a specific programming language. WPILib is an open source project, licensed under the BSD 3-clause license. You can find a copy of the license [here](license.txt).
The WPILib Mission is to enable FIRST Robotics Competition (FRC) and FIRST Tech Challenge (FTC) teams to focus on writing game-specific software rather than focusing on hardware details - "raise the floor, don't lower the ceiling". We work to enable teams with limited programming knowledge and/or mentor experience to be as successful as possible, while not hampering the abilities of teams with more advanced programming capabilities. We support the FRC Kit of Parts/FTC control system components directly in the library. We also strive to keep parity between major features of each language (Java, C++, and Python), so that teams aren't at a disadvantage for choosing a specific programming language. WPILib is an open source project, licensed under the BSD 3-clause license. You can find a copy of the license [here](LICENSE.md).
# Quick Start
Below is a list of instructions that guide you through cloning, building, publishing and using local allwpilib binaries in a robot project. This quick start is not intended as a replacement for the information further listed in this document.
1. Clone the repository with `git clone https://github.com/wpilibsuite/allwpilib.git`
2. Build the repository with `./gradlew build` or `./gradlew build --build-cache` if you have an internet connection
3. Publish the artifacts locally by running `./gradlew publish`
4. [Update your](DevelopmentBuilds.md) `build.gradle` [to use the artifacts](DevelopmentBuilds.md)
# Building WPILib
Using Gradle makes building WPILib very straightforward. It only has a few dependencies on outside tools, such as the ARM cross compiler for creating roboRIO binaries.
Using Gradle makes building WPILib very straightforward. It only has a few dependencies on outside tools, such as the ARM cross compiler for creating Systemcore binaries.
## Requirements
-A C++ compiler
-On Linux, gcc works fine
- On Windows, you need Visual Studio 2015 (the free community edition works fine).
Make sure to select the C++ Programming Language for installation
-Note that the JRE is insufficient; the full JDK is required
- On Ubuntu, run `sudo apt install openjdk-25-jdk`
- On Windows, install the JDK 25 .msi from the link above
- On macOS, install the JDK 25 .pkg from the link above
- C++ compiler
- On Linux, install GCC 11 or greater
- On Windows, install [Visual Studio Community 2022](https://visualstudio.microsoft.com/vs/community/) and select the C++ programming language during installation (Gradle can't use the build tools for Visual Studio)
- On macOS, install the Xcode command-line build tools via `xcode-select --install`. Xcode 14 or later is required.
- Raspberry Pi toolchain (optional)
- Run `./gradlew installArm64Toolchain` after cloning this repository
- Systemcore toolchain (required for Systemcore development)
- Run `./gradlew installSystemCoreToolchain` after cloning this repository
- If the WPILib installer was used, this toolchain is already installed
On macOS ARM, run `softwareupdate --install-rosetta`. This is necessary to be able to use the macOS x86 Systemcore toolchain on ARM.
On linux, run `sudo apt install libx11-dev libgl-dev libxcursor-dev libxrandr-dev libxinerama-dev libxi-dev` to be able to build things depending on glfw.
## Setup
Clone the WPILib repository. If the toolchains are not installed, install them, and make sure they are available on the system PATH.
Clone the WPILib repository and follow the instructions above for installing any required tooling. The build process uses versioning information from git. Downloading the source is not sufficient to run the build.
See the [styleguide README](https://github.com/wpilibsuite/styleguide/blob/master/README.md) for wpiformat setup instructions.
See the [styleguide README](https://github.com/wpilibsuite/styleguide/blob/main/README.md) for wpiformat setup instructions.
## Building
@@ -51,64 +82,115 @@ To build a specific subproject, such as WPILibC, you must access the subproject
./gradlew :wpilibc:build
```
If you have installed the FRC Toolchain to a directory other than the default, or if the Toolchain location is not on your System PATH, you can pass the `toolChainPath` property to specify where it is located. Example:
If you also want simulation to be built, add -PmakeSim. This requires gazebo_transport. We have tested on 14.04 and 15.05, but any correct install of Gazebo should work, even on Windows if you build Gazebo from source. Correct means CMake needs to be able to find gazebo-config.cmake. See [The Gazebo website](https://gazebosim.org/) for installation instructions.
```bash
./gradlew build -PmakeSim
```
If you prefer to use CMake directly, the you can still do so.
The common CMake tasks are wpilibcSim, frc_gazebo_plugins, and gz_msgs
```bash
mkdir build #run this in the root of allwpilib
cd build
cmake ..
make
```
The gradlew wrapper only exists in the root of the main project, so be sure to run all commands from there. All of the subprojects have build tasks that can be run. Gradle automatically determines and rebuilds dependencies, so if you make a change in the HAL and then run `./gradlew :wpilibc:build`, the HAL will be rebuilt, then WPILibC.
There are a few tasks other than `build` available. To see them, run the meta-task `tasks`. This will print a list of all available tasks, with a description of each task.
If opening from a fresh clone, generated java dependencies will not exist. Most IDEs will not run the generation tasks, which will cause lots of IDE errors. Manually run `./gradlew compileJava` from a terminal to run all the compile tasks, and then refresh your IDE's configuration (In VS Code open settings.gradle and save).
### Faster builds
`./gradlew build` builds _everything_, which includes debug and release builds for desktop and all installed cross compilers. Many developers don't need or want to build all of this. Therefore, common tasks have shortcuts to only build necessary components for common development and testing tasks.
`./gradlew testDesktopCpp` and `./gradlew testDesktopJava` will build and run the tests for `wpilibc` and `wpilibj` respectively. They will only build the minimum components required to run the tests. `./gradlew testDesktop` will run both `testDesktopJava` and `testDesktopCpp`.
`testDesktopCpp`, `testDesktopJava`, and `testDesktop` tasks also exist for the following projects:
-`apriltag`
-`cameraserver`
-`cscore`
-`hal`
-`ntcore`
-`commandsv2`
-`wpimath`
-`wpinet`
-`wpiunits`
-`wpiutil`
-`romiVendordep`
-`xrpVendordep`
These can be ran with `./gradlew :projectName:task`.
`./gradlew buildDesktopCpp` and `./gradlew buildDesktopJava` will compile `wpilibcExamples` and `wpilibjExamples` respectively. The results can't be ran, but they can compile.
### Build Cache
Run with `--build-cache` on the command-line to use the shared [build cache](https://docs.gradle.org/current/userguide/build_cache.html) artifacts generated by the continuous integration server. Example:
```bash
./gradlew build --build-cache
```
### Using Development Builds
Please read the documentation available [here](DevelopmentBuilds.md)
### Custom toolchain location
If you have installed the WPILib Toolchain to a directory other than the default, or if the Toolchain location is not on your System PATH, you can pass the `toolChainPath` property to specify where it is located. Example:
Once a PR has been submitted, formatting can be run in CI by commenting `/format` on the PR. A new commit will be pushed with the formatting changes.
> [!NOTE]
> The `/format` action has been temporarily disabled. The individual formatting commands can be run locally as shown below. Alternately, the Lint and Format action for a PR will upload a patch file that can be downloaded and applied manually.
#### wpiformat
wpiformat can be executed anywhere in the repository via `py -3 -m wpiformat` on Windows or `python3 -m wpiformat` on other platforms.
#### Java Code Quality Tools
The Java code quality tools Checkstyle, PMD, and Spotless can be run via `./gradlew javaFormat`. SpotBugs can be run via the `spotbugsMain`, `spotbugsTest`, and `spotbugsDev` tasks. These tools will all be run automatically by the `build` task. To disable this behavior, pass the `-PskipJavaFormat` flag.
If you only want to run the Java autoformatter, run `./gradlew spotlessApply`.
### Generated files
Several files within WPILib are generated using Jinja. If a PR is opened that modifies these templates then the files can be generated through CI by commenting `/pregen` on the PR. A new commit will be pushed with the regenerated files. See [GeneratedFiles.md](GeneratedFiles.md) for more information.
### CMake
CMake is also supported for building. See [README-CMake.md](README-CMake.md).
### Bazel
Bazel is also supported for building. See [README-Bazel.md](README-Bazel.md).
## Running examples in simulation
Examples can be run in simulation with the following command:
```bash
./gradlew wpilibcExamples:runExample
./gradlew wpilibjExamples:runExample
```
where `Example` is the example's folder name.
## Publishing
If you are building to test with the Eclipse plugins or just want to export the build as a Maven-style dependency, simply run the `publish` task. This task will publish all available packages to ~/releases/maven/development. If you need to publish the project to a different repo, you can specify it with `-Prepo=repo_name`. Valid options are:
If you are building to test with other dependencies or just want to export the build as a Maven-style dependency, simply run the `publish` task. This task will publish all available packages to ~/releases/maven/development. If you need to publish the project to a different repo, you can specify it with `-Prepo=repo_name`. Valid options are:
- development - The default repo.
- beta - Publishes to ~/releases/maven/beta.
- stable - Publishes to ~/releases/maven/stable.
- release - Publishes to ~/releases/maven/release.
The following maven targets a published by this task:
- edu.wpi.first.wpilib.cmake:cpp-root:1.0.0 - roboRIO C++
- edu.wpi.first.wpilibc.simulation:WPILibCSim:0.1.0 - Simulation C++
- edu.wpi.first.wpilibj.simulation:SimDS:0.1.0-SNAPSHOT - The driverstation for controlling simulation.
- org.gazebosim:JavaGazebo:0.1.0-SNAPSHOT - Gazebo protocol for Java.
The Maven artifacts are described in [MavenArtifacts.md](MavenArtifacts.md)
## Structure and Organization
The main WPILib code you're probably looking for is in WPILibJ and WPILibC. Those directories are split into shared, sim, and athena. Athena contains the WPILib code meant to run on your roboRIO. Sim is WPILib code meant to run on your computer with Gazebo, and shared is code shared between the two. Shared code must be platform-independent, since it will be compiled with both the ARM cross-compiler and whatever desktop compiler you are using (g++, msvc, etc...).
The main WPILib code you're probably looking for is in WPILibJ and WPILibC. Those directories contain the high-level hardware/robot classes used for interacting with hardware, the Driver Station, and contain the core framework that almost all robot projects use.
The Simulation directory contains extra simulation tools and libraries, such as gz_msgs and JavaGazebo. See sub-directories for more information.
The src/test directories under each subproject for C++ and Java contain test code that runs on GitHub Actions. When you submit code for review, it is tested by GitHub Actions' runners. If you add new functionality you should make sureto write tests for it so we don't break it in the future.
The integration test directories for C++ and Java contain test code that runs on our test-system. When you submit code for review, it is tested by those programs. If you add new functionality you should make sure to write tests for it so we don't break it in the future.
The hal directory contains more C++ code meant to run on Systemcore. HAL is an acronym for "Hardware Abstraction Layer", and it interfaces with the robot controller to enable hardware interactions. The HAL is split into cpp, sim, and systemcore. The systemcore directory contains the WPILib code meant to run on your Systemcore. Sim is WPILib code meant to run on your computer, and cpp is code shared between the two. Code in the cpp directory must be platform-independent, since it will be compiled with both the ARM cross-compiler and whatever desktop compiler you are using (g++, MSVC, etc...).
The hal directory contains more C++ code meant to run on the roboRIO. HAL is an acronym for "Hardware Abstraction Layer", and it interfaces with the NI Libraries. The NI Libraries contain the low-level code for controlling devices on your robot. The NI Libraries are found in the ni-libraries folder.
The upstream_utils directory contains scripts for updating copies of thirdparty code in the repository.
The [styleguide repository](https://github.com/wpilibsuite/styleguide) contains our style guides for C++ and Java code. Anything submitted to the WPILib project needs to follow the code style guides outlined in there. For details about the style, please see the contributors document [here](CONTRIBUTING.md#coding-guidelines).
A C++ wrapper around the [University of Michigan's AprilTag detector](https://github.com/AprilRobotics/apriltag), alongside a vendored copy of their code with some patches (patches are located in [upstream_utils](../upstream_utils/apriltag_patches/)).
## Adding new field to AprilTagFields
### Adding field JSON
1. Add a field layout CSV file to `src/main/native/resources/org/wpilib/vision/apriltag`
1. See docstring in `convert_apriltag_layouts.py` for more
2. Run `convert_apriltag_layouts.py` in the same directory as this readme to generate the JSON
3. That script overwrites all generated JSONs, so undo undesired changes if necessary
4. Update the field dimensions at the bottom of the JSON
1. Length should be in meters from alliance wall to alliance wall
2. Width should be in meters from inside guardrail plastic to plastic
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.