Squashed 'third_party/allwpilib/' changes from 66b57f032..e473a00f9
e473a00f9 [wpiutil] Base64: Add unsigned span/vector variants (#3702)
52f2d580e [wpiutil] raw_uv_ostream: Add reset() (#3701)
d7b1e3576 [wpiutil] WebSocket: move std::function (#3700)
93799fbe9 [examples] Fix description of TrapezoidProfileSubsystem (#3699)
b84644740 [wpimath] Document pose estimator states, inputs, and outputs (#3698)
2dc35c139 [wpimath] Fix classpaths for JNI class loads (#3697)
2cb171f6f [docs] Set Doxygen extract_all to true and fix Doxygen failures (#3695)
a939cd9c8 [wpimath] Print uncontrollable/unobservable models in LQR and KF (#3694)
d5270d113 [wpimath] Clean up C++ StateSpaceUtil tests (#3692)
b20903960 [wpimath] Remove redundant discretization tests from StateSpaceUtilTest (#3689)
c0cb545b4 [wpilibc] Add deprecated Doxygen attribute to SpeedController (#3691)
35c9f66a7 [wpilib] Rename PneumaticsHub to PneumaticHub (#3686)
796d03d10 [wpiutil] Remove unused LLVM header (#3688)
8723caf78 [wpilibj] Make Java TrapezoidProfile.Constraints an immutable class (#3687)
187f50a34 [wpimath] Catch incorrect parameters to state-space models earlier (#3680)
8d04606c4 Replace instances of frc-characterization with SysId (NFC) (#3681)
b82d4f6e5 [hal, cscore, ntcore] Use WPI common handle type base
87e34967e [wpiutil] Add synchronization primitives
e32499c54 [wpiutil] Add ParallelTcpConnector (#3655)
aa0b49228 [wpilib] Remove redundant "quick turn" docs for curvature drive (NFC) (#3674)
57301a7f9 [hal] REVPH: Start closed-loop compressor control on init (#3673)
d1842ea8f [wpilib] Improve interrupt docs (NFC) (#3679)
558151061 [wpiutil] Add DsClient (#3654)
181723e57 Replace `.to<double>()` and `.template to<double>()` with `.value()` (#3667)
6bc1db44b [commands] Add pointer overload of AddRequirements (artf6003) (#3669)
737b57ed5 [wpimath] Update to drake v0.35.0 (#3665)
4d287d1ae [build] Upgrade WPIJREArtifact to JRE 2022-11.0.12u5 (#3666)
f26eb5ada [hal] Fix another typo (get -> gets) (NFC) (#3663)
94ed275ba [hal] Fix misspelling (numer -> number) (NFC) (#3662)
ac2f44da3 [wpiutil] uv: use move for std::function (#3653)
75fa1fbfb [wpiutil] json::serializer: Optimize construction (#3647)
5e689faea [wpiutil] Import MessagePack implementation (mpack) (#3650)
649a50b40 [wpiutil] Add LEB128 byte-by-byte reader (#3652)
e94397a97 [wpiutil] Move json_serializer.h to public headers (#3646)
4ec58724d [wpiutil] uv::Tcp: Clarify SetNoDelay documentation (#3649)
8cb294aa4 [wpiutil] WebSocket: Make Shutdown() public (#3651)
2b3a9a52b [wpiutil] json: Fix map iterator key() for std::string_view (#3645)
138cbb94b [wpiutil] uv::Async: Add direct call for no-parameter specialization (#3648)
e56d6dea8 [ci] Update testbench pool image to ubuntu-latest (#3643)
43f30e44e [build] Enable comments in doxygen source files (#3644)
9e6db17ef [build] Enable doxygen preprocessor expansion of WPI_DEPRECATED (#3642)
0e631ad2f Add WPILib version to issue template (#3641)
6229d8d2f [build] Docs: set case_sense_names to false (#3392)
4647d09b5 [docs] Fix Doxygen warnings, add CI docs lint job (#3639)
4ad3a5402 [hal] Fix PWM allocation channel (#3637)
05e5feac4 [docs] Fix brownout docs (NFC) (#3638)
67df469c5 [examples] Remove old command-based templates and examples (#3263)
689e9ccfb [hal, wpilib] Add brownout voltage configuration (#3632)
9cd4bc407 [docs] Add useLocal to avoid using installer artifacts (#3634)
61996c2bb [cscore] Fix Java direct callback notifications (#3631)
6d3dd99eb [build] Update to newest native-utils (#3633)
f0b484892 [wpiutil] Fix StringMap iterator equality check (#3629)
8352cbb7a Update development build instructions for 2022 (#3616)
6da08b71d [examples] Fix Intermediate Vision Java Example description (#3628)
5d99059bf [wpiutil] Remove optional.h (#3627)
fa41b106a [glass, wpiutil] Add missing format args (#3626)
4e3fd7d42 [build] Enable Zc:__cplusplus for Windows (#3625)
791d8354d [build] Suppress deprecation/removal warnings for old commands (#3618)
10f19e6fc [hal, wpilib] Add REV PneumaticsHub (#3600)
4c61a1305 [ntcore] Revert to per-element copy for toNative() (#3621)
7b3f62244 [wpiutil] SendableRegistry: Print exception stacktrace (#3620)
d347928e4 [hal] Use better error for when console out is enabled while attempting to use onboard serial port (#3622)
cc31079a1 [hal] Use setcap instead of setuid for setting thread priorities (#3613)
4676648b7 [wpimath] Upgrade to Drake v0.34.0 (#3607)
c7594c911 [build] Allow building wpilibc in cmake without cscore and opencv (#3605)
173cb7359 [wpilib] Add TimesliceRobot (#3502)
af295879f [hal] Set error status for I2C port out of range (#3603)
95dd20a15 [build] Enable spotbugs (#3601)
b65fce86b [wpilib] Remove Timer lock in wpilibj and update docs (#3602)
3b8d3bbcb Remove unused and add missing deprecated.h includes (#3599)
f9e976467 [examples] Rename DriveTrain classes to Drivetrain (#3594)
118a27be2 [wpilib] Add Timer tests (#3595)
59c89428e [wpilib] Deprecate Timer::HasPeriodPassed() (#3598)
202ca5e78 Force C++17 in .clang-format (#3597)
d6f185d8e Rename tests for consistency (#3592)
54ca474db [ci] Enable asan and tsan in CI for tests that pass (#3591)
1ca383b23 Add Debouncer (#3590)
179fde3a7 [build] Update to 2022 native utils and gradle 7 (#3588)
50198ffcf [examples] Add Mechanism2d visualization to Elevator Sim (#3587)
a446c2559 [examples] Synchronize C++ and Java Mechanism2d examples (#3589)
a7fb83103 [ci] clang-tidy: Generate compilation commands DB with Gradle (#3585)
4f5e0c9f8 [examples] Update ArmSimulation example to use Mechanism2d (#3572)
8164b91dc [CI] Print CMake test output on failure (#3583)
4d5fca27e [wpilib] Impove Mechanism2D documentation (NFC) (#3584)
fe59e4b9f Make C++ test names more consistent (#3586)
5c8868549 [wpilibc] Fix C++ MechanisimRoot2D to use same NT entries as Java/Glass (#3582)
9359431ba [wpimath] Clean up Eigen usage
72716f51c [wpimath] Upgrade to Eigen 3.4
382deef75 [wpimath] Explicitly export wpimath symbols
161e21173 [ntcore] Match standard handle layout, only allow 16 instances (#3577)
263a24811 [wpimath] Use jinja for codegen (#3574)
725251d29 [wpilib] Increase tolerances of DifferentialDriveSimTest (#3581)
4dff87301 [wpimath] Make LinearFilter::Factorial() constexpr (#3579)
60ede67ab [hal, wpilib] Switch PCM to be a single object that is allowed to be duplicated (#3475)
906bfc846 [build] Add CMake build support for sanitizers (#3576)
0d4f08ad9 [hal] Simplify string copy of joystick name (#3575)
a52bf87b7 [wpiutil] Add Java function package (#3570)
40c7645d6 [wpiutil] UidVector: Return old object from erase() (#3571)
5b886a23f [wpiutil] jni_util: Add size, operator[] to JArrayRef (#3569)
65797caa7 [sim] Fix halsim_ds_socket stringop overflow warning from GCC 10 (#3568)
66abb3988 [hal] Update runtime enum to allow selecting roborio 2 (#3565)
95a12e0ee [hal] UidSetter: Don't revert euid if its already current value (#3566)
27951442b [wpimath] Use external Eigen headers only (#3564)
c42e053ae [docs] Update to doxygen 1.9.2 (#3562)
e7048c8c8 [docs] Disable doxygen linking for common words that are also classes (#3563)
d8e0b6c97 [wpilibj] Fix java async interrupts (#3559)
5e6c34c61 Update to 2022 roborio image (#3537)
828f073eb [wpiutil] Fix uv::Buffer memory leaks caught by asan (#3555)
2dd5701ac [cscore] Fix mutex use-after-free in cscore test (#3557)
531439198 [ntcore] Fix NetworkTables memory leaks caught by asan (#3556)
3d9a4d585 [wpilibc] Fix AnalogTriggerOutput memory leak reported by asan (#3554)
54eda5928 [wpiutil] Ignore ubsan vptr upcast warning in SendableHelper moves (#3553)
5a4f75c9f [wpilib] Replace Speed controller comments with motor controller (NFC) (#3551)
7810f665f [wpiutil] Fix bug in uleb128 (#3540)
697e2dd33 [wpilib] Fix errant jaguar reference in comments (NFC) (#3550)
936c64ff5 [docs] Enable -linksource for javadocs (#3549)
1ea654954 [build] Upgrade CMake build to googletest 1.11.0 (#3548)
32d9949e4 [wpimath] Move controller tests to wpimath (#3541)
01ba56a8a [hal] Replace strncpy with memcpy (#3539)
e109c4251 [build] Rename makeSim flag to forceGazebo to better describe what it does (#3535)
e4c709164 [docs] Use a doxygen theme and add logo (#3533)
960b6e589 [wpimath] Fix Javadoc warning (#3532)
82eef8d5e [hal] Remove over current fault HAL functions from REV PDH (#3526)
aa3848b2c [wpimath] Move RobotDriveBase::ApplyDeadband() to MathUtil (#3529)
3b5d0d141 [wpimath] Add LinearFilter::BackwardFiniteDifference() (#3528)
c8fc715fe [wpimath] Upgrade drake files to v0.33.0 (#3531)
e5fe3a8e1 [build] Treat javadoc warnings as errors in CI and fix warnings (#3530)
e0c6cd3dc [wpimath] Add an operator for composing two Transform2ds (#3527)
2edd510ab [sim] Add sim wrappers for sensors that use SimDevice (#3517)
2b3e2ebc1 [hal] Fix HAL Notifier thread priority setting (#3522)
ab4cb5932 [gitignore] Update gitignore to ignore bazel / clion files (#3524)
57c8615af [build] Generate spotless patch on failure (#3523)
b90317321 Replace std::cout and std::cerr with fmt::print() (#3519)
10cc8b89c [hal] [wpilib] Add initial support for the REV PDH (#3503)
5d9ae3cdb [hal] Set HAL Notifier thread as RT by default (#3482)
192d251ee [wpilibcIntegrationTests] Properly disable DMA integration tests (#3514)
031962608 [wpilib] Add PS4Controller, remove Hand from GenericHID/XboxController (#3345)
25f6f478a [wpilib] Rename DriverStation::IsOperatorControl() to IsTeleop() (#3505)
e80f09f84 [wpilibj] Add unit tests (#3501)
c159f91f0 [wpilib] Only read DS control word once in IterativeRobotBase (#3504)
eb790a74d Add rio development docs documenting myRobot deploy tasks (#3508)
e47451f5a [wpimath] Replace auto with Eigen types (#3511)
252b8c83b Remove Java formatting from build task in CI (#3507)
09666ff29 Shorten Gazebo CI build (#3506)
baf2e501d Update myRobot to use 2021 java (#3509)
5ac60f0a2 [wpilib] Remove IterativeRobotBase mode init prints (#3500)
fb2ee8ec3 [wpilib] Add TimedRobot functions for running code on mode exit (#3499)
94e0db796 [wpilibc] Add more unit tests (#3494)
b25324695 [wpilibj] Add units to parameter names (NFC) (#3497)
1ac73a247 [hal] Rename PowerDistributionPanel to PowerDistribution (#3466)
2014115bc [examples] frisbeebot: Fix typo and reflow comments (NFC) (#3498)
4a944dc39 [examples] Consistently use 0 for controller port (#3496)
3838cc4ec Use unicode characters in docs equations (#3487)
85748f2e6 [examples] Add C++ TankDrive example (#3493)
d7b8aa56d [wpilibj] Rename DriverStation In[Mode] functions to follow style guide (#3488)
16e096cf8 [build] Fix CMake Windows CI (#3490)
50af74c38 [wpimath] Clean up NumericalIntegration and add Discretization tests (#3489)
bfc209b12 Automate fmt update (#3486)
e7f9331e4 [build] Update to Doxygen 1.9.1 (#3008)
ab8e8aa2a [wpimath] Update drake with upstream (#3484)
1ef826d1d [wpimath] Fix IOException path in WPIMath JNI (#3485)
52bddaa97 [wpimath] Disable iostream support for units and enable fmtlib (#3481)
e4dc3908b [wpiutil] Upgrade to fmtlib 8.0.1 (#3483)
1daadb812 [wpimath] Implement Dormand-Prince integration method (#3476)
9c2723391 [cscore] Add [[nodiscard]] to GrabFrame functions (#3479)
7a8796414 [wpilib] Add Notifier integration tests (#3480)
f8f13c536 [wpilibcExamples] Prefix decimal numbers with 0 (#3478)
1adb69c0f [ntcore] Use "NetworkTables" instead of "Network Tables" in NT specs (#3477)
5f5830b96 Upload wpiformat diff if one exists (#3474)
9fb4f35bb [wpimath] Add tests for DARE overload with Q, R, and N matrices (#3472)
c002e6f92 Run wpiformat (#3473)
c154e5262 [wpilib] Make solenoids exclusive use, PCM act like old sendable compressor (#3464)
6ddef1cca [hal] JNI setDIO: use a boolean and not a short (#3469)
9d68d9582 Remove extra newlines after open curly braces (NFC) (#3471)
a4233e1a1 [wpimath] Add script for updating Drake (#3470)
39373c6d2 Update README.md for new GCC version requirement (#3467)
d29acc90a [wpigui] Add option to reset UI on exit (#3463)
a371235b0 [ntcore] Fix dangling pointer in logger (#3465)
53b4891a5 [wpilibcintegrationtests] Fix deprecated Preferences usage (#3461)
646ded912 [wpimath] Remove incorrect discretization in pose estimators (#3460)
ea0b8f48e Fix some deprecation warnings due to fmtlib upgrade (#3459)
2067d7e30 [wpilibjexamples] Add wpimathjni, wpiutiljni to library path (#3455)
866571ab4 [wpiutil] Upgrade to fmtlib 8.0.0 (#3457)
4e1fa0308 [build] Skip PDB copy on windows build servers (#3458)
b45572167 [build] Change CI back to 18.04 docker images (#3456)
57a160f1b [wpilibc] Fix LiveWindow deprecation warning in RobotBase skeleton template (#3454)
29ae8640d [HLT] Implement duty cycle cross connect tests (#3453)
ee6377e54 [HLT] Add relay and analog cross connects (#3452)
b0f1ae7ea [build] CMake: Build the HAL even if WITH_CSCORE=OFF (#3449)
7aae2b72d Replace std::to_string() with fmt::format() (#3451)
73fcbbd74 [HLT] Add relay digital cross connect tests (#3450)
e7bedde83 [HLT] Add PWM tests that use DMA as the back end (#3447)
7253edb1e [wpilibc] Timer: Fix deprecated warning (#3446)
efa28125c [wpilibc] Add message to RobotBase on how to read stacktrace (#3444)
9832fcfe1 [hal] Fix DIO direction getter (#3445)
49c71f9f2 [wpilibj] Clarify robot quit message (#3364)
791770cf6 [wpimath] Move controller from wpilibj to wpimath (#3439)
9ce9188ff [wpimath] Add ReportWarning to MathShared (#3441)
362066a9b [wpilib] Deprecate getInstance() in favor of static functions (#3440)
26ff9371d Initial commit of cross connect integration test project (#3434)
4a36f86c8 [hal] Add support for DMA to Java (#3158)
85144e47f [commands] Unbreak build (#3438)
b417d961e Split Sendable into NT and non-NT portions (#3432)
ef4ea84cb [commands] Change grouping decorator impl to flatten nested group structures (#3335)
b422665a3 [examples] Invert right side of drive subsystems (#3437)
186dadf14 [hal] Error if attempting to set DIO output on an input port (#3436)
04e64db94 Remove redundant C++ lambda parentheses (NFC) (#3433)
f60994ad2 [wpiutil] Rename Java package to edu.wpi.first.util (#3431)
cfa1ca96f [wpilibc] Make ShuffleboardValue non-copyable (#3430)
4d9ff7643 Fix documentation warnings generated by JavaDoc (NFC) (#3428)
9e1b7e046 [build] Fix clang-tidy and clang-format (#3429)
a77c6ff3a [build] Upgrade clang-format and clang-tidy (NFC) (#3422)
099fde97d [wpilib] Improve PDP comments (NFC) (#3427)
f8fc2463e [wpilibc, wpiutil] Clean up includes (NFC) (#3426)
e246b7884 [wpimath] Clean up member initialization in feedforward classes (#3425)
c1e128bd5 Disable frivolous PMD warnings and enable PMD in ntcore (#3419)
8284075ee Run "Lint and Format" CI job on push as well as pull request (#3412)
f7db09a12 [wpimath] Move C++ filters into filter folder to match Java (#3417)
f9c3d54bd [wpimath] Reset error covariance in pose estimator ResetPosition() (#3418)
0773f4033 [hal] Ensure HAL status variables are initialized to zero (#3421)
d068fb321 [build] Upgrade CI to use 20.04 docker images (#3420)
8d054c940 [wpiutil] Remove STLExtras.h
80f1d7921 [wpiutil] Split function_ref to a separate header
64f541325 Use wpi::span instead of wpi::ArrayRef across all libraries (#3414)
2abbbd9e7 [build] clang-tidy: Remove bugprone-exception-escape (#3415)
a5c471af7 [wpimath] Add LQR template specialization for 2x2 system
edd2f0232 [wpimath] Add DARE solver for Q, R, and N with LQR ctor overloads
b2c3b2dd8 Use std::string_view and fmtlib across all libraries (#3402)
4f1cecb8e [wpiutil] Remove Path.h (#3413)
b336eac34 [build] Publish halsim_ws_core to Maven
2a09f6fa4 [build] Also build sim modules as static libraries
0e702eb79 [hal] Add a unified PCM object (#3331)
dea841103 [wpimath] Add fmtlib formatter overloads for Eigen::Matrix and units (#3409)
82856cf81 [wpiutil] Improve wpi::circular_buffer iterators (#3410)
8aecda03e [wpilib] Fix a documentation typo (#3408)
5c817082a [wpilib] Remove InterruptableSensorBase and replace with interrupt classes (#2410)
15c521a7f [wpimath] Fix drivetrain system identification (#3406)
989de4a1b [build] Force all linker warnings to be fatal for rio builds (#3407)
d9eeb45b0 [wpilibc] Add units to Ultrasonic class API (#3403)
fe570e000 [wpiutil] Replace llvm filesystem with C++17 filesystem (#3401)
01dc0249d [wpimath] Move SlewRateLimiter from wpilib to wpimath (#3399)
93523d572 [wpilibc] Clean up integration tests (#3400)
4f7a4464d [wpiutil] Rewrite StringExtras for std::string_view (#3394)
e09293a15 [wpilibc] Transition C++ classes to units::second_t (#3396)
827b17a52 [build] Create run tasks for Glass and OutlineViewer (#3397)
a61037996 [wpiutil] Avoid MSVC warning on span include (#3393)
4e2c3051b [wpilibc] Use std::string_view instead of Twine (#3380)
50915cb7e [wpilibc] MotorSafety::GetDescription(): Return std::string (#3390)
f4e2d26d5 [wpilibc] Move NullDeleter from frc/Base.h to wpi/NullDeleter.h (#3387)
cb0051ae6 [wpilibc] SimDeviceSim: use fmtlib (#3389)
a238cec12 [wpiutil] Deprecate wpi::math constants in favor of wpi::numbers (#3383)
393bf23c0 [ntcore, cscore, wpiutil] Standardize template impl files on .inc extension (NFC) (#3124)
e7d9ba135 [sim] Disable flaky web server integration tests (#3388)
0a0003c11 [wpilibjExamples] Fix name of Java swerve drive pose estimator example (#3382)
7e1b27554 [wpilibc] Use default copies and moves when possible (#3381)
fb2a56e2d [wpilibc] Remove START_ROBOT_CLASS macro (#3384)
84218bfb4 [wpilibc] Remove frc namespace shim (#3385)
dd7824340 [wpilibc] Remove C++ compiler version static asserts (#3386)
484cf9c0e [wpimath] Suppress the -Wmaybe-uninitialized warning in Eigen (#3378)
a04d1b4f9 [wpilibc] DriverStation: Remove ReportError and ReportWarning
831c10bdf [wpilibc] Errors: Use fmtlib
87603e400 [wpiutil] Import fmtlib (#3375)
442621672 [wpiutil] Add ArrayRef/std::span/wpi::span implicit conversions
bc15b953b [wpiutil] Add std::span implementation
6d20b1204 [wpiutil] StringRef, Twine, raw_ostream: Add std::string_view support (#3373)
2385c2a43 [wpilibc] Remove Utility.h (#3376)
87384ea68 [wpilib] Fix PIDController continuous range error calculations (#3170)
04dae799a [wpimath] Add SimpleMotorFeedforward::Calculate(velocity, nextVelocity) overload (#3183)
0768c3903 [wpilib] DifferentialDrive: Remove right side inversion (#3340)
8dd8d4d2d [wpimath] Fix redundant nested math package introduced by #3316 (#3368)
49b06beed [examples] Add Field2d to RamseteController example (#3371)
4c562a445 [wpimath] Fix typo in comment of update_eigen.py (#3369)
fdbbf1188 [wpimath] Add script for updating Eigen
f1e64b349 [wpimath] Move Eigen unsupported folder into eigeninclude
224f3a05c [sim] Fix build error when building with GCC 11.1 (#3361)
ff56d6861 [wpilibj] Fix SpeedController deprecated warnings (#3360)
1873fbefb [examples] Fix Swerve and Mecanum examples (#3359)
80b479e50 [examples] Fix SwerveBot example to use unique encoder ports (#3358)
1f7c9adee [wpilibjExamples] Fix pose estimator examples (#3356)
9ebc3b058 [outlineviewer] Change default size to 600x400 (#3353)
e21b443a4 [build] Gradle: Make C++ examples runnable (#3348)
da590120c [wpilibj] Add MotorController.setVoltage default (#3347)
561d53885 [build] Update opencv to 4.5.2, imgui/implot to latest (#3344)
44ad67ca8 [wpilibj] Preferences: Add missing Deprecated annotation (#3343)
3fe8fc75a [wpilibc] Revert "Return reference from GetInstance" (#3342)
3cc2da332 Merge branch '2022'
a3cd90dd7 [wpimath] Fix classpath used by generate_numbers.py (#3339)
d6cfdd3ba [wpilib] Preferences: Deprecate Put* in favor of Set* (#3337)
ba08baabb [wpimath] Update Drake DARE solver to v0.29.0 (#3336)
497b712f6 [wpilib] Make IterativeRobotBase::m_period private with getter
f00dfed7a [wpilib] Remove IterativeRobot base class
3c0846168 [hal] Use last error reporting instead of PARAMETER_OUT_OF_RANGE (#3328)
5ef2b4fdc [wpilibj] Fix @deprecated warning for SerialPort constructor (#3329)
23d2326d1 [hal] Report previous allocation location for indexed resource duplicates (#3322)
e338f9f19 [build] Fix wpilibc runCpp task (#3327)
c8ff626fe [wpimath] Move Java classes to edu.wpi.first.math (#3316)
4e424d51f [wpilibj] DifferentialDrivetrainSim: Rename constants to match the style guide (#3312)
6b50323b0 [cscore] Use Lock2DSize if possible for Windows USB cameras (#3326)
65c148536 [wpilibc] Fix "control reaches end of non-void function" warning (#3324)
f99f62bee [wpiutil] uv Handle: Use malloc/free instead of new/delete (#3325)
365f5449c [wpimath] Fix MecanumDriveKinematics (#3266)
ff52f207c [glass, wpilib] Rewrite Mechanism2d (#3281)
ee0eed143 [wpimath] Add DCMotor factory function for Romi motors (#3319)
512738072 [hal] Add HAL_GetLastError to enable better error messages from HAL calls (#3320)
ced654880 [glass, outlineviewer] Update Mac icons to macOS 11 style (#3313)
936d3b9f8 [templates] Add Java template for educational robot (#3309)
6e31230ad [examples] Fix odometry update in SwerveControllerCommand example (#3310)
05ebe9318 Merge branch 'main' into 2022
aaf24e255 [wpilib] Fix initial heading behavior in HolonomicDriveController (#3290)
8d961dfd2 [wpilibc] Remove ErrorBase (#3306)
659b37ef9 [wpiutil] StackTrace: Include offset on Linux (#3305)
0abf6c904 [wpilib] Move motor controllers to motorcontrol package (#3302)
4630191fa [wpiutil] circular_buffer: Use value initialization instead of passing zero (#3303)
b7b178f49 [wpilib] Remove Potentiometer interface
687066af3 [wpilib] Remove GyroBase
6b168ab0c [wpilib] Remove PIDController, PIDOutput, PIDSource
948625de9 [wpimath] Document conversion from filter cutoff frequency to time constant (#3299)
3848eb8b1 [wpilibc] Fix flywhel -> flywheel typo in FlywheelSim (#3298)
3abe0b9d4 [cscore] Move java package to edu.wpi.first.cscore (#3294)
d7fabe81f [wpilib] Remove RobotDrive (#3295)
1dc81669c [wpilib] Remove GearTooth (#3293)
01d0e1260 [wpilib] Revert move of RomiGyro into main wpilibc/j (#3296)
397e569aa [ntcore] Remove "using wpi" from nt namespace
79267f9e6 [ntcore] Remove NetworkTable -> nt::NetworkTable shim
48ebe5736 [ntcore] Remove deprecated Java interfaces and classes
c2064c78b [ntcore] Remove deprecated ITable interfaces
36608a283 [ntcore] Remove deprecated C++ APIs
a1c87e1e1 [glass] LogView: Add "copy to clipboard" button (#3274)
fa7240a50 [wpimath] Fix typo in quintic spline basis matrix
ffb4d38e2 [wpimath] Add derivation for spline basis matrices
f57c188f2 [wpilib] Add AnalogEncoder(int) ctor (#3273)
8471c4fb2 [wpilib] FieldObject2d: Add setTrajectory() method (#3277)
c97acd18e [glass] Field2d enhancements (#3234)
ffb590bfc [wpilib] Fix Compressor sendable properties (#3269)
6137f98eb [hal] Rename SimValueCallback2 to SimValueCallback (#3212)
a6f653969 [hal] Move registerSimPeriodic functions to HAL package (#3211)
10c038d9b [glass] Plot: Fix window creation after removal (#3264)
2d2eaa3ef [wpigui] Ensure window will be initially visible (#3256)
4d28b1f0c [wpimath] Use JNI for trajectory serialization (#3257)
3de800a60 [wpimath] TrajectoryUtil.h: Comment formatting (NFC) (#3262)
eff592377 [glass] Plot: Don't overwrite series ID (#3260)
a79faace1 [wpilibc] Return reference from GetInstance (#3247)
9550777b9 [wpilib] PWMSpeedController: Use PWM by composition (#3248)
c8521a3c3 [glass] Plot: Set reasonable default window size (#3261)
d71eb2cf3 [glass] Plot: Show full source name as tooltip and in popup (#3255)
160fb740f [hal] Use std::lround() instead of adding 0.5 and truncating (#3012)
48e9f3951 [wpilibj] Remove wpilibj package CameraServer (#3213)
8afa596fd [wpilib] Remove deprecated Sendable functions and SendableBase (#3210)
d3e45c297 [wpimath] Make C++ geometry classes immutable (#3249)
2c98939c1 [glass] StringChooser: Don't call SameLine() at end
a18a7409f [glass] NTStringChooser: Clear value of deleted entries
2f19cf452 [glass] NetworkTablesHelper: listen to delete events
da96707dc Merge branch 'main' into 2022
c3a8bdc24 [build] Fix clang-tidy action (#3246)
21624ef27 Add ImGui OutlineViewer (#3220)
1032c9b91 [wpiutil] Unbreak wpi::Format on Windows (#3242)
2e07902d7 [glass] NTField2D: Fix name lookup (#3233)
6e23e1840 [wpilibc] Remove WPILib.h (#3235)
3e22e4506 [wpilib] Make KoP drivetrain simulation weight 60 lbs (#3228)
79d1bd6c8 [glass] NetworkTablesSetting: Allow disable of server option (#3227)
fe341a16f [examples] Use more logical elevator setpoints in GearsBot (#3198)
62abf46b3 [glass] NetworkTablesSettings: Don't block GUI (#3226)
a95a5e0d9 [glass] Move NetworkTablesSettings to libglassnt (#3224)
d6f6ceaba [build] Run Spotless formatter (NFC) (#3221)
0922f8af5 [commands] CommandScheduler.requiring(): Note return can be null (NFC) (#2934)
6812302ff [examples] Make DriveDistanceOffboard example work in sim (#3199)
f3f86b8e7 [wpimath] Add pose estimator overload for vision + std dev measurement (#3200)
1a2680b9e [wpilibj] Change CommandBase.withName() to return CommandBase (#3209)
435bbb6a8 [command] RamseteCommand: Output 0 if interrupted (#3216)
3cf44e0a5 [hal] Add function for changing HAL Notifier thread priority (#3218)
40b367513 [wpimath] Units.java: Add kg-lb conversions (#3203)
9f563d584 [glass] NT: Fix return value in StringToDoubleArray (#3208)
af4adf537 [glass] Auto-size plots to fit window (#3193)
2560146da [sim] GUI: Add option to show prefix in Other Devices (#3186)
eae3a6397 gitignore: Ignore .cache directory (#3196)
959611420 [wpilib] Require non-zero positive value for PIDController.period (#3175)
9522f2e8c [wpimath] Add methods to concatenate trajectories (#3139)
e42a0b6cf [wpimath] Rotation2d comment formatting (NFC) (#3162)
d1c7032de [wpimath] Fix order of setting gyro offset in pose estimators (#3176)
d241bc81a [sim] Add DoubleSolenoidSim and SolenoidSim classes (#3177)
cb7f39afa [wpilibc] Add RobotController::GetBatteryVoltage() to C++ (#3179)
99b5ad9eb [wpilibj] Fix warnings that are not unused variables or deprecation (#3161)
c14b23775 [build] Fixup doxygen generated include dirs to match what users would need (#3154)
d447c7dc3 [sim] Add SimDeviceSim ctor overloads (#3134)
247420c9c [build] Remove jcenter repo (#3157)
04b112e00 [build] Include debug info in plugin published artifacts (#3149)
be0ce9900 [examples] Use PWMSparkMax instead of PWMVictorSPX (#3156)
69e8d0b65 [wpilib] Move RomiGyro into main wpilibc/j (#3143)
94e685e1b [wpimath] Add custom residual support to EKF (#3148)
5899f3dd2 [sim] GUI: Make keyboard settings loading more robust (#3167)
f82aa1d56 [wpilib] Fix HolonomicDriveController atReference() behavior (#3163)
fe5c2cf4b [wpimath] Remove ControllerUtil.java (#3169)
43d40c6e9 [wpiutil] Suppress unchecked cast in CombinedRuntimeLoader (#3155)
3d44d8f79 [wpimath] Fix argument order in UKF docs (NFC) (#3147)
ba6fe8ff2 [cscore] Add USB camera change event (#3123)
533725888 [build] Tweak OpenCV cmake search paths to work better on Linux (#3144)
29bf9d6ef [cscore] Add polled support to listener
483beb636 [ntcore] Move CallbackManager to wpiutil
fdaec7759 [examples] Instantiate m_ramseteController in example (#3142)
8494a5761 Rename default branch to main (#3140)
45590eea2 [wpigui] Hardcode window scale to 1 on macOS (#3135)
834a64920 [build] Publish libglass and libglassnt to Maven (#3127)
2c2ccb361 [wpimath] Fix Rotation2d equality operator (#3128)
fb5c8c39a [wpigui] clang-tidy: readability-braces-around-statements
f7d39193a [wpigui] Fix copyright in pfd and wpigui_metal.mm
aec796b21 [ntcore] Fix conditional jump on uninitialized value (#3125)
fb13bb239 [sim] GUI: Add right click popup for keyboard joystick settings (#3119)
c517ec677 [build] Update thirdparty-imgui to 1.79-2 (#3118)
e8cbf2a71 [wpimath] Fix typo in SwerveDrivePoseEstimator doc (NFC) (#3112)
e9c86df46 [wpimath] Add tests for swerve module optimization (#3100)
6ba8c289c [examples] Remove negative of ArcadeDrive(fwd, ..) in the C++ Getting Started Example (#3102)
3f1672e89 [hal] Add SimDevice createInt() and createLong() (#3110)
15be5cbf1 [examples] Fix segfault in GearsBot C++ example (#3111)
4cf0e5e6d Add quick links to API documentation in README (#3082)
6b1898f12 Fix RT priority docs (NFC) (#3098)
b3426e9c0 [wpimath] Fix missing whitespace in pose estimator doc (#3097)
38c1a1f3e [examples] Fix feildRelative -> fieldRelative typo in XControllerCommand examples (#3104)
4488e25f1 [glass] Shorten SmartDashboard window names (#3096)
cfdb3058e [wpilibj] Update SimDeviceSimTest (#3095)
64adff5fe [examples] Fix typo in ArcadeDrive constructor parameter name (#3092)
6efc58e3d [build] Fix issues with build on windows, deprecations, and native utils (#3090)
f393989a5 [wpimath, wpiutil] Add wpi::array for compile time size checking (#3087)
d6ed20c1e [build] Set macOS deployment target to 10.14 (#3088)
7c524014c [hal] Add [[nodiscard]] to HAL_WaitForNotifierAlarm() (#3085)
406d055f0 [wpilib] Fixup wouldHitLowerLimit in elevator and arm simulation classes. (#3076)
04a90b5dd [examples] Don't continually set setpoint in PotentiometerPID Examples (#3084)
8c5bfa013 [sim] GUI: Add max value setting for keyboard joysticks (#3083)
bc80c5535 [hal] Add SimValue reset() function (#3064)
9c3b51ca0 [wpilib] Document simulation APIs (#3079)
26584ff14 [wpimath] Add model description to LinearSystemId Javadocs (#3080)
42c3d5286 [examples] Sync Java and C++ trajectories in sim example (#3081)
64e72f710 [wpilibc] Add missing function RoboRioSim::ResetData (#3073)
e95503798 [wpimath] Add optimize() to SwerveModuleState (#3065)
fb99910c2 [hal] Add SimInt and SimLong wrappers for int/long SimValue (#3066)
e620bd4d3 [doc] Add machine-readable websocket specification (#3059)
a44e761d9 [glass] Add support for plot Y axis labels
ea1974d57 [wpigui] Update imgui and implot to latest
85a0bd43c [wpimath] Add RKF45 integration (#3047)
278e0f126 [glass] Use .controllable to set widgets' read-only state (#3035)
d8652cfd4 [wpimath] Make Java DCMotor API consistent with C++ and fix motor calcs (#3046)
377b7065a [build] Add toggleOffOn to Java spotless (#3053)
1e9c79c58 [sim] Use plant output to retrieve simulated position (#3043)
78147aa34 [sim] GUI: Fix Keyboard Joystick (#3052)
cd4a2265b [ntcore] Fix NetworkTableEntry::GetRaw() (#3051)
767ac1de1 [build] Use deploy key for doc publish (#3048)
d762215d1 [build] Add publish documentation script (#3040)
1fd09593c [examples] Add missing TestInit method to GettingStarted Example (#3039)
e45a0f6ce [examples] Add RomiGyro to the Romi Reference example (#3037)
94f852572 Update imaging link and fix typo (#3038)
d73cf64e5 [examples] Update RomiReference to match motor directions (#3036)
f945462ba Bump copyright year to 2021 (#3033)
b05946175 [wpimath] Catch Drake JNI exceptions and rethrow them (#3032)
62f0f8190 [wpimath] Deduplicate angle modulus functions (#2998)
bf8c0da4b [glass] Add "About" popup with version number (#3031)
dfdd6b389 [build] Increase Gradle heap size in Gazebo build (#3028)
f5e0fc3e9 Finish clang-tidy cleanups (#3003)
d741101fe [sim] Revert accidental commit of WSProvider_PDP.h (#3027)
e1620799c [examples] Add C++ RomiReference example (#2969)
749c7adb1 [command] Fix use-after-free in CommandScheduler (#3024)
921a73391 [sim] Add WS providers for AddressableLED, PCM, and Solenoid (#3026)
26d0004fe [build] Split Actions into different yml files (#3025)
948af6d5b [wpilib] PWMSpeedController.get(): Apply Inversion (#3016)
670a187a3 [wpilibc] SuppliedValueWidget.h: Forward declare ShuffleboardContainer (#3021)
be9f72502 [ntcore] NetworkTableValue: Use std::forward instead of std::move (#3022)
daf3f4cb1 [cscore] cscore_raw_cv.h: Fix error in PutFrame() (#3019)
5acda4cc7 [wpimath] ElevatorFeedforward.h: Add time.h include
8452af606 [wpimath] units/radiation.h: Add mass.h include
630d44952 [hal] ErrorsInternal.h: Add stdint.h include
7372cf7d9 [cscore] Windows NetworkUtil.cpp: Add missing include
b7e46c558 Include .h from .inc/.inl files (NFC) (#3017)
bf8f8710e [examples] Update Romi template and example (#2996)
6ffe5b775 [glass] Ensure NetworkTableTree parent context menu has an id (#3015)
be0805b85 [build] Update to WPILibVersioningPlugin 4.1.0 (#3014)
65b2359b2 [build] Add spotless for other files (#3007)
8651aa73e [examples] Enable NT Flush in Field2d examples (#3013)
78b542737 [build] Add Gazebo build to Actions CI (#3004)
fccf86532 [sim] DriverStationGui: Fix two bugs (#3010)
185741760 [sim] WSProvider_Joystick: Fix off-by-1 in incoming buttons (#3011)
ee7114a58 [glass] Add drive class widgets (#2975)
00fa91d0d [glass] Use ImGui style for gyro widget colors (#3009)
b7a25bfc3 ThirdPartyNotices: Add portable file dialogs license (#3005)
a2e46b9a1 [glass] modernize-use-nullptr (NFC) (#3006)
a751fa22d [build] Apply spotless for java formatting (#1768)
e563a0b7d [wpimath] Make LinearSystemLoop move-constructible and move-assignable (#2967)
49085ca94 [glass] Add context menus to remove and add NetworkTables values (#2979)
560a850a2 [glass] Add NetworkTables Log window (#2997)
66782e231 [sim] Create Left/Right drivetrain current accessors (#3001)
b60eb1544 clang-tidy: bugprone-virtual-near-miss
cbe59fa3b clang-tidy: google-explicit-constructor
c97c6dc06 clang-tidy: google-readability-casting (NFC)
32fa97d68 clang-tidy: modernize-use-nullptr (NFC)
aee460326 clang-tidy: modernize-pass-by-value
29c7da5f1 clang-tidy: modernize-make-unique
6131f4e32 clang-tidy: modernize-concat-nested-namespaces (NFC)
67e03e625 clang-tidy: modernize-use-equals-default
b124f9101 clang-tidy: modernize-use-default-member-init
d11a3a638 clang-tidy: modernize-use-override (NFC)
4cc0706b0 clang-tidy: modernize-use-using (NFC)
885f5a978 [wpilibc] Speed up ScopedTracerTest (#2999)
60b596457 [wpilibj] Fix typos (NFC) (#3000)
6e1919414 [build] Bring naming checkstyle rules up to date with Google Style guide (#1781)
8c8ec5e63 [wpilibj] Suppress unchecked cast warnings (#2995)
b8413ddd5 [wpiutil] Add noexcept to timestamp static functions (#2994)
5d976b6e1 [glass] Load NetworkTableView settings on first draw (#2993)
2b4317452 Replace NOLINT(runtime/explicit) comments with NOLINT (NFC) (#2992)
1c3011ba4 [glass] Fix handling of "/" NetworkTables key (#2991)
574a42f3b [hal] Fix UnsafeManipulateDIO status check (#2987)
9005cd59e [wpilib] Clamp input voltage in sim classes (#2955)
dd494d4ab [glass] NetworkTablesModel::Update(): Avoid use-after-move (#2988)
7cca469a1 [wpimath] NormalizeAngle: Make inline, remove unnamed namespace (#2986)
2aed432b4 Add braces to C++ single-line loops and conditionals (NFC) (#2973)
0291a3ff5 [wpiutil] StringRef: Add noexcept to several constructors (#2984)
5d7315280 [wpimath] Update UnitsTest.cpp copyright (#2985)
254931b9a [wpimath] Remove LinearSystem from LinearSystemLoop (#2968)
aa89744c9 Update OtherVersions.md to include wpimath info (#2983)
1cda3f5ad [glass] Fix styleguide (#2976)
8f1f64ffb Remove year from file copyright message (NFC) (#2972)
2bc0a7795 [examples] Fix wpiformat warning about utility include (#2971)
4204da6ad [glass] Add application icon
7ac39b10f [wpigui] Add icon support
6b567e006 [wpimath] Add support for varying vision standard deviations in pose estimators (#2956)
df299d6ed [wpimath] Add UnscentedKalmanFilter::Correct() overload (#2966)
4e34f0523 [examples] Use ADXRS450_GyroSim class in simulation example (#2964)
9962f6fd7 [wpilib] Give Field2d a default Sendable name (#2953)
f9d492f4b [sim] GUI: Show "Other Devices" window by default (#2961)
a8bb2ef1c [sim] Fix ADXRS450_GyroSim and DutyCycleEncoderSim (#2963)
240c629cd [sim] Try to guess "Map Gamepad" setting (#2960)
952567dd3 [wpilibc] Add missing move constructors and assignment operators (#2959)
10b396b4c [sim] Various WebSockets fixes and enhancements (#2952)
699bbe21a [examples] Fix comments in Gearsbot to match implementation (NFC) (#2957)
27b67deca [glass] Add more widgets (#2947)
581b7ec55 [wpilib] Add option to flush NetworkTables every iterative loop
acfbb1a44 [ntcore] DispatcherBase::Flush: Use wpi::Now()
d85a6d8fe [ntcore] Reduce limit on flush and update rate to 5 ms
20fbb5c63 [sim] Fix stringop truncation warning from GCC 10 (#2945)
1051a06a7 [glass] Show NT timestamps in seconds (#2944)
98dfc2620 [glass] Fix plots (#2943)
1ba0a2ced [sim] GUI: Add keyboard virtual joystick support (#2940)
4afb13f98 [examples] Replace M_PI with wpi::math::pi (#2938)
b27d33675 [examples] Enhance Romi templates (#2931)
00b9ae77f [sim] Change default WS port number to 3300 (#2932)
65219f309 [examples] Update Field2d position in periodic() (#2928)
f78d1d434 [sim] Process WS Encoder reset internally (#2927)
941edca59 [hal] Add Java SimDeviceDataJNI.getSimDeviceName (#2924)
a699435ed [wpilibj] Fix FlywheelSim argument order in constructor (#2922)
66d641718 [examples] Add tasks to run Java examples (#2920)
558e37c41 [examples] Add simple differential drive simulation example (#2918)
4f40d991e [glass] Switch name of Glass back to glass (#2919)
549af9900 [build] Update native-utils to 2021.0.6 (#2914)
b33693009 [glass] Change basename of glass to Glass (#2915)
c9a0edfb8 [glass] Package macOS application bundle
2c5668af4 [wpigui] Add platform-specific preferences save
751dea32a [wpilibc] Try to work around ABI break introduced in #2901 (#2917)
cd8f4bfb1 [build] Package up msvc runtime into maven artifact (#2913)
a6cfcc686 [wpilibc] Move SendableChooser Doxygen comments to header (NFC) (#2911)
b8c4f603d [wpimath] Upgrade to Eigen 3.3.9 (#2910)
0075e4b39 [wpilibj] Fix NPE in Field2d (#2909)
125af556c [simulation] Fix halsim_gui ntcore and wpiutil deps (#2908)
963ad5c25 [wpilib] Add noise to Differential Drive simulator (#2903)
387f56cb7 [examples] Add Romi reference Java example and templates (#2905)
b3deda38c [examples] Zero motors on disabledInit() in sim physics examples (#2906)
2a5ca7745 [glass] Add glass: an application for display of robot data
727940d84 [wpilib] Move Field2d to SmartDashboard
8cd42478e [wpilib] SendableBuilder: Make GetTable() visible
c11d34b26 [command] Use addCommands in command group templates (#2900)
339d7445b [sim] Add HAL hooks for simulationPeriodic (#2881)
d16f05f2c [wpilib] Fix SmartDashboard update order (#2896)
5427b32a4 [wpiutil] unique_function: Restrict implicit conversion (#2899)
f73701239 [ntcore] Add missing SetDefault initializer_list functions (#2898)
f5a6fc070 [sim] Add initialized flag for all solenoids on a PCM (#2897)
bdf5ba91a [wpilibj] Fix typo in ElevatorSim (#2895)
bc8f33877 [wpilib] Add pose estimators (#2867)
3413bfc06 [wpilib] PIDController: Recompute the error in AtSetpoint() (#2822)
2056f0ce0 [wpilib] Fix bugs in Hatchbot examples (#2893)
5eb8cfd69 [wpilibc] Fix MatchDataSender (#2892)
e6a425448 [build] Delete test folders after tests execute (#2891)
d478ad00d [imgui] Allow usage of imgui_stdlib (#2889)
53eda861d [build] Add unit-testing infrastructure to examples (#2863)
cc1d86ba6 [sim] Add title to simulator GUI window (#2888)
f0528f00e [build] CMake: Use project-specific binary and source dirs (#2886)
5cd2ad124 [wpilibc] Add Color::operator!= (#2887)
6c00e7a90 [build] CI CMake: build with GUI enabled (#2884)
53170bbb5 Update roboRIO toolchain installation instructions (#2883)
467258e05 [sim] GUI: Add option to not zero disconnected joysticks (#2876)
129be23c9 Clarify JDK installation instructions in readme (#2882)
8e9290e86 [build] Add separate CMake setting for wpimath (#2885)
7cf5bebf8 [wpilibj] Cache NT writes from DriverStation (#2780)
f7f9087fb [command] Fix timing issue in RamseteCommand (#2871)
256e7904f [wpilibj] SimDeviceSim: Fix sim value changed callback (#2880)
c8ea1b6c3 [wpilib] Add function to adjust LQR controller gain for pure time delay (#2878)
2816b06c0 [sim] HAL_GetControlWord: Fully zero output (#2873)
4c695ea08 Add toolchain installation instructions to README (#2875)
a14d51806 [wpimath] DCMotor: fix doc typo (NFC) (#2868)
017097791 [build] CMake: build sim extensions as shared libs (#2866)
f61726b5a [build] Fix cmake-config files (#2865)
fc27fdac5 [wpilibc] Cache NT values from driver station (#2768)
47c59859e [sim] Make SimDevice callbacks synchronous (#2861)
6e76ab9c0 [build] Turn on WITH_GUI for Windows cmake CI
5f78b7670 [build] Set GLFW_INSTALL to OFF
5e0808c84 [wpigui] Fix Windows cmake build
508f05a47 [imgui] Fix typo in Windows CMake target sources
Change-Id: I1737b45965f31803a96676bedc7dc40e337aa321
git-subtree-dir: third_party/allwpilib
git-subtree-split: e473a00f9785f9949e5ced30901baeaf426d2fc9
Signed-off-by: Austin Schuh <austin.linux@gmail.com>
diff --git a/wpilibc/src/dev/native/cpp/main.cpp b/wpilibc/src/dev/native/cpp/main.cpp
index f1370bb..28fac9d 100644
--- a/wpilibc/src/dev/native/cpp/main.cpp
+++ b/wpilibc/src/dev/native/cpp/main.cpp
@@ -1,19 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
-#include <iostream>
-
+#include <fmt/core.h>
#include <hal/HALBase.h>
#include "WPILibVersion.h"
int main() {
- std::cout << "Hello World" << std::endl;
- std::cout << HAL_GetRuntimeType() << std::endl;
- std::cout << GetWPILibVersion() << std::endl;
- return 0;
+ fmt::print("Hello World\n");
+ fmt::print("{}\n", HAL_GetRuntimeType());
+ fmt::print("{}\n", GetWPILibVersion());
}
diff --git a/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp b/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp
index aff0802..484e690 100644
--- a/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp
+++ b/wpilibc/src/main/native/cpp/ADXL345_I2C.cpp
@@ -1,28 +1,25 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/ADXL345_I2C.h"
#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <networktables/NTSendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
using namespace frc;
ADXL345_I2C::ADXL345_I2C(I2C::Port port, Range range, int deviceAddress)
: m_i2c(port, deviceAddress),
- m_simDevice("ADXL345_I2C", port, deviceAddress) {
+ m_simDevice("Accel:ADXL345_I2C", port, deviceAddress) {
if (m_simDevice) {
- m_simRange =
- m_simDevice.CreateEnum("Range", true, {"2G", "4G", "8G", "16G"}, 0);
- m_simX = m_simDevice.CreateDouble("X Accel", false, 0.0);
- m_simY = m_simDevice.CreateDouble("Y Accel", false, 0.0);
- m_simZ = m_simDevice.CreateDouble("Z Accel", false, 0.0);
+ m_simRange = m_simDevice.CreateEnumDouble("range", hal::SimDevice::kOutput,
+ {"2G", "4G", "8G", "16G"},
+ {2.0, 4.0, 8.0, 16.0}, 0);
+ m_simX = m_simDevice.CreateDouble("x", hal::SimDevice::kInput, 0.0);
+ m_simY = m_simDevice.CreateDouble("y", hal::SimDevice::kInput, 0.0);
+ m_simZ = m_simDevice.CreateDouble("z", hal::SimDevice::kInput, 0.0);
}
// Turn on the measurements
m_i2c.Write(kPowerCtlRegister, kPowerCtl_Measure);
@@ -32,7 +29,15 @@
HAL_Report(HALUsageReporting::kResourceType_ADXL345,
HALUsageReporting::kADXL345_I2C, 0);
- SendableRegistry::GetInstance().AddLW(this, "ADXL345_I2C", port);
+ wpi::SendableRegistry::AddLW(this, "ADXL345_I2C", port);
+}
+
+I2C::Port ADXL345_I2C::GetI2CPort() const {
+ return m_i2c.GetPort();
+}
+
+int ADXL345_I2C::GetI2CDeviceAddress() const {
+ return m_i2c.GetDeviceAddress();
}
void ADXL345_I2C::SetRange(Range range) {
@@ -40,16 +45,28 @@
kDataFormat_FullRes | static_cast<uint8_t>(range));
}
-double ADXL345_I2C::GetX() { return GetAcceleration(kAxis_X); }
+double ADXL345_I2C::GetX() {
+ return GetAcceleration(kAxis_X);
+}
-double ADXL345_I2C::GetY() { return GetAcceleration(kAxis_Y); }
+double ADXL345_I2C::GetY() {
+ return GetAcceleration(kAxis_Y);
+}
-double ADXL345_I2C::GetZ() { return GetAcceleration(kAxis_Z); }
+double ADXL345_I2C::GetZ() {
+ return GetAcceleration(kAxis_Z);
+}
double ADXL345_I2C::GetAcceleration(ADXL345_I2C::Axes axis) {
- if (axis == kAxis_X && m_simX) return m_simX.Get();
- if (axis == kAxis_Y && m_simY) return m_simY.Get();
- if (axis == kAxis_Z && m_simZ) return m_simZ.Get();
+ if (axis == kAxis_X && m_simX) {
+ return m_simX.Get();
+ }
+ if (axis == kAxis_Y && m_simY) {
+ return m_simY.Get();
+ }
+ if (axis == kAxis_Z && m_simZ) {
+ return m_simZ.Get();
+ }
int16_t rawAccel = 0;
m_i2c.Read(kDataRegister + static_cast<int>(axis), sizeof(rawAccel),
reinterpret_cast<uint8_t*>(&rawAccel));
@@ -74,12 +91,12 @@
return data;
}
-void ADXL345_I2C::InitSendable(SendableBuilder& builder) {
+void ADXL345_I2C::InitSendable(nt::NTSendableBuilder& builder) {
builder.SetSmartDashboardType("3AxisAccelerometer");
auto x = builder.GetEntry("X").GetHandle();
auto y = builder.GetEntry("Y").GetHandle();
auto z = builder.GetEntry("Z").GetHandle();
- builder.SetUpdateTable([=]() {
+ builder.SetUpdateTable([=] {
auto data = GetAccelerations();
nt::NetworkTableEntry(x).SetDouble(data.XAxis);
nt::NetworkTableEntry(y).SetDouble(data.YAxis);
diff --git a/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp b/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp
index 329b148..9a95bcc 100644
--- a/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp
+++ b/wpilibc/src/main/native/cpp/ADXL345_SPI.cpp
@@ -1,27 +1,24 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/ADXL345_SPI.h"
#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <networktables/NTSendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
using namespace frc;
ADXL345_SPI::ADXL345_SPI(SPI::Port port, ADXL345_SPI::Range range)
- : m_spi(port), m_simDevice("ADXL345_SPI", port) {
+ : m_spi(port), m_simDevice("Accel:ADXL345_SPI", port) {
if (m_simDevice) {
- m_simRange =
- m_simDevice.CreateEnum("Range", true, {"2G", "4G", "8G", "16G"}, 0);
- m_simX = m_simDevice.CreateDouble("X Accel", false, 0.0);
- m_simY = m_simDevice.CreateDouble("Y Accel", false, 0.0);
- m_simZ = m_simDevice.CreateDouble("Z Accel", false, 0.0);
+ m_simRange = m_simDevice.CreateEnumDouble("range", hal::SimDevice::kOutput,
+ {"2G", "4G", "8G", "16G"},
+ {2.0, 4.0, 8.0, 16.0}, 0);
+ m_simX = m_simDevice.CreateDouble("x", hal::SimDevice::kInput, 0.0);
+ m_simY = m_simDevice.CreateDouble("y", hal::SimDevice::kInput, 0.0);
+ m_simZ = m_simDevice.CreateDouble("z", hal::SimDevice::kInput, 0.0);
}
m_spi.SetClockRate(500000);
m_spi.SetMSBFirst();
@@ -40,7 +37,11 @@
HAL_Report(HALUsageReporting::kResourceType_ADXL345,
HALUsageReporting::kADXL345_SPI);
- SendableRegistry::GetInstance().AddLW(this, "ADXL345_SPI", port);
+ wpi::SendableRegistry::AddLW(this, "ADXL345_SPI", port);
+}
+
+SPI::Port ADXL345_SPI::GetSpiPort() const {
+ return m_spi.GetPort();
}
void ADXL345_SPI::SetRange(Range range) {
@@ -51,19 +52,33 @@
commands[1] = kDataFormat_FullRes | static_cast<uint8_t>(range & 0x03);
m_spi.Transaction(commands, commands, 2);
- if (m_simRange) m_simRange.Set(range);
+ if (m_simRange) {
+ m_simRange.Set(range);
+ }
}
-double ADXL345_SPI::GetX() { return GetAcceleration(kAxis_X); }
+double ADXL345_SPI::GetX() {
+ return GetAcceleration(kAxis_X);
+}
-double ADXL345_SPI::GetY() { return GetAcceleration(kAxis_Y); }
+double ADXL345_SPI::GetY() {
+ return GetAcceleration(kAxis_Y);
+}
-double ADXL345_SPI::GetZ() { return GetAcceleration(kAxis_Z); }
+double ADXL345_SPI::GetZ() {
+ return GetAcceleration(kAxis_Z);
+}
double ADXL345_SPI::GetAcceleration(ADXL345_SPI::Axes axis) {
- if (axis == kAxis_X && m_simX) return m_simX.Get();
- if (axis == kAxis_Y && m_simY) return m_simY.Get();
- if (axis == kAxis_Z && m_simZ) return m_simZ.Get();
+ if (axis == kAxis_X && m_simX) {
+ return m_simX.Get();
+ }
+ if (axis == kAxis_Y && m_simY) {
+ return m_simY.Get();
+ }
+ if (axis == kAxis_Z && m_simZ) {
+ return m_simZ.Get();
+ }
uint8_t buffer[3];
uint8_t command[3] = {0, 0, 0};
command[0] = (kAddress_Read | kAddress_MultiByte | kDataRegister) +
@@ -103,12 +118,12 @@
return data;
}
-void ADXL345_SPI::InitSendable(SendableBuilder& builder) {
+void ADXL345_SPI::InitSendable(nt::NTSendableBuilder& builder) {
builder.SetSmartDashboardType("3AxisAccelerometer");
auto x = builder.GetEntry("X").GetHandle();
auto y = builder.GetEntry("Y").GetHandle();
auto z = builder.GetEntry("Z").GetHandle();
- builder.SetUpdateTable([=]() {
+ builder.SetUpdateTable([=] {
auto data = GetAccelerations();
nt::NetworkTableEntry(x).SetDouble(data.XAxis);
nt::NetworkTableEntry(y).SetDouble(data.YAxis);
diff --git a/wpilibc/src/main/native/cpp/ADXL362.cpp b/wpilibc/src/main/native/cpp/ADXL362.cpp
index aff572f..deda965 100644
--- a/wpilibc/src/main/native/cpp/ADXL362.cpp
+++ b/wpilibc/src/main/native/cpp/ADXL362.cpp
@@ -1,17 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/ADXL362.h"
#include <hal/FRCUsageReporting.h>
+#include <networktables/NTSendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/DriverStation.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -35,13 +32,14 @@
ADXL362::ADXL362(Range range) : ADXL362(SPI::Port::kOnboardCS1, range) {}
ADXL362::ADXL362(SPI::Port port, Range range)
- : m_spi(port), m_simDevice("ADXL362", port) {
+ : m_spi(port), m_simDevice("Accel:ADXL362", port) {
if (m_simDevice) {
- m_simRange =
- m_simDevice.CreateEnum("Range", true, {"2G", "4G", "8G", "16G"}, 0);
- m_simX = m_simDevice.CreateDouble("X Accel", false, 0.0);
- m_simY = m_simDevice.CreateDouble("Y Accel", false, 0.0);
- m_simZ = m_simDevice.CreateDouble("Z Accel", false, 0.0);
+ m_simRange = m_simDevice.CreateEnumDouble("range", hal::SimDevice::kOutput,
+ {"2G", "4G", "8G", "16G"},
+ {2.0, 4.0, 8.0, 16.0}, 0);
+ m_simX = m_simDevice.CreateDouble("x", hal::SimDevice::kInput, 0.0);
+ m_simY = m_simDevice.CreateDouble("y", hal::SimDevice::kInput, 0.0);
+ m_simZ = m_simDevice.CreateDouble("z", hal::SimDevice::kInput, 0.0);
}
m_spi.SetClockRate(3000000);
@@ -58,7 +56,7 @@
commands[2] = 0;
m_spi.Transaction(commands, commands, 3);
if (commands[2] != 0xF2) {
- DriverStation::ReportError("could not find ADXL362");
+ FRC_ReportError(err::Error, "{}", "could not find ADXL362");
m_gsPerLSB = 0.0;
return;
}
@@ -74,11 +72,17 @@
HAL_Report(HALUsageReporting::kResourceType_ADXL362, port + 1);
- SendableRegistry::GetInstance().AddLW(this, "ADXL362", port);
+ wpi::SendableRegistry::AddLW(this, "ADXL362", port);
+}
+
+SPI::Port ADXL362::GetSpiPort() const {
+ return m_spi.GetPort();
}
void ADXL362::SetRange(Range range) {
- if (m_gsPerLSB == 0.0) return;
+ if (m_gsPerLSB == 0.0) {
+ return;
+ }
uint8_t commands[3];
@@ -102,21 +106,37 @@
kFilterCtl_ODR_100Hz | static_cast<uint8_t>((range & 0x03) << 6);
m_spi.Write(commands, 3);
- if (m_simRange) m_simRange.Set(range);
+ if (m_simRange) {
+ m_simRange.Set(range);
+ }
}
-double ADXL362::GetX() { return GetAcceleration(kAxis_X); }
+double ADXL362::GetX() {
+ return GetAcceleration(kAxis_X);
+}
-double ADXL362::GetY() { return GetAcceleration(kAxis_Y); }
+double ADXL362::GetY() {
+ return GetAcceleration(kAxis_Y);
+}
-double ADXL362::GetZ() { return GetAcceleration(kAxis_Z); }
+double ADXL362::GetZ() {
+ return GetAcceleration(kAxis_Z);
+}
double ADXL362::GetAcceleration(ADXL362::Axes axis) {
- if (m_gsPerLSB == 0.0) return 0.0;
+ if (m_gsPerLSB == 0.0) {
+ return 0.0;
+ }
- if (axis == kAxis_X && m_simX) return m_simX.Get();
- if (axis == kAxis_Y && m_simY) return m_simY.Get();
- if (axis == kAxis_Z && m_simZ) return m_simZ.Get();
+ if (axis == kAxis_X && m_simX) {
+ return m_simX.Get();
+ }
+ if (axis == kAxis_Y && m_simY) {
+ return m_simY.Get();
+ }
+ if (axis == kAxis_Z && m_simZ) {
+ return m_simZ.Get();
+ }
uint8_t buffer[4];
uint8_t command[4] = {0, 0, 0, 0};
@@ -162,12 +182,12 @@
return data;
}
-void ADXL362::InitSendable(SendableBuilder& builder) {
+void ADXL362::InitSendable(nt::NTSendableBuilder& builder) {
builder.SetSmartDashboardType("3AxisAccelerometer");
auto x = builder.GetEntry("X").GetHandle();
auto y = builder.GetEntry("Y").GetHandle();
auto z = builder.GetEntry("Z").GetHandle();
- builder.SetUpdateTable([=]() {
+ builder.SetUpdateTable([=] {
auto data = GetAccelerations();
nt::NetworkTableEntry(x).SetDouble(data.XAxis);
nt::NetworkTableEntry(y).SetDouble(data.YAxis);
diff --git a/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp b/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp
index 8ea5b41..5a2f625 100644
--- a/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp
+++ b/wpilibc/src/main/native/cpp/ADXRS450_Gyro.cpp
@@ -1,22 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/ADXRS450_Gyro.h"
#include <hal/FRCUsageReporting.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/DriverStation.h"
+#include "frc/Errors.h"
#include "frc/Timer.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
-static constexpr auto kSamplePeriod = 0.0005_s;
-static constexpr double kCalibrationSampleTime = 5.0;
+static constexpr auto kSamplePeriod = 0.5_ms;
+static constexpr auto kCalibrationSampleTime = 5_s;
static constexpr double kDegreePerSecondPerLSB = 0.0125;
// static constexpr int kRateRegister = 0x00;
@@ -32,10 +30,11 @@
ADXRS450_Gyro::ADXRS450_Gyro() : ADXRS450_Gyro(SPI::kOnboardCS0) {}
ADXRS450_Gyro::ADXRS450_Gyro(SPI::Port port)
- : m_spi(port), m_port(port), m_simDevice("ADXRS450_Gyro", port) {
+ : m_spi(port), m_port(port), m_simDevice("Gyro:ADXRS450", port) {
if (m_simDevice) {
- m_simAngle = m_simDevice.CreateDouble("Angle", false, 0.0);
- m_simRate = m_simDevice.CreateDouble("Rate", false, 0.0);
+ m_simAngle =
+ m_simDevice.CreateDouble("angle_x", hal::SimDevice::kInput, 0.0);
+ m_simRate = m_simDevice.CreateDouble("rate_x", hal::SimDevice::kInput, 0.0);
}
m_spi.SetClockRate(3000000);
@@ -47,7 +46,7 @@
if (!m_simDevice) {
// Validate the part ID
if ((ReadRegister(kPIDRegister) & 0xff00) != 0x5200) {
- DriverStation::ReportError("could not find ADXRS450 gyro");
+ FRC_ReportError(err::Error, "{}", "could not find ADXRS450 gyro");
return;
}
@@ -59,7 +58,7 @@
HAL_Report(HALUsageReporting::kResourceType_ADXRS450, port + 1);
- SendableRegistry::GetInstance().AddLW(this, "ADXRS450_Gyro", port);
+ wpi::SendableRegistry::AddLW(this, "ADXRS450_Gyro", port);
}
static bool CalcParity(int v) {
@@ -81,7 +80,9 @@
uint16_t ADXRS450_Gyro::ReadRegister(int reg) {
int cmd = 0x80000000 | static_cast<int>(reg) << 17;
- if (!CalcParity(cmd)) cmd |= 1u;
+ if (!CalcParity(cmd)) {
+ cmd |= 1u;
+ }
// big endian
uint8_t buf[4] = {static_cast<uint8_t>((cmd >> 24) & 0xff),
@@ -91,29 +92,36 @@
m_spi.Write(buf, 4);
m_spi.Read(false, buf, 4);
- if ((buf[0] & 0xe0) == 0) return 0; // error, return 0
+ if ((buf[0] & 0xe0) == 0) {
+ return 0; // error, return 0
+ }
return static_cast<uint16_t>((BytesToIntBE(buf) >> 5) & 0xffff);
}
double ADXRS450_Gyro::GetAngle() const {
- if (m_simAngle) return m_simAngle.Get();
+ if (m_simAngle) {
+ return m_simAngle.Get();
+ }
return m_spi.GetAccumulatorIntegratedValue() * kDegreePerSecondPerLSB;
}
double ADXRS450_Gyro::GetRate() const {
- if (m_simRate) return m_simRate.Get();
+ if (m_simRate) {
+ return m_simRate.Get();
+ }
return static_cast<double>(m_spi.GetAccumulatorLastValue()) *
kDegreePerSecondPerLSB;
}
void ADXRS450_Gyro::Reset() {
- if (m_simAngle) m_simAngle.Set(0.0);
- if (m_simRate) m_simRate.Set(0.0);
+ if (m_simAngle) {
+ m_simAngle.Reset();
+ }
m_spi.ResetAccumulator();
}
void ADXRS450_Gyro::Calibrate() {
- Wait(0.1);
+ Wait(100_ms);
m_spi.SetAccumulatorIntegratedCenter(0);
m_spi.ResetAccumulator();
@@ -124,4 +132,12 @@
m_spi.ResetAccumulator();
}
-int ADXRS450_Gyro::GetPort() const { return m_port; }
+int ADXRS450_Gyro::GetPort() const {
+ return m_port;
+}
+
+void ADXRS450_Gyro::InitSendable(wpi::SendableBuilder& builder) {
+ builder.SetSmartDashboardType("Gyro");
+ builder.AddDoubleProperty(
+ "Value", [=] { return GetAngle(); }, nullptr);
+}
diff --git a/wpilibc/src/main/native/cpp/AddressableLED.cpp b/wpilibc/src/main/native/cpp/AddressableLED.cpp
index 81adc7b..759c386 100644
--- a/wpilibc/src/main/native/cpp/AddressableLED.cpp
+++ b/wpilibc/src/main/native/cpp/AddressableLED.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AddressableLED.h"
@@ -12,22 +9,25 @@
#include <hal/HALBase.h>
#include <hal/PWM.h>
#include <hal/Ports.h>
+#include <wpi/StackTrace.h>
-#include "frc/WPIErrors.h"
+#include "frc/Errors.h"
using namespace frc;
-AddressableLED::AddressableLED(int port) {
+AddressableLED::AddressableLED(int port) : m_port{port} {
int32_t status = 0;
- m_pwmHandle = HAL_InitializePWMPort(HAL_GetPort(port), &status);
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumPWMChannels(), port);
+ auto stack = wpi::GetStackTrace(1);
+ m_pwmHandle =
+ HAL_InitializePWMPort(HAL_GetPort(port), stack.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Port {}", port);
if (m_pwmHandle == HAL_kInvalidHandle) {
return;
}
m_handle = HAL_InitializeAddressableLED(m_pwmHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", port);
if (m_handle == HAL_kInvalidHandle) {
HAL_FreePWMPort(m_pwmHandle, &status);
}
@@ -39,29 +39,30 @@
HAL_FreeAddressableLED(m_handle);
int32_t status = 0;
HAL_FreePWMPort(m_pwmHandle, &status);
+ FRC_ReportError(status, "Port {}", m_port);
}
void AddressableLED::SetLength(int length) {
int32_t status = 0;
HAL_SetAddressableLEDLength(m_handle, length, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {} length {}", m_port, length);
}
static_assert(sizeof(AddressableLED::LEDData) == sizeof(HAL_AddressableLEDData),
"LED Structs MUST be the same size");
-void AddressableLED::SetData(wpi::ArrayRef<LEDData> ledData) {
+void AddressableLED::SetData(wpi::span<const LEDData> ledData) {
int32_t status = 0;
HAL_WriteAddressableLEDData(m_handle, ledData.begin(), ledData.size(),
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void AddressableLED::SetData(std::initializer_list<LEDData> ledData) {
int32_t status = 0;
HAL_WriteAddressableLEDData(m_handle, ledData.begin(), ledData.size(),
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void AddressableLED::SetBitTiming(units::nanosecond_t lowTime0,
@@ -72,25 +73,25 @@
HAL_SetAddressableLEDBitTiming(
m_handle, lowTime0.to<int32_t>(), highTime0.to<int32_t>(),
lowTime1.to<int32_t>(), highTime1.to<int32_t>(), &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void AddressableLED::SetSyncTime(units::microsecond_t syncTime) {
int32_t status = 0;
HAL_SetAddressableLEDSyncTime(m_handle, syncTime.to<int32_t>(), &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void AddressableLED::Start() {
int32_t status = 0;
HAL_StartAddressableLEDOutput(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void AddressableLED::Stop() {
int32_t status = 0;
HAL_StopAddressableLEDOutput(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void AddressableLED::LEDData::SetHSV(int h, int s, int v) {
diff --git a/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp b/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp
index 09bc2f5..0b39e64 100644
--- a/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogAccelerometer.cpp
@@ -1,42 +1,37 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogAccelerometer.h"
#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/Base.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
AnalogAccelerometer::AnalogAccelerometer(int channel)
: AnalogAccelerometer(std::make_shared<AnalogInput>(channel)) {
- SendableRegistry::GetInstance().AddChild(this, m_analogInput.get());
+ wpi::SendableRegistry::AddChild(this, m_analogInput.get());
}
AnalogAccelerometer::AnalogAccelerometer(AnalogInput* channel)
- : m_analogInput(channel, NullDeleter<AnalogInput>()) {
- if (channel == nullptr) {
- wpi_setWPIError(NullParameter);
- } else {
- InitAccelerometer();
+ : m_analogInput(channel, wpi::NullDeleter<AnalogInput>()) {
+ if (!channel) {
+ throw FRC_MakeError(err::NullParameter, "{}", "channel");
}
+ InitAccelerometer();
}
AnalogAccelerometer::AnalogAccelerometer(std::shared_ptr<AnalogInput> channel)
: m_analogInput(channel) {
- if (channel == nullptr) {
- wpi_setWPIError(NullParameter);
- } else {
- InitAccelerometer();
+ if (!channel) {
+ throw FRC_MakeError(err::NullParameter, "{}", "channel");
}
+ InitAccelerometer();
}
double AnalogAccelerometer::GetAcceleration() const {
@@ -47,20 +42,20 @@
m_voltsPerG = sensitivity;
}
-void AnalogAccelerometer::SetZero(double zero) { m_zeroGVoltage = zero; }
+void AnalogAccelerometer::SetZero(double zero) {
+ m_zeroGVoltage = zero;
+}
-double AnalogAccelerometer::PIDGet() { return GetAcceleration(); }
-
-void AnalogAccelerometer::InitSendable(SendableBuilder& builder) {
+void AnalogAccelerometer::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Accelerometer");
builder.AddDoubleProperty(
- "Value", [=]() { return GetAcceleration(); }, nullptr);
+ "Value", [=] { return GetAcceleration(); }, nullptr);
}
void AnalogAccelerometer::InitAccelerometer() {
HAL_Report(HALUsageReporting::kResourceType_Accelerometer,
m_analogInput->GetChannel() + 1);
- SendableRegistry::GetInstance().AddLW(this, "Accelerometer",
- m_analogInput->GetChannel());
+ wpi::SendableRegistry::AddLW(this, "Accelerometer",
+ m_analogInput->GetChannel());
}
diff --git a/wpilibc/src/main/native/cpp/AnalogEncoder.cpp b/wpilibc/src/main/native/cpp/AnalogEncoder.cpp
index c1f4e8d..5f26e87 100644
--- a/wpilibc/src/main/native/cpp/AnalogEncoder.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogEncoder.cpp
@@ -1,29 +1,30 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogEncoder.h"
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+
#include "frc/AnalogInput.h"
-#include "frc/Base.h"
#include "frc/Counter.h"
-#include "frc/DriverStation.h"
-#include "frc/smartdashboard/SendableBuilder.h"
+#include "frc/Errors.h"
using namespace frc;
+AnalogEncoder::AnalogEncoder(int channel)
+ : AnalogEncoder(std::make_shared<AnalogInput>(channel)) {}
+
AnalogEncoder::AnalogEncoder(AnalogInput& analogInput)
- : m_analogInput{&analogInput, NullDeleter<AnalogInput>{}},
+ : m_analogInput{&analogInput, wpi::NullDeleter<AnalogInput>{}},
m_analogTrigger{m_analogInput.get()},
m_counter{} {
Init();
}
AnalogEncoder::AnalogEncoder(AnalogInput* analogInput)
- : m_analogInput{analogInput, NullDeleter<AnalogInput>{}},
+ : m_analogInput{analogInput, wpi::NullDeleter<AnalogInput>{}},
m_analogTrigger{m_analogInput.get()},
m_counter{} {
Init();
@@ -49,12 +50,14 @@
m_counter.SetDownSource(
m_analogTrigger.CreateOutput(AnalogTriggerType::kFallingPulse));
- SendableRegistry::GetInstance().AddLW(this, "DutyCycle Encoder",
- m_analogInput->GetChannel());
+ wpi::SendableRegistry::AddLW(this, "DutyCycle Encoder",
+ m_analogInput->GetChannel());
}
units::turn_t AnalogEncoder::Get() const {
- if (m_simPosition) return units::turn_t{m_simPosition.Get()};
+ if (m_simPosition) {
+ return units::turn_t{m_simPosition.Get()};
+ }
// As the values are not atomic, keep trying until we get 2 reads of the same
// value If we don't within 10 attempts, error
@@ -70,13 +73,16 @@
}
}
- frc::DriverStation::GetInstance().ReportWarning(
+ FRC_ReportError(
+ warn::Warning, "{}",
"Failed to read Analog Encoder. Potential Speed Overrun. Returning last "
"value");
return m_lastPosition;
}
-double AnalogEncoder::GetPositionOffset() const { return m_positionOffset; }
+double AnalogEncoder::GetPositionOffset() const {
+ return m_positionOffset;
+}
void AnalogEncoder::SetDistancePerRotation(double distancePerRotation) {
m_distancePerRotation = distancePerRotation;
@@ -87,7 +93,7 @@
}
double AnalogEncoder::GetDistance() const {
- return Get().to<double>() * GetDistancePerRotation();
+ return Get().value() * GetDistancePerRotation();
}
void AnalogEncoder::Reset() {
@@ -95,9 +101,11 @@
m_positionOffset = m_analogInput->GetVoltage();
}
-int AnalogEncoder::GetChannel() const { return m_analogInput->GetChannel(); }
+int AnalogEncoder::GetChannel() const {
+ return m_analogInput->GetChannel();
+}
-void AnalogEncoder::InitSendable(SendableBuilder& builder) {
+void AnalogEncoder::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("AbsoluteEncoder");
builder.AddDoubleProperty(
"Distance", [this] { return this->GetDistance(); }, nullptr);
diff --git a/wpilibc/src/main/native/cpp/AnalogGyro.cpp b/wpilibc/src/main/native/cpp/AnalogGyro.cpp
index 2ec4439..106293b 100644
--- a/wpilibc/src/main/native/cpp/AnalogGyro.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogGyro.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogGyro.h"
@@ -13,89 +10,83 @@
#include <hal/AnalogGyro.h>
#include <hal/Errors.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
#include "frc/AnalogInput.h"
-#include "frc/Base.h"
+#include "frc/Errors.h"
#include "frc/Timer.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
AnalogGyro::AnalogGyro(int channel)
: AnalogGyro(std::make_shared<AnalogInput>(channel)) {
- SendableRegistry::GetInstance().AddChild(this, m_analog.get());
+ wpi::SendableRegistry::AddChild(this, m_analog.get());
}
AnalogGyro::AnalogGyro(AnalogInput* channel)
- : AnalogGyro(
- std::shared_ptr<AnalogInput>(channel, NullDeleter<AnalogInput>())) {}
+ : AnalogGyro(std::shared_ptr<AnalogInput>(
+ channel, wpi::NullDeleter<AnalogInput>())) {}
AnalogGyro::AnalogGyro(std::shared_ptr<AnalogInput> channel)
: m_analog(channel) {
- if (channel == nullptr) {
- wpi_setWPIError(NullParameter);
- } else {
- InitGyro();
- Calibrate();
+ if (!channel) {
+ throw FRC_MakeError(err::NullParameter, "{}", "channel");
}
+ InitGyro();
+ Calibrate();
}
AnalogGyro::AnalogGyro(int channel, int center, double offset)
: AnalogGyro(std::make_shared<AnalogInput>(channel), center, offset) {
- SendableRegistry::GetInstance().AddChild(this, m_analog.get());
+ wpi::SendableRegistry::AddChild(this, m_analog.get());
}
AnalogGyro::AnalogGyro(std::shared_ptr<AnalogInput> channel, int center,
double offset)
: m_analog(channel) {
- if (channel == nullptr) {
- wpi_setWPIError(NullParameter);
- } else {
- InitGyro();
- int32_t status = 0;
- HAL_SetAnalogGyroParameters(m_gyroHandle, kDefaultVoltsPerDegreePerSecond,
- offset, center, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_gyroHandle = HAL_kInvalidHandle;
- return;
- }
- Reset();
+ if (!channel) {
+ throw FRC_MakeError(err::NullParameter, "{}", "channel");
}
+ InitGyro();
+ int32_t status = 0;
+ HAL_SetAnalogGyroParameters(m_gyroHandle, kDefaultVoltsPerDegreePerSecond,
+ offset, center, &status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
+ Reset();
}
-AnalogGyro::~AnalogGyro() { HAL_FreeAnalogGyro(m_gyroHandle); }
+AnalogGyro::~AnalogGyro() {
+ HAL_FreeAnalogGyro(m_gyroHandle);
+}
double AnalogGyro::GetAngle() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double value = HAL_GetAnalogGyroAngle(m_gyroHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
return value;
}
double AnalogGyro::GetRate() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double value = HAL_GetAnalogGyroRate(m_gyroHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
return value;
}
int AnalogGyro::GetCenter() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int value = HAL_GetAnalogGyroCenter(m_gyroHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
return value;
}
double AnalogGyro::GetOffset() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double value = HAL_GetAnalogGyroOffset(m_gyroHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
return value;
}
@@ -103,65 +94,51 @@
int32_t status = 0;
HAL_SetAnalogGyroVoltsPerDegreePerSecond(m_gyroHandle,
voltsPerDegreePerSecond, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
}
void AnalogGyro::SetDeadband(double volts) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogGyroDeadband(m_gyroHandle, volts, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
}
void AnalogGyro::Reset() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_ResetAnalogGyro(m_gyroHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
}
void AnalogGyro::InitGyro() {
- if (StatusIsFatal()) return;
if (m_gyroHandle == HAL_kInvalidHandle) {
int32_t status = 0;
- m_gyroHandle = HAL_InitializeAnalogGyro(m_analog->m_port, &status);
- if (status == PARAMETER_OUT_OF_RANGE) {
- wpi_setWPIErrorWithContext(ParameterOutOfRange,
- " channel (must be accumulator channel)");
- m_analog = nullptr;
- m_gyroHandle = HAL_kInvalidHandle;
- return;
- }
- if (status != 0) {
- wpi_setHALError(status);
- m_analog = nullptr;
- m_gyroHandle = HAL_kInvalidHandle;
- return;
- }
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_gyroHandle =
+ HAL_InitializeAnalogGyro(m_analog->m_port, stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
}
int32_t status = 0;
HAL_SetupAnalogGyro(m_gyroHandle, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_analog = nullptr;
- m_gyroHandle = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
HAL_Report(HALUsageReporting::kResourceType_Gyro, m_analog->GetChannel() + 1);
- SendableRegistry::GetInstance().AddLW(this, "AnalogGyro",
- m_analog->GetChannel());
+ wpi::SendableRegistry::AddLW(this, "AnalogGyro", m_analog->GetChannel());
}
void AnalogGyro::Calibrate() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_CalibrateAnalogGyro(m_gyroHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_analog->GetChannel());
}
std::shared_ptr<AnalogInput> AnalogGyro::GetAnalogInput() const {
return m_analog;
}
+
+void AnalogGyro::InitSendable(wpi::SendableBuilder& builder) {
+ builder.SetSmartDashboardType("Gyro");
+ builder.AddDoubleProperty(
+ "Value", [=] { return GetAngle(); }, nullptr);
+}
diff --git a/wpilibc/src/main/native/cpp/AnalogInput.cpp b/wpilibc/src/main/native/cpp/AnalogInput.cpp
index 11c30ee..dfa5764 100644
--- a/wpilibc/src/main/native/cpp/AnalogInput.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogInput.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogInput.h"
@@ -12,222 +9,193 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
#include "frc/Timer.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
AnalogInput::AnalogInput(int channel) {
if (!SensorUtil::CheckAnalogInputChannel(channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "Analog Input " + wpi::Twine(channel));
- return;
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", channel);
}
m_channel = channel;
HAL_PortHandle port = HAL_GetPort(channel);
int32_t status = 0;
- m_port = HAL_InitializeAnalogInputPort(port, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumAnalogInputs(), channel);
- m_channel = std::numeric_limits<int>::max();
- m_port = HAL_kInvalidHandle;
- return;
- }
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_port = HAL_InitializeAnalogInputPort(port, stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
HAL_Report(HALUsageReporting::kResourceType_AnalogChannel, channel + 1);
- SendableRegistry::GetInstance().AddLW(this, "AnalogInput", channel);
+ wpi::SendableRegistry::AddLW(this, "AnalogInput", channel);
}
-AnalogInput::~AnalogInput() { HAL_FreeAnalogInputPort(m_port); }
+AnalogInput::~AnalogInput() {
+ HAL_FreeAnalogInputPort(m_port);
+}
int AnalogInput::GetValue() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int value = HAL_GetAnalogValue(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return value;
}
int AnalogInput::GetAverageValue() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int value = HAL_GetAnalogAverageValue(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return value;
}
double AnalogInput::GetVoltage() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double voltage = HAL_GetAnalogVoltage(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return voltage;
}
double AnalogInput::GetAverageVoltage() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double voltage = HAL_GetAnalogAverageVoltage(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return voltage;
}
int AnalogInput::GetChannel() const {
- if (StatusIsFatal()) return 0;
return m_channel;
}
void AnalogInput::SetAverageBits(int bits) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogAverageBits(m_port, bits, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
int AnalogInput::GetAverageBits() const {
int32_t status = 0;
int averageBits = HAL_GetAnalogAverageBits(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return averageBits;
}
void AnalogInput::SetOversampleBits(int bits) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogOversampleBits(m_port, bits, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
int AnalogInput::GetOversampleBits() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int oversampleBits = HAL_GetAnalogOversampleBits(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return oversampleBits;
}
int AnalogInput::GetLSBWeight() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int lsbWeight = HAL_GetAnalogLSBWeight(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return lsbWeight;
}
int AnalogInput::GetOffset() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int offset = HAL_GetAnalogOffset(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return offset;
}
bool AnalogInput::IsAccumulatorChannel() const {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool isAccum = HAL_IsAccumulatorChannel(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return isAccum;
}
void AnalogInput::InitAccumulator() {
- if (StatusIsFatal()) return;
m_accumulatorOffset = 0;
int32_t status = 0;
HAL_InitAccumulator(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void AnalogInput::SetAccumulatorInitialValue(int64_t initialValue) {
- if (StatusIsFatal()) return;
m_accumulatorOffset = initialValue;
}
void AnalogInput::ResetAccumulator() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_ResetAccumulator(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
- if (!StatusIsFatal()) {
- // Wait until the next sample, so the next call to GetAccumulator*()
- // won't have old values.
- const double sampleTime = 1.0 / GetSampleRate();
- const double overSamples = 1 << GetOversampleBits();
- const double averageSamples = 1 << GetAverageBits();
- Wait(sampleTime * overSamples * averageSamples);
- }
+ // Wait until the next sample, so the next call to GetAccumulator*()
+ // won't have old values.
+ const double sampleTime = 1.0 / GetSampleRate();
+ const double overSamples = 1 << GetOversampleBits();
+ const double averageSamples = 1 << GetAverageBits();
+ Wait(units::second_t{sampleTime * overSamples * averageSamples});
}
void AnalogInput::SetAccumulatorCenter(int center) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAccumulatorCenter(m_port, center, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void AnalogInput::SetAccumulatorDeadband(int deadband) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAccumulatorDeadband(m_port, deadband, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
int64_t AnalogInput::GetAccumulatorValue() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int64_t value = HAL_GetAccumulatorValue(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return value + m_accumulatorOffset;
}
int64_t AnalogInput::GetAccumulatorCount() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int64_t count = HAL_GetAccumulatorCount(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return count;
}
void AnalogInput::GetAccumulatorOutput(int64_t& value, int64_t& count) const {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_GetAccumulatorOutput(m_port, &value, &count, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
value += m_accumulatorOffset;
}
void AnalogInput::SetSampleRate(double samplesPerSecond) {
int32_t status = 0;
HAL_SetAnalogSampleRate(samplesPerSecond, &status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetSampleRate");
}
double AnalogInput::GetSampleRate() {
int32_t status = 0;
double sampleRate = HAL_GetAnalogSampleRate(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetSampleRate");
return sampleRate;
}
-double AnalogInput::PIDGet() {
- if (StatusIsFatal()) return 0.0;
- return GetAverageVoltage();
-}
-
void AnalogInput::SetSimDevice(HAL_SimDeviceHandle device) {
HAL_SetAnalogInputSimDevice(m_port, device);
}
-void AnalogInput::InitSendable(SendableBuilder& builder) {
+void AnalogInput::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Analog Input");
builder.AddDoubleProperty(
- "Value", [=]() { return GetAverageVoltage(); }, nullptr);
+ "Value", [=] { return GetAverageVoltage(); }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/AnalogOutput.cpp b/wpilibc/src/main/native/cpp/AnalogOutput.cpp
index bd8126a..a391271 100644
--- a/wpilibc/src/main/native/cpp/AnalogOutput.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogOutput.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogOutput.h"
@@ -14,62 +11,56 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
AnalogOutput::AnalogOutput(int channel) {
if (!SensorUtil::CheckAnalogOutputChannel(channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "analog output " + wpi::Twine(channel));
- m_channel = std::numeric_limits<int>::max();
- m_port = HAL_kInvalidHandle;
- return;
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", channel);
}
m_channel = channel;
HAL_PortHandle port = HAL_GetPort(m_channel);
int32_t status = 0;
- m_port = HAL_InitializeAnalogOutputPort(port, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumAnalogOutputs(), channel);
- m_channel = std::numeric_limits<int>::max();
- m_port = HAL_kInvalidHandle;
- return;
- }
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_port = HAL_InitializeAnalogOutputPort(port, stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
HAL_Report(HALUsageReporting::kResourceType_AnalogOutput, m_channel + 1);
- SendableRegistry::GetInstance().AddLW(this, "AnalogOutput", m_channel);
+ wpi::SendableRegistry::AddLW(this, "AnalogOutput", m_channel);
}
-AnalogOutput::~AnalogOutput() { HAL_FreeAnalogOutputPort(m_port); }
+AnalogOutput::~AnalogOutput() {
+ HAL_FreeAnalogOutputPort(m_port);
+}
void AnalogOutput::SetVoltage(double voltage) {
int32_t status = 0;
HAL_SetAnalogOutput(m_port, voltage, &status);
-
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
double AnalogOutput::GetVoltage() const {
int32_t status = 0;
double voltage = HAL_GetAnalogOutput(m_port, &status);
-
- wpi_setHALError(status);
-
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return voltage;
}
-int AnalogOutput::GetChannel() const { return m_channel; }
+int AnalogOutput::GetChannel() const {
+ return m_channel;
+}
-void AnalogOutput::InitSendable(SendableBuilder& builder) {
+void AnalogOutput::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Analog Output");
builder.AddDoubleProperty(
- "Value", [=]() { return GetVoltage(); },
+ "Value", [=] { return GetVoltage(); },
[=](double value) { SetVoltage(value); });
}
diff --git a/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp b/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp
index c7aedd6..ba94613 100644
--- a/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogPotentiometer.cpp
@@ -1,16 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogPotentiometer.h"
-#include "frc/Base.h"
+#include <utility>
+
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
#include "frc/RobotController.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -18,20 +18,22 @@
double offset)
: AnalogPotentiometer(std::make_shared<AnalogInput>(channel), fullRange,
offset) {
- SendableRegistry::GetInstance().AddChild(this, m_analog_input.get());
+ wpi::SendableRegistry::AddChild(this, m_analog_input.get());
}
AnalogPotentiometer::AnalogPotentiometer(AnalogInput* input, double fullRange,
double offset)
: AnalogPotentiometer(
- std::shared_ptr<AnalogInput>(input, NullDeleter<AnalogInput>()),
+ std::shared_ptr<AnalogInput>(input, wpi::NullDeleter<AnalogInput>()),
fullRange, offset) {}
AnalogPotentiometer::AnalogPotentiometer(std::shared_ptr<AnalogInput> input,
double fullRange, double offset)
- : m_analog_input(input), m_fullRange(fullRange), m_offset(offset) {
- SendableRegistry::GetInstance().AddLW(this, "AnalogPotentiometer",
- m_analog_input->GetChannel());
+ : m_analog_input(std::move(input)),
+ m_fullRange(fullRange),
+ m_offset(offset) {
+ wpi::SendableRegistry::AddLW(this, "AnalogPotentiometer",
+ m_analog_input->GetChannel());
}
double AnalogPotentiometer::Get() const {
@@ -41,10 +43,8 @@
m_offset;
}
-double AnalogPotentiometer::PIDGet() { return Get(); }
-
-void AnalogPotentiometer::InitSendable(SendableBuilder& builder) {
+void AnalogPotentiometer::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Analog Input");
builder.AddDoubleProperty(
- "Value", [=]() { return Get(); }, nullptr);
+ "Value", [=] { return Get(); }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/AnalogTrigger.cpp b/wpilibc/src/main/native/cpp/AnalogTrigger.cpp
index 45821ba..ea33c73 100644
--- a/wpilibc/src/main/native/cpp/AnalogTrigger.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogTrigger.cpp
@@ -1,156 +1,129 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogTrigger.h"
#include <utility>
+#include <hal/AnalogTrigger.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableRegistry.h>
#include "frc/AnalogInput.h"
-#include "frc/Base.h"
#include "frc/DutyCycle.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
AnalogTrigger::AnalogTrigger(int channel)
: AnalogTrigger(new AnalogInput(channel)) {
m_ownsAnalog = true;
- SendableRegistry::GetInstance().AddChild(this, m_analogInput);
+ wpi::SendableRegistry::AddChild(this, m_analogInput);
}
AnalogTrigger::AnalogTrigger(AnalogInput* input) {
m_analogInput = input;
int32_t status = 0;
m_trigger = HAL_InitializeAnalogTrigger(input->m_port, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_trigger = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "Channel {}", input->GetChannel());
int index = GetIndex();
HAL_Report(HALUsageReporting::kResourceType_AnalogTrigger, index + 1);
- SendableRegistry::GetInstance().AddLW(this, "AnalogTrigger", index);
+ wpi::SendableRegistry::AddLW(this, "AnalogTrigger", index);
}
AnalogTrigger::AnalogTrigger(DutyCycle* input) {
m_dutyCycle = input;
int32_t status = 0;
m_trigger = HAL_InitializeAnalogTriggerDutyCycle(input->m_handle, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_trigger = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "Channel {}", m_dutyCycle->GetSourceChannel());
int index = GetIndex();
HAL_Report(HALUsageReporting::kResourceType_AnalogTrigger, index + 1);
- SendableRegistry::GetInstance().AddLW(this, "AnalogTrigger", index);
+ wpi::SendableRegistry::AddLW(this, "AnalogTrigger", index);
}
AnalogTrigger::~AnalogTrigger() {
int32_t status = 0;
HAL_CleanAnalogTrigger(m_trigger, &status);
+ FRC_ReportError(status, "Channel {}", GetSourceChannel());
if (m_ownsAnalog) {
delete m_analogInput;
}
}
-AnalogTrigger::AnalogTrigger(AnalogTrigger&& rhs)
- : ErrorBase(std::move(rhs)),
- SendableHelper(std::move(rhs)),
- m_trigger(std::move(rhs.m_trigger)) {
- std::swap(m_analogInput, rhs.m_analogInput);
- std::swap(m_dutyCycle, rhs.m_dutyCycle);
- std::swap(m_ownsAnalog, rhs.m_ownsAnalog);
-}
-
-AnalogTrigger& AnalogTrigger::operator=(AnalogTrigger&& rhs) {
- ErrorBase::operator=(std::move(rhs));
- SendableHelper::operator=(std::move(rhs));
-
- m_trigger = std::move(rhs.m_trigger);
- std::swap(m_analogInput, rhs.m_analogInput);
- std::swap(m_dutyCycle, rhs.m_dutyCycle);
- std::swap(m_ownsAnalog, rhs.m_ownsAnalog);
-
- return *this;
-}
-
void AnalogTrigger::SetLimitsVoltage(double lower, double upper) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
}
void AnalogTrigger::SetLimitsDutyCycle(double lower, double upper) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerLimitsDutyCycle(m_trigger, lower, upper, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
}
void AnalogTrigger::SetLimitsRaw(int lower, int upper) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
}
void AnalogTrigger::SetAveraged(bool useAveragedValue) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerAveraged(m_trigger, useAveragedValue, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
}
void AnalogTrigger::SetFiltered(bool useFilteredValue) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetAnalogTriggerFiltered(m_trigger, useFilteredValue, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
}
int AnalogTrigger::GetIndex() const {
- if (StatusIsFatal()) return -1;
int32_t status = 0;
auto ret = HAL_GetAnalogTriggerFPGAIndex(m_trigger, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return ret;
}
bool AnalogTrigger::GetInWindow() {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool result = HAL_GetAnalogTriggerInWindow(m_trigger, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return result;
}
bool AnalogTrigger::GetTriggerState() {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool result = HAL_GetAnalogTriggerTriggerState(m_trigger, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return result;
}
std::shared_ptr<AnalogTriggerOutput> AnalogTrigger::CreateOutput(
AnalogTriggerType type) const {
- if (StatusIsFatal()) return nullptr;
return std::shared_ptr<AnalogTriggerOutput>(
- new AnalogTriggerOutput(*this, type), NullDeleter<AnalogTriggerOutput>());
+ new AnalogTriggerOutput(*this, type));
}
-void AnalogTrigger::InitSendable(SendableBuilder& builder) {
- if (m_ownsAnalog) m_analogInput->InitSendable(builder);
+void AnalogTrigger::InitSendable(wpi::SendableBuilder& builder) {
+ if (m_ownsAnalog) {
+ m_analogInput->InitSendable(builder);
+ }
+}
+
+int AnalogTrigger::GetSourceChannel() const {
+ if (m_analogInput) {
+ return m_analogInput->GetChannel();
+ } else if (m_dutyCycle) {
+ return m_dutyCycle->GetSourceChannel();
+ } else {
+ return -1;
+ }
}
diff --git a/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp b/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp
index 8fba479..93d1969 100644
--- a/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp
+++ b/wpilibc/src/main/native/cpp/AnalogTriggerOutput.cpp
@@ -1,16 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/AnalogTriggerOutput.h"
+#include <hal/AnalogTrigger.h>
#include <hal/FRCUsageReporting.h>
#include "frc/AnalogTrigger.h"
-#include "frc/WPIErrors.h"
+#include "frc/AnalogTriggerType.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -19,7 +18,7 @@
bool result = HAL_GetAnalogTriggerOutput(
m_trigger->m_trigger, static_cast<HAL_AnalogTriggerType>(m_outputType),
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Get");
return result;
}
@@ -31,11 +30,15 @@
return m_outputType;
}
-bool AnalogTriggerOutput::IsAnalogTrigger() const { return true; }
+bool AnalogTriggerOutput::IsAnalogTrigger() const {
+ return true;
+}
-int AnalogTriggerOutput::GetChannel() const { return m_trigger->GetIndex(); }
+int AnalogTriggerOutput::GetChannel() const {
+ return m_trigger->GetIndex();
+}
-void AnalogTriggerOutput::InitSendable(SendableBuilder&) {}
+void AnalogTriggerOutput::InitSendable(wpi::SendableBuilder&) {}
AnalogTriggerOutput::AnalogTriggerOutput(const AnalogTrigger& trigger,
AnalogTriggerType outputType)
diff --git a/wpilibc/src/main/native/cpp/AsynchronousInterrupt.cpp b/wpilibc/src/main/native/cpp/AsynchronousInterrupt.cpp
new file mode 100644
index 0000000..d45d5e4
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/AsynchronousInterrupt.cpp
@@ -0,0 +1,67 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/AsynchronousInterrupt.h"
+
+#include <frc/DigitalSource.h>
+
+using namespace frc;
+
+AsynchronousInterrupt::AsynchronousInterrupt(
+ DigitalSource& source, std::function<void(bool, bool)> callback)
+ : m_interrupt{source}, m_callback{std::move(callback)} {}
+AsynchronousInterrupt::AsynchronousInterrupt(
+ DigitalSource* source, std::function<void(bool, bool)> callback)
+ : m_interrupt{source}, m_callback{std::move(callback)} {}
+AsynchronousInterrupt::AsynchronousInterrupt(
+ std::shared_ptr<DigitalSource> source,
+ std::function<void(bool, bool)> callback)
+ : m_interrupt{source}, m_callback{std::move(callback)} {}
+
+AsynchronousInterrupt::~AsynchronousInterrupt() {
+ Disable();
+}
+
+void AsynchronousInterrupt::ThreadMain() {
+ while (m_keepRunning) {
+ auto result = m_interrupt.WaitForInterrupt(10_s, false);
+ if (!m_keepRunning) {
+ break;
+ }
+ if (result == SynchronousInterrupt::WaitResult::kTimeout) {
+ continue;
+ }
+ m_callback((result & SynchronousInterrupt::WaitResult::kRisingEdge) != 0,
+ (result & SynchronousInterrupt::WaitResult::kFallingEdge) != 0);
+ }
+}
+
+void AsynchronousInterrupt::Enable() {
+ if (m_keepRunning) {
+ return;
+ }
+
+ m_keepRunning = true;
+ m_thread = std::thread([this] { this->ThreadMain(); });
+}
+
+void AsynchronousInterrupt::Disable() {
+ m_keepRunning = false;
+ m_interrupt.WakeupWaitingInterrupt();
+ if (m_thread.joinable()) {
+ m_thread.join();
+ }
+}
+
+void AsynchronousInterrupt::SetInterruptEdges(bool risingEdge,
+ bool fallingEdge) {
+ m_interrupt.SetInterruptEdges(risingEdge, fallingEdge);
+}
+
+units::second_t AsynchronousInterrupt::GetRisingTimestamp() {
+ return m_interrupt.GetRisingTimestamp();
+}
+units::second_t AsynchronousInterrupt::GetFallingTimestamp() {
+ return m_interrupt.GetFallingTimestamp();
+}
diff --git a/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp b/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp
index efc0fe6..1b8da85 100644
--- a/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp
+++ b/wpilibc/src/main/native/cpp/BuiltInAccelerometer.cpp
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/BuiltInAccelerometer.h"
#include <hal/Accelerometer.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -21,32 +18,38 @@
HAL_Report(HALUsageReporting::kResourceType_Accelerometer, 0, 0,
"Built-in accelerometer");
- SendableRegistry::GetInstance().AddLW(this, "BuiltInAccel");
+ wpi::SendableRegistry::AddLW(this, "BuiltInAccel");
}
void BuiltInAccelerometer::SetRange(Range range) {
if (range == kRange_16G) {
- wpi_setWPIErrorWithContext(
- ParameterOutOfRange, "16G range not supported (use k2G, k4G, or k8G)");
+ throw FRC_MakeError(err::ParameterOutOfRange, "{}",
+ "16G range not supported (use k2G, k4G, or k8G)");
}
HAL_SetAccelerometerActive(false);
- HAL_SetAccelerometerRange((HAL_AccelerometerRange)range);
+ HAL_SetAccelerometerRange(static_cast<HAL_AccelerometerRange>(range));
HAL_SetAccelerometerActive(true);
}
-double BuiltInAccelerometer::GetX() { return HAL_GetAccelerometerX(); }
+double BuiltInAccelerometer::GetX() {
+ return HAL_GetAccelerometerX();
+}
-double BuiltInAccelerometer::GetY() { return HAL_GetAccelerometerY(); }
+double BuiltInAccelerometer::GetY() {
+ return HAL_GetAccelerometerY();
+}
-double BuiltInAccelerometer::GetZ() { return HAL_GetAccelerometerZ(); }
+double BuiltInAccelerometer::GetZ() {
+ return HAL_GetAccelerometerZ();
+}
-void BuiltInAccelerometer::InitSendable(SendableBuilder& builder) {
+void BuiltInAccelerometer::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("3AxisAccelerometer");
builder.AddDoubleProperty(
- "X", [=]() { return GetX(); }, nullptr);
+ "X", [=] { return GetX(); }, nullptr);
builder.AddDoubleProperty(
- "Y", [=]() { return GetY(); }, nullptr);
+ "Y", [=] { return GetY(); }, nullptr);
builder.AddDoubleProperty(
- "Z", [=]() { return GetZ(); }, nullptr);
+ "Z", [=] { return GetZ(); }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/CAN.cpp b/wpilibc/src/main/native/cpp/CAN.cpp
index e56e435..e26ca37 100644
--- a/wpilibc/src/main/native/cpp/CAN.cpp
+++ b/wpilibc/src/main/native/cpp/CAN.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/CAN.h"
@@ -14,17 +11,15 @@
#include <hal/Errors.h>
#include <hal/FRCUsageReporting.h>
+#include "frc/Errors.h"
+
using namespace frc;
CAN::CAN(int deviceId) {
int32_t status = 0;
m_handle =
HAL_InitializeCAN(kTeamManufacturer, deviceId, kTeamDeviceType, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_handle = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "device id {}", deviceId);
HAL_Report(HALUsageReporting::kResourceType_CAN, deviceId + 1);
}
@@ -34,17 +29,13 @@
m_handle = HAL_InitializeCAN(
static_cast<HAL_CANManufacturer>(deviceManufacturer), deviceId,
static_cast<HAL_CANDeviceType>(deviceType), &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_handle = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "device id {} mfg {} type {}", deviceId,
+ deviceManufacturer, deviceType);
HAL_Report(HALUsageReporting::kResourceType_CAN, deviceId + 1);
}
CAN::~CAN() {
- if (StatusIsFatal()) return;
if (m_handle != HAL_kInvalidHandle) {
HAL_CleanCAN(m_handle);
m_handle = HAL_kInvalidHandle;
@@ -54,20 +45,20 @@
void CAN::WritePacket(const uint8_t* data, int length, int apiId) {
int32_t status = 0;
HAL_WriteCANPacket(m_handle, data, length, apiId, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "WritePacket");
}
void CAN::WritePacketRepeating(const uint8_t* data, int length, int apiId,
int repeatMs) {
int32_t status = 0;
HAL_WriteCANPacketRepeating(m_handle, data, length, apiId, repeatMs, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "WritePacketRepeating");
}
void CAN::WriteRTRFrame(int length, int apiId) {
int32_t status = 0;
HAL_WriteCANRTRFrame(m_handle, length, apiId, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "WriteRTRFrame");
}
int CAN::WritePacketNoError(const uint8_t* data, int length, int apiId) {
@@ -92,7 +83,7 @@
void CAN::StopPacketRepeating(int apiId) {
int32_t status = 0;
HAL_StopCANPacketRepeating(m_handle, apiId, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "StopPacketRepeating");
}
bool CAN::ReadPacketNew(int apiId, CANData* data) {
@@ -103,7 +94,7 @@
return false;
}
if (status != 0) {
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "ReadPacketNew");
return false;
} else {
return true;
@@ -118,7 +109,7 @@
return false;
}
if (status != 0) {
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "ReadPacketLatest");
return false;
} else {
return true;
@@ -134,7 +125,7 @@
return false;
}
if (status != 0) {
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "ReadPacketTimeout");
return false;
} else {
return true;
diff --git a/wpilibc/src/main/native/cpp/Compressor.cpp b/wpilibc/src/main/native/cpp/Compressor.cpp
index e40758f..0302acb 100644
--- a/wpilibc/src/main/native/cpp/Compressor.cpp
+++ b/wpilibc/src/main/native/cpp/Compressor.cpp
@@ -1,221 +1,72 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Compressor.h"
-#include <hal/Compressor.h>
#include <hal/FRCUsageReporting.h>
#include <hal/Ports.h>
-#include <hal/Solenoid.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
-Compressor::Compressor(int pcmID) : m_module(pcmID) {
- int32_t status = 0;
- m_compressorHandle = HAL_InitializeCompressor(m_module, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumPCMModules(), pcmID);
- return;
+Compressor::Compressor(int module, PneumaticsModuleType moduleType)
+ : m_module{PneumaticsBase::GetForType(module, moduleType)} {
+ if (!m_module->ReserveCompressor()) {
+ throw FRC_MakeError(err::ResourceAlreadyAllocated, "{}", module);
}
+
SetClosedLoopControl(true);
- HAL_Report(HALUsageReporting::kResourceType_Compressor, pcmID + 1);
- SendableRegistry::GetInstance().AddLW(this, "Compressor", pcmID);
+ HAL_Report(HALUsageReporting::kResourceType_Compressor, module + 1);
+ wpi::SendableRegistry::AddLW(this, "Compressor", module);
+}
+
+Compressor::Compressor(PneumaticsModuleType moduleType)
+ : Compressor{PneumaticsBase::GetDefaultForType(moduleType), moduleType} {}
+
+Compressor::~Compressor() {
+ m_module->UnreserveCompressor();
}
void Compressor::Start() {
- if (StatusIsFatal()) return;
SetClosedLoopControl(true);
}
void Compressor::Stop() {
- if (StatusIsFatal()) return;
SetClosedLoopControl(false);
}
bool Compressor::Enabled() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressor(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
+ return m_module->GetCompressor();
}
bool Compressor::GetPressureSwitchValue() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorPressureSwitch(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
+ return m_module->GetPressureSwitch();
}
double Compressor::GetCompressorCurrent() const {
- if (StatusIsFatal()) return 0;
- int32_t status = 0;
- double value;
-
- value = HAL_GetCompressorCurrent(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
+ return m_module->GetCompressorCurrent();
}
void Compressor::SetClosedLoopControl(bool on) {
- if (StatusIsFatal()) return;
- int32_t status = 0;
-
- HAL_SetCompressorClosedLoopControl(m_compressorHandle, on, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
+ m_module->SetClosedLoopControl(on);
}
bool Compressor::GetClosedLoopControl() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorClosedLoopControl(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
+ return m_module->GetClosedLoopControl();
}
-bool Compressor::GetCompressorCurrentTooHighFault() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorCurrentTooHighFault(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
-}
-
-bool Compressor::GetCompressorCurrentTooHighStickyFault() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value =
- HAL_GetCompressorCurrentTooHighStickyFault(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
-}
-
-bool Compressor::GetCompressorShortedStickyFault() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorShortedStickyFault(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
-}
-
-bool Compressor::GetCompressorShortedFault() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorShortedFault(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
-}
-
-bool Compressor::GetCompressorNotConnectedStickyFault() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorNotConnectedStickyFault(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
-}
-
-bool Compressor::GetCompressorNotConnectedFault() const {
- if (StatusIsFatal()) return false;
- int32_t status = 0;
- bool value;
-
- value = HAL_GetCompressorNotConnectedFault(m_compressorHandle, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-
- return value;
-}
-
-void Compressor::ClearAllPCMStickyFaults() {
- if (StatusIsFatal()) return;
- int32_t status = 0;
-
- HAL_ClearAllPCMStickyFaults(m_module, &status);
-
- if (status) {
- wpi_setWPIError(Timeout);
- }
-}
-
-int Compressor::GetModule() const { return m_module; }
-
-void Compressor::InitSendable(SendableBuilder& builder) {
+void Compressor::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Compressor");
builder.AddBooleanProperty(
- "Enabled", [=]() { return Enabled(); },
- [=](bool value) {
- if (value)
- Start();
- else
- Stop();
- });
+ "Closed Loop Control", [=]() { return GetClosedLoopControl(); },
+ [=](bool value) { SetClosedLoopControl(value); });
+ builder.AddBooleanProperty(
+ "Enabled", [=] { return Enabled(); }, nullptr);
builder.AddBooleanProperty(
"Pressure switch", [=]() { return GetPressureSwitchValue(); }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/Counter.cpp b/wpilibc/src/main/native/cpp/Counter.cpp
index ca74ab8..a1ad9e7 100644
--- a/wpilibc/src/main/native/cpp/Counter.cpp
+++ b/wpilibc/src/main/native/cpp/Counter.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Counter.h"
@@ -11,25 +8,26 @@
#include <hal/Counter.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
#include "frc/AnalogTrigger.h"
-#include "frc/Base.h"
#include "frc/DigitalInput.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
Counter::Counter(Mode mode) {
int32_t status = 0;
- m_counter = HAL_InitializeCounter((HAL_Counter_Mode)mode, &m_index, &status);
- wpi_setHALError(status);
+ m_counter = HAL_InitializeCounter(static_cast<HAL_Counter_Mode>(mode),
+ &m_index, &status);
+ FRC_CheckErrorStatus(status, "{}", "InitializeCounter");
- SetMaxPeriod(0.5);
+ SetMaxPeriod(0.5_s);
HAL_Report(HALUsageReporting::kResourceType_Counter, m_index + 1, mode + 1);
- SendableRegistry::GetInstance().AddLW(this, "Counter", m_index);
+ wpi::SendableRegistry::AddLW(this, "Counter", m_index);
}
Counter::Counter(int channel) : Counter(kTwoPulse) {
@@ -56,9 +54,9 @@
DigitalSource* downSource, bool inverted)
: Counter(encodingType,
std::shared_ptr<DigitalSource>(upSource,
- NullDeleter<DigitalSource>()),
+ wpi::NullDeleter<DigitalSource>()),
std::shared_ptr<DigitalSource>(downSource,
- NullDeleter<DigitalSource>()),
+ wpi::NullDeleter<DigitalSource>()),
inverted) {}
Counter::Counter(EncodingType encodingType,
@@ -66,10 +64,8 @@
std::shared_ptr<DigitalSource> downSource, bool inverted)
: Counter(kExternalDirection) {
if (encodingType != k1X && encodingType != k2X) {
- wpi_setWPIErrorWithContext(
- ParameterOutOfRange,
- "Counter only supports 1X and 2X quadrature decoding.");
- return;
+ throw FRC_MakeError(err::ParameterOutOfRange, "{}",
+ "Counter only supports 1X and 2X quadrature decoding");
}
SetUpSource(upSource);
SetDownSource(downSource);
@@ -83,256 +79,235 @@
HAL_SetCounterAverageSize(m_counter, 2, &status);
}
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Counter constructor");
SetDownSourceEdge(inverted, true);
}
Counter::~Counter() {
- SetUpdateWhenEmpty(true);
+ try {
+ SetUpdateWhenEmpty(true);
+ } catch (const RuntimeError& e) {
+ e.Report();
+ }
int32_t status = 0;
HAL_FreeCounter(m_counter, &status);
- wpi_setHALError(status);
+ FRC_ReportError(status, "{}", "Counter destructor");
}
void Counter::SetUpSource(int channel) {
- if (StatusIsFatal()) return;
SetUpSource(std::make_shared<DigitalInput>(channel));
- SendableRegistry::GetInstance().AddChild(this, m_upSource.get());
+ wpi::SendableRegistry::AddChild(this, m_upSource.get());
}
void Counter::SetUpSource(AnalogTrigger* analogTrigger,
AnalogTriggerType triggerType) {
SetUpSource(std::shared_ptr<AnalogTrigger>(analogTrigger,
- NullDeleter<AnalogTrigger>()),
+ wpi::NullDeleter<AnalogTrigger>()),
triggerType);
}
void Counter::SetUpSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType) {
- if (StatusIsFatal()) return;
SetUpSource(analogTrigger->CreateOutput(triggerType));
}
void Counter::SetUpSource(DigitalSource* source) {
- SetUpSource(
- std::shared_ptr<DigitalSource>(source, NullDeleter<DigitalSource>()));
+ SetUpSource(std::shared_ptr<DigitalSource>(
+ source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetUpSource(std::shared_ptr<DigitalSource> source) {
- if (StatusIsFatal()) return;
m_upSource = source;
- if (m_upSource->StatusIsFatal()) {
- CloneError(*m_upSource);
- } else {
- int32_t status = 0;
- HAL_SetCounterUpSource(
- m_counter, source->GetPortHandleForRouting(),
- (HAL_AnalogTriggerType)source->GetAnalogTriggerTypeForRouting(),
- &status);
- wpi_setHALError(status);
- }
+ int32_t status = 0;
+ HAL_SetCounterUpSource(m_counter, source->GetPortHandleForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ source->GetAnalogTriggerTypeForRouting()),
+ &status);
+ FRC_CheckErrorStatus(status, "{}", "SetUpSource");
}
void Counter::SetUpSource(DigitalSource& source) {
- SetUpSource(
- std::shared_ptr<DigitalSource>(&source, NullDeleter<DigitalSource>()));
+ SetUpSource(std::shared_ptr<DigitalSource>(
+ &source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) {
- if (StatusIsFatal()) return;
if (m_upSource == nullptr) {
- wpi_setWPIErrorWithContext(
- NullParameter,
+ throw FRC_MakeError(
+ err::NullParameter, "{}",
"Must set non-nullptr UpSource before setting UpSourceEdge");
}
int32_t status = 0;
HAL_SetCounterUpSourceEdge(m_counter, risingEdge, fallingEdge, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetUpSourceEdge");
}
void Counter::ClearUpSource() {
- if (StatusIsFatal()) return;
m_upSource.reset();
int32_t status = 0;
HAL_ClearCounterUpSource(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "ClearUpSource");
}
void Counter::SetDownSource(int channel) {
- if (StatusIsFatal()) return;
SetDownSource(std::make_shared<DigitalInput>(channel));
- SendableRegistry::GetInstance().AddChild(this, m_downSource.get());
+ wpi::SendableRegistry::AddChild(this, m_downSource.get());
}
void Counter::SetDownSource(AnalogTrigger* analogTrigger,
AnalogTriggerType triggerType) {
- SetDownSource(std::shared_ptr<AnalogTrigger>(analogTrigger,
- NullDeleter<AnalogTrigger>()),
+ SetDownSource(std::shared_ptr<AnalogTrigger>(
+ analogTrigger, wpi::NullDeleter<AnalogTrigger>()),
triggerType);
}
void Counter::SetDownSource(std::shared_ptr<AnalogTrigger> analogTrigger,
AnalogTriggerType triggerType) {
- if (StatusIsFatal()) return;
SetDownSource(analogTrigger->CreateOutput(triggerType));
}
void Counter::SetDownSource(DigitalSource* source) {
- SetDownSource(
- std::shared_ptr<DigitalSource>(source, NullDeleter<DigitalSource>()));
+ SetDownSource(std::shared_ptr<DigitalSource>(
+ source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetDownSource(DigitalSource& source) {
- SetDownSource(
- std::shared_ptr<DigitalSource>(&source, NullDeleter<DigitalSource>()));
+ SetDownSource(std::shared_ptr<DigitalSource>(
+ &source, wpi::NullDeleter<DigitalSource>()));
}
void Counter::SetDownSource(std::shared_ptr<DigitalSource> source) {
- if (StatusIsFatal()) return;
m_downSource = source;
- if (m_downSource->StatusIsFatal()) {
- CloneError(*m_downSource);
- } else {
- int32_t status = 0;
- HAL_SetCounterDownSource(
- m_counter, source->GetPortHandleForRouting(),
- (HAL_AnalogTriggerType)source->GetAnalogTriggerTypeForRouting(),
- &status);
- wpi_setHALError(status);
- }
+ int32_t status = 0;
+ HAL_SetCounterDownSource(m_counter, source->GetPortHandleForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ source->GetAnalogTriggerTypeForRouting()),
+ &status);
+ FRC_CheckErrorStatus(status, "{}", "SetDownSource");
}
void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) {
- if (StatusIsFatal()) return;
if (m_downSource == nullptr) {
- wpi_setWPIErrorWithContext(
- NullParameter,
+ throw FRC_MakeError(
+ err::NullParameter, "{}",
"Must set non-nullptr DownSource before setting DownSourceEdge");
}
int32_t status = 0;
HAL_SetCounterDownSourceEdge(m_counter, risingEdge, fallingEdge, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetDownSourceEdge");
}
void Counter::ClearDownSource() {
- if (StatusIsFatal()) return;
m_downSource.reset();
int32_t status = 0;
HAL_ClearCounterDownSource(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "ClearDownSource");
}
void Counter::SetUpDownCounterMode() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetCounterUpDownMode(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetUpDownCounterMode");
}
void Counter::SetExternalDirectionMode() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetCounterExternalDirectionMode(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetExternalDirectionMode");
}
void Counter::SetSemiPeriodMode(bool highSemiPeriod) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetCounterSemiPeriodMode(m_counter, highSemiPeriod, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSemiPeriodMode to {}",
+ highSemiPeriod ? "true" : "false");
}
void Counter::SetPulseLengthMode(double threshold) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetCounterPulseLengthMode(m_counter, threshold, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetPulseLengthMode");
}
void Counter::SetReverseDirection(bool reverseDirection) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetCounterReverseDirection(m_counter, reverseDirection, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetReverseDirection to {}",
+ reverseDirection ? "true" : "false");
}
void Counter::SetSamplesToAverage(int samplesToAverage) {
if (samplesToAverage < 1 || samplesToAverage > 127) {
- wpi_setWPIErrorWithContext(
- ParameterOutOfRange,
- "Average counter values must be between 1 and 127");
+ throw FRC_MakeError(
+ err::ParameterOutOfRange,
+ "Average counter values must be between 1 and 127, {} out of range",
+ samplesToAverage);
}
int32_t status = 0;
HAL_SetCounterSamplesToAverage(m_counter, samplesToAverage, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSamplesToAverage to {}", samplesToAverage);
}
int Counter::GetSamplesToAverage() const {
int32_t status = 0;
int samples = HAL_GetCounterSamplesToAverage(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetSamplesToAverage");
return samples;
}
-int Counter::GetFPGAIndex() const { return m_index; }
+int Counter::GetFPGAIndex() const {
+ return m_index;
+}
int Counter::Get() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int value = HAL_GetCounter(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Get");
return value;
}
void Counter::Reset() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_ResetCounter(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Reset");
}
-double Counter::GetPeriod() const {
- if (StatusIsFatal()) return 0.0;
+units::second_t Counter::GetPeriod() const {
int32_t status = 0;
double value = HAL_GetCounterPeriod(m_counter, &status);
- wpi_setHALError(status);
- return value;
+ FRC_CheckErrorStatus(status, "{}", "GetPeriod");
+ return units::second_t{value};
}
-void Counter::SetMaxPeriod(double maxPeriod) {
- if (StatusIsFatal()) return;
+void Counter::SetMaxPeriod(units::second_t maxPeriod) {
int32_t status = 0;
- HAL_SetCounterMaxPeriod(m_counter, maxPeriod, &status);
- wpi_setHALError(status);
+ HAL_SetCounterMaxPeriod(m_counter, maxPeriod.value(), &status);
+ FRC_CheckErrorStatus(status, "{}", "SetMaxPeriod");
}
void Counter::SetUpdateWhenEmpty(bool enabled) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetCounterUpdateWhenEmpty(m_counter, enabled, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetUpdateWhenEmpty");
}
bool Counter::GetStopped() const {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool value = HAL_GetCounterStopped(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetStopped");
return value;
}
bool Counter::GetDirection() const {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool value = HAL_GetCounterDirection(m_counter, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetDirection");
return value;
}
-void Counter::InitSendable(SendableBuilder& builder) {
+void Counter::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Counter");
builder.AddDoubleProperty(
- "Value", [=]() { return Get(); }, nullptr);
+ "Value", [=] { return Get(); }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/DMA.cpp b/wpilibc/src/main/native/cpp/DMA.cpp
index 1861555..80c0adb 100644
--- a/wpilibc/src/main/native/cpp/DMA.cpp
+++ b/wpilibc/src/main/native/cpp/DMA.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DMA.h"
@@ -12,104 +9,154 @@
#include <frc/DigitalSource.h>
#include <frc/DutyCycle.h>
#include <frc/Encoder.h>
+#include <frc/PWM.h>
+#include <frc/motorcontrol/PWMMotorController.h>
#include <hal/DMA.h>
#include <hal/HALBase.h>
+#include "frc/AnalogInput.h"
+#include "frc/Counter.h"
+#include "frc/DigitalSource.h"
+#include "frc/DutyCycle.h"
+#include "frc/Encoder.h"
+#include "frc/Errors.h"
+
using namespace frc;
DMA::DMA() {
int32_t status = 0;
dmaHandle = HAL_InitializeDMA(&status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "InitializeDMA");
}
-DMA::~DMA() { HAL_FreeDMA(dmaHandle); }
+DMA::~DMA() {
+ HAL_FreeDMA(dmaHandle);
+}
void DMA::SetPause(bool pause) {
int32_t status = 0;
HAL_SetDMAPause(dmaHandle, pause, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "SetPause");
}
-void DMA::SetRate(int cycles) {
+void DMA::SetTimedTrigger(units::second_t seconds) {
int32_t status = 0;
- HAL_SetDMARate(dmaHandle, cycles, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ HAL_SetDMATimedTrigger(dmaHandle, seconds.value(), &status);
+ FRC_CheckErrorStatus(status, "{}", "SetTimedTrigger");
+}
+
+void DMA::SetTimedTriggerCycles(int cycles) {
+ int32_t status = 0;
+ HAL_SetDMATimedTriggerCycles(dmaHandle, cycles, &status);
+ FRC_CheckErrorStatus(status, "{}", "SetTimedTriggerCycles");
}
void DMA::AddEncoder(const Encoder* encoder) {
int32_t status = 0;
HAL_AddDMAEncoder(dmaHandle, encoder->m_encoder, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddEncoder");
}
void DMA::AddEncoderPeriod(const Encoder* encoder) {
int32_t status = 0;
HAL_AddDMAEncoderPeriod(dmaHandle, encoder->m_encoder, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddEncoderPeriod");
}
void DMA::AddCounter(const Counter* counter) {
int32_t status = 0;
HAL_AddDMACounter(dmaHandle, counter->m_counter, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddCounter");
}
void DMA::AddCounterPeriod(const Counter* counter) {
int32_t status = 0;
HAL_AddDMACounterPeriod(dmaHandle, counter->m_counter, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddCounterPeriod");
}
void DMA::AddDigitalSource(const DigitalSource* digitalSource) {
int32_t status = 0;
HAL_AddDMADigitalSource(dmaHandle, digitalSource->GetPortHandleForRouting(),
&status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddDigitalSource");
}
void DMA::AddDutyCycle(const DutyCycle* dutyCycle) {
int32_t status = 0;
HAL_AddDMADutyCycle(dmaHandle, dutyCycle->m_handle, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddDutyCycle");
}
void DMA::AddAnalogInput(const AnalogInput* analogInput) {
int32_t status = 0;
HAL_AddDMAAnalogInput(dmaHandle, analogInput->m_port, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddAnalogInput");
}
void DMA::AddAveragedAnalogInput(const AnalogInput* analogInput) {
int32_t status = 0;
HAL_AddDMAAveragedAnalogInput(dmaHandle, analogInput->m_port, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddAveragedAnalogInput");
}
void DMA::AddAnalogAccumulator(const AnalogInput* analogInput) {
int32_t status = 0;
HAL_AddDMAAnalogAccumulator(dmaHandle, analogInput->m_port, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "AddAnalogAccumulator");
}
-void DMA::SetExternalTrigger(DigitalSource* source, bool rising, bool falling) {
+int DMA::SetExternalTrigger(DigitalSource* source, bool rising, bool falling) {
int32_t status = 0;
- HAL_SetDMAExternalTrigger(dmaHandle, source->GetPortHandleForRouting(),
- static_cast<HAL_AnalogTriggerType>(
- source->GetAnalogTriggerTypeForRouting()),
- rising, falling, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ int32_t idx =
+ HAL_SetDMAExternalTrigger(dmaHandle, source->GetPortHandleForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ source->GetAnalogTriggerTypeForRouting()),
+ rising, falling, &status);
+ FRC_CheckErrorStatus(status, "{}", "SetExternalTrigger");
+ return idx;
}
-void DMA::StartDMA(int queueDepth) {
+int DMA::SetPwmEdgeTrigger(PWMMotorController* source, bool rising,
+ bool falling) {
+ int32_t status = 0;
+ int32_t idx = HAL_SetDMAExternalTrigger(
+ dmaHandle, source->GetPwm()->m_handle,
+ HAL_AnalogTriggerType::HAL_Trigger_kInWindow, rising, falling, &status);
+ FRC_CheckErrorStatus(status, "{}", "SetPWmEdgeTrigger");
+ return idx;
+}
+
+int DMA::SetPwmEdgeTrigger(PWM* source, bool rising, bool falling) {
+ int32_t status = 0;
+ int32_t idx = HAL_SetDMAExternalTrigger(
+ dmaHandle, source->m_handle, HAL_AnalogTriggerType::HAL_Trigger_kInWindow,
+ rising, falling, &status);
+ FRC_CheckErrorStatus(status, "{}", "SetPWmEdgeTrigger");
+ return idx;
+}
+
+void DMA::ClearSensors() {
+ int32_t status = 0;
+ HAL_ClearDMASensors(dmaHandle, &status);
+ FRC_CheckErrorStatus(status, "{}", "ClearSensors");
+}
+
+void DMA::ClearExternalTriggers() {
+ int32_t status = 0;
+ HAL_ClearDMAExternalTriggers(dmaHandle, &status);
+ FRC_CheckErrorStatus(status, "{}", "ClearExternalTriggers");
+}
+
+void DMA::Start(int queueDepth) {
int32_t status = 0;
HAL_StartDMA(dmaHandle, queueDepth, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "Start");
}
-void DMA::StopDMA() {
+void DMA::Stop() {
int32_t status = 0;
HAL_StopDMA(dmaHandle, &status);
- wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
+ FRC_CheckErrorStatus(status, "{}", "Stop");
}
diff --git a/wpilibc/src/main/native/cpp/DMC60.cpp b/wpilibc/src/main/native/cpp/DMC60.cpp
deleted file mode 100644
index e7d2c65..0000000
--- a/wpilibc/src/main/native/cpp/DMC60.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/DMC60.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-DMC60::DMC60(int channel) : PWMSpeedController(channel) {
- SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_DigilentDMC60, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "DMC60", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/DSControlWord.cpp b/wpilibc/src/main/native/cpp/DSControlWord.cpp
new file mode 100644
index 0000000..15d209a
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/DSControlWord.cpp
@@ -0,0 +1,55 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/DSControlWord.h"
+
+#include <hal/DriverStation.h>
+
+using namespace frc;
+
+DSControlWord::DSControlWord() {
+ HAL_GetControlWord(&m_controlWord);
+}
+
+bool DSControlWord::IsEnabled() const {
+ return m_controlWord.enabled && m_controlWord.dsAttached;
+}
+
+bool DSControlWord::IsDisabled() const {
+ return !(m_controlWord.enabled && m_controlWord.dsAttached);
+}
+
+bool DSControlWord::IsEStopped() const {
+ return m_controlWord.eStop;
+}
+
+bool DSControlWord::IsAutonomous() const {
+ return m_controlWord.autonomous;
+}
+
+bool DSControlWord::IsAutonomousEnabled() const {
+ return m_controlWord.autonomous && m_controlWord.enabled &&
+ m_controlWord.dsAttached;
+}
+
+bool DSControlWord::IsTeleop() const {
+ return !(m_controlWord.autonomous || m_controlWord.test);
+}
+
+bool DSControlWord::IsTeleopEnabled() const {
+ return !m_controlWord.autonomous && !m_controlWord.test &&
+ m_controlWord.enabled && m_controlWord.dsAttached;
+}
+
+bool DSControlWord::IsTest() const {
+ return m_controlWord.test;
+}
+
+bool DSControlWord::IsDSAttached() const {
+ return m_controlWord.dsAttached;
+}
+
+bool DSControlWord::IsFMSAttached() const {
+ return m_controlWord.fmsAttached;
+}
diff --git a/wpilibc/src/main/native/cpp/Debouncer.cpp b/wpilibc/src/main/native/cpp/Debouncer.cpp
new file mode 100644
index 0000000..eb402cd
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/Debouncer.cpp
@@ -0,0 +1,37 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/Debouncer.h"
+
+using namespace frc;
+
+Debouncer::Debouncer(units::second_t debounceTime, DebounceType type)
+ : m_debounceTime(debounceTime), m_debounceType(type) {
+ switch (type) {
+ case DebounceType::kBoth: // fall-through
+ case DebounceType::kRising:
+ m_baseline = false;
+ break;
+ case DebounceType::kFalling:
+ m_baseline = true;
+ break;
+ }
+ m_timer.Start();
+}
+
+bool Debouncer::Calculate(bool input) {
+ if (input == m_baseline) {
+ m_timer.Reset();
+ }
+
+ if (m_timer.HasElapsed(m_debounceTime)) {
+ if (m_debounceType == DebounceType::kBoth) {
+ m_baseline = input;
+ m_timer.Reset();
+ }
+ return input;
+ } else {
+ return m_baseline;
+ }
+}
diff --git a/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp b/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp
index 3cec3f1..3294a99 100644
--- a/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp
+++ b/wpilibc/src/main/native/cpp/DigitalGlitchFilter.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DigitalGlitchFilter.h"
@@ -14,13 +11,12 @@
#include <hal/Constants.h>
#include <hal/DIO.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/sendable/SendableRegistry.h>
#include "frc/Counter.h"
#include "frc/Encoder.h"
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -32,15 +28,14 @@
std::scoped_lock lock(m_mutex);
auto index =
std::find(m_filterAllocated.begin(), m_filterAllocated.end(), false);
- wpi_assert(index != m_filterAllocated.end());
+ FRC_Assert(index != m_filterAllocated.end());
m_channelIndex = std::distance(m_filterAllocated.begin(), index);
*index = true;
HAL_Report(HALUsageReporting::kResourceType_DigitalGlitchFilter,
m_channelIndex + 1);
- SendableRegistry::GetInstance().AddLW(this, "DigitalGlitchFilter",
- m_channelIndex);
+ wpi::SendableRegistry::AddLW(this, "DigitalGlitchFilter", m_channelIndex);
}
DigitalGlitchFilter::~DigitalGlitchFilter() {
@@ -50,20 +45,6 @@
}
}
-DigitalGlitchFilter::DigitalGlitchFilter(DigitalGlitchFilter&& rhs)
- : ErrorBase(std::move(rhs)), SendableHelper(std::move(rhs)) {
- std::swap(m_channelIndex, rhs.m_channelIndex);
-}
-
-DigitalGlitchFilter& DigitalGlitchFilter::operator=(DigitalGlitchFilter&& rhs) {
- ErrorBase::operator=(std::move(rhs));
- SendableHelper::operator=(std::move(rhs));
-
- std::swap(m_channelIndex, rhs.m_channelIndex);
-
- return *this;
-}
-
void DigitalGlitchFilter::Add(DigitalSource* input) {
DoAdd(input, m_channelIndex + 1);
}
@@ -74,60 +55,50 @@
if (input) {
// We don't support GlitchFilters on AnalogTriggers.
if (input->IsAnalogTrigger()) {
- wpi_setErrorWithContext(
- -1, "Analog Triggers not supported for DigitalGlitchFilters");
- return;
+ throw FRC_MakeError(
+ -1, "{}", "Analog Triggers not supported for DigitalGlitchFilters");
}
int32_t status = 0;
HAL_SetFilterSelect(input->GetPortHandleForRouting(), requestedIndex,
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "requested index {}", requestedIndex);
// Validate that we set it correctly.
int actualIndex =
HAL_GetFilterSelect(input->GetPortHandleForRouting(), &status);
- wpi_assertEqual(actualIndex, requestedIndex);
+ FRC_CheckErrorStatus(status, "requested index {}", requestedIndex);
+ FRC_Assert(actualIndex == requestedIndex);
}
}
void DigitalGlitchFilter::Add(Encoder* input) {
Add(input->m_aSource.get());
- if (StatusIsFatal()) {
- return;
- }
Add(input->m_bSource.get());
}
void DigitalGlitchFilter::Add(Counter* input) {
Add(input->m_upSource.get());
- if (StatusIsFatal()) {
- return;
- }
Add(input->m_downSource.get());
}
-void DigitalGlitchFilter::Remove(DigitalSource* input) { DoAdd(input, 0); }
+void DigitalGlitchFilter::Remove(DigitalSource* input) {
+ DoAdd(input, 0);
+}
void DigitalGlitchFilter::Remove(Encoder* input) {
Remove(input->m_aSource.get());
- if (StatusIsFatal()) {
- return;
- }
Remove(input->m_bSource.get());
}
void DigitalGlitchFilter::Remove(Counter* input) {
Remove(input->m_upSource.get());
- if (StatusIsFatal()) {
- return;
- }
Remove(input->m_downSource.get());
}
void DigitalGlitchFilter::SetPeriodCycles(int fpgaCycles) {
int32_t status = 0;
HAL_SetFilterPeriod(m_channelIndex, fpgaCycles, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channelIndex);
}
void DigitalGlitchFilter::SetPeriodNanoSeconds(uint64_t nanoseconds) {
@@ -135,27 +106,22 @@
int fpgaCycles =
nanoseconds * HAL_GetSystemClockTicksPerMicrosecond() / 4 / 1000;
HAL_SetFilterPeriod(m_channelIndex, fpgaCycles, &status);
-
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channelIndex);
}
int DigitalGlitchFilter::GetPeriodCycles() {
int32_t status = 0;
int fpgaCycles = HAL_GetFilterPeriod(m_channelIndex, &status);
-
- wpi_setHALError(status);
-
+ FRC_CheckErrorStatus(status, "Channel {}", m_channelIndex);
return fpgaCycles;
}
uint64_t DigitalGlitchFilter::GetPeriodNanoSeconds() {
int32_t status = 0;
int fpgaCycles = HAL_GetFilterPeriod(m_channelIndex, &status);
-
- wpi_setHALError(status);
-
+ FRC_CheckErrorStatus(status, "Channel {}", m_channelIndex);
return static_cast<uint64_t>(fpgaCycles) * 1000L /
static_cast<uint64_t>(HAL_GetSystemClockTicksPerMicrosecond() / 4);
}
-void DigitalGlitchFilter::InitSendable(SendableBuilder&) {}
+void DigitalGlitchFilter::InitSendable(wpi::SendableBuilder&) {}
diff --git a/wpilibc/src/main/native/cpp/DigitalInput.cpp b/wpilibc/src/main/native/cpp/DigitalInput.cpp
index d82f570..7bce921 100644
--- a/wpilibc/src/main/native/cpp/DigitalInput.cpp
+++ b/wpilibc/src/main/native/cpp/DigitalInput.cpp
@@ -1,77 +1,74 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DigitalInput.h"
+#include <iostream>
#include <limits>
#include <hal/DIO.h>
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
DigitalInput::DigitalInput(int channel) {
if (!SensorUtil::CheckDigitalChannel(channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "Digital Channel " + wpi::Twine(channel));
- m_channel = std::numeric_limits<int>::max();
- return;
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", channel);
}
m_channel = channel;
int32_t status = 0;
- m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), true, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumDigitalChannels(), channel);
- m_handle = HAL_kInvalidHandle;
- m_channel = std::numeric_limits<int>::max();
- return;
- }
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), true,
+ stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
HAL_Report(HALUsageReporting::kResourceType_DigitalInput, channel + 1);
- SendableRegistry::GetInstance().AddLW(this, "DigitalInput", channel);
+ wpi::SendableRegistry::AddLW(this, "DigitalInput", channel);
}
DigitalInput::~DigitalInput() {
- if (StatusIsFatal()) return;
HAL_FreeDIOPort(m_handle);
}
bool DigitalInput::Get() const {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool value = HAL_GetDIO(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return value;
}
-HAL_Handle DigitalInput::GetPortHandleForRouting() const { return m_handle; }
-
-AnalogTriggerType DigitalInput::GetAnalogTriggerTypeForRouting() const {
- return (AnalogTriggerType)0;
+HAL_Handle DigitalInput::GetPortHandleForRouting() const {
+ return m_handle;
}
-bool DigitalInput::IsAnalogTrigger() const { return false; }
+AnalogTriggerType DigitalInput::GetAnalogTriggerTypeForRouting() const {
+ return static_cast<AnalogTriggerType>(0);
+}
+
+bool DigitalInput::IsAnalogTrigger() const {
+ return false;
+}
void DigitalInput::SetSimDevice(HAL_SimDeviceHandle device) {
HAL_SetDIOSimDevice(m_handle, device);
}
-int DigitalInput::GetChannel() const { return m_channel; }
+int DigitalInput::GetChannel() const {
+ return m_channel;
+}
-void DigitalInput::InitSendable(SendableBuilder& builder) {
+void DigitalInput::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Digital Input");
builder.AddBooleanProperty(
- "Value", [=]() { return Get(); }, nullptr);
+ "Value", [=] { return Get(); }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/DigitalOutput.cpp b/wpilibc/src/main/native/cpp/DigitalOutput.cpp
index 0bdc57c..5810e30 100644
--- a/wpilibc/src/main/native/cpp/DigitalOutput.cpp
+++ b/wpilibc/src/main/native/cpp/DigitalOutput.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DigitalOutput.h"
@@ -13,146 +10,138 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
DigitalOutput::DigitalOutput(int channel) {
m_pwmGenerator = HAL_kInvalidHandle;
if (!SensorUtil::CheckDigitalChannel(channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "Digital Channel " + wpi::Twine(channel));
- m_channel = std::numeric_limits<int>::max();
- return;
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", channel);
}
m_channel = channel;
int32_t status = 0;
- m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), false, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumDigitalChannels(), channel);
- m_channel = std::numeric_limits<int>::max();
- m_handle = HAL_kInvalidHandle;
- return;
- }
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_handle = HAL_InitializeDIOPort(HAL_GetPort(channel), false,
+ stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
HAL_Report(HALUsageReporting::kResourceType_DigitalOutput, channel + 1);
- SendableRegistry::GetInstance().AddLW(this, "DigitalOutput", channel);
+ wpi::SendableRegistry::AddLW(this, "DigitalOutput", channel);
}
DigitalOutput::~DigitalOutput() {
- if (StatusIsFatal()) return;
// Disable the PWM in case it was running.
- DisablePWM();
+ try {
+ DisablePWM();
+ } catch (const RuntimeError& e) {
+ e.Report();
+ }
HAL_FreeDIOPort(m_handle);
}
void DigitalOutput::Set(bool value) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
HAL_SetDIO(m_handle, value, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
bool DigitalOutput::Get() const {
- if (StatusIsFatal()) return false;
-
int32_t status = 0;
bool val = HAL_GetDIO(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return val;
}
-HAL_Handle DigitalOutput::GetPortHandleForRouting() const { return m_handle; }
-
-AnalogTriggerType DigitalOutput::GetAnalogTriggerTypeForRouting() const {
- return (AnalogTriggerType)0;
+HAL_Handle DigitalOutput::GetPortHandleForRouting() const {
+ return m_handle;
}
-bool DigitalOutput::IsAnalogTrigger() const { return false; }
+AnalogTriggerType DigitalOutput::GetAnalogTriggerTypeForRouting() const {
+ return static_cast<AnalogTriggerType>(0);
+}
-int DigitalOutput::GetChannel() const { return m_channel; }
+bool DigitalOutput::IsAnalogTrigger() const {
+ return false;
+}
+
+int DigitalOutput::GetChannel() const {
+ return m_channel;
+}
void DigitalOutput::Pulse(double length) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
HAL_Pulse(m_handle, length, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
bool DigitalOutput::IsPulsing() const {
- if (StatusIsFatal()) return false;
-
int32_t status = 0;
bool value = HAL_IsPulsing(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return value;
}
void DigitalOutput::SetPWMRate(double rate) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
HAL_SetDigitalPWMRate(rate, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void DigitalOutput::EnablePWM(double initialDutyCycle) {
- if (m_pwmGenerator != HAL_kInvalidHandle) return;
+ if (m_pwmGenerator != HAL_kInvalidHandle) {
+ return;
+ }
int32_t status = 0;
- if (StatusIsFatal()) return;
m_pwmGenerator = HAL_AllocateDigitalPWM(&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
- if (StatusIsFatal()) return;
HAL_SetDigitalPWMDutyCycle(m_pwmGenerator, initialDutyCycle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
- if (StatusIsFatal()) return;
HAL_SetDigitalPWMOutputChannel(m_pwmGenerator, m_channel, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void DigitalOutput::DisablePWM() {
- if (StatusIsFatal()) return;
- if (m_pwmGenerator == HAL_kInvalidHandle) return;
+ if (m_pwmGenerator == HAL_kInvalidHandle) {
+ return;
+ }
int32_t status = 0;
// Disable the output by routing to a dead bit.
HAL_SetDigitalPWMOutputChannel(m_pwmGenerator, SensorUtil::kDigitalChannels,
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
HAL_FreeDigitalPWM(m_pwmGenerator, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
m_pwmGenerator = HAL_kInvalidHandle;
}
void DigitalOutput::UpdateDutyCycle(double dutyCycle) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
HAL_SetDigitalPWMDutyCycle(m_pwmGenerator, dutyCycle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void DigitalOutput::SetSimDevice(HAL_SimDeviceHandle device) {
HAL_SetDIOSimDevice(m_handle, device);
}
-void DigitalOutput::InitSendable(SendableBuilder& builder) {
+void DigitalOutput::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Digital Output");
builder.AddBooleanProperty(
- "Value", [=]() { return Get(); }, [=](bool value) { Set(value); });
+ "Value", [=] { return Get(); }, [=](bool value) { Set(value); });
}
diff --git a/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp b/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp
index 67eb0b7..212673a 100644
--- a/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp
+++ b/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DoubleSolenoid.h"
@@ -12,128 +9,92 @@
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
-#include <hal/Solenoid.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
-DoubleSolenoid::DoubleSolenoid(int forwardChannel, int reverseChannel)
- : DoubleSolenoid(SensorUtil::GetDefaultSolenoidModule(), forwardChannel,
- reverseChannel) {}
-
-DoubleSolenoid::DoubleSolenoid(int moduleNumber, int forwardChannel,
- int reverseChannel)
- : SolenoidBase(moduleNumber),
- m_forwardChannel(forwardChannel),
- m_reverseChannel(reverseChannel) {
- if (!SensorUtil::CheckSolenoidModule(m_moduleNumber)) {
- wpi_setWPIErrorWithContext(ModuleIndexOutOfRange,
- "Solenoid Module " + wpi::Twine(m_moduleNumber));
- return;
+DoubleSolenoid::DoubleSolenoid(int module, PneumaticsModuleType moduleType,
+ int forwardChannel, int reverseChannel)
+ : m_module{PneumaticsBase::GetForType(module, moduleType)},
+ m_forwardChannel{forwardChannel},
+ m_reverseChannel{reverseChannel} {
+ if (!m_module->CheckSolenoidChannel(m_forwardChannel)) {
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}",
+ m_forwardChannel);
}
- if (!SensorUtil::CheckSolenoidChannel(m_forwardChannel)) {
- wpi_setWPIErrorWithContext(
- ChannelIndexOutOfRange,
- "Solenoid Channel " + wpi::Twine(m_forwardChannel));
- return;
- }
- if (!SensorUtil::CheckSolenoidChannel(m_reverseChannel)) {
- wpi_setWPIErrorWithContext(
- ChannelIndexOutOfRange,
- "Solenoid Channel " + wpi::Twine(m_reverseChannel));
- return;
- }
- int32_t status = 0;
- m_forwardHandle = HAL_InitializeSolenoidPort(
- HAL_GetPortWithModule(moduleNumber, m_forwardChannel), &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumSolenoidChannels(),
- forwardChannel);
- m_forwardHandle = HAL_kInvalidHandle;
- m_reverseHandle = HAL_kInvalidHandle;
- return;
+ if (!m_module->CheckSolenoidChannel(m_reverseChannel)) {
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}",
+ m_reverseChannel);
}
- m_reverseHandle = HAL_InitializeSolenoidPort(
- HAL_GetPortWithModule(moduleNumber, m_reverseChannel), &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumSolenoidChannels(),
- reverseChannel);
- // free forward solenoid
- HAL_FreeSolenoidPort(m_forwardHandle);
- m_forwardHandle = HAL_kInvalidHandle;
- m_reverseHandle = HAL_kInvalidHandle;
- return;
- }
+ m_forwardMask = 1 << forwardChannel;
+ m_reverseMask = 1 << reverseChannel;
+ m_mask = m_forwardMask | m_reverseMask;
- m_forwardMask = 1 << m_forwardChannel;
- m_reverseMask = 1 << m_reverseChannel;
+ int allocMask = m_module->CheckAndReserveSolenoids(m_mask);
+ if (allocMask != 0) {
+ if (allocMask == m_mask) {
+ throw FRC_MakeError(err::ResourceAlreadyAllocated, "Channels {} and {}",
+ m_forwardChannel, m_reverseChannel);
+ } else if (allocMask == m_forwardMask) {
+ throw FRC_MakeError(err::ResourceAlreadyAllocated, "Channel {}",
+ m_forwardChannel);
+ } else {
+ throw FRC_MakeError(err::ResourceAlreadyAllocated, "Channel {}",
+ m_reverseChannel);
+ }
+ }
HAL_Report(HALUsageReporting::kResourceType_Solenoid, m_forwardChannel + 1,
- m_moduleNumber + 1);
+ m_module->GetModuleNumber() + 1);
HAL_Report(HALUsageReporting::kResourceType_Solenoid, m_reverseChannel + 1,
- m_moduleNumber + 1);
+ m_module->GetModuleNumber() + 1);
- SendableRegistry::GetInstance().AddLW(this, "DoubleSolenoid", m_moduleNumber,
- m_forwardChannel);
+ wpi::SendableRegistry::AddLW(this, "DoubleSolenoid",
+ m_module->GetModuleNumber(), m_forwardChannel);
}
+DoubleSolenoid::DoubleSolenoid(PneumaticsModuleType moduleType,
+ int forwardChannel, int reverseChannel)
+ : DoubleSolenoid{PneumaticsBase::GetDefaultForType(moduleType), moduleType,
+ forwardChannel, reverseChannel} {}
+
DoubleSolenoid::~DoubleSolenoid() {
- HAL_FreeSolenoidPort(m_forwardHandle);
- HAL_FreeSolenoidPort(m_reverseHandle);
+ m_module->UnreserveSolenoids(m_mask);
}
void DoubleSolenoid::Set(Value value) {
- if (StatusIsFatal()) return;
-
- bool forward = false;
- bool reverse = false;
+ int setValue = 0;
switch (value) {
case kOff:
- forward = false;
- reverse = false;
+ setValue = 0;
break;
case kForward:
- forward = true;
- reverse = false;
+ setValue = m_forwardMask;
break;
case kReverse:
- forward = false;
- reverse = true;
+ setValue = m_reverseMask;
break;
}
- int fstatus = 0;
- HAL_SetSolenoid(m_forwardHandle, forward, &fstatus);
- int rstatus = 0;
- HAL_SetSolenoid(m_reverseHandle, reverse, &rstatus);
-
- wpi_setHALError(fstatus);
- wpi_setHALError(rstatus);
+ m_module->SetSolenoids(m_mask, setValue);
}
DoubleSolenoid::Value DoubleSolenoid::Get() const {
- if (StatusIsFatal()) return kOff;
+ auto values = m_module->GetSolenoids();
- int fstatus = 0;
- int rstatus = 0;
- bool valueForward = HAL_GetSolenoid(m_forwardHandle, &fstatus);
- bool valueReverse = HAL_GetSolenoid(m_reverseHandle, &rstatus);
-
- wpi_setHALError(fstatus);
- wpi_setHALError(rstatus);
-
- if (valueForward) {
- return kForward;
- } else if (valueReverse) {
- return kReverse;
+ if ((values & m_forwardMask) != 0) {
+ return Value::kForward;
+ } else if ((values & m_reverseMask) != 0) {
+ return Value::kReverse;
} else {
- return kOff;
+ return Value::kOff;
}
}
@@ -147,23 +108,29 @@
}
}
-bool DoubleSolenoid::IsFwdSolenoidBlackListed() const {
- int blackList = GetPCMSolenoidBlackList(m_moduleNumber);
- return (blackList & m_forwardMask) != 0;
+int DoubleSolenoid::GetFwdChannel() const {
+ return m_forwardChannel;
}
-bool DoubleSolenoid::IsRevSolenoidBlackListed() const {
- int blackList = GetPCMSolenoidBlackList(m_moduleNumber);
- return (blackList & m_reverseMask) != 0;
+int DoubleSolenoid::GetRevChannel() const {
+ return m_reverseChannel;
}
-void DoubleSolenoid::InitSendable(SendableBuilder& builder) {
+bool DoubleSolenoid::IsFwdSolenoidDisabled() const {
+ return (m_module->GetSolenoidDisabledList() & m_forwardMask) != 0;
+}
+
+bool DoubleSolenoid::IsRevSolenoidDisabled() const {
+ return (m_module->GetSolenoidDisabledList() & m_reverseMask) != 0;
+}
+
+void DoubleSolenoid::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Double Solenoid");
builder.SetActuator(true);
- builder.SetSafeState([=]() { Set(kOff); });
+ builder.SetSafeState([=] { Set(kOff); });
builder.AddSmallStringProperty(
"Value",
- [=](wpi::SmallVectorImpl<char>& buf) -> wpi::StringRef {
+ [=](wpi::SmallVectorImpl<char>& buf) -> std::string_view {
switch (Get()) {
case kForward:
return "Forward";
@@ -173,12 +140,13 @@
return "Off";
}
},
- [=](wpi::StringRef value) {
+ [=](std::string_view value) {
Value lvalue = kOff;
- if (value == "Forward")
+ if (value == "Forward") {
lvalue = kForward;
- else if (value == "Reverse")
+ } else if (value == "Reverse") {
lvalue = kReverse;
+ }
Set(lvalue);
});
}
diff --git a/wpilibc/src/main/native/cpp/DriverStation.cpp b/wpilibc/src/main/native/cpp/DriverStation.cpp
index dbb99f9..37fc65f 100644
--- a/wpilibc/src/main/native/cpp/DriverStation.cpp
+++ b/wpilibc/src/main/native/cpp/DriverStation.cpp
@@ -1,69 +1,163 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DriverStation.h"
-#include <chrono>
+#include <stdint.h>
+#include <array>
+#include <atomic>
+#include <chrono>
+#include <string>
+#include <string_view>
+#include <thread>
+#include <type_traits>
+
+#include <fmt/format.h>
#include <hal/DriverStation.h>
+#include <hal/DriverStationTypes.h>
#include <hal/HALBase.h>
#include <hal/Power.h>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableInstance.h>
-#include <wpi/SmallString.h>
-#include <wpi/StringRef.h>
+#include <wpi/condition_variable.h>
+#include <wpi/mutex.h>
+#include "frc/Errors.h"
#include "frc/MotorSafety.h"
#include "frc/Timer.h"
-#include "frc/WPIErrors.h"
-
-namespace frc {
-
-class MatchDataSender {
- public:
- std::shared_ptr<nt::NetworkTable> table;
- nt::NetworkTableEntry typeMetadata;
- nt::NetworkTableEntry gameSpecificMessage;
- nt::NetworkTableEntry eventName;
- nt::NetworkTableEntry matchNumber;
- nt::NetworkTableEntry replayNumber;
- nt::NetworkTableEntry matchType;
- nt::NetworkTableEntry alliance;
- nt::NetworkTableEntry station;
- nt::NetworkTableEntry controlWord;
-
- MatchDataSender() {
- table = nt::NetworkTableInstance::GetDefault().GetTable("FMSInfo");
- typeMetadata = table->GetEntry(".type");
- typeMetadata.ForceSetString("FMSInfo");
- gameSpecificMessage = table->GetEntry("GameSpecificMessage");
- gameSpecificMessage.ForceSetString("");
- eventName = table->GetEntry("EventName");
- eventName.ForceSetString("");
- matchNumber = table->GetEntry("MatchNumber");
- matchNumber.ForceSetDouble(0);
- replayNumber = table->GetEntry("ReplayNumber");
- replayNumber.ForceSetDouble(0);
- matchType = table->GetEntry("MatchType");
- matchType.ForceSetDouble(0);
- alliance = table->GetEntry("IsRedAlliance");
- alliance.ForceSetBoolean(true);
- station = table->GetEntry("StationNumber");
- station.ForceSetDouble(1);
- controlWord = table->GetEntry("FMSControlData");
- controlWord.ForceSetDouble(0);
- }
-};
-} // namespace frc
using namespace frc;
-static constexpr double kJoystickUnpluggedMessageInterval = 1.0;
+namespace {
+// A simple class which caches the previous value written to an NT entry
+// Used to prevent redundant, repeated writes of the same value
+template <class T>
+class MatchDataSenderEntry {
+ public:
+ MatchDataSenderEntry(const std::shared_ptr<nt::NetworkTable>& table,
+ std::string_view key, const T& initialVal) {
+ static_assert(std::is_same_v<T, bool> || std::is_same_v<T, double> ||
+ std::is_same_v<T, std::string>,
+ "Invalid type for MatchDataSenderEntry - must be "
+ "to bool, double or std::string");
+
+ ntEntry = table->GetEntry(key);
+ if constexpr (std::is_same_v<T, bool>) {
+ ntEntry.ForceSetBoolean(initialVal);
+ } else if constexpr (std::is_same_v<T, double>) {
+ ntEntry.ForceSetDouble(initialVal);
+ } else if constexpr (std::is_same_v<T, std::string>) {
+ ntEntry.ForceSetString(initialVal);
+ }
+ prevVal = initialVal;
+ }
+
+ void Set(const T& val) {
+ if (val != prevVal) {
+ SetValue(val);
+ prevVal = val;
+ }
+ }
+
+ private:
+ nt::NetworkTableEntry ntEntry;
+ T prevVal;
+
+ void SetValue(bool val) { ntEntry.SetBoolean(val); }
+ void SetValue(double val) { ntEntry.SetDouble(val); }
+ void SetValue(std::string_view val) { ntEntry.SetString(val); }
+};
+
+struct MatchDataSender {
+ std::shared_ptr<nt::NetworkTable> table =
+ nt::NetworkTableInstance::GetDefault().GetTable("FMSInfo");
+ MatchDataSenderEntry<std::string> typeMetaData{table, ".type", "FMSInfo"};
+ MatchDataSenderEntry<std::string> gameSpecificMessage{
+ table, "GameSpecificMessage", ""};
+ MatchDataSenderEntry<std::string> eventName{table, "EventName", ""};
+ MatchDataSenderEntry<double> matchNumber{table, "MatchNumber", 0.0};
+ MatchDataSenderEntry<double> replayNumber{table, "ReplayNumber", 0.0};
+ MatchDataSenderEntry<double> matchType{table, "MatchType", 0.0};
+ MatchDataSenderEntry<bool> alliance{table, "IsRedAlliance", true};
+ MatchDataSenderEntry<double> station{table, "StationNumber", 1.0};
+ MatchDataSenderEntry<double> controlWord{table, "FMSControlData", 0.0};
+};
+
+struct Instance {
+ Instance();
+ ~Instance();
+
+ MatchDataSender matchDataSender;
+
+ // Joystick button rising/falling edge flags
+ wpi::mutex buttonEdgeMutex;
+ std::array<HAL_JoystickButtons, DriverStation::kJoystickPorts>
+ previousButtonStates;
+ std::array<uint32_t, DriverStation::kJoystickPorts> joystickButtonsPressed;
+ std::array<uint32_t, DriverStation::kJoystickPorts> joystickButtonsReleased;
+
+ // Internal Driver Station thread
+ std::thread dsThread;
+ std::atomic<bool> isRunning{false};
+
+ mutable wpi::mutex waitForDataMutex;
+ wpi::condition_variable waitForDataCond;
+ int waitForDataCounter = 0;
+
+ bool silenceJoystickWarning = false;
+
+ // Robot state status variables
+ bool userInDisabled = false;
+ bool userInAutonomous = false;
+ bool userInTeleop = false;
+ bool userInTest = false;
+
+ units::second_t nextMessageTime = 0_s;
+};
+} // namespace
+
+static constexpr auto kJoystickUnpluggedMessageInterval = 1_s;
+
+static Instance& GetInstance() {
+ static Instance instance;
+ return instance;
+}
+
+static void Run();
+static void SendMatchData();
+
+/**
+ * Reports errors related to unplugged joysticks.
+ *
+ * Throttles the errors so that they don't overwhelm the DS.
+ */
+static void ReportJoystickUnpluggedErrorV(fmt::string_view format,
+ fmt::format_args args);
+
+template <typename S, typename... Args>
+static inline void ReportJoystickUnpluggedError(const S& format,
+ Args&&... args) {
+ ReportJoystickUnpluggedErrorV(
+ format, fmt::make_args_checked<Args...>(format, args...));
+}
+
+/**
+ * Reports errors related to unplugged joysticks.
+ *
+ * Throttles the errors so that they don't overwhelm the DS.
+ */
+static void ReportJoystickUnpluggedWarningV(fmt::string_view format,
+ fmt::format_args args);
+
+template <typename S, typename... Args>
+static inline void ReportJoystickUnpluggedWarning(const S& format,
+ Args&&... args) {
+ ReportJoystickUnpluggedWarningV(
+ format, fmt::make_args_checked<Args...>(format, args...));
+}
static int& GetDSLastCount() {
// There is a rollover error condition here. At Packet# = n * (uintmax), this
@@ -74,51 +168,42 @@
return lastCount;
}
-DriverStation::~DriverStation() {
- m_isRunning = false;
+Instance::Instance() {
+ HAL_Initialize(500, 0);
+
+ // All joysticks should default to having zero axes, povs and buttons, so
+ // uninitialized memory doesn't get sent to motor controllers.
+ for (unsigned int i = 0; i < DriverStation::kJoystickPorts; i++) {
+ joystickButtonsPressed[i] = 0;
+ joystickButtonsReleased[i] = 0;
+ previousButtonStates[i].count = 0;
+ previousButtonStates[i].buttons = 0;
+ }
+
+ dsThread = std::thread(&Run);
+}
+
+Instance::~Instance() {
+ isRunning = false;
// Trigger a DS mutex release in case there is no driver station running.
HAL_ReleaseDSMutex();
- m_dsThread.join();
+ dsThread.join();
}
DriverStation& DriverStation::GetInstance() {
+ ::GetInstance();
static DriverStation instance;
return instance;
}
-void DriverStation::ReportError(const wpi::Twine& error) {
- wpi::SmallString<128> temp;
- HAL_SendError(1, 1, 0, error.toNullTerminatedStringRef(temp).data(), "", "",
- 1);
-}
-
-void DriverStation::ReportWarning(const wpi::Twine& error) {
- wpi::SmallString<128> temp;
- HAL_SendError(0, 1, 0, error.toNullTerminatedStringRef(temp).data(), "", "",
- 1);
-}
-
-void DriverStation::ReportError(bool isError, int32_t code,
- const wpi::Twine& error,
- const wpi::Twine& location,
- const wpi::Twine& stack) {
- wpi::SmallString<128> errorTemp;
- wpi::SmallString<128> locationTemp;
- wpi::SmallString<128> stackTemp;
- HAL_SendError(isError, code, 0,
- error.toNullTerminatedStringRef(errorTemp).data(),
- location.toNullTerminatedStringRef(locationTemp).data(),
- stack.toNullTerminatedStringRef(stackTemp).data(), 1);
-}
-
bool DriverStation::GetStickButton(int stick, int button) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return false;
}
if (button <= 0) {
ReportJoystickUnpluggedError(
- "ERROR: Button indexes begin at 1 in WPILib for C++ and Java");
+ "Joystick Button {} index out of range; indexes begin at 1", button);
return false;
}
@@ -127,7 +212,9 @@
if (button > buttons.count) {
ReportJoystickUnpluggedWarning(
- "Joystick Button missing, check if all controllers are plugged in");
+ "Joystick Button {} missing (max {}), check if all controllers are "
+ "plugged in",
+ button, buttons.count);
return false;
}
@@ -136,12 +223,12 @@
bool DriverStation::GetStickButtonPressed(int stick, int button) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return false;
}
if (button <= 0) {
ReportJoystickUnpluggedError(
- "ERROR: Button indexes begin at 1 in WPILib for C++ and Java");
+ "Joystick Button {} index out of range; indexes begin at 1", button);
return false;
}
@@ -150,27 +237,29 @@
if (button > buttons.count) {
ReportJoystickUnpluggedWarning(
- "Joystick Button missing, check if all controllers are plugged in");
+ "Joystick Button {} missing (max {}), check if all controllers are "
+ "plugged in",
+ button, buttons.count);
return false;
}
- std::unique_lock lock(m_buttonEdgeMutex);
+ auto& inst = ::GetInstance();
+ std::unique_lock lock(inst.buttonEdgeMutex);
// If button was pressed, clear flag and return true
- if (m_joystickButtonsPressed[stick] & 1 << (button - 1)) {
- m_joystickButtonsPressed[stick] &= ~(1 << (button - 1));
+ if (inst.joystickButtonsPressed[stick] & 1 << (button - 1)) {
+ inst.joystickButtonsPressed[stick] &= ~(1 << (button - 1));
return true;
- } else {
- return false;
}
+ return false;
}
bool DriverStation::GetStickButtonReleased(int stick, int button) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return false;
}
if (button <= 0) {
ReportJoystickUnpluggedError(
- "ERROR: Button indexes begin at 1 in WPILib for C++ and Java");
+ "Joystick Button {} index out of range; indexes begin at 1", button);
return false;
}
@@ -179,26 +268,28 @@
if (button > buttons.count) {
ReportJoystickUnpluggedWarning(
- "Joystick Button missing, check if all controllers are plugged in");
+ "Joystick Button {} missing (max {}), check if all controllers are "
+ "plugged in",
+ button, buttons.count);
return false;
}
- std::unique_lock lock(m_buttonEdgeMutex);
+ auto& inst = ::GetInstance();
+ std::unique_lock lock(inst.buttonEdgeMutex);
// If button was released, clear flag and return true
- if (m_joystickButtonsReleased[stick] & 1 << (button - 1)) {
- m_joystickButtonsReleased[stick] &= ~(1 << (button - 1));
+ if (inst.joystickButtonsReleased[stick] & 1 << (button - 1)) {
+ inst.joystickButtonsReleased[stick] &= ~(1 << (button - 1));
return true;
- } else {
- return false;
}
+ return false;
}
double DriverStation::GetStickAxis(int stick, int axis) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return 0.0;
}
if (axis < 0 || axis >= HAL_kMaxJoystickAxes) {
- wpi_setWPIError(BadJoystickAxis);
+ FRC_ReportError(warn::BadJoystickAxis, "axis {} out of range", axis);
return 0.0;
}
@@ -207,7 +298,9 @@
if (axis >= axes.count) {
ReportJoystickUnpluggedWarning(
- "Joystick Axis missing, check if all controllers are plugged in");
+ "Joystick Axis {} missing (max {}), check if all controllers are "
+ "plugged in",
+ axis, axes.count);
return 0.0;
}
@@ -216,11 +309,11 @@
int DriverStation::GetStickPOV(int stick, int pov) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return -1;
}
if (pov < 0 || pov >= HAL_kMaxJoystickPOVs) {
- wpi_setWPIError(BadJoystickAxis);
+ FRC_ReportError(warn::BadJoystickAxis, "POV {} out of range", pov);
return -1;
}
@@ -229,16 +322,18 @@
if (pov >= povs.count) {
ReportJoystickUnpluggedWarning(
- "Joystick POV missing, check if all controllers are plugged in");
+ "Joystick POV {} missing (max {}), check if all controllers are "
+ "plugged in",
+ pov, povs.count);
return -1;
}
return povs.povs[pov];
}
-int DriverStation::GetStickButtons(int stick) const {
+int DriverStation::GetStickButtons(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return 0;
}
@@ -248,9 +343,9 @@
return buttons.buttons;
}
-int DriverStation::GetStickAxisCount(int stick) const {
+int DriverStation::GetStickAxisCount(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return 0;
}
@@ -260,9 +355,9 @@
return axes.count;
}
-int DriverStation::GetStickPOVCount(int stick) const {
+int DriverStation::GetStickPOVCount(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return 0;
}
@@ -272,9 +367,9 @@
return povs.count;
}
-int DriverStation::GetStickButtonCount(int stick) const {
+int DriverStation::GetStickButtonCount(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return 0;
}
@@ -284,9 +379,9 @@
return buttons.count;
}
-bool DriverStation::GetJoystickIsXbox(int stick) const {
+bool DriverStation::GetJoystickIsXbox(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return false;
}
@@ -296,9 +391,9 @@
return static_cast<bool>(descriptor.isXbox);
}
-int DriverStation::GetJoystickType(int stick) const {
+int DriverStation::GetJoystickType(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return -1;
}
@@ -308,9 +403,9 @@
return static_cast<int>(descriptor.type);
}
-std::string DriverStation::GetJoystickName(int stick) const {
+std::string DriverStation::GetJoystickName(int stick) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
}
HAL_JoystickDescriptor descriptor;
@@ -319,9 +414,9 @@
return descriptor.name;
}
-int DriverStation::GetJoystickAxisType(int stick, int axis) const {
+int DriverStation::GetJoystickAxisType(int stick, int axis) {
if (stick < 0 || stick >= kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+ FRC_ReportError(warn::BadJoystickIndex, "stick {} out of range", stick);
return -1;
}
@@ -331,112 +426,123 @@
return static_cast<bool>(descriptor.axisTypes);
}
-bool DriverStation::IsJoystickConnected(int stick) const {
+bool DriverStation::IsJoystickConnected(int stick) {
return GetStickAxisCount(stick) > 0 || GetStickButtonCount(stick) > 0 ||
GetStickPOVCount(stick) > 0;
}
-bool DriverStation::IsEnabled() const {
+bool DriverStation::IsEnabled() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.enabled && controlWord.dsAttached;
}
-bool DriverStation::IsDisabled() const {
+bool DriverStation::IsDisabled() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return !(controlWord.enabled && controlWord.dsAttached);
}
-bool DriverStation::IsEStopped() const {
+bool DriverStation::IsEStopped() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.eStop;
}
-bool DriverStation::IsAutonomous() const {
+bool DriverStation::IsAutonomous() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.autonomous;
}
-bool DriverStation::IsAutonomousEnabled() const {
+bool DriverStation::IsAutonomousEnabled() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.autonomous && controlWord.enabled;
}
-bool DriverStation::IsOperatorControl() const {
+bool DriverStation::IsOperatorControl() {
+ return IsTeleop();
+}
+
+bool DriverStation::IsTeleop() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return !(controlWord.autonomous || controlWord.test);
}
-bool DriverStation::IsOperatorControlEnabled() const {
+bool DriverStation::IsOperatorControlEnabled() {
+ return IsTeleopEnabled();
+}
+
+bool DriverStation::IsTeleopEnabled() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return !controlWord.autonomous && !controlWord.test && controlWord.enabled;
}
-bool DriverStation::IsTest() const {
+bool DriverStation::IsTest() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.test;
}
-bool DriverStation::IsDSAttached() const {
+bool DriverStation::IsDSAttached() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.dsAttached;
}
-bool DriverStation::IsNewControlData() const {
- std::unique_lock lock(m_waitForDataMutex);
+bool DriverStation::IsNewControlData() {
+ auto& inst = ::GetInstance();
+ std::unique_lock lock(inst.waitForDataMutex);
int& lastCount = GetDSLastCount();
- int currentCount = m_waitForDataCounter;
- if (lastCount == currentCount) return false;
+ int currentCount = inst.waitForDataCounter;
+ if (lastCount == currentCount) {
+ return false;
+ }
lastCount = currentCount;
return true;
}
-bool DriverStation::IsFMSAttached() const {
+bool DriverStation::IsFMSAttached() {
HAL_ControlWord controlWord;
HAL_GetControlWord(&controlWord);
return controlWord.fmsAttached;
}
-std::string DriverStation::GetGameSpecificMessage() const {
+std::string DriverStation::GetGameSpecificMessage() {
HAL_MatchInfo info;
HAL_GetMatchInfo(&info);
return std::string(reinterpret_cast<char*>(info.gameSpecificMessage),
info.gameSpecificMessageSize);
}
-std::string DriverStation::GetEventName() const {
+std::string DriverStation::GetEventName() {
HAL_MatchInfo info;
HAL_GetMatchInfo(&info);
return info.eventName;
}
-DriverStation::MatchType DriverStation::GetMatchType() const {
+DriverStation::MatchType DriverStation::GetMatchType() {
HAL_MatchInfo info;
HAL_GetMatchInfo(&info);
return static_cast<DriverStation::MatchType>(info.matchType);
}
-int DriverStation::GetMatchNumber() const {
+int DriverStation::GetMatchNumber() {
HAL_MatchInfo info;
HAL_GetMatchInfo(&info);
return info.matchNumber;
}
-int DriverStation::GetReplayNumber() const {
+int DriverStation::GetReplayNumber() {
HAL_MatchInfo info;
HAL_GetMatchInfo(&info);
return info.replayNumber;
}
-DriverStation::Alliance DriverStation::GetAlliance() const {
+DriverStation::Alliance DriverStation::GetAlliance() {
int32_t status = 0;
auto allianceStationID = HAL_GetAllianceStation(&status);
switch (allianceStationID) {
@@ -453,7 +559,7 @@
}
}
-int DriverStation::GetLocation() const {
+int DriverStation::GetLocation() {
int32_t status = 0;
auto allianceStationID = HAL_GetAllianceStation(&status);
switch (allianceStationID) {
@@ -471,143 +577,171 @@
}
}
-void DriverStation::WaitForData() { WaitForData(0); }
+void DriverStation::WaitForData() {
+ WaitForData(0_s);
+}
-bool DriverStation::WaitForData(double timeout) {
- auto timeoutTime =
- std::chrono::steady_clock::now() + std::chrono::duration<double>(timeout);
+bool DriverStation::WaitForData(units::second_t timeout) {
+ auto& inst = ::GetInstance();
+ auto timeoutTime = std::chrono::steady_clock::now() +
+ std::chrono::steady_clock::duration{timeout};
- std::unique_lock lock(m_waitForDataMutex);
+ std::unique_lock lock(inst.waitForDataMutex);
int& lastCount = GetDSLastCount();
- int currentCount = m_waitForDataCounter;
+ int currentCount = inst.waitForDataCounter;
if (lastCount != currentCount) {
lastCount = currentCount;
return true;
}
- while (m_waitForDataCounter == currentCount) {
- if (timeout > 0) {
- auto timedOut = m_waitForDataCond.wait_until(lock, timeoutTime);
+ while (inst.waitForDataCounter == currentCount) {
+ if (timeout > 0_s) {
+ auto timedOut = inst.waitForDataCond.wait_until(lock, timeoutTime);
if (timedOut == std::cv_status::timeout) {
return false;
}
} else {
- m_waitForDataCond.wait(lock);
+ inst.waitForDataCond.wait(lock);
}
}
- lastCount = m_waitForDataCounter;
+ lastCount = inst.waitForDataCounter;
return true;
}
-double DriverStation::GetMatchTime() const {
- int32_t status;
+double DriverStation::GetMatchTime() {
+ int32_t status = 0;
return HAL_GetMatchTime(&status);
}
-double DriverStation::GetBatteryVoltage() const {
+double DriverStation::GetBatteryVoltage() {
int32_t status = 0;
double voltage = HAL_GetVinVoltage(&status);
- wpi_setErrorWithContext(status, "getVinVoltage");
+ FRC_CheckErrorStatus(status, "{}", "getVinVoltage");
return voltage;
}
-void DriverStation::WakeupWaitForData() {
- std::scoped_lock waitLock(m_waitForDataMutex);
- // Nofify all threads
- m_waitForDataCounter++;
- m_waitForDataCond.notify_all();
+void DriverStation::InDisabled(bool entering) {
+ ::GetInstance().userInDisabled = entering;
}
-void DriverStation::GetData() {
+void DriverStation::InAutonomous(bool entering) {
+ ::GetInstance().userInAutonomous = entering;
+}
+
+void DriverStation::InOperatorControl(bool entering) {
+ InTeleop(entering);
+}
+
+void DriverStation::InTeleop(bool entering) {
+ ::GetInstance().userInTeleop = entering;
+}
+
+void DriverStation::InTest(bool entering) {
+ ::GetInstance().userInTest = entering;
+}
+
+void DriverStation::WakeupWaitForData() {
+ auto& inst = ::GetInstance();
+ std::scoped_lock waitLock(inst.waitForDataMutex);
+ // Nofify all threads
+ inst.waitForDataCounter++;
+ inst.waitForDataCond.notify_all();
+}
+
+/**
+ * Copy data from the DS task for the user.
+ *
+ * If no new data exists, it will just be returned, otherwise
+ * the data will be copied from the DS polling loop.
+ */
+void GetData() {
+ auto& inst = ::GetInstance();
{
// Compute the pressed and released buttons
HAL_JoystickButtons currentButtons;
- std::unique_lock lock(m_buttonEdgeMutex);
+ std::unique_lock lock(inst.buttonEdgeMutex);
- for (int32_t i = 0; i < kJoystickPorts; i++) {
+ for (int32_t i = 0; i < DriverStation::kJoystickPorts; i++) {
HAL_GetJoystickButtons(i, ¤tButtons);
// If buttons weren't pressed and are now, set flags in m_buttonsPressed
- m_joystickButtonsPressed[i] |=
- ~m_previousButtonStates[i].buttons & currentButtons.buttons;
+ inst.joystickButtonsPressed[i] |=
+ ~inst.previousButtonStates[i].buttons & currentButtons.buttons;
// If buttons were pressed and aren't now, set flags in m_buttonsReleased
- m_joystickButtonsReleased[i] |=
- m_previousButtonStates[i].buttons & ~currentButtons.buttons;
+ inst.joystickButtonsReleased[i] |=
+ inst.previousButtonStates[i].buttons & ~currentButtons.buttons;
- m_previousButtonStates[i] = currentButtons;
+ inst.previousButtonStates[i] = currentButtons;
}
}
- WakeupWaitForData();
+ DriverStation::WakeupWaitForData();
SendMatchData();
}
void DriverStation::SilenceJoystickConnectionWarning(bool silence) {
- m_silenceJoystickWarning = silence;
+ ::GetInstance().silenceJoystickWarning = silence;
}
-bool DriverStation::IsJoystickConnectionWarningSilenced() const {
- return !IsFMSAttached() && m_silenceJoystickWarning;
+bool DriverStation::IsJoystickConnectionWarningSilenced() {
+ return !IsFMSAttached() && ::GetInstance().silenceJoystickWarning;
}
-DriverStation::DriverStation() {
- HAL_Initialize(500, 0);
- m_waitForDataCounter = 0;
-
- m_matchDataSender = std::make_unique<MatchDataSender>();
-
- // All joysticks should default to having zero axes, povs and buttons, so
- // uninitialized memory doesn't get sent to speed controllers.
- for (unsigned int i = 0; i < kJoystickPorts; i++) {
- m_joystickButtonsPressed[i] = 0;
- m_joystickButtonsReleased[i] = 0;
- m_previousButtonStates[i].count = 0;
- m_previousButtonStates[i].buttons = 0;
- }
-
- m_dsThread = std::thread(&DriverStation::Run, this);
-}
-
-void DriverStation::ReportJoystickUnpluggedError(const wpi::Twine& message) {
- double currentTime = Timer::GetFPGATimestamp();
- if (currentTime > m_nextMessageTime) {
- ReportError(message);
- m_nextMessageTime = currentTime + kJoystickUnpluggedMessageInterval;
+void ReportJoystickUnpluggedErrorV(fmt::string_view format,
+ fmt::format_args args) {
+ auto& inst = GetInstance();
+ auto currentTime = Timer::GetFPGATimestamp();
+ if (currentTime > inst.nextMessageTime) {
+ ReportErrorV(err::Error, "", 0, "", format, args);
+ inst.nextMessageTime = currentTime + kJoystickUnpluggedMessageInterval;
}
}
-void DriverStation::ReportJoystickUnpluggedWarning(const wpi::Twine& message) {
- if (IsFMSAttached() || !m_silenceJoystickWarning) {
- double currentTime = Timer::GetFPGATimestamp();
- if (currentTime > m_nextMessageTime) {
- ReportWarning(message);
- m_nextMessageTime = currentTime + kJoystickUnpluggedMessageInterval;
+void ReportJoystickUnpluggedWarningV(fmt::string_view format,
+ fmt::format_args args) {
+ auto& inst = GetInstance();
+ if (DriverStation::IsFMSAttached() || !inst.silenceJoystickWarning) {
+ auto currentTime = Timer::GetFPGATimestamp();
+ if (currentTime > inst.nextMessageTime) {
+ ReportErrorV(warn::Warning, "", 0, "", format, args);
+ inst.nextMessageTime = currentTime + kJoystickUnpluggedMessageInterval;
}
}
}
-void DriverStation::Run() {
- m_isRunning = true;
+void Run() {
+ auto& inst = GetInstance();
+ inst.isRunning = true;
int safetyCounter = 0;
- while (m_isRunning) {
+ while (inst.isRunning) {
HAL_WaitForDSData();
GetData();
- if (IsDisabled()) safetyCounter = 0;
+ if (DriverStation::IsDisabled()) {
+ safetyCounter = 0;
+ }
if (++safetyCounter >= 4) {
MotorSafety::CheckMotors();
safetyCounter = 0;
}
- if (m_userInDisabled) HAL_ObserveUserProgramDisabled();
- if (m_userInAutonomous) HAL_ObserveUserProgramAutonomous();
- if (m_userInTeleop) HAL_ObserveUserProgramTeleop();
- if (m_userInTest) HAL_ObserveUserProgramTest();
+ if (inst.userInDisabled) {
+ HAL_ObserveUserProgramDisabled();
+ }
+ if (inst.userInAutonomous) {
+ HAL_ObserveUserProgramAutonomous();
+ }
+ if (inst.userInTeleop) {
+ HAL_ObserveUserProgramTeleop();
+ }
+ if (inst.userInTest) {
+ HAL_ObserveUserProgramTest();
+ }
}
}
-void DriverStation::SendMatchData() {
+void SendMatchData() {
int32_t status = 0;
HAL_AllianceStationID alliance = HAL_GetAllianceStation(&status);
bool isRedAlliance = false;
@@ -642,20 +776,20 @@
HAL_MatchInfo tmpDataStore;
HAL_GetMatchInfo(&tmpDataStore);
- m_matchDataSender->alliance.SetBoolean(isRedAlliance);
- m_matchDataSender->station.SetDouble(stationNumber);
- m_matchDataSender->eventName.SetString(tmpDataStore.eventName);
- m_matchDataSender->gameSpecificMessage.SetString(
+ auto& inst = GetInstance();
+ inst.matchDataSender.alliance.Set(isRedAlliance);
+ inst.matchDataSender.station.Set(stationNumber);
+ inst.matchDataSender.eventName.Set(tmpDataStore.eventName);
+ inst.matchDataSender.gameSpecificMessage.Set(
std::string(reinterpret_cast<char*>(tmpDataStore.gameSpecificMessage),
tmpDataStore.gameSpecificMessageSize));
- m_matchDataSender->matchNumber.SetDouble(tmpDataStore.matchNumber);
- m_matchDataSender->replayNumber.SetDouble(tmpDataStore.replayNumber);
- m_matchDataSender->matchType.SetDouble(
- static_cast<int>(tmpDataStore.matchType));
+ inst.matchDataSender.matchNumber.Set(tmpDataStore.matchNumber);
+ inst.matchDataSender.replayNumber.Set(tmpDataStore.replayNumber);
+ inst.matchDataSender.matchType.Set(static_cast<int>(tmpDataStore.matchType));
HAL_ControlWord ctlWord;
HAL_GetControlWord(&ctlWord);
int32_t wordInt = 0;
std::memcpy(&wordInt, &ctlWord, sizeof(wordInt));
- m_matchDataSender->controlWord.SetDouble(wordInt);
+ inst.matchDataSender.controlWord.Set(wordInt);
}
diff --git a/wpilibc/src/main/native/cpp/DutyCycle.cpp b/wpilibc/src/main/native/cpp/DutyCycle.cpp
index 7e4e98d..a8375e0 100644
--- a/wpilibc/src/main/native/cpp/DutyCycle.cpp
+++ b/wpilibc/src/main/native/cpp/DutyCycle.cpp
@@ -1,46 +1,43 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DutyCycle.h"
#include <hal/DutyCycle.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
-#include "frc/Base.h"
#include "frc/DigitalSource.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
+#include "frc/Errors.h"
using namespace frc;
DutyCycle::DutyCycle(DigitalSource* source)
- : m_source{source, NullDeleter<DigitalSource>()} {
- if (m_source == nullptr) {
- wpi_setWPIError(NullParameter);
- } else {
- InitDutyCycle();
+ : m_source{source, wpi::NullDeleter<DigitalSource>()} {
+ if (!m_source) {
+ throw FRC_MakeError(err::NullParameter, "{}", "source");
}
+ InitDutyCycle();
}
DutyCycle::DutyCycle(DigitalSource& source)
- : m_source{&source, NullDeleter<DigitalSource>()} {
+ : m_source{&source, wpi::NullDeleter<DigitalSource>()} {
InitDutyCycle();
}
DutyCycle::DutyCycle(std::shared_ptr<DigitalSource> source)
: m_source{std::move(source)} {
- if (m_source == nullptr) {
- wpi_setWPIError(NullParameter);
- } else {
- InitDutyCycle();
+ if (!m_source) {
+ throw FRC_MakeError(err::NullParameter, "{}", "source");
}
+ InitDutyCycle();
}
-DutyCycle::~DutyCycle() { HAL_FreeDutyCycle(m_handle); }
+DutyCycle::~DutyCycle() {
+ HAL_FreeDutyCycle(m_handle);
+}
void DutyCycle::InitDutyCycle() {
int32_t status = 0;
@@ -49,50 +46,52 @@
static_cast<HAL_AnalogTriggerType>(
m_source->GetAnalogTriggerTypeForRouting()),
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
int index = GetFPGAIndex();
HAL_Report(HALUsageReporting::kResourceType_DutyCycle, index + 1);
- SendableRegistry::GetInstance().AddLW(this, "Duty Cycle", index);
+ wpi::SendableRegistry::AddLW(this, "Duty Cycle", index);
}
int DutyCycle::GetFPGAIndex() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleFPGAIndex(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return retVal;
}
int DutyCycle::GetFrequency() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleFrequency(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return retVal;
}
double DutyCycle::GetOutput() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleOutput(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return retVal;
}
unsigned int DutyCycle::GetOutputRaw() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleOutputRaw(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return retVal;
}
unsigned int DutyCycle::GetOutputScaleFactor() const {
int32_t status = 0;
auto retVal = HAL_GetDutyCycleOutputScaleFactor(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", GetSourceChannel());
return retVal;
}
-int DutyCycle::GetSourceChannel() const { return m_source->GetChannel(); }
+int DutyCycle::GetSourceChannel() const {
+ return m_source->GetChannel();
+}
-void DutyCycle::InitSendable(SendableBuilder& builder) {
+void DutyCycle::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Duty Cycle");
builder.AddDoubleProperty(
"Frequency", [this] { return this->GetFrequency(); }, nullptr);
diff --git a/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp b/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp
index 4fc5457..8e994e9 100644
--- a/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp
+++ b/wpilibc/src/main/native/cpp/DutyCycleEncoder.cpp
@@ -1,19 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/DutyCycleEncoder.h"
-#include "frc/Base.h"
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+
#include "frc/Counter.h"
#include "frc/DigitalInput.h"
#include "frc/DigitalSource.h"
-#include "frc/DriverStation.h"
#include "frc/DutyCycle.h"
-#include "frc/smartdashboard/SendableBuilder.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -24,12 +22,12 @@
}
DutyCycleEncoder::DutyCycleEncoder(DutyCycle& dutyCycle)
- : m_dutyCycle{&dutyCycle, NullDeleter<DutyCycle>{}} {
+ : m_dutyCycle{&dutyCycle, wpi::NullDeleter<DutyCycle>{}} {
Init();
}
DutyCycleEncoder::DutyCycleEncoder(DutyCycle* dutyCycle)
- : m_dutyCycle{dutyCycle, NullDeleter<DutyCycle>{}} {
+ : m_dutyCycle{dutyCycle, wpi::NullDeleter<DutyCycle>{}} {
Init();
}
@@ -54,13 +52,16 @@
}
void DutyCycleEncoder::Init() {
- m_simDevice = hal::SimDevice{"DutyCycleEncoder", m_dutyCycle->GetFPGAIndex()};
+ m_simDevice = hal::SimDevice{"DutyCycle:DutyCycleEncoder",
+ m_dutyCycle->GetSourceChannel()};
if (m_simDevice) {
- m_simPosition = m_simDevice.CreateDouble("Position", false, 0.0);
- m_simDistancePerRotation =
- m_simDevice.CreateDouble("DistancePerRotation", false, 1.0);
- m_simIsConnected = m_simDevice.CreateBoolean("Connected", false, true);
+ m_simPosition =
+ m_simDevice.CreateDouble("position", hal::SimDevice::kInput, 0.0);
+ m_simDistancePerRotation = m_simDevice.CreateDouble(
+ "distance_per_rot", hal::SimDevice::kOutput, 1.0);
+ m_simIsConnected =
+ m_simDevice.CreateBoolean("connected", hal::SimDevice::kInput, true);
} else {
m_analogTrigger = std::make_unique<AnalogTrigger>(m_dutyCycle.get());
m_analogTrigger->SetLimitsDutyCycle(0.25, 0.75);
@@ -71,12 +72,14 @@
m_analogTrigger->CreateOutput(AnalogTriggerType::kFallingPulse));
}
- SendableRegistry::GetInstance().AddLW(this, "DutyCycle Encoder",
- m_dutyCycle->GetSourceChannel());
+ wpi::SendableRegistry::AddLW(this, "DutyCycle Encoder",
+ m_dutyCycle->GetSourceChannel());
}
units::turn_t DutyCycleEncoder::Get() const {
- if (m_simPosition) return units::turn_t{m_simPosition.Get()};
+ if (m_simPosition) {
+ return units::turn_t{m_simPosition.Get()};
+ }
// As the values are not atomic, keep trying until we get 2 reads of the same
// value If we don't within 10 attempts, error
@@ -92,7 +95,8 @@
}
}
- frc::DriverStation::GetInstance().ReportWarning(
+ FRC_ReportError(
+ warn::Warning, "{}",
"Failed to read DutyCycle Encoder. Potential Speed Overrun. Returning "
"last value");
return m_lastPosition;
@@ -108,7 +112,7 @@
}
double DutyCycleEncoder::GetDistance() const {
- return Get().to<double>() * GetDistancePerRotation();
+ return Get().value() * GetDistancePerRotation();
}
int DutyCycleEncoder::GetFrequency() const {
@@ -116,12 +120,16 @@
}
void DutyCycleEncoder::Reset() {
- if (m_counter) m_counter->Reset();
+ if (m_counter) {
+ m_counter->Reset();
+ }
m_positionOffset = m_dutyCycle->GetOutput();
}
bool DutyCycleEncoder::IsConnected() const {
- if (m_simIsConnected) return m_simIsConnected.Get();
+ if (m_simIsConnected) {
+ return m_simIsConnected.Get();
+ }
return GetFrequency() > m_frequencyThreshold;
}
@@ -140,7 +148,7 @@
return m_dutyCycle->GetSourceChannel();
}
-void DutyCycleEncoder::InitSendable(SendableBuilder& builder) {
+void DutyCycleEncoder::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("AbsoluteEncoder");
builder.AddDoubleProperty(
"Distance", [this] { return this->GetDistance(); }, nullptr);
diff --git a/wpilibc/src/main/native/cpp/Encoder.cpp b/wpilibc/src/main/native/cpp/Encoder.cpp
index 87bb45f..bef6d76 100644
--- a/wpilibc/src/main/native/cpp/Encoder.cpp
+++ b/wpilibc/src/main/native/cpp/Encoder.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Encoder.h"
@@ -11,12 +8,12 @@
#include <hal/Encoder.h>
#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/Base.h"
#include "frc/DigitalInput.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -25,196 +22,177 @@
m_aSource = std::make_shared<DigitalInput>(aChannel);
m_bSource = std::make_shared<DigitalInput>(bChannel);
InitEncoder(reverseDirection, encodingType);
- auto& registry = SendableRegistry::GetInstance();
- registry.AddChild(this, m_aSource.get());
- registry.AddChild(this, m_bSource.get());
+ wpi::SendableRegistry::AddChild(this, m_aSource.get());
+ wpi::SendableRegistry::AddChild(this, m_bSource.get());
}
Encoder::Encoder(DigitalSource* aSource, DigitalSource* bSource,
bool reverseDirection, EncodingType encodingType)
- : m_aSource(aSource, NullDeleter<DigitalSource>()),
- m_bSource(bSource, NullDeleter<DigitalSource>()) {
- if (m_aSource == nullptr || m_bSource == nullptr)
- wpi_setWPIError(NullParameter);
- else
- InitEncoder(reverseDirection, encodingType);
+ : m_aSource(aSource, wpi::NullDeleter<DigitalSource>()),
+ m_bSource(bSource, wpi::NullDeleter<DigitalSource>()) {
+ if (!m_aSource) {
+ throw FRC_MakeError(err::NullParameter, "{}", "aSource");
+ }
+ if (!m_bSource) {
+ throw FRC_MakeError(err::NullParameter, "{}", "bSource");
+ }
+ InitEncoder(reverseDirection, encodingType);
}
Encoder::Encoder(DigitalSource& aSource, DigitalSource& bSource,
bool reverseDirection, EncodingType encodingType)
- : m_aSource(&aSource, NullDeleter<DigitalSource>()),
- m_bSource(&bSource, NullDeleter<DigitalSource>()) {
+ : m_aSource(&aSource, wpi::NullDeleter<DigitalSource>()),
+ m_bSource(&bSource, wpi::NullDeleter<DigitalSource>()) {
InitEncoder(reverseDirection, encodingType);
}
Encoder::Encoder(std::shared_ptr<DigitalSource> aSource,
std::shared_ptr<DigitalSource> bSource, bool reverseDirection,
EncodingType encodingType)
- : m_aSource(aSource), m_bSource(bSource) {
- if (m_aSource == nullptr || m_bSource == nullptr)
- wpi_setWPIError(NullParameter);
- else
- InitEncoder(reverseDirection, encodingType);
+ : m_aSource(std::move(aSource)), m_bSource(std::move(bSource)) {
+ if (!m_aSource) {
+ throw FRC_MakeError(err::NullParameter, "{}", "aSource");
+ }
+ if (!m_bSource) {
+ throw FRC_MakeError(err::NullParameter, "{}", "bSource");
+ }
+ InitEncoder(reverseDirection, encodingType);
}
Encoder::~Encoder() {
int32_t status = 0;
HAL_FreeEncoder(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_ReportError(status, "{}", "FreeEncoder");
}
int Encoder::Get() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int value = HAL_GetEncoder(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Get");
return value;
}
void Encoder::Reset() {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_ResetEncoder(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Reset");
}
-double Encoder::GetPeriod() const {
- if (StatusIsFatal()) return 0.0;
+units::second_t Encoder::GetPeriod() const {
int32_t status = 0;
double value = HAL_GetEncoderPeriod(m_encoder, &status);
- wpi_setHALError(status);
- return value;
+ FRC_CheckErrorStatus(status, "{}", "GetPeriod");
+ return units::second_t{value};
}
-void Encoder::SetMaxPeriod(double maxPeriod) {
- if (StatusIsFatal()) return;
+void Encoder::SetMaxPeriod(units::second_t maxPeriod) {
int32_t status = 0;
- HAL_SetEncoderMaxPeriod(m_encoder, maxPeriod, &status);
- wpi_setHALError(status);
+ HAL_SetEncoderMaxPeriod(m_encoder, maxPeriod.value(), &status);
+ FRC_CheckErrorStatus(status, "{}", "SetMaxPeriod");
}
bool Encoder::GetStopped() const {
- if (StatusIsFatal()) return true;
int32_t status = 0;
bool value = HAL_GetEncoderStopped(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetStopped");
return value;
}
bool Encoder::GetDirection() const {
- if (StatusIsFatal()) return false;
int32_t status = 0;
bool value = HAL_GetEncoderDirection(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetDirection");
return value;
}
int Encoder::GetRaw() const {
- if (StatusIsFatal()) return 0;
int32_t status = 0;
int value = HAL_GetEncoderRaw(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetRaw");
return value;
}
int Encoder::GetEncodingScale() const {
int32_t status = 0;
int val = HAL_GetEncoderEncodingScale(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetEncodingScale");
return val;
}
double Encoder::GetDistance() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double value = HAL_GetEncoderDistance(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetDistance");
return value;
}
double Encoder::GetRate() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double value = HAL_GetEncoderRate(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetRate");
return value;
}
void Encoder::SetMinRate(double minRate) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetEncoderMinRate(m_encoder, minRate, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetMinRate");
}
void Encoder::SetDistancePerPulse(double distancePerPulse) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetEncoderDistancePerPulse(m_encoder, distancePerPulse, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetDistancePerPulse");
}
double Encoder::GetDistancePerPulse() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double distancePerPulse = HAL_GetEncoderDistancePerPulse(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetDistancePerPulse");
return distancePerPulse;
}
void Encoder::SetReverseDirection(bool reverseDirection) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetEncoderReverseDirection(m_encoder, reverseDirection, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetReverseDirection");
}
void Encoder::SetSamplesToAverage(int samplesToAverage) {
if (samplesToAverage < 1 || samplesToAverage > 127) {
- wpi_setWPIErrorWithContext(
- ParameterOutOfRange,
- "Average counter values must be between 1 and 127");
- return;
+ throw FRC_MakeError(
+ err::ParameterOutOfRange,
+ "Average counter values must be between 1 and 127, got {}",
+ samplesToAverage);
}
int32_t status = 0;
HAL_SetEncoderSamplesToAverage(m_encoder, samplesToAverage, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetSamplesToAverage");
}
int Encoder::GetSamplesToAverage() const {
int32_t status = 0;
int result = HAL_GetEncoderSamplesToAverage(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetSamplesToAverage");
return result;
}
-double Encoder::PIDGet() {
- if (StatusIsFatal()) return 0.0;
- switch (GetPIDSourceType()) {
- case PIDSourceType::kDisplacement:
- return GetDistance();
- case PIDSourceType::kRate:
- return GetRate();
- default:
- return 0.0;
- }
-}
-
void Encoder::SetIndexSource(int channel, Encoder::IndexingType type) {
// Force digital input if just given an index
m_indexSource = std::make_shared<DigitalInput>(channel);
- SendableRegistry::GetInstance().AddChild(this, m_indexSource.get());
+ wpi::SendableRegistry::AddChild(this, m_indexSource.get());
SetIndexSource(*m_indexSource.get(), type);
}
void Encoder::SetIndexSource(const DigitalSource& source,
Encoder::IndexingType type) {
int32_t status = 0;
- HAL_SetEncoderIndexSource(
- m_encoder, source.GetPortHandleForRouting(),
- (HAL_AnalogTriggerType)source.GetAnalogTriggerTypeForRouting(),
- (HAL_EncoderIndexingType)type, &status);
- wpi_setHALError(status);
+ HAL_SetEncoderIndexSource(m_encoder, source.GetPortHandleForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ source.GetAnalogTriggerTypeForRouting()),
+ static_cast<HAL_EncoderIndexingType>(type),
+ &status);
+ FRC_CheckErrorStatus(status, "{}", "SetIndexSource");
}
void Encoder::SetSimDevice(HAL_SimDeviceHandle device) {
@@ -224,47 +202,49 @@
int Encoder::GetFPGAIndex() const {
int32_t status = 0;
int val = HAL_GetEncoderFPGAIndex(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFPGAIndex");
return val;
}
-void Encoder::InitSendable(SendableBuilder& builder) {
+void Encoder::InitSendable(wpi::SendableBuilder& builder) {
int32_t status = 0;
HAL_EncoderEncodingType type = HAL_GetEncoderEncodingType(m_encoder, &status);
- wpi_setHALError(status);
- if (type == HAL_EncoderEncodingType::HAL_Encoder_k4X)
+ FRC_CheckErrorStatus(status, "{}", "GetEncodingType");
+ if (type == HAL_EncoderEncodingType::HAL_Encoder_k4X) {
builder.SetSmartDashboardType("Quadrature Encoder");
- else
+ } else {
builder.SetSmartDashboardType("Encoder");
+ }
builder.AddDoubleProperty(
- "Speed", [=]() { return GetRate(); }, nullptr);
+ "Speed", [=] { return GetRate(); }, nullptr);
builder.AddDoubleProperty(
- "Distance", [=]() { return GetDistance(); }, nullptr);
+ "Distance", [=] { return GetDistance(); }, nullptr);
builder.AddDoubleProperty(
- "Distance per Tick", [=]() { return GetDistancePerPulse(); }, nullptr);
+ "Distance per Tick", [=] { return GetDistancePerPulse(); }, nullptr);
}
void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) {
int32_t status = 0;
m_encoder = HAL_InitializeEncoder(
m_aSource->GetPortHandleForRouting(),
- (HAL_AnalogTriggerType)m_aSource->GetAnalogTriggerTypeForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ m_aSource->GetAnalogTriggerTypeForRouting()),
m_bSource->GetPortHandleForRouting(),
- (HAL_AnalogTriggerType)m_bSource->GetAnalogTriggerTypeForRouting(),
- reverseDirection, (HAL_EncoderEncodingType)encodingType, &status);
- wpi_setHALError(status);
+ static_cast<HAL_AnalogTriggerType>(
+ m_bSource->GetAnalogTriggerTypeForRouting()),
+ reverseDirection, static_cast<HAL_EncoderEncodingType>(encodingType),
+ &status);
+ FRC_CheckErrorStatus(status, "{}", "InitEncoder");
HAL_Report(HALUsageReporting::kResourceType_Encoder, GetFPGAIndex() + 1,
encodingType);
- SendableRegistry::GetInstance().AddLW(this, "Encoder",
- m_aSource->GetChannel());
+ wpi::SendableRegistry::AddLW(this, "Encoder", m_aSource->GetChannel());
}
double Encoder::DecodingScaleFactor() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double val = HAL_GetEncoderDecodingScaleFactor(m_encoder, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "DecodingScaleFactor");
return val;
}
diff --git a/wpilibc/src/main/native/cpp/Error.cpp b/wpilibc/src/main/native/cpp/Error.cpp
deleted file mode 100644
index 5e072c9..0000000
--- a/wpilibc/src/main/native/cpp/Error.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/Error.h"
-
-#include <wpi/Path.h>
-#include <wpi/StackTrace.h>
-
-#include "frc/Base.h"
-#include "frc/DriverStation.h"
-#include "frc/Timer.h"
-
-using namespace frc;
-
-Error::Error(Code code, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function, int lineNumber,
- const ErrorBase* originatingObject) {
- Set(code, contextMessage, filename, function, lineNumber, originatingObject);
-}
-
-bool Error::operator<(const Error& rhs) const {
- if (m_code < rhs.m_code) {
- return true;
- } else if (m_message < rhs.m_message) {
- return true;
- } else if (m_filename < rhs.m_filename) {
- return true;
- } else if (m_function < rhs.m_function) {
- return true;
- } else if (m_lineNumber < rhs.m_lineNumber) {
- return true;
- } else if (m_originatingObject < rhs.m_originatingObject) {
- return true;
- } else if (m_timestamp < rhs.m_timestamp) {
- return true;
- } else {
- return false;
- }
-}
-
-Error::Code Error::GetCode() const { return m_code; }
-
-std::string Error::GetMessage() const { return m_message; }
-
-std::string Error::GetFilename() const { return m_filename; }
-
-std::string Error::GetFunction() const { return m_function; }
-
-int Error::GetLineNumber() const { return m_lineNumber; }
-
-const ErrorBase* Error::GetOriginatingObject() const {
- return m_originatingObject;
-}
-
-double Error::GetTimestamp() const { return m_timestamp; }
-
-void Error::Set(Code code, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber, const ErrorBase* originatingObject) {
- bool report = true;
-
- if (code == m_code && GetTime() - m_timestamp < 1) {
- report = false;
- }
-
- m_code = code;
- m_message = contextMessage.str();
- m_filename = filename;
- m_function = function;
- m_lineNumber = lineNumber;
- m_originatingObject = originatingObject;
-
- if (report) {
- m_timestamp = GetTime();
- Report();
- }
-}
-
-void Error::Report() {
- DriverStation::ReportError(
- true, m_code, m_message,
- m_function + wpi::Twine(" [") + wpi::sys::path::filename(m_filename) +
- wpi::Twine(':') + wpi::Twine(m_lineNumber) + wpi::Twine(']'),
- wpi::GetStackTrace(4));
-}
-
-void Error::Clear() {
- m_code = 0;
- m_message = "";
- m_filename = "";
- m_function = "";
- m_lineNumber = 0;
- m_originatingObject = nullptr;
- m_timestamp = 0.0;
-}
diff --git a/wpilibc/src/main/native/cpp/ErrorBase.cpp b/wpilibc/src/main/native/cpp/ErrorBase.cpp
deleted file mode 100644
index 8c7c5a2..0000000
--- a/wpilibc/src/main/native/cpp/ErrorBase.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/ErrorBase.h"
-
-#include <cerrno>
-#include <cstring>
-#include <set>
-#include <utility>
-
-#include <hal/HALBase.h>
-#include <wpi/Format.h>
-#include <wpi/SmallString.h>
-#include <wpi/mutex.h>
-#include <wpi/raw_ostream.h>
-
-#include "frc/Base.h"
-
-using namespace frc;
-
-namespace {
-struct GlobalErrors {
- wpi::mutex mutex;
- std::set<Error> errors;
- const Error* lastError{nullptr};
-
- static GlobalErrors& GetInstance();
- static void Insert(const Error& error);
- static void Insert(Error&& error);
-};
-} // namespace
-
-GlobalErrors& GlobalErrors::GetInstance() {
- static GlobalErrors inst;
- return inst;
-}
-
-void GlobalErrors::Insert(const Error& error) {
- GlobalErrors& inst = GetInstance();
- std::scoped_lock lock(inst.mutex);
- inst.lastError = &(*inst.errors.insert(error).first);
-}
-
-void GlobalErrors::Insert(Error&& error) {
- GlobalErrors& inst = GetInstance();
- std::scoped_lock lock(inst.mutex);
- inst.lastError = &(*inst.errors.insert(std::move(error)).first);
-}
-
-ErrorBase::ErrorBase() { HAL_Initialize(500, 0); }
-
-Error& ErrorBase::GetError() { return m_error; }
-
-const Error& ErrorBase::GetError() const { return m_error; }
-
-void ErrorBase::ClearError() const { m_error.Clear(); }
-
-void ErrorBase::SetErrnoError(const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const {
- wpi::SmallString<128> buf;
- wpi::raw_svector_ostream err(buf);
- int errNo = errno;
- if (errNo == 0) {
- err << "OK: ";
- } else {
- err << std::strerror(errNo) << " (" << wpi::format_hex(errNo, 10, true)
- << "): ";
- }
-
- // Set the current error information for this object.
- m_error.Set(-1, err.str() + contextMessage, filename, function, lineNumber,
- this);
-
- // Update the global error if there is not one already set.
- GlobalErrors::Insert(m_error);
-}
-
-void ErrorBase::SetImaqError(int success, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const {
- // If there was an error
- if (success <= 0) {
- // Set the current error information for this object.
- m_error.Set(success, wpi::Twine(success) + ": " + contextMessage, filename,
- function, lineNumber, this);
-
- // Update the global error if there is not one already set.
- GlobalErrors::Insert(m_error);
- }
-}
-
-void ErrorBase::SetError(Error::Code code, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const {
- // If there was an error
- if (code != 0) {
- // Set the current error information for this object.
- m_error.Set(code, contextMessage, filename, function, lineNumber, this);
-
- // Update the global error if there is not one already set.
- GlobalErrors::Insert(m_error);
- }
-}
-
-void ErrorBase::SetErrorRange(Error::Code code, int32_t minRange,
- int32_t maxRange, int32_t requestedValue,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const {
- // If there was an error
- if (code != 0) {
- // Set the current error information for this object.
- m_error.Set(code,
- contextMessage + ", Minimum Value: " + wpi::Twine(minRange) +
- ", MaximumValue: " + wpi::Twine(maxRange) +
- ", Requested Value: " + wpi::Twine(requestedValue),
- filename, function, lineNumber, this);
-
- // Update the global error if there is not one already set.
- GlobalErrors::Insert(m_error);
- }
-}
-
-void ErrorBase::SetWPIError(const wpi::Twine& errorMessage, Error::Code code,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const {
- // Set the current error information for this object.
- m_error.Set(code, errorMessage + ": " + contextMessage, filename, function,
- lineNumber, this);
-
- // Update the global error if there is not one already set.
- GlobalErrors::Insert(m_error);
-}
-
-void ErrorBase::CloneError(const ErrorBase& rhs) const {
- m_error = rhs.GetError();
-}
-
-bool ErrorBase::StatusIsFatal() const { return m_error.GetCode() < 0; }
-
-void ErrorBase::SetGlobalError(Error::Code code,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) {
- // If there was an error
- if (code != 0) {
- // Set the current error information for this object.
- GlobalErrors::Insert(
- Error(code, contextMessage, filename, function, lineNumber, nullptr));
- }
-}
-
-void ErrorBase::SetGlobalWPIError(const wpi::Twine& errorMessage,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename,
- wpi::StringRef function, int lineNumber) {
- GlobalErrors::Insert(Error(-1, errorMessage + ": " + contextMessage, filename,
- function, lineNumber, nullptr));
-}
-
-Error ErrorBase::GetGlobalError() {
- auto& inst = GlobalErrors::GetInstance();
- std::scoped_lock mutex(inst.mutex);
- if (!inst.lastError) return Error{};
- return *inst.lastError;
-}
-
-std::vector<Error> ErrorBase::GetGlobalErrors() {
- auto& inst = GlobalErrors::GetInstance();
- std::scoped_lock mutex(inst.mutex);
- std::vector<Error> rv;
- for (auto&& error : inst.errors) rv.push_back(error);
- return rv;
-}
-
-void ErrorBase::ClearGlobalErrors() {
- auto& inst = GlobalErrors::GetInstance();
- std::scoped_lock mutex(inst.mutex);
- inst.errors.clear();
- inst.lastError = nullptr;
-}
diff --git a/wpilibc/src/main/native/cpp/Errors.cpp b/wpilibc/src/main/native/cpp/Errors.cpp
new file mode 100644
index 0000000..0ff4dc1
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/Errors.cpp
@@ -0,0 +1,81 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/Errors.h"
+
+#include <exception>
+
+#include <hal/DriverStation.h>
+#include <hal/HALBase.h>
+#include <wpi/StackTrace.h>
+#include <wpi/fs.h>
+
+using namespace frc;
+
+RuntimeError::RuntimeError(int32_t code, std::string&& loc, std::string&& stack,
+ std::string&& message)
+ : runtime_error{std::move(message)}, m_data{std::make_shared<Data>()} {
+ m_data->code = code;
+ m_data->loc = std::move(loc);
+ m_data->stack = stack;
+}
+
+RuntimeError::RuntimeError(int32_t code, const char* fileName, int lineNumber,
+ const char* funcName, std::string&& stack,
+ std::string&& message)
+ : RuntimeError{
+ code,
+ fmt::format("{} [{}:{}]", funcName,
+ fs::path{fileName}.filename().string(), lineNumber),
+ std::move(stack), std::move(message)} {}
+
+void RuntimeError::Report() const {
+ HAL_SendError(m_data->code < 0, m_data->code, 0, what(), m_data->loc.c_str(),
+ m_data->stack.c_str(), 1);
+}
+
+const char* frc::GetErrorMessage(int32_t* code) {
+ switch (*code) {
+#define S(label, offset, message) \
+ case err::label: \
+ return message;
+#include "frc/WPIErrors.mac"
+#undef S
+#define S(label, offset, message) \
+ case warn::label: \
+ return message;
+#include "frc/WPIWarnings.mac"
+#undef S
+ default:
+ return HAL_GetLastError(code);
+ }
+}
+
+void frc::ReportErrorV(int32_t status, const char* fileName, int lineNumber,
+ const char* funcName, fmt::string_view format,
+ fmt::format_args args) {
+ if (status == 0) {
+ return;
+ }
+ fmt::memory_buffer out;
+ fmt::format_to(fmt::appender{out}, "{}: ", GetErrorMessage(&status));
+ fmt::vformat_to(fmt::appender{out}, format, args);
+ out.push_back('\0');
+ HAL_SendError(status < 0, status, 0, out.data(), funcName,
+ wpi::GetStackTrace(2).c_str(), 1);
+}
+
+RuntimeError frc::MakeErrorV(int32_t status, const char* fileName,
+ int lineNumber, const char* funcName,
+ fmt::string_view format, fmt::format_args args) {
+ fmt::memory_buffer out;
+ fmt::format_to(fmt::appender{out}, "{}: ", GetErrorMessage(&status));
+ fmt::vformat_to(fmt::appender{out}, format, args);
+ return RuntimeError{status,
+ fileName,
+ lineNumber,
+ funcName,
+ wpi::GetStackTrace(2),
+ fmt::to_string(out)};
+}
diff --git a/wpilibc/src/main/native/cpp/Filesystem.cpp b/wpilibc/src/main/native/cpp/Filesystem.cpp
index 7d2ea1d..d497779 100644
--- a/wpilibc/src/main/native/cpp/Filesystem.cpp
+++ b/wpilibc/src/main/native/cpp/Filesystem.cpp
@@ -1,37 +1,29 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Filesystem.h"
-#include <wpi/FileSystem.h>
-#include <wpi/Path.h>
+#include <wpi/fs.h>
#include "frc/RobotBase.h"
-void frc::filesystem::GetLaunchDirectory(wpi::SmallVectorImpl<char>& result) {
- wpi::sys::fs::current_path(result);
+std::string frc::filesystem::GetLaunchDirectory() {
+ return fs::current_path().string();
}
-void frc::filesystem::GetOperatingDirectory(
- wpi::SmallVectorImpl<char>& result) {
+std::string frc::filesystem::GetOperatingDirectory() {
if constexpr (RobotBase::IsReal()) {
- wpi::sys::path::native("/home/lvuser", result);
+ return "/home/lvuser";
} else {
- frc::filesystem::GetLaunchDirectory(result);
+ return frc::filesystem::GetLaunchDirectory();
}
}
-void frc::filesystem::GetDeployDirectory(wpi::SmallVectorImpl<char>& result) {
- frc::filesystem::GetOperatingDirectory(result);
+std::string frc::filesystem::GetDeployDirectory() {
if constexpr (RobotBase::IsReal()) {
- wpi::sys::path::append(result, "deploy");
+ return "/home/lvuser/deploy";
} else {
- wpi::sys::path::append(result, "src");
- wpi::sys::path::append(result, "main");
- wpi::sys::path::append(result, "deploy");
+ return (fs::current_path() / "src" / "main" / "deploy").string();
}
}
diff --git a/wpilibc/src/main/native/cpp/GearTooth.cpp b/wpilibc/src/main/native/cpp/GearTooth.cpp
deleted file mode 100644
index 5fb5021..0000000
--- a/wpilibc/src/main/native/cpp/GearTooth.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/GearTooth.h"
-
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-constexpr double GearTooth::kGearToothThreshold;
-
-GearTooth::GearTooth(int channel, bool directionSensitive) : Counter(channel) {
- EnableDirectionSensing(directionSensitive);
- SendableRegistry::GetInstance().SetName(this, "GearTooth", channel);
-}
-
-GearTooth::GearTooth(DigitalSource* source, bool directionSensitive)
- : Counter(source) {
- EnableDirectionSensing(directionSensitive);
- SendableRegistry::GetInstance().SetName(this, "GearTooth",
- source->GetChannel());
-}
-
-GearTooth::GearTooth(std::shared_ptr<DigitalSource> source,
- bool directionSensitive)
- : Counter(source) {
- EnableDirectionSensing(directionSensitive);
- SendableRegistry::GetInstance().SetName(this, "GearTooth",
- source->GetChannel());
-}
-
-void GearTooth::EnableDirectionSensing(bool directionSensitive) {
- if (directionSensitive) {
- SetPulseLengthMode(kGearToothThreshold);
- }
-}
-
-void GearTooth::InitSendable(SendableBuilder& builder) {
- Counter::InitSendable(builder);
- builder.SetSmartDashboardType("Gear Tooth");
-}
diff --git a/wpilibc/src/main/native/cpp/GenericHID.cpp b/wpilibc/src/main/native/cpp/GenericHID.cpp
index 4a264c8..6c186eb 100644
--- a/wpilibc/src/main/native/cpp/GenericHID.cpp
+++ b/wpilibc/src/main/native/cpp/GenericHID.cpp
@@ -1,69 +1,74 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/GenericHID.h"
#include <hal/DriverStation.h>
#include "frc/DriverStation.h"
-#include "frc/WPIErrors.h"
+#include "frc/Errors.h"
using namespace frc;
-GenericHID::GenericHID(int port) : m_ds(&DriverStation::GetInstance()) {
- if (port >= DriverStation::kJoystickPorts) {
- wpi_setWPIError(BadJoystickIndex);
+GenericHID::GenericHID(int port) {
+ if (port < 0 || port >= DriverStation::kJoystickPorts) {
+ throw FRC_MakeError(warn::BadJoystickIndex, "port {} out of range", port);
}
m_port = port;
}
bool GenericHID::GetRawButton(int button) const {
- return m_ds->GetStickButton(m_port, button);
+ return DriverStation::GetStickButton(m_port, button);
}
bool GenericHID::GetRawButtonPressed(int button) {
- return m_ds->GetStickButtonPressed(m_port, button);
+ return DriverStation::GetStickButtonPressed(m_port, button);
}
bool GenericHID::GetRawButtonReleased(int button) {
- return m_ds->GetStickButtonReleased(m_port, button);
+ return DriverStation::GetStickButtonReleased(m_port, button);
}
double GenericHID::GetRawAxis(int axis) const {
- return m_ds->GetStickAxis(m_port, axis);
+ return DriverStation::GetStickAxis(m_port, axis);
}
-int GenericHID::GetPOV(int pov) const { return m_ds->GetStickPOV(m_port, pov); }
+int GenericHID::GetPOV(int pov) const {
+ return DriverStation::GetStickPOV(m_port, pov);
+}
-int GenericHID::GetAxisCount() const { return m_ds->GetStickAxisCount(m_port); }
+int GenericHID::GetAxisCount() const {
+ return DriverStation::GetStickAxisCount(m_port);
+}
-int GenericHID::GetPOVCount() const { return m_ds->GetStickPOVCount(m_port); }
+int GenericHID::GetPOVCount() const {
+ return DriverStation::GetStickPOVCount(m_port);
+}
int GenericHID::GetButtonCount() const {
- return m_ds->GetStickButtonCount(m_port);
+ return DriverStation::GetStickButtonCount(m_port);
}
bool GenericHID::IsConnected() const {
- return m_ds->IsJoystickConnected(m_port);
+ return DriverStation::IsJoystickConnected(m_port);
}
GenericHID::HIDType GenericHID::GetType() const {
- return static_cast<HIDType>(m_ds->GetJoystickType(m_port));
+ return static_cast<HIDType>(DriverStation::GetJoystickType(m_port));
}
std::string GenericHID::GetName() const {
- return m_ds->GetJoystickName(m_port);
+ return DriverStation::GetJoystickName(m_port);
}
int GenericHID::GetAxisType(int axis) const {
- return m_ds->GetJoystickAxisType(m_port, axis);
+ return DriverStation::GetJoystickAxisType(m_port, axis);
}
-int GenericHID::GetPort() const { return m_port; }
+int GenericHID::GetPort() const {
+ return m_port;
+}
void GenericHID::SetOutput(int outputNumber, bool value) {
m_outputs =
@@ -78,10 +83,11 @@
}
void GenericHID::SetRumble(RumbleType type, double value) {
- if (value < 0)
+ if (value < 0) {
value = 0;
- else if (value > 1)
+ } else if (value > 1) {
value = 1;
+ }
if (type == kLeftRumble) {
m_leftRumble = value * 65535;
} else {
diff --git a/wpilibc/src/main/native/cpp/GyroBase.cpp b/wpilibc/src/main/native/cpp/GyroBase.cpp
deleted file mode 100644
index ba9b2f0..0000000
--- a/wpilibc/src/main/native/cpp/GyroBase.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/GyroBase.h"
-
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-
-using namespace frc;
-
-double GyroBase::PIDGet() {
- switch (GetPIDSourceType()) {
- case PIDSourceType::kRate:
- return GetRate();
- case PIDSourceType::kDisplacement:
- return GetAngle();
- default:
- return 0;
- }
-}
-
-void GyroBase::InitSendable(SendableBuilder& builder) {
- builder.SetSmartDashboardType("Gyro");
- builder.AddDoubleProperty(
- "Value", [=]() { return GetAngle(); }, nullptr);
-}
diff --git a/wpilibc/src/main/native/cpp/I2C.cpp b/wpilibc/src/main/native/cpp/I2C.cpp
index 21d92f2..adf1c54 100644
--- a/wpilibc/src/main/native/cpp/I2C.cpp
+++ b/wpilibc/src/main/native/cpp/I2C.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/I2C.h"
@@ -12,7 +9,7 @@
#include <hal/FRCUsageReporting.h>
#include <hal/I2C.h>
-#include "frc/WPIErrors.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -20,23 +17,34 @@
: m_port(static_cast<HAL_I2CPort>(port)), m_deviceAddress(deviceAddress) {
int32_t status = 0;
HAL_InitializeI2C(m_port, &status);
- // wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", port);
HAL_Report(HALUsageReporting::kResourceType_I2C, deviceAddress);
}
-I2C::~I2C() { HAL_CloseI2C(m_port); }
+I2C::~I2C() {
+ HAL_CloseI2C(m_port);
+}
+
+I2C::Port I2C::GetPort() const {
+ return static_cast<Port>(static_cast<int>(m_port));
+}
+
+int I2C::GetDeviceAddress() const {
+ return m_deviceAddress;
+}
bool I2C::Transaction(uint8_t* dataToSend, int sendSize, uint8_t* dataReceived,
int receiveSize) {
int32_t status = 0;
status = HAL_TransactionI2C(m_port, m_deviceAddress, dataToSend, sendSize,
dataReceived, receiveSize);
- // wpi_setHALError(status);
return status < 0;
}
-bool I2C::AddressOnly() { return Transaction(nullptr, 0, nullptr, 0); }
+bool I2C::AddressOnly() {
+ return Transaction(nullptr, 0, nullptr, 0);
+}
bool I2C::Write(int registerAddress, uint8_t data) {
uint8_t buffer[2];
@@ -55,12 +63,10 @@
bool I2C::Read(int registerAddress, int count, uint8_t* buffer) {
if (count < 1) {
- wpi_setWPIErrorWithContext(ParameterOutOfRange, "count");
- return true;
+ throw FRC_MakeError(err::ParameterOutOfRange, "count {}", count);
}
- if (buffer == nullptr) {
- wpi_setWPIErrorWithContext(NullParameter, "buffer");
- return true;
+ if (!buffer) {
+ throw FRC_MakeError(err::NullParameter, "{}", "buffer");
}
uint8_t regAddr = registerAddress;
return Transaction(®Addr, sizeof(regAddr), buffer, count);
@@ -68,12 +74,10 @@
bool I2C::ReadOnly(int count, uint8_t* buffer) {
if (count < 1) {
- wpi_setWPIErrorWithContext(ParameterOutOfRange, "count");
- return true;
+ throw FRC_MakeError(err::ParameterOutOfRange, "count {}", count);
}
- if (buffer == nullptr) {
- wpi_setWPIErrorWithContext(NullParameter, "buffer");
- return true;
+ if (!buffer) {
+ throw FRC_MakeError(err::NullParameter, "{}", "buffer");
}
return HAL_ReadI2C(m_port, m_deviceAddress, buffer, count) < 0;
}
@@ -86,10 +90,14 @@
i += 4, curRegisterAddress += 4) {
int toRead = count - i < 4 ? count - i : 4;
// Read the chunk of data. Return false if the sensor does not respond.
- if (Read(curRegisterAddress, toRead, deviceData)) return false;
+ if (Read(curRegisterAddress, toRead, deviceData)) {
+ return false;
+ }
for (int j = 0; j < toRead; j++) {
- if (deviceData[j] != expected[i + j]) return false;
+ if (deviceData[j] != expected[i + j]) {
+ return false;
+ }
}
}
return true;
diff --git a/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp b/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp
deleted file mode 100644
index 744e349..0000000
--- a/wpilibc/src/main/native/cpp/InterruptableSensorBase.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/InterruptableSensorBase.h"
-
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
-
-using namespace frc;
-
-InterruptableSensorBase::~InterruptableSensorBase() {
- if (m_interrupt == HAL_kInvalidHandle) return;
- int32_t status = 0;
- HAL_CleanInterrupts(m_interrupt, &status);
- // Ignore status, as an invalid handle just needs to be ignored.
-}
-
-void InterruptableSensorBase::RequestInterrupts(
- HAL_InterruptHandlerFunction handler, void* param) {
- if (StatusIsFatal()) return;
-
- wpi_assert(m_interrupt == HAL_kInvalidHandle);
- AllocateInterrupts(false);
- if (StatusIsFatal()) return; // if allocate failed, out of interrupts
-
- int32_t status = 0;
- HAL_RequestInterrupts(
- m_interrupt, GetPortHandleForRouting(),
- static_cast<HAL_AnalogTriggerType>(GetAnalogTriggerTypeForRouting()),
- &status);
- SetUpSourceEdge(true, false);
- HAL_AttachInterruptHandler(m_interrupt, handler, param, &status);
- wpi_setHALError(status);
-}
-
-void InterruptableSensorBase::RequestInterrupts(InterruptEventHandler handler) {
- if (StatusIsFatal()) return;
-
- wpi_assert(m_interrupt == HAL_kInvalidHandle);
- AllocateInterrupts(false);
- if (StatusIsFatal()) return; // if allocate failed, out of interrupts
-
- m_interruptHandler =
- std::make_unique<InterruptEventHandler>(std::move(handler));
-
- int32_t status = 0;
- HAL_RequestInterrupts(
- m_interrupt, GetPortHandleForRouting(),
- static_cast<HAL_AnalogTriggerType>(GetAnalogTriggerTypeForRouting()),
- &status);
- SetUpSourceEdge(true, false);
- HAL_AttachInterruptHandler(
- m_interrupt,
- [](uint32_t mask, void* param) {
- auto self = reinterpret_cast<InterruptEventHandler*>(param);
- // Rising edge result is the interrupt bit set in the byte 0xFF
- // Falling edge result is the interrupt bit set in the byte 0xFF00
- // Set any bit set to be true for that edge, and AND the 2 results
- // together to match the existing enum for all interrupts
- int32_t rising = (mask & 0xFF) ? 0x1 : 0x0;
- int32_t falling = ((mask & 0xFF00) ? 0x0100 : 0x0);
- WaitResult res = static_cast<WaitResult>(falling | rising);
- (*self)(res);
- },
- m_interruptHandler.get(), &status);
- wpi_setHALError(status);
-}
-
-void InterruptableSensorBase::RequestInterrupts() {
- if (StatusIsFatal()) return;
-
- wpi_assert(m_interrupt == HAL_kInvalidHandle);
- AllocateInterrupts(true);
- if (StatusIsFatal()) return; // if allocate failed, out of interrupts
-
- int32_t status = 0;
- HAL_RequestInterrupts(
- m_interrupt, GetPortHandleForRouting(),
- static_cast<HAL_AnalogTriggerType>(GetAnalogTriggerTypeForRouting()),
- &status);
- wpi_setHALError(status);
- SetUpSourceEdge(true, false);
-}
-
-void InterruptableSensorBase::CancelInterrupts() {
- if (StatusIsFatal()) return;
- wpi_assert(m_interrupt != HAL_kInvalidHandle);
- int32_t status = 0;
- HAL_CleanInterrupts(m_interrupt, &status);
- // Ignore status, as an invalid handle just needs to be ignored.
- m_interrupt = HAL_kInvalidHandle;
- m_interruptHandler = nullptr;
-}
-
-InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt(
- double timeout, bool ignorePrevious) {
- if (StatusIsFatal()) return InterruptableSensorBase::kTimeout;
- wpi_assert(m_interrupt != HAL_kInvalidHandle);
- int32_t status = 0;
- int result;
-
- result = HAL_WaitForInterrupt(m_interrupt, timeout, ignorePrevious, &status);
- wpi_setHALError(status);
-
- // Rising edge result is the interrupt bit set in the byte 0xFF
- // Falling edge result is the interrupt bit set in the byte 0xFF00
- // Set any bit set to be true for that edge, and AND the 2 results
- // together to match the existing enum for all interrupts
- int32_t rising = (result & 0xFF) ? 0x1 : 0x0;
- int32_t falling = ((result & 0xFF00) ? 0x0100 : 0x0);
- return static_cast<WaitResult>(falling | rising);
-}
-
-void InterruptableSensorBase::EnableInterrupts() {
- if (StatusIsFatal()) return;
- wpi_assert(m_interrupt != HAL_kInvalidHandle);
- int32_t status = 0;
- HAL_EnableInterrupts(m_interrupt, &status);
- wpi_setHALError(status);
-}
-
-void InterruptableSensorBase::DisableInterrupts() {
- if (StatusIsFatal()) return;
- wpi_assert(m_interrupt != HAL_kInvalidHandle);
- int32_t status = 0;
- HAL_DisableInterrupts(m_interrupt, &status);
- wpi_setHALError(status);
-}
-
-double InterruptableSensorBase::ReadRisingTimestamp() {
- if (StatusIsFatal()) return 0.0;
- wpi_assert(m_interrupt != HAL_kInvalidHandle);
- int32_t status = 0;
- int64_t timestamp = HAL_ReadInterruptRisingTimestamp(m_interrupt, &status);
- wpi_setHALError(status);
- return timestamp * 1e-6;
-}
-
-double InterruptableSensorBase::ReadFallingTimestamp() {
- if (StatusIsFatal()) return 0.0;
- wpi_assert(m_interrupt != HAL_kInvalidHandle);
- int32_t status = 0;
- int64_t timestamp = HAL_ReadInterruptFallingTimestamp(m_interrupt, &status);
- wpi_setHALError(status);
- return timestamp * 1e-6;
-}
-
-void InterruptableSensorBase::SetUpSourceEdge(bool risingEdge,
- bool fallingEdge) {
- if (StatusIsFatal()) return;
- if (m_interrupt == HAL_kInvalidHandle) {
- wpi_setWPIErrorWithContext(
- NullParameter,
- "You must call RequestInterrupts before SetUpSourceEdge");
- return;
- }
- if (m_interrupt != HAL_kInvalidHandle) {
- int32_t status = 0;
- HAL_SetInterruptUpSourceEdge(m_interrupt, risingEdge, fallingEdge, &status);
- wpi_setHALError(status);
- }
-}
-
-void InterruptableSensorBase::AllocateInterrupts(bool watcher) {
- wpi_assert(m_interrupt == HAL_kInvalidHandle);
- // Expects the calling leaf class to allocate an interrupt index.
- int32_t status = 0;
- m_interrupt = HAL_InitializeInterrupts(watcher, &status);
- wpi_setHALError(status);
-}
diff --git a/wpilibc/src/main/native/cpp/IterativeRobot.cpp b/wpilibc/src/main/native/cpp/IterativeRobot.cpp
deleted file mode 100644
index 72fb79b..0000000
--- a/wpilibc/src/main/native/cpp/IterativeRobot.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/IterativeRobot.h"
-
-#include <hal/DriverStation.h>
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/DriverStation.h"
-
-using namespace frc;
-
-static constexpr auto kPacketPeriod = 0.02_s;
-
-IterativeRobot::IterativeRobot() : IterativeRobotBase(kPacketPeriod) {
- HAL_Report(HALUsageReporting::kResourceType_Framework,
- HALUsageReporting::kFramework_Iterative);
-}
-
-void IterativeRobot::StartCompetition() {
- RobotInit();
-
- if constexpr (IsSimulation()) {
- SimulationInit();
- }
-
- // Tell the DS that the robot is ready to be enabled
- HAL_ObserveUserProgramStarting();
-
- // Loop forever, calling the appropriate mode-dependent function
- while (true) {
- // Wait for driver station data so the loop doesn't hog the CPU
- DriverStation::GetInstance().WaitForData();
- if (m_exit) break;
-
- LoopFunc();
- }
-}
-
-void IterativeRobot::EndCompetition() {
- m_exit = true;
- DriverStation::GetInstance().WakeupWaitForData();
-}
diff --git a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp
index 7b29130..47eb299 100644
--- a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp
+++ b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/IterativeRobotBase.h"
+#include <fmt/format.h>
#include <hal/DriverStation.h>
-#include <wpi/Format.h>
-#include <wpi/SmallString.h>
-#include <wpi/raw_ostream.h>
+#include <networktables/NetworkTableInstance.h>
-#include "frc/DriverStation.h"
+#include "frc/DSControlWord.h"
+#include "frc/Errors.h"
#include "frc/livewindow/LiveWindow.h"
#include "frc/shuffleboard/Shuffleboard.h"
#include "frc/smartdashboard/SmartDashboard.h"
@@ -26,34 +23,22 @@
: m_period(period),
m_watchdog(period, [this] { PrintLoopOverrunMessage(); }) {}
-void IterativeRobotBase::RobotInit() {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
-}
+void IterativeRobotBase::RobotInit() {}
-void IterativeRobotBase::SimulationInit() {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
-}
+void IterativeRobotBase::SimulationInit() {}
-void IterativeRobotBase::DisabledInit() {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
-}
+void IterativeRobotBase::DisabledInit() {}
-void IterativeRobotBase::AutonomousInit() {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
-}
+void IterativeRobotBase::AutonomousInit() {}
-void IterativeRobotBase::TeleopInit() {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
-}
+void IterativeRobotBase::TeleopInit() {}
-void IterativeRobotBase::TestInit() {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
-}
+void IterativeRobotBase::TestInit() {}
void IterativeRobotBase::RobotPeriodic() {
static bool firstRun = true;
if (firstRun) {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
+ fmt::print("Default {}() method... Override me!\n", __FUNCTION__);
firstRun = false;
}
}
@@ -61,7 +46,7 @@
void IterativeRobotBase::SimulationPeriodic() {
static bool firstRun = true;
if (firstRun) {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
+ fmt::print("Default {}() method... Override me!\n", __FUNCTION__);
firstRun = false;
}
}
@@ -69,7 +54,7 @@
void IterativeRobotBase::DisabledPeriodic() {
static bool firstRun = true;
if (firstRun) {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
+ fmt::print("Default {}() method... Override me!\n", __FUNCTION__);
firstRun = false;
}
}
@@ -77,7 +62,7 @@
void IterativeRobotBase::AutonomousPeriodic() {
static bool firstRun = true;
if (firstRun) {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
+ fmt::print("Default {}() method... Override me!\n", __FUNCTION__);
firstRun = false;
}
}
@@ -85,7 +70,7 @@
void IterativeRobotBase::TeleopPeriodic() {
static bool firstRun = true;
if (firstRun) {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
+ fmt::print("Default {}() method... Override me!\n", __FUNCTION__);
firstRun = false;
}
}
@@ -93,68 +78,92 @@
void IterativeRobotBase::TestPeriodic() {
static bool firstRun = true;
if (firstRun) {
- wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n";
+ fmt::print("Default {}() method... Override me!\n", __FUNCTION__);
firstRun = false;
}
}
+void IterativeRobotBase::DisabledExit() {}
+
+void IterativeRobotBase::AutonomousExit() {}
+
+void IterativeRobotBase::TeleopExit() {}
+
+void IterativeRobotBase::TestExit() {}
+
+void IterativeRobotBase::SetNetworkTablesFlushEnabled(bool enabled) {
+ m_ntFlushEnabled = enabled;
+}
+
+units::second_t IterativeRobotBase::GetPeriod() const {
+ return m_period;
+}
+
void IterativeRobotBase::LoopFunc() {
m_watchdog.Reset();
- // Call the appropriate function depending upon the current robot mode
- if (IsDisabled()) {
- // Call DisabledInit() if we are now just entering disabled mode from
- // either a different mode or from power-on.
- if (m_lastMode != Mode::kDisabled) {
- LiveWindow::GetInstance()->SetEnabled(false);
+ // Get current mode
+ DSControlWord word;
+ Mode mode = Mode::kNone;
+ if (word.IsDisabled()) {
+ mode = Mode::kDisabled;
+ } else if (word.IsAutonomous()) {
+ mode = Mode::kAutonomous;
+ } else if (word.IsTeleop()) {
+ mode = Mode::kTeleop;
+ } else if (word.IsTest()) {
+ mode = Mode::kTest;
+ }
+
+ // If mode changed, call mode exit and entry functions
+ if (m_lastMode != mode) {
+ // Call last mode's exit function
+ if (m_lastMode == Mode::kDisabled) {
+ DisabledExit();
+ } else if (m_lastMode == Mode::kAutonomous) {
+ AutonomousExit();
+ } else if (m_lastMode == Mode::kTeleop) {
+ TeleopExit();
+ } else if (m_lastMode == Mode::kTest) {
+ LiveWindow::SetEnabled(false);
Shuffleboard::DisableActuatorWidgets();
+ TestExit();
+ }
+
+ // Call current mode's entry function
+ if (mode == Mode::kDisabled) {
DisabledInit();
m_watchdog.AddEpoch("DisabledInit()");
- m_lastMode = Mode::kDisabled;
- }
-
- HAL_ObserveUserProgramDisabled();
- DisabledPeriodic();
- m_watchdog.AddEpoch("DisabledPeriodic()");
- } else if (IsAutonomous()) {
- // Call AutonomousInit() if we are now just entering autonomous mode from
- // either a different mode or from power-on.
- if (m_lastMode != Mode::kAutonomous) {
- LiveWindow::GetInstance()->SetEnabled(false);
- Shuffleboard::DisableActuatorWidgets();
+ } else if (mode == Mode::kAutonomous) {
AutonomousInit();
m_watchdog.AddEpoch("AutonomousInit()");
- m_lastMode = Mode::kAutonomous;
- }
-
- HAL_ObserveUserProgramAutonomous();
- AutonomousPeriodic();
- m_watchdog.AddEpoch("AutonomousPeriodic()");
- } else if (IsOperatorControl()) {
- // Call TeleopInit() if we are now just entering teleop mode from
- // either a different mode or from power-on.
- if (m_lastMode != Mode::kTeleop) {
- LiveWindow::GetInstance()->SetEnabled(false);
- Shuffleboard::DisableActuatorWidgets();
+ } else if (mode == Mode::kTeleop) {
TeleopInit();
m_watchdog.AddEpoch("TeleopInit()");
- m_lastMode = Mode::kTeleop;
- }
-
- HAL_ObserveUserProgramTeleop();
- TeleopPeriodic();
- m_watchdog.AddEpoch("TeleopPeriodic()");
- } else {
- // Call TestInit() if we are now just entering test mode from
- // either a different mode or from power-on.
- if (m_lastMode != Mode::kTest) {
- LiveWindow::GetInstance()->SetEnabled(true);
+ } else if (mode == Mode::kTest) {
+ LiveWindow::SetEnabled(true);
Shuffleboard::EnableActuatorWidgets();
TestInit();
m_watchdog.AddEpoch("TestInit()");
- m_lastMode = Mode::kTest;
}
+ m_lastMode = mode;
+ }
+
+ // Call the appropriate function depending upon the current robot mode
+ if (mode == Mode::kDisabled) {
+ HAL_ObserveUserProgramDisabled();
+ DisabledPeriodic();
+ m_watchdog.AddEpoch("DisabledPeriodic()");
+ } else if (mode == Mode::kAutonomous) {
+ HAL_ObserveUserProgramAutonomous();
+ AutonomousPeriodic();
+ m_watchdog.AddEpoch("AutonomousPeriodic()");
+ } else if (mode == Mode::kTeleop) {
+ HAL_ObserveUserProgramTeleop();
+ TeleopPeriodic();
+ m_watchdog.AddEpoch("TeleopPeriodic()");
+ } else if (mode == Mode::kTest) {
HAL_ObserveUserProgramTest();
TestPeriodic();
m_watchdog.AddEpoch("TestPeriodic()");
@@ -165,18 +174,25 @@
SmartDashboard::UpdateValues();
m_watchdog.AddEpoch("SmartDashboard::UpdateValues()");
- LiveWindow::GetInstance()->UpdateValues();
+ LiveWindow::UpdateValues();
m_watchdog.AddEpoch("LiveWindow::UpdateValues()");
Shuffleboard::Update();
m_watchdog.AddEpoch("Shuffleboard::Update()");
if constexpr (IsSimulation()) {
+ HAL_SimPeriodicBefore();
SimulationPeriodic();
+ HAL_SimPeriodicAfter();
m_watchdog.AddEpoch("SimulationPeriodic()");
}
m_watchdog.Disable();
+ // Flush NetworkTables
+ if (m_ntFlushEnabled) {
+ nt::NetworkTableInstance::GetDefault().Flush();
+ }
+
// Warn on loop time overruns
if (m_watchdog.IsExpired()) {
m_watchdog.PrintEpochs();
@@ -184,11 +200,5 @@
}
void IterativeRobotBase::PrintLoopOverrunMessage() {
- wpi::SmallString<128> str;
- wpi::raw_svector_ostream buf(str);
-
- buf << "Loop time of " << wpi::format("%.6f", m_period.to<double>())
- << "s overrun\n";
-
- DriverStation::ReportWarning(str);
+ FRC_ReportError(err::Error, "Loop time of {:.6f}s overrun", m_period.value());
}
diff --git a/wpilibc/src/main/native/cpp/Jaguar.cpp b/wpilibc/src/main/native/cpp/Jaguar.cpp
deleted file mode 100644
index c87e4d1..0000000
--- a/wpilibc/src/main/native/cpp/Jaguar.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/Jaguar.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-Jaguar::Jaguar(int channel) : PWMSpeedController(channel) {
- SetBounds(2.31, 1.55, 1.507, 1.454, 0.697);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_Jaguar, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "Jaguar", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/Joystick.cpp b/wpilibc/src/main/native/cpp/Joystick.cpp
index c2cdaea..48f0c77 100644
--- a/wpilibc/src/main/native/cpp/Joystick.cpp
+++ b/wpilibc/src/main/native/cpp/Joystick.cpp
@@ -1,16 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Joystick.h"
#include <cmath>
#include <hal/FRCUsageReporting.h>
-#include <wpi/math>
+#include <wpi/numbers>
using namespace frc;
@@ -24,45 +21,69 @@
HAL_Report(HALUsageReporting::kResourceType_Joystick, port + 1);
}
-void Joystick::SetXChannel(int channel) { m_axes[Axis::kX] = channel; }
+void Joystick::SetXChannel(int channel) {
+ m_axes[Axis::kX] = channel;
+}
-void Joystick::SetYChannel(int channel) { m_axes[Axis::kY] = channel; }
+void Joystick::SetYChannel(int channel) {
+ m_axes[Axis::kY] = channel;
+}
-void Joystick::SetZChannel(int channel) { m_axes[Axis::kZ] = channel; }
+void Joystick::SetZChannel(int channel) {
+ m_axes[Axis::kZ] = channel;
+}
-void Joystick::SetTwistChannel(int channel) { m_axes[Axis::kTwist] = channel; }
+void Joystick::SetTwistChannel(int channel) {
+ m_axes[Axis::kTwist] = channel;
+}
void Joystick::SetThrottleChannel(int channel) {
m_axes[Axis::kThrottle] = channel;
}
-int Joystick::GetXChannel() const { return m_axes[Axis::kX]; }
+int Joystick::GetXChannel() const {
+ return m_axes[Axis::kX];
+}
-int Joystick::GetYChannel() const { return m_axes[Axis::kY]; }
+int Joystick::GetYChannel() const {
+ return m_axes[Axis::kY];
+}
-int Joystick::GetZChannel() const { return m_axes[Axis::kZ]; }
+int Joystick::GetZChannel() const {
+ return m_axes[Axis::kZ];
+}
-int Joystick::GetTwistChannel() const { return m_axes[Axis::kTwist]; }
+int Joystick::GetTwistChannel() const {
+ return m_axes[Axis::kTwist];
+}
-int Joystick::GetThrottleChannel() const { return m_axes[Axis::kThrottle]; }
+int Joystick::GetThrottleChannel() const {
+ return m_axes[Axis::kThrottle];
+}
-double Joystick::GetX(JoystickHand hand) const {
+double Joystick::GetX() const {
return GetRawAxis(m_axes[Axis::kX]);
}
-double Joystick::GetY(JoystickHand hand) const {
+double Joystick::GetY() const {
return GetRawAxis(m_axes[Axis::kY]);
}
-double Joystick::GetZ() const { return GetRawAxis(m_axes[Axis::kZ]); }
+double Joystick::GetZ() const {
+ return GetRawAxis(m_axes[Axis::kZ]);
+}
-double Joystick::GetTwist() const { return GetRawAxis(m_axes[Axis::kTwist]); }
+double Joystick::GetTwist() const {
+ return GetRawAxis(m_axes[Axis::kTwist]);
+}
double Joystick::GetThrottle() const {
return GetRawAxis(m_axes[Axis::kThrottle]);
}
-bool Joystick::GetTrigger() const { return GetRawButton(Button::kTrigger); }
+bool Joystick::GetTrigger() const {
+ return GetRawButton(Button::kTrigger);
+}
bool Joystick::GetTriggerPressed() {
return GetRawButtonPressed(Button::kTrigger);
@@ -72,11 +93,17 @@
return GetRawButtonReleased(Button::kTrigger);
}
-bool Joystick::GetTop() const { return GetRawButton(Button::kTop); }
+bool Joystick::GetTop() const {
+ return GetRawButton(Button::kTop);
+}
-bool Joystick::GetTopPressed() { return GetRawButtonPressed(Button::kTop); }
+bool Joystick::GetTopPressed() {
+ return GetRawButtonPressed(Button::kTop);
+}
-bool Joystick::GetTopReleased() { return GetRawButtonReleased(Button::kTop); }
+bool Joystick::GetTopReleased() {
+ return GetRawButtonReleased(Button::kTop);
+}
double Joystick::GetMagnitude() const {
return std::sqrt(std::pow(GetX(), 2) + std::pow(GetY(), 2));
@@ -87,5 +114,5 @@
}
double Joystick::GetDirectionDegrees() const {
- return (180 / wpi::math::pi) * GetDirectionRadians();
+ return (180 / wpi::numbers::pi) * GetDirectionRadians();
}
diff --git a/wpilibc/src/main/native/cpp/MotorSafety.cpp b/wpilibc/src/main/native/cpp/MotorSafety.cpp
index 1806e86..9cb28cd 100644
--- a/wpilibc/src/main/native/cpp/MotorSafety.cpp
+++ b/wpilibc/src/main/native/cpp/MotorSafety.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/MotorSafety.h"
@@ -11,11 +8,9 @@
#include <utility>
#include <wpi/SmallPtrSet.h>
-#include <wpi/SmallString.h>
-#include <wpi/raw_ostream.h>
#include "frc/DriverStation.h"
-#include "frc/WPIErrors.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -33,16 +28,13 @@
}
MotorSafety::MotorSafety(MotorSafety&& rhs)
- : ErrorBase(std::move(rhs)),
- m_expiration(std::move(rhs.m_expiration)),
+ : m_expiration(std::move(rhs.m_expiration)),
m_enabled(std::move(rhs.m_enabled)),
m_stopTime(std::move(rhs.m_stopTime)) {}
MotorSafety& MotorSafety::operator=(MotorSafety&& rhs) {
std::scoped_lock lock(m_thisMutex, rhs.m_thisMutex);
- ErrorBase::operator=(std::move(rhs));
-
m_expiration = std::move(rhs.m_expiration);
m_enabled = std::move(rhs.m_enabled);
m_stopTime = std::move(rhs.m_stopTime);
@@ -55,12 +47,12 @@
m_stopTime = Timer::GetFPGATimestamp() + m_expiration;
}
-void MotorSafety::SetExpiration(double expirationTime) {
+void MotorSafety::SetExpiration(units::second_t expirationTime) {
std::scoped_lock lock(m_thisMutex);
m_expiration = expirationTime;
}
-double MotorSafety::GetExpiration() const {
+units::second_t MotorSafety::GetExpiration() const {
std::scoped_lock lock(m_thisMutex);
return m_expiration;
}
@@ -82,7 +74,7 @@
void MotorSafety::Check() {
bool enabled;
- double stopTime;
+ units::second_t stopTime;
{
std::scoped_lock lock(m_thisMutex);
@@ -90,17 +82,13 @@
stopTime = m_stopTime;
}
- DriverStation& ds = DriverStation::GetInstance();
- if (!enabled || ds.IsDisabled() || ds.IsTest()) {
+ if (!enabled || DriverStation::IsDisabled() || DriverStation::IsTest()) {
return;
}
if (stopTime < Timer::GetFPGATimestamp()) {
- wpi::SmallString<128> buf;
- wpi::raw_svector_ostream desc(buf);
- GetDescription(desc);
- desc << "... Output not updated often enough.";
- wpi_setWPIErrorWithContext(Timeout, desc.str());
+ FRC_ReportError(err::Timeout, "{}... Output not updated often enough",
+ GetDescription());
StopMotor();
}
}
diff --git a/wpilibc/src/main/native/cpp/NidecBrushless.cpp b/wpilibc/src/main/native/cpp/NidecBrushless.cpp
deleted file mode 100644
index 82a278e..0000000
--- a/wpilibc/src/main/native/cpp/NidecBrushless.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/NidecBrushless.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-NidecBrushless::NidecBrushless(int pwmChannel, int dioChannel)
- : m_dio(dioChannel), m_pwm(pwmChannel) {
- auto& registry = SendableRegistry::GetInstance();
- registry.AddChild(this, &m_dio);
- registry.AddChild(this, &m_pwm);
- SetExpiration(0.0);
- SetSafetyEnabled(false);
-
- // the dio controls the output (in PWM mode)
- m_dio.SetPWMRate(15625);
- m_dio.EnablePWM(0.5);
-
- HAL_Report(HALUsageReporting::kResourceType_NidecBrushless, pwmChannel + 1);
- registry.AddLW(this, "Nidec Brushless", pwmChannel);
-}
-
-void NidecBrushless::Set(double speed) {
- if (!m_disabled) {
- m_speed = speed;
- m_dio.UpdateDutyCycle(0.5 + 0.5 * (m_isInverted ? -speed : speed));
- m_pwm.SetRaw(0xffff);
- }
- Feed();
-}
-
-double NidecBrushless::Get() const { return m_speed; }
-
-void NidecBrushless::SetInverted(bool isInverted) { m_isInverted = isInverted; }
-
-bool NidecBrushless::GetInverted() const { return m_isInverted; }
-
-void NidecBrushless::Disable() {
- m_disabled = true;
- m_dio.UpdateDutyCycle(0.5);
- m_pwm.SetDisabled();
-}
-
-void NidecBrushless::Enable() { m_disabled = false; }
-
-void NidecBrushless::PIDWrite(double output) { Set(output); }
-
-void NidecBrushless::StopMotor() {
- m_dio.UpdateDutyCycle(0.5);
- m_pwm.SetDisabled();
-}
-
-void NidecBrushless::GetDescription(wpi::raw_ostream& desc) const {
- desc << "Nidec " << GetChannel();
-}
-
-int NidecBrushless::GetChannel() const { return m_pwm.GetChannel(); }
-
-void NidecBrushless::InitSendable(SendableBuilder& builder) {
- builder.SetSmartDashboardType("Nidec Brushless");
- builder.SetActuator(true);
- builder.SetSafeState([=]() { StopMotor(); });
- builder.AddDoubleProperty(
- "Value", [=]() { return Get(); }, [=](double value) { Set(value); });
-}
diff --git a/wpilibc/src/main/native/cpp/Notifier.cpp b/wpilibc/src/main/native/cpp/Notifier.cpp
index 4280ce4..441f750 100644
--- a/wpilibc/src/main/native/cpp/Notifier.cpp
+++ b/wpilibc/src/main/native/cpp/Notifier.cpp
@@ -1,40 +1,41 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Notifier.h"
#include <utility>
+#include <fmt/format.h>
#include <hal/FRCUsageReporting.h>
#include <hal/Notifier.h>
#include <hal/Threads.h>
-#include <wpi/SmallString.h>
+#include "frc/Errors.h"
#include "frc/Timer.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
using namespace frc;
Notifier::Notifier(std::function<void()> handler) {
- if (handler == nullptr)
- wpi_setWPIErrorWithContext(NullParameter, "handler must not be nullptr");
+ if (!handler) {
+ throw FRC_MakeError(err::NullParameter, "{}", "handler");
+ }
m_handler = handler;
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "InitializeNotifier");
m_thread = std::thread([=] {
for (;;) {
int32_t status = 0;
HAL_NotifierHandle notifier = m_notifier.load();
- if (notifier == 0) break;
+ if (notifier == 0) {
+ break;
+ }
uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status);
- if (curTime == 0 || status != 0) break;
+ if (curTime == 0 || status != 0) {
+ break;
+ }
std::function<void()> handler;
{
@@ -50,27 +51,34 @@
}
// call callback
- if (handler) handler();
+ if (handler) {
+ handler();
+ }
}
});
}
Notifier::Notifier(int priority, std::function<void()> handler) {
- if (handler == nullptr)
- wpi_setWPIErrorWithContext(NullParameter, "handler must not be nullptr");
+ if (!handler) {
+ throw FRC_MakeError(err::NullParameter, "{}", "handler");
+ }
m_handler = handler;
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "InitializeNotifier");
m_thread = std::thread([=] {
int32_t status = 0;
HAL_SetCurrentThreadPriority(true, priority, &status);
for (;;) {
HAL_NotifierHandle notifier = m_notifier.load();
- if (notifier == 0) break;
+ if (notifier == 0) {
+ break;
+ }
uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status);
- if (curTime == 0 || status != 0) break;
+ if (curTime == 0 || status != 0) {
+ break;
+ }
std::function<void()> handler;
{
@@ -86,7 +94,9 @@
}
// call callback
- if (handler) handler();
+ if (handler) {
+ handler();
+ }
}
});
}
@@ -96,17 +106,18 @@
// atomically set handle to 0, then clean
HAL_NotifierHandle handle = m_notifier.exchange(0);
HAL_StopNotifier(handle, &status);
- wpi_setHALError(status);
+ FRC_ReportError(status, "{}", "StopNotifier");
// Join the thread to ensure the handler has exited.
- if (m_thread.joinable()) m_thread.join();
+ if (m_thread.joinable()) {
+ m_thread.join();
+ }
HAL_CleanNotifier(handle, &status);
}
Notifier::Notifier(Notifier&& rhs)
- : ErrorBase(std::move(rhs)),
- m_thread(std::move(rhs.m_thread)),
+ : m_thread(std::move(rhs.m_thread)),
m_notifier(rhs.m_notifier.load()),
m_handler(std::move(rhs.m_handler)),
m_expirationTime(std::move(rhs.m_expirationTime)),
@@ -116,8 +127,6 @@
}
Notifier& Notifier::operator=(Notifier&& rhs) {
- ErrorBase::operator=(std::move(rhs));
-
m_thread = std::move(rhs.m_thread);
m_notifier = rhs.m_notifier.load();
rhs.m_notifier = HAL_kInvalidHandle;
@@ -129,11 +138,12 @@
return *this;
}
-void Notifier::SetName(const wpi::Twine& name) {
- wpi::SmallString<64> nameBuf;
+void Notifier::SetName(std::string_view name) {
+ fmt::memory_buffer buf;
+ fmt::format_to(fmt::appender{buf}, "{}", name);
+ buf.push_back('\0'); // null terminate
int32_t status = 0;
- HAL_SetNotifierName(m_notifier,
- name.toNullTerminatedStringRef(nameBuf).data(), &status);
+ HAL_SetNotifierName(m_notifier, buf.data(), &status);
}
void Notifier::SetHandler(std::function<void()> handler) {
@@ -141,26 +151,18 @@
m_handler = handler;
}
-void Notifier::StartSingle(double delay) {
- StartSingle(units::second_t(delay));
-}
-
void Notifier::StartSingle(units::second_t delay) {
std::scoped_lock lock(m_processMutex);
m_periodic = false;
- m_period = delay.to<double>();
+ m_period = delay;
m_expirationTime = Timer::GetFPGATimestamp() + m_period;
UpdateAlarm();
}
-void Notifier::StartPeriodic(double period) {
- StartPeriodic(units::second_t(period));
-}
-
void Notifier::StartPeriodic(units::second_t period) {
std::scoped_lock lock(m_processMutex);
m_periodic = true;
- m_period = period.to<double>();
+ m_period = period;
m_expirationTime = Timer::GetFPGATimestamp() + m_period;
UpdateAlarm();
}
@@ -170,18 +172,25 @@
m_periodic = false;
int32_t status = 0;
HAL_CancelNotifierAlarm(m_notifier, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "CancelNotifierAlarm");
}
void Notifier::UpdateAlarm(uint64_t triggerTime) {
int32_t status = 0;
// Return if we are being destructed, or were not created successfully
auto notifier = m_notifier.load();
- if (notifier == 0) return;
+ if (notifier == 0) {
+ return;
+ }
HAL_UpdateNotifierAlarm(notifier, triggerTime, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "UpdateNotifierAlarm");
}
void Notifier::UpdateAlarm() {
UpdateAlarm(static_cast<uint64_t>(m_expirationTime * 1e6));
}
+
+bool Notifier::SetHALThreadPriority(bool realTime, int32_t priority) {
+ int32_t status = 0;
+ return HAL_SetNotifierThreadPriority(realTime, priority, &status);
+}
diff --git a/wpilibc/src/main/native/cpp/PIDBase.cpp b/wpilibc/src/main/native/cpp/PIDBase.cpp
deleted file mode 100644
index 5802d98..0000000
--- a/wpilibc/src/main/native/cpp/PIDBase.cpp
+++ /dev/null
@@ -1,354 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PIDBase.h"
-
-#include <algorithm>
-#include <cmath>
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/PIDOutput.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-template <class T>
-constexpr const T& clamp(const T& value, const T& low, const T& high) {
- return std::max(low, std::min(value, high));
-}
-
-PIDBase::PIDBase(double Kp, double Ki, double Kd, PIDSource& source,
- PIDOutput& output)
- : PIDBase(Kp, Ki, Kd, 0.0, source, output) {}
-
-PIDBase::PIDBase(double Kp, double Ki, double Kd, double Kf, PIDSource& source,
- PIDOutput& output) {
- m_P = Kp;
- m_I = Ki;
- m_D = Kd;
- m_F = Kf;
-
- m_pidInput = &source;
- m_filter = LinearFilter<double>::MovingAverage(1);
-
- m_pidOutput = &output;
-
- m_setpointTimer.Start();
-
- static int instances = 0;
- instances++;
- HAL_Report(HALUsageReporting::kResourceType_PIDController, instances);
- SendableRegistry::GetInstance().Add(this, "PIDController", instances);
-}
-
-double PIDBase::Get() const {
- std::scoped_lock lock(m_thisMutex);
- return m_result;
-}
-
-void PIDBase::SetContinuous(bool continuous) {
- std::scoped_lock lock(m_thisMutex);
- m_continuous = continuous;
-}
-
-void PIDBase::SetInputRange(double minimumInput, double maximumInput) {
- {
- std::scoped_lock lock(m_thisMutex);
- m_minimumInput = minimumInput;
- m_maximumInput = maximumInput;
- m_inputRange = maximumInput - minimumInput;
- }
-
- SetSetpoint(m_setpoint);
-}
-
-void PIDBase::SetOutputRange(double minimumOutput, double maximumOutput) {
- std::scoped_lock lock(m_thisMutex);
- m_minimumOutput = minimumOutput;
- m_maximumOutput = maximumOutput;
-}
-
-void PIDBase::SetPID(double p, double i, double d) {
- {
- std::scoped_lock lock(m_thisMutex);
- m_P = p;
- m_I = i;
- m_D = d;
- }
-}
-
-void PIDBase::SetPID(double p, double i, double d, double f) {
- std::scoped_lock lock(m_thisMutex);
- m_P = p;
- m_I = i;
- m_D = d;
- m_F = f;
-}
-
-void PIDBase::SetP(double p) {
- std::scoped_lock lock(m_thisMutex);
- m_P = p;
-}
-
-void PIDBase::SetI(double i) {
- std::scoped_lock lock(m_thisMutex);
- m_I = i;
-}
-
-void PIDBase::SetD(double d) {
- std::scoped_lock lock(m_thisMutex);
- m_D = d;
-}
-
-void PIDBase::SetF(double f) {
- std::scoped_lock lock(m_thisMutex);
- m_F = f;
-}
-
-double PIDBase::GetP() const {
- std::scoped_lock lock(m_thisMutex);
- return m_P;
-}
-
-double PIDBase::GetI() const {
- std::scoped_lock lock(m_thisMutex);
- return m_I;
-}
-
-double PIDBase::GetD() const {
- std::scoped_lock lock(m_thisMutex);
- return m_D;
-}
-
-double PIDBase::GetF() const {
- std::scoped_lock lock(m_thisMutex);
- return m_F;
-}
-
-void PIDBase::SetSetpoint(double setpoint) {
- {
- std::scoped_lock lock(m_thisMutex);
-
- if (m_maximumInput > m_minimumInput) {
- if (setpoint > m_maximumInput)
- m_setpoint = m_maximumInput;
- else if (setpoint < m_minimumInput)
- m_setpoint = m_minimumInput;
- else
- m_setpoint = setpoint;
- } else {
- m_setpoint = setpoint;
- }
- }
-}
-
-double PIDBase::GetSetpoint() const {
- std::scoped_lock lock(m_thisMutex);
- return m_setpoint;
-}
-
-double PIDBase::GetDeltaSetpoint() const {
- std::scoped_lock lock(m_thisMutex);
- return (m_setpoint - m_prevSetpoint) / m_setpointTimer.Get();
-}
-
-double PIDBase::GetError() const {
- double setpoint = GetSetpoint();
- {
- std::scoped_lock lock(m_thisMutex);
- return GetContinuousError(setpoint - m_pidInput->PIDGet());
- }
-}
-
-double PIDBase::GetAvgError() const { return GetError(); }
-
-void PIDBase::SetPIDSourceType(PIDSourceType pidSource) {
- m_pidInput->SetPIDSourceType(pidSource);
-}
-
-PIDSourceType PIDBase::GetPIDSourceType() const {
- return m_pidInput->GetPIDSourceType();
-}
-
-void PIDBase::SetTolerance(double percent) {
- std::scoped_lock lock(m_thisMutex);
- m_toleranceType = kPercentTolerance;
- m_tolerance = percent;
-}
-
-void PIDBase::SetAbsoluteTolerance(double absTolerance) {
- std::scoped_lock lock(m_thisMutex);
- m_toleranceType = kAbsoluteTolerance;
- m_tolerance = absTolerance;
-}
-
-void PIDBase::SetPercentTolerance(double percent) {
- std::scoped_lock lock(m_thisMutex);
- m_toleranceType = kPercentTolerance;
- m_tolerance = percent;
-}
-
-void PIDBase::SetToleranceBuffer(int bufLength) {
- std::scoped_lock lock(m_thisMutex);
- m_filter = LinearFilter<double>::MovingAverage(bufLength);
-}
-
-bool PIDBase::OnTarget() const {
- double error = GetError();
-
- std::scoped_lock lock(m_thisMutex);
- switch (m_toleranceType) {
- case kPercentTolerance:
- return std::fabs(error) < m_tolerance / 100 * m_inputRange;
- break;
- case kAbsoluteTolerance:
- return std::fabs(error) < m_tolerance;
- break;
- case kNoTolerance:
- // TODO: this case needs an error
- return false;
- }
- return false;
-}
-
-void PIDBase::Reset() {
- std::scoped_lock lock(m_thisMutex);
- m_prevError = 0;
- m_totalError = 0;
- m_result = 0;
-}
-
-void PIDBase::PIDWrite(double output) { SetSetpoint(output); }
-
-void PIDBase::InitSendable(SendableBuilder& builder) {
- builder.SetSmartDashboardType("PIDController");
- builder.SetSafeState([=]() { Reset(); });
- builder.AddDoubleProperty(
- "p", [=]() { return GetP(); }, [=](double value) { SetP(value); });
- builder.AddDoubleProperty(
- "i", [=]() { return GetI(); }, [=](double value) { SetI(value); });
- builder.AddDoubleProperty(
- "d", [=]() { return GetD(); }, [=](double value) { SetD(value); });
- builder.AddDoubleProperty(
- "f", [=]() { return GetF(); }, [=](double value) { SetF(value); });
- builder.AddDoubleProperty(
- "setpoint", [=]() { return GetSetpoint(); },
- [=](double value) { SetSetpoint(value); });
-}
-
-void PIDBase::Calculate() {
- if (m_pidInput == nullptr || m_pidOutput == nullptr) return;
-
- bool enabled;
- {
- std::scoped_lock lock(m_thisMutex);
- enabled = m_enabled;
- }
-
- if (enabled) {
- double input;
-
- // Storage for function inputs
- PIDSourceType pidSourceType;
- double P;
- double I;
- double D;
- double feedForward = CalculateFeedForward();
- double minimumOutput;
- double maximumOutput;
-
- // Storage for function input-outputs
- double prevError;
- double error;
- double totalError;
-
- {
- std::scoped_lock lock(m_thisMutex);
-
- input = m_filter.Calculate(m_pidInput->PIDGet());
-
- pidSourceType = m_pidInput->GetPIDSourceType();
- P = m_P;
- I = m_I;
- D = m_D;
- minimumOutput = m_minimumOutput;
- maximumOutput = m_maximumOutput;
-
- prevError = m_prevError;
- error = GetContinuousError(m_setpoint - input);
- totalError = m_totalError;
- }
-
- // Storage for function outputs
- double result;
-
- if (pidSourceType == PIDSourceType::kRate) {
- if (P != 0) {
- totalError =
- clamp(totalError + error, minimumOutput / P, maximumOutput / P);
- }
-
- result = D * error + P * totalError + feedForward;
- } else {
- if (I != 0) {
- totalError =
- clamp(totalError + error, minimumOutput / I, maximumOutput / I);
- }
-
- result =
- P * error + I * totalError + D * (error - prevError) + feedForward;
- }
-
- result = clamp(result, minimumOutput, maximumOutput);
-
- {
- // Ensures m_enabled check and PIDWrite() call occur atomically
- std::scoped_lock pidWriteLock(m_pidWriteMutex);
- std::unique_lock mainLock(m_thisMutex);
- if (m_enabled) {
- // Don't block other PIDBase operations on PIDWrite()
- mainLock.unlock();
-
- m_pidOutput->PIDWrite(result);
- }
- }
-
- std::scoped_lock lock(m_thisMutex);
- m_prevError = m_error;
- m_error = error;
- m_totalError = totalError;
- m_result = result;
- }
-}
-
-double PIDBase::CalculateFeedForward() {
- if (m_pidInput->GetPIDSourceType() == PIDSourceType::kRate) {
- return m_F * GetSetpoint();
- } else {
- double temp = m_F * GetDeltaSetpoint();
- m_prevSetpoint = m_setpoint;
- m_setpointTimer.Reset();
- return temp;
- }
-}
-
-double PIDBase::GetContinuousError(double error) const {
- if (m_continuous && m_inputRange != 0) {
- error = std::fmod(error, m_inputRange);
- if (std::fabs(error) > m_inputRange / 2) {
- if (error > 0) {
- return error - m_inputRange;
- } else {
- return error + m_inputRange;
- }
- }
- }
-
- return error;
-}
diff --git a/wpilibc/src/main/native/cpp/PIDController.cpp b/wpilibc/src/main/native/cpp/PIDController.cpp
deleted file mode 100644
index a90a645..0000000
--- a/wpilibc/src/main/native/cpp/PIDController.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PIDController.h"
-
-#include "frc/Notifier.h"
-#include "frc/PIDOutput.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-
-using namespace frc;
-
-PIDController::PIDController(double Kp, double Ki, double Kd, PIDSource* source,
- PIDOutput* output, double period)
- : PIDController(Kp, Ki, Kd, 0.0, *source, *output, period) {}
-
-PIDController::PIDController(double Kp, double Ki, double Kd, double Kf,
- PIDSource* source, PIDOutput* output,
- double period)
- : PIDController(Kp, Ki, Kd, Kf, *source, *output, period) {}
-
-PIDController::PIDController(double Kp, double Ki, double Kd, PIDSource& source,
- PIDOutput& output, double period)
- : PIDController(Kp, Ki, Kd, 0.0, source, output, period) {}
-
-PIDController::PIDController(double Kp, double Ki, double Kd, double Kf,
- PIDSource& source, PIDOutput& output,
- double period)
- : PIDBase(Kp, Ki, Kd, Kf, source, output) {
- m_controlLoop = std::make_unique<Notifier>(&PIDController::Calculate, this);
- m_controlLoop->StartPeriodic(units::second_t(period));
-}
-
-PIDController::~PIDController() {
- // Forcefully stopping the notifier so the callback can successfully run.
- m_controlLoop->Stop();
-}
-
-void PIDController::Enable() {
- {
- std::scoped_lock lock(m_thisMutex);
- m_enabled = true;
- }
-}
-
-void PIDController::Disable() {
- {
- // Ensures m_enabled modification and PIDWrite() call occur atomically
- std::scoped_lock pidWriteLock(m_pidWriteMutex);
- {
- std::scoped_lock mainLock(m_thisMutex);
- m_enabled = false;
- }
-
- m_pidOutput->PIDWrite(0);
- }
-}
-
-void PIDController::SetEnabled(bool enable) {
- if (enable) {
- Enable();
- } else {
- Disable();
- }
-}
-
-bool PIDController::IsEnabled() const {
- std::scoped_lock lock(m_thisMutex);
- return m_enabled;
-}
-
-void PIDController::Reset() {
- Disable();
-
- PIDBase::Reset();
-}
-
-void PIDController::InitSendable(SendableBuilder& builder) {
- PIDBase::InitSendable(builder);
- builder.AddBooleanProperty(
- "enabled", [=]() { return IsEnabled(); },
- [=](bool value) { SetEnabled(value); });
-}
diff --git a/wpilibc/src/main/native/cpp/PIDSource.cpp b/wpilibc/src/main/native/cpp/PIDSource.cpp
deleted file mode 100644
index 28291dd..0000000
--- a/wpilibc/src/main/native/cpp/PIDSource.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PIDSource.h"
-
-using namespace frc;
-
-void PIDSource::SetPIDSourceType(PIDSourceType pidSource) {
- m_pidSource = pidSource;
-}
-
-PIDSourceType PIDSource::GetPIDSourceType() const { return m_pidSource; }
diff --git a/wpilibc/src/main/native/cpp/PS4Controller.cpp b/wpilibc/src/main/native/cpp/PS4Controller.cpp
new file mode 100644
index 0000000..91fd304
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/PS4Controller.cpp
@@ -0,0 +1,205 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/PS4Controller.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+PS4Controller::PS4Controller(int port) : GenericHID(port) {
+ HAL_Report(HALUsageReporting::kResourceType_PS4Controller, port + 1);
+}
+
+double PS4Controller::GetLeftX() const {
+ return GetRawAxis(Axis::kLeftX);
+}
+
+double PS4Controller::GetRightX() const {
+ return GetRawAxis(Axis::kRightX);
+}
+
+double PS4Controller::GetLeftY() const {
+ return GetRawAxis(Axis::kLeftY);
+}
+
+double PS4Controller::GetRightY() const {
+ return GetRawAxis(Axis::kRightY);
+}
+
+double PS4Controller::GetL2Axis() const {
+ return GetRawAxis(Axis::kL2);
+}
+
+double PS4Controller::GetR2Axis() const {
+ return GetRawAxis(Axis::kR2);
+}
+
+bool PS4Controller::GetSquareButton() const {
+ return GetRawButton(Button::kSquare);
+}
+
+bool PS4Controller::GetSquareButtonPressed() {
+ return GetRawButtonPressed(Button::kSquare);
+}
+
+bool PS4Controller::GetSquareButtonReleased() {
+ return GetRawButtonReleased(Button::kSquare);
+}
+
+bool PS4Controller::GetCrossButton() const {
+ return GetRawButton(Button::kCross);
+}
+
+bool PS4Controller::GetCrossButtonPressed() {
+ return GetRawButtonPressed(Button::kCross);
+}
+
+bool PS4Controller::GetCrossButtonReleased() {
+ return GetRawButtonReleased(Button::kCross);
+}
+
+bool PS4Controller::GetCircleButton() const {
+ return GetRawButton(Button::kCircle);
+}
+
+bool PS4Controller::GetCircleButtonPressed() {
+ return GetRawButtonPressed(Button::kCircle);
+}
+
+bool PS4Controller::GetCircleButtonReleased() {
+ return GetRawButtonReleased(Button::kCircle);
+}
+
+bool PS4Controller::GetTriangleButton() const {
+ return GetRawButton(Button::kTriangle);
+}
+
+bool PS4Controller::GetTriangleButtonPressed() {
+ return GetRawButtonPressed(Button::kTriangle);
+}
+
+bool PS4Controller::GetTriangleButtonReleased() {
+ return GetRawButtonReleased(Button::kTriangle);
+}
+
+bool PS4Controller::GetL1Button() const {
+ return GetRawButton(Button::kL1);
+}
+
+bool PS4Controller::GetL1ButtonPressed() {
+ return GetRawButtonPressed(Button::kL1);
+}
+
+bool PS4Controller::GetL1ButtonReleased() {
+ return GetRawButtonReleased(Button::kL1);
+}
+
+bool PS4Controller::GetR1Button() const {
+ return GetRawButton(Button::kR1);
+}
+
+bool PS4Controller::GetR1ButtonPressed() {
+ return GetRawButtonPressed(Button::kR1);
+}
+
+bool PS4Controller::GetR1ButtonReleased() {
+ return GetRawButtonReleased(Button::kR1);
+}
+
+bool PS4Controller::GetL2Button() const {
+ return GetRawButton(Button::kL2);
+}
+
+bool PS4Controller::GetL2ButtonPressed() {
+ return GetRawButtonPressed(Button::kL2);
+}
+
+bool PS4Controller::GetL2ButtonReleased() {
+ return GetRawButtonReleased(Button::kL2);
+}
+
+bool PS4Controller::GetR2Button() const {
+ return GetRawButton(Button::kR2);
+}
+
+bool PS4Controller::GetR2ButtonPressed() {
+ return GetRawButtonPressed(Button::kR2);
+}
+
+bool PS4Controller::GetR2ButtonReleased() {
+ return GetRawButtonReleased(Button::kR2);
+}
+
+bool PS4Controller::GetShareButton() const {
+ return GetRawButton(Button::kShare);
+}
+
+bool PS4Controller::GetShareButtonPressed() {
+ return GetRawButtonPressed(Button::kShare);
+}
+
+bool PS4Controller::GetShareButtonReleased() {
+ return GetRawButtonReleased(Button::kShare);
+}
+
+bool PS4Controller::GetOptionsButton() const {
+ return GetRawButton(Button::kOptions);
+}
+
+bool PS4Controller::GetOptionsButtonPressed() {
+ return GetRawButtonPressed(Button::kOptions);
+}
+
+bool PS4Controller::GetOptionsButtonReleased() {
+ return GetRawButtonReleased(Button::kOptions);
+}
+
+bool PS4Controller::GetL3Button() const {
+ return GetRawButton(Button::kL3);
+}
+
+bool PS4Controller::GetL3ButtonPressed() {
+ return GetRawButtonPressed(Button::kL3);
+}
+
+bool PS4Controller::GetL3ButtonReleased() {
+ return GetRawButtonReleased(Button::kL3);
+}
+
+bool PS4Controller::GetR3Button() const {
+ return GetRawButton(Button::kR3);
+}
+
+bool PS4Controller::GetR3ButtonPressed() {
+ return GetRawButtonPressed(Button::kR3);
+}
+
+bool PS4Controller::GetR3ButtonReleased() {
+ return GetRawButtonReleased(Button::kR3);
+}
+
+bool PS4Controller::GetPSButton() const {
+ return GetRawButton(Button::kPS);
+}
+
+bool PS4Controller::GetPSButtonPressed() {
+ return GetRawButtonPressed(Button::kPS);
+}
+
+bool PS4Controller::GetPSButtonReleased() {
+ return GetRawButtonReleased(Button::kPS);
+}
+
+bool PS4Controller::GetTouchpad() const {
+ return GetRawButton(Button::kTouchpad);
+}
+
+bool PS4Controller::GetTouchpadPressed() {
+ return GetRawButtonPressed(Button::kTouchpad);
+}
+
+bool PS4Controller::GetTouchpadReleased() {
+ return GetRawButtonReleased(Button::kTouchpad);
+}
diff --git a/wpilibc/src/main/native/cpp/PWM.cpp b/wpilibc/src/main/native/cpp/PWM.cpp
index c2cd2e2..393accc 100644
--- a/wpilibc/src/main/native/cpp/PWM.cpp
+++ b/wpilibc/src/main/native/cpp/PWM.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/PWM.h"
@@ -13,123 +10,97 @@
#include <hal/HALBase.h>
#include <hal/PWM.h>
#include <hal/Ports.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
-PWM::PWM(int channel) {
+PWM::PWM(int channel, bool registerSendable) {
if (!SensorUtil::CheckPWMChannel(channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "PWM Channel " + wpi::Twine(channel));
- return;
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", channel);
}
+ auto stack = wpi::GetStackTrace(1);
int32_t status = 0;
- m_handle = HAL_InitializePWMPort(HAL_GetPort(channel), &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumPWMChannels(), channel);
- m_channel = std::numeric_limits<int>::max();
- m_handle = HAL_kInvalidHandle;
- return;
- }
+ m_handle =
+ HAL_InitializePWMPort(HAL_GetPort(channel), stack.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
m_channel = channel;
HAL_SetPWMDisabled(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
status = 0;
HAL_SetPWMEliminateDeadband(m_handle, false, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", channel);
HAL_Report(HALUsageReporting::kResourceType_PWM, channel + 1);
- SendableRegistry::GetInstance().AddLW(this, "PWM", channel);
-
- SetSafetyEnabled(false);
+ if (registerSendable) {
+ wpi::SendableRegistry::AddLW(this, "PWM", channel);
+ }
}
PWM::~PWM() {
int32_t status = 0;
HAL_SetPWMDisabled(m_handle, &status);
- wpi_setHALError(status);
+ FRC_ReportError(status, "Channel {}", m_channel);
HAL_FreePWMPort(m_handle, &status);
- wpi_setHALError(status);
-}
-
-void PWM::StopMotor() { SetDisabled(); }
-
-void PWM::GetDescription(wpi::raw_ostream& desc) const {
- desc << "PWM " << GetChannel();
+ FRC_ReportError(status, "Channel {}", m_channel);
}
void PWM::SetRaw(uint16_t value) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
HAL_SetPWMRaw(m_handle, value, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
uint16_t PWM::GetRaw() const {
- if (StatusIsFatal()) return 0;
-
int32_t status = 0;
uint16_t value = HAL_GetPWMRaw(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return value;
}
void PWM::SetPosition(double pos) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetPWMPosition(m_handle, pos, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
double PWM::GetPosition() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double position = HAL_GetPWMPosition(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return position;
}
void PWM::SetSpeed(double speed) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetPWMSpeed(m_handle, speed, &status);
- wpi_setHALError(status);
-
- Feed();
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
double PWM::GetSpeed() const {
- if (StatusIsFatal()) return 0.0;
int32_t status = 0;
double speed = HAL_GetPWMSpeed(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
return speed;
}
void PWM::SetDisabled() {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
-
HAL_SetPWMDisabled(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void PWM::SetPeriodMultiplier(PeriodMultiplier mult) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
switch (mult) {
@@ -145,44 +116,39 @@
HAL_SetPWMPeriodScale(m_handle, 0, &status); // Don't squelch any outputs
break;
default:
- wpi_assert(false);
+ throw FRC_MakeError(err::InvalidParameter, "PeriodMultiplier value {}",
+ mult);
}
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void PWM::SetZeroLatch() {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
-
HAL_LatchPWMZero(m_handle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void PWM::EnableDeadbandElimination(bool eliminateDeadband) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetPWMEliminateDeadband(m_handle, eliminateDeadband, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void PWM::SetBounds(double max, double deadbandMax, double center,
double deadbandMin, double min) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetPWMConfig(m_handle, max, deadbandMax, center, deadbandMin, min,
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void PWM::SetRawBounds(int max, int deadbandMax, int center, int deadbandMin,
int min) {
- if (StatusIsFatal()) return;
int32_t status = 0;
HAL_SetPWMConfigRaw(m_handle, max, deadbandMax, center, deadbandMin, min,
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
void PWM::GetRawBounds(int* max, int* deadbandMax, int* center,
@@ -190,16 +156,17 @@
int32_t status = 0;
HAL_GetPWMConfigRaw(m_handle, max, deadbandMax, center, deadbandMin, min,
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
-int PWM::GetChannel() const { return m_channel; }
+int PWM::GetChannel() const {
+ return m_channel;
+}
-void PWM::InitSendable(SendableBuilder& builder) {
+void PWM::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("PWM");
builder.SetActuator(true);
- builder.SetSafeState([=]() { SetDisabled(); });
+ builder.SetSafeState([=] { SetDisabled(); });
builder.AddDoubleProperty(
- "Value", [=]() { return GetRaw(); },
- [=](double value) { SetRaw(value); });
+ "Value", [=] { return GetRaw(); }, [=](double value) { SetRaw(value); });
}
diff --git a/wpilibc/src/main/native/cpp/PWMSparkMax.cpp b/wpilibc/src/main/native/cpp/PWMSparkMax.cpp
deleted file mode 100644
index c5375f4..0000000
--- a/wpilibc/src/main/native/cpp/PWMSparkMax.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PWMSparkMax.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-PWMSparkMax::PWMSparkMax(int channel) : PWMSpeedController(channel) {
- SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_RevSparkMaxPWM, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "PWMSparkMax", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/PWMSpeedController.cpp b/wpilibc/src/main/native/cpp/PWMSpeedController.cpp
deleted file mode 100644
index ec0be7b..0000000
--- a/wpilibc/src/main/native/cpp/PWMSpeedController.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PWMSpeedController.h"
-
-#include "frc/smartdashboard/SendableBuilder.h"
-
-using namespace frc;
-
-void PWMSpeedController::Set(double speed) {
- SetSpeed(m_isInverted ? -speed : speed);
-}
-
-double PWMSpeedController::Get() const { return GetSpeed(); }
-
-void PWMSpeedController::SetInverted(bool isInverted) {
- m_isInverted = isInverted;
-}
-
-bool PWMSpeedController::GetInverted() const { return m_isInverted; }
-
-void PWMSpeedController::Disable() { SetDisabled(); }
-
-void PWMSpeedController::StopMotor() { PWM::StopMotor(); }
-
-void PWMSpeedController::PIDWrite(double output) { Set(output); }
-
-PWMSpeedController::PWMSpeedController(int channel) : PWM(channel) {}
-
-void PWMSpeedController::InitSendable(SendableBuilder& builder) {
- builder.SetSmartDashboardType("Speed Controller");
- builder.SetActuator(true);
- builder.SetSafeState([=]() { SetDisabled(); });
- builder.AddDoubleProperty(
- "Value", [=]() { return GetSpeed(); },
- [=](double value) { SetSpeed(value); });
-}
diff --git a/wpilibc/src/main/native/cpp/PWMTalonFX.cpp b/wpilibc/src/main/native/cpp/PWMTalonFX.cpp
deleted file mode 100644
index 09b7163..0000000
--- a/wpilibc/src/main/native/cpp/PWMTalonFX.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PWMTalonFX.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-PWMTalonFX::PWMTalonFX(int channel) : PWMSpeedController(channel) {
- SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_TalonFX, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "PWMTalonFX", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/PWMTalonSRX.cpp b/wpilibc/src/main/native/cpp/PWMTalonSRX.cpp
deleted file mode 100644
index 1242be9..0000000
--- a/wpilibc/src/main/native/cpp/PWMTalonSRX.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PWMTalonSRX.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-PWMTalonSRX::PWMTalonSRX(int channel) : PWMSpeedController(channel) {
- SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_PWMTalonSRX, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "PWMTalonSRX", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/PWMVenom.cpp b/wpilibc/src/main/native/cpp/PWMVenom.cpp
deleted file mode 100644
index 9fa14b7..0000000
--- a/wpilibc/src/main/native/cpp/PWMVenom.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PWMVenom.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-PWMVenom::PWMVenom(int channel) : PWMSpeedController(channel) {
- SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_FusionVenom, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "PWMVenom", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/PWMVictorSPX.cpp b/wpilibc/src/main/native/cpp/PWMVictorSPX.cpp
deleted file mode 100644
index 0d966ae..0000000
--- a/wpilibc/src/main/native/cpp/PWMVictorSPX.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PWMVictorSPX.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-PWMVictorSPX::PWMVictorSPX(int channel) : PWMSpeedController(channel) {
- SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_PWMVictorSPX, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "PWMVictorSPX", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/PneumaticHub.cpp b/wpilibc/src/main/native/cpp/PneumaticHub.cpp
new file mode 100644
index 0000000..8217e86
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/PneumaticHub.cpp
@@ -0,0 +1,209 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/PneumaticHub.h"
+
+#include <hal/REVPH.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/StackTrace.h>
+
+#include "frc/Compressor.h"
+#include "frc/DoubleSolenoid.h"
+#include "frc/Errors.h"
+#include "frc/SensorUtil.h"
+#include "frc/Solenoid.h"
+
+using namespace frc;
+
+wpi::mutex PneumaticHub::m_handleLock;
+std::unique_ptr<wpi::DenseMap<int, std::weak_ptr<PneumaticHub::DataStore>>>
+ PneumaticHub::m_handleMap = nullptr;
+
+// Always called under lock, so we can avoid the double lock from the magic
+// static
+std::weak_ptr<PneumaticHub::DataStore>& PneumaticHub::GetDataStore(int module) {
+ if (!m_handleMap) {
+ m_handleMap = std::make_unique<
+ wpi::DenseMap<int, std::weak_ptr<PneumaticHub::DataStore>>>();
+ }
+ return (*m_handleMap)[module];
+}
+
+class PneumaticHub::DataStore {
+ public:
+ explicit DataStore(int module, const char* stackTrace) {
+ int32_t status = 0;
+ HAL_REVPHHandle handle = HAL_InitializeREVPH(module, stackTrace, &status);
+ FRC_CheckErrorStatus(status, "Module {}", module);
+ m_moduleObject = PneumaticHub{handle, module};
+ m_moduleObject.m_dataStore =
+ std::shared_ptr<DataStore>{this, wpi::NullDeleter<DataStore>()};
+ }
+
+ ~DataStore() noexcept { HAL_FreeREVPH(m_moduleObject.m_handle); }
+
+ DataStore(DataStore&&) = delete;
+ DataStore& operator=(DataStore&&) = delete;
+
+ private:
+ friend class PneumaticHub;
+ uint32_t m_reservedMask{0};
+ bool m_compressorReserved{false};
+ wpi::mutex m_reservedLock;
+ PneumaticHub m_moduleObject{HAL_kInvalidHandle, 0};
+};
+
+PneumaticHub::PneumaticHub()
+ : PneumaticHub{SensorUtil::GetDefaultREVPHModule()} {}
+
+PneumaticHub::PneumaticHub(int module) {
+ std::string stackTrace = wpi::GetStackTrace(1);
+ std::scoped_lock lock(m_handleLock);
+ auto& res = GetDataStore(module);
+ m_dataStore = res.lock();
+ if (!m_dataStore) {
+ m_dataStore = std::make_shared<DataStore>(module, stackTrace.c_str());
+ res = m_dataStore;
+ }
+ m_handle = m_dataStore->m_moduleObject.m_handle;
+ m_module = module;
+}
+
+PneumaticHub::PneumaticHub(HAL_REVPHHandle handle, int module)
+ : m_handle{handle}, m_module{module} {}
+
+bool PneumaticHub::GetCompressor() const {
+ int32_t status = 0;
+ auto result = HAL_GetREVPHCompressor(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+void PneumaticHub::SetClosedLoopControl(bool enabled) {
+ int32_t status = 0;
+ HAL_SetREVPHClosedLoopControl(m_handle, enabled, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+bool PneumaticHub::GetClosedLoopControl() const {
+ int32_t status = 0;
+ auto result = HAL_GetREVPHClosedLoopControl(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+bool PneumaticHub::GetPressureSwitch() const {
+ int32_t status = 0;
+ auto result = HAL_GetREVPHPressureSwitch(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+double PneumaticHub::GetCompressorCurrent() const {
+ int32_t status = 0;
+ auto result = HAL_GetREVPHCompressorCurrent(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+void PneumaticHub::SetSolenoids(int mask, int values) {
+ int32_t status = 0;
+ HAL_SetREVPHSolenoids(m_handle, mask, values, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+int PneumaticHub::GetSolenoids() const {
+ int32_t status = 0;
+ auto result = HAL_GetREVPHSolenoids(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+int PneumaticHub::GetModuleNumber() const {
+ return m_module;
+}
+
+int PneumaticHub::GetSolenoidDisabledList() const {
+ return 0;
+ // TODO Fix me
+ // int32_t status = 0;
+ // auto result = HAL_GetREVPHSolenoidDisabledList(m_handle, &status);
+ // FRC_CheckErrorStatus(status, "Module {}", m_module);
+ // return result;
+}
+
+void PneumaticHub::FireOneShot(int index) {
+ // TODO Fix me
+ // int32_t status = 0;
+ // HAL_FireREVPHOneShot(m_handle, index, &status);
+ // FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+void PneumaticHub::SetOneShotDuration(int index, units::second_t duration) {
+ // TODO Fix me
+ // int32_t status = 0;
+ // units::millisecond_t millis = duration;
+ // HAL_SetREVPHOneShotDuration(m_handle, index, millis.to<int32_t>(),
+ // &status); FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+bool PneumaticHub::CheckSolenoidChannel(int channel) const {
+ return HAL_CheckREVPHSolenoidChannel(channel);
+}
+
+int PneumaticHub::CheckAndReserveSolenoids(int mask) {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ uint32_t uMask = static_cast<uint32_t>(mask);
+ if ((m_dataStore->m_reservedMask & uMask) != 0) {
+ return m_dataStore->m_reservedMask & uMask;
+ }
+ m_dataStore->m_reservedMask |= uMask;
+ return 0;
+}
+
+void PneumaticHub::UnreserveSolenoids(int mask) {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ m_dataStore->m_reservedMask &= ~(static_cast<uint32_t>(mask));
+}
+
+bool PneumaticHub::ReserveCompressor() {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ if (m_dataStore->m_compressorReserved) {
+ return false;
+ }
+ m_dataStore->m_compressorReserved = true;
+ return true;
+}
+
+void PneumaticHub::UnreserveCompressor() {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ m_dataStore->m_compressorReserved = false;
+}
+
+Solenoid PneumaticHub::MakeSolenoid(int channel) {
+ return Solenoid{m_module, PneumaticsModuleType::REVPH, channel};
+}
+
+DoubleSolenoid PneumaticHub::MakeDoubleSolenoid(int forwardChannel,
+ int reverseChannel) {
+ return DoubleSolenoid{m_module, PneumaticsModuleType::REVPH, forwardChannel,
+ reverseChannel};
+}
+
+Compressor PneumaticHub::MakeCompressor() {
+ return Compressor{m_module, PneumaticsModuleType::REVPH};
+}
+
+std::shared_ptr<PneumaticsBase> PneumaticHub::GetForModule(int module) {
+ std::string stackTrace = wpi::GetStackTrace(1);
+ std::scoped_lock lock(m_handleLock);
+ auto& res = GetDataStore(module);
+ std::shared_ptr<DataStore> dataStore = res.lock();
+ if (!dataStore) {
+ dataStore = std::make_shared<DataStore>(module, stackTrace.c_str());
+ res = dataStore;
+ }
+
+ return std::shared_ptr<PneumaticsBase>{dataStore, &dataStore->m_moduleObject};
+}
diff --git a/wpilibc/src/main/native/cpp/PneumaticsBase.cpp b/wpilibc/src/main/native/cpp/PneumaticsBase.cpp
new file mode 100644
index 0000000..9d96651
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/PneumaticsBase.cpp
@@ -0,0 +1,31 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/PneumaticsBase.h"
+
+#include "frc/Errors.h"
+#include "frc/PneumaticHub.h"
+#include "frc/PneumaticsControlModule.h"
+#include "frc/SensorUtil.h"
+
+using namespace frc;
+
+std::shared_ptr<PneumaticsBase> PneumaticsBase::GetForType(
+ int module, PneumaticsModuleType moduleType) {
+ if (moduleType == PneumaticsModuleType::CTREPCM) {
+ return PneumaticsControlModule::GetForModule(module);
+ } else if (moduleType == PneumaticsModuleType::REVPH) {
+ return PneumaticHub::GetForModule(module);
+ }
+ throw FRC_MakeError(err::InvalidParameter, "{}", moduleType);
+}
+
+int PneumaticsBase::GetDefaultForType(PneumaticsModuleType moduleType) {
+ if (moduleType == PneumaticsModuleType::CTREPCM) {
+ return SensorUtil::GetDefaultCTREPCMModule();
+ } else if (moduleType == PneumaticsModuleType::REVPH) {
+ return SensorUtil::GetDefaultREVPHModule();
+ }
+ throw FRC_MakeError(err::InvalidParameter, "{}", moduleType);
+}
diff --git a/wpilibc/src/main/native/cpp/PneumaticsControlModule.cpp b/wpilibc/src/main/native/cpp/PneumaticsControlModule.cpp
new file mode 100644
index 0000000..32de5ca
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/PneumaticsControlModule.cpp
@@ -0,0 +1,269 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/PneumaticsControlModule.h"
+
+#include <hal/CTREPCM.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/StackTrace.h>
+
+#include "frc/Compressor.h"
+#include "frc/DoubleSolenoid.h"
+#include "frc/Errors.h"
+#include "frc/SensorUtil.h"
+#include "frc/Solenoid.h"
+
+using namespace frc;
+
+wpi::mutex PneumaticsControlModule::m_handleLock;
+std::unique_ptr<
+ wpi::DenseMap<int, std::weak_ptr<PneumaticsControlModule::DataStore>>>
+ PneumaticsControlModule::m_handleMap = nullptr;
+
+// Always called under lock, so we can avoid the double lock from the magic
+// static
+std::weak_ptr<PneumaticsControlModule::DataStore>&
+PneumaticsControlModule::GetDataStore(int module) {
+ if (!m_handleMap) {
+ m_handleMap = std::make_unique<wpi::DenseMap<
+ int, std::weak_ptr<PneumaticsControlModule::DataStore>>>();
+ }
+ return (*m_handleMap)[module];
+}
+
+class PneumaticsControlModule::DataStore {
+ public:
+ explicit DataStore(int module, const char* stackTrace) {
+ int32_t status = 0;
+ HAL_CTREPCMHandle handle =
+ HAL_InitializeCTREPCM(module, stackTrace, &status);
+ FRC_CheckErrorStatus(status, "Module {}", module);
+ m_moduleObject = PneumaticsControlModule{handle, module};
+ m_moduleObject.m_dataStore =
+ std::shared_ptr<DataStore>{this, wpi::NullDeleter<DataStore>()};
+ }
+
+ ~DataStore() noexcept { HAL_FreeCTREPCM(m_moduleObject.m_handle); }
+
+ DataStore(DataStore&&) = delete;
+ DataStore& operator=(DataStore&&) = delete;
+
+ private:
+ friend class PneumaticsControlModule;
+ uint32_t m_reservedMask{0};
+ bool m_compressorReserved{false};
+ wpi::mutex m_reservedLock;
+ PneumaticsControlModule m_moduleObject{HAL_kInvalidHandle, 0};
+};
+
+PneumaticsControlModule::PneumaticsControlModule()
+ : PneumaticsControlModule{SensorUtil::GetDefaultCTREPCMModule()} {}
+
+PneumaticsControlModule::PneumaticsControlModule(int module) {
+ std::string stackTrace = wpi::GetStackTrace(1);
+ std::scoped_lock lock(m_handleLock);
+ auto& res = GetDataStore(module);
+ m_dataStore = res.lock();
+ if (!m_dataStore) {
+ m_dataStore = std::make_shared<DataStore>(module, stackTrace.c_str());
+ res = m_dataStore;
+ }
+ m_handle = m_dataStore->m_moduleObject.m_handle;
+ m_module = module;
+}
+
+PneumaticsControlModule::PneumaticsControlModule(HAL_CTREPCMHandle handle,
+ int module)
+ : m_handle{handle}, m_module{module} {}
+
+bool PneumaticsControlModule::GetCompressor() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMCompressor(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+void PneumaticsControlModule::SetClosedLoopControl(bool enabled) {
+ int32_t status = 0;
+ HAL_SetCTREPCMClosedLoopControl(m_handle, enabled, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+bool PneumaticsControlModule::GetClosedLoopControl() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMClosedLoopControl(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+bool PneumaticsControlModule::GetPressureSwitch() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMPressureSwitch(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+double PneumaticsControlModule::GetCompressorCurrent() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMCompressorCurrent(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+bool PneumaticsControlModule::GetCompressorCurrentTooHighFault() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMCompressorCurrentTooHighFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+bool PneumaticsControlModule::GetCompressorCurrentTooHighStickyFault() const {
+ int32_t status = 0;
+ auto result =
+ HAL_GetCTREPCMCompressorCurrentTooHighStickyFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+bool PneumaticsControlModule::GetCompressorShortedFault() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMCompressorShortedFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+bool PneumaticsControlModule::GetCompressorShortedStickyFault() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMCompressorShortedStickyFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+bool PneumaticsControlModule::GetCompressorNotConnectedFault() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMCompressorNotConnectedFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+bool PneumaticsControlModule::GetCompressorNotConnectedStickyFault() const {
+ int32_t status = 0;
+ auto result =
+ HAL_GetCTREPCMCompressorNotConnectedStickyFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+bool PneumaticsControlModule::GetSolenoidVoltageFault() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMSolenoidVoltageFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+bool PneumaticsControlModule::GetSolenoidVoltageStickyFault() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMSolenoidVoltageStickyFault(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+void PneumaticsControlModule::ClearAllStickyFaults() {
+ int32_t status = 0;
+ HAL_ClearAllCTREPCMStickyFaults(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+void PneumaticsControlModule::SetSolenoids(int mask, int values) {
+ int32_t status = 0;
+ HAL_SetCTREPCMSolenoids(m_handle, mask, values, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+int PneumaticsControlModule::GetSolenoids() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMSolenoids(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+int PneumaticsControlModule::GetModuleNumber() const {
+ return m_module;
+}
+
+int PneumaticsControlModule::GetSolenoidDisabledList() const {
+ int32_t status = 0;
+ auto result = HAL_GetCTREPCMSolenoidDisabledList(m_handle, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+ return result;
+}
+
+void PneumaticsControlModule::FireOneShot(int index) {
+ int32_t status = 0;
+ HAL_FireCTREPCMOneShot(m_handle, index, &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+void PneumaticsControlModule::SetOneShotDuration(int index,
+ units::second_t duration) {
+ int32_t status = 0;
+ units::millisecond_t millis = duration;
+ HAL_SetCTREPCMOneShotDuration(m_handle, index, millis.to<int32_t>(), &status);
+ FRC_CheckErrorStatus(status, "Module {}", m_module);
+}
+
+bool PneumaticsControlModule::CheckSolenoidChannel(int channel) const {
+ return HAL_CheckCTREPCMSolenoidChannel(channel);
+}
+
+int PneumaticsControlModule::CheckAndReserveSolenoids(int mask) {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ uint32_t uMask = static_cast<uint32_t>(mask);
+ if ((m_dataStore->m_reservedMask & uMask) != 0) {
+ return m_dataStore->m_reservedMask & uMask;
+ }
+ m_dataStore->m_reservedMask |= uMask;
+ return 0;
+}
+
+void PneumaticsControlModule::UnreserveSolenoids(int mask) {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ m_dataStore->m_reservedMask &= ~(static_cast<uint32_t>(mask));
+}
+
+bool PneumaticsControlModule::ReserveCompressor() {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ if (m_dataStore->m_compressorReserved) {
+ return false;
+ }
+ m_dataStore->m_compressorReserved = true;
+ return true;
+}
+
+void PneumaticsControlModule::UnreserveCompressor() {
+ std::scoped_lock lock{m_dataStore->m_reservedLock};
+ m_dataStore->m_compressorReserved = false;
+}
+
+Solenoid PneumaticsControlModule::MakeSolenoid(int channel) {
+ return Solenoid{m_module, PneumaticsModuleType::CTREPCM, channel};
+}
+
+DoubleSolenoid PneumaticsControlModule::MakeDoubleSolenoid(int forwardChannel,
+ int reverseChannel) {
+ return DoubleSolenoid{m_module, PneumaticsModuleType::CTREPCM, forwardChannel,
+ reverseChannel};
+}
+
+Compressor PneumaticsControlModule::MakeCompressor() {
+ return Compressor{m_module, PneumaticsModuleType::CTREPCM};
+}
+
+std::shared_ptr<PneumaticsBase> PneumaticsControlModule::GetForModule(
+ int module) {
+ std::string stackTrace = wpi::GetStackTrace(1);
+ std::scoped_lock lock(m_handleLock);
+ auto& res = GetDataStore(module);
+ std::shared_ptr<DataStore> dataStore = res.lock();
+ if (!dataStore) {
+ dataStore = std::make_shared<DataStore>(module, stackTrace.c_str());
+ res = dataStore;
+ }
+
+ return std::shared_ptr<PneumaticsBase>{dataStore, &dataStore->m_moduleObject};
+}
diff --git a/wpilibc/src/main/native/cpp/PowerDistribution.cpp b/wpilibc/src/main/native/cpp/PowerDistribution.cpp
new file mode 100644
index 0000000..4c2acfc
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/PowerDistribution.cpp
@@ -0,0 +1,146 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/PowerDistribution.h"
+
+#include <fmt/format.h>
+#include <hal/FRCUsageReporting.h>
+#include <hal/Ports.h>
+#include <hal/PowerDistribution.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
+#include "frc/Errors.h"
+#include "frc/SensorUtil.h"
+
+static_assert(static_cast<HAL_PowerDistributionType>(
+ frc::PowerDistribution::ModuleType::kAutomatic) ==
+ HAL_PowerDistributionType::HAL_PowerDistributionType_kAutomatic);
+static_assert(static_cast<HAL_PowerDistributionType>(
+ frc::PowerDistribution::ModuleType::kCTRE) ==
+ HAL_PowerDistributionType::HAL_PowerDistributionType_kCTRE);
+static_assert(static_cast<HAL_PowerDistributionType>(
+ frc::PowerDistribution::ModuleType::kRev) ==
+ HAL_PowerDistributionType::HAL_PowerDistributionType_kRev);
+static_assert(frc::PowerDistribution::kDefaultModule ==
+ HAL_DEFAULT_POWER_DISTRIBUTION_MODULE);
+
+using namespace frc;
+
+PowerDistribution::PowerDistribution()
+ : PowerDistribution(-1, ModuleType::kAutomatic) {}
+
+PowerDistribution::PowerDistribution(int module, ModuleType moduleType) {
+ auto stack = wpi::GetStackTrace(1);
+
+ int32_t status = 0;
+ m_handle = HAL_InitializePowerDistribution(
+ module, static_cast<HAL_PowerDistributionType>(moduleType), stack.c_str(),
+ &status);
+ FRC_CheckErrorStatus(status, "Module {}", module);
+ m_module = HAL_GetPowerDistributionModuleNumber(m_handle, &status);
+ FRC_ReportError(status, "Module {}", module);
+
+ HAL_Report(HALUsageReporting::kResourceType_PDP, m_module + 1);
+ wpi::SendableRegistry::AddLW(this, "PowerDistribution", m_module);
+}
+
+PowerDistribution::~PowerDistribution() {
+ if (m_handle != HAL_kInvalidHandle) {
+ HAL_CleanPowerDistribution(m_handle);
+ m_handle = HAL_kInvalidHandle;
+ }
+}
+
+double PowerDistribution::GetVoltage() const {
+ int32_t status = 0;
+ double voltage = HAL_GetPowerDistributionVoltage(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ return voltage;
+}
+
+double PowerDistribution::GetTemperature() const {
+ int32_t status = 0;
+ double temperature = HAL_GetPowerDistributionTemperature(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ return temperature;
+}
+
+double PowerDistribution::GetCurrent(int channel) const {
+ int32_t status = 0;
+ double current =
+ HAL_GetPowerDistributionChannelCurrent(m_handle, channel, &status);
+ FRC_ReportError(status, "Module {} Channel {}", m_module, channel);
+
+ return current;
+}
+
+double PowerDistribution::GetTotalCurrent() const {
+ int32_t status = 0;
+ double current = HAL_GetPowerDistributionTotalCurrent(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ return current;
+}
+
+double PowerDistribution::GetTotalPower() const {
+ int32_t status = 0;
+ double power = HAL_GetPowerDistributionTotalPower(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ return power;
+}
+
+double PowerDistribution::GetTotalEnergy() const {
+ int32_t status = 0;
+ double energy = HAL_GetPowerDistributionTotalEnergy(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ return energy;
+}
+
+void PowerDistribution::ResetTotalEnergy() {
+ int32_t status = 0;
+ HAL_ResetPowerDistributionTotalEnergy(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+}
+
+void PowerDistribution::ClearStickyFaults() {
+ int32_t status = 0;
+ HAL_ClearPowerDistributionStickyFaults(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+}
+
+int PowerDistribution::GetModule() const {
+ return m_module;
+}
+
+bool PowerDistribution::GetSwitchableChannel() const {
+ int32_t status = 0;
+ bool state = HAL_GetPowerDistributionSwitchableChannel(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ return state;
+}
+
+void PowerDistribution::SetSwitchableChannel(bool enabled) {
+ int32_t status = 0;
+ HAL_SetPowerDistributionSwitchableChannel(m_handle, enabled, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+}
+
+void PowerDistribution::InitSendable(wpi::SendableBuilder& builder) {
+ builder.SetSmartDashboardType("PowerDistribution");
+ int32_t status = 0;
+ int numChannels = HAL_GetPowerDistributionNumChannels(m_handle, &status);
+ FRC_ReportError(status, "Module {}", m_module);
+ for (int i = 0; i < numChannels; ++i) {
+ builder.AddDoubleProperty(
+ fmt::format("Chan{}", i), [=] { return GetCurrent(i); }, nullptr);
+ }
+ builder.AddDoubleProperty(
+ "Voltage", [=] { return GetVoltage(); }, nullptr);
+ builder.AddDoubleProperty(
+ "TotalCurrent", [=] { return GetTotalCurrent(); }, nullptr);
+ builder.AddBooleanProperty(
+ "SwitchableChannel", [=] { return GetSwitchableChannel(); },
+ [=](bool value) { SetSwitchableChannel(value); });
+}
diff --git a/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp b/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp
deleted file mode 100644
index 4070633..0000000
--- a/wpilibc/src/main/native/cpp/PowerDistributionPanel.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/PowerDistributionPanel.h"
-
-#include <hal/FRCUsageReporting.h>
-#include <hal/PDP.h>
-#include <hal/Ports.h>
-#include <wpi/SmallString.h>
-#include <wpi/raw_ostream.h>
-
-#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-PowerDistributionPanel::PowerDistributionPanel() : PowerDistributionPanel(0) {}
-
-/**
- * Initialize the PDP.
- */
-PowerDistributionPanel::PowerDistributionPanel(int module) : m_module(module) {
- int32_t status = 0;
- m_handle = HAL_InitializePDP(module, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumPDPModules(), module);
- return;
- }
-
- HAL_Report(HALUsageReporting::kResourceType_PDP, module + 1);
- SendableRegistry::GetInstance().AddLW(this, "PowerDistributionPanel", module);
-}
-
-double PowerDistributionPanel::GetVoltage() const {
- int32_t status = 0;
-
- double voltage = HAL_GetPDPVoltage(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-
- return voltage;
-}
-
-double PowerDistributionPanel::GetTemperature() const {
- int32_t status = 0;
-
- double temperature = HAL_GetPDPTemperature(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-
- return temperature;
-}
-
-double PowerDistributionPanel::GetCurrent(int channel) const {
- int32_t status = 0;
-
- if (!SensorUtil::CheckPDPChannel(channel)) {
- wpi::SmallString<32> str;
- wpi::raw_svector_ostream buf(str);
- buf << "PDP Channel " << channel;
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf.str());
- }
-
- double current = HAL_GetPDPChannelCurrent(m_handle, channel, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-
- return current;
-}
-
-double PowerDistributionPanel::GetTotalCurrent() const {
- int32_t status = 0;
-
- double current = HAL_GetPDPTotalCurrent(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-
- return current;
-}
-
-double PowerDistributionPanel::GetTotalPower() const {
- int32_t status = 0;
-
- double power = HAL_GetPDPTotalPower(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-
- return power;
-}
-
-double PowerDistributionPanel::GetTotalEnergy() const {
- int32_t status = 0;
-
- double energy = HAL_GetPDPTotalEnergy(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-
- return energy;
-}
-
-void PowerDistributionPanel::ResetTotalEnergy() {
- int32_t status = 0;
-
- HAL_ResetPDPTotalEnergy(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-}
-
-void PowerDistributionPanel::ClearStickyFaults() {
- int32_t status = 0;
-
- HAL_ClearPDPStickyFaults(m_handle, &status);
-
- if (status) {
- wpi_setWPIErrorWithContext(Timeout, "");
- }
-}
-
-int PowerDistributionPanel::GetModule() const { return m_module; }
-
-void PowerDistributionPanel::InitSendable(SendableBuilder& builder) {
- builder.SetSmartDashboardType("PowerDistributionPanel");
- for (int i = 0; i < SensorUtil::kPDPChannels; ++i) {
- builder.AddDoubleProperty(
- "Chan" + wpi::Twine(i), [=]() { return GetCurrent(i); }, nullptr);
- }
- builder.AddDoubleProperty(
- "Voltage", [=]() { return GetVoltage(); }, nullptr);
- builder.AddDoubleProperty(
- "TotalCurrent", [=]() { return GetTotalCurrent(); }, nullptr);
-}
diff --git a/wpilibc/src/main/native/cpp/Preferences.cpp b/wpilibc/src/main/native/cpp/Preferences.cpp
index 8c1eb87..0c82f54 100644
--- a/wpilibc/src/main/native/cpp/Preferences.cpp
+++ b/wpilibc/src/main/native/cpp/Preferences.cpp
@@ -1,128 +1,168 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Preferences.h"
#include <algorithm>
#include <hal/FRCUsageReporting.h>
+#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableInstance.h>
-#include <wpi/StringRef.h>
-
-#include "frc/WPIErrors.h"
using namespace frc;
// The Preferences table name
-static wpi::StringRef kTableName{"Preferences"};
+static constexpr std::string_view kTableName{"Preferences"};
+
+namespace {
+struct Instance {
+ Instance();
+
+ std::shared_ptr<nt::NetworkTable> table{
+ nt::NetworkTableInstance::GetDefault().GetTable(kTableName)};
+ NT_EntryListener listener;
+};
+} // namespace
+
+static Instance& GetInstance() {
+ static Instance instance;
+ return instance;
+}
Preferences* Preferences::GetInstance() {
+ ::GetInstance();
static Preferences instance;
return &instance;
}
-std::vector<std::string> Preferences::GetKeys() { return m_table->GetKeys(); }
-
-std::string Preferences::GetString(wpi::StringRef key,
- wpi::StringRef defaultValue) {
- return m_table->GetString(key, defaultValue);
+std::vector<std::string> Preferences::GetKeys() {
+ return ::GetInstance().table->GetKeys();
}
-int Preferences::GetInt(wpi::StringRef key, int defaultValue) {
- return static_cast<int>(m_table->GetNumber(key, defaultValue));
+std::string Preferences::GetString(std::string_view key,
+ std::string_view defaultValue) {
+ return ::GetInstance().table->GetString(key, defaultValue);
}
-double Preferences::GetDouble(wpi::StringRef key, double defaultValue) {
- return m_table->GetNumber(key, defaultValue);
+int Preferences::GetInt(std::string_view key, int defaultValue) {
+ return static_cast<int>(::GetInstance().table->GetNumber(key, defaultValue));
}
-float Preferences::GetFloat(wpi::StringRef key, float defaultValue) {
- return m_table->GetNumber(key, defaultValue);
+double Preferences::GetDouble(std::string_view key, double defaultValue) {
+ return ::GetInstance().table->GetNumber(key, defaultValue);
}
-bool Preferences::GetBoolean(wpi::StringRef key, bool defaultValue) {
- return m_table->GetBoolean(key, defaultValue);
+float Preferences::GetFloat(std::string_view key, float defaultValue) {
+ return ::GetInstance().table->GetNumber(key, defaultValue);
}
-int64_t Preferences::GetLong(wpi::StringRef key, int64_t defaultValue) {
- return static_cast<int64_t>(m_table->GetNumber(key, defaultValue));
+bool Preferences::GetBoolean(std::string_view key, bool defaultValue) {
+ return ::GetInstance().table->GetBoolean(key, defaultValue);
}
-void Preferences::PutString(wpi::StringRef key, wpi::StringRef value) {
- auto entry = m_table->GetEntry(key);
+int64_t Preferences::GetLong(std::string_view key, int64_t defaultValue) {
+ return static_cast<int64_t>(
+ ::GetInstance().table->GetNumber(key, defaultValue));
+}
+
+void Preferences::SetString(std::string_view key, std::string_view value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetString(value);
entry.SetPersistent();
}
-void Preferences::InitString(wpi::StringRef key, wpi::StringRef value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::PutString(std::string_view key, std::string_view value) {
+ SetString(key, value);
+}
+
+void Preferences::InitString(std::string_view key, std::string_view value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDefaultString(value);
}
-void Preferences::PutInt(wpi::StringRef key, int value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::SetInt(std::string_view key, int value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
-void Preferences::InitInt(wpi::StringRef key, int value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::PutInt(std::string_view key, int value) {
+ SetInt(key, value);
+}
+
+void Preferences::InitInt(std::string_view key, int value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDefaultDouble(value);
}
-void Preferences::PutDouble(wpi::StringRef key, double value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::SetDouble(std::string_view key, double value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
-void Preferences::InitDouble(wpi::StringRef key, double value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::PutDouble(std::string_view key, double value) {
+ SetDouble(key, value);
+}
+
+void Preferences::InitDouble(std::string_view key, double value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDefaultDouble(value);
}
-void Preferences::PutFloat(wpi::StringRef key, float value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::SetFloat(std::string_view key, float value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
-void Preferences::InitFloat(wpi::StringRef key, float value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::PutFloat(std::string_view key, float value) {
+ SetFloat(key, value);
+}
+
+void Preferences::InitFloat(std::string_view key, float value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDefaultDouble(value);
}
-void Preferences::PutBoolean(wpi::StringRef key, bool value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::SetBoolean(std::string_view key, bool value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetBoolean(value);
entry.SetPersistent();
}
-void Preferences::InitBoolean(wpi::StringRef key, bool value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::PutBoolean(std::string_view key, bool value) {
+ SetBoolean(key, value);
+}
+
+void Preferences::InitBoolean(std::string_view key, bool value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDefaultBoolean(value);
}
-void Preferences::PutLong(wpi::StringRef key, int64_t value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::SetLong(std::string_view key, int64_t value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDouble(value);
entry.SetPersistent();
}
-void Preferences::InitLong(wpi::StringRef key, int64_t value) {
- auto entry = m_table->GetEntry(key);
+void Preferences::PutLong(std::string_view key, int64_t value) {
+ SetLong(key, value);
+}
+
+void Preferences::InitLong(std::string_view key, int64_t value) {
+ auto entry = ::GetInstance().table->GetEntry(key);
entry.SetDefaultDouble(value);
}
-bool Preferences::ContainsKey(wpi::StringRef key) {
- return m_table->ContainsKey(key);
+bool Preferences::ContainsKey(std::string_view key) {
+ return ::GetInstance().table->ContainsKey(key);
}
-void Preferences::Remove(wpi::StringRef key) { m_table->Delete(key); }
+void Preferences::Remove(std::string_view key) {
+ ::GetInstance().table->Delete(key);
+}
void Preferences::RemoveAll() {
for (auto preference : GetKeys()) {
@@ -132,11 +172,10 @@
}
}
-Preferences::Preferences()
- : m_table(nt::NetworkTableInstance::GetDefault().GetTable(kTableName)) {
- m_table->GetEntry(".type").SetString("RobotPreferences");
- m_listener = m_table->AddEntryListener(
- [=](nt::NetworkTable* table, wpi::StringRef name,
+Instance::Instance() {
+ table->GetEntry(".type").SetString("RobotPreferences");
+ listener = table->AddEntryListener(
+ [=](nt::NetworkTable* table, std::string_view name,
nt::NetworkTableEntry entry, std::shared_ptr<nt::Value> value,
int flags) { entry.SetPersistent(); },
NT_NOTIFY_NEW | NT_NOTIFY_IMMEDIATE);
diff --git a/wpilibc/src/main/native/cpp/Relay.cpp b/wpilibc/src/main/native/cpp/Relay.cpp
index cb95223..9bec566 100644
--- a/wpilibc/src/main/native/cpp/Relay.cpp
+++ b/wpilibc/src/main/native/cpp/Relay.cpp
@@ -1,32 +1,29 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Relay.h"
#include <utility>
+#include <fmt/format.h>
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <hal/Ports.h>
#include <hal/Relay.h>
-#include <wpi/raw_ostream.h>
+#include <wpi/StackTrace.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
Relay::Relay(int channel, Relay::Direction direction)
: m_channel(channel), m_direction(direction) {
if (!SensorUtil::CheckRelayChannel(m_channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "Relay Channel " + wpi::Twine(m_channel));
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", m_channel);
return;
}
@@ -34,49 +31,32 @@
if (m_direction == kBothDirections || m_direction == kForwardOnly) {
int32_t status = 0;
- m_forwardHandle = HAL_InitializeRelayPort(portHandle, true, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumRelayChannels(), channel);
- m_forwardHandle = HAL_kInvalidHandle;
- m_reverseHandle = HAL_kInvalidHandle;
- return;
- }
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_forwardHandle =
+ HAL_InitializeRelayPort(portHandle, true, stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
HAL_Report(HALUsageReporting::kResourceType_Relay, m_channel + 1);
}
if (m_direction == kBothDirections || m_direction == kReverseOnly) {
int32_t status = 0;
- m_reverseHandle = HAL_InitializeRelayPort(portHandle, false, &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumRelayChannels(), channel);
- m_forwardHandle = HAL_kInvalidHandle;
- m_reverseHandle = HAL_kInvalidHandle;
- return;
- }
-
+ std::string stackTrace = wpi::GetStackTrace(1);
+ m_reverseHandle =
+ HAL_InitializeRelayPort(portHandle, false, stackTrace.c_str(), &status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
HAL_Report(HALUsageReporting::kResourceType_Relay, m_channel + 128);
}
int32_t status = 0;
if (m_forwardHandle != HAL_kInvalidHandle) {
HAL_SetRelay(m_forwardHandle, false, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_forwardHandle = HAL_kInvalidHandle;
- m_reverseHandle = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
if (m_reverseHandle != HAL_kInvalidHandle) {
HAL_SetRelay(m_reverseHandle, false, &status);
- if (status != 0) {
- wpi_setHALError(status);
- m_forwardHandle = HAL_kInvalidHandle;
- m_reverseHandle = HAL_kInvalidHandle;
- return;
- }
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
- SendableRegistry::GetInstance().AddLW(this, "Relay", m_channel);
+ wpi::SendableRegistry::AddLW(this, "Relay", m_channel);
}
Relay::~Relay() {
@@ -84,13 +64,15 @@
HAL_SetRelay(m_forwardHandle, false, &status);
HAL_SetRelay(m_reverseHandle, false, &status);
// ignore errors, as we want to make sure a free happens.
- if (m_forwardHandle != HAL_kInvalidHandle) HAL_FreeRelayPort(m_forwardHandle);
- if (m_reverseHandle != HAL_kInvalidHandle) HAL_FreeRelayPort(m_reverseHandle);
+ if (m_forwardHandle != HAL_kInvalidHandle) {
+ HAL_FreeRelayPort(m_forwardHandle);
+ }
+ if (m_reverseHandle != HAL_kInvalidHandle) {
+ HAL_FreeRelayPort(m_reverseHandle);
+ }
}
void Relay::Set(Relay::Value value) {
- if (StatusIsFatal()) return;
-
int32_t status = 0;
switch (value) {
@@ -112,7 +94,8 @@
break;
case kForward:
if (m_direction == kReverseOnly) {
- wpi_setWPIError(IncompatibleMode);
+ FRC_ReportError(err::IncompatibleMode, "channel {} setting {}",
+ m_channel, "forward");
break;
}
if (m_direction == kBothDirections || m_direction == kForwardOnly) {
@@ -124,7 +107,8 @@
break;
case kReverse:
if (m_direction == kForwardOnly) {
- wpi_setWPIError(IncompatibleMode);
+ FRC_ReportError(err::IncompatibleMode, "channel {} setting {}",
+ m_channel, "reverse");
break;
}
if (m_direction == kBothDirections) {
@@ -136,58 +120,65 @@
break;
}
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
}
Relay::Value Relay::Get() const {
- int32_t status;
+ Relay::Value value = kOff;
+ int32_t status = 0;
if (m_direction == kForwardOnly) {
if (HAL_GetRelay(m_forwardHandle, &status)) {
- return kOn;
+ value = kOn;
} else {
- return kOff;
+ value = kOff;
}
} else if (m_direction == kReverseOnly) {
if (HAL_GetRelay(m_reverseHandle, &status)) {
- return kOn;
+ value = kOn;
} else {
- return kOff;
+ value = kOff;
}
} else {
if (HAL_GetRelay(m_forwardHandle, &status)) {
if (HAL_GetRelay(m_reverseHandle, &status)) {
- return kOn;
+ value = kOn;
} else {
- return kForward;
+ value = kForward;
}
} else {
if (HAL_GetRelay(m_reverseHandle, &status)) {
- return kReverse;
+ value = kReverse;
} else {
- return kOff;
+ value = kOff;
}
}
}
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Channel {}", m_channel);
+
+ return value;
}
-int Relay::GetChannel() const { return m_channel; }
-
-void Relay::StopMotor() { Set(kOff); }
-
-void Relay::GetDescription(wpi::raw_ostream& desc) const {
- desc << "Relay " << GetChannel();
+int Relay::GetChannel() const {
+ return m_channel;
}
-void Relay::InitSendable(SendableBuilder& builder) {
+void Relay::StopMotor() {
+ Set(kOff);
+}
+
+std::string Relay::GetDescription() const {
+ return fmt::format("Relay {}", GetChannel());
+}
+
+void Relay::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Relay");
builder.SetActuator(true);
- builder.SetSafeState([=]() { Set(kOff); });
+ builder.SetSafeState([=] { Set(kOff); });
builder.AddSmallStringProperty(
"Value",
- [=](wpi::SmallVectorImpl<char>& buf) -> wpi::StringRef {
+ [=](wpi::SmallVectorImpl<char>& buf) -> std::string_view {
switch (Get()) {
case kOn:
return "On";
@@ -199,14 +190,15 @@
return "Off";
}
},
- [=](wpi::StringRef value) {
- if (value == "Off")
+ [=](std::string_view value) {
+ if (value == "Off") {
Set(kOff);
- else if (value == "Forward")
+ } else if (value == "Forward") {
Set(kForward);
- else if (value == "Reverse")
+ } else if (value == "Reverse") {
Set(kReverse);
- else if (value == "On")
+ } else if (value == "On") {
Set(kOn);
+ }
});
}
diff --git a/wpilibc/src/main/native/cpp/Resource.cpp b/wpilibc/src/main/native/cpp/Resource.cpp
index d546461..1f0e348 100644
--- a/wpilibc/src/main/native/cpp/Resource.cpp
+++ b/wpilibc/src/main/native/cpp/Resource.cpp
@@ -1,14 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Resource.h"
-#include "frc/ErrorBase.h"
-#include "frc/WPIErrors.h"
+#include "frc/Errors.h"
using namespace frc;
@@ -34,19 +30,16 @@
return i;
}
}
- wpi_setWPIErrorWithContext(NoAvailableResources, resourceDesc);
- return std::numeric_limits<uint32_t>::max();
+ throw FRC_MakeError(err::NoAvailableResources, "{}", resourceDesc);
}
uint32_t Resource::Allocate(uint32_t index, const std::string& resourceDesc) {
std::scoped_lock lock(m_allocateMutex);
if (index >= m_isAllocated.size()) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, resourceDesc);
- return std::numeric_limits<uint32_t>::max();
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "{}", resourceDesc);
}
if (m_isAllocated[index]) {
- wpi_setWPIErrorWithContext(ResourceAlreadyAllocated, resourceDesc);
- return std::numeric_limits<uint32_t>::max();
+ throw FRC_MakeError(err::ResourceAlreadyAllocated, "{}", resourceDesc);
}
m_isAllocated[index] = true;
return index;
@@ -54,14 +47,14 @@
void Resource::Free(uint32_t index) {
std::unique_lock lock(m_allocateMutex);
- if (index == std::numeric_limits<uint32_t>::max()) return;
- if (index >= m_isAllocated.size()) {
- wpi_setWPIError(NotAllocated);
+ if (index == std::numeric_limits<uint32_t>::max()) {
return;
}
+ if (index >= m_isAllocated.size()) {
+ throw FRC_MakeError(err::NotAllocated, "index {}", index);
+ }
if (!m_isAllocated[index]) {
- wpi_setWPIError(NotAllocated);
- return;
+ throw FRC_MakeError(err::NotAllocated, "index {}", index);
}
m_isAllocated[index] = false;
}
diff --git a/wpilibc/src/main/native/cpp/RobotController.cpp b/wpilibc/src/main/native/cpp/RobotController.cpp
index b33479f..8bc2d6b 100644
--- a/wpilibc/src/main/native/cpp/RobotController.cpp
+++ b/wpilibc/src/main/native/cpp/RobotController.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/RobotController.h"
@@ -11,152 +8,170 @@
#include <hal/HALBase.h>
#include <hal/Power.h>
-#include "frc/ErrorBase.h"
+#include "frc/Errors.h"
using namespace frc;
int RobotController::GetFPGAVersion() {
int32_t status = 0;
int version = HAL_GetFPGAVersion(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFPGAVersion");
return version;
}
int64_t RobotController::GetFPGARevision() {
int32_t status = 0;
int64_t revision = HAL_GetFPGARevision(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFPGARevision");
return revision;
}
uint64_t RobotController::GetFPGATime() {
int32_t status = 0;
uint64_t time = HAL_GetFPGATime(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFPGATime");
return time;
}
bool RobotController::GetUserButton() {
int32_t status = 0;
-
bool value = HAL_GetFPGAButton(&status);
- wpi_setGlobalError(status);
-
+ FRC_CheckErrorStatus(status, "{}", "GetUserButton");
return value;
}
+units::volt_t RobotController::GetBatteryVoltage() {
+ int32_t status = 0;
+ double retVal = HAL_GetVinVoltage(&status);
+ FRC_CheckErrorStatus(status, "{}", "GetBatteryVoltage");
+ return units::volt_t{retVal};
+}
+
bool RobotController::IsSysActive() {
int32_t status = 0;
bool retVal = HAL_GetSystemActive(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "IsSysActive");
return retVal;
}
bool RobotController::IsBrownedOut() {
int32_t status = 0;
bool retVal = HAL_GetBrownedOut(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "IsBrownedOut");
return retVal;
}
double RobotController::GetInputVoltage() {
int32_t status = 0;
double retVal = HAL_GetVinVoltage(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetInputVoltage");
return retVal;
}
double RobotController::GetInputCurrent() {
int32_t status = 0;
double retVal = HAL_GetVinCurrent(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetInputCurrent");
return retVal;
}
double RobotController::GetVoltage3V3() {
int32_t status = 0;
double retVal = HAL_GetUserVoltage3V3(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetVoltage3V3");
return retVal;
}
double RobotController::GetCurrent3V3() {
int32_t status = 0;
double retVal = HAL_GetUserCurrent3V3(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetCurrent3V3");
return retVal;
}
bool RobotController::GetEnabled3V3() {
int32_t status = 0;
bool retVal = HAL_GetUserActive3V3(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetEnabled3V3");
return retVal;
}
int RobotController::GetFaultCount3V3() {
int32_t status = 0;
int retVal = HAL_GetUserCurrentFaults3V3(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFaultCount3V3");
return retVal;
}
double RobotController::GetVoltage5V() {
int32_t status = 0;
double retVal = HAL_GetUserVoltage5V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetVoltage5V");
return retVal;
}
double RobotController::GetCurrent5V() {
int32_t status = 0;
double retVal = HAL_GetUserCurrent5V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetCurrent5V");
return retVal;
}
bool RobotController::GetEnabled5V() {
int32_t status = 0;
bool retVal = HAL_GetUserActive5V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetEnabled5V");
return retVal;
}
int RobotController::GetFaultCount5V() {
int32_t status = 0;
int retVal = HAL_GetUserCurrentFaults5V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFaultCount5V");
return retVal;
}
double RobotController::GetVoltage6V() {
int32_t status = 0;
double retVal = HAL_GetUserVoltage6V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetVoltage6V");
return retVal;
}
double RobotController::GetCurrent6V() {
int32_t status = 0;
double retVal = HAL_GetUserCurrent6V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetCurrent6V");
return retVal;
}
bool RobotController::GetEnabled6V() {
int32_t status = 0;
bool retVal = HAL_GetUserActive6V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetEnabled6V");
return retVal;
}
int RobotController::GetFaultCount6V() {
int32_t status = 0;
int retVal = HAL_GetUserCurrentFaults6V(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetFaultCount6V");
return retVal;
}
+units::volt_t RobotController::GetBrownoutVoltage() {
+ int32_t status = 0;
+ double retVal = HAL_GetBrownoutVoltage(&status);
+ FRC_CheckErrorStatus(status, "{}", "GetBrownoutVoltage");
+ return units::volt_t(retVal);
+}
+
+void RobotController::SetBrownoutVoltage(units::volt_t brownoutVoltage) {
+ int32_t status = 0;
+ HAL_SetBrownoutVoltage(brownoutVoltage.value(), &status);
+ FRC_CheckErrorStatus(status, "{}", "SetBrownoutVoltage");
+}
+
CANStatus RobotController::GetCANStatus() {
int32_t status = 0;
float percentBusUtilization = 0;
@@ -166,10 +181,7 @@
uint32_t transmitErrorCount = 0;
HAL_CAN_GetCANStatus(&percentBusUtilization, &busOffCount, &txFullCount,
&receiveErrorCount, &transmitErrorCount, &status);
- if (status != 0) {
- wpi_setGlobalHALError(status);
- return {};
- }
+ FRC_CheckErrorStatus(status, "{}", "GetCANStatus");
return {percentBusUtilization, static_cast<int>(busOffCount),
static_cast<int>(txFullCount), static_cast<int>(receiveErrorCount),
static_cast<int>(transmitErrorCount)};
diff --git a/wpilibc/src/main/native/cpp/RobotDrive.cpp b/wpilibc/src/main/native/cpp/RobotDrive.cpp
deleted file mode 100644
index 9eafe0c..0000000
--- a/wpilibc/src/main/native/cpp/RobotDrive.cpp
+++ /dev/null
@@ -1,427 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/RobotDrive.h"
-
-#include <algorithm>
-#include <cmath>
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/GenericHID.h"
-#include "frc/Joystick.h"
-#include "frc/Talon.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
-
-using namespace frc;
-
-static std::shared_ptr<SpeedController> make_shared_nodelete(
- SpeedController* ptr) {
- return std::shared_ptr<SpeedController>(ptr, NullDeleter<SpeedController>());
-}
-
-RobotDrive::RobotDrive(int leftMotorChannel, int rightMotorChannel) {
- InitRobotDrive();
- m_rearLeftMotor = std::make_shared<Talon>(leftMotorChannel);
- m_rearRightMotor = std::make_shared<Talon>(rightMotorChannel);
- SetLeftRightMotorOutputs(0.0, 0.0);
-}
-
-RobotDrive::RobotDrive(int frontLeftMotor, int rearLeftMotor,
- int frontRightMotor, int rearRightMotor) {
- InitRobotDrive();
- m_rearLeftMotor = std::make_shared<Talon>(rearLeftMotor);
- m_rearRightMotor = std::make_shared<Talon>(rearRightMotor);
- m_frontLeftMotor = std::make_shared<Talon>(frontLeftMotor);
- m_frontRightMotor = std::make_shared<Talon>(frontRightMotor);
- SetLeftRightMotorOutputs(0.0, 0.0);
-}
-
-RobotDrive::RobotDrive(SpeedController* leftMotor,
- SpeedController* rightMotor) {
- InitRobotDrive();
- if (leftMotor == nullptr || rightMotor == nullptr) {
- wpi_setWPIError(NullParameter);
- m_rearLeftMotor = m_rearRightMotor = nullptr;
- return;
- }
- m_rearLeftMotor = make_shared_nodelete(leftMotor);
- m_rearRightMotor = make_shared_nodelete(rightMotor);
-}
-
-RobotDrive::RobotDrive(SpeedController& leftMotor,
- SpeedController& rightMotor) {
- InitRobotDrive();
- m_rearLeftMotor = make_shared_nodelete(&leftMotor);
- m_rearRightMotor = make_shared_nodelete(&rightMotor);
-}
-
-RobotDrive::RobotDrive(std::shared_ptr<SpeedController> leftMotor,
- std::shared_ptr<SpeedController> rightMotor) {
- InitRobotDrive();
- if (leftMotor == nullptr || rightMotor == nullptr) {
- wpi_setWPIError(NullParameter);
- m_rearLeftMotor = m_rearRightMotor = nullptr;
- return;
- }
- m_rearLeftMotor = leftMotor;
- m_rearRightMotor = rightMotor;
-}
-
-RobotDrive::RobotDrive(SpeedController* frontLeftMotor,
- SpeedController* rearLeftMotor,
- SpeedController* frontRightMotor,
- SpeedController* rearRightMotor) {
- InitRobotDrive();
- if (frontLeftMotor == nullptr || rearLeftMotor == nullptr ||
- frontRightMotor == nullptr || rearRightMotor == nullptr) {
- wpi_setWPIError(NullParameter);
- return;
- }
- m_frontLeftMotor = make_shared_nodelete(frontLeftMotor);
- m_rearLeftMotor = make_shared_nodelete(rearLeftMotor);
- m_frontRightMotor = make_shared_nodelete(frontRightMotor);
- m_rearRightMotor = make_shared_nodelete(rearRightMotor);
-}
-
-RobotDrive::RobotDrive(SpeedController& frontLeftMotor,
- SpeedController& rearLeftMotor,
- SpeedController& frontRightMotor,
- SpeedController& rearRightMotor) {
- InitRobotDrive();
- m_frontLeftMotor = make_shared_nodelete(&frontLeftMotor);
- m_rearLeftMotor = make_shared_nodelete(&rearLeftMotor);
- m_frontRightMotor = make_shared_nodelete(&frontRightMotor);
- m_rearRightMotor = make_shared_nodelete(&rearRightMotor);
-}
-
-RobotDrive::RobotDrive(std::shared_ptr<SpeedController> frontLeftMotor,
- std::shared_ptr<SpeedController> rearLeftMotor,
- std::shared_ptr<SpeedController> frontRightMotor,
- std::shared_ptr<SpeedController> rearRightMotor) {
- InitRobotDrive();
- if (frontLeftMotor == nullptr || rearLeftMotor == nullptr ||
- frontRightMotor == nullptr || rearRightMotor == nullptr) {
- wpi_setWPIError(NullParameter);
- return;
- }
- m_frontLeftMotor = frontLeftMotor;
- m_rearLeftMotor = rearLeftMotor;
- m_frontRightMotor = frontRightMotor;
- m_rearRightMotor = rearRightMotor;
-}
-
-void RobotDrive::Drive(double outputMagnitude, double curve) {
- double leftOutput, rightOutput;
- static bool reported = false;
- if (!reported) {
- HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
- HALUsageReporting::kRobotDrive_ArcadeRatioCurve, GetNumMotors());
- reported = true;
- }
-
- if (curve < 0) {
- double value = std::log(-curve);
- double ratio = (value - m_sensitivity) / (value + m_sensitivity);
- if (ratio == 0) ratio = 0.0000000001;
- leftOutput = outputMagnitude / ratio;
- rightOutput = outputMagnitude;
- } else if (curve > 0) {
- double value = std::log(curve);
- double ratio = (value - m_sensitivity) / (value + m_sensitivity);
- if (ratio == 0) ratio = 0.0000000001;
- leftOutput = outputMagnitude;
- rightOutput = outputMagnitude / ratio;
- } else {
- leftOutput = outputMagnitude;
- rightOutput = outputMagnitude;
- }
- SetLeftRightMotorOutputs(leftOutput, rightOutput);
-}
-
-void RobotDrive::TankDrive(GenericHID* leftStick, GenericHID* rightStick,
- bool squaredInputs) {
- if (leftStick == nullptr || rightStick == nullptr) {
- wpi_setWPIError(NullParameter);
- return;
- }
- TankDrive(leftStick->GetY(), rightStick->GetY(), squaredInputs);
-}
-
-void RobotDrive::TankDrive(GenericHID& leftStick, GenericHID& rightStick,
- bool squaredInputs) {
- TankDrive(leftStick.GetY(), rightStick.GetY(), squaredInputs);
-}
-
-void RobotDrive::TankDrive(GenericHID* leftStick, int leftAxis,
- GenericHID* rightStick, int rightAxis,
- bool squaredInputs) {
- if (leftStick == nullptr || rightStick == nullptr) {
- wpi_setWPIError(NullParameter);
- return;
- }
- TankDrive(leftStick->GetRawAxis(leftAxis), rightStick->GetRawAxis(rightAxis),
- squaredInputs);
-}
-
-void RobotDrive::TankDrive(GenericHID& leftStick, int leftAxis,
- GenericHID& rightStick, int rightAxis,
- bool squaredInputs) {
- TankDrive(leftStick.GetRawAxis(leftAxis), rightStick.GetRawAxis(rightAxis),
- squaredInputs);
-}
-
-void RobotDrive::TankDrive(double leftValue, double rightValue,
- bool squaredInputs) {
- static bool reported = false;
- if (!reported) {
- HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
- HALUsageReporting::kRobotDrive_Tank, GetNumMotors());
- reported = true;
- }
-
- leftValue = Limit(leftValue);
- rightValue = Limit(rightValue);
-
- // square the inputs (while preserving the sign) to increase fine control
- // while permitting full power
- if (squaredInputs) {
- leftValue = std::copysign(leftValue * leftValue, leftValue);
- rightValue = std::copysign(rightValue * rightValue, rightValue);
- }
-
- SetLeftRightMotorOutputs(leftValue, rightValue);
-}
-
-void RobotDrive::ArcadeDrive(GenericHID* stick, bool squaredInputs) {
- // simply call the full-featured ArcadeDrive with the appropriate values
- ArcadeDrive(stick->GetY(), stick->GetX(), squaredInputs);
-}
-
-void RobotDrive::ArcadeDrive(GenericHID& stick, bool squaredInputs) {
- // simply call the full-featured ArcadeDrive with the appropriate values
- ArcadeDrive(stick.GetY(), stick.GetX(), squaredInputs);
-}
-
-void RobotDrive::ArcadeDrive(GenericHID* moveStick, int moveAxis,
- GenericHID* rotateStick, int rotateAxis,
- bool squaredInputs) {
- double moveValue = moveStick->GetRawAxis(moveAxis);
- double rotateValue = rotateStick->GetRawAxis(rotateAxis);
-
- ArcadeDrive(moveValue, rotateValue, squaredInputs);
-}
-
-void RobotDrive::ArcadeDrive(GenericHID& moveStick, int moveAxis,
- GenericHID& rotateStick, int rotateAxis,
- bool squaredInputs) {
- double moveValue = moveStick.GetRawAxis(moveAxis);
- double rotateValue = rotateStick.GetRawAxis(rotateAxis);
-
- ArcadeDrive(moveValue, rotateValue, squaredInputs);
-}
-
-void RobotDrive::ArcadeDrive(double moveValue, double rotateValue,
- bool squaredInputs) {
- static bool reported = false;
- if (!reported) {
- HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
- HALUsageReporting::kRobotDrive_ArcadeStandard, GetNumMotors());
- reported = true;
- }
-
- // local variables to hold the computed PWM values for the motors
- double leftMotorOutput;
- double rightMotorOutput;
-
- moveValue = Limit(moveValue);
- rotateValue = Limit(rotateValue);
-
- // square the inputs (while preserving the sign) to increase fine control
- // while permitting full power
- if (squaredInputs) {
- moveValue = std::copysign(moveValue * moveValue, moveValue);
- rotateValue = std::copysign(rotateValue * rotateValue, rotateValue);
- }
-
- if (moveValue > 0.0) {
- if (rotateValue > 0.0) {
- leftMotorOutput = moveValue - rotateValue;
- rightMotorOutput = std::max(moveValue, rotateValue);
- } else {
- leftMotorOutput = std::max(moveValue, -rotateValue);
- rightMotorOutput = moveValue + rotateValue;
- }
- } else {
- if (rotateValue > 0.0) {
- leftMotorOutput = -std::max(-moveValue, rotateValue);
- rightMotorOutput = moveValue + rotateValue;
- } else {
- leftMotorOutput = moveValue - rotateValue;
- rightMotorOutput = -std::max(-moveValue, -rotateValue);
- }
- }
- SetLeftRightMotorOutputs(leftMotorOutput, rightMotorOutput);
-}
-
-void RobotDrive::MecanumDrive_Cartesian(double x, double y, double rotation,
- double gyroAngle) {
- static bool reported = false;
- if (!reported) {
- HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
- HALUsageReporting::kRobotDrive_MecanumCartesian, GetNumMotors());
- reported = true;
- }
-
- double xIn = x;
- double yIn = y;
- // Negate y for the joystick.
- yIn = -yIn;
- // Compensate for gyro angle.
- RotateVector(xIn, yIn, gyroAngle);
-
- double wheelSpeeds[kMaxNumberOfMotors];
- wheelSpeeds[kFrontLeftMotor] = xIn + yIn + rotation;
- wheelSpeeds[kFrontRightMotor] = -xIn + yIn - rotation;
- wheelSpeeds[kRearLeftMotor] = -xIn + yIn + rotation;
- wheelSpeeds[kRearRightMotor] = xIn + yIn - rotation;
-
- Normalize(wheelSpeeds);
-
- m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput);
- m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput);
- m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput);
- m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput);
-
- Feed();
-}
-
-void RobotDrive::MecanumDrive_Polar(double magnitude, double direction,
- double rotation) {
- static bool reported = false;
- if (!reported) {
- HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
- HALUsageReporting::kRobotDrive_MecanumPolar, GetNumMotors());
- reported = true;
- }
-
- // Normalized for full power along the Cartesian axes.
- magnitude = Limit(magnitude) * std::sqrt(2.0);
- // The rollers are at 45 degree angles.
- double dirInRad = (direction + 45.0) * 3.14159 / 180.0;
- double cosD = std::cos(dirInRad);
- double sinD = std::sin(dirInRad);
-
- double wheelSpeeds[kMaxNumberOfMotors];
- wheelSpeeds[kFrontLeftMotor] = sinD * magnitude + rotation;
- wheelSpeeds[kFrontRightMotor] = cosD * magnitude - rotation;
- wheelSpeeds[kRearLeftMotor] = cosD * magnitude + rotation;
- wheelSpeeds[kRearRightMotor] = sinD * magnitude - rotation;
-
- Normalize(wheelSpeeds);
-
- m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput);
- m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput);
- m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput);
- m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput);
-
- Feed();
-}
-
-void RobotDrive::HolonomicDrive(double magnitude, double direction,
- double rotation) {
- MecanumDrive_Polar(magnitude, direction, rotation);
-}
-
-void RobotDrive::SetLeftRightMotorOutputs(double leftOutput,
- double rightOutput) {
- wpi_assert(m_rearLeftMotor != nullptr && m_rearRightMotor != nullptr);
-
- if (m_frontLeftMotor != nullptr)
- m_frontLeftMotor->Set(Limit(leftOutput) * m_maxOutput);
- m_rearLeftMotor->Set(Limit(leftOutput) * m_maxOutput);
-
- if (m_frontRightMotor != nullptr)
- m_frontRightMotor->Set(-Limit(rightOutput) * m_maxOutput);
- m_rearRightMotor->Set(-Limit(rightOutput) * m_maxOutput);
-
- Feed();
-}
-
-void RobotDrive::SetInvertedMotor(MotorType motor, bool isInverted) {
- if (motor < 0 || motor > 3) {
- wpi_setWPIError(InvalidMotorIndex);
- return;
- }
- switch (motor) {
- case kFrontLeftMotor:
- m_frontLeftMotor->SetInverted(isInverted);
- break;
- case kFrontRightMotor:
- m_frontRightMotor->SetInverted(isInverted);
- break;
- case kRearLeftMotor:
- m_rearLeftMotor->SetInverted(isInverted);
- break;
- case kRearRightMotor:
- m_rearRightMotor->SetInverted(isInverted);
- break;
- }
-}
-
-void RobotDrive::SetSensitivity(double sensitivity) {
- m_sensitivity = sensitivity;
-}
-
-void RobotDrive::SetMaxOutput(double maxOutput) { m_maxOutput = maxOutput; }
-
-void RobotDrive::GetDescription(wpi::raw_ostream& desc) const {
- desc << "RobotDrive";
-}
-
-void RobotDrive::StopMotor() {
- if (m_frontLeftMotor != nullptr) m_frontLeftMotor->StopMotor();
- if (m_frontRightMotor != nullptr) m_frontRightMotor->StopMotor();
- if (m_rearLeftMotor != nullptr) m_rearLeftMotor->StopMotor();
- if (m_rearRightMotor != nullptr) m_rearRightMotor->StopMotor();
- Feed();
-}
-
-void RobotDrive::InitRobotDrive() { SetSafetyEnabled(true); }
-
-double RobotDrive::Limit(double number) {
- if (number > 1.0) {
- return 1.0;
- }
- if (number < -1.0) {
- return -1.0;
- }
- return number;
-}
-
-void RobotDrive::Normalize(double* wheelSpeeds) {
- double maxMagnitude = std::fabs(wheelSpeeds[0]);
- for (int i = 1; i < kMaxNumberOfMotors; i++) {
- double temp = std::fabs(wheelSpeeds[i]);
- if (maxMagnitude < temp) maxMagnitude = temp;
- }
- if (maxMagnitude > 1.0) {
- for (int i = 0; i < kMaxNumberOfMotors; i++) {
- wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude;
- }
- }
-}
-
-void RobotDrive::RotateVector(double& x, double& y, double angle) {
- double cosA = std::cos(angle * (3.14159 / 180.0));
- double sinA = std::sin(angle * (3.14159 / 180.0));
- double xOut = x * cosA - y * sinA;
- double yOut = x * sinA + y * cosA;
- x = xOut;
- y = yOut;
-}
diff --git a/wpilibc/src/main/native/cpp/RobotState.cpp b/wpilibc/src/main/native/cpp/RobotState.cpp
index 530cee3..651a644 100644
--- a/wpilibc/src/main/native/cpp/RobotState.cpp
+++ b/wpilibc/src/main/native/cpp/RobotState.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/RobotState.h"
@@ -12,23 +9,29 @@
using namespace frc;
bool RobotState::IsDisabled() {
- return DriverStation::GetInstance().IsDisabled();
+ return DriverStation::IsDisabled();
}
bool RobotState::IsEnabled() {
- return DriverStation::GetInstance().IsEnabled();
+ return DriverStation::IsEnabled();
}
bool RobotState::IsEStopped() {
- return DriverStation::GetInstance().IsEStopped();
+ return DriverStation::IsEStopped();
}
bool RobotState::IsOperatorControl() {
- return DriverStation::GetInstance().IsOperatorControl();
+ return IsTeleop();
+}
+
+bool RobotState::IsTeleop() {
+ return DriverStation::IsTeleop();
}
bool RobotState::IsAutonomous() {
- return DriverStation::GetInstance().IsAutonomous();
+ return DriverStation::IsAutonomous();
}
-bool RobotState::IsTest() { return DriverStation::GetInstance().IsTest(); }
+bool RobotState::IsTest() {
+ return DriverStation::IsTest();
+}
diff --git a/wpilibc/src/main/native/cpp/SD540.cpp b/wpilibc/src/main/native/cpp/SD540.cpp
deleted file mode 100644
index 9611f66..0000000
--- a/wpilibc/src/main/native/cpp/SD540.cpp
+++ /dev/null
@@ -1,25 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/SD540.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-SD540::SD540(int channel) : PWMSpeedController(channel) {
- SetBounds(2.05, 1.55, 1.50, 1.44, 0.94);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_MindsensorsSD540,
- GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "SD540", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/SPI.cpp b/wpilibc/src/main/native/cpp/SPI.cpp
index d51fa3b..bdcee45 100644
--- a/wpilibc/src/main/native/cpp/SPI.cpp
+++ b/wpilibc/src/main/native/cpp/SPI.cpp
@@ -1,13 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/SPI.h"
#include <cstring>
+#include <memory>
#include <utility>
#include <hal/FRCUsageReporting.h>
@@ -16,8 +14,8 @@
#include <wpi/mutex.h>
#include "frc/DigitalSource.h"
+#include "frc/Errors.h"
#include "frc/Notifier.h"
-#include "frc/WPIErrors.h"
using namespace frc;
@@ -27,7 +25,7 @@
public:
Accumulator(HAL_SPIPort port, int xferSize, int validMask, int validValue,
int dataShift, int dataSize, bool isSigned, bool bigEndian)
- : m_notifier([=]() {
+ : m_notifier([=] {
std::scoped_lock lock(m_mutex);
Update();
}),
@@ -79,7 +77,7 @@
// get amount of data available
int32_t numToRead =
HAL_ReadSPIAutoReceivedData(m_port, m_buf, 0, 0, &status);
- if (status != 0) return; // error reading
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
// only get whole responses; +1 is for timestamp
numToRead -= numToRead % m_xferSize;
@@ -87,11 +85,13 @@
numToRead = m_xferSize * kAccumulateDepth;
done = false;
}
- if (numToRead == 0) return; // no samples
+ if (numToRead == 0) {
+ return; // no samples
+ }
// read buffered data
HAL_ReadSPIAutoReceivedData(m_port, m_buf, numToRead, 0, &status);
- if (status != 0) return; // error reading
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
// loop over all responses
for (int32_t off = 0; off < numToRead; off += m_xferSize) {
@@ -118,7 +118,9 @@
int32_t data = static_cast<int32_t>(resp >> m_dataShift);
data &= m_dataMax - 1;
// 2s complement conversion if signed MSB is set
- if (m_isSigned && (data & m_dataMsbMask) != 0) data -= m_dataMax;
+ if (m_isSigned && (data & m_dataMsbMask) != 0) {
+ data -= m_dataMax;
+ }
// center offset
int32_t dataNoCenter = data;
data -= m_center;
@@ -127,18 +129,19 @@
m_value += data;
if (m_count != 0) {
// timestamps use the 1us FPGA clock; also handle rollover
- if (timestamp >= m_lastTimestamp)
+ if (timestamp >= m_lastTimestamp) {
m_integratedValue +=
dataNoCenter *
static_cast<int32_t>(timestamp - m_lastTimestamp) * 1e-6 -
m_integratedCenter;
- else
+ } else {
m_integratedValue +=
dataNoCenter *
static_cast<int32_t>((1ULL << 32) - m_lastTimestamp +
timestamp) *
1e-6 -
m_integratedCenter;
+ }
}
}
++m_count;
@@ -155,15 +158,23 @@
SPI::SPI(Port port) : m_port(static_cast<HAL_SPIPort>(port)) {
int32_t status = 0;
HAL_InitializeSPI(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
HAL_Report(HALUsageReporting::kResourceType_SPI,
static_cast<uint8_t>(port) + 1);
}
-SPI::~SPI() { HAL_CloseSPI(m_port); }
+SPI::~SPI() {
+ HAL_CloseSPI(m_port);
+}
-void SPI::SetClockRate(int hz) { HAL_SetSPISpeed(m_port, hz); }
+SPI::Port SPI::GetPort() const {
+ return static_cast<Port>(static_cast<int>(m_port));
+}
+
+void SPI::SetClockRate(int hz) {
+ HAL_SetSPISpeed(m_port, hz);
+}
void SPI::SetMSBFirst() {
m_msbFirst = true;
@@ -208,13 +219,13 @@
void SPI::SetChipSelectActiveHigh() {
int32_t status = 0;
HAL_SetSPIChipSelectActiveHigh(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::SetChipSelectActiveLow() {
int32_t status = 0;
HAL_SetSPIChipSelectActiveLow(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
int SPI::Write(uint8_t* data, int size) {
@@ -244,26 +255,27 @@
void SPI::InitAuto(int bufferSize) {
int32_t status = 0;
HAL_InitSPIAuto(m_port, bufferSize, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::FreeAuto() {
int32_t status = 0;
HAL_FreeSPIAuto(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
-void SPI::SetAutoTransmitData(wpi::ArrayRef<uint8_t> dataToSend, int zeroSize) {
+void SPI::SetAutoTransmitData(wpi::span<const uint8_t> dataToSend,
+ int zeroSize) {
int32_t status = 0;
HAL_SetSPIAutoTransmitData(m_port, dataToSend.data(), dataToSend.size(),
zeroSize, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::StartAutoRate(units::second_t period) {
int32_t status = 0;
- HAL_StartSPIAutoRate(m_port, period.to<double>(), &status);
- wpi_setHALError(status);
+ HAL_StartSPIAutoRate(m_port, period.value(), &status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::StartAutoRate(double period) {
@@ -272,42 +284,38 @@
void SPI::StartAutoTrigger(DigitalSource& source, bool rising, bool falling) {
int32_t status = 0;
- HAL_StartSPIAutoTrigger(
- m_port, source.GetPortHandleForRouting(),
- (HAL_AnalogTriggerType)source.GetAnalogTriggerTypeForRouting(), rising,
- falling, &status);
- wpi_setHALError(status);
+ HAL_StartSPIAutoTrigger(m_port, source.GetPortHandleForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ source.GetAnalogTriggerTypeForRouting()),
+ rising, falling, &status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::StopAuto() {
int32_t status = 0;
HAL_StopSPIAuto(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::ForceAutoRead() {
int32_t status = 0;
HAL_ForceSPIAutoRead(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
int SPI::ReadAutoReceivedData(uint32_t* buffer, int numToRead,
units::second_t timeout) {
int32_t status = 0;
int32_t val = HAL_ReadSPIAutoReceivedData(m_port, buffer, numToRead,
- timeout.to<double>(), &status);
- wpi_setHALError(status);
+ timeout.value(), &status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
return val;
}
-int SPI::ReadAutoReceivedData(uint32_t* buffer, int numToRead, double timeout) {
- return ReadAutoReceivedData(buffer, numToRead, units::second_t(timeout));
-}
-
int SPI::GetAutoDroppedCount() {
int32_t status = 0;
int32_t val = HAL_GetSPIAutoDroppedCount(m_port, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
return val;
}
@@ -316,7 +324,7 @@
int32_t status = 0;
HAL_ConfigureSPIAutoStall(m_port, csToSclkTicks, stallTicks, pow2BytesPerRead,
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "Port {}", m_port);
}
void SPI::InitAccumulator(units::second_t period, int cmd, int xferSize,
@@ -341,8 +349,9 @@
SetAutoTransmitData(cmdBytes, xferSize - 4);
StartAutoRate(period);
- m_accum.reset(new Accumulator(m_port, xferSize, validMask, validValue,
- dataShift, dataSize, isSigned, bigEndian));
+ m_accum =
+ std::make_unique<Accumulator>(m_port, xferSize, validMask, validValue,
+ dataShift, dataSize, isSigned, bigEndian);
m_accum->m_notifier.StartPeriodic(period * kAccumulateDepth / 2);
}
@@ -359,7 +368,9 @@
}
void SPI::ResetAccumulator() {
- if (!m_accum) return;
+ if (!m_accum) {
+ return;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->m_value = 0;
m_accum->m_count = 0;
@@ -369,43 +380,57 @@
}
void SPI::SetAccumulatorCenter(int center) {
- if (!m_accum) return;
+ if (!m_accum) {
+ return;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->m_center = center;
}
void SPI::SetAccumulatorDeadband(int deadband) {
- if (!m_accum) return;
+ if (!m_accum) {
+ return;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->m_deadband = deadband;
}
int SPI::GetAccumulatorLastValue() const {
- if (!m_accum) return 0;
+ if (!m_accum) {
+ return 0;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->Update();
return m_accum->m_lastValue;
}
int64_t SPI::GetAccumulatorValue() const {
- if (!m_accum) return 0;
+ if (!m_accum) {
+ return 0;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->Update();
return m_accum->m_value;
}
int64_t SPI::GetAccumulatorCount() const {
- if (!m_accum) return 0;
+ if (!m_accum) {
+ return 0;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->Update();
return m_accum->m_count;
}
double SPI::GetAccumulatorAverage() const {
- if (!m_accum) return 0;
+ if (!m_accum) {
+ return 0;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->Update();
- if (m_accum->m_count == 0) return 0.0;
+ if (m_accum->m_count == 0) {
+ return 0.0;
+ }
return static_cast<double>(m_accum->m_value) / m_accum->m_count;
}
@@ -422,23 +447,31 @@
}
void SPI::SetAccumulatorIntegratedCenter(double center) {
- if (!m_accum) return;
+ if (!m_accum) {
+ return;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->m_integratedCenter = center;
}
double SPI::GetAccumulatorIntegratedValue() const {
- if (!m_accum) return 0;
+ if (!m_accum) {
+ return 0;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->Update();
return m_accum->m_integratedValue;
}
double SPI::GetAccumulatorIntegratedAverage() const {
- if (!m_accum) return 0;
+ if (!m_accum) {
+ return 0;
+ }
std::scoped_lock lock(m_accum->m_mutex);
m_accum->Update();
- if (m_accum->m_count <= 1) return 0.0;
+ if (m_accum->m_count <= 1) {
+ return 0.0;
+ }
// count-1 due to not integrating the first value received
return m_accum->m_integratedValue / (m_accum->m_count - 1);
}
diff --git a/wpilibc/src/main/native/cpp/ScopedTracer.cpp b/wpilibc/src/main/native/cpp/ScopedTracer.cpp
index 2024a65..3c8fc80 100644
--- a/wpilibc/src/main/native/cpp/ScopedTracer.cpp
+++ b/wpilibc/src/main/native/cpp/ScopedTracer.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/ScopedTracer.h"
@@ -11,8 +8,8 @@
using namespace frc;
-ScopedTracer::ScopedTracer(wpi::Twine name, wpi::raw_ostream& os)
- : m_name(name.str()), m_os(os) {
+ScopedTracer::ScopedTracer(std::string_view name, wpi::raw_ostream& os)
+ : m_name(name), m_os(os) {
m_tracer.ResetTimer();
}
diff --git a/wpilibc/src/main/native/cpp/SensorUtil.cpp b/wpilibc/src/main/native/cpp/SensorUtil.cpp
index f86c72c..55aacce 100644
--- a/wpilibc/src/main/native/cpp/SensorUtil.cpp
+++ b/wpilibc/src/main/native/cpp/SensorUtil.cpp
@@ -1,36 +1,30 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/SensorUtil.h"
#include <hal/AnalogInput.h>
#include <hal/AnalogOutput.h>
#include <hal/DIO.h>
-#include <hal/PDP.h>
#include <hal/PWM.h>
#include <hal/Ports.h>
#include <hal/Relay.h>
-#include <hal/Solenoid.h>
using namespace frc;
const int SensorUtil::kDigitalChannels = HAL_GetNumDigitalChannels();
const int SensorUtil::kAnalogInputs = HAL_GetNumAnalogInputs();
const int SensorUtil::kAnalogOutputs = HAL_GetNumAnalogOutputs();
-const int SensorUtil::kSolenoidChannels = HAL_GetNumSolenoidChannels();
-const int SensorUtil::kSolenoidModules = HAL_GetNumPCMModules();
const int SensorUtil::kPwmChannels = HAL_GetNumPWMChannels();
const int SensorUtil::kRelayChannels = HAL_GetNumRelayHeaders();
-const int SensorUtil::kPDPChannels = HAL_GetNumPDPChannels();
-int SensorUtil::GetDefaultSolenoidModule() { return 0; }
+int SensorUtil::GetDefaultCTREPCMModule() {
+ return 0;
+}
-bool SensorUtil::CheckSolenoidModule(int moduleNumber) {
- return HAL_CheckSolenoidModule(moduleNumber);
+int SensorUtil::GetDefaultREVPHModule() {
+ return 1;
}
bool SensorUtil::CheckDigitalChannel(int channel) {
@@ -52,15 +46,3 @@
bool SensorUtil::CheckAnalogOutputChannel(int channel) {
return HAL_CheckAnalogOutputChannel(channel);
}
-
-bool SensorUtil::CheckSolenoidChannel(int channel) {
- return HAL_CheckSolenoidChannel(channel);
-}
-
-bool SensorUtil::CheckPDPChannel(int channel) {
- return HAL_CheckPDPChannel(channel);
-}
-
-bool SensorUtil::CheckPDPModule(int module) {
- return HAL_CheckPDPModule(module);
-}
diff --git a/wpilibc/src/main/native/cpp/SerialPort.cpp b/wpilibc/src/main/native/cpp/SerialPort.cpp
index e092fc2..fb984f1 100644
--- a/wpilibc/src/main/native/cpp/SerialPort.cpp
+++ b/wpilibc/src/main/native/cpp/SerialPort.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/SerialPort.h"
@@ -12,6 +9,8 @@
#include <hal/FRCUsageReporting.h>
#include <hal/SerialPort.h>
+#include "frc/Errors.h"
+
using namespace frc;
SerialPort::SerialPort(int baudRate, Port port, int dataBits,
@@ -21,20 +20,18 @@
m_portHandle =
HAL_InitializeSerialPort(static_cast<HAL_SerialPort>(port), &status);
- wpi_setHALError(status);
- // Don't continue if initialization failed
- if (status < 0) return;
+ FRC_CheckErrorStatus(status, "Port {}", port);
HAL_SetSerialBaudRate(m_portHandle, baudRate, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialBaudRate {}", baudRate);
HAL_SetSerialDataBits(m_portHandle, dataBits, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialDataBits {}", dataBits);
HAL_SetSerialParity(m_portHandle, parity, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialParity {}", parity);
HAL_SetSerialStopBits(m_portHandle, stopBits, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialStopBits {}", stopBits);
// Set the default timeout to 5 seconds.
- SetTimeout(5.0);
+ SetTimeout(5_s);
// Don't wait until the buffer is full to transmit.
SetWriteBufferMode(kFlushOnAccess);
@@ -45,30 +42,26 @@
static_cast<uint8_t>(port) + 1);
}
-SerialPort::SerialPort(int baudRate, const wpi::Twine& portName, Port port,
+SerialPort::SerialPort(int baudRate, std::string_view portName, Port port,
int dataBits, SerialPort::Parity parity,
SerialPort::StopBits stopBits) {
int32_t status = 0;
- wpi::SmallVector<char, 64> buf;
- const char* portNameC = portName.toNullTerminatedStringRef(buf).data();
-
- m_portHandle = HAL_InitializeSerialPortDirect(
- static_cast<HAL_SerialPort>(port), portNameC, &status);
- wpi_setHALError(status);
- // Don't continue if initialization failed
- if (status < 0) return;
+ m_portHandle =
+ HAL_InitializeSerialPortDirect(static_cast<HAL_SerialPort>(port),
+ std::string(portName).c_str(), &status);
+ FRC_CheckErrorStatus(status, "Port {}", port);
HAL_SetSerialBaudRate(m_portHandle, baudRate, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialBaudRate {}", baudRate);
HAL_SetSerialDataBits(m_portHandle, dataBits, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialDataBits {}", dataBits);
HAL_SetSerialParity(m_portHandle, parity, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialParity {}", parity);
HAL_SetSerialStopBits(m_portHandle, stopBits, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetSerialStopBits {}", stopBits);
// Set the default timeout to 5 seconds.
- SetTimeout(5.0);
+ SetTimeout(5_s);
// Don't wait until the buffer is full to transmit.
SetWriteBufferMode(kFlushOnAccess);
@@ -82,85 +75,85 @@
SerialPort::~SerialPort() {
int32_t status = 0;
HAL_CloseSerial(m_portHandle, &status);
- wpi_setHALError(status);
+ FRC_ReportError(status, "{}", "CloseSerial");
}
void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl) {
int32_t status = 0;
HAL_SetSerialFlowControl(m_portHandle, flowControl, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetFlowControl {}", flowControl);
}
void SerialPort::EnableTermination(char terminator) {
int32_t status = 0;
HAL_EnableSerialTermination(m_portHandle, terminator, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "EnableTermination {}", terminator);
}
void SerialPort::DisableTermination() {
int32_t status = 0;
HAL_DisableSerialTermination(m_portHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "DisableTermination");
}
int SerialPort::GetBytesReceived() {
int32_t status = 0;
int retVal = HAL_GetSerialBytesReceived(m_portHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetBytesReceived");
return retVal;
}
int SerialPort::Read(char* buffer, int count) {
int32_t status = 0;
int retVal = HAL_ReadSerial(m_portHandle, buffer, count, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Read");
return retVal;
}
int SerialPort::Write(const char* buffer, int count) {
- return Write(wpi::StringRef(buffer, static_cast<size_t>(count)));
+ return Write(std::string_view(buffer, static_cast<size_t>(count)));
}
-int SerialPort::Write(wpi::StringRef buffer) {
+int SerialPort::Write(std::string_view buffer) {
int32_t status = 0;
int retVal =
HAL_WriteSerial(m_portHandle, buffer.data(), buffer.size(), &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Write");
return retVal;
}
-void SerialPort::SetTimeout(double timeout) {
+void SerialPort::SetTimeout(units::second_t timeout) {
int32_t status = 0;
- HAL_SetSerialTimeout(m_portHandle, timeout, &status);
- wpi_setHALError(status);
+ HAL_SetSerialTimeout(m_portHandle, timeout.value(), &status);
+ FRC_CheckErrorStatus(status, "{}", "SetTimeout");
}
void SerialPort::SetReadBufferSize(int size) {
int32_t status = 0;
HAL_SetSerialReadBufferSize(m_portHandle, size, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetReadBufferSize {}", size);
}
void SerialPort::SetWriteBufferSize(int size) {
int32_t status = 0;
HAL_SetSerialWriteBufferSize(m_portHandle, size, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetWriteBufferSize {}", size);
}
void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode) {
int32_t status = 0;
HAL_SetSerialWriteMode(m_portHandle, mode, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "SetWriteBufferMode {}", mode);
}
void SerialPort::Flush() {
int32_t status = 0;
HAL_FlushSerial(m_portHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Flush");
}
void SerialPort::Reset() {
int32_t status = 0;
HAL_ClearSerial(m_portHandle, &status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "Reset");
}
diff --git a/wpilibc/src/main/native/cpp/Servo.cpp b/wpilibc/src/main/native/cpp/Servo.cpp
index 5edcebc..c410bff 100644
--- a/wpilibc/src/main/native/cpp/Servo.cpp
+++ b/wpilibc/src/main/native/cpp/Servo.cpp
@@ -1,16 +1,12 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Servo.h"
#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
using namespace frc;
@@ -28,14 +24,20 @@
SetPeriodMultiplier(kPeriodMultiplier_4X);
HAL_Report(HALUsageReporting::kResourceType_Servo, channel + 1);
- SendableRegistry::GetInstance().SetName(this, "Servo", channel);
+ wpi::SendableRegistry::SetName(this, "Servo", channel);
}
-void Servo::Set(double value) { SetPosition(value); }
+void Servo::Set(double value) {
+ SetPosition(value);
+}
-void Servo::SetOffline() { SetRaw(0); }
+void Servo::SetOffline() {
+ SetRaw(0);
+}
-double Servo::Get() const { return GetPosition(); }
+double Servo::Get() const {
+ return GetPosition();
+}
void Servo::SetAngle(double degrees) {
if (degrees < kMinServoAngle) {
@@ -51,14 +53,18 @@
return GetPosition() * GetServoAngleRange() + kMinServoAngle;
}
-double Servo::GetMaxAngle() const { return kMaxServoAngle; }
+double Servo::GetMaxAngle() const {
+ return kMaxServoAngle;
+}
-double Servo::GetMinAngle() const { return kMinServoAngle; }
+double Servo::GetMinAngle() const {
+ return kMinServoAngle;
+}
-void Servo::InitSendable(SendableBuilder& builder) {
+void Servo::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Servo");
builder.AddDoubleProperty(
- "Value", [=]() { return Get(); }, [=](double value) { Set(value); });
+ "Value", [=] { return Get(); }, [=](double value) { Set(value); });
}
double Servo::GetServoAngleRange() const {
diff --git a/wpilibc/src/main/native/cpp/Solenoid.cpp b/wpilibc/src/main/native/cpp/Solenoid.cpp
index b5abf20..49000c2 100644
--- a/wpilibc/src/main/native/cpp/Solenoid.cpp
+++ b/wpilibc/src/main/native/cpp/Solenoid.cpp
@@ -1,103 +1,81 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Solenoid.h"
#include <utility>
#include <hal/FRCUsageReporting.h>
-#include <hal/HALBase.h>
-#include <hal/Ports.h>
-#include <hal/Solenoid.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/SensorUtil.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
-Solenoid::Solenoid(int channel)
- : Solenoid(SensorUtil::GetDefaultSolenoidModule(), channel) {}
-
-Solenoid::Solenoid(int moduleNumber, int channel)
- : SolenoidBase(moduleNumber), m_channel(channel) {
- if (!SensorUtil::CheckSolenoidModule(m_moduleNumber)) {
- wpi_setWPIErrorWithContext(ModuleIndexOutOfRange,
- "Solenoid Module " + wpi::Twine(m_moduleNumber));
- return;
+Solenoid::Solenoid(int module, PneumaticsModuleType moduleType, int channel)
+ : m_module{PneumaticsBase::GetForType(module, moduleType)},
+ m_channel{channel} {
+ if (!m_module->CheckSolenoidChannel(m_channel)) {
+ throw FRC_MakeError(err::ChannelIndexOutOfRange, "Channel {}", m_channel);
}
- if (!SensorUtil::CheckSolenoidChannel(m_channel)) {
- wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
- "Solenoid Channel " + wpi::Twine(m_channel));
- return;
- }
+ m_mask = 1 << channel;
- int32_t status = 0;
- m_solenoidHandle = HAL_InitializeSolenoidPort(
- HAL_GetPortWithModule(moduleNumber, channel), &status);
- if (status != 0) {
- wpi_setHALErrorWithRange(status, 0, HAL_GetNumSolenoidChannels(), channel);
- m_solenoidHandle = HAL_kInvalidHandle;
- return;
+ if (m_module->CheckAndReserveSolenoids(m_mask) != 0) {
+ throw FRC_MakeError(err::ResourceAlreadyAllocated, "Channel {}", m_channel);
}
HAL_Report(HALUsageReporting::kResourceType_Solenoid, m_channel + 1,
- m_moduleNumber + 1);
- SendableRegistry::GetInstance().AddLW(this, "Solenoid", m_moduleNumber,
- m_channel);
+ m_module->GetModuleNumber() + 1);
+ wpi::SendableRegistry::AddLW(this, "Solenoid", m_module->GetModuleNumber(),
+ m_channel);
}
-Solenoid::~Solenoid() { HAL_FreeSolenoidPort(m_solenoidHandle); }
+Solenoid::Solenoid(PneumaticsModuleType moduleType, int channel)
+ : Solenoid{PneumaticsBase::GetDefaultForType(moduleType), moduleType,
+ channel} {}
+
+Solenoid::~Solenoid() {
+ m_module->UnreserveSolenoids(m_mask);
+}
void Solenoid::Set(bool on) {
- if (StatusIsFatal()) return;
-
- int32_t status = 0;
- HAL_SetSolenoid(m_solenoidHandle, on, &status);
- wpi_setHALError(status);
+ int value = on ? (0xFFFF & m_mask) : 0;
+ m_module->SetSolenoids(m_mask, value);
}
bool Solenoid::Get() const {
- if (StatusIsFatal()) return false;
-
- int32_t status = 0;
- bool value = HAL_GetSolenoid(m_solenoidHandle, &status);
- wpi_setHALError(status);
-
- return value;
+ int currentAll = m_module->GetSolenoids();
+ return (currentAll & m_mask) != 0;
}
-void Solenoid::Toggle() { Set(!Get()); }
-
-bool Solenoid::IsBlackListed() const {
- int value = GetPCMSolenoidBlackList(m_moduleNumber) & (1 << m_channel);
- return (value != 0);
+void Solenoid::Toggle() {
+ Set(!Get());
}
-void Solenoid::SetPulseDuration(double durationSeconds) {
- int32_t durationMS = durationSeconds * 1000;
- if (StatusIsFatal()) return;
- int32_t status = 0;
- HAL_SetOneShotDuration(m_solenoidHandle, durationMS, &status);
- wpi_setHALError(status);
+int Solenoid::GetChannel() const {
+ return m_channel;
+}
+
+bool Solenoid::IsDisabled() const {
+ return (m_module->GetSolenoidDisabledList() & m_mask) != 0;
+}
+
+void Solenoid::SetPulseDuration(units::second_t duration) {
+ m_module->SetOneShotDuration(m_channel, duration);
}
void Solenoid::StartPulse() {
- if (StatusIsFatal()) return;
- int32_t status = 0;
- HAL_FireOneShot(m_solenoidHandle, &status);
- wpi_setHALError(status);
+ m_module->FireOneShot(m_channel);
}
-void Solenoid::InitSendable(SendableBuilder& builder) {
+void Solenoid::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Solenoid");
builder.SetActuator(true);
- builder.SetSafeState([=]() { Set(false); });
+ builder.SetSafeState([=] { Set(false); });
builder.AddBooleanProperty(
- "Value", [=]() { return Get(); }, [=](bool value) { Set(value); });
+ "Value", [=] { return Get(); }, [=](bool value) { Set(value); });
}
diff --git a/wpilibc/src/main/native/cpp/SolenoidBase.cpp b/wpilibc/src/main/native/cpp/SolenoidBase.cpp
deleted file mode 100644
index f5f8aad..0000000
--- a/wpilibc/src/main/native/cpp/SolenoidBase.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/SolenoidBase.h"
-
-#include <hal/FRCUsageReporting.h>
-#include <hal/Solenoid.h>
-
-using namespace frc;
-
-int SolenoidBase::GetAll(int module) {
- int value = 0;
- int32_t status = 0;
- value = HAL_GetAllSolenoids(module, &status);
- wpi_setGlobalHALError(status);
- return value;
-}
-
-int SolenoidBase::GetAll() const {
- return SolenoidBase::GetAll(m_moduleNumber);
-}
-
-int SolenoidBase::GetPCMSolenoidBlackList(int module) {
- int32_t status = 0;
- return HAL_GetPCMSolenoidBlackList(module, &status);
-}
-
-int SolenoidBase::GetPCMSolenoidBlackList() const {
- return SolenoidBase::GetPCMSolenoidBlackList(m_moduleNumber);
-}
-
-bool SolenoidBase::GetPCMSolenoidVoltageStickyFault(int module) {
- int32_t status = 0;
- return HAL_GetPCMSolenoidVoltageStickyFault(module, &status);
-}
-
-bool SolenoidBase::GetPCMSolenoidVoltageStickyFault() const {
- return SolenoidBase::GetPCMSolenoidVoltageStickyFault(m_moduleNumber);
-}
-
-bool SolenoidBase::GetPCMSolenoidVoltageFault(int module) {
- int32_t status = 0;
- return HAL_GetPCMSolenoidVoltageFault(module, &status);
-}
-
-bool SolenoidBase::GetPCMSolenoidVoltageFault() const {
- return SolenoidBase::GetPCMSolenoidVoltageFault(m_moduleNumber);
-}
-
-void SolenoidBase::ClearAllPCMStickyFaults(int module) {
- int32_t status = 0;
- return HAL_ClearAllPCMStickyFaults(module, &status);
-}
-
-void SolenoidBase::ClearAllPCMStickyFaults() {
- SolenoidBase::ClearAllPCMStickyFaults(m_moduleNumber);
-}
-
-SolenoidBase::SolenoidBase(int moduleNumber) : m_moduleNumber(moduleNumber) {}
diff --git a/wpilibc/src/main/native/cpp/Spark.cpp b/wpilibc/src/main/native/cpp/Spark.cpp
deleted file mode 100644
index 3717df4..0000000
--- a/wpilibc/src/main/native/cpp/Spark.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/Spark.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-Spark::Spark(int channel) : PWMSpeedController(channel) {
- SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_RevSPARK, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "Spark", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/SpeedController.cpp b/wpilibc/src/main/native/cpp/SpeedController.cpp
index cb3cc5b..e0b0cb2 100644
--- a/wpilibc/src/main/native/cpp/SpeedController.cpp
+++ b/wpilibc/src/main/native/cpp/SpeedController.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/SpeedController.h"
diff --git a/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp b/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp
index 8fea1b2..c3704df 100644
--- a/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp
+++ b/wpilibc/src/main/native/cpp/SpeedControllerGroup.cpp
@@ -1,14 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/SpeedControllerGroup.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
using namespace frc;
@@ -22,11 +19,12 @@
}
void SpeedControllerGroup::Initialize() {
- for (auto& speedController : m_speedControllers)
- SendableRegistry::GetInstance().AddChild(this, &speedController.get());
+ for (auto& speedController : m_speedControllers) {
+ wpi::SendableRegistry::AddChild(this, &speedController.get());
+ }
static int instances = 0;
++instances;
- SendableRegistry::GetInstance().Add(this, "SpeedControllerGroup", instances);
+ wpi::SendableRegistry::Add(this, "SpeedControllerGroup", instances);
}
void SpeedControllerGroup::Set(double speed) {
@@ -46,7 +44,9 @@
m_isInverted = isInverted;
}
-bool SpeedControllerGroup::GetInverted() const { return m_isInverted; }
+bool SpeedControllerGroup::GetInverted() const {
+ return m_isInverted;
+}
void SpeedControllerGroup::Disable() {
for (auto speedController : m_speedControllers) {
@@ -60,12 +60,10 @@
}
}
-void SpeedControllerGroup::PIDWrite(double output) { Set(output); }
-
-void SpeedControllerGroup::InitSendable(SendableBuilder& builder) {
+void SpeedControllerGroup::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Speed Controller");
builder.SetActuator(true);
- builder.SetSafeState([=]() { StopMotor(); });
+ builder.SetSafeState([=] { StopMotor(); });
builder.AddDoubleProperty(
- "Value", [=]() { return Get(); }, [=](double value) { Set(value); });
+ "Value", [=] { return Get(); }, [=](double value) { Set(value); });
}
diff --git a/wpilibc/src/main/native/cpp/SynchronousInterrupt.cpp b/wpilibc/src/main/native/cpp/SynchronousInterrupt.cpp
new file mode 100644
index 0000000..49acd84
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/SynchronousInterrupt.cpp
@@ -0,0 +1,105 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/SynchronousInterrupt.h"
+
+#include <type_traits>
+
+#include <hal/Interrupts.h>
+#include <wpi/NullDeleter.h>
+
+#include "frc/DigitalSource.h"
+#include "frc/Errors.h"
+
+using namespace frc;
+
+SynchronousInterrupt::SynchronousInterrupt(DigitalSource& source)
+ : m_source{&source, wpi::NullDeleter<DigitalSource>()} {
+ InitSynchronousInterrupt();
+}
+SynchronousInterrupt::SynchronousInterrupt(DigitalSource* source)
+ : m_source{source, wpi::NullDeleter<DigitalSource>()} {
+ if (m_source == nullptr) {
+ FRC_CheckErrorStatus(frc::err::NullParameter, "{}", "Source is null");
+ } else {
+ InitSynchronousInterrupt();
+ }
+}
+SynchronousInterrupt::SynchronousInterrupt(
+ std::shared_ptr<DigitalSource> source)
+ : m_source{std::move(source)} {
+ if (m_source == nullptr) {
+ FRC_CheckErrorStatus(frc::err::NullParameter, "{}", "Source is null");
+ } else {
+ InitSynchronousInterrupt();
+ }
+}
+
+void SynchronousInterrupt::InitSynchronousInterrupt() {
+ int32_t status = 0;
+ m_handle = HAL_InitializeInterrupts(&status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt failed to initialize");
+ HAL_RequestInterrupts(m_handle, m_source->GetPortHandleForRouting(),
+ static_cast<HAL_AnalogTriggerType>(
+ m_source->GetAnalogTriggerTypeForRouting()),
+ &status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt request failed");
+ HAL_SetInterruptUpSourceEdge(m_handle, true, false, &status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt setting up source edge failed");
+}
+
+SynchronousInterrupt::~SynchronousInterrupt() {
+ HAL_CleanInterrupts(m_handle);
+}
+
+inline SynchronousInterrupt::WaitResult operator|(
+ SynchronousInterrupt::WaitResult lhs,
+ SynchronousInterrupt::WaitResult rhs) {
+ using T = std::underlying_type_t<SynchronousInterrupt::WaitResult>;
+ return static_cast<SynchronousInterrupt::WaitResult>(static_cast<T>(lhs) |
+ static_cast<T>(rhs));
+}
+
+SynchronousInterrupt::WaitResult SynchronousInterrupt::WaitForInterrupt(
+ units::second_t timeout, bool ignorePrevious) {
+ int32_t status = 0;
+ auto result =
+ HAL_WaitForInterrupt(m_handle, timeout.value(), ignorePrevious, &status);
+
+ auto rising =
+ ((result & 0xFF) != 0) ? WaitResult::kRisingEdge : WaitResult::kTimeout;
+ auto falling = ((result & 0xFF00) != 0) ? WaitResult::kFallingEdge
+ : WaitResult::kTimeout;
+
+ return rising | falling;
+}
+
+void SynchronousInterrupt::SetInterruptEdges(bool risingEdge,
+ bool fallingEdge) {
+ int32_t status = 0;
+ HAL_SetInterruptUpSourceEdge(m_handle, risingEdge, fallingEdge, &status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt setting edges failed");
+}
+
+void SynchronousInterrupt::WakeupWaitingInterrupt() {
+ int32_t status = 0;
+ HAL_ReleaseWaitingInterrupt(m_handle, &status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt wakeup failed");
+}
+
+units::second_t SynchronousInterrupt::GetRisingTimestamp() {
+ int32_t status = 0;
+ auto ts = HAL_ReadInterruptRisingTimestamp(m_handle, &status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt rising timestamp failed");
+ units::microsecond_t ms{static_cast<double>(ts)};
+ return ms;
+}
+
+units::second_t SynchronousInterrupt::GetFallingTimestamp() {
+ int32_t status = 0;
+ auto ts = HAL_ReadInterruptFallingTimestamp(m_handle, &status);
+ FRC_CheckErrorStatus(status, "{}", "Interrupt falling timestamp failed");
+ units::microsecond_t ms{static_cast<double>(ts)};
+ return ms;
+}
diff --git a/wpilibc/src/main/native/cpp/Talon.cpp b/wpilibc/src/main/native/cpp/Talon.cpp
deleted file mode 100644
index 4807d71..0000000
--- a/wpilibc/src/main/native/cpp/Talon.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/Talon.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-Talon::Talon(int channel) : PWMSpeedController(channel) {
- SetBounds(2.037, 1.539, 1.513, 1.487, 0.989);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_Talon, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "Talon", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/Threads.cpp b/wpilibc/src/main/native/cpp/Threads.cpp
index 7b1e647..2b9c151 100644
--- a/wpilibc/src/main/native/cpp/Threads.cpp
+++ b/wpilibc/src/main/native/cpp/Threads.cpp
@@ -1,16 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Threads.h"
#include <hal/FRCUsageReporting.h>
#include <hal/Threads.h>
-#include "frc/ErrorBase.h"
+#include "frc/Errors.h"
namespace frc {
@@ -19,7 +16,7 @@
HAL_Bool rt = false;
auto native = thread.native_handle();
auto ret = HAL_GetThreadPriority(&native, &rt, &status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetThreadPriority");
*isRealTime = rt;
return ret;
}
@@ -28,7 +25,7 @@
int32_t status = 0;
HAL_Bool rt = false;
auto ret = HAL_GetCurrentThreadPriority(&rt, &status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "GetCurrentThreadPriority");
*isRealTime = rt;
return ret;
}
@@ -37,14 +34,14 @@
int32_t status = 0;
auto native = thread.native_handle();
auto ret = HAL_SetThreadPriority(&native, realTime, priority, &status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetThreadPriority");
return ret;
}
bool SetCurrentThreadPriority(bool realTime, int priority) {
int32_t status = 0;
auto ret = HAL_SetCurrentThreadPriority(realTime, priority, &status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "SetCurrentThreadPriority");
return ret;
}
diff --git a/wpilibc/src/main/native/cpp/TimedRobot.cpp b/wpilibc/src/main/native/cpp/TimedRobot.cpp
index 74e658a..93e6698 100644
--- a/wpilibc/src/main/native/cpp/TimedRobot.cpp
+++ b/wpilibc/src/main/native/cpp/TimedRobot.cpp
@@ -1,23 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/TimedRobot.h"
#include <stdint.h>
+#include <cstdio>
#include <utility>
#include <hal/DriverStation.h>
#include <hal/FRCUsageReporting.h>
#include <hal/Notifier.h>
+#include "frc/Errors.h"
#include "frc/Timer.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
using namespace frc;
@@ -29,6 +26,7 @@
}
// Tell the DS that the robot is ready to be enabled
+ std::puts("\n********** Robot program startup complete **********");
HAL_ObserveUserProgramStarting();
// Loop forever, calling the appropriate mode-dependent function
@@ -42,10 +40,12 @@
HAL_UpdateNotifierAlarm(
m_notifier, static_cast<uint64_t>(callback.expirationTime * 1e6),
&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "UpdateNotifierAlarm");
uint64_t curTime = HAL_WaitForNotifierAlarm(m_notifier, &status);
- if (curTime == 0 || status != 0) break;
+ if (curTime == 0 || status != 0) {
+ break;
+ }
callback.func();
@@ -70,19 +70,15 @@
HAL_StopNotifier(m_notifier, &status);
}
-units::second_t TimedRobot::GetPeriod() const {
- return units::second_t(m_period);
-}
-
TimedRobot::TimedRobot(double period) : TimedRobot(units::second_t(period)) {}
TimedRobot::TimedRobot(units::second_t period) : IterativeRobotBase(period) {
- m_startTime = frc2::Timer::GetFPGATimestamp();
+ m_startTime = Timer::GetFPGATimestamp();
AddPeriodic([=] { LoopFunc(); }, period);
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
- wpi_setHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "InitializeNotifier");
HAL_SetNotifierName(m_notifier, "TimedRobot", &status);
HAL_Report(HALUsageReporting::kResourceType_Framework,
@@ -93,7 +89,7 @@
int32_t status = 0;
HAL_StopNotifier(m_notifier, &status);
- wpi_setHALError(status);
+ FRC_ReportError(status, "{}", "StopNotifier");
HAL_CleanNotifier(m_notifier, &status);
}
diff --git a/wpilibc/src/main/native/cpp/Timer.cpp b/wpilibc/src/main/native/cpp/Timer.cpp
index b428e03..bbd2262 100644
--- a/wpilibc/src/main/native/cpp/Timer.cpp
+++ b/wpilibc/src/main/native/cpp/Timer.cpp
@@ -1,42 +1,90 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Timer.h"
-#include <units/time.h>
+#include <chrono>
+#include <thread>
+
+#include "frc/DriverStation.h"
+#include "frc/RobotController.h"
namespace frc {
-void Wait(double seconds) { frc2::Wait(units::second_t(seconds)); }
+void Wait(units::second_t seconds) {
+ std::this_thread::sleep_for(std::chrono::duration<double>(seconds.value()));
+}
-double GetTime() { return frc2::GetTime().to<double>(); }
+units::second_t GetTime() {
+ using std::chrono::duration;
+ using std::chrono::duration_cast;
+ using std::chrono::system_clock;
+
+ return units::second_t(
+ duration_cast<duration<double>>(system_clock::now().time_since_epoch())
+ .count());
+}
} // namespace frc
using namespace frc;
-Timer::Timer() { Reset(); }
-
-double Timer::Get() const { return m_timer.Get().to<double>(); }
-
-void Timer::Reset() { m_timer.Reset(); }
-
-void Timer::Start() { m_timer.Start(); }
-
-void Timer::Stop() { m_timer.Stop(); }
-
-bool Timer::HasPeriodPassed(double period) {
- return m_timer.HasPeriodPassed(units::second_t(period));
+Timer::Timer() {
+ Reset();
}
-double Timer::GetFPGATimestamp() {
- return frc2::Timer::GetFPGATimestamp().to<double>();
+units::second_t Timer::Get() const {
+ if (m_running) {
+ return (GetFPGATimestamp() - m_startTime) + m_accumulatedTime;
+ } else {
+ return m_accumulatedTime;
+ }
}
-double Timer::GetMatchTime() {
- return frc2::Timer::GetMatchTime().to<double>();
+void Timer::Reset() {
+ m_accumulatedTime = 0_s;
+ m_startTime = GetFPGATimestamp();
+}
+
+void Timer::Start() {
+ if (!m_running) {
+ m_startTime = GetFPGATimestamp();
+ m_running = true;
+ }
+}
+
+void Timer::Stop() {
+ if (m_running) {
+ m_accumulatedTime = Get();
+ m_running = false;
+ }
+}
+
+bool Timer::HasElapsed(units::second_t period) const {
+ return Get() >= period;
+}
+
+bool Timer::HasPeriodPassed(units::second_t period) {
+ return AdvanceIfElapsed(period);
+}
+
+bool Timer::AdvanceIfElapsed(units::second_t period) {
+ if (Get() >= period) {
+ // Advance the start time by the period.
+ m_startTime += period;
+ // Don't set it to the current time... we want to avoid drift.
+ return true;
+ } else {
+ return false;
+ }
+}
+
+units::second_t Timer::GetFPGATimestamp() {
+ // FPGA returns the timestamp in microseconds
+ return units::second_t(frc::RobotController::GetFPGATime() * 1.0e-6);
+}
+
+units::second_t Timer::GetMatchTime() {
+ return units::second_t(frc::DriverStation::GetMatchTime());
}
diff --git a/wpilibc/src/main/native/cpp/TimesliceRobot.cpp b/wpilibc/src/main/native/cpp/TimesliceRobot.cpp
new file mode 100644
index 0000000..d212c10
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/TimesliceRobot.cpp
@@ -0,0 +1,28 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/TimesliceRobot.h"
+
+#include "frc/Errors.h"
+#include "frc/fmt/Units.h"
+
+using namespace frc;
+
+TimesliceRobot::TimesliceRobot(units::second_t robotPeriodicAllocation,
+ units::second_t controllerPeriod)
+ : m_nextOffset{robotPeriodicAllocation},
+ m_controllerPeriod{controllerPeriod} {}
+
+void TimesliceRobot::Schedule(std::function<void()> func,
+ units::second_t allocation) {
+ if (m_nextOffset + allocation > m_controllerPeriod) {
+ throw FRC_MakeError(err::Error,
+ "Function scheduled at offset {} with allocation {} "
+ "exceeded controller period of {}\n",
+ m_nextOffset, allocation, m_controllerPeriod);
+ }
+
+ AddPeriodic(func, m_controllerPeriod, m_nextOffset);
+ m_nextOffset += allocation;
+}
diff --git a/wpilibc/src/main/native/cpp/Tracer.cpp b/wpilibc/src/main/native/cpp/Tracer.cpp
index af5177a..1375411 100644
--- a/wpilibc/src/main/native/cpp/Tracer.cpp
+++ b/wpilibc/src/main/native/cpp/Tracer.cpp
@@ -1,30 +1,31 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Tracer.h"
-#include <wpi/Format.h>
+#include <fmt/format.h>
#include <wpi/SmallString.h>
#include <wpi/raw_ostream.h>
-#include "frc/DriverStation.h"
+#include "frc/Errors.h"
using namespace frc;
-Tracer::Tracer() { ResetTimer(); }
+Tracer::Tracer() {
+ ResetTimer();
+}
-void Tracer::ResetTimer() { m_startTime = hal::fpga_clock::now(); }
+void Tracer::ResetTimer() {
+ m_startTime = hal::fpga_clock::now();
+}
void Tracer::ClearEpochs() {
ResetTimer();
m_epochs.clear();
}
-void Tracer::AddEpoch(wpi::StringRef epochName) {
+void Tracer::AddEpoch(std::string_view epochName) {
auto currentTime = hal::fpga_clock::now();
m_epochs[epochName] = currentTime - m_startTime;
m_startTime = currentTime;
@@ -34,7 +35,9 @@
wpi::SmallString<128> buf;
wpi::raw_svector_ostream os(buf);
PrintEpochs(os);
- if (!buf.empty()) DriverStation::ReportWarning(buf);
+ if (!buf.empty()) {
+ FRC_ReportError(warn::Warning, "{}", buf.c_str());
+ }
}
void Tracer::PrintEpochs(wpi::raw_ostream& os) {
@@ -45,11 +48,9 @@
if (now - m_lastEpochsPrintTime > kMinPrintPeriod) {
m_lastEpochsPrintTime = now;
for (const auto& epoch : m_epochs) {
- os << '\t' << epoch.getKey() << ": "
- << wpi::format(
- "%.6f",
- duration_cast<microseconds>(epoch.getValue()).count() / 1.0e6)
- << "s\n";
+ os << fmt::format(
+ "\t{}: {:.6f}s\n", epoch.getKey(),
+ duration_cast<microseconds>(epoch.getValue()).count() / 1.0e6);
}
}
}
diff --git a/wpilibc/src/main/native/cpp/Ultrasonic.cpp b/wpilibc/src/main/native/cpp/Ultrasonic.cpp
index dbd0d13..02035dd 100644
--- a/wpilibc/src/main/native/cpp/Ultrasonic.cpp
+++ b/wpilibc/src/main/native/cpp/Ultrasonic.cpp
@@ -1,23 +1,21 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Ultrasonic.h"
-#include <hal/FRCUsageReporting.h>
+#include <utility>
-#include "frc/Base.h"
+#include <hal/FRCUsageReporting.h>
+#include <wpi/NullDeleter.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
#include "frc/Counter.h"
#include "frc/DigitalInput.h"
#include "frc/DigitalOutput.h"
+#include "frc/Errors.h"
#include "frc/Timer.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -27,47 +25,40 @@
std::vector<Ultrasonic*> Ultrasonic::m_sensors;
std::thread Ultrasonic::m_thread;
-Ultrasonic::Ultrasonic(int pingChannel, int echoChannel, DistanceUnit units)
+Ultrasonic::Ultrasonic(int pingChannel, int echoChannel)
: m_pingChannel(std::make_shared<DigitalOutput>(pingChannel)),
m_echoChannel(std::make_shared<DigitalInput>(echoChannel)),
m_counter(m_echoChannel) {
- m_units = units;
Initialize();
- auto& registry = SendableRegistry::GetInstance();
- registry.AddChild(this, m_pingChannel.get());
- registry.AddChild(this, m_echoChannel.get());
+ wpi::SendableRegistry::AddChild(this, m_pingChannel.get());
+ wpi::SendableRegistry::AddChild(this, m_echoChannel.get());
}
-Ultrasonic::Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel,
- DistanceUnit units)
- : m_pingChannel(pingChannel, NullDeleter<DigitalOutput>()),
- m_echoChannel(echoChannel, NullDeleter<DigitalInput>()),
+Ultrasonic::Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel)
+ : m_pingChannel(pingChannel, wpi::NullDeleter<DigitalOutput>()),
+ m_echoChannel(echoChannel, wpi::NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
- if (pingChannel == nullptr || echoChannel == nullptr) {
- wpi_setWPIError(NullParameter);
- m_units = units;
- return;
+ if (!pingChannel) {
+ throw FRC_MakeError(err::NullParameter, "{}", "pingChannel");
}
- m_units = units;
+ if (!echoChannel) {
+ throw FRC_MakeError(err::NullParameter, "{}", "echoChannel");
+ }
Initialize();
}
-Ultrasonic::Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel,
- DistanceUnit units)
- : m_pingChannel(&pingChannel, NullDeleter<DigitalOutput>()),
- m_echoChannel(&echoChannel, NullDeleter<DigitalInput>()),
+Ultrasonic::Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel)
+ : m_pingChannel(&pingChannel, wpi::NullDeleter<DigitalOutput>()),
+ m_echoChannel(&echoChannel, wpi::NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
- m_units = units;
Initialize();
}
Ultrasonic::Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
- std::shared_ptr<DigitalInput> echoChannel,
- DistanceUnit units)
- : m_pingChannel(pingChannel),
- m_echoChannel(echoChannel),
+ std::shared_ptr<DigitalInput> echoChannel)
+ : m_pingChannel(std::move(pingChannel)),
+ m_echoChannel(std::move(echoChannel)),
m_counter(m_echoChannel) {
- m_units = units;
Initialize();
}
@@ -89,8 +80,15 @@
}
}
+int Ultrasonic::GetEchoChannel() const {
+ return m_echoChannel->GetChannel();
+}
+
void Ultrasonic::Ping() {
- wpi_assert(!m_automaticEnabled);
+ if (m_automaticEnabled) {
+ throw FRC_MakeError(err::IncompatibleMode, "{}",
+ "cannot call Ping() in automatic mode");
+ }
// Reset the counter to zero (invalid data now)
m_counter.Reset();
@@ -100,12 +98,16 @@
}
bool Ultrasonic::IsRangeValid() const {
- if (m_simRangeValid) return m_simRangeValid.Get();
+ if (m_simRangeValid) {
+ return m_simRangeValid.Get();
+ }
return m_counter.Get() > 1;
}
void Ultrasonic::SetAutomaticMode(bool enabling) {
- if (enabling == m_automaticEnabled) return; // ignore the case of no change
+ if (enabling == m_automaticEnabled) {
+ return; // ignore the case of no change
+ }
m_automaticEnabled = enabling;
@@ -138,48 +140,29 @@
}
}
-double Ultrasonic::GetRangeInches() const {
+units::meter_t Ultrasonic::GetRange() const {
if (IsRangeValid()) {
- if (m_simRange) return m_simRange.Get();
- return m_counter.GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0;
+ if (m_simRange) {
+ return units::meter_t{m_simRange.Get()};
+ }
+ return m_counter.GetPeriod() * kSpeedOfSound / 2.0;
} else {
- return 0;
+ return 0_m;
}
}
-double Ultrasonic::GetRangeMM() const { return GetRangeInches() * 25.4; }
-
-bool Ultrasonic::IsEnabled() const { return m_enabled; }
-
-void Ultrasonic::SetEnabled(bool enable) { m_enabled = enable; }
-
-void Ultrasonic::SetDistanceUnits(DistanceUnit units) { m_units = units; }
-
-Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const {
- return m_units;
+bool Ultrasonic::IsEnabled() const {
+ return m_enabled;
}
-double Ultrasonic::PIDGet() {
- switch (m_units) {
- case Ultrasonic::kInches:
- return GetRangeInches();
- case Ultrasonic::kMilliMeters:
- return GetRangeMM();
- default:
- return 0.0;
- }
+void Ultrasonic::SetEnabled(bool enable) {
+ m_enabled = enable;
}
-void Ultrasonic::SetPIDSourceType(PIDSourceType pidSource) {
- if (wpi_assert(pidSource == PIDSourceType::kDisplacement)) {
- m_pidSource = pidSource;
- }
-}
-
-void Ultrasonic::InitSendable(SendableBuilder& builder) {
+void Ultrasonic::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("Ultrasonic");
builder.AddDoubleProperty(
- "Value", [=]() { return GetRangeInches(); }, nullptr);
+ "Value", [=] { return units::inch_t{GetRange()}.value(); }, nullptr);
}
void Ultrasonic::Initialize() {
@@ -196,7 +179,7 @@
// Link this instance on the list
m_sensors.emplace_back(this);
- m_counter.SetMaxPeriod(1.0);
+ m_counter.SetMaxPeriod(1_s);
m_counter.SetSemiPeriodMode(true);
m_counter.Reset();
m_enabled = true; // Make it available for round robin scheduling
@@ -205,20 +188,21 @@
static int instances = 0;
instances++;
HAL_Report(HALUsageReporting::kResourceType_Ultrasonic, instances);
- SendableRegistry::GetInstance().AddLW(this, "Ultrasonic",
- m_echoChannel->GetChannel());
+ wpi::SendableRegistry::AddLW(this, "Ultrasonic", m_echoChannel->GetChannel());
}
void Ultrasonic::UltrasonicChecker() {
while (m_automaticEnabled) {
for (auto& sensor : m_sensors) {
- if (!m_automaticEnabled) break;
+ if (!m_automaticEnabled) {
+ break;
+ }
if (sensor->IsEnabled()) {
sensor->m_pingChannel->Pulse(kPingTime); // do the ping
}
- Wait(0.1); // wait for ping to return
+ Wait(100_ms); // wait for ping to return
}
}
}
diff --git a/wpilibc/src/main/native/cpp/Utility.cpp b/wpilibc/src/main/native/cpp/Utility.cpp
deleted file mode 100644
index 4b69cc8..0000000
--- a/wpilibc/src/main/native/cpp/Utility.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/Utility.h"
-
-#ifndef _WIN32
-#include <cxxabi.h>
-#include <execinfo.h>
-#endif
-
-#include <frc/Base.h>
-#include <hal/DriverStation.h>
-#include <wpi/Path.h>
-#include <wpi/SmallString.h>
-#include <wpi/StackTrace.h>
-#include <wpi/raw_ostream.h>
-
-using namespace frc;
-
-bool wpi_assert_impl(bool conditionValue, const wpi::Twine& conditionText,
- const wpi::Twine& message, wpi::StringRef fileName,
- int lineNumber, wpi::StringRef funcName) {
- if (!conditionValue) {
- wpi::SmallString<128> locBuf;
- wpi::raw_svector_ostream locStream(locBuf);
- locStream << funcName << " [" << wpi::sys::path::filename(fileName) << ":"
- << lineNumber << "]";
-
- wpi::SmallString<128> errorBuf;
- wpi::raw_svector_ostream errorStream(errorBuf);
-
- errorStream << "Assertion \"" << conditionText << "\" ";
-
- if (message.isTriviallyEmpty() ||
- (message.isSingleStringRef() && message.getSingleStringRef().empty())) {
- errorStream << "failed.\n";
- } else {
- errorStream << "failed: " << message << "\n";
- }
-
- std::string stack = wpi::GetStackTrace(2);
-
- // Print the error and send it to the DriverStation
- HAL_SendError(1, 1, 0, errorBuf.c_str(), locBuf.c_str(), stack.c_str(), 1);
- }
-
- return conditionValue;
-}
-
-/**
- * Common error routines for wpi_assertEqual_impl and wpi_assertNotEqual_impl.
- *
- * This should not be called directly; it should only be used by
- * wpi_assertEqual_impl and wpi_assertNotEqual_impl.
- */
-void wpi_assertEqual_common_impl(const wpi::Twine& valueA,
- const wpi::Twine& valueB,
- const wpi::Twine& equalityType,
- const wpi::Twine& message,
- wpi::StringRef fileName, int lineNumber,
- wpi::StringRef funcName) {
- wpi::SmallString<128> locBuf;
- wpi::raw_svector_ostream locStream(locBuf);
- locStream << funcName << " [" << wpi::sys::path::filename(fileName) << ":"
- << lineNumber << "]";
-
- wpi::SmallString<128> errorBuf;
- wpi::raw_svector_ostream errorStream(errorBuf);
-
- errorStream << "Assertion \"" << valueA << " " << equalityType << " "
- << valueB << "\" ";
-
- if (message.isTriviallyEmpty() ||
- (message.isSingleStringRef() && message.getSingleStringRef().empty())) {
- errorStream << "failed.\n";
- } else {
- errorStream << "failed: " << message << "\n";
- }
-
- std::string trace = wpi::GetStackTrace(3);
-
- // Print the error and send it to the DriverStation
- HAL_SendError(1, 1, 0, errorBuf.c_str(), locBuf.c_str(), trace.c_str(), 1);
-}
-
-bool wpi_assertEqual_impl(int valueA, int valueB,
- const wpi::Twine& valueAString,
- const wpi::Twine& valueBString,
- const wpi::Twine& message, wpi::StringRef fileName,
- int lineNumber, wpi::StringRef funcName) {
- if (!(valueA == valueB)) {
- wpi_assertEqual_common_impl(valueAString, valueBString, "==", message,
- fileName, lineNumber, funcName);
- }
- return valueA == valueB;
-}
-
-bool wpi_assertNotEqual_impl(int valueA, int valueB,
- const wpi::Twine& valueAString,
- const wpi::Twine& valueBString,
- const wpi::Twine& message, wpi::StringRef fileName,
- int lineNumber, wpi::StringRef funcName) {
- if (!(valueA != valueB)) {
- wpi_assertEqual_common_impl(valueAString, valueBString, "!=", message,
- fileName, lineNumber, funcName);
- }
- return valueA != valueB;
-}
diff --git a/wpilibc/src/main/native/cpp/Victor.cpp b/wpilibc/src/main/native/cpp/Victor.cpp
deleted file mode 100644
index bce1913..0000000
--- a/wpilibc/src/main/native/cpp/Victor.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/Victor.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-Victor::Victor(int channel) : PWMSpeedController(channel) {
- SetBounds(2.027, 1.525, 1.507, 1.49, 1.026);
- SetPeriodMultiplier(kPeriodMultiplier_2X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_Victor, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "Victor", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/VictorSP.cpp b/wpilibc/src/main/native/cpp/VictorSP.cpp
deleted file mode 100644
index 221777d..0000000
--- a/wpilibc/src/main/native/cpp/VictorSP.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/VictorSP.h"
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-VictorSP::VictorSP(int channel) : PWMSpeedController(channel) {
- SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
- SetPeriodMultiplier(kPeriodMultiplier_1X);
- SetSpeed(0.0);
- SetZeroLatch();
-
- HAL_Report(HALUsageReporting::kResourceType_VictorSP, GetChannel() + 1);
- SendableRegistry::GetInstance().SetName(this, "VictorSP", GetChannel());
-}
diff --git a/wpilibc/src/main/native/cpp/Watchdog.cpp b/wpilibc/src/main/native/cpp/Watchdog.cpp
index 81c7cc8..854f9e9 100644
--- a/wpilibc/src/main/native/cpp/Watchdog.cpp
+++ b/wpilibc/src/main/native/cpp/Watchdog.cpp
@@ -1,22 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Watchdog.h"
#include <atomic>
+#include <thread>
+#include <utility>
+#include <fmt/format.h>
#include <hal/Notifier.h>
-#include <wpi/Format.h>
-#include <wpi/SmallString.h>
+#include <wpi/mutex.h>
#include <wpi/priority_queue.h>
-#include <wpi/raw_ostream.h>
-#include "frc/DriverStation.h"
-#include "frc2/Timer.h"
+#include "frc/Errors.h"
+#include "frc/Timer.h"
using namespace frc;
@@ -49,7 +47,7 @@
Watchdog::Impl::Impl() {
int32_t status = 0;
m_notifier = HAL_InitializeNotifier(&status);
- wpi_setGlobalHALError(status);
+ FRC_CheckErrorStatus(status, "{}", "starting watchdog notifier");
HAL_SetNotifierName(m_notifier, "Watchdog", &status);
m_thread = std::thread([=] { Main(); });
@@ -60,10 +58,12 @@
// atomically set handle to 0, then clean
HAL_NotifierHandle handle = m_notifier.exchange(0);
HAL_StopNotifier(handle, &status);
- wpi_setGlobalHALError(status);
+ FRC_ReportError(status, "{}", "stopping watchdog notifier");
// Join the thread to ensure the handler has exited.
- if (m_thread.joinable()) m_thread.join();
+ if (m_thread.joinable()) {
+ m_thread.join();
+ }
HAL_CleanNotifier(handle, &status);
}
@@ -72,29 +72,38 @@
int32_t status = 0;
// Return if we are being destructed, or were not created successfully
auto notifier = m_notifier.load();
- if (notifier == 0) return;
- if (m_watchdogs.empty())
+ if (notifier == 0) {
+ return;
+ }
+ if (m_watchdogs.empty()) {
HAL_CancelNotifierAlarm(notifier, &status);
- else
+ } else {
HAL_UpdateNotifierAlarm(
notifier,
- static_cast<uint64_t>(m_watchdogs.top()->m_expirationTime.to<double>() *
+ static_cast<uint64_t>(m_watchdogs.top()->m_expirationTime.value() *
1e6),
&status);
- wpi_setGlobalHALError(status);
+ }
+ FRC_CheckErrorStatus(status, "{}", "updating watchdog notifier alarm");
}
void Watchdog::Impl::Main() {
for (;;) {
int32_t status = 0;
HAL_NotifierHandle notifier = m_notifier.load();
- if (notifier == 0) break;
+ if (notifier == 0) {
+ break;
+ }
uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status);
- if (curTime == 0 || status != 0) break;
+ if (curTime == 0 || status != 0) {
+ break;
+ }
std::unique_lock lock(m_mutex);
- if (m_watchdogs.empty()) continue;
+ if (m_watchdogs.empty()) {
+ continue;
+ }
// If the condition variable timed out, that means a Watchdog timeout
// has occurred, so call its timeout function.
@@ -104,11 +113,8 @@
if (now - watchdog->m_lastTimeoutPrintTime > kMinPrintPeriod) {
watchdog->m_lastTimeoutPrintTime = now;
if (!watchdog->m_suppressTimeoutMessage) {
- wpi::SmallString<128> buf;
- wpi::raw_svector_ostream err(buf);
- err << "Watchdog not fed within "
- << wpi::format("%.6f", watchdog->m_timeout.to<double>()) << "s\n";
- frc::DriverStation::ReportWarning(err.str());
+ FRC_ReportError(warn::Warning, "Watchdog not fed within {:.6f}s",
+ watchdog->m_timeout.value());
}
}
@@ -125,15 +131,20 @@
}
}
-Watchdog::Watchdog(double timeout, std::function<void()> callback)
- : Watchdog(units::second_t{timeout}, callback) {}
-
Watchdog::Watchdog(units::second_t timeout, std::function<void()> callback)
- : m_timeout(timeout), m_callback(callback), m_impl(GetImpl()) {}
+ : m_timeout(timeout), m_callback(std::move(callback)), m_impl(GetImpl()) {}
-Watchdog::~Watchdog() { Disable(); }
+Watchdog::~Watchdog() {
+ try {
+ Disable();
+ } catch (const RuntimeError& e) {
+ e.Report();
+ }
+}
-Watchdog::Watchdog(Watchdog&& rhs) { *this = std::move(rhs); }
+Watchdog::Watchdog(Watchdog&& rhs) {
+ *this = std::move(rhs);
+}
Watchdog& Watchdog::operator=(Watchdog&& rhs) {
m_impl = rhs.m_impl;
@@ -153,16 +164,12 @@
return *this;
}
-double Watchdog::GetTime() const {
- return (frc2::Timer::GetFPGATimestamp() - m_startTime).to<double>();
-}
-
-void Watchdog::SetTimeout(double timeout) {
- SetTimeout(units::second_t{timeout});
+units::second_t Watchdog::GetTime() const {
+ return Timer::GetFPGATimestamp() - m_startTime;
}
void Watchdog::SetTimeout(units::second_t timeout) {
- m_startTime = frc2::Timer::GetFPGATimestamp();
+ m_startTime = Timer::GetFPGATimestamp();
m_tracer.ClearEpochs();
std::scoped_lock lock(m_impl->m_mutex);
@@ -175,9 +182,9 @@
m_impl->UpdateAlarm();
}
-double Watchdog::GetTimeout() const {
+units::second_t Watchdog::GetTimeout() const {
std::scoped_lock lock(m_impl->m_mutex);
- return m_timeout.to<double>();
+ return m_timeout;
}
bool Watchdog::IsExpired() const {
@@ -185,16 +192,20 @@
return m_isExpired;
}
-void Watchdog::AddEpoch(wpi::StringRef epochName) {
+void Watchdog::AddEpoch(std::string_view epochName) {
m_tracer.AddEpoch(epochName);
}
-void Watchdog::PrintEpochs() { m_tracer.PrintEpochs(); }
+void Watchdog::PrintEpochs() {
+ m_tracer.PrintEpochs();
+}
-void Watchdog::Reset() { Enable(); }
+void Watchdog::Reset() {
+ Enable();
+}
void Watchdog::Enable() {
- m_startTime = frc2::Timer::GetFPGATimestamp();
+ m_startTime = Timer::GetFPGATimestamp();
m_tracer.ClearEpochs();
std::scoped_lock lock(m_impl->m_mutex);
diff --git a/wpilibc/src/main/native/cpp/XboxController.cpp b/wpilibc/src/main/native/cpp/XboxController.cpp
index de77624..a08225b 100644
--- a/wpilibc/src/main/native/cpp/XboxController.cpp
+++ b/wpilibc/src/main/native/cpp/XboxController.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/XboxController.h"
@@ -15,146 +12,146 @@
HAL_Report(HALUsageReporting::kResourceType_XboxController, port + 1);
}
-double XboxController::GetX(JoystickHand hand) const {
- if (hand == kLeftHand) {
- return GetRawAxis(static_cast<int>(Axis::kLeftX));
- } else {
- return GetRawAxis(static_cast<int>(Axis::kRightX));
- }
+double XboxController::GetLeftX() const {
+ return GetRawAxis(Axis::kLeftX);
}
-double XboxController::GetY(JoystickHand hand) const {
- if (hand == kLeftHand) {
- return GetRawAxis(static_cast<int>(Axis::kLeftY));
- } else {
- return GetRawAxis(static_cast<int>(Axis::kRightY));
- }
+double XboxController::GetRightX() const {
+ return GetRawAxis(Axis::kRightX);
}
-double XboxController::GetTriggerAxis(JoystickHand hand) const {
- if (hand == kLeftHand) {
- return GetRawAxis(static_cast<int>(Axis::kLeftTrigger));
- } else {
- return GetRawAxis(static_cast<int>(Axis::kRightTrigger));
- }
+double XboxController::GetLeftY() const {
+ return GetRawAxis(Axis::kLeftY);
}
-bool XboxController::GetBumper(JoystickHand hand) const {
- if (hand == kLeftHand) {
- return GetRawButton(static_cast<int>(Button::kBumperLeft));
- } else {
- return GetRawButton(static_cast<int>(Button::kBumperRight));
- }
+double XboxController::GetRightY() const {
+ return GetRawAxis(Axis::kRightY);
}
-bool XboxController::GetBumperPressed(JoystickHand hand) {
- if (hand == kLeftHand) {
- return GetRawButtonPressed(static_cast<int>(Button::kBumperLeft));
- } else {
- return GetRawButtonPressed(static_cast<int>(Button::kBumperRight));
- }
+double XboxController::GetLeftTriggerAxis() const {
+ return GetRawAxis(Axis::kLeftTrigger);
}
-bool XboxController::GetBumperReleased(JoystickHand hand) {
- if (hand == kLeftHand) {
- return GetRawButtonReleased(static_cast<int>(Button::kBumperLeft));
- } else {
- return GetRawButtonReleased(static_cast<int>(Button::kBumperRight));
- }
+double XboxController::GetRightTriggerAxis() const {
+ return GetRawAxis(Axis::kRightTrigger);
}
-bool XboxController::GetStickButton(JoystickHand hand) const {
- if (hand == kLeftHand) {
- return GetRawButton(static_cast<int>(Button::kStickLeft));
- } else {
- return GetRawButton(static_cast<int>(Button::kStickRight));
- }
+bool XboxController::GetLeftBumper() const {
+ return GetRawButton(Button::kLeftBumper);
}
-bool XboxController::GetStickButtonPressed(JoystickHand hand) {
- if (hand == kLeftHand) {
- return GetRawButtonPressed(static_cast<int>(Button::kStickLeft));
- } else {
- return GetRawButtonPressed(static_cast<int>(Button::kStickRight));
- }
+bool XboxController::GetRightBumper() const {
+ return GetRawButton(Button::kRightBumper);
}
-bool XboxController::GetStickButtonReleased(JoystickHand hand) {
- if (hand == kLeftHand) {
- return GetRawButtonReleased(static_cast<int>(Button::kStickLeft));
- } else {
- return GetRawButtonReleased(static_cast<int>(Button::kStickRight));
- }
+bool XboxController::GetLeftBumperPressed() {
+ return GetRawButtonPressed(Button::kLeftBumper);
+}
+
+bool XboxController::GetRightBumperPressed() {
+ return GetRawButtonPressed(Button::kRightBumper);
+}
+
+bool XboxController::GetLeftBumperReleased() {
+ return GetRawButtonReleased(Button::kLeftBumper);
+}
+
+bool XboxController::GetRightBumperReleased() {
+ return GetRawButtonReleased(Button::kRightBumper);
+}
+
+bool XboxController::GetLeftStickButton() const {
+ return GetRawButton(Button::kLeftStick);
+}
+
+bool XboxController::GetRightStickButton() const {
+ return GetRawButton(Button::kRightStick);
+}
+
+bool XboxController::GetLeftStickButtonPressed() {
+ return GetRawButtonPressed(Button::kLeftStick);
+}
+
+bool XboxController::GetRightStickButtonPressed() {
+ return GetRawButtonPressed(Button::kRightStick);
+}
+
+bool XboxController::GetLeftStickButtonReleased() {
+ return GetRawButtonReleased(Button::kLeftStick);
+}
+
+bool XboxController::GetRightStickButtonReleased() {
+ return GetRawButtonReleased(Button::kRightStick);
}
bool XboxController::GetAButton() const {
- return GetRawButton(static_cast<int>(Button::kA));
+ return GetRawButton(Button::kA);
}
bool XboxController::GetAButtonPressed() {
- return GetRawButtonPressed(static_cast<int>(Button::kA));
+ return GetRawButtonPressed(Button::kA);
}
bool XboxController::GetAButtonReleased() {
- return GetRawButtonReleased(static_cast<int>(Button::kA));
+ return GetRawButtonReleased(Button::kA);
}
bool XboxController::GetBButton() const {
- return GetRawButton(static_cast<int>(Button::kB));
+ return GetRawButton(Button::kB);
}
bool XboxController::GetBButtonPressed() {
- return GetRawButtonPressed(static_cast<int>(Button::kB));
+ return GetRawButtonPressed(Button::kB);
}
bool XboxController::GetBButtonReleased() {
- return GetRawButtonReleased(static_cast<int>(Button::kB));
+ return GetRawButtonReleased(Button::kB);
}
bool XboxController::GetXButton() const {
- return GetRawButton(static_cast<int>(Button::kX));
+ return GetRawButton(Button::kX);
}
bool XboxController::GetXButtonPressed() {
- return GetRawButtonPressed(static_cast<int>(Button::kX));
+ return GetRawButtonPressed(Button::kX);
}
bool XboxController::GetXButtonReleased() {
- return GetRawButtonReleased(static_cast<int>(Button::kX));
+ return GetRawButtonReleased(Button::kX);
}
bool XboxController::GetYButton() const {
- return GetRawButton(static_cast<int>(Button::kY));
+ return GetRawButton(Button::kY);
}
bool XboxController::GetYButtonPressed() {
- return GetRawButtonPressed(static_cast<int>(Button::kY));
+ return GetRawButtonPressed(Button::kY);
}
bool XboxController::GetYButtonReleased() {
- return GetRawButtonReleased(static_cast<int>(Button::kY));
+ return GetRawButtonReleased(Button::kY);
}
bool XboxController::GetBackButton() const {
- return GetRawButton(static_cast<int>(Button::kBack));
+ return GetRawButton(Button::kBack);
}
bool XboxController::GetBackButtonPressed() {
- return GetRawButtonPressed(static_cast<int>(Button::kBack));
+ return GetRawButtonPressed(Button::kBack);
}
bool XboxController::GetBackButtonReleased() {
- return GetRawButtonReleased(static_cast<int>(Button::kBack));
+ return GetRawButtonReleased(Button::kBack);
}
bool XboxController::GetStartButton() const {
- return GetRawButton(static_cast<int>(Button::kStart));
+ return GetRawButton(Button::kStart);
}
bool XboxController::GetStartButtonPressed() {
- return GetRawButtonPressed(static_cast<int>(Button::kStart));
+ return GetRawButtonPressed(Button::kStart);
}
bool XboxController::GetStartButtonReleased() {
- return GetRawButtonReleased(static_cast<int>(Button::kStart));
+ return GetRawButtonReleased(Button::kStart);
}
diff --git a/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp b/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp
deleted file mode 100644
index 7482e22..0000000
--- a/wpilibc/src/main/native/cpp/controller/HolonomicDriveController.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/controller/HolonomicDriveController.h"
-
-#include <units/angular_velocity.h>
-
-using namespace frc;
-
-HolonomicDriveController::HolonomicDriveController(
- const frc2::PIDController& xController,
- const frc2::PIDController& yController,
- const ProfiledPIDController<units::radian>& thetaController)
- : m_xController(xController),
- m_yController(yController),
- m_thetaController(thetaController) {}
-
-bool HolonomicDriveController::AtReference() const {
- const auto& eTranslate = m_poseError.Translation();
- const auto& eRotate = m_poseError.Rotation();
- const auto& tolTranslate = m_poseTolerance.Translation();
- const auto& tolRotate = m_poseTolerance.Rotation();
- return units::math::abs(eTranslate.X()) < tolTranslate.X() &&
- units::math::abs(eTranslate.Y()) < tolTranslate.Y() &&
- units::math::abs(eRotate.Radians()) < tolRotate.Radians();
-}
-
-void HolonomicDriveController::SetTolerance(const Pose2d& tolerance) {
- m_poseTolerance = tolerance;
-}
-
-ChassisSpeeds HolonomicDriveController::Calculate(
- const Pose2d& currentPose, const Pose2d& poseRef,
- units::meters_per_second_t linearVelocityRef, const Rotation2d& angleRef) {
- // Calculate feedforward velocities (field-relative)
- auto xFF = linearVelocityRef * poseRef.Rotation().Cos();
- auto yFF = linearVelocityRef * poseRef.Rotation().Sin();
- auto thetaFF = units::radians_per_second_t(m_thetaController.Calculate(
- currentPose.Rotation().Radians(), angleRef.Radians()));
-
- m_poseError = poseRef.RelativeTo(currentPose);
-
- if (!m_enabled) {
- return ChassisSpeeds::FromFieldRelativeSpeeds(xFF, yFF, thetaFF,
- currentPose.Rotation());
- }
-
- // Calculate feedback velocities (based on position error).
- auto xFeedback = units::meters_per_second_t(m_xController.Calculate(
- currentPose.X().to<double>(), poseRef.X().to<double>()));
- auto yFeedback = units::meters_per_second_t(m_yController.Calculate(
- currentPose.Y().to<double>(), poseRef.Y().to<double>()));
-
- // Return next output.
- return ChassisSpeeds::FromFieldRelativeSpeeds(
- xFF + xFeedback, yFF + yFeedback, thetaFF, currentPose.Rotation());
-}
-
-ChassisSpeeds HolonomicDriveController::Calculate(
- const Pose2d& currentPose, const Trajectory::State& desiredState,
- const Rotation2d& angleRef) {
- return Calculate(currentPose, desiredState.pose, desiredState.velocity,
- angleRef);
-}
-
-void HolonomicDriveController::SetEnabled(bool enabled) { m_enabled = enabled; }
diff --git a/wpilibc/src/main/native/cpp/controller/PIDController.cpp b/wpilibc/src/main/native/cpp/controller/PIDController.cpp
deleted file mode 100644
index 7b9b623..0000000
--- a/wpilibc/src/main/native/cpp/controller/PIDController.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/controller/PIDController.h"
-
-#include <algorithm>
-#include <cmath>
-
-#include <hal/FRCUsageReporting.h>
-
-#include "frc/controller/ControllerUtil.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc2;
-
-PIDController::PIDController(double Kp, double Ki, double Kd,
- units::second_t period)
- : m_Kp(Kp), m_Ki(Ki), m_Kd(Kd), m_period(period) {
- static int instances = 0;
- instances++;
- HAL_Report(HALUsageReporting::kResourceType_PIDController2, instances);
- frc::SendableRegistry::GetInstance().Add(this, "PIDController", instances);
-}
-
-void PIDController::SetPID(double Kp, double Ki, double Kd) {
- m_Kp = Kp;
- m_Ki = Ki;
- m_Kd = Kd;
-}
-
-void PIDController::SetP(double Kp) { m_Kp = Kp; }
-
-void PIDController::SetI(double Ki) { m_Ki = Ki; }
-
-void PIDController::SetD(double Kd) { m_Kd = Kd; }
-
-double PIDController::GetP() const { return m_Kp; }
-
-double PIDController::GetI() const { return m_Ki; }
-
-double PIDController::GetD() const { return m_Kd; }
-
-units::second_t PIDController::GetPeriod() const {
- return units::second_t(m_period);
-}
-
-void PIDController::SetSetpoint(double setpoint) { m_setpoint = setpoint; }
-
-double PIDController::GetSetpoint() const { return m_setpoint; }
-
-bool PIDController::AtSetpoint() const {
- return std::abs(m_positionError) < m_positionTolerance &&
- std::abs(m_velocityError) < m_velocityTolerance;
-}
-
-void PIDController::EnableContinuousInput(double minimumInput,
- double maximumInput) {
- m_continuous = true;
- m_minimumInput = minimumInput;
- m_maximumInput = maximumInput;
-}
-
-void PIDController::DisableContinuousInput() { m_continuous = false; }
-
-bool PIDController::IsContinuousInputEnabled() const { return m_continuous; }
-
-void PIDController::SetIntegratorRange(double minimumIntegral,
- double maximumIntegral) {
- m_minimumIntegral = minimumIntegral;
- m_maximumIntegral = maximumIntegral;
-}
-
-void PIDController::SetTolerance(double positionTolerance,
- double velocityTolerance) {
- m_positionTolerance = positionTolerance;
- m_velocityTolerance = velocityTolerance;
-}
-
-double PIDController::GetPositionError() const { return m_positionError; }
-
-double PIDController::GetVelocityError() const { return m_velocityError; }
-
-double PIDController::Calculate(double measurement) {
- m_prevError = m_positionError;
-
- if (m_continuous) {
- m_positionError = frc::GetModulusError<double>(
- m_setpoint, measurement, m_minimumInput, m_maximumInput);
- } else {
- m_positionError = m_setpoint - measurement;
- }
-
- m_velocityError = (m_positionError - m_prevError) / m_period.to<double>();
-
- if (m_Ki != 0) {
- m_totalError =
- std::clamp(m_totalError + m_positionError * m_period.to<double>(),
- m_minimumIntegral / m_Ki, m_maximumIntegral / m_Ki);
- }
-
- return m_Kp * m_positionError + m_Ki * m_totalError + m_Kd * m_velocityError;
-}
-
-double PIDController::Calculate(double measurement, double setpoint) {
- // Set setpoint to provided value
- SetSetpoint(setpoint);
- return Calculate(measurement);
-}
-
-void PIDController::Reset() {
- m_prevError = 0;
- m_totalError = 0;
-}
-
-void PIDController::InitSendable(frc::SendableBuilder& builder) {
- builder.SetSmartDashboardType("PIDController");
- builder.AddDoubleProperty(
- "p", [this] { return GetP(); }, [this](double value) { SetP(value); });
- builder.AddDoubleProperty(
- "i", [this] { return GetI(); }, [this](double value) { SetI(value); });
- builder.AddDoubleProperty(
- "d", [this] { return GetD(); }, [this](double value) { SetD(value); });
- builder.AddDoubleProperty(
- "setpoint", [this] { return GetSetpoint(); },
- [this](double value) { SetSetpoint(value); });
-}
diff --git a/wpilibc/src/main/native/cpp/controller/ProfiledPIDController.cpp b/wpilibc/src/main/native/cpp/controller/ProfiledPIDController.cpp
deleted file mode 100644
index a0fffc6..0000000
--- a/wpilibc/src/main/native/cpp/controller/ProfiledPIDController.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/controller/ProfiledPIDController.h"
-
-#include <hal/FRCUsageReporting.h>
-
-void frc::detail::ReportProfiledPIDController() {
- static int instances = 0;
- ++instances;
- HAL_Report(HALUsageReporting::kResourceType_ProfiledPIDController, instances);
-}
diff --git a/wpilibc/src/main/native/cpp/controller/RamseteController.cpp b/wpilibc/src/main/native/cpp/controller/RamseteController.cpp
deleted file mode 100644
index aad6937..0000000
--- a/wpilibc/src/main/native/cpp/controller/RamseteController.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/controller/RamseteController.h"
-
-#include <cmath>
-
-#include <units/math.h>
-
-using namespace frc;
-
-/**
- * Returns sin(x) / x.
- *
- * @param x Value of which to take sinc(x).
- */
-static double Sinc(double x) {
- if (std::abs(x) < 1e-9) {
- return 1.0 - 1.0 / 6.0 * x * x;
- } else {
- return std::sin(x) / x;
- }
-}
-
-RamseteController::RamseteController(double b, double zeta)
- : m_b{b}, m_zeta{zeta} {}
-
-bool RamseteController::AtReference() const {
- const auto& eTranslate = m_poseError.Translation();
- const auto& eRotate = m_poseError.Rotation();
- const auto& tolTranslate = m_poseTolerance.Translation();
- const auto& tolRotate = m_poseTolerance.Rotation();
- return units::math::abs(eTranslate.X()) < tolTranslate.X() &&
- units::math::abs(eTranslate.Y()) < tolTranslate.Y() &&
- units::math::abs(eRotate.Radians()) < tolRotate.Radians();
-}
-
-void RamseteController::SetTolerance(const Pose2d& poseTolerance) {
- m_poseTolerance = poseTolerance;
-}
-
-ChassisSpeeds RamseteController::Calculate(
- const Pose2d& currentPose, const Pose2d& poseRef,
- units::meters_per_second_t linearVelocityRef,
- units::radians_per_second_t angularVelocityRef) {
- if (!m_enabled) {
- return ChassisSpeeds{linearVelocityRef, 0_mps, angularVelocityRef};
- }
-
- m_poseError = poseRef.RelativeTo(currentPose);
-
- // Aliases for equation readability
- double eX = m_poseError.X().to<double>();
- double eY = m_poseError.Y().to<double>();
- double eTheta = m_poseError.Rotation().Radians().to<double>();
- double vRef = linearVelocityRef.to<double>();
- double omegaRef = angularVelocityRef.to<double>();
-
- double k =
- 2.0 * m_zeta * std::sqrt(std::pow(omegaRef, 2) + m_b * std::pow(vRef, 2));
-
- units::meters_per_second_t v{vRef * m_poseError.Rotation().Cos() + k * eX};
- units::radians_per_second_t omega{omegaRef + k * eTheta +
- m_b * vRef * Sinc(eTheta) * eY};
- return ChassisSpeeds{v, 0_mps, omega};
-}
-
-ChassisSpeeds RamseteController::Calculate(
- const Pose2d& currentPose, const Trajectory::State& desiredState) {
- return Calculate(currentPose, desiredState.pose, desiredState.velocity,
- desiredState.velocity * desiredState.curvature);
-}
-
-void RamseteController::SetEnabled(bool enabled) { m_enabled = enabled; }
diff --git a/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp b/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp
index ce9aa05..b54b607 100644
--- a/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp
+++ b/wpilibc/src/main/native/cpp/drive/DifferentialDrive.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/drive/DifferentialDrive.h"
@@ -11,22 +8,30 @@
#include <cmath>
#include <hal/FRCUsageReporting.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/MathUtil.h"
#include "frc/SpeedController.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
+#if defined(_MSC_VER)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
DifferentialDrive::DifferentialDrive(SpeedController& leftMotor,
SpeedController& rightMotor)
: m_leftMotor(&leftMotor), m_rightMotor(&rightMotor) {
- auto& registry = SendableRegistry::GetInstance();
- registry.AddChild(this, m_leftMotor);
- registry.AddChild(this, m_rightMotor);
+ wpi::SendableRegistry::AddChild(this, m_leftMotor);
+ wpi::SendableRegistry::AddChild(this, m_rightMotor);
static int instances = 0;
++instances;
- registry.AddLW(this, "DifferentialDrive", instances);
+ wpi::SendableRegistry::AddLW(this, "DifferentialDrive", instances);
}
void DifferentialDrive::ArcadeDrive(double xSpeed, double zRotation,
@@ -38,54 +43,19 @@
reported = true;
}
- xSpeed = std::clamp(xSpeed, -1.0, 1.0);
xSpeed = ApplyDeadband(xSpeed, m_deadband);
-
- zRotation = std::clamp(zRotation, -1.0, 1.0);
zRotation = ApplyDeadband(zRotation, m_deadband);
- // Square the inputs (while preserving the sign) to increase fine control
- // while permitting full power.
- if (squareInputs) {
- xSpeed = std::copysign(xSpeed * xSpeed, xSpeed);
- zRotation = std::copysign(zRotation * zRotation, zRotation);
- }
+ auto [left, right] = ArcadeDriveIK(xSpeed, zRotation, squareInputs);
- double leftMotorOutput;
- double rightMotorOutput;
-
- double maxInput =
- std::copysign(std::max(std::abs(xSpeed), std::abs(zRotation)), xSpeed);
-
- if (xSpeed >= 0.0) {
- // First quadrant, else second quadrant
- if (zRotation >= 0.0) {
- leftMotorOutput = maxInput;
- rightMotorOutput = xSpeed - zRotation;
- } else {
- leftMotorOutput = xSpeed + zRotation;
- rightMotorOutput = maxInput;
- }
- } else {
- // Third quadrant, else fourth quadrant
- if (zRotation >= 0.0) {
- leftMotorOutput = xSpeed + zRotation;
- rightMotorOutput = maxInput;
- } else {
- leftMotorOutput = maxInput;
- rightMotorOutput = xSpeed - zRotation;
- }
- }
-
- m_leftMotor->Set(std::clamp(leftMotorOutput, -1.0, 1.0) * m_maxOutput);
- double maxOutput = m_maxOutput * m_rightSideInvertMultiplier;
- m_rightMotor->Set(std::clamp(rightMotorOutput, -1.0, 1.0) * maxOutput);
+ m_leftMotor->Set(left);
+ m_rightMotor->Set(right);
Feed();
}
void DifferentialDrive::CurvatureDrive(double xSpeed, double zRotation,
- bool isQuickTurn) {
+ bool allowTurnInPlace) {
static bool reported = false;
if (!reported) {
HAL_Report(HALUsageReporting::kResourceType_RobotDrive,
@@ -93,67 +63,13 @@
reported = true;
}
- xSpeed = std::clamp(xSpeed, -1.0, 1.0);
xSpeed = ApplyDeadband(xSpeed, m_deadband);
-
- zRotation = std::clamp(zRotation, -1.0, 1.0);
zRotation = ApplyDeadband(zRotation, m_deadband);
- double angularPower;
- bool overPower;
+ auto [left, right] = CurvatureDriveIK(xSpeed, zRotation, allowTurnInPlace);
- if (isQuickTurn) {
- if (std::abs(xSpeed) < m_quickStopThreshold) {
- m_quickStopAccumulator =
- (1 - m_quickStopAlpha) * m_quickStopAccumulator +
- m_quickStopAlpha * std::clamp(zRotation, -1.0, 1.0) * 2;
- }
- overPower = true;
- angularPower = zRotation;
- } else {
- overPower = false;
- angularPower = std::abs(xSpeed) * zRotation - m_quickStopAccumulator;
-
- if (m_quickStopAccumulator > 1) {
- m_quickStopAccumulator -= 1;
- } else if (m_quickStopAccumulator < -1) {
- m_quickStopAccumulator += 1;
- } else {
- m_quickStopAccumulator = 0.0;
- }
- }
-
- double leftMotorOutput = xSpeed + angularPower;
- double rightMotorOutput = xSpeed - angularPower;
-
- // If rotation is overpowered, reduce both outputs to within acceptable range
- if (overPower) {
- if (leftMotorOutput > 1.0) {
- rightMotorOutput -= leftMotorOutput - 1.0;
- leftMotorOutput = 1.0;
- } else if (rightMotorOutput > 1.0) {
- leftMotorOutput -= rightMotorOutput - 1.0;
- rightMotorOutput = 1.0;
- } else if (leftMotorOutput < -1.0) {
- rightMotorOutput -= leftMotorOutput + 1.0;
- leftMotorOutput = -1.0;
- } else if (rightMotorOutput < -1.0) {
- leftMotorOutput -= rightMotorOutput + 1.0;
- rightMotorOutput = -1.0;
- }
- }
-
- // Normalize the wheel speeds
- double maxMagnitude =
- std::max(std::abs(leftMotorOutput), std::abs(rightMotorOutput));
- if (maxMagnitude > 1.0) {
- leftMotorOutput /= maxMagnitude;
- rightMotorOutput /= maxMagnitude;
- }
-
- m_leftMotor->Set(leftMotorOutput * m_maxOutput);
- m_rightMotor->Set(rightMotorOutput * m_maxOutput *
- m_rightSideInvertMultiplier);
+ m_leftMotor->Set(left * m_maxOutput);
+ m_rightMotor->Set(right * m_maxOutput);
Feed();
}
@@ -167,12 +83,96 @@
reported = true;
}
- leftSpeed = std::clamp(leftSpeed, -1.0, 1.0);
leftSpeed = ApplyDeadband(leftSpeed, m_deadband);
-
- rightSpeed = std::clamp(rightSpeed, -1.0, 1.0);
rightSpeed = ApplyDeadband(rightSpeed, m_deadband);
+ auto [left, right] = TankDriveIK(leftSpeed, rightSpeed, squareInputs);
+
+ m_leftMotor->Set(left * m_maxOutput);
+ m_rightMotor->Set(right * m_maxOutput);
+
+ Feed();
+}
+
+DifferentialDrive::WheelSpeeds DifferentialDrive::ArcadeDriveIK(
+ double xSpeed, double zRotation, bool squareInputs) {
+ xSpeed = std::clamp(xSpeed, -1.0, 1.0);
+ zRotation = std::clamp(zRotation, -1.0, 1.0);
+
+ // Square the inputs (while preserving the sign) to increase fine control
+ // while permitting full power.
+ if (squareInputs) {
+ xSpeed = std::copysign(xSpeed * xSpeed, xSpeed);
+ zRotation = std::copysign(zRotation * zRotation, zRotation);
+ }
+
+ double leftSpeed;
+ double rightSpeed;
+
+ double maxInput =
+ std::copysign(std::max(std::abs(xSpeed), std::abs(zRotation)), xSpeed);
+
+ if (xSpeed >= 0.0) {
+ // First quadrant, else second quadrant
+ if (zRotation >= 0.0) {
+ leftSpeed = maxInput;
+ rightSpeed = xSpeed - zRotation;
+ } else {
+ leftSpeed = xSpeed + zRotation;
+ rightSpeed = maxInput;
+ }
+ } else {
+ // Third quadrant, else fourth quadrant
+ if (zRotation >= 0.0) {
+ leftSpeed = xSpeed + zRotation;
+ rightSpeed = maxInput;
+ } else {
+ leftSpeed = maxInput;
+ rightSpeed = xSpeed - zRotation;
+ }
+ }
+
+ // Normalize the wheel speeds
+ double maxMagnitude = std::max(std::abs(leftSpeed), std::abs(rightSpeed));
+ if (maxMagnitude > 1.0) {
+ leftSpeed /= maxMagnitude;
+ rightSpeed /= maxMagnitude;
+ }
+
+ return {leftSpeed, rightSpeed};
+}
+
+DifferentialDrive::WheelSpeeds DifferentialDrive::CurvatureDriveIK(
+ double xSpeed, double zRotation, bool allowTurnInPlace) {
+ xSpeed = std::clamp(xSpeed, -1.0, 1.0);
+ zRotation = std::clamp(zRotation, -1.0, 1.0);
+
+ double leftSpeed = 0.0;
+ double rightSpeed = 0.0;
+
+ if (allowTurnInPlace) {
+ leftSpeed = xSpeed + zRotation;
+ rightSpeed = xSpeed - zRotation;
+ } else {
+ leftSpeed = xSpeed + std::abs(xSpeed) * zRotation;
+ rightSpeed = xSpeed - std::abs(xSpeed) * zRotation;
+ }
+
+ // Normalize wheel speeds
+ double maxMagnitude = std::max(std::abs(leftSpeed), std::abs(rightSpeed));
+ if (maxMagnitude > 1.0) {
+ leftSpeed /= maxMagnitude;
+ rightSpeed /= maxMagnitude;
+ }
+
+ return {leftSpeed, rightSpeed};
+}
+
+DifferentialDrive::WheelSpeeds DifferentialDrive::TankDriveIK(
+ double leftSpeed, double rightSpeed, bool squareInputs) {
+ leftSpeed = std::clamp(leftSpeed, -1.0, 1.0);
+ rightSpeed = std::clamp(rightSpeed, -1.0, 1.0);
+
// Square the inputs (while preserving the sign) to increase fine control
// while permitting full power.
if (squareInputs) {
@@ -180,26 +180,7 @@
rightSpeed = std::copysign(rightSpeed * rightSpeed, rightSpeed);
}
- m_leftMotor->Set(leftSpeed * m_maxOutput);
- m_rightMotor->Set(rightSpeed * m_maxOutput * m_rightSideInvertMultiplier);
-
- Feed();
-}
-
-void DifferentialDrive::SetQuickStopThreshold(double threshold) {
- m_quickStopThreshold = threshold;
-}
-
-void DifferentialDrive::SetQuickStopAlpha(double alpha) {
- m_quickStopAlpha = alpha;
-}
-
-bool DifferentialDrive::IsRightSideInverted() const {
- return m_rightSideInvertMultiplier == -1.0;
-}
-
-void DifferentialDrive::SetRightSideInverted(bool rightSideInverted) {
- m_rightSideInvertMultiplier = rightSideInverted ? -1.0 : 1.0;
+ return {leftSpeed, rightSpeed};
}
void DifferentialDrive::StopMotor() {
@@ -208,21 +189,18 @@
Feed();
}
-void DifferentialDrive::GetDescription(wpi::raw_ostream& desc) const {
- desc << "DifferentialDrive";
+std::string DifferentialDrive::GetDescription() const {
+ return "DifferentialDrive";
}
-void DifferentialDrive::InitSendable(SendableBuilder& builder) {
+void DifferentialDrive::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("DifferentialDrive");
builder.SetActuator(true);
builder.SetSafeState([=] { StopMotor(); });
builder.AddDoubleProperty(
- "Left Motor Speed", [=]() { return m_leftMotor->Get(); },
+ "Left Motor Speed", [=] { return m_leftMotor->Get(); },
[=](double value) { m_leftMotor->Set(value); });
builder.AddDoubleProperty(
- "Right Motor Speed",
- [=]() { return m_rightMotor->Get() * m_rightSideInvertMultiplier; },
- [=](double value) {
- m_rightMotor->Set(value * m_rightSideInvertMultiplier);
- });
+ "Right Motor Speed", [=] { return m_rightMotor->Get(); },
+ [=](double value) { m_rightMotor->Set(value); });
}
diff --git a/wpilibc/src/main/native/cpp/drive/KilloughDrive.cpp b/wpilibc/src/main/native/cpp/drive/KilloughDrive.cpp
index 983ce6a..c847678 100644
--- a/wpilibc/src/main/native/cpp/drive/KilloughDrive.cpp
+++ b/wpilibc/src/main/native/cpp/drive/KilloughDrive.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/drive/KilloughDrive.h"
@@ -11,14 +8,23 @@
#include <cmath>
#include <hal/FRCUsageReporting.h>
-#include <wpi/math>
+#include <wpi/numbers>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/MathUtil.h"
#include "frc/SpeedController.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
+#if defined(_MSC_VER)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
KilloughDrive::KilloughDrive(SpeedController& leftMotor,
SpeedController& rightMotor,
SpeedController& backMotor)
@@ -32,19 +38,18 @@
: m_leftMotor(&leftMotor),
m_rightMotor(&rightMotor),
m_backMotor(&backMotor) {
- m_leftVec = {std::cos(leftMotorAngle * (wpi::math::pi / 180.0)),
- std::sin(leftMotorAngle * (wpi::math::pi / 180.0))};
- m_rightVec = {std::cos(rightMotorAngle * (wpi::math::pi / 180.0)),
- std::sin(rightMotorAngle * (wpi::math::pi / 180.0))};
- m_backVec = {std::cos(backMotorAngle * (wpi::math::pi / 180.0)),
- std::sin(backMotorAngle * (wpi::math::pi / 180.0))};
- auto& registry = SendableRegistry::GetInstance();
- registry.AddChild(this, m_leftMotor);
- registry.AddChild(this, m_rightMotor);
- registry.AddChild(this, m_backMotor);
+ m_leftVec = {std::cos(leftMotorAngle * (wpi::numbers::pi / 180.0)),
+ std::sin(leftMotorAngle * (wpi::numbers::pi / 180.0))};
+ m_rightVec = {std::cos(rightMotorAngle * (wpi::numbers::pi / 180.0)),
+ std::sin(rightMotorAngle * (wpi::numbers::pi / 180.0))};
+ m_backVec = {std::cos(backMotorAngle * (wpi::numbers::pi / 180.0)),
+ std::sin(backMotorAngle * (wpi::numbers::pi / 180.0))};
+ wpi::SendableRegistry::AddChild(this, m_leftMotor);
+ wpi::SendableRegistry::AddChild(this, m_rightMotor);
+ wpi::SendableRegistry::AddChild(this, m_backMotor);
static int instances = 0;
++instances;
- registry.AddLW(this, "KilloughDrive", instances);
+ wpi::SendableRegistry::AddLW(this, "KilloughDrive", instances);
}
void KilloughDrive::DriveCartesian(double ySpeed, double xSpeed,
@@ -55,26 +60,15 @@
reported = true;
}
- ySpeed = std::clamp(ySpeed, -1.0, 1.0);
ySpeed = ApplyDeadband(ySpeed, m_deadband);
-
- xSpeed = std::clamp(xSpeed, -1.0, 1.0);
xSpeed = ApplyDeadband(xSpeed, m_deadband);
- // Compensate for gyro angle.
- Vector2d input{ySpeed, xSpeed};
- input.Rotate(-gyroAngle);
+ auto [left, right, back] =
+ DriveCartesianIK(ySpeed, xSpeed, zRotation, gyroAngle);
- double wheelSpeeds[3];
- wheelSpeeds[kLeft] = input.ScalarProject(m_leftVec) + zRotation;
- wheelSpeeds[kRight] = input.ScalarProject(m_rightVec) + zRotation;
- wheelSpeeds[kBack] = input.ScalarProject(m_backVec) + zRotation;
-
- Normalize(wheelSpeeds);
-
- m_leftMotor->Set(wheelSpeeds[kLeft] * m_maxOutput);
- m_rightMotor->Set(wheelSpeeds[kRight] * m_maxOutput);
- m_backMotor->Set(wheelSpeeds[kBack] * m_maxOutput);
+ m_leftMotor->Set(left * m_maxOutput);
+ m_rightMotor->Set(right * m_maxOutput);
+ m_backMotor->Set(back * m_maxOutput);
Feed();
}
@@ -87,11 +81,32 @@
reported = true;
}
- DriveCartesian(magnitude * std::sin(angle * (wpi::math::pi / 180.0)),
- magnitude * std::cos(angle * (wpi::math::pi / 180.0)),
+ DriveCartesian(magnitude * std::sin(angle * (wpi::numbers::pi / 180.0)),
+ magnitude * std::cos(angle * (wpi::numbers::pi / 180.0)),
zRotation, 0.0);
}
+KilloughDrive::WheelSpeeds KilloughDrive::DriveCartesianIK(double ySpeed,
+ double xSpeed,
+ double zRotation,
+ double gyroAngle) {
+ ySpeed = std::clamp(ySpeed, -1.0, 1.0);
+ xSpeed = std::clamp(xSpeed, -1.0, 1.0);
+
+ // Compensate for gyro angle.
+ Vector2d input{ySpeed, xSpeed};
+ input.Rotate(-gyroAngle);
+
+ double wheelSpeeds[3];
+ wheelSpeeds[kLeft] = input.ScalarProject(m_leftVec) + zRotation;
+ wheelSpeeds[kRight] = input.ScalarProject(m_rightVec) + zRotation;
+ wheelSpeeds[kBack] = input.ScalarProject(m_backVec) + zRotation;
+
+ Normalize(wheelSpeeds);
+
+ return {wheelSpeeds[kLeft], wheelSpeeds[kRight], wheelSpeeds[kBack]};
+}
+
void KilloughDrive::StopMotor() {
m_leftMotor->StopMotor();
m_rightMotor->StopMotor();
@@ -99,21 +114,21 @@
Feed();
}
-void KilloughDrive::GetDescription(wpi::raw_ostream& desc) const {
- desc << "KilloughDrive";
+std::string KilloughDrive::GetDescription() const {
+ return "KilloughDrive";
}
-void KilloughDrive::InitSendable(SendableBuilder& builder) {
+void KilloughDrive::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("KilloughDrive");
builder.SetActuator(true);
builder.SetSafeState([=] { StopMotor(); });
builder.AddDoubleProperty(
- "Left Motor Speed", [=]() { return m_leftMotor->Get(); },
+ "Left Motor Speed", [=] { return m_leftMotor->Get(); },
[=](double value) { m_leftMotor->Set(value); });
builder.AddDoubleProperty(
- "Right Motor Speed", [=]() { return m_rightMotor->Get(); },
+ "Right Motor Speed", [=] { return m_rightMotor->Get(); },
[=](double value) { m_rightMotor->Set(value); });
builder.AddDoubleProperty(
- "Back Motor Speed", [=]() { return m_backMotor->Get(); },
+ "Back Motor Speed", [=] { return m_backMotor->Get(); },
[=](double value) { m_backMotor->Set(value); });
}
diff --git a/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp b/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp
index cb11d8a..b74c611 100644
--- a/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp
+++ b/wpilibc/src/main/native/cpp/drive/MecanumDrive.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/drive/MecanumDrive.h"
@@ -11,15 +8,24 @@
#include <cmath>
#include <hal/FRCUsageReporting.h>
-#include <wpi/math>
+#include <wpi/numbers>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/MathUtil.h"
#include "frc/SpeedController.h"
#include "frc/drive/Vector2d.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
+#if defined(_MSC_VER)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
MecanumDrive::MecanumDrive(SpeedController& frontLeftMotor,
SpeedController& rearLeftMotor,
SpeedController& frontRightMotor,
@@ -28,14 +34,13 @@
m_rearLeftMotor(&rearLeftMotor),
m_frontRightMotor(&frontRightMotor),
m_rearRightMotor(&rearRightMotor) {
- auto& registry = SendableRegistry::GetInstance();
- registry.AddChild(this, m_frontLeftMotor);
- registry.AddChild(this, m_rearLeftMotor);
- registry.AddChild(this, m_frontRightMotor);
- registry.AddChild(this, m_rearRightMotor);
+ wpi::SendableRegistry::AddChild(this, m_frontLeftMotor);
+ wpi::SendableRegistry::AddChild(this, m_rearLeftMotor);
+ wpi::SendableRegistry::AddChild(this, m_frontRightMotor);
+ wpi::SendableRegistry::AddChild(this, m_rearRightMotor);
static int instances = 0;
++instances;
- registry.AddLW(this, "MecanumDrive", instances);
+ wpi::SendableRegistry::AddLW(this, "MecanumDrive", instances);
}
void MecanumDrive::DriveCartesian(double ySpeed, double xSpeed,
@@ -46,30 +51,16 @@
reported = true;
}
- ySpeed = std::clamp(ySpeed, -1.0, 1.0);
ySpeed = ApplyDeadband(ySpeed, m_deadband);
-
- xSpeed = std::clamp(xSpeed, -1.0, 1.0);
xSpeed = ApplyDeadband(xSpeed, m_deadband);
- // Compensate for gyro angle.
- Vector2d input{ySpeed, xSpeed};
- input.Rotate(-gyroAngle);
+ auto [frontLeft, frontRight, rearLeft, rearRight] =
+ DriveCartesianIK(ySpeed, xSpeed, zRotation, gyroAngle);
- double wheelSpeeds[4];
- wheelSpeeds[kFrontLeft] = input.x + input.y + zRotation;
- wheelSpeeds[kFrontRight] = -input.x + input.y - zRotation;
- wheelSpeeds[kRearLeft] = -input.x + input.y + zRotation;
- wheelSpeeds[kRearRight] = input.x + input.y - zRotation;
-
- Normalize(wheelSpeeds);
-
- m_frontLeftMotor->Set(wheelSpeeds[kFrontLeft] * m_maxOutput);
- m_frontRightMotor->Set(wheelSpeeds[kFrontRight] * m_maxOutput *
- m_rightSideInvertMultiplier);
- m_rearLeftMotor->Set(wheelSpeeds[kRearLeft] * m_maxOutput);
- m_rearRightMotor->Set(wheelSpeeds[kRearRight] * m_maxOutput *
- m_rightSideInvertMultiplier);
+ m_frontLeftMotor->Set(frontLeft * m_maxOutput);
+ m_frontRightMotor->Set(frontRight * m_maxOutput);
+ m_rearLeftMotor->Set(rearLeft * m_maxOutput);
+ m_rearRightMotor->Set(rearRight * m_maxOutput);
Feed();
}
@@ -82,19 +73,11 @@
reported = true;
}
- DriveCartesian(magnitude * std::sin(angle * (wpi::math::pi / 180.0)),
- magnitude * std::cos(angle * (wpi::math::pi / 180.0)),
+ DriveCartesian(magnitude * std::cos(angle * (wpi::numbers::pi / 180.0)),
+ magnitude * std::sin(angle * (wpi::numbers::pi / 180.0)),
zRotation, 0.0);
}
-bool MecanumDrive::IsRightSideInverted() const {
- return m_rightSideInvertMultiplier == -1.0;
-}
-
-void MecanumDrive::SetRightSideInverted(bool rightSideInverted) {
- m_rightSideInvertMultiplier = rightSideInverted ? -1.0 : 1.0;
-}
-
void MecanumDrive::StopMotor() {
m_frontLeftMotor->StopMotor();
m_frontRightMotor->StopMotor();
@@ -103,30 +86,47 @@
Feed();
}
-void MecanumDrive::GetDescription(wpi::raw_ostream& desc) const {
- desc << "MecanumDrive";
+MecanumDrive::WheelSpeeds MecanumDrive::DriveCartesianIK(double ySpeed,
+ double xSpeed,
+ double zRotation,
+ double gyroAngle) {
+ ySpeed = std::clamp(ySpeed, -1.0, 1.0);
+ xSpeed = std::clamp(xSpeed, -1.0, 1.0);
+
+ // Compensate for gyro angle.
+ Vector2d input{ySpeed, xSpeed};
+ input.Rotate(-gyroAngle);
+
+ double wheelSpeeds[4];
+ wheelSpeeds[kFrontLeft] = input.x + input.y + zRotation;
+ wheelSpeeds[kFrontRight] = input.x - input.y - zRotation;
+ wheelSpeeds[kRearLeft] = input.x - input.y + zRotation;
+ wheelSpeeds[kRearRight] = input.x + input.y - zRotation;
+
+ Normalize(wheelSpeeds);
+
+ return {wheelSpeeds[kFrontLeft], wheelSpeeds[kFrontRight],
+ wheelSpeeds[kRearLeft], wheelSpeeds[kRearRight]};
}
-void MecanumDrive::InitSendable(SendableBuilder& builder) {
+std::string MecanumDrive::GetDescription() const {
+ return "MecanumDrive";
+}
+
+void MecanumDrive::InitSendable(wpi::SendableBuilder& builder) {
builder.SetSmartDashboardType("MecanumDrive");
builder.SetActuator(true);
builder.SetSafeState([=] { StopMotor(); });
builder.AddDoubleProperty(
- "Front Left Motor Speed", [=]() { return m_frontLeftMotor->Get(); },
+ "Front Left Motor Speed", [=] { return m_frontLeftMotor->Get(); },
[=](double value) { m_frontLeftMotor->Set(value); });
builder.AddDoubleProperty(
- "Front Right Motor Speed",
- [=]() { return m_frontRightMotor->Get() * m_rightSideInvertMultiplier; },
- [=](double value) {
- m_frontRightMotor->Set(value * m_rightSideInvertMultiplier);
- });
+ "Front Right Motor Speed", [=] { return m_frontRightMotor->Get(); },
+ [=](double value) { m_frontRightMotor->Set(value); });
builder.AddDoubleProperty(
- "Rear Left Motor Speed", [=]() { return m_rearLeftMotor->Get(); },
+ "Rear Left Motor Speed", [=] { return m_rearLeftMotor->Get(); },
[=](double value) { m_rearLeftMotor->Set(value); });
builder.AddDoubleProperty(
- "Rear Right Motor Speed",
- [=]() { return m_rearRightMotor->Get() * m_rightSideInvertMultiplier; },
- [=](double value) {
- m_rearRightMotor->Set(value * m_rightSideInvertMultiplier);
- });
+ "Rear Right Motor Speed", [=] { return m_rearRightMotor->Get(); },
+ [=](double value) { m_rearRightMotor->Set(value); });
}
diff --git a/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp b/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp
index fbce5a1..2159958 100644
--- a/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp
+++ b/wpilibc/src/main/native/cpp/drive/RobotDriveBase.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/drive/RobotDriveBase.h"
@@ -13,32 +10,32 @@
#include <hal/FRCUsageReporting.h>
-#include "frc/Base.h"
-#include "frc/SpeedController.h"
+#include "frc/MathUtil.h"
+#include "frc/motorcontrol/MotorController.h"
using namespace frc;
-RobotDriveBase::RobotDriveBase() { SetSafetyEnabled(true); }
-
-void RobotDriveBase::SetDeadband(double deadband) { m_deadband = deadband; }
-
-void RobotDriveBase::SetMaxOutput(double maxOutput) { m_maxOutput = maxOutput; }
-
-void RobotDriveBase::FeedWatchdog() { Feed(); }
-
-double RobotDriveBase::ApplyDeadband(double value, double deadband) {
- if (std::abs(value) > deadband) {
- if (value > 0.0) {
- return (value - deadband) / (1.0 - deadband);
- } else {
- return (value + deadband) / (1.0 - deadband);
- }
- } else {
- return 0.0;
- }
+RobotDriveBase::RobotDriveBase() {
+ SetSafetyEnabled(true);
}
-void RobotDriveBase::Normalize(wpi::MutableArrayRef<double> wheelSpeeds) {
+void RobotDriveBase::SetDeadband(double deadband) {
+ m_deadband = deadband;
+}
+
+void RobotDriveBase::SetMaxOutput(double maxOutput) {
+ m_maxOutput = maxOutput;
+}
+
+void RobotDriveBase::FeedWatchdog() {
+ Feed();
+}
+
+double RobotDriveBase::ApplyDeadband(double value, double deadband) {
+ return frc::ApplyDeadband(value, deadband);
+}
+
+void RobotDriveBase::Normalize(wpi::span<double> wheelSpeeds) {
double maxMagnitude = std::abs(wheelSpeeds[0]);
for (size_t i = 1; i < wheelSpeeds.size(); i++) {
double temp = std::abs(wheelSpeeds[i]);
diff --git a/wpilibc/src/main/native/cpp/drive/Vector2d.cpp b/wpilibc/src/main/native/cpp/drive/Vector2d.cpp
index a6e68a6..a342dc2 100644
--- a/wpilibc/src/main/native/cpp/drive/Vector2d.cpp
+++ b/wpilibc/src/main/native/cpp/drive/Vector2d.cpp
@@ -1,15 +1,12 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/drive/Vector2d.h"
#include <cmath>
-#include <wpi/math>
+#include <wpi/numbers>
using namespace frc;
@@ -19,8 +16,8 @@
}
void Vector2d::Rotate(double angle) {
- double cosA = std::cos(angle * (wpi::math::pi / 180.0));
- double sinA = std::sin(angle * (wpi::math::pi / 180.0));
+ double cosA = std::cos(angle * (wpi::numbers::pi / 180.0));
+ double sinA = std::sin(angle * (wpi::numbers::pi / 180.0));
double out[2];
out[0] = x * cosA - y * sinA;
out[1] = x * sinA + y * cosA;
@@ -32,7 +29,9 @@
return x * vec.x + y * vec.y;
}
-double Vector2d::Magnitude() const { return std::sqrt(x * x + y * y); }
+double Vector2d::Magnitude() const {
+ return std::sqrt(x * x + y * y);
+}
double Vector2d::ScalarProject(const Vector2d& vec) const {
return Dot(vec) / vec.Magnitude();
diff --git a/wpilibc/src/main/native/cpp/filters/Filter.cpp b/wpilibc/src/main/native/cpp/filters/Filter.cpp
deleted file mode 100644
index c25d7af..0000000
--- a/wpilibc/src/main/native/cpp/filters/Filter.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/filters/Filter.h"
-
-#include "frc/Base.h"
-
-using namespace frc;
-
-Filter::Filter(PIDSource& source)
- : m_source(std::shared_ptr<PIDSource>(&source, NullDeleter<PIDSource>())) {}
-
-Filter::Filter(std::shared_ptr<PIDSource> source)
- : m_source(std::move(source)) {}
-
-void Filter::SetPIDSourceType(PIDSourceType pidSource) {
- m_source->SetPIDSourceType(pidSource);
-}
-
-PIDSourceType Filter::GetPIDSourceType() const {
- return m_source->GetPIDSourceType();
-}
-
-double Filter::PIDGetSource() { return m_source->PIDGet(); }
diff --git a/wpilibc/src/main/native/cpp/filters/LinearDigitalFilter.cpp b/wpilibc/src/main/native/cpp/filters/LinearDigitalFilter.cpp
deleted file mode 100644
index 434cc27..0000000
--- a/wpilibc/src/main/native/cpp/filters/LinearDigitalFilter.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/filters/LinearDigitalFilter.h"
-
-#include <cassert>
-#include <cmath>
-
-#include <hal/FRCUsageReporting.h>
-
-using namespace frc;
-
-LinearDigitalFilter::LinearDigitalFilter(PIDSource& source,
- wpi::ArrayRef<double> ffGains,
- wpi::ArrayRef<double> fbGains)
- : Filter(source),
- m_inputs(ffGains.size()),
- m_outputs(fbGains.size()),
- m_inputGains(ffGains),
- m_outputGains(fbGains) {
- static int instances = 0;
- instances++;
- HAL_Report(HALUsageReporting::kResourceType_LinearFilter, instances);
-}
-
-LinearDigitalFilter::LinearDigitalFilter(PIDSource& source,
- std::initializer_list<double> ffGains,
- std::initializer_list<double> fbGains)
- : LinearDigitalFilter(source,
- wpi::makeArrayRef(ffGains.begin(), ffGains.end()),
- wpi::makeArrayRef(fbGains.begin(), fbGains.end())) {}
-
-LinearDigitalFilter::LinearDigitalFilter(std::shared_ptr<PIDSource> source,
- wpi::ArrayRef<double> ffGains,
- wpi::ArrayRef<double> fbGains)
- : Filter(source),
- m_inputs(ffGains.size()),
- m_outputs(fbGains.size()),
- m_inputGains(ffGains),
- m_outputGains(fbGains) {
- static int instances = 0;
- instances++;
- HAL_Report(HALUsageReporting::kResourceType_LinearFilter, instances);
-}
-
-LinearDigitalFilter::LinearDigitalFilter(std::shared_ptr<PIDSource> source,
- std::initializer_list<double> ffGains,
- std::initializer_list<double> fbGains)
- : LinearDigitalFilter(source,
- wpi::makeArrayRef(ffGains.begin(), ffGains.end()),
- wpi::makeArrayRef(fbGains.begin(), fbGains.end())) {}
-
-LinearDigitalFilter LinearDigitalFilter::SinglePoleIIR(PIDSource& source,
- double timeConstant,
- double period) {
- double gain = std::exp(-period / timeConstant);
- return LinearDigitalFilter(source, {1.0 - gain}, {-gain});
-}
-
-LinearDigitalFilter LinearDigitalFilter::HighPass(PIDSource& source,
- double timeConstant,
- double period) {
- double gain = std::exp(-period / timeConstant);
- return LinearDigitalFilter(source, {gain, -gain}, {-gain});
-}
-
-LinearDigitalFilter LinearDigitalFilter::MovingAverage(PIDSource& source,
- int taps) {
- assert(taps > 0);
-
- std::vector<double> gains(taps, 1.0 / taps);
- return LinearDigitalFilter(source, gains, {});
-}
-
-LinearDigitalFilter LinearDigitalFilter::SinglePoleIIR(
- std::shared_ptr<PIDSource> source, double timeConstant, double period) {
- double gain = std::exp(-period / timeConstant);
- return LinearDigitalFilter(std::move(source), {1.0 - gain}, {-gain});
-}
-
-LinearDigitalFilter LinearDigitalFilter::HighPass(
- std::shared_ptr<PIDSource> source, double timeConstant, double period) {
- double gain = std::exp(-period / timeConstant);
- return LinearDigitalFilter(std::move(source), {gain, -gain}, {-gain});
-}
-
-LinearDigitalFilter LinearDigitalFilter::MovingAverage(
- std::shared_ptr<PIDSource> source, int taps) {
- assert(taps > 0);
-
- std::vector<double> gains(taps, 1.0 / taps);
- return LinearDigitalFilter(std::move(source), gains, {});
-}
-
-double LinearDigitalFilter::Get() const {
- double retVal = 0.0;
-
- // Calculate the new value
- for (size_t i = 0; i < m_inputGains.size(); i++) {
- retVal += m_inputs[i] * m_inputGains[i];
- }
- for (size_t i = 0; i < m_outputGains.size(); i++) {
- retVal -= m_outputs[i] * m_outputGains[i];
- }
-
- return retVal;
-}
-
-void LinearDigitalFilter::Reset() {
- m_inputs.reset();
- m_outputs.reset();
-}
-
-double LinearDigitalFilter::PIDGet() {
- double retVal = 0.0;
-
- // Rotate the inputs
- m_inputs.push_front(PIDGetSource());
-
- // Calculate the new value
- for (size_t i = 0; i < m_inputGains.size(); i++) {
- retVal += m_inputs[i] * m_inputGains[i];
- }
- for (size_t i = 0; i < m_outputGains.size(); i++) {
- retVal -= m_outputs[i] * m_outputGains[i];
- }
-
- // Rotate the outputs
- m_outputs.push_front(retVal);
-
- return retVal;
-}
diff --git a/wpilibc/src/main/native/cpp/frc2/Timer.cpp b/wpilibc/src/main/native/cpp/frc2/Timer.cpp
deleted file mode 100644
index 36da4c6..0000000
--- a/wpilibc/src/main/native/cpp/frc2/Timer.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc2/Timer.h"
-
-#include <chrono>
-#include <thread>
-
-#include "frc/DriverStation.h"
-#include "frc/RobotController.h"
-
-namespace frc2 {
-
-void Wait(units::second_t seconds) {
- std::this_thread::sleep_for(
- std::chrono::duration<double>(seconds.to<double>()));
-}
-
-units::second_t GetTime() {
- using std::chrono::duration;
- using std::chrono::duration_cast;
- using std::chrono::system_clock;
-
- return units::second_t(
- duration_cast<duration<double>>(system_clock::now().time_since_epoch())
- .count());
-}
-
-} // namespace frc2
-
-using namespace frc2;
-
-Timer::Timer() { Reset(); }
-
-Timer::Timer(const Timer& rhs)
- : m_startTime(rhs.m_startTime),
- m_accumulatedTime(rhs.m_accumulatedTime),
- m_running(rhs.m_running) {}
-
-Timer& Timer::operator=(const Timer& rhs) {
- std::scoped_lock lock(m_mutex, rhs.m_mutex);
-
- m_startTime = rhs.m_startTime;
- m_accumulatedTime = rhs.m_accumulatedTime;
- m_running = rhs.m_running;
-
- return *this;
-}
-
-Timer::Timer(Timer&& rhs)
- : m_startTime(std::move(rhs.m_startTime)),
- m_accumulatedTime(std::move(rhs.m_accumulatedTime)),
- m_running(std::move(rhs.m_running)) {}
-
-Timer& Timer::operator=(Timer&& rhs) {
- std::scoped_lock lock(m_mutex, rhs.m_mutex);
-
- m_startTime = std::move(rhs.m_startTime);
- m_accumulatedTime = std::move(rhs.m_accumulatedTime);
- m_running = std::move(rhs.m_running);
-
- return *this;
-}
-
-units::second_t Timer::Get() const {
- units::second_t result;
- units::second_t currentTime = GetFPGATimestamp();
-
- std::scoped_lock lock(m_mutex);
- if (m_running) {
- result = (currentTime - m_startTime) + m_accumulatedTime;
- } else {
- result = m_accumulatedTime;
- }
-
- return result;
-}
-
-void Timer::Reset() {
- std::scoped_lock lock(m_mutex);
- m_accumulatedTime = 0_s;
- m_startTime = GetFPGATimestamp();
-}
-
-void Timer::Start() {
- std::scoped_lock lock(m_mutex);
- if (!m_running) {
- m_startTime = GetFPGATimestamp();
- m_running = true;
- }
-}
-
-void Timer::Stop() {
- units::second_t temp = Get();
-
- std::scoped_lock lock(m_mutex);
- if (m_running) {
- m_accumulatedTime = temp;
- m_running = false;
- }
-}
-
-bool Timer::HasElapsed(units::second_t period) const { return Get() > period; }
-
-bool Timer::HasPeriodPassed(units::second_t period) {
- return AdvanceIfElapsed(period);
-}
-
-bool Timer::AdvanceIfElapsed(units::second_t period) {
- if (Get() > period) {
- std::scoped_lock lock(m_mutex);
- // Advance the start time by the period.
- m_startTime += period;
- // Don't set it to the current time... we want to avoid drift.
- return true;
- } else {
- return false;
- }
-}
-
-units::second_t Timer::GetFPGATimestamp() {
- // FPGA returns the timestamp in microseconds
- return units::second_t(frc::RobotController::GetFPGATime() * 1.0e-6);
-}
-
-units::second_t Timer::GetMatchTime() {
- return units::second_t(frc::DriverStation::GetInstance().GetMatchTime());
-}
diff --git a/wpilibc/src/main/native/cpp/interfaces/Potentiometer.cpp b/wpilibc/src/main/native/cpp/interfaces/Potentiometer.cpp
deleted file mode 100644
index 44f4aab..0000000
--- a/wpilibc/src/main/native/cpp/interfaces/Potentiometer.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/interfaces/Potentiometer.h"
-
-#include "frc/Utility.h"
-
-using namespace frc;
-
-void Potentiometer::SetPIDSourceType(PIDSourceType pidSource) {
- if (wpi_assert(pidSource == PIDSourceType::kDisplacement)) {
- m_pidSource = pidSource;
- }
-}
diff --git a/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp b/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp
index 517ecf7..f8be7de 100644
--- a/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp
+++ b/wpilibc/src/main/native/cpp/livewindow/LiveWindow.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2012-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/livewindow/LiveWindow.h"
@@ -11,153 +8,191 @@
#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableInstance.h>
#include <wpi/mutex.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/smartdashboard/Sendable.h"
#include "frc/smartdashboard/SendableBuilderImpl.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
-using wpi::Twine;
+namespace {
+struct Component {
+ bool firstTime = true;
+ bool telemetryEnabled = true;
+};
-struct LiveWindow::Impl {
- Impl();
-
- struct Component {
- bool firstTime = true;
- bool telemetryEnabled = true;
- };
+struct Instance {
+ Instance() {
+ wpi::SendableRegistry::SetLiveWindowBuilderFactory(
+ [] { return std::make_unique<SendableBuilderImpl>(); });
+ }
wpi::mutex mutex;
- SendableRegistry& registry;
- int dataHandle;
+ int dataHandle = wpi::SendableRegistry::GetDataHandle();
- std::shared_ptr<nt::NetworkTable> liveWindowTable;
- std::shared_ptr<nt::NetworkTable> statusTable;
- nt::NetworkTableEntry enabledEntry;
+ std::shared_ptr<nt::NetworkTable> liveWindowTable =
+ nt::NetworkTableInstance::GetDefault().GetTable("LiveWindow");
+ std::shared_ptr<nt::NetworkTable> statusTable =
+ liveWindowTable->GetSubTable(".status");
+ nt::NetworkTableEntry enabledEntry = statusTable->GetEntry("LW Enabled");
bool startLiveWindow = false;
bool liveWindowEnabled = false;
bool telemetryEnabled = true;
- std::shared_ptr<Component> GetOrAdd(Sendable* sendable);
-};
+ std::function<void()> enabled;
+ std::function<void()> disabled;
-LiveWindow::Impl::Impl()
- : registry(SendableRegistry::GetInstance()),
- dataHandle(registry.GetDataHandle()),
- liveWindowTable(
- nt::NetworkTableInstance::GetDefault().GetTable("LiveWindow")) {
- statusTable = liveWindowTable->GetSubTable(".status");
- enabledEntry = statusTable->GetEntry("LW Enabled");
+ std::shared_ptr<Component> GetOrAdd(wpi::Sendable* sendable);
+};
+} // namespace
+
+static Instance& GetInstance() {
+ static Instance instance;
+ return instance;
}
-std::shared_ptr<LiveWindow::Impl::Component> LiveWindow::Impl::GetOrAdd(
- Sendable* sendable) {
+std::shared_ptr<Component> Instance::GetOrAdd(wpi::Sendable* sendable) {
auto data = std::static_pointer_cast<Component>(
- registry.GetData(sendable, dataHandle));
+ wpi::SendableRegistry::GetData(sendable, dataHandle));
if (!data) {
data = std::make_shared<Component>();
- registry.SetData(sendable, dataHandle, data);
+ wpi::SendableRegistry::SetData(sendable, dataHandle, data);
}
return data;
}
LiveWindow* LiveWindow::GetInstance() {
+ ::GetInstance();
static LiveWindow instance;
return &instance;
}
-void LiveWindow::EnableTelemetry(Sendable* sendable) {
- std::scoped_lock lock(m_impl->mutex);
- // Re-enable global setting in case DisableAllTelemetry() was called.
- m_impl->telemetryEnabled = true;
- m_impl->GetOrAdd(sendable)->telemetryEnabled = true;
+void LiveWindow::SetEnabledCallback(std::function<void()> func) {
+ ::GetInstance().enabled = func;
}
-void LiveWindow::DisableTelemetry(Sendable* sendable) {
- std::scoped_lock lock(m_impl->mutex);
- m_impl->GetOrAdd(sendable)->telemetryEnabled = false;
+void LiveWindow::SetDisabledCallback(std::function<void()> func) {
+ ::GetInstance().disabled = func;
+}
+
+void LiveWindow::EnableTelemetry(wpi::Sendable* sendable) {
+ auto& inst = ::GetInstance();
+ std::scoped_lock lock(inst.mutex);
+ // Re-enable global setting in case DisableAllTelemetry() was called.
+ inst.telemetryEnabled = true;
+ inst.GetOrAdd(sendable)->telemetryEnabled = true;
+}
+
+void LiveWindow::DisableTelemetry(wpi::Sendable* sendable) {
+ auto& inst = ::GetInstance();
+ std::scoped_lock lock(inst.mutex);
+ inst.GetOrAdd(sendable)->telemetryEnabled = false;
}
void LiveWindow::DisableAllTelemetry() {
- std::scoped_lock lock(m_impl->mutex);
- m_impl->telemetryEnabled = false;
- m_impl->registry.ForeachLiveWindow(m_impl->dataHandle, [&](auto& cbdata) {
- if (!cbdata.data) cbdata.data = std::make_shared<Impl::Component>();
- std::static_pointer_cast<Impl::Component>(cbdata.data)->telemetryEnabled =
- false;
+ auto& inst = ::GetInstance();
+ std::scoped_lock lock(inst.mutex);
+ inst.telemetryEnabled = false;
+ wpi::SendableRegistry::ForeachLiveWindow(inst.dataHandle, [&](auto& cbdata) {
+ if (!cbdata.data) {
+ cbdata.data = std::make_shared<Component>();
+ }
+ std::static_pointer_cast<Component>(cbdata.data)->telemetryEnabled = false;
});
}
-bool LiveWindow::IsEnabled() const {
- std::scoped_lock lock(m_impl->mutex);
- return m_impl->liveWindowEnabled;
+bool LiveWindow::IsEnabled() {
+ auto& inst = ::GetInstance();
+ std::scoped_lock lock(inst.mutex);
+ return inst.liveWindowEnabled;
}
void LiveWindow::SetEnabled(bool enabled) {
- std::scoped_lock lock(m_impl->mutex);
- if (m_impl->liveWindowEnabled == enabled) return;
- m_impl->startLiveWindow = enabled;
- m_impl->liveWindowEnabled = enabled;
+ auto& inst = ::GetInstance();
+ std::scoped_lock lock(inst.mutex);
+ if (inst.liveWindowEnabled == enabled) {
+ return;
+ }
+ inst.startLiveWindow = enabled;
+ inst.liveWindowEnabled = enabled;
// Force table generation now to make sure everything is defined
UpdateValuesUnsafe();
if (enabled) {
- if (this->enabled) this->enabled();
+ if (inst.enabled) {
+ inst.enabled();
+ }
} else {
- m_impl->registry.ForeachLiveWindow(m_impl->dataHandle, [&](auto& cbdata) {
- cbdata.builder.StopLiveWindowMode();
- });
- if (this->disabled) this->disabled();
+ wpi::SendableRegistry::ForeachLiveWindow(
+ inst.dataHandle, [&](auto& cbdata) {
+ static_cast<SendableBuilderImpl&>(cbdata.builder)
+ .StopLiveWindowMode();
+ });
+ if (inst.disabled) {
+ inst.disabled();
+ }
}
- m_impl->enabledEntry.SetBoolean(enabled);
+ inst.enabledEntry.SetBoolean(enabled);
}
void LiveWindow::UpdateValues() {
- std::scoped_lock lock(m_impl->mutex);
+ auto& inst = ::GetInstance();
+ std::scoped_lock lock(inst.mutex);
UpdateValuesUnsafe();
}
void LiveWindow::UpdateValuesUnsafe() {
+ auto& inst = ::GetInstance();
// Only do this if either LiveWindow mode or telemetry is enabled.
- if (!m_impl->liveWindowEnabled && !m_impl->telemetryEnabled) return;
+ if (!inst.liveWindowEnabled && !inst.telemetryEnabled) {
+ return;
+ }
- m_impl->registry.ForeachLiveWindow(m_impl->dataHandle, [&](auto& cbdata) {
- if (!cbdata.sendable || cbdata.parent) return;
+ wpi::SendableRegistry::ForeachLiveWindow(inst.dataHandle, [&](auto& cbdata) {
+ if (!cbdata.sendable || cbdata.parent) {
+ return;
+ }
- if (!cbdata.data) cbdata.data = std::make_shared<Impl::Component>();
+ if (!cbdata.data) {
+ cbdata.data = std::make_shared<Component>();
+ }
- auto& comp = *std::static_pointer_cast<Impl::Component>(cbdata.data);
+ auto& comp = *std::static_pointer_cast<Component>(cbdata.data);
- if (!m_impl->liveWindowEnabled && !comp.telemetryEnabled) return;
+ if (!inst.liveWindowEnabled && !comp.telemetryEnabled) {
+ return;
+ }
if (comp.firstTime) {
// By holding off creating the NetworkTable entries, it allows the
// components to be redefined. This allows default sensor and actuator
// values to be created that are replaced with the custom names from
// users calling setName.
- if (cbdata.name.empty()) return;
- auto ssTable = m_impl->liveWindowTable->GetSubTable(cbdata.subsystem);
- std::shared_ptr<NetworkTable> table;
+ if (cbdata.name.empty()) {
+ return;
+ }
+ auto ssTable = inst.liveWindowTable->GetSubTable(cbdata.subsystem);
+ std::shared_ptr<nt::NetworkTable> table;
// Treat name==subsystem as top level of subsystem
- if (cbdata.name == cbdata.subsystem)
+ if (cbdata.name == cbdata.subsystem) {
table = ssTable;
- else
+ } else {
table = ssTable->GetSubTable(cbdata.name);
+ }
table->GetEntry(".name").SetString(cbdata.name);
- cbdata.builder.SetTable(table);
+ static_cast<SendableBuilderImpl&>(cbdata.builder).SetTable(table);
cbdata.sendable->InitSendable(cbdata.builder);
ssTable->GetEntry(".type").SetString("LW Subsystem");
comp.firstTime = false;
}
- if (m_impl->startLiveWindow) cbdata.builder.StartLiveWindowMode();
- cbdata.builder.UpdateTable();
+ if (inst.startLiveWindow) {
+ static_cast<SendableBuilderImpl&>(cbdata.builder).StartLiveWindowMode();
+ }
+ cbdata.builder.Update();
});
- m_impl->startLiveWindow = false;
+ inst.startLiveWindow = false;
}
-
-LiveWindow::LiveWindow() : m_impl(new Impl) {}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/DMC60.cpp b/wpilibc/src/main/native/cpp/motorcontrol/DMC60.cpp
new file mode 100644
index 0000000..81fa868
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/DMC60.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/DMC60.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+DMC60::DMC60(int channel) : PWMMotorController("DMC60", channel) {
+ m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_DigilentDMC60, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/Jaguar.cpp b/wpilibc/src/main/native/cpp/motorcontrol/Jaguar.cpp
new file mode 100644
index 0000000..c68ae0c
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/Jaguar.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/Jaguar.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+Jaguar::Jaguar(int channel) : PWMMotorController("Jaguar", channel) {
+ m_pwm.SetBounds(2.31, 1.55, 1.507, 1.454, 0.697);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_Jaguar, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp b/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp
new file mode 100644
index 0000000..b7f26d1
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/MotorControllerGroup.cpp
@@ -0,0 +1,69 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/MotorControllerGroup.h"
+
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
+using namespace frc;
+
+// Can't use a delegated constructor here because of an MSVC bug.
+// https://developercommunity.visualstudio.com/content/problem/583/compiler-bug-with-delegating-a-constructor.html
+
+MotorControllerGroup::MotorControllerGroup(
+ std::vector<std::reference_wrapper<MotorController>>&& motorControllers)
+ : m_motorControllers(std::move(motorControllers)) {
+ Initialize();
+}
+
+void MotorControllerGroup::Initialize() {
+ for (auto& motorController : m_motorControllers) {
+ wpi::SendableRegistry::AddChild(this, &motorController.get());
+ }
+ static int instances = 0;
+ ++instances;
+ wpi::SendableRegistry::Add(this, "MotorControllerGroup", instances);
+}
+
+void MotorControllerGroup::Set(double speed) {
+ for (auto motorController : m_motorControllers) {
+ motorController.get().Set(m_isInverted ? -speed : speed);
+ }
+}
+
+double MotorControllerGroup::Get() const {
+ if (!m_motorControllers.empty()) {
+ return m_motorControllers.front().get().Get() * (m_isInverted ? -1 : 1);
+ }
+ return 0.0;
+}
+
+void MotorControllerGroup::SetInverted(bool isInverted) {
+ m_isInverted = isInverted;
+}
+
+bool MotorControllerGroup::GetInverted() const {
+ return m_isInverted;
+}
+
+void MotorControllerGroup::Disable() {
+ for (auto motorController : m_motorControllers) {
+ motorController.get().Disable();
+ }
+}
+
+void MotorControllerGroup::StopMotor() {
+ for (auto motorController : m_motorControllers) {
+ motorController.get().StopMotor();
+ }
+}
+
+void MotorControllerGroup::InitSendable(wpi::SendableBuilder& builder) {
+ builder.SetSmartDashboardType("Motor Controller");
+ builder.SetActuator(true);
+ builder.SetSafeState([=] { StopMotor(); });
+ builder.AddDoubleProperty(
+ "Value", [=] { return Get(); }, [=](double value) { Set(value); });
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp b/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp
new file mode 100644
index 0000000..21164eb
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/NidecBrushless.cpp
@@ -0,0 +1,79 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/NidecBrushless.h"
+
+#include <fmt/format.h>
+#include <hal/FRCUsageReporting.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
+using namespace frc;
+
+NidecBrushless::NidecBrushless(int pwmChannel, int dioChannel)
+ : m_dio(dioChannel), m_pwm(pwmChannel) {
+ wpi::SendableRegistry::AddChild(this, &m_dio);
+ wpi::SendableRegistry::AddChild(this, &m_pwm);
+ SetExpiration(0_s);
+ SetSafetyEnabled(false);
+
+ // the dio controls the output (in PWM mode)
+ m_dio.SetPWMRate(15625);
+ m_dio.EnablePWM(0.5);
+
+ HAL_Report(HALUsageReporting::kResourceType_NidecBrushless, pwmChannel + 1);
+ wpi::SendableRegistry::AddLW(this, "Nidec Brushless", pwmChannel);
+}
+
+void NidecBrushless::Set(double speed) {
+ if (!m_disabled) {
+ m_speed = speed;
+ m_dio.UpdateDutyCycle(0.5 + 0.5 * (m_isInverted ? -speed : speed));
+ m_pwm.SetRaw(0xffff);
+ }
+ Feed();
+}
+
+double NidecBrushless::Get() const {
+ return m_speed;
+}
+
+void NidecBrushless::SetInverted(bool isInverted) {
+ m_isInverted = isInverted;
+}
+
+bool NidecBrushless::GetInverted() const {
+ return m_isInverted;
+}
+
+void NidecBrushless::Disable() {
+ m_disabled = true;
+ m_dio.UpdateDutyCycle(0.5);
+ m_pwm.SetDisabled();
+}
+
+void NidecBrushless::Enable() {
+ m_disabled = false;
+}
+
+void NidecBrushless::StopMotor() {
+ m_dio.UpdateDutyCycle(0.5);
+ m_pwm.SetDisabled();
+}
+
+std::string NidecBrushless::GetDescription() const {
+ return fmt::format("Nidec {}", GetChannel());
+}
+
+int NidecBrushless::GetChannel() const {
+ return m_pwm.GetChannel();
+}
+
+void NidecBrushless::InitSendable(wpi::SendableBuilder& builder) {
+ builder.SetSmartDashboardType("Nidec Brushless");
+ builder.SetActuator(true);
+ builder.SetSafeState([=] { StopMotor(); });
+ builder.AddDoubleProperty(
+ "Value", [=] { return Get(); }, [=](double value) { Set(value); });
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp
new file mode 100644
index 0000000..9829a75
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMMotorController.cpp
@@ -0,0 +1,56 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+#include <fmt/format.h>
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
+using namespace frc;
+
+void PWMMotorController::Set(double speed) {
+ m_pwm.SetSpeed(m_isInverted ? -speed : speed);
+}
+
+double PWMMotorController::Get() const {
+ return m_pwm.GetSpeed() * (m_isInverted ? -1.0 : 1.0);
+}
+
+void PWMMotorController::SetInverted(bool isInverted) {
+ m_isInverted = isInverted;
+}
+
+bool PWMMotorController::GetInverted() const {
+ return m_isInverted;
+}
+
+void PWMMotorController::Disable() {
+ m_pwm.SetDisabled();
+}
+
+void PWMMotorController::StopMotor() {
+ Disable();
+}
+
+std::string PWMMotorController::GetDescription() const {
+ return fmt::format("PWM {}", GetChannel());
+}
+
+int PWMMotorController::GetChannel() const {
+ return m_pwm.GetChannel();
+}
+
+PWMMotorController::PWMMotorController(std::string_view name, int channel)
+ : m_pwm(channel, false) {
+ wpi::SendableRegistry::AddLW(this, name, channel);
+}
+
+void PWMMotorController::InitSendable(wpi::SendableBuilder& builder) {
+ builder.SetSmartDashboardType("Motor Controller");
+ builder.SetActuator(true);
+ builder.SetSafeState([=] { Disable(); });
+ builder.AddDoubleProperty(
+ "Value", [=] { return Get(); }, [=](double value) { Set(value); });
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMSparkMax.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMSparkMax.cpp
new file mode 100644
index 0000000..608d452
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMSparkMax.cpp
@@ -0,0 +1,19 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/PWMSparkMax.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+PWMSparkMax::PWMSparkMax(int channel)
+ : PWMMotorController("PWMSparkMax", channel) {
+ m_pwm.SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_RevSparkMaxPWM, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMTalonFX.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMTalonFX.cpp
new file mode 100644
index 0000000..2c6982b
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMTalonFX.cpp
@@ -0,0 +1,19 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/PWMTalonFX.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+PWMTalonFX::PWMTalonFX(int channel)
+ : PWMMotorController("PWMTalonFX", channel) {
+ m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_TalonFX, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMTalonSRX.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMTalonSRX.cpp
new file mode 100644
index 0000000..b253412
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMTalonSRX.cpp
@@ -0,0 +1,19 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/PWMTalonSRX.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+PWMTalonSRX::PWMTalonSRX(int channel)
+ : PWMMotorController("PWMTalonSRX", channel) {
+ m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_PWMTalonSRX, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMVenom.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMVenom.cpp
new file mode 100644
index 0000000..e558028
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMVenom.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/PWMVenom.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+PWMVenom::PWMVenom(int channel) : PWMMotorController("PWMVenom", channel) {
+ m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_FusionVenom, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/PWMVictorSPX.cpp b/wpilibc/src/main/native/cpp/motorcontrol/PWMVictorSPX.cpp
new file mode 100644
index 0000000..10ce992
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/PWMVictorSPX.cpp
@@ -0,0 +1,19 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/PWMVictorSPX.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+PWMVictorSPX::PWMVictorSPX(int channel)
+ : PWMMotorController("PWMVictorSPX", channel) {
+ m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_PWMVictorSPX, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/SD540.cpp b/wpilibc/src/main/native/cpp/motorcontrol/SD540.cpp
new file mode 100644
index 0000000..3d5738f
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/SD540.cpp
@@ -0,0 +1,19 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/SD540.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+SD540::SD540(int channel) : PWMMotorController("SD540", channel) {
+ m_pwm.SetBounds(2.05, 1.55, 1.50, 1.44, 0.94);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_MindsensorsSD540,
+ GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/Spark.cpp b/wpilibc/src/main/native/cpp/motorcontrol/Spark.cpp
new file mode 100644
index 0000000..45394df
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/Spark.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/Spark.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+Spark::Spark(int channel) : PWMMotorController("Spark", channel) {
+ m_pwm.SetBounds(2.003, 1.55, 1.50, 1.46, 0.999);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_RevSPARK, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/Talon.cpp b/wpilibc/src/main/native/cpp/motorcontrol/Talon.cpp
new file mode 100644
index 0000000..f4b3b69
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/Talon.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/Talon.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+Talon::Talon(int channel) : PWMMotorController("Talon", channel) {
+ m_pwm.SetBounds(2.037, 1.539, 1.513, 1.487, 0.989);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_Talon, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/Victor.cpp b/wpilibc/src/main/native/cpp/motorcontrol/Victor.cpp
new file mode 100644
index 0000000..3ad29f7
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/Victor.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/Victor.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+Victor::Victor(int channel) : PWMMotorController("Victor", channel) {
+ m_pwm.SetBounds(2.027, 1.525, 1.507, 1.49, 1.026);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_2X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_Victor, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/motorcontrol/VictorSP.cpp b/wpilibc/src/main/native/cpp/motorcontrol/VictorSP.cpp
new file mode 100644
index 0000000..6dc888e
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/motorcontrol/VictorSP.cpp
@@ -0,0 +1,18 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/motorcontrol/VictorSP.h"
+
+#include <hal/FRCUsageReporting.h>
+
+using namespace frc;
+
+VictorSP::VictorSP(int channel) : PWMMotorController("VictorSP", channel) {
+ m_pwm.SetBounds(2.004, 1.52, 1.50, 1.48, 0.997);
+ m_pwm.SetPeriodMultiplier(PWM::kPeriodMultiplier_1X);
+ m_pwm.SetSpeed(0.0);
+ m_pwm.SetZeroLatch();
+
+ HAL_Report(HALUsageReporting::kResourceType_VictorSP, GetChannel() + 1);
+}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ComplexWidget.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ComplexWidget.cpp
index 19e17bb..eaac173 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ComplexWidget.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ComplexWidget.cpp
@@ -1,42 +1,44 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ComplexWidget.h"
-#include "frc/smartdashboard/Sendable.h"
+#include <wpi/sendable/Sendable.h>
+
+#include "frc/smartdashboard/SendableBuilderImpl.h"
using namespace frc;
ComplexWidget::ComplexWidget(ShuffleboardContainer& parent,
- const wpi::Twine& title, Sendable& sendable)
+ std::string_view title, wpi::Sendable& sendable)
: ShuffleboardValue(title),
ShuffleboardWidget(parent, title),
m_sendable(sendable) {}
+ComplexWidget::~ComplexWidget() = default;
+
void ComplexWidget::EnableIfActuator() {
- if (m_builder.IsActuator()) {
- m_builder.StartLiveWindowMode();
+ if (m_builder && static_cast<SendableBuilderImpl&>(*m_builder).IsActuator()) {
+ static_cast<SendableBuilderImpl&>(*m_builder).StartLiveWindowMode();
}
}
void ComplexWidget::DisableIfActuator() {
- if (m_builder.IsActuator()) {
- m_builder.StopLiveWindowMode();
+ if (m_builder && static_cast<SendableBuilderImpl&>(*m_builder).IsActuator()) {
+ static_cast<SendableBuilderImpl&>(*m_builder).StopLiveWindowMode();
}
}
void ComplexWidget::BuildInto(std::shared_ptr<nt::NetworkTable> parentTable,
std::shared_ptr<nt::NetworkTable> metaTable) {
BuildMetadata(metaTable);
- if (!m_builderInit) {
- m_builder.SetTable(parentTable->GetSubTable(GetTitle()));
- m_sendable.InitSendable(m_builder);
- m_builder.StartListeners();
- m_builderInit = true;
+ if (!m_builder) {
+ m_builder = std::make_unique<SendableBuilderImpl>();
+ static_cast<SendableBuilderImpl&>(*m_builder)
+ .SetTable(parentTable->GetSubTable(GetTitle()));
+ m_sendable.InitSendable(static_cast<SendableBuilderImpl&>(*m_builder));
+ static_cast<SendableBuilderImpl&>(*m_builder).StartListeners();
}
- m_builder.UpdateTable();
+ m_builder->Update();
}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp b/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp
index a21cad9..9c47efb 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp
@@ -1,12 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/LayoutType.h"
using namespace frc;
-wpi::StringRef LayoutType::GetLayoutName() const { return m_layoutName; }
+std::string_view LayoutType::GetLayoutName() const {
+ return m_layoutName;
+}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp b/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp
index d80001e..834c4be 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/RecordingController.h"
-#include "frc/DriverStation.h"
+#include "frc/Errors.h"
using namespace frc;
using namespace frc::detail;
@@ -29,7 +26,7 @@
m_recordingControlEntry.SetBoolean(false);
}
-void RecordingController::SetRecordingFileNameFormat(wpi::StringRef format) {
+void RecordingController::SetRecordingFileNameFormat(std::string_view format) {
m_recordingFileNameFormatEntry.SetString(format);
}
@@ -38,12 +35,14 @@
}
void RecordingController::AddEventMarker(
- wpi::StringRef name, wpi::StringRef description,
+ std::string_view name, std::string_view description,
ShuffleboardEventImportance importance) {
if (name.empty()) {
- DriverStation::ReportError("Shuffleboard event name was not specified");
+ FRC_ReportError(err::Error, "{}",
+ "Shuffleboard event name was not specified");
return;
}
m_eventsTable->GetSubTable(name)->GetEntry("Info").SetStringArray(
- {description, ShuffleboardEventImportanceName(importance)});
+ {std::string{description},
+ std::string{ShuffleboardEventImportanceName(importance)}});
}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/SendableCameraWrapper.cpp b/wpilibc/src/main/native/cpp/shuffleboard/SendableCameraWrapper.cpp
index 663cc19..1675c64 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/SendableCameraWrapper.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/SendableCameraWrapper.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/SendableCameraWrapper.h"
@@ -12,9 +9,8 @@
#include <string>
#include <wpi/DenseMap.h>
-
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
namespace frc {
namespace detail {
@@ -24,12 +20,12 @@
return wrappers[static_cast<int>(source)];
}
-void AddToSendableRegistry(frc::Sendable* sendable, std::string name) {
- SendableRegistry::GetInstance().Add(sendable, name);
+void AddToSendableRegistry(wpi::Sendable* sendable, std::string name) {
+ wpi::SendableRegistry::Add(sendable, name);
}
} // namespace detail
-void SendableCameraWrapper::InitSendable(SendableBuilder& builder) {
+void SendableCameraWrapper::InitSendable(wpi::SendableBuilder& builder) {
builder.AddStringProperty(
".ShuffleboardURI", [this] { return m_uri; }, nullptr);
}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp b/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp
index 2d69847..16b404c 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/Shuffleboard.h"
@@ -13,15 +10,19 @@
using namespace frc;
-void Shuffleboard::Update() { GetInstance().Update(); }
+void Shuffleboard::Update() {
+ GetInstance().Update();
+}
-ShuffleboardTab& Shuffleboard::GetTab(wpi::StringRef title) {
+ShuffleboardTab& Shuffleboard::GetTab(std::string_view title) {
return GetInstance().GetTab(title);
}
-void Shuffleboard::SelectTab(int index) { GetInstance().SelectTab(index); }
+void Shuffleboard::SelectTab(int index) {
+ GetInstance().SelectTab(index);
+}
-void Shuffleboard::SelectTab(wpi::StringRef title) {
+void Shuffleboard::SelectTab(std::string_view title) {
GetInstance().SelectTab(title);
}
@@ -39,9 +40,11 @@
GetRecordingController().StartRecording();
}
-void Shuffleboard::StopRecording() { GetRecordingController().StopRecording(); }
+void Shuffleboard::StopRecording() {
+ GetRecordingController().StopRecording();
+}
-void Shuffleboard::SetRecordingFileNameFormat(wpi::StringRef format) {
+void Shuffleboard::SetRecordingFileNameFormat(std::string_view format) {
GetRecordingController().SetRecordingFileNameFormat(format);
}
@@ -49,13 +52,13 @@
GetRecordingController().ClearRecordingFileNameFormat();
}
-void Shuffleboard::AddEventMarker(wpi::StringRef name,
- wpi::StringRef description,
+void Shuffleboard::AddEventMarker(std::string_view name,
+ std::string_view description,
ShuffleboardEventImportance importance) {
GetRecordingController().AddEventMarker(name, description, importance);
}
-void Shuffleboard::AddEventMarker(wpi::StringRef name,
+void Shuffleboard::AddEventMarker(std::string_view name,
ShuffleboardEventImportance importance) {
AddEventMarker(name, "", importance);
}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp
index 7617333..940f6ab 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardComponentBase.cpp
@@ -1,27 +1,18 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardComponentBase.h"
-#include <wpi/SmallVector.h>
-
using namespace frc;
ShuffleboardComponentBase::ShuffleboardComponentBase(
- ShuffleboardContainer& parent, const wpi::Twine& title,
- const wpi::Twine& type)
- : ShuffleboardValue(title), m_parent(parent) {
- wpi::SmallVector<char, 16> storage;
- m_type = type.toStringRef(storage);
-}
+ ShuffleboardContainer& parent, std::string_view title,
+ std::string_view type)
+ : ShuffleboardValue(title), m_parent(parent), m_type(type) {}
-void ShuffleboardComponentBase::SetType(const wpi::Twine& type) {
- wpi::SmallVector<char, 16> storage;
- m_type = type.toStringRef(storage);
+void ShuffleboardComponentBase::SetType(std::string_view type) {
+ m_type = type;
m_metadataDirty = true;
}
@@ -68,7 +59,9 @@
return m_parent;
}
-const std::string& ShuffleboardComponentBase::GetType() const { return m_type; }
+const std::string& ShuffleboardComponentBase::GetType() const {
+ return m_type;
+}
const wpi::StringMap<std::shared_ptr<nt::Value>>&
ShuffleboardComponentBase::GetProperties() const {
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp
index d73f635..004f7c5 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp
@@ -1,20 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardContainer.h"
-#include <wpi/SmallVector.h>
-#include <wpi/raw_ostream.h>
+#include <wpi/sendable/SendableRegistry.h>
+#include "frc/Errors.h"
#include "frc/shuffleboard/ComplexWidget.h"
#include "frc/shuffleboard/ShuffleboardComponent.h"
#include "frc/shuffleboard/ShuffleboardLayout.h"
#include "frc/shuffleboard/SimpleWidget.h"
-#include "frc/smartdashboard/SendableRegistry.h"
using namespace frc;
@@ -24,7 +20,7 @@
return layoutStrings[static_cast<int>(layout)];
}
-ShuffleboardContainer::ShuffleboardContainer(const wpi::Twine& title)
+ShuffleboardContainer::ShuffleboardContainer(std::string_view title)
: ShuffleboardValue(title) {}
const std::vector<std::unique_ptr<ShuffleboardComponentBase>>&
@@ -32,41 +28,37 @@
return m_components;
}
-ShuffleboardLayout& ShuffleboardContainer::GetLayout(const wpi::Twine& title,
+ShuffleboardLayout& ShuffleboardContainer::GetLayout(std::string_view title,
BuiltInLayouts type) {
return GetLayout(title, GetStringFromBuiltInLayout(type));
}
-ShuffleboardLayout& ShuffleboardContainer::GetLayout(const wpi::Twine& title,
+ShuffleboardLayout& ShuffleboardContainer::GetLayout(std::string_view title,
const LayoutType& type) {
return GetLayout(title, type.GetLayoutName());
}
-ShuffleboardLayout& ShuffleboardContainer::GetLayout(const wpi::Twine& title,
- const wpi::Twine& type) {
- wpi::SmallVector<char, 16> storage;
- auto titleRef = title.toStringRef(storage);
- if (m_layouts.count(titleRef) == 0) {
- auto layout = std::make_unique<ShuffleboardLayout>(*this, titleRef, type);
+ShuffleboardLayout& ShuffleboardContainer::GetLayout(std::string_view title,
+ std::string_view type) {
+ if (m_layouts.count(title) == 0) {
+ auto layout = std::make_unique<ShuffleboardLayout>(*this, title, type);
auto ptr = layout.get();
m_components.emplace_back(std::move(layout));
- m_layouts.insert(std::make_pair(titleRef, ptr));
+ m_layouts.insert(std::make_pair(title, ptr));
}
- return *m_layouts[titleRef];
+ return *m_layouts[title];
}
-ShuffleboardLayout& ShuffleboardContainer::GetLayout(const wpi::Twine& title) {
- wpi::SmallVector<char, 16> storage;
- auto titleRef = title.toStringRef(storage);
- if (m_layouts.count(titleRef) == 0) {
- wpi_setWPIErrorWithContext(
- InvalidParameter, "No layout with the given title has been defined");
+ShuffleboardLayout& ShuffleboardContainer::GetLayout(std::string_view title) {
+ if (m_layouts.count(title) == 0) {
+ throw FRC_MakeError(err::InvalidParameter,
+ "No layout with title {} has been defined", title);
}
- return *m_layouts[titleRef];
+ return *m_layouts[title];
}
-ComplexWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
- Sendable& sendable) {
+ComplexWidget& ShuffleboardContainer::Add(std::string_view title,
+ wpi::Sendable& sendable) {
CheckTitle(title);
auto widget = std::make_unique<ComplexWidget>(*this, title, sendable);
auto ptr = widget.get();
@@ -74,16 +66,16 @@
return *ptr;
}
-ComplexWidget& ShuffleboardContainer::Add(Sendable& sendable) {
- auto name = SendableRegistry::GetInstance().GetName(&sendable);
+ComplexWidget& ShuffleboardContainer::Add(wpi::Sendable& sendable) {
+ auto name = wpi::SendableRegistry::GetName(&sendable);
if (name.empty()) {
- wpi::outs() << "Sendable must have a name\n";
+ FRC_ReportError(err::Error, "{}", "Sendable must have a name");
}
return Add(name, sendable);
}
SimpleWidget& ShuffleboardContainer::Add(
- const wpi::Twine& title, std::shared_ptr<nt::Value> defaultValue) {
+ std::string_view title, std::shared_ptr<nt::Value> defaultValue) {
CheckTitle(title);
auto widget = std::make_unique<SimpleWidget>(*this, title);
@@ -93,48 +85,48 @@
return *ptr;
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
bool defaultValue) {
return Add(title, nt::Value::MakeBoolean(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
double defaultValue) {
return Add(title, nt::Value::MakeDouble(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
int defaultValue) {
return Add(title, nt::Value::MakeDouble(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
- const wpi::Twine& defaultValue) {
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
+ std::string_view defaultValue) {
return Add(title, nt::Value::MakeString(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
const char* defaultValue) {
return Add(title, nt::Value::MakeString(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
- wpi::ArrayRef<bool> defaultValue) {
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
+ wpi::span<const bool> defaultValue) {
return Add(title, nt::Value::MakeBooleanArray(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::Add(const wpi::Twine& title,
- wpi::ArrayRef<double> defaultValue) {
+SimpleWidget& ShuffleboardContainer::Add(std::string_view title,
+ wpi::span<const double> defaultValue) {
return Add(title, nt::Value::MakeDoubleArray(defaultValue));
}
SimpleWidget& ShuffleboardContainer::Add(
- const wpi::Twine& title, wpi::ArrayRef<std::string> defaultValue) {
+ std::string_view title, wpi::span<const std::string> defaultValue) {
return Add(title, nt::Value::MakeStringArray(defaultValue));
}
SuppliedValueWidget<std::string>& ShuffleboardContainer::AddString(
- const wpi::Twine& title, std::function<std::string()> supplier) {
+ std::string_view title, std::function<std::string()> supplier) {
static auto setter = [](nt::NetworkTableEntry entry, std::string value) {
entry.SetString(value);
};
@@ -148,7 +140,7 @@
}
SuppliedValueWidget<double>& ShuffleboardContainer::AddNumber(
- const wpi::Twine& title, std::function<double()> supplier) {
+ std::string_view title, std::function<double()> supplier) {
static auto setter = [](nt::NetworkTableEntry entry, double value) {
entry.SetDouble(value);
};
@@ -162,7 +154,7 @@
}
SuppliedValueWidget<bool>& ShuffleboardContainer::AddBoolean(
- const wpi::Twine& title, std::function<bool()> supplier) {
+ std::string_view title, std::function<bool()> supplier) {
static auto setter = [](nt::NetworkTableEntry entry, bool value) {
entry.SetBoolean(value);
};
@@ -177,7 +169,7 @@
SuppliedValueWidget<std::vector<std::string>>&
ShuffleboardContainer::AddStringArray(
- const wpi::Twine& title,
+ std::string_view title,
std::function<std::vector<std::string>()> supplier) {
static auto setter = [](nt::NetworkTableEntry entry,
std::vector<std::string> value) {
@@ -193,7 +185,7 @@
}
SuppliedValueWidget<std::vector<double>>& ShuffleboardContainer::AddNumberArray(
- const wpi::Twine& title, std::function<std::vector<double>()> supplier) {
+ std::string_view title, std::function<std::vector<double>()> supplier) {
static auto setter = [](nt::NetworkTableEntry entry,
std::vector<double> value) {
entry.SetDoubleArray(value);
@@ -208,7 +200,7 @@
}
SuppliedValueWidget<std::vector<int>>& ShuffleboardContainer::AddBooleanArray(
- const wpi::Twine& title, std::function<std::vector<int>()> supplier) {
+ std::string_view title, std::function<std::vector<int>()> supplier) {
static auto setter = [](nt::NetworkTableEntry entry, std::vector<int> value) {
entry.SetBooleanArray(value);
};
@@ -221,14 +213,14 @@
return *ptr;
}
-SuppliedValueWidget<wpi::StringRef>& ShuffleboardContainer::AddRaw(
- const wpi::Twine& title, std::function<wpi::StringRef()> supplier) {
- static auto setter = [](nt::NetworkTableEntry entry, wpi::StringRef value) {
+SuppliedValueWidget<std::string_view>& ShuffleboardContainer::AddRaw(
+ std::string_view title, std::function<std::string_view()> supplier) {
+ static auto setter = [](nt::NetworkTableEntry entry, std::string_view value) {
entry.SetRaw(value);
};
CheckTitle(title);
- auto widget = std::make_unique<SuppliedValueWidget<wpi::StringRef>>(
+ auto widget = std::make_unique<SuppliedValueWidget<std::string_view>>(
*this, title, supplier, setter);
auto ptr = widget.get();
m_components.emplace_back(std::move(widget));
@@ -236,44 +228,44 @@
}
SimpleWidget& ShuffleboardContainer::AddPersistent(
- const wpi::Twine& title, std::shared_ptr<nt::Value> defaultValue) {
+ std::string_view title, std::shared_ptr<nt::Value> defaultValue) {
auto& widget = Add(title, defaultValue);
widget.GetEntry().SetPersistent();
return widget;
}
-SimpleWidget& ShuffleboardContainer::AddPersistent(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::AddPersistent(std::string_view title,
bool defaultValue) {
return AddPersistent(title, nt::Value::MakeBoolean(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::AddPersistent(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::AddPersistent(std::string_view title,
double defaultValue) {
return AddPersistent(title, nt::Value::MakeDouble(defaultValue));
}
-SimpleWidget& ShuffleboardContainer::AddPersistent(const wpi::Twine& title,
+SimpleWidget& ShuffleboardContainer::AddPersistent(std::string_view title,
int defaultValue) {
return AddPersistent(title, nt::Value::MakeDouble(defaultValue));
}
SimpleWidget& ShuffleboardContainer::AddPersistent(
- const wpi::Twine& title, const wpi::Twine& defaultValue) {
+ std::string_view title, std::string_view defaultValue) {
return AddPersistent(title, nt::Value::MakeString(defaultValue));
}
SimpleWidget& ShuffleboardContainer::AddPersistent(
- const wpi::Twine& title, wpi::ArrayRef<bool> defaultValue) {
+ std::string_view title, wpi::span<const bool> defaultValue) {
return AddPersistent(title, nt::Value::MakeBooleanArray(defaultValue));
}
SimpleWidget& ShuffleboardContainer::AddPersistent(
- const wpi::Twine& title, wpi::ArrayRef<double> defaultValue) {
+ std::string_view title, wpi::span<const double> defaultValue) {
return AddPersistent(title, nt::Value::MakeDoubleArray(defaultValue));
}
SimpleWidget& ShuffleboardContainer::AddPersistent(
- const wpi::Twine& title, wpi::ArrayRef<std::string> defaultValue) {
+ std::string_view title, wpi::span<const std::string> defaultValue) {
return AddPersistent(title, nt::Value::MakeStringArray(defaultValue));
}
@@ -289,12 +281,11 @@
}
}
-void ShuffleboardContainer::CheckTitle(const wpi::Twine& title) {
- wpi::SmallVector<char, 16> storage;
- auto titleRef = title.toStringRef(storage);
- if (m_usedTitles.count(titleRef) > 0) {
- wpi::errs() << "Title is already in use: " << title << "\n";
+void ShuffleboardContainer::CheckTitle(std::string_view title) {
+ std::string titleStr{title};
+ if (m_usedTitles.count(titleStr) > 0) {
+ FRC_ReportError(err::Error, "Title is already in use: {}", title);
return;
}
- m_usedTitles.insert(titleRef);
+ m_usedTitles.insert(titleStr);
}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp
index 3316b3e..083b4a2 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardInstance.h"
@@ -18,7 +15,7 @@
using namespace frc::detail;
struct ShuffleboardInstance::Impl {
- wpi::StringMap<ShuffleboardTab> tabs;
+ wpi::StringMap<std::unique_ptr<ShuffleboardTab>> tabs;
bool tabsChanged = false;
std::shared_ptr<nt::NetworkTable> rootTable;
@@ -32,27 +29,28 @@
HAL_Report(HALUsageReporting::kResourceType_Shuffleboard, 0);
}
-ShuffleboardInstance::~ShuffleboardInstance() {}
+ShuffleboardInstance::~ShuffleboardInstance() = default;
-frc::ShuffleboardTab& ShuffleboardInstance::GetTab(wpi::StringRef title) {
+frc::ShuffleboardTab& ShuffleboardInstance::GetTab(std::string_view title) {
if (m_impl->tabs.find(title) == m_impl->tabs.end()) {
- m_impl->tabs.try_emplace(title, ShuffleboardTab(*this, title));
+ m_impl->tabs.try_emplace(title,
+ std::make_unique<ShuffleboardTab>(*this, title));
m_impl->tabsChanged = true;
}
- return m_impl->tabs.find(title)->second;
+ return *m_impl->tabs.find(title)->second;
}
void ShuffleboardInstance::Update() {
if (m_impl->tabsChanged) {
wpi::SmallVector<std::string, 16> tabTitles;
for (auto& entry : m_impl->tabs) {
- tabTitles.emplace_back(entry.second.GetTitle());
+ tabTitles.emplace_back(entry.second->GetTitle());
}
m_impl->rootMetaTable->GetEntry("Tabs").ForceSetStringArray(tabTitles);
m_impl->tabsChanged = false;
}
for (auto& entry : m_impl->tabs) {
- auto& tab = entry.second;
+ auto& tab = *entry.second;
tab.BuildInto(m_impl->rootTable,
m_impl->rootMetaTable->GetSubTable(tab.GetTitle()));
}
@@ -60,7 +58,7 @@
void ShuffleboardInstance::EnableActuatorWidgets() {
for (auto& entry : m_impl->tabs) {
- auto& tab = entry.second;
+ auto& tab = *entry.second;
for (auto& component : tab.GetComponents()) {
component->EnableIfActuator();
}
@@ -69,7 +67,7 @@
void ShuffleboardInstance::DisableActuatorWidgets() {
for (auto& entry : m_impl->tabs) {
- auto& tab = entry.second;
+ auto& tab = *entry.second;
for (auto& component : tab.GetComponents()) {
component->DisableIfActuator();
}
@@ -80,6 +78,6 @@
m_impl->rootMetaTable->GetEntry("Selected").ForceSetDouble(index);
}
-void ShuffleboardInstance::SelectTab(wpi::StringRef title) {
+void ShuffleboardInstance::SelectTab(std::string_view title) {
m_impl->rootMetaTable->GetEntry("Selected").ForceSetString(title);
}
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardLayout.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardLayout.cpp
index 1cbfb80..c4c933e 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardLayout.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardLayout.cpp
@@ -1,17 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardLayout.h"
using namespace frc;
ShuffleboardLayout::ShuffleboardLayout(ShuffleboardContainer& parent,
- const wpi::Twine& title,
- const wpi::Twine& type)
+ std::string_view title,
+ std::string_view type)
: ShuffleboardValue(title),
ShuffleboardComponent(parent, title, type),
ShuffleboardContainer(title) {
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp
index 7a8338e..61e0e45 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp
@@ -1,18 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardTab.h"
using namespace frc;
-ShuffleboardTab::ShuffleboardTab(ShuffleboardRoot& root, wpi::StringRef title)
+ShuffleboardTab::ShuffleboardTab(ShuffleboardRoot& root, std::string_view title)
: ShuffleboardValue(title), ShuffleboardContainer(title), m_root(root) {}
-ShuffleboardRoot& ShuffleboardTab::GetRoot() { return m_root; }
+ShuffleboardRoot& ShuffleboardTab::GetRoot() {
+ return m_root;
+}
void ShuffleboardTab::BuildInto(std::shared_ptr<nt::NetworkTable> parentTable,
std::shared_ptr<nt::NetworkTable> metaTable) {
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardWidget.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardWidget.cpp
index 3b79a9c..81f6671 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardWidget.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardWidget.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardWidget.h"
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/SimpleWidget.cpp b/wpilibc/src/main/native/cpp/shuffleboard/SimpleWidget.cpp
index 89af25d..390c9c4 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/SimpleWidget.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/SimpleWidget.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/SimpleWidget.h"
@@ -14,7 +11,7 @@
using namespace frc;
SimpleWidget::SimpleWidget(ShuffleboardContainer& parent,
- const wpi::Twine& title)
+ std::string_view title)
: ShuffleboardValue(title), ShuffleboardWidget(parent, title), m_entry() {}
nt::NetworkTableEntry SimpleWidget::GetEntry() {
diff --git a/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp b/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp
index cb73d30..3062cba 100644
--- a/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp
+++ b/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp
@@ -1,12 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/WidgetType.h"
using namespace frc;
-wpi::StringRef WidgetType::GetWidgetName() const { return m_widgetName; }
+std::string_view WidgetType::GetWidgetName() const {
+ return m_widgetName;
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/ADXL345Sim.cpp b/wpilibc/src/main/native/cpp/simulation/ADXL345Sim.cpp
new file mode 100644
index 0000000..27f9c1f
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/ADXL345Sim.cpp
@@ -0,0 +1,38 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/ADXL345Sim.h"
+
+#include "frc/ADXL345_I2C.h"
+#include "frc/ADXL345_SPI.h"
+#include "frc/simulation/SimDeviceSim.h"
+
+using namespace frc::sim;
+
+ADXL345Sim::ADXL345Sim(const frc::ADXL345_I2C& accel) {
+ frc::sim::SimDeviceSim deviceSim{"Accel:ADXL345_I2C", accel.GetI2CPort(),
+ accel.GetI2CDeviceAddress()};
+ m_simX = deviceSim.GetDouble("x");
+ m_simY = deviceSim.GetDouble("y");
+ m_simZ = deviceSim.GetDouble("z");
+}
+
+ADXL345Sim::ADXL345Sim(const frc::ADXL345_SPI& accel) {
+ frc::sim::SimDeviceSim deviceSim{"Accel:ADXL345_SPI", accel.GetSpiPort()};
+ m_simX = deviceSim.GetDouble("x");
+ m_simY = deviceSim.GetDouble("y");
+ m_simZ = deviceSim.GetDouble("z");
+}
+
+void ADXL345Sim::SetX(double accel) {
+ m_simX.Set(accel);
+}
+
+void ADXL345Sim::SetY(double accel) {
+ m_simY.Set(accel);
+}
+
+void ADXL345Sim::SetZ(double accel) {
+ m_simZ.Set(accel);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/ADXL362Sim.cpp b/wpilibc/src/main/native/cpp/simulation/ADXL362Sim.cpp
new file mode 100644
index 0000000..ac5bb5a
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/ADXL362Sim.cpp
@@ -0,0 +1,29 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/ADXL362Sim.h"
+
+#include "frc/ADXL362.h"
+#include "frc/simulation/SimDeviceSim.h"
+
+using namespace frc::sim;
+
+ADXL362Sim::ADXL362Sim(const frc::ADXL362& accel) {
+ frc::sim::SimDeviceSim deviceSim{"Accel:ADXL362", accel.GetSpiPort()};
+ m_simX = deviceSim.GetDouble("x");
+ m_simY = deviceSim.GetDouble("y");
+ m_simZ = deviceSim.GetDouble("z");
+}
+
+void ADXL362Sim::SetX(double accel) {
+ m_simX.Set(accel);
+}
+
+void ADXL362Sim::SetY(double accel) {
+ m_simY.Set(accel);
+}
+
+void ADXL362Sim::SetZ(double accel) {
+ m_simZ.Set(accel);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/ADXRS450_GyroSim.cpp b/wpilibc/src/main/native/cpp/simulation/ADXRS450_GyroSim.cpp
index 74a5180..a21d1b7 100644
--- a/wpilibc/src/main/native/cpp/simulation/ADXRS450_GyroSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/ADXRS450_GyroSim.cpp
@@ -1,33 +1,24 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/ADXRS450_GyroSim.h"
-#include <wpi/SmallString.h>
-#include <wpi/raw_ostream.h>
-
#include "frc/ADXRS450_Gyro.h"
#include "frc/simulation/SimDeviceSim.h"
using namespace frc::sim;
ADXRS450_GyroSim::ADXRS450_GyroSim(const frc::ADXRS450_Gyro& gyro) {
- wpi::SmallString<128> fullname;
- wpi::raw_svector_ostream os(fullname);
- os << "ADXRS450_Gyro" << '[' << gyro.GetPort() << ']';
- frc::sim::SimDeviceSim deviceSim{fullname.c_str()};
- m_simAngle = deviceSim.GetDouble("Angle");
- m_simRate = deviceSim.GetDouble("Rate");
+ frc::sim::SimDeviceSim deviceSim{"Gyro:ADXRS450", gyro.GetPort()};
+ m_simAngle = deviceSim.GetDouble("angle_x");
+ m_simRate = deviceSim.GetDouble("rate_x");
}
void ADXRS450_GyroSim::SetAngle(units::degree_t angle) {
- m_simAngle.Set(angle.to<double>());
+ m_simAngle.Set(angle.value());
}
void ADXRS450_GyroSim::SetRate(units::degrees_per_second_t rate) {
- m_simRate.Set(rate.to<double>());
+ m_simRate.Set(rate.value());
}
diff --git a/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp b/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp
index 743c51d..8114bb3 100644
--- a/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/AddressableLEDSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/AddressableLEDSim.h"
@@ -23,8 +20,9 @@
AddressableLEDSim AddressableLEDSim::CreateForChannel(int pwmChannel) {
int index = HALSIM_FindAddressableLEDForChannel(pwmChannel);
- if (index < 0)
+ if (index < 0) {
throw std::out_of_range("no addressable LED found for PWM channel");
+ }
return AddressableLEDSim{index};
}
@@ -101,7 +99,7 @@
}
std::unique_ptr<CallbackStore> AddressableLEDSim::RegisterDataCallback(
- NotifyCallback callback, bool initialNotify) {
+ ConstBufferCallback callback, bool initialNotify) {
auto store = std::make_unique<CallbackStore>(
m_index, -1, callback, &HALSIM_CancelAddressableLEDDataCallback);
store->SetUid(HALSIM_RegisterAddressableLEDDataCallback(
diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogEncoderSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogEncoderSim.cpp
index 5fee737..049241e 100644
--- a/wpilibc/src/main/native/cpp/simulation/AnalogEncoderSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/AnalogEncoderSim.cpp
@@ -1,25 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/AnalogEncoderSim.h"
-#include <wpi/SmallString.h>
-#include <wpi/raw_ostream.h>
-
#include "frc/AnalogEncoder.h"
#include "frc/simulation/SimDeviceSim.h"
using namespace frc::sim;
AnalogEncoderSim::AnalogEncoderSim(const frc::AnalogEncoder& encoder) {
- wpi::SmallString<128> fullname;
- wpi::raw_svector_ostream os(fullname);
- os << "AnalogEncoder" << '[' << encoder.GetChannel() << ']';
- frc::sim::SimDeviceSim deviceSim{fullname.c_str()};
+ frc::sim::SimDeviceSim deviceSim{"AnalogEncoder", encoder.GetChannel()};
m_positionSim = deviceSim.GetDouble("Position");
}
@@ -28,7 +19,7 @@
}
void AnalogEncoderSim::SetTurns(units::turn_t turns) {
- m_positionSim.Set(turns.to<double>());
+ m_positionSim.Set(turns.value());
}
units::turn_t AnalogEncoderSim::GetTurns() {
diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp
index b7cab6b..625a3c0 100644
--- a/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/AnalogGyroSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/AnalogGyroSim.h"
@@ -74,4 +71,6 @@
HALSIM_SetAnalogGyroInitialized(m_index, initialized);
}
-void AnalogGyroSim::ResetData() { HALSIM_ResetAnalogGyroData(m_index); }
+void AnalogGyroSim::ResetData() {
+ HALSIM_ResetAnalogGyroData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp
index 057a188..14a6596 100644
--- a/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/AnalogInputSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/AnalogInputSim.h"
@@ -179,4 +176,6 @@
HALSIM_SetAnalogInAccumulatorDeadband(m_index, accumulatorDeadband);
}
-void AnalogInputSim::ResetData() { HALSIM_ResetAnalogInData(m_index); }
+void AnalogInputSim::ResetData() {
+ HALSIM_ResetAnalogInData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp
index 4de9082..c2b01cf 100644
--- a/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/AnalogOutputSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/AnalogOutputSim.h"
@@ -56,4 +53,6 @@
HALSIM_SetAnalogOutInitialized(m_index, initialized);
}
-void AnalogOutputSim::ResetData() { HALSIM_ResetAnalogOutData(m_index); }
+void AnalogOutputSim::ResetData() {
+ HALSIM_ResetAnalogOutData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp b/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp
index 3325827..09e0a8d 100644
--- a/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/AnalogTriggerSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/AnalogTriggerSim.h"
@@ -23,7 +20,9 @@
AnalogTriggerSim AnalogTriggerSim::CreateForChannel(int channel) {
int index = HALSIM_FindAnalogTriggerForChannel(channel);
- if (index < 0) throw std::out_of_range("no analog trigger found for channel");
+ if (index < 0) {
+ throw std::out_of_range("no analog trigger found for channel");
+ }
return AnalogTriggerSim{index};
}
@@ -86,4 +85,6 @@
HALSIM_SetAnalogTriggerTriggerUpperBound(m_index, triggerUpperBound);
}
-void AnalogTriggerSim::ResetData() { HALSIM_ResetAnalogTriggerData(m_index); }
+void AnalogTriggerSim::ResetData() {
+ HALSIM_ResetAnalogTriggerData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/BuiltInAccelerometerSim.cpp b/wpilibc/src/main/native/cpp/simulation/BuiltInAccelerometerSim.cpp
index 601ee6e..0f6aa88 100644
--- a/wpilibc/src/main/native/cpp/simulation/BuiltInAccelerometerSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/BuiltInAccelerometerSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/BuiltInAccelerometerSim.h"
diff --git a/wpilibc/src/main/native/cpp/simulation/CTREPCMSim.cpp b/wpilibc/src/main/native/cpp/simulation/CTREPCMSim.cpp
new file mode 100644
index 0000000..9c7450b
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/CTREPCMSim.cpp
@@ -0,0 +1,139 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/CTREPCMSim.h"
+
+#include <memory>
+#include <utility>
+
+#include <hal/simulation/CTREPCMData.h>
+
+#include "frc/SensorUtil.h"
+
+using namespace frc;
+using namespace frc::sim;
+
+CTREPCMSim::CTREPCMSim() : m_index{SensorUtil::GetDefaultCTREPCMModule()} {}
+
+CTREPCMSim::CTREPCMSim(int module) : m_index{module} {}
+
+CTREPCMSim::CTREPCMSim(const PneumaticsBase& pneumatics)
+ : m_index{pneumatics.GetModuleNumber()} {}
+
+std::unique_ptr<CallbackStore> CTREPCMSim::RegisterInitializedCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelCTREPCMInitializedCallback);
+ store->SetUid(HALSIM_RegisterCTREPCMInitializedCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool CTREPCMSim::GetInitialized() const {
+ return HALSIM_GetCTREPCMInitialized(m_index);
+}
+
+void CTREPCMSim::SetInitialized(bool solenoidInitialized) {
+ HALSIM_SetCTREPCMInitialized(m_index, solenoidInitialized);
+}
+
+std::unique_ptr<CallbackStore> CTREPCMSim::RegisterSolenoidOutputCallback(
+ int channel, NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, channel, -1, callback,
+ &HALSIM_CancelCTREPCMSolenoidOutputCallback);
+ store->SetUid(HALSIM_RegisterCTREPCMSolenoidOutputCallback(
+ m_index, channel, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool CTREPCMSim::GetSolenoidOutput(int channel) const {
+ return HALSIM_GetCTREPCMSolenoidOutput(m_index, channel);
+}
+
+void CTREPCMSim::SetSolenoidOutput(int channel, bool solenoidOutput) {
+ HALSIM_SetCTREPCMSolenoidOutput(m_index, channel, solenoidOutput);
+}
+
+std::unique_ptr<CallbackStore> CTREPCMSim::RegisterCompressorOnCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelCTREPCMCompressorOnCallback);
+ store->SetUid(HALSIM_RegisterCTREPCMCompressorOnCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool CTREPCMSim::GetCompressorOn() const {
+ return HALSIM_GetCTREPCMCompressorOn(m_index);
+}
+
+void CTREPCMSim::SetCompressorOn(bool compressorOn) {
+ HALSIM_SetCTREPCMCompressorOn(m_index, compressorOn);
+}
+
+std::unique_ptr<CallbackStore> CTREPCMSim::RegisterClosedLoopEnabledCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelCTREPCMClosedLoopEnabledCallback);
+ store->SetUid(HALSIM_RegisterCTREPCMClosedLoopEnabledCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool CTREPCMSim::GetClosedLoopEnabled() const {
+ return HALSIM_GetCTREPCMClosedLoopEnabled(m_index);
+}
+
+void CTREPCMSim::SetClosedLoopEnabled(bool closedLoopEnabled) {
+ HALSIM_SetCTREPCMClosedLoopEnabled(m_index, closedLoopEnabled);
+}
+
+std::unique_ptr<CallbackStore> CTREPCMSim::RegisterPressureSwitchCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelCTREPCMPressureSwitchCallback);
+ store->SetUid(HALSIM_RegisterCTREPCMPressureSwitchCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool CTREPCMSim::GetPressureSwitch() const {
+ return HALSIM_GetCTREPCMPressureSwitch(m_index);
+}
+
+void CTREPCMSim::SetPressureSwitch(bool pressureSwitch) {
+ HALSIM_SetCTREPCMPressureSwitch(m_index, pressureSwitch);
+}
+
+std::unique_ptr<CallbackStore> CTREPCMSim::RegisterCompressorCurrentCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelCTREPCMCompressorCurrentCallback);
+ store->SetUid(HALSIM_RegisterCTREPCMCompressorCurrentCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+double CTREPCMSim::GetCompressorCurrent() const {
+ return HALSIM_GetCTREPCMCompressorCurrent(m_index);
+}
+
+void CTREPCMSim::SetCompressorCurrent(double compressorCurrent) {
+ HALSIM_SetCTREPCMCompressorCurrent(m_index, compressorCurrent);
+}
+
+uint8_t CTREPCMSim::GetAllSolenoidOutputs() const {
+ uint8_t ret = 0;
+ HALSIM_GetCTREPCMAllSolenoids(m_index, &ret);
+ return ret;
+}
+
+void CTREPCMSim::SetAllSolenoidOutputs(uint8_t outputs) {
+ HALSIM_SetCTREPCMAllSolenoids(m_index, outputs);
+}
+
+void CTREPCMSim::ResetData() {
+ HALSIM_ResetCTREPCMData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp b/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp
index 5c38372..be071e9 100644
--- a/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/CallbackStore.cpp
@@ -1,12 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/CallbackStore.h"
+#include <utility>
+
using namespace frc;
using namespace frc::sim;
@@ -24,31 +23,35 @@
CallbackStore::CallbackStore(int32_t i, NotifyCallback cb,
CancelCallbackNoIndexFunc ccf)
- : index(i), callback(cb), cancelType(NoIndex) {
+ : index(i), callback(std::move(cb)), cancelType(NoIndex) {
this->ccnif = ccf;
}
CallbackStore::CallbackStore(int32_t i, int32_t u, NotifyCallback cb,
CancelCallbackFunc ccf)
- : index(i), uid(u), callback(cb), cancelType(Normal) {
+ : index(i), uid(u), callback(std::move(cb)), cancelType(Normal) {
this->ccf = ccf;
}
CallbackStore::CallbackStore(int32_t i, int32_t c, int32_t u, NotifyCallback cb,
CancelCallbackChannelFunc ccf)
- : index(i), channel(c), uid(u), callback(cb), cancelType(Channel) {
+ : index(i),
+ channel(c),
+ uid(u),
+ callback(std::move(cb)),
+ cancelType(Channel) {
this->cccf = ccf;
}
CallbackStore::CallbackStore(int32_t i, ConstBufferCallback cb,
CancelCallbackNoIndexFunc ccf)
- : index(i), constBufferCallback(cb), cancelType(NoIndex) {
+ : index(i), constBufferCallback(std::move(cb)), cancelType(NoIndex) {
this->ccnif = ccf;
}
CallbackStore::CallbackStore(int32_t i, int32_t u, ConstBufferCallback cb,
CancelCallbackFunc ccf)
- : index(i), uid(u), constBufferCallback(cb), cancelType(Normal) {
+ : index(i), uid(u), constBufferCallback(std::move(cb)), cancelType(Normal) {
this->ccf = ccf;
}
@@ -58,7 +61,7 @@
: index(i),
channel(c),
uid(u),
- constBufferCallback(cb),
+ constBufferCallback(std::move(cb)),
cancelType(Channel) {
this->cccf = ccf;
}
@@ -77,4 +80,6 @@
}
}
-void CallbackStore::SetUid(int32_t uid) { this->uid = uid; }
+void CallbackStore::SetUid(int32_t uid) {
+ this->uid = uid;
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp b/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp
index 9330735..8b73b7c 100644
--- a/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/DIOSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/DIOSim.h"
@@ -50,9 +47,13 @@
return store;
}
-bool DIOSim::GetValue() const { return HALSIM_GetDIOValue(m_index); }
+bool DIOSim::GetValue() const {
+ return HALSIM_GetDIOValue(m_index);
+}
-void DIOSim::SetValue(bool value) { HALSIM_SetDIOValue(m_index, value); }
+void DIOSim::SetValue(bool value) {
+ HALSIM_SetDIOValue(m_index, value);
+}
std::unique_ptr<CallbackStore> DIOSim::RegisterPulseLengthCallback(
NotifyCallback callback, bool initialNotify) {
@@ -80,7 +81,9 @@
return store;
}
-bool DIOSim::GetIsInput() const { return HALSIM_GetDIOIsInput(m_index); }
+bool DIOSim::GetIsInput() const {
+ return HALSIM_GetDIOIsInput(m_index);
+}
void DIOSim::SetIsInput(bool isInput) {
HALSIM_SetDIOIsInput(m_index, isInput);
@@ -95,10 +98,14 @@
return store;
}
-int DIOSim::GetFilterIndex() const { return HALSIM_GetDIOFilterIndex(m_index); }
+int DIOSim::GetFilterIndex() const {
+ return HALSIM_GetDIOFilterIndex(m_index);
+}
void DIOSim::SetFilterIndex(int filterIndex) {
HALSIM_SetDIOFilterIndex(m_index, filterIndex);
}
-void DIOSim::ResetData() { HALSIM_ResetDIOData(m_index); }
+void DIOSim::ResetData() {
+ HALSIM_ResetDIOData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp b/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp
index 51ed94a..0bbf9c3 100644
--- a/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/DifferentialDrivetrainSim.cpp
@@ -1,44 +1,56 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/DifferentialDrivetrainSim.h"
#include <frc/system/plant/LinearSystemId.h>
-#include "frc/system/RungeKutta.h"
+#include <utility>
+
+#include <wpi/MathExtras.h>
+
+#include "frc/RobotController.h"
+#include "frc/system/NumericalIntegration.h"
using namespace frc;
using namespace frc::sim;
DifferentialDrivetrainSim::DifferentialDrivetrainSim(
- const LinearSystem<2, 2, 2>& plant, units::meter_t trackWidth,
- DCMotor driveMotor, double gearRatio, units::meter_t wheelRadius)
- : m_plant(plant),
+ LinearSystem<2, 2, 2> plant, units::meter_t trackWidth, DCMotor driveMotor,
+ double gearRatio, units::meter_t wheelRadius,
+ const std::array<double, 7>& measurementStdDevs)
+ : m_plant(std::move(plant)),
m_rb(trackWidth / 2.0),
m_wheelRadius(wheelRadius),
m_motor(driveMotor),
m_originalGearing(gearRatio),
- m_currentGearing(gearRatio) {
+ m_currentGearing(gearRatio),
+ m_measurementStdDevs(measurementStdDevs) {
m_x.setZero();
m_u.setZero();
+ m_y.setZero();
}
DifferentialDrivetrainSim::DifferentialDrivetrainSim(
frc::DCMotor driveMotor, double gearing, units::kilogram_square_meter_t J,
units::kilogram_t mass, units::meter_t wheelRadius,
- units::meter_t trackWidth)
+ units::meter_t trackWidth, const std::array<double, 7>& measurementStdDevs)
: DifferentialDrivetrainSim(
frc::LinearSystemId::DrivetrainVelocitySystem(
driveMotor, mass, wheelRadius, trackWidth / 2.0, J, gearing),
- trackWidth, driveMotor, gearing, wheelRadius) {}
+ trackWidth, driveMotor, gearing, wheelRadius, measurementStdDevs) {}
+
+Eigen::Vector<double, 2> DifferentialDrivetrainSim::ClampInput(
+ const Eigen::Vector<double, 2>& u) {
+ return frc::NormalizeInputVector<2>(u,
+ frc::RobotController::GetInputVoltage());
+}
void DifferentialDrivetrainSim::SetInputs(units::volt_t leftVoltage,
units::volt_t rightVoltage) {
- m_u << leftVoltage.to<double>(), rightVoltage.to<double>();
+ m_u << leftVoltage.value(), rightVoltage.value();
+ m_u = ClampInput(m_u);
}
void DifferentialDrivetrainSim::SetGearing(double newGearing) {
@@ -46,65 +58,79 @@
}
void DifferentialDrivetrainSim::Update(units::second_t dt) {
- m_x = RungeKutta([this](auto& x, auto& u) { return Dynamics(x, u); }, m_x,
- m_u, dt);
-}
-
-double DifferentialDrivetrainSim::GetState(int state) const {
- return m_x(state);
+ m_x = RK4([this](auto& x, auto& u) { return Dynamics(x, u); }, m_x, m_u, dt);
+ m_y = m_x + frc::MakeWhiteNoiseVector<7>(m_measurementStdDevs);
}
double DifferentialDrivetrainSim::GetGearing() const {
return m_currentGearing;
}
-Eigen::Matrix<double, 7, 1> DifferentialDrivetrainSim::GetState() const {
+Eigen::Vector<double, 7> DifferentialDrivetrainSim::GetOutput() const {
+ return m_y;
+}
+
+Eigen::Vector<double, 7> DifferentialDrivetrainSim::GetState() const {
return m_x;
}
+double DifferentialDrivetrainSim::GetOutput(int output) const {
+ return m_y(output);
+}
+
+double DifferentialDrivetrainSim::GetState(int state) const {
+ return m_x(state);
+}
+
Rotation2d DifferentialDrivetrainSim::GetHeading() const {
- return Rotation2d(units::radian_t(m_x(State::kHeading)));
+ return Rotation2d(units::radian_t(GetOutput(State::kHeading)));
}
Pose2d DifferentialDrivetrainSim::GetPose() const {
- return Pose2d(units::meter_t(m_x(State::kX)), units::meter_t(m_x(State::kY)),
- Rotation2d(units::radian_t(m_x(State::kHeading))));
+ return Pose2d(units::meter_t(GetOutput(State::kX)),
+ units::meter_t(GetOutput(State::kY)), GetHeading());
}
-units::ampere_t DifferentialDrivetrainSim::GetCurrentDraw() const {
+units::ampere_t DifferentialDrivetrainSim::GetLeftCurrentDraw() const {
auto loadIleft =
- m_motor.Current(units::radians_per_second_t(m_x(State::kLeftVelocity) *
- m_currentGearing /
- m_wheelRadius.to<double>()),
- units::volt_t(m_u(0))) *
+ m_motor.Current(
+ units::radians_per_second_t(m_x(State::kLeftVelocity) *
+ m_currentGearing / m_wheelRadius.value()),
+ units::volt_t(m_u(0))) *
wpi::sgn(m_u(0));
+ return loadIleft;
+}
+
+units::ampere_t DifferentialDrivetrainSim::GetRightCurrentDraw() const {
auto loadIRight =
- m_motor.Current(units::radians_per_second_t(m_x(State::kRightVelocity) *
- m_currentGearing /
- m_wheelRadius.to<double>()),
- units::volt_t(m_u(1))) *
+ m_motor.Current(
+ units::radians_per_second_t(m_x(State::kRightVelocity) *
+ m_currentGearing / m_wheelRadius.value()),
+ units::volt_t(m_u(1))) *
wpi::sgn(m_u(1));
- return loadIleft + loadIRight;
+ return loadIRight;
+}
+units::ampere_t DifferentialDrivetrainSim::GetCurrentDraw() const {
+ return GetLeftCurrentDraw() + GetRightCurrentDraw();
}
void DifferentialDrivetrainSim::SetState(
- const Eigen::Matrix<double, 7, 1>& state) {
+ const Eigen::Vector<double, 7>& state) {
m_x = state;
}
void DifferentialDrivetrainSim::SetPose(const frc::Pose2d& pose) {
- m_x(State::kX) = pose.X().to<double>();
- m_x(State::kY) = pose.Y().to<double>();
- m_x(State::kHeading) = pose.Rotation().Radians().to<double>();
+ m_x(State::kX) = pose.X().value();
+ m_x(State::kY) = pose.Y().value();
+ m_x(State::kHeading) = pose.Rotation().Radians().value();
m_x(State::kLeftPosition) = 0;
m_x(State::kRightPosition) = 0;
}
-Eigen::Matrix<double, 7, 1> DifferentialDrivetrainSim::Dynamics(
- const Eigen::Matrix<double, 7, 1>& x,
- const Eigen::Matrix<double, 2, 1>& u) {
+Eigen::Vector<double, 7> DifferentialDrivetrainSim::Dynamics(
+ const Eigen::Vector<double, 7>& x, const Eigen::Vector<double, 2>& u) {
// Because G^2 can be factored out of A, we can divide by the old ratio
// squared and multiply by the new ratio squared to get a new drivetrain
// model.
@@ -123,12 +149,12 @@
double v = (x(State::kLeftVelocity) + x(State::kRightVelocity)) / 2.0;
- Eigen::Matrix<double, 7, 1> xdot;
+ Eigen::Vector<double, 7> xdot;
xdot(0) = v * std::cos(x(State::kHeading));
xdot(1) = v * std::sin(x(State::kHeading));
xdot(2) =
((x(State::kRightVelocity) - x(State::kLeftVelocity)) / (2.0 * m_rb))
- .to<double>();
+ .value();
xdot.block<4, 1>(3, 0) = A * x.block<4, 1>(3, 0) + B * u;
return xdot;
}
diff --git a/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp b/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp
index 2ee55ce..eb1e02e 100644
--- a/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/DigitalPWMSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/DigitalPWMSim.h"
@@ -23,7 +20,9 @@
DigitalPWMSim DigitalPWMSim::CreateForChannel(int channel) {
int index = HALSIM_FindDigitalPWMForChannel(channel);
- if (index < 0) throw std::out_of_range("no digital PWM found for channel");
+ if (index < 0) {
+ throw std::out_of_range("no digital PWM found for channel");
+ }
return DigitalPWMSim{index};
}
@@ -74,8 +73,14 @@
return store;
}
-int DigitalPWMSim::GetPin() const { return HALSIM_GetDigitalPWMPin(m_index); }
+int DigitalPWMSim::GetPin() const {
+ return HALSIM_GetDigitalPWMPin(m_index);
+}
-void DigitalPWMSim::SetPin(int pin) { HALSIM_SetDigitalPWMPin(m_index, pin); }
+void DigitalPWMSim::SetPin(int pin) {
+ HALSIM_SetDigitalPWMPin(m_index, pin);
+}
-void DigitalPWMSim::ResetData() { HALSIM_ResetDigitalPWMData(m_index); }
+void DigitalPWMSim::ResetData() {
+ HALSIM_ResetDigitalPWMData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp b/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp
index 8c0bf70..5f2c645 100644
--- a/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/DriverStationSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/DriverStationSim.h"
@@ -27,7 +24,9 @@
return store;
}
-bool DriverStationSim::GetEnabled() { return HALSIM_GetDriverStationEnabled(); }
+bool DriverStationSim::GetEnabled() {
+ return HALSIM_GetDriverStationEnabled();
+}
void DriverStationSim::SetEnabled(bool enabled) {
HALSIM_SetDriverStationEnabled(enabled);
@@ -59,9 +58,13 @@
return store;
}
-bool DriverStationSim::GetTest() { return HALSIM_GetDriverStationTest(); }
+bool DriverStationSim::GetTest() {
+ return HALSIM_GetDriverStationTest();
+}
-void DriverStationSim::SetTest(bool test) { HALSIM_SetDriverStationTest(test); }
+void DriverStationSim::SetTest(bool test) {
+ HALSIM_SetDriverStationTest(test);
+}
std::unique_ptr<CallbackStore> DriverStationSim::RegisterEStopCallback(
NotifyCallback callback, bool initialNotify) {
@@ -72,7 +75,9 @@
return store;
}
-bool DriverStationSim::GetEStop() { return HALSIM_GetDriverStationEStop(); }
+bool DriverStationSim::GetEStop() {
+ return HALSIM_GetDriverStationEStop();
+}
void DriverStationSim::SetEStop(bool eStop) {
HALSIM_SetDriverStationEStop(eStop);
@@ -150,7 +155,7 @@
void DriverStationSim::NotifyNewData() {
HALSIM_NotifyDriverStationNewData();
- DriverStation::GetInstance().WaitForData();
+ DriverStation::WaitForData();
}
void DriverStationSim::SetSendError(bool shouldSend) {
@@ -252,4 +257,6 @@
HALSIM_SetReplayNumber(replayNumber);
}
-void DriverStationSim::ResetData() { HALSIM_ResetDriverStationData(); }
+void DriverStationSim::ResetData() {
+ HALSIM_ResetDriverStationData();
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/DutyCycleEncoderSim.cpp b/wpilibc/src/main/native/cpp/simulation/DutyCycleEncoderSim.cpp
index b12f00a..cb83ccb 100644
--- a/wpilibc/src/main/native/cpp/simulation/DutyCycleEncoderSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/DutyCycleEncoderSim.cpp
@@ -1,31 +1,23 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/DutyCycleEncoderSim.h"
-#include <wpi/SmallString.h>
-#include <wpi/raw_ostream.h>
-
#include "frc/DutyCycleEncoder.h"
#include "frc/simulation/SimDeviceSim.h"
using namespace frc::sim;
DutyCycleEncoderSim::DutyCycleEncoderSim(const frc::DutyCycleEncoder& encoder) {
- wpi::SmallString<128> fullname;
- wpi::raw_svector_ostream os(fullname);
- os << "DutyCycleEncoder" << '[' << encoder.GetFPGAIndex() << ']';
- frc::sim::SimDeviceSim deviceSim{fullname.c_str()};
- m_simPosition = deviceSim.GetDouble("Position");
- m_simDistancePerRotation = deviceSim.GetDouble("DistancePerRotation");
+ frc::sim::SimDeviceSim deviceSim{"DutyCycle:DutyCycleEncoder",
+ encoder.GetSourceChannel()};
+ m_simPosition = deviceSim.GetDouble("position");
+ m_simDistancePerRotation = deviceSim.GetDouble("distance_per_rot");
}
void DutyCycleEncoderSim::Set(units::turn_t turns) {
- m_simPosition.Set(turns.to<double>());
+ m_simPosition.Set(turns.value());
}
void DutyCycleEncoderSim::SetDistance(double distance) {
diff --git a/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp b/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp
index 7ec19fd..29f2df4 100644
--- a/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/DutyCycleSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/DutyCycleSim.h"
@@ -23,7 +20,9 @@
DutyCycleSim DutyCycleSim::CreateForChannel(int channel) {
int index = HALSIM_FindDutyCycleForChannel(channel);
- if (index < 0) throw std::out_of_range("no duty cycle found for channel");
+ if (index < 0) {
+ throw std::out_of_range("no duty cycle found for channel");
+ }
return DutyCycleSim{index};
}
@@ -61,8 +60,8 @@
return HALSIM_GetDutyCycleFrequency(m_index);
}
-void DutyCycleSim::SetFrequency(int count) {
- HALSIM_SetDutyCycleFrequency(m_index, count);
+void DutyCycleSim::SetFrequency(int frequency) {
+ HALSIM_SetDutyCycleFrequency(m_index, frequency);
}
std::unique_ptr<CallbackStore> DutyCycleSim::RegisterOutputCallback(
@@ -78,8 +77,10 @@
return HALSIM_GetDutyCycleOutput(m_index);
}
-void DutyCycleSim::SetOutput(double period) {
- HALSIM_SetDutyCycleOutput(m_index, period);
+void DutyCycleSim::SetOutput(double output) {
+ HALSIM_SetDutyCycleOutput(m_index, output);
}
-void DutyCycleSim::ResetData() { HALSIM_ResetDutyCycleData(m_index); }
+void DutyCycleSim::ResetData() {
+ HALSIM_ResetDutyCycleData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp b/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp
index 89c09cb..a2d5c66 100644
--- a/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/ElevatorSim.cpp
@@ -1,16 +1,12 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/ElevatorSim.h"
#include <wpi/MathExtras.h>
-#include "frc/StateSpaceUtil.h"
-#include "frc/system/RungeKutta.h"
+#include "frc/system/NumericalIntegration.h"
#include "frc/system/plant/LinearSystemId.h"
using namespace frc;
@@ -42,16 +38,24 @@
m_maxHeight(maxHeight),
m_gearing(gearing) {}
-bool ElevatorSim::HasHitLowerLimit(const Eigen::Matrix<double, 2, 1>& x) const {
- return x(0) < m_minHeight.to<double>();
+bool ElevatorSim::WouldHitLowerLimit(units::meter_t elevatorHeight) const {
+ return elevatorHeight < m_minHeight;
}
-bool ElevatorSim::HasHitUpperLimit(const Eigen::Matrix<double, 2, 1>& x) const {
- return x(0) > m_maxHeight.to<double>();
+bool ElevatorSim::WouldHitUpperLimit(units::meter_t elevatorHeight) const {
+ return elevatorHeight > m_maxHeight;
+}
+
+bool ElevatorSim::HasHitLowerLimit() const {
+ return WouldHitLowerLimit(units::meter_t(m_y(0)));
+}
+
+bool ElevatorSim::HasHitUpperLimit() const {
+ return WouldHitUpperLimit(units::meter_t(m_y(0)));
}
units::meter_t ElevatorSim::GetPosition() const {
- return units::meter_t{m_x(0)};
+ return units::meter_t{m_y(0)};
}
units::meters_per_second_t ElevatorSim::GetVelocity() const {
@@ -74,25 +78,25 @@
}
void ElevatorSim::SetInputVoltage(units::volt_t voltage) {
- SetInput(frc::MakeMatrix<1, 1>(voltage.to<double>()));
+ SetInput(Eigen::Vector<double, 1>{voltage.value()});
}
-Eigen::Matrix<double, 2, 1> ElevatorSim::UpdateX(
- const Eigen::Matrix<double, 2, 1>& currentXhat,
- const Eigen::Matrix<double, 1, 1>& u, units::second_t dt) {
- auto updatedXhat = RungeKutta(
- [&](const Eigen::Matrix<double, 2, 1>& x,
- const Eigen::Matrix<double, 1, 1>& u_)
- -> Eigen::Matrix<double, 2, 1> {
- return m_plant.A() * x + m_plant.B() * u_ + MakeMatrix<2, 1>(0.0, -9.8);
+Eigen::Vector<double, 2> ElevatorSim::UpdateX(
+ const Eigen::Vector<double, 2>& currentXhat,
+ const Eigen::Vector<double, 1>& u, units::second_t dt) {
+ auto updatedXhat = RKDP(
+ [&](const Eigen::Vector<double, 2>& x,
+ const Eigen::Vector<double, 1>& u_) -> Eigen::Vector<double, 2> {
+ return m_plant.A() * x + m_plant.B() * u_ +
+ Eigen::Vector<double, 2>{0.0, -9.8};
},
currentXhat, u, dt);
// Check for collision after updating x-hat.
- if (HasHitLowerLimit(updatedXhat)) {
- return MakeMatrix<2, 1>(m_minHeight.to<double>(), 0.0);
+ if (WouldHitLowerLimit(units::meter_t(updatedXhat(0)))) {
+ return Eigen::Vector<double, 2>{m_minHeight.value(), 0.0};
}
- if (HasHitUpperLimit(updatedXhat)) {
- return MakeMatrix<2, 1>(m_maxHeight.to<double>(), 0.0);
+ if (WouldHitUpperLimit(units::meter_t(updatedXhat(0)))) {
+ return Eigen::Vector<double, 2>{m_maxHeight.value(), 0.0};
}
return updatedXhat;
}
diff --git a/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp b/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp
index 5bc5d52..146328d 100644
--- a/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/EncoderSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/EncoderSim.h"
@@ -23,11 +20,15 @@
EncoderSim EncoderSim::CreateForChannel(int channel) {
int index = HALSIM_FindEncoderForChannel(channel);
- if (index < 0) throw std::out_of_range("no encoder found for channel");
+ if (index < 0) {
+ throw std::out_of_range("no encoder found for channel");
+ }
return EncoderSim{index};
}
-EncoderSim EncoderSim::CreateForIndex(int index) { return EncoderSim{index}; }
+EncoderSim EncoderSim::CreateForIndex(int index) {
+ return EncoderSim{index};
+}
std::unique_ptr<CallbackStore> EncoderSim::RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify) {
@@ -55,9 +56,13 @@
return store;
}
-int EncoderSim::GetCount() const { return HALSIM_GetEncoderCount(m_index); }
+int EncoderSim::GetCount() const {
+ return HALSIM_GetEncoderCount(m_index);
+}
-void EncoderSim::SetCount(int count) { HALSIM_SetEncoderCount(m_index, count); }
+void EncoderSim::SetCount(int count) {
+ HALSIM_SetEncoderCount(m_index, count);
+}
std::unique_ptr<CallbackStore> EncoderSim::RegisterPeriodCallback(
NotifyCallback callback, bool initialNotify) {
@@ -85,7 +90,9 @@
return store;
}
-bool EncoderSim::GetReset() const { return HALSIM_GetEncoderReset(m_index); }
+bool EncoderSim::GetReset() const {
+ return HALSIM_GetEncoderReset(m_index);
+}
void EncoderSim::SetReset(bool reset) {
HALSIM_SetEncoderReset(m_index, reset);
@@ -176,14 +183,22 @@
HALSIM_SetEncoderDistancePerPulse(m_index, distancePerPulse);
}
-void EncoderSim::ResetData() { HALSIM_ResetEncoderData(m_index); }
+void EncoderSim::ResetData() {
+ HALSIM_ResetEncoderData(m_index);
+}
void EncoderSim::SetDistance(double distance) {
HALSIM_SetEncoderDistance(m_index, distance);
}
-double EncoderSim::GetDistance() { return HALSIM_GetEncoderDistance(m_index); }
+double EncoderSim::GetDistance() {
+ return HALSIM_GetEncoderDistance(m_index);
+}
-void EncoderSim::SetRate(double rate) { HALSIM_SetEncoderRate(m_index, rate); }
+void EncoderSim::SetRate(double rate) {
+ HALSIM_SetEncoderRate(m_index, rate);
+}
-double EncoderSim::GetRate() { return HALSIM_GetEncoderRate(m_index); }
+double EncoderSim::GetRate() {
+ return HALSIM_GetEncoderRate(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/Field2d.cpp b/wpilibc/src/main/native/cpp/simulation/Field2d.cpp
deleted file mode 100644
index a6098b6..0000000
--- a/wpilibc/src/main/native/cpp/simulation/Field2d.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/simulation/Field2d.h"
-
-using namespace frc;
-
-Field2d::Field2d() : m_device{"Field2D"} {
- if (m_device) {
- m_x = m_device.CreateDouble("x", false, 0.0);
- m_y = m_device.CreateDouble("y", false, 0.0);
- m_rot = m_device.CreateDouble("rot", false, 0.0);
- }
-}
-
-void Field2d::SetRobotPose(const Pose2d& pose) {
- if (m_device) {
- auto& translation = pose.Translation();
- m_x.Set(translation.X().to<double>());
- m_y.Set(translation.Y().to<double>());
- m_rot.Set(pose.Rotation().Degrees().to<double>());
- } else {
- m_pose = pose;
- }
-}
-
-void Field2d::SetRobotPose(units::meter_t x, units::meter_t y,
- Rotation2d rotation) {
- if (m_device) {
- m_x.Set(x.to<double>());
- m_y.Set(y.to<double>());
- m_rot.Set(rotation.Degrees().to<double>());
- } else {
- m_pose = Pose2d{x, y, rotation};
- }
-}
-
-Pose2d Field2d::GetRobotPose() {
- if (m_device) {
- return Pose2d{units::meter_t{m_x.Get()}, units::meter_t{m_y.Get()},
- Rotation2d{units::degree_t{m_rot.Get()}}};
- } else {
- return m_pose;
- }
-}
diff --git a/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp b/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp
index 65fc3c8..f4371b1 100644
--- a/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/FlywheelSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/FlywheelSim.h"
@@ -41,5 +38,5 @@
}
void FlywheelSim::SetInputVoltage(units::volt_t voltage) {
- SetInput(frc::MakeMatrix<1, 1>(voltage.to<double>()));
+ SetInput(Eigen::Vector<double, 1>{voltage.value()});
}
diff --git a/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp b/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp
index 8df265a..f4981e9 100644
--- a/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/GenericHIDSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/GenericHIDSim.h"
@@ -18,7 +15,9 @@
GenericHIDSim::GenericHIDSim(int port) : m_port{port} {}
-void GenericHIDSim::NotifyNewData() { DriverStationSim::NotifyNewData(); }
+void GenericHIDSim::NotifyNewData() {
+ DriverStationSim::NotifyNewData();
+}
void GenericHIDSim::SetRawButton(int button, bool value) {
DriverStationSim::SetJoystickButton(m_port, button, value);
@@ -32,7 +31,9 @@
DriverStationSim::SetJoystickPOV(m_port, pov, value);
}
-void GenericHIDSim::SetPOV(int value) { SetPOV(0, value); }
+void GenericHIDSim::SetPOV(int value) {
+ SetPOV(0, value);
+}
void GenericHIDSim::SetAxisCount(int count) {
DriverStationSim::SetJoystickAxisCount(m_port, count);
diff --git a/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp b/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp
index 55f6089..d103822 100644
--- a/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/JoystickSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/JoystickSim.h"
@@ -58,6 +55,10 @@
value);
}
-void JoystickSim::SetTrigger(bool state) { SetRawButton(1, state); }
+void JoystickSim::SetTrigger(bool state) {
+ SetRawButton(1, state);
+}
-void JoystickSim::SetTop(bool state) { SetRawButton(2, state); }
+void JoystickSim::SetTop(bool state) {
+ SetRawButton(2, state);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/Mechanism2D.cpp b/wpilibc/src/main/native/cpp/simulation/Mechanism2D.cpp
deleted file mode 100644
index 43178b1..0000000
--- a/wpilibc/src/main/native/cpp/simulation/Mechanism2D.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/simulation/Mechanism2D.h"
-
-#include <wpi/SmallString.h>
-#include <wpi/Twine.h>
-#include <wpi/raw_ostream.h>
-
-using namespace frc;
-
-Mechanism2D::Mechanism2D() : m_device{"Mechanism2D"} {}
-
-void Mechanism2D::SetLigamentAngle(const wpi::Twine& ligamentPath,
- float angle) {
- if (m_device) {
- wpi::SmallString<64> fullPathBuf;
- wpi::StringRef fullPath =
- (ligamentPath + "/angle").toNullTerminatedStringRef(fullPathBuf);
- if (!createdItems.count(fullPath)) {
- createdItems[fullPath] =
- m_device.CreateDouble(fullPath.data(), false, angle);
- }
- createdItems[fullPath].Set(angle);
- }
-}
-
-void Mechanism2D::SetLigamentLength(const wpi::Twine& ligamentPath,
- float length) {
- if (m_device) {
- wpi::SmallString<64> fullPathBuf;
- wpi::StringRef fullPath =
- (ligamentPath + "/length").toNullTerminatedStringRef(fullPathBuf);
- if (!createdItems.count(fullPath)) {
- createdItems[fullPath] =
- m_device.CreateDouble(fullPath.data(), false, length);
- }
- createdItems[fullPath].Set(length);
- }
-}
diff --git a/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp b/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp
deleted file mode 100644
index 5d0566a..0000000
--- a/wpilibc/src/main/native/cpp/simulation/PCMSim.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/simulation/PCMSim.h"
-
-#include <memory>
-#include <utility>
-
-#include <hal/simulation/PCMData.h>
-
-#include "frc/Compressor.h"
-#include "frc/SensorUtil.h"
-
-using namespace frc;
-using namespace frc::sim;
-
-PCMSim::PCMSim() : m_index{SensorUtil::GetDefaultSolenoidModule()} {}
-
-PCMSim::PCMSim(int module) : m_index{module} {}
-
-PCMSim::PCMSim(const Compressor& compressor)
- : m_index{compressor.GetModule()} {}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterSolenoidInitializedCallback(
- int channel, NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, channel, -1, callback,
- &HALSIM_CancelPCMSolenoidInitializedCallback);
- store->SetUid(HALSIM_RegisterPCMSolenoidInitializedCallback(
- m_index, channel, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PCMSim::GetSolenoidInitialized(int channel) const {
- return HALSIM_GetPCMSolenoidInitialized(m_index, channel);
-}
-
-void PCMSim::SetSolenoidInitialized(int channel, bool solenoidInitialized) {
- HALSIM_SetPCMSolenoidInitialized(m_index, channel, solenoidInitialized);
-}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterSolenoidOutputCallback(
- int channel, NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, channel, -1, callback, &HALSIM_CancelPCMSolenoidOutputCallback);
- store->SetUid(HALSIM_RegisterPCMSolenoidOutputCallback(
- m_index, channel, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PCMSim::GetSolenoidOutput(int channel) const {
- return HALSIM_GetPCMSolenoidOutput(m_index, channel);
-}
-
-void PCMSim::SetSolenoidOutput(int channel, bool solenoidOutput) {
- HALSIM_SetPCMSolenoidOutput(m_index, channel, solenoidOutput);
-}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterCompressorInitializedCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPCMCompressorInitializedCallback);
- store->SetUid(HALSIM_RegisterPCMCompressorInitializedCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PCMSim::GetCompressorInitialized() const {
- return HALSIM_GetPCMCompressorInitialized(m_index);
-}
-
-void PCMSim::SetCompressorInitialized(bool compressorInitialized) {
- HALSIM_SetPCMCompressorInitialized(m_index, compressorInitialized);
-}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterCompressorOnCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPCMCompressorOnCallback);
- store->SetUid(HALSIM_RegisterPCMCompressorOnCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PCMSim::GetCompressorOn() const {
- return HALSIM_GetPCMCompressorOn(m_index);
-}
-
-void PCMSim::SetCompressorOn(bool compressorOn) {
- HALSIM_SetPCMCompressorOn(m_index, compressorOn);
-}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterClosedLoopEnabledCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPCMClosedLoopEnabledCallback);
- store->SetUid(HALSIM_RegisterPCMClosedLoopEnabledCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PCMSim::GetClosedLoopEnabled() const {
- return HALSIM_GetPCMClosedLoopEnabled(m_index);
-}
-
-void PCMSim::SetClosedLoopEnabled(bool closedLoopEnabled) {
- HALSIM_SetPCMClosedLoopEnabled(m_index, closedLoopEnabled);
-}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterPressureSwitchCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPCMPressureSwitchCallback);
- store->SetUid(HALSIM_RegisterPCMPressureSwitchCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PCMSim::GetPressureSwitch() const {
- return HALSIM_GetPCMPressureSwitch(m_index);
-}
-
-void PCMSim::SetPressureSwitch(bool pressureSwitch) {
- HALSIM_SetPCMPressureSwitch(m_index, pressureSwitch);
-}
-
-std::unique_ptr<CallbackStore> PCMSim::RegisterCompressorCurrentCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPCMCompressorCurrentCallback);
- store->SetUid(HALSIM_RegisterPCMCompressorCurrentCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-double PCMSim::GetCompressorCurrent() const {
- return HALSIM_GetPCMCompressorCurrent(m_index);
-}
-
-void PCMSim::SetCompressorCurrent(double compressorCurrent) {
- HALSIM_SetPCMCompressorCurrent(m_index, compressorCurrent);
-}
-
-uint8_t PCMSim::GetAllSolenoidOutputs() const {
- uint8_t ret = 0;
- HALSIM_GetPCMAllSolenoids(m_index, &ret);
- return ret;
-}
-
-void PCMSim::SetAllSolenoidOutputs(uint8_t outputs) {
- HALSIM_SetPCMAllSolenoids(m_index, outputs);
-}
-
-void PCMSim::ResetData() { HALSIM_ResetPCMData(m_index); }
diff --git a/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp b/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp
deleted file mode 100644
index 26d6a45..0000000
--- a/wpilibc/src/main/native/cpp/simulation/PDPSim.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/simulation/PDPSim.h"
-
-#include <memory>
-#include <utility>
-
-#include <hal/simulation/PDPData.h>
-
-#include "frc/PowerDistributionPanel.h"
-
-using namespace frc;
-using namespace frc::sim;
-
-PDPSim::PDPSim(int module) : m_index{module} {}
-
-PDPSim::PDPSim(const PowerDistributionPanel& pdp) : m_index{pdp.GetModule()} {}
-
-std::unique_ptr<CallbackStore> PDPSim::RegisterInitializedCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPDPInitializedCallback);
- store->SetUid(HALSIM_RegisterPDPInitializedCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-bool PDPSim::GetInitialized() const {
- return HALSIM_GetPDPInitialized(m_index);
-}
-
-void PDPSim::SetInitialized(bool initialized) {
- HALSIM_SetPDPInitialized(m_index, initialized);
-}
-
-std::unique_ptr<CallbackStore> PDPSim::RegisterTemperatureCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPDPTemperatureCallback);
- store->SetUid(HALSIM_RegisterPDPTemperatureCallback(
- m_index, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-double PDPSim::GetTemperature() const {
- return HALSIM_GetPDPTemperature(m_index);
-}
-
-void PDPSim::SetTemperature(double temperature) {
- HALSIM_SetPDPTemperature(m_index, temperature);
-}
-
-std::unique_ptr<CallbackStore> PDPSim::RegisterVoltageCallback(
- NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, -1, callback, &HALSIM_CancelPDPVoltageCallback);
- store->SetUid(HALSIM_RegisterPDPVoltageCallback(m_index, &CallbackStoreThunk,
- store.get(), initialNotify));
- return store;
-}
-
-double PDPSim::GetVoltage() const { return HALSIM_GetPDPVoltage(m_index); }
-
-void PDPSim::SetVoltage(double voltage) {
- HALSIM_SetPDPVoltage(m_index, voltage);
-}
-
-std::unique_ptr<CallbackStore> PDPSim::RegisterCurrentCallback(
- int channel, NotifyCallback callback, bool initialNotify) {
- auto store = std::make_unique<CallbackStore>(
- m_index, channel, -1, callback, &HALSIM_CancelPDPCurrentCallback);
- store->SetUid(HALSIM_RegisterPDPCurrentCallback(
- m_index, channel, &CallbackStoreThunk, store.get(), initialNotify));
- return store;
-}
-
-double PDPSim::GetCurrent(int channel) const {
- return HALSIM_GetPDPCurrent(m_index, channel);
-}
-
-void PDPSim::SetCurrent(int channel, double current) {
- HALSIM_SetPDPCurrent(m_index, channel, current);
-}
-
-void PDPSim::GetAllCurrents(double* currents) const {
- HALSIM_GetPDPAllCurrents(m_index, currents);
-}
-
-void PDPSim::SetAllCurrents(const double* currents) {
- HALSIM_SetPDPAllCurrents(m_index, currents);
-}
-
-void PDPSim::ResetData() { HALSIM_ResetPDPData(m_index); }
diff --git a/wpilibc/src/main/native/cpp/simulation/PS4ControllerSim.cpp b/wpilibc/src/main/native/cpp/simulation/PS4ControllerSim.cpp
new file mode 100644
index 0000000..3403755
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/PS4ControllerSim.cpp
@@ -0,0 +1,101 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/PS4ControllerSim.h"
+
+#include "frc/PS4Controller.h"
+
+using namespace frc;
+using namespace frc::sim;
+
+PS4ControllerSim::PS4ControllerSim(const PS4Controller& joystick)
+ : GenericHIDSim{joystick} {
+ SetAxisCount(6);
+ SetButtonCount(14);
+}
+
+PS4ControllerSim::PS4ControllerSim(int port) : GenericHIDSim{port} {
+ SetAxisCount(6);
+ SetButtonCount(14);
+}
+
+void PS4ControllerSim::SetLeftX(double value) {
+ SetRawAxis(PS4Controller::Axis::kLeftX, value);
+}
+
+void PS4ControllerSim::SetRightX(double value) {
+ SetRawAxis(PS4Controller::Axis::kRightX, value);
+}
+
+void PS4ControllerSim::SetLeftY(double value) {
+ SetRawAxis(PS4Controller::Axis::kLeftY, value);
+}
+
+void PS4ControllerSim::SetRightY(double value) {
+ SetRawAxis(PS4Controller::Axis::kRightY, value);
+}
+
+void PS4ControllerSim::SetL2Axis(double value) {
+ SetRawAxis(PS4Controller::Axis::kL2, value);
+}
+
+void PS4ControllerSim::SetR2Axis(double value) {
+ SetRawAxis(PS4Controller::Axis::kR2, value);
+}
+
+void PS4ControllerSim::SetSquareButton(bool value) {
+ SetRawButton(PS4Controller::Button::kSquare, value);
+}
+
+void PS4ControllerSim::SetCrossButton(bool value) {
+ SetRawButton(PS4Controller::Button::kCross, value);
+}
+
+void PS4ControllerSim::SetCircleButton(bool value) {
+ SetRawButton(PS4Controller::Button::kCircle, value);
+}
+
+void PS4ControllerSim::SetTriangleButton(bool value) {
+ SetRawButton(PS4Controller::Button::kTriangle, value);
+}
+
+void PS4ControllerSim::SetL1Button(bool value) {
+ SetRawButton(PS4Controller::Button::kL1, value);
+}
+
+void PS4ControllerSim::SetR1Button(bool value) {
+ SetRawButton(PS4Controller::Button::kR1, value);
+}
+
+void PS4ControllerSim::SetL2Button(bool value) {
+ SetRawButton(PS4Controller::Button::kL2, value);
+}
+
+void PS4ControllerSim::SetR2Button(bool value) {
+ SetRawButton(PS4Controller::Button::kR2, value);
+}
+
+void PS4ControllerSim::SetShareButton(bool value) {
+ SetRawButton(PS4Controller::Button::kShare, value);
+}
+
+void PS4ControllerSim::SetOptionsButton(bool value) {
+ SetRawButton(PS4Controller::Button::kOptions, value);
+}
+
+void PS4ControllerSim::SetL3Button(bool value) {
+ SetRawButton(PS4Controller::Button::kL3, value);
+}
+
+void PS4ControllerSim::SetR3Button(bool value) {
+ SetRawButton(PS4Controller::Button::kR3, value);
+}
+
+void PS4ControllerSim::SetPSButton(bool value) {
+ SetRawButton(PS4Controller::Button::kPS, value);
+}
+
+void PS4ControllerSim::SetTouchpad(bool value) {
+ SetRawButton(PS4Controller::Button::kTouchpad, value);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp b/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp
index 2fae8fb..f5d69db 100644
--- a/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/PWMSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/PWMSim.h"
@@ -47,7 +44,9 @@
return store;
}
-int PWMSim::GetRawValue() const { return HALSIM_GetPWMRawValue(m_index); }
+int PWMSim::GetRawValue() const {
+ return HALSIM_GetPWMRawValue(m_index);
+}
void PWMSim::SetRawValue(int rawValue) {
HALSIM_SetPWMRawValue(m_index, rawValue);
@@ -62,9 +61,13 @@
return store;
}
-double PWMSim::GetSpeed() const { return HALSIM_GetPWMSpeed(m_index); }
+double PWMSim::GetSpeed() const {
+ return HALSIM_GetPWMSpeed(m_index);
+}
-void PWMSim::SetSpeed(double speed) { HALSIM_SetPWMSpeed(m_index, speed); }
+void PWMSim::SetSpeed(double speed) {
+ HALSIM_SetPWMSpeed(m_index, speed);
+}
std::unique_ptr<CallbackStore> PWMSim::RegisterPositionCallback(
NotifyCallback callback, bool initialNotify) {
@@ -75,7 +78,9 @@
return store;
}
-double PWMSim::GetPosition() const { return HALSIM_GetPWMPosition(m_index); }
+double PWMSim::GetPosition() const {
+ return HALSIM_GetPWMPosition(m_index);
+}
void PWMSim::SetPosition(double position) {
HALSIM_SetPWMPosition(m_index, position);
@@ -90,7 +95,9 @@
return store;
}
-int PWMSim::GetPeriodScale() const { return HALSIM_GetPWMPeriodScale(m_index); }
+int PWMSim::GetPeriodScale() const {
+ return HALSIM_GetPWMPeriodScale(m_index);
+}
void PWMSim::SetPeriodScale(int periodScale) {
HALSIM_SetPWMPeriodScale(m_index, periodScale);
@@ -105,10 +112,14 @@
return store;
}
-bool PWMSim::GetZeroLatch() const { return HALSIM_GetPWMZeroLatch(m_index); }
+bool PWMSim::GetZeroLatch() const {
+ return HALSIM_GetPWMZeroLatch(m_index);
+}
void PWMSim::SetZeroLatch(bool zeroLatch) {
HALSIM_SetPWMZeroLatch(m_index, zeroLatch);
}
-void PWMSim::ResetData() { HALSIM_ResetPWMData(m_index); }
+void PWMSim::ResetData() {
+ HALSIM_ResetPWMData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/PowerDistributionSim.cpp b/wpilibc/src/main/native/cpp/simulation/PowerDistributionSim.cpp
new file mode 100644
index 0000000..844a1b6
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/PowerDistributionSim.cpp
@@ -0,0 +1,105 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/PowerDistributionSim.h"
+
+#include <memory>
+#include <utility>
+
+#include <hal/simulation/PowerDistributionData.h>
+
+#include "frc/PowerDistribution.h"
+
+using namespace frc;
+using namespace frc::sim;
+
+PowerDistributionSim::PowerDistributionSim(int module) : m_index{module} {}
+
+PowerDistributionSim::PowerDistributionSim(const PowerDistribution& pdp)
+ : m_index{pdp.GetModule()} {}
+
+std::unique_ptr<CallbackStore>
+PowerDistributionSim::RegisterInitializedCallback(NotifyCallback callback,
+ bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback,
+ &HALSIM_CancelPowerDistributionInitializedCallback);
+ store->SetUid(HALSIM_RegisterPowerDistributionInitializedCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool PowerDistributionSim::GetInitialized() const {
+ return HALSIM_GetPowerDistributionInitialized(m_index);
+}
+
+void PowerDistributionSim::SetInitialized(bool initialized) {
+ HALSIM_SetPowerDistributionInitialized(m_index, initialized);
+}
+
+std::unique_ptr<CallbackStore>
+PowerDistributionSim::RegisterTemperatureCallback(NotifyCallback callback,
+ bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback,
+ &HALSIM_CancelPowerDistributionTemperatureCallback);
+ store->SetUid(HALSIM_RegisterPowerDistributionTemperatureCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+double PowerDistributionSim::GetTemperature() const {
+ return HALSIM_GetPowerDistributionTemperature(m_index);
+}
+
+void PowerDistributionSim::SetTemperature(double temperature) {
+ HALSIM_SetPowerDistributionTemperature(m_index, temperature);
+}
+
+std::unique_ptr<CallbackStore> PowerDistributionSim::RegisterVoltageCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelPowerDistributionVoltageCallback);
+ store->SetUid(HALSIM_RegisterPowerDistributionVoltageCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+double PowerDistributionSim::GetVoltage() const {
+ return HALSIM_GetPowerDistributionVoltage(m_index);
+}
+
+void PowerDistributionSim::SetVoltage(double voltage) {
+ HALSIM_SetPowerDistributionVoltage(m_index, voltage);
+}
+
+std::unique_ptr<CallbackStore> PowerDistributionSim::RegisterCurrentCallback(
+ int channel, NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, channel, -1, callback,
+ &HALSIM_CancelPowerDistributionCurrentCallback);
+ store->SetUid(HALSIM_RegisterPowerDistributionCurrentCallback(
+ m_index, channel, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+double PowerDistributionSim::GetCurrent(int channel) const {
+ return HALSIM_GetPowerDistributionCurrent(m_index, channel);
+}
+
+void PowerDistributionSim::SetCurrent(int channel, double current) {
+ HALSIM_SetPowerDistributionCurrent(m_index, channel, current);
+}
+
+void PowerDistributionSim::GetAllCurrents(double* currents, int length) const {
+ HALSIM_GetPowerDistributionAllCurrents(m_index, currents, length);
+}
+
+void PowerDistributionSim::SetAllCurrents(const double* currents, int length) {
+ HALSIM_SetPowerDistributionAllCurrents(m_index, currents, length);
+}
+
+void PowerDistributionSim::ResetData() {
+ HALSIM_ResetPowerDistributionData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/REVPHSim.cpp b/wpilibc/src/main/native/cpp/simulation/REVPHSim.cpp
new file mode 100644
index 0000000..dd6dba8
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/REVPHSim.cpp
@@ -0,0 +1,139 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/REVPHSim.h"
+
+#include <memory>
+#include <utility>
+
+#include <hal/simulation/REVPHData.h>
+
+#include "frc/SensorUtil.h"
+
+using namespace frc;
+using namespace frc::sim;
+
+REVPHSim::REVPHSim() : m_index{SensorUtil::GetDefaultREVPHModule()} {}
+
+REVPHSim::REVPHSim(int module) : m_index{module} {}
+
+REVPHSim::REVPHSim(const PneumaticsBase& pneumatics)
+ : m_index{pneumatics.GetModuleNumber()} {}
+
+std::unique_ptr<CallbackStore> REVPHSim::RegisterInitializedCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelREVPHInitializedCallback);
+ store->SetUid(HALSIM_RegisterREVPHInitializedCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool REVPHSim::GetInitialized() const {
+ return HALSIM_GetREVPHInitialized(m_index);
+}
+
+void REVPHSim::SetInitialized(bool solenoidInitialized) {
+ HALSIM_SetREVPHInitialized(m_index, solenoidInitialized);
+}
+
+std::unique_ptr<CallbackStore> REVPHSim::RegisterSolenoidOutputCallback(
+ int channel, NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, channel, -1, callback,
+ &HALSIM_CancelREVPHSolenoidOutputCallback);
+ store->SetUid(HALSIM_RegisterREVPHSolenoidOutputCallback(
+ m_index, channel, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool REVPHSim::GetSolenoidOutput(int channel) const {
+ return HALSIM_GetREVPHSolenoidOutput(m_index, channel);
+}
+
+void REVPHSim::SetSolenoidOutput(int channel, bool solenoidOutput) {
+ HALSIM_SetREVPHSolenoidOutput(m_index, channel, solenoidOutput);
+}
+
+std::unique_ptr<CallbackStore> REVPHSim::RegisterCompressorOnCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelREVPHCompressorOnCallback);
+ store->SetUid(HALSIM_RegisterREVPHCompressorOnCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool REVPHSim::GetCompressorOn() const {
+ return HALSIM_GetREVPHCompressorOn(m_index);
+}
+
+void REVPHSim::SetCompressorOn(bool compressorOn) {
+ HALSIM_SetREVPHCompressorOn(m_index, compressorOn);
+}
+
+std::unique_ptr<CallbackStore> REVPHSim::RegisterClosedLoopEnabledCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelREVPHClosedLoopEnabledCallback);
+ store->SetUid(HALSIM_RegisterREVPHClosedLoopEnabledCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool REVPHSim::GetClosedLoopEnabled() const {
+ return HALSIM_GetREVPHClosedLoopEnabled(m_index);
+}
+
+void REVPHSim::SetClosedLoopEnabled(bool closedLoopEnabled) {
+ HALSIM_SetREVPHClosedLoopEnabled(m_index, closedLoopEnabled);
+}
+
+std::unique_ptr<CallbackStore> REVPHSim::RegisterPressureSwitchCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelREVPHPressureSwitchCallback);
+ store->SetUid(HALSIM_RegisterREVPHPressureSwitchCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+bool REVPHSim::GetPressureSwitch() const {
+ return HALSIM_GetREVPHPressureSwitch(m_index);
+}
+
+void REVPHSim::SetPressureSwitch(bool pressureSwitch) {
+ HALSIM_SetREVPHPressureSwitch(m_index, pressureSwitch);
+}
+
+std::unique_ptr<CallbackStore> REVPHSim::RegisterCompressorCurrentCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ m_index, -1, callback, &HALSIM_CancelREVPHCompressorCurrentCallback);
+ store->SetUid(HALSIM_RegisterREVPHCompressorCurrentCallback(
+ m_index, &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+double REVPHSim::GetCompressorCurrent() const {
+ return HALSIM_GetREVPHCompressorCurrent(m_index);
+}
+
+void REVPHSim::SetCompressorCurrent(double compressorCurrent) {
+ HALSIM_SetREVPHCompressorCurrent(m_index, compressorCurrent);
+}
+
+uint8_t REVPHSim::GetAllSolenoidOutputs() const {
+ uint8_t ret = 0;
+ HALSIM_GetREVPHAllSolenoids(m_index, &ret);
+ return ret;
+}
+
+void REVPHSim::SetAllSolenoidOutputs(uint8_t outputs) {
+ HALSIM_SetREVPHAllSolenoids(m_index, outputs);
+}
+
+void REVPHSim::ResetData() {
+ HALSIM_ResetREVPHData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp b/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp
index 7f7aa65..84ce120 100644
--- a/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/RelaySim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/RelaySim.h"
@@ -64,7 +61,9 @@
return store;
}
-bool RelaySim::GetForward() const { return HALSIM_GetRelayForward(m_index); }
+bool RelaySim::GetForward() const {
+ return HALSIM_GetRelayForward(m_index);
+}
void RelaySim::SetForward(bool forward) {
HALSIM_SetRelayForward(m_index, forward);
@@ -79,10 +78,14 @@
return store;
}
-bool RelaySim::GetReverse() const { return HALSIM_GetRelayReverse(m_index); }
+bool RelaySim::GetReverse() const {
+ return HALSIM_GetRelayReverse(m_index);
+}
void RelaySim::SetReverse(bool reverse) {
HALSIM_SetRelayReverse(m_index, reverse);
}
-void RelaySim::ResetData() { HALSIM_ResetRelayData(m_index); }
+void RelaySim::ResetData() {
+ HALSIM_ResetRelayData(m_index);
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp b/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp
index 0d1d104..dc2b557 100644
--- a/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/RoboRioSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/RoboRioSim.h"
@@ -24,7 +21,9 @@
return store;
}
-bool RoboRioSim::GetFPGAButton() { return HALSIM_GetRoboRioFPGAButton(); }
+bool RoboRioSim::GetFPGAButton() {
+ return HALSIM_GetRoboRioFPGAButton();
+}
void RoboRioSim::SetFPGAButton(bool fPGAButton) {
HALSIM_SetRoboRioFPGAButton(fPGAButton);
@@ -44,7 +43,7 @@
}
void RoboRioSim::SetVInVoltage(units::volt_t vInVoltage) {
- HALSIM_SetRoboRioVInVoltage(vInVoltage.to<double>());
+ HALSIM_SetRoboRioVInVoltage(vInVoltage.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterVInCurrentCallback(
@@ -61,7 +60,7 @@
}
void RoboRioSim::SetVInCurrent(units::ampere_t vInCurrent) {
- HALSIM_SetRoboRioVInCurrent(vInCurrent.to<double>());
+ HALSIM_SetRoboRioVInCurrent(vInCurrent.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserVoltage6VCallback(
@@ -78,7 +77,7 @@
}
void RoboRioSim::SetUserVoltage6V(units::volt_t userVoltage6V) {
- HALSIM_SetRoboRioUserVoltage6V(userVoltage6V.to<double>());
+ HALSIM_SetRoboRioUserVoltage6V(userVoltage6V.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserCurrent6VCallback(
@@ -95,7 +94,7 @@
}
void RoboRioSim::SetUserCurrent6V(units::ampere_t userCurrent6V) {
- HALSIM_SetRoboRioUserCurrent6V(userCurrent6V.to<double>());
+ HALSIM_SetRoboRioUserCurrent6V(userCurrent6V.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserActive6VCallback(
@@ -107,7 +106,9 @@
return store;
}
-bool RoboRioSim::GetUserActive6V() { return HALSIM_GetRoboRioUserActive6V(); }
+bool RoboRioSim::GetUserActive6V() {
+ return HALSIM_GetRoboRioUserActive6V();
+}
void RoboRioSim::SetUserActive6V(bool userActive6V) {
HALSIM_SetRoboRioUserActive6V(userActive6V);
@@ -127,7 +128,7 @@
}
void RoboRioSim::SetUserVoltage5V(units::volt_t userVoltage5V) {
- HALSIM_SetRoboRioUserVoltage5V(userVoltage5V.to<double>());
+ HALSIM_SetRoboRioUserVoltage5V(userVoltage5V.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserCurrent5VCallback(
@@ -144,7 +145,7 @@
}
void RoboRioSim::SetUserCurrent5V(units::ampere_t userCurrent5V) {
- HALSIM_SetRoboRioUserCurrent5V(userCurrent5V.to<double>());
+ HALSIM_SetRoboRioUserCurrent5V(userCurrent5V.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserActive5VCallback(
@@ -156,7 +157,9 @@
return store;
}
-bool RoboRioSim::GetUserActive5V() { return HALSIM_GetRoboRioUserActive5V(); }
+bool RoboRioSim::GetUserActive5V() {
+ return HALSIM_GetRoboRioUserActive5V();
+}
void RoboRioSim::SetUserActive5V(bool userActive5V) {
HALSIM_SetRoboRioUserActive5V(userActive5V);
@@ -176,7 +179,7 @@
}
void RoboRioSim::SetUserVoltage3V3(units::volt_t userVoltage3V3) {
- HALSIM_SetRoboRioUserVoltage3V3(userVoltage3V3.to<double>());
+ HALSIM_SetRoboRioUserVoltage3V3(userVoltage3V3.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserCurrent3V3Callback(
@@ -193,7 +196,7 @@
}
void RoboRioSim::SetUserCurrent3V3(units::ampere_t userCurrent3V3) {
- HALSIM_SetRoboRioUserCurrent3V3(userCurrent3V3.to<double>());
+ HALSIM_SetRoboRioUserCurrent3V3(userCurrent3V3.value());
}
std::unique_ptr<CallbackStore> RoboRioSim::RegisterUserActive3V3Callback(
@@ -205,7 +208,9 @@
return store;
}
-bool RoboRioSim::GetUserActive3V3() { return HALSIM_GetRoboRioUserActive3V3(); }
+bool RoboRioSim::GetUserActive3V3() {
+ return HALSIM_GetRoboRioUserActive3V3();
+}
void RoboRioSim::SetUserActive3V3(bool userActive3V3) {
HALSIM_SetRoboRioUserActive3V3(userActive3V3);
@@ -220,7 +225,9 @@
return store;
}
-int RoboRioSim::GetUserFaults6V() { return HALSIM_GetRoboRioUserFaults6V(); }
+int RoboRioSim::GetUserFaults6V() {
+ return HALSIM_GetRoboRioUserFaults6V();
+}
void RoboRioSim::SetUserFaults6V(int userFaults6V) {
HALSIM_SetRoboRioUserFaults6V(userFaults6V);
@@ -235,7 +242,9 @@
return store;
}
-int RoboRioSim::GetUserFaults5V() { return HALSIM_GetRoboRioUserFaults5V(); }
+int RoboRioSim::GetUserFaults5V() {
+ return HALSIM_GetRoboRioUserFaults5V();
+}
void RoboRioSim::SetUserFaults5V(int userFaults5V) {
HALSIM_SetRoboRioUserFaults5V(userFaults5V);
@@ -250,10 +259,31 @@
return store;
}
-int RoboRioSim::GetUserFaults3V3() { return HALSIM_GetRoboRioUserFaults3V3(); }
+int RoboRioSim::GetUserFaults3V3() {
+ return HALSIM_GetRoboRioUserFaults3V3();
+}
void RoboRioSim::SetUserFaults3V3(int userFaults3V3) {
HALSIM_SetRoboRioUserFaults3V3(userFaults3V3);
}
-void ResetData() { HALSIM_ResetRoboRioData(); }
+std::unique_ptr<CallbackStore> RoboRioSim::RegisterBrownoutVoltageCallback(
+ NotifyCallback callback, bool initialNotify) {
+ auto store = std::make_unique<CallbackStore>(
+ -1, callback, &HALSIM_CancelRoboRioBrownoutVoltageCallback);
+ store->SetUid(HALSIM_RegisterRoboRioBrownoutVoltageCallback(
+ &CallbackStoreThunk, store.get(), initialNotify));
+ return store;
+}
+
+units::volt_t RoboRioSim::GetBrownoutVoltage() {
+ return units::volt_t(HALSIM_GetRoboRioBrownoutVoltage());
+}
+
+void RoboRioSim::SetBrownoutVoltage(units::volt_t vInVoltage) {
+ HALSIM_SetRoboRioBrownoutVoltage(vInVoltage.value());
+}
+
+void RoboRioSim::ResetData() {
+ HALSIM_ResetRoboRioData();
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp b/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp
index b71f99d..9483af3 100644
--- a/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/SPIAccelerometerSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/SPIAccelerometerSim.h"
@@ -15,7 +12,9 @@
using namespace frc;
using namespace frc::sim;
-SPIAccelerometerSim::SPIAccelerometerSim(int index) { m_index = index; }
+SPIAccelerometerSim::SPIAccelerometerSim(int index) {
+ m_index = index;
+}
std::unique_ptr<CallbackStore> SPIAccelerometerSim::RegisterActiveCallback(
NotifyCallback callback, bool initialNotify) {
diff --git a/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp b/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp
index 3d52cdf..34fd1e3 100644
--- a/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/SimDeviceSim.cpp
@@ -1,15 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/SimDeviceSim.h"
#include <string>
#include <vector>
+#include <fmt/format.h>
#include <hal/SimDevice.h>
#include <hal/simulation/SimDeviceData.h>
@@ -19,10 +17,28 @@
SimDeviceSim::SimDeviceSim(const char* name)
: m_handle{HALSIM_GetSimDeviceHandle(name)} {}
+SimDeviceSim::SimDeviceSim(const char* name, int index) {
+ m_handle =
+ HALSIM_GetSimDeviceHandle(fmt::format("{}[{}]", name, index).c_str());
+}
+
+SimDeviceSim::SimDeviceSim(const char* name, int index, int channel) {
+ m_handle = HALSIM_GetSimDeviceHandle(
+ fmt::format("{}[{},{}]", name, index, channel).c_str());
+}
+
hal::SimValue SimDeviceSim::GetValue(const char* name) const {
return HALSIM_GetSimValueHandle(m_handle, name);
}
+hal::SimInt SimDeviceSim::GetInt(const char* name) const {
+ return HALSIM_GetSimValueHandle(m_handle, name);
+}
+
+hal::SimLong SimDeviceSim::GetLong(const char* name) const {
+ return HALSIM_GetSimValueHandle(m_handle, name);
+}
+
hal::SimDouble SimDeviceSim::GetDouble(const char* name) const {
return HALSIM_GetSimValueHandle(m_handle, name);
}
@@ -40,8 +56,12 @@
const char** options = HALSIM_GetSimValueEnumOptions(val, &numOptions);
std::vector<std::string> rv;
rv.reserve(numOptions);
- for (int32_t i = 0; i < numOptions; ++i) rv.emplace_back(options[i]);
+ for (int32_t i = 0; i < numOptions; ++i) {
+ rv.emplace_back(options[i]);
+ }
return rv;
}
-void SimDeviceSim::ResetData() { HALSIM_ResetSimDeviceData(); }
+void SimDeviceSim::ResetData() {
+ HALSIM_ResetSimDeviceData();
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp b/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp
index 28c434c..fe1cc65 100644
--- a/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/SimHooks.cpp
@@ -1,40 +1,51 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/SimHooks.h"
#include <hal/simulation/MockHooks.h>
-namespace frc {
-namespace sim {
+namespace frc::sim {
-void SetRuntimeType(HAL_RuntimeType type) { HALSIM_SetRuntimeType(type); }
+void SetRuntimeType(HAL_RuntimeType type) {
+ HALSIM_SetRuntimeType(type);
+}
-void WaitForProgramStart() { HALSIM_WaitForProgramStart(); }
+void WaitForProgramStart() {
+ HALSIM_WaitForProgramStart();
+}
-void SetProgramStarted() { HALSIM_SetProgramStarted(); }
+void SetProgramStarted() {
+ HALSIM_SetProgramStarted();
+}
-bool GetProgramStarted() { return HALSIM_GetProgramStarted(); }
+bool GetProgramStarted() {
+ return HALSIM_GetProgramStarted();
+}
-void RestartTiming() { HALSIM_RestartTiming(); }
+void RestartTiming() {
+ HALSIM_RestartTiming();
+}
-void PauseTiming() { HALSIM_PauseTiming(); }
+void PauseTiming() {
+ HALSIM_PauseTiming();
+}
-void ResumeTiming() { HALSIM_ResumeTiming(); }
+void ResumeTiming() {
+ HALSIM_ResumeTiming();
+}
-bool IsTimingPaused() { return HALSIM_IsTimingPaused(); }
+bool IsTimingPaused() {
+ return HALSIM_IsTimingPaused();
+}
void StepTiming(units::second_t delta) {
- HALSIM_StepTiming(static_cast<uint64_t>(delta.to<double>() * 1e6));
+ HALSIM_StepTiming(static_cast<uint64_t>(delta.value() * 1e6));
}
void StepTimingAsync(units::second_t delta) {
- HALSIM_StepTimingAsync(static_cast<uint64_t>(delta.to<double>() * 1e6));
+ HALSIM_StepTimingAsync(static_cast<uint64_t>(delta.value() * 1e6));
}
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp b/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp
index b33a19e..db56434 100644
--- a/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/SingleJointedArmSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/SingleJointedArmSim.h"
@@ -12,7 +9,7 @@
#include <units/voltage.h>
#include <wpi/MathExtras.h>
-#include "frc/system/RungeKutta.h"
+#include "frc/system/NumericalIntegration.h"
#include "frc/system/plant/LinearSystemId.h"
using namespace frc;
@@ -42,18 +39,24 @@
gearbox, gearing, armLength, minAngle, maxAngle, mass,
simulateGravity, measurementStdDevs) {}
-bool SingleJointedArmSim::HasHitLowerLimit(
- const Eigen::Matrix<double, 2, 1>& x) const {
- return x(0) < m_minAngle.to<double>();
+bool SingleJointedArmSim::WouldHitLowerLimit(units::radian_t armAngle) const {
+ return armAngle < m_minAngle;
}
-bool SingleJointedArmSim::HasHitUpperLimit(
- const Eigen::Matrix<double, 2, 1>& x) const {
- return x(0) > m_maxAngle.to<double>();
+bool SingleJointedArmSim::WouldHitUpperLimit(units::radian_t armAngle) const {
+ return armAngle > m_maxAngle;
+}
+
+bool SingleJointedArmSim::HasHitLowerLimit() const {
+ return WouldHitLowerLimit(units::radian_t(m_y(0)));
+}
+
+bool SingleJointedArmSim::HasHitUpperLimit() const {
+ return WouldHitUpperLimit(units::radian_t(m_y(0)));
}
units::radian_t SingleJointedArmSim::GetAngle() const {
- return units::radian_t{m_x(0)};
+ return units::radian_t{m_y(0)};
}
units::radians_per_second_t SingleJointedArmSim::GetVelocity() const {
@@ -69,12 +72,12 @@
}
void SingleJointedArmSim::SetInputVoltage(units::volt_t voltage) {
- SetInput(frc::MakeMatrix<1, 1>(voltage.to<double>()));
+ SetInput(Eigen::Vector<double, 1>{voltage.value()});
}
-Eigen::Matrix<double, 2, 1> SingleJointedArmSim::UpdateX(
- const Eigen::Matrix<double, 2, 1>& currentXhat,
- const Eigen::Matrix<double, 1, 1>& u, units::second_t dt) {
+Eigen::Vector<double, 2> SingleJointedArmSim::UpdateX(
+ const Eigen::Vector<double, 2>& currentXhat,
+ const Eigen::Vector<double, 1>& u, units::second_t dt) {
// Horizontal case:
// Torque = F * r = I * alpha
// alpha = F * r / I
@@ -85,24 +88,25 @@
// We therefore find that f(x, u) = Ax + Bu + [[0] [m * g * r / I *
// std::cos(theta)]]
- auto updatedXhat = RungeKutta(
- [&](const auto& x, const auto& u) -> Eigen::Matrix<double, 2, 1> {
- Eigen::Matrix<double, 2, 1> xdot = m_plant.A() * x + m_plant.B() * u;
+ Eigen::Vector<double, 2> updatedXhat = RKDP(
+ [&](const auto& x, const auto& u) -> Eigen::Vector<double, 2> {
+ Eigen::Vector<double, 2> xdot = m_plant.A() * x + m_plant.B() * u;
if (m_simulateGravity) {
- xdot += MakeMatrix<2, 1>(0.0, (m_mass * m_r * -9.8 * 3.0 /
- (m_mass * m_r * m_r) * std::cos(x(0)))
- .template to<double>());
+ xdot += Eigen::Vector<double, 2>{
+ 0.0, (m_mass * m_r * -9.8 * 3.0 / (m_mass * m_r * m_r) *
+ std::cos(x(0)))
+ .value()};
}
return xdot;
},
currentXhat, u, dt);
// Check for collisions.
- if (HasHitLowerLimit(updatedXhat)) {
- return MakeMatrix<2, 1>(m_minAngle.to<double>(), 0.0);
- } else if (HasHitUpperLimit(updatedXhat)) {
- return MakeMatrix<2, 1>(m_maxAngle.to<double>(), 0.0);
+ if (WouldHitLowerLimit(units::radian_t(updatedXhat(0)))) {
+ return Eigen::Vector<double, 2>{m_minAngle.value(), 0.0};
+ } else if (WouldHitUpperLimit(units::radian_t(updatedXhat(0)))) {
+ return Eigen::Vector<double, 2>{m_maxAngle.value(), 0.0};
}
return updatedXhat;
}
diff --git a/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp b/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp
new file mode 100644
index 0000000..d2d1687
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/simulation/UltrasonicSim.cpp
@@ -0,0 +1,24 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/UltrasonicSim.h"
+
+#include "frc/Ultrasonic.h"
+#include "frc/simulation/SimDeviceSim.h"
+
+using namespace frc::sim;
+
+UltrasonicSim::UltrasonicSim(const frc::Ultrasonic& ultrasonic) {
+ frc::sim::SimDeviceSim deviceSim{"Ultrasonic", ultrasonic.GetEchoChannel()};
+ m_simRangeValid = deviceSim.GetBoolean("Range Valid");
+ m_simRange = deviceSim.GetDouble("Range (in)");
+}
+
+void UltrasonicSim::SetRangeValid(bool isValid) {
+ m_simRangeValid.Set(isValid);
+}
+
+void UltrasonicSim::SetRange(units::meter_t range) {
+ m_simRange.Set(range.value());
+}
diff --git a/wpilibc/src/main/native/cpp/simulation/XboxControllerSim.cpp b/wpilibc/src/main/native/cpp/simulation/XboxControllerSim.cpp
index e3bbdce..393c41a 100644
--- a/wpilibc/src/main/native/cpp/simulation/XboxControllerSim.cpp
+++ b/wpilibc/src/main/native/cpp/simulation/XboxControllerSim.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/XboxControllerSim.h"
@@ -23,68 +20,66 @@
SetButtonCount(10);
}
-void XboxControllerSim::SetX(GenericHID::JoystickHand hand, double value) {
- if (hand == GenericHID::kLeftHand) {
- SetRawAxis(static_cast<int>(XboxController::Axis::kLeftX), value);
- } else {
- SetRawAxis(static_cast<int>(XboxController::Axis::kRightX), value);
- }
+void XboxControllerSim::SetLeftX(double value) {
+ SetRawAxis(XboxController::Axis::kLeftX, value);
}
-void XboxControllerSim::SetY(GenericHID::JoystickHand hand, double value) {
- if (hand == GenericHID::kLeftHand) {
- SetRawAxis(static_cast<int>(XboxController::Axis::kLeftY), value);
- } else {
- SetRawAxis(static_cast<int>(XboxController::Axis::kRightY), value);
- }
+void XboxControllerSim::SetRightX(double value) {
+ SetRawAxis(XboxController::Axis::kRightX, value);
}
-void XboxControllerSim::SetTriggerAxis(GenericHID::JoystickHand hand,
- double value) {
- if (hand == GenericHID::kLeftHand) {
- SetRawAxis(static_cast<int>(XboxController::Axis::kLeftTrigger), value);
- } else {
- SetRawAxis(static_cast<int>(XboxController::Axis::kRightTrigger), value);
- }
+void XboxControllerSim::SetLeftY(double value) {
+ SetRawAxis(XboxController::Axis::kLeftY, value);
}
-void XboxControllerSim::SetBumper(GenericHID::JoystickHand hand, bool state) {
- if (hand == GenericHID::kLeftHand) {
- SetRawButton(static_cast<int>(XboxController::Button::kBumperLeft), state);
- } else {
- SetRawButton(static_cast<int>(XboxController::Button::kBumperRight), state);
- }
+void XboxControllerSim::SetRightY(double value) {
+ SetRawAxis(XboxController::Axis::kRightY, value);
}
-void XboxControllerSim::SetStickButton(GenericHID::JoystickHand hand,
- bool state) {
- if (hand == GenericHID::kLeftHand) {
- SetRawButton(static_cast<int>(XboxController::Button::kStickLeft), state);
- } else {
- SetRawButton(static_cast<int>(XboxController::Button::kStickRight), state);
- }
+void XboxControllerSim::SetLeftTriggerAxis(double value) {
+ SetRawAxis(XboxController::Axis::kLeftTrigger, value);
+}
+
+void XboxControllerSim::SetRightTriggerAxis(double value) {
+ SetRawAxis(XboxController::Axis::kRightTrigger, value);
+}
+
+void XboxControllerSim::SetLeftBumper(bool state) {
+ SetRawButton(XboxController::Button::kLeftBumper, state);
+}
+
+void XboxControllerSim::SetRightBumper(bool state) {
+ SetRawButton(XboxController::Button::kRightBumper, state);
+}
+
+void XboxControllerSim::SetLeftStickButton(bool state) {
+ SetRawButton(XboxController::Button::kLeftStick, state);
+}
+
+void XboxControllerSim::SetRightStickButton(bool state) {
+ SetRawButton(XboxController::Button::kRightStick, state);
}
void XboxControllerSim::SetAButton(bool state) {
- SetRawButton(static_cast<int>(XboxController::Button::kA), state);
+ SetRawButton(XboxController::Button::kA, state);
}
void XboxControllerSim::SetBButton(bool state) {
- SetRawButton(static_cast<int>(XboxController::Button::kB), state);
+ SetRawButton(XboxController::Button::kB, state);
}
void XboxControllerSim::SetXButton(bool state) {
- SetRawButton(static_cast<int>(XboxController::Button::kX), state);
+ SetRawButton(XboxController::Button::kX, state);
}
void XboxControllerSim::SetYButton(bool state) {
- SetRawButton(static_cast<int>(XboxController::Button::kY), state);
+ SetRawButton(XboxController::Button::kY, state);
}
void XboxControllerSim::SetBackButton(bool state) {
- SetRawButton(static_cast<int>(XboxController::Button::kBack), state);
+ SetRawButton(XboxController::Button::kBack, state);
}
void XboxControllerSim::SetStartButton(bool state) {
- SetRawButton(static_cast<int>(XboxController::Button::kStart), state);
+ SetRawButton(XboxController::Button::kStart, state);
}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp
new file mode 100644
index 0000000..2915a12
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/smartdashboard/Field2d.cpp
@@ -0,0 +1,80 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/smartdashboard/Field2d.h"
+
+#include <networktables/NTSendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
+
+using namespace frc;
+
+Field2d::Field2d() {
+ m_objects.emplace_back(
+ std::make_unique<FieldObject2d>("Robot", FieldObject2d::private_init{}));
+ m_objects[0]->SetPose(Pose2d{});
+ wpi::SendableRegistry::Add(this, "Field");
+}
+
+Field2d::Field2d(Field2d&& rhs) : SendableHelper(std::move(rhs)) {
+ std::swap(m_table, rhs.m_table);
+ std::swap(m_objects, rhs.m_objects);
+}
+
+Field2d& Field2d::operator=(Field2d&& rhs) {
+ SendableHelper::operator=(std::move(rhs));
+
+ std::swap(m_table, rhs.m_table);
+ std::swap(m_objects, rhs.m_objects);
+
+ return *this;
+}
+
+void Field2d::SetRobotPose(const Pose2d& pose) {
+ std::scoped_lock lock(m_mutex);
+ m_objects[0]->SetPose(pose);
+}
+
+void Field2d::SetRobotPose(units::meter_t x, units::meter_t y,
+ Rotation2d rotation) {
+ std::scoped_lock lock(m_mutex);
+ m_objects[0]->SetPose(x, y, rotation);
+}
+
+Pose2d Field2d::GetRobotPose() const {
+ std::scoped_lock lock(m_mutex);
+ return m_objects[0]->GetPose();
+}
+
+FieldObject2d* Field2d::GetObject(std::string_view name) {
+ std::scoped_lock lock(m_mutex);
+ for (auto&& obj : m_objects) {
+ if (obj->m_name == name) {
+ return obj.get();
+ }
+ }
+ m_objects.emplace_back(
+ std::make_unique<FieldObject2d>(name, FieldObject2d::private_init{}));
+ auto obj = m_objects.back().get();
+ if (m_table) {
+ obj->m_entry = m_table->GetEntry(obj->m_name);
+ }
+ return obj;
+}
+
+FieldObject2d* Field2d::GetRobotObject() {
+ std::scoped_lock lock(m_mutex);
+ return m_objects[0].get();
+}
+
+void Field2d::InitSendable(nt::NTSendableBuilder& builder) {
+ builder.SetSmartDashboardType("Field2d");
+
+ std::scoped_lock lock(m_mutex);
+ m_table = builder.GetTable();
+ for (auto&& obj : m_objects) {
+ std::scoped_lock lock2(obj->m_mutex);
+ obj->m_entry = m_table->GetEntry(obj->m_name);
+ obj->UpdateEntry(true);
+ }
+}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp
new file mode 100644
index 0000000..93d6d7e
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp
@@ -0,0 +1,170 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/smartdashboard/FieldObject2d.h"
+
+#include <vector>
+
+#include <wpi/Endian.h>
+#include <wpi/MathExtras.h>
+
+#include "frc/trajectory/Trajectory.h"
+
+using namespace frc;
+
+FieldObject2d::FieldObject2d(FieldObject2d&& rhs) {
+ std::swap(m_name, rhs.m_name);
+ std::swap(m_entry, rhs.m_entry);
+ std::swap(m_poses, rhs.m_poses);
+}
+
+FieldObject2d& FieldObject2d::operator=(FieldObject2d&& rhs) {
+ std::swap(m_name, rhs.m_name);
+ std::swap(m_entry, rhs.m_entry);
+ std::swap(m_poses, rhs.m_poses);
+
+ return *this;
+}
+
+void FieldObject2d::SetPose(const Pose2d& pose) {
+ SetPoses({pose});
+}
+
+void FieldObject2d::SetPose(units::meter_t x, units::meter_t y,
+ Rotation2d rotation) {
+ SetPoses({{x, y, rotation}});
+}
+
+Pose2d FieldObject2d::GetPose() const {
+ std::scoped_lock lock(m_mutex);
+ UpdateFromEntry();
+ if (m_poses.empty()) {
+ return {};
+ }
+ return m_poses[0];
+}
+
+void FieldObject2d::SetPoses(wpi::span<const Pose2d> poses) {
+ std::scoped_lock lock(m_mutex);
+ m_poses.assign(poses.begin(), poses.end());
+ UpdateEntry();
+}
+
+void FieldObject2d::SetPoses(std::initializer_list<Pose2d> poses) {
+ SetPoses({poses.begin(), poses.end()});
+}
+
+void FieldObject2d::SetTrajectory(const Trajectory& trajectory) {
+ std::scoped_lock lock(m_mutex);
+ m_poses.clear();
+ m_poses.reserve(trajectory.States().size());
+ for (auto&& state : trajectory.States()) {
+ m_poses.push_back(state.pose);
+ }
+ UpdateEntry();
+}
+
+std::vector<Pose2d> FieldObject2d::GetPoses() const {
+ std::scoped_lock lock(m_mutex);
+ UpdateFromEntry();
+ return std::vector<Pose2d>(m_poses.begin(), m_poses.end());
+}
+
+wpi::span<const Pose2d> FieldObject2d::GetPoses(
+ wpi::SmallVectorImpl<Pose2d>& out) const {
+ std::scoped_lock lock(m_mutex);
+ UpdateFromEntry();
+ out.assign(m_poses.begin(), m_poses.end());
+ return out;
+}
+
+void FieldObject2d::UpdateEntry(bool setDefault) {
+ if (!m_entry) {
+ return;
+ }
+ if (m_poses.size() < (255 / 3)) {
+ wpi::SmallVector<double, 9> arr;
+ for (auto&& pose : m_poses) {
+ auto& translation = pose.Translation();
+ arr.push_back(translation.X().value());
+ arr.push_back(translation.Y().value());
+ arr.push_back(pose.Rotation().Degrees().value());
+ }
+ if (setDefault) {
+ m_entry.SetDefaultDoubleArray(arr);
+ } else {
+ m_entry.ForceSetDoubleArray(arr);
+ }
+ } else {
+ // send as raw array of doubles if too big for NT array
+ std::vector<char> arr;
+ arr.resize(m_poses.size() * 3 * 8);
+ char* p = arr.data();
+ for (auto&& pose : m_poses) {
+ auto& translation = pose.Translation();
+ wpi::support::endian::write64be(
+ p, wpi::DoubleToBits(translation.X().value()));
+ p += 8;
+ wpi::support::endian::write64be(
+ p, wpi::DoubleToBits(translation.Y().value()));
+ p += 8;
+ wpi::support::endian::write64be(
+ p, wpi::DoubleToBits(pose.Rotation().Degrees().value()));
+ p += 8;
+ }
+ if (setDefault) {
+ m_entry.SetDefaultRaw({arr.data(), arr.size()});
+ } else {
+ m_entry.ForceSetRaw({arr.data(), arr.size()});
+ }
+ }
+}
+
+void FieldObject2d::UpdateFromEntry() const {
+ if (!m_entry) {
+ return;
+ }
+ auto val = m_entry.GetValue();
+ if (!val) {
+ return;
+ }
+
+ if (val->IsDoubleArray()) {
+ auto arr = val->GetDoubleArray();
+ auto size = arr.size();
+ if ((size % 3) != 0) {
+ return;
+ }
+ m_poses.resize(size / 3);
+ for (size_t i = 0; i < size / 3; ++i) {
+ m_poses[i] =
+ Pose2d{units::meter_t{arr[i * 3 + 0]}, units::meter_t{arr[i * 3 + 1]},
+ Rotation2d{units::degree_t{arr[i * 3 + 2]}}};
+ }
+ } else if (val->IsRaw()) {
+ // treat it simply as an array of doubles
+ std::string_view data = val->GetRaw();
+
+ // must be triples of doubles
+ auto size = data.size();
+ if ((size % (3 * 8)) != 0) {
+ return;
+ }
+ m_poses.resize(size / (3 * 8));
+ const char* p = data.data();
+ for (size_t i = 0; i < size / (3 * 8); ++i) {
+ double x = wpi::BitsToDouble(
+ wpi::support::endian::readNext<uint64_t, wpi::support::big,
+ wpi::support::unaligned>(p));
+ double y = wpi::BitsToDouble(
+ wpi::support::endian::readNext<uint64_t, wpi::support::big,
+ wpi::support::unaligned>(p));
+ double rot = wpi::BitsToDouble(
+ wpi::support::endian::readNext<uint64_t, wpi::support::big,
+ wpi::support::unaligned>(p));
+ m_poses[i] = Pose2d{units::meter_t{x}, units::meter_t{y},
+ Rotation2d{units::degree_t{rot}}};
+ }
+ }
+}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/ListenerExecutor.cpp b/wpilibc/src/main/native/cpp/smartdashboard/ListenerExecutor.cpp
index 75b373a..2a53196 100644
--- a/wpilibc/src/main/native/cpp/smartdashboard/ListenerExecutor.cpp
+++ b/wpilibc/src/main/native/cpp/smartdashboard/ListenerExecutor.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/smartdashboard/ListenerExecutor.h"
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp
new file mode 100644
index 0000000..bfa827a
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp
@@ -0,0 +1,55 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/smartdashboard/Mechanism2d.h"
+
+#include <cstdio>
+
+#include <networktables/NTSendableBuilder.h>
+
+using namespace frc;
+
+static constexpr char kBackgroundColor[] = "backgroundColor";
+static constexpr char kDims[] = "dims";
+
+Mechanism2d::Mechanism2d(double width, double height,
+ const Color8Bit& backgroundColor)
+ : m_width{width}, m_height{height} {
+ SetBackgroundColor(backgroundColor);
+}
+
+MechanismRoot2d* Mechanism2d::GetRoot(std::string_view name, double x,
+ double y) {
+ auto& obj = m_roots[name];
+ if (obj) {
+ return obj.get();
+ }
+ obj = std::make_unique<MechanismRoot2d>(name, x, y,
+ MechanismRoot2d::private_init{});
+ if (m_table) {
+ obj->Update(m_table->GetSubTable(name));
+ }
+ return obj.get();
+}
+
+void Mechanism2d::SetBackgroundColor(const Color8Bit& color) {
+ std::snprintf(m_color, sizeof(m_color), "#%02X%02X%02X", color.red,
+ color.green, color.blue);
+ if (m_table) {
+ m_table->GetEntry(kBackgroundColor).SetString(m_color);
+ }
+}
+
+void Mechanism2d::InitSendable(nt::NTSendableBuilder& builder) {
+ builder.SetSmartDashboardType("Mechanism2d");
+
+ std::scoped_lock lock(m_mutex);
+ m_table = builder.GetTable();
+ m_table->GetEntry(kDims).SetDoubleArray({m_width, m_height});
+ m_table->GetEntry(kBackgroundColor).SetString(m_color);
+ for (const auto& entry : m_roots) {
+ const auto& root = entry.getValue().get();
+ root->Update(m_table->GetSubTable(entry.getKey()));
+ }
+}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/MechanismLigament2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/MechanismLigament2d.cpp
new file mode 100644
index 0000000..175db0d
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/smartdashboard/MechanismLigament2d.cpp
@@ -0,0 +1,82 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/smartdashboard/MechanismLigament2d.h"
+
+#include <cstdio>
+
+using namespace frc;
+
+MechanismLigament2d::MechanismLigament2d(std::string_view name, double length,
+ units::degree_t angle,
+ double lineWeight,
+ const frc::Color8Bit& color)
+ : MechanismObject2d(name),
+ m_length{length},
+ m_angle{angle.value()},
+ m_weight{lineWeight} {
+ SetColor(color);
+}
+
+void MechanismLigament2d::UpdateEntries(
+ std::shared_ptr<nt::NetworkTable> table) {
+ std::scoped_lock lock(m_mutex);
+ table->GetEntry(".type").SetString("line");
+
+ m_colorEntry = table->GetEntry("color");
+ m_angleEntry = table->GetEntry("angle");
+ m_weightEntry = table->GetEntry("weight");
+ m_lengthEntry = table->GetEntry("length");
+ Flush();
+}
+
+void MechanismLigament2d::SetColor(const Color8Bit& color) {
+ std::scoped_lock lock(m_mutex);
+ std::snprintf(m_color, sizeof(m_color), "#%02X%02X%02X", color.red,
+ color.green, color.blue);
+ Flush();
+}
+
+void MechanismLigament2d::SetAngle(units::degree_t angle) {
+ std::scoped_lock lock(m_mutex);
+ m_angle = angle.value();
+ Flush();
+}
+
+void MechanismLigament2d::SetLineWeight(double lineWidth) {
+ std::scoped_lock lock(m_mutex);
+ m_weight = lineWidth;
+ Flush();
+}
+
+double MechanismLigament2d::GetAngle() {
+ if (m_angleEntry) {
+ m_angle = m_angleEntry.GetDouble(0.0);
+ }
+ return m_angle;
+}
+
+double MechanismLigament2d::GetLength() {
+ if (m_lengthEntry) {
+ m_length = m_lengthEntry.GetDouble(0.0);
+ }
+ return m_length;
+}
+
+void MechanismLigament2d::SetLength(double length) {
+ std::scoped_lock lock(m_mutex);
+ m_length = length;
+ Flush();
+}
+
+#define SAFE_WRITE(data, Type) \
+ if (m_##data##Entry) { \
+ m_##data##Entry.Set##Type(m_##data); \
+ }
+void MechanismLigament2d::Flush() {
+ SAFE_WRITE(color, String)
+ SAFE_WRITE(angle, Double)
+ SAFE_WRITE(length, Double)
+ SAFE_WRITE(weight, Double)
+}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/MechanismObject2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/MechanismObject2d.cpp
new file mode 100644
index 0000000..15d24a3
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/smartdashboard/MechanismObject2d.cpp
@@ -0,0 +1,23 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/smartdashboard/MechanismObject2d.h"
+
+using namespace frc;
+
+MechanismObject2d::MechanismObject2d(std::string_view name) : m_name{name} {}
+
+const std::string& MechanismObject2d::GetName() const {
+ return m_name;
+}
+
+void MechanismObject2d::Update(std::shared_ptr<nt::NetworkTable> table) {
+ std::scoped_lock lock(m_mutex);
+ m_table = table;
+ UpdateEntries(m_table);
+ for (const wpi::StringMapEntry<std::unique_ptr<MechanismObject2d>>& entry :
+ m_objects) {
+ entry.getValue()->Update(m_table->GetSubTable(entry.getKey()));
+ }
+}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/MechanismRoot2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/MechanismRoot2d.cpp
new file mode 100644
index 0000000..07d15f0
--- /dev/null
+++ b/wpilibc/src/main/native/cpp/smartdashboard/MechanismRoot2d.cpp
@@ -0,0 +1,37 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/smartdashboard/MechanismRoot2d.h"
+
+#include "frc/util/Color8Bit.h"
+
+using namespace frc;
+
+MechanismRoot2d::MechanismRoot2d(std::string_view name, double x, double y,
+ const private_init&)
+ : MechanismObject2d(name), m_x{x}, m_y{y} {}
+
+void MechanismRoot2d::SetPosition(double x, double y) {
+ std::scoped_lock lock(m_mutex);
+ m_x = x;
+ m_y = y;
+ Flush();
+}
+
+void MechanismRoot2d::UpdateEntries(std::shared_ptr<nt::NetworkTable> table) {
+ std::scoped_lock lock(m_mutex);
+ m_xEntry = table->GetEntry("x");
+ m_yEntry = table->GetEntry("y");
+ Flush();
+}
+
+inline void MechanismRoot2d::Flush() {
+ std::scoped_lock lock(m_mutex);
+ if (m_xEntry) {
+ m_xEntry.SetDouble(m_x);
+ }
+ if (m_yEntry) {
+ m_yEntry.SetDouble(m_y);
+ }
+}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp
deleted file mode 100644
index 7fc8635..0000000
--- a/wpilibc/src/main/native/cpp/smartdashboard/SendableBase.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/smartdashboard/SendableBase.h"
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-using namespace frc;
-
-SendableBase::SendableBase(bool addLiveWindow) {
- if (addLiveWindow)
- SendableRegistry::GetInstance().AddLW(this, "");
- else
- SendableRegistry::GetInstance().Add(this, "");
-}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp
index 135f4be..48af198 100644
--- a/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp
+++ b/wpilibc/src/main/native/cpp/smartdashboard/SendableBuilderImpl.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/smartdashboard/SendableBuilderImpl.h"
@@ -23,14 +20,20 @@
return m_table;
}
-bool SendableBuilderImpl::HasTable() const { return m_table != nullptr; }
+bool SendableBuilderImpl::IsPublished() const {
+ return m_table != nullptr;
+}
-bool SendableBuilderImpl::IsActuator() const { return m_actuator; }
+bool SendableBuilderImpl::IsActuator() const {
+ return m_actuator;
+}
-void SendableBuilderImpl::UpdateTable() {
+void SendableBuilderImpl::Update() {
uint64_t time = nt::Now();
for (auto& property : m_properties) {
- if (property.update) property.update(property.entry, time);
+ if (property.update) {
+ property.update(property.entry, time);
+ }
}
for (auto& updateTable : m_updateTables) {
updateTable();
@@ -38,28 +41,42 @@
}
void SendableBuilderImpl::StartListeners() {
- for (auto& property : m_properties) property.StartListener();
- if (m_controllableEntry) m_controllableEntry.SetBoolean(true);
+ for (auto& property : m_properties) {
+ property.StartListener();
+ }
+ if (m_controllableEntry) {
+ m_controllableEntry.SetBoolean(true);
+ }
}
void SendableBuilderImpl::StopListeners() {
- for (auto& property : m_properties) property.StopListener();
- if (m_controllableEntry) m_controllableEntry.SetBoolean(false);
+ for (auto& property : m_properties) {
+ property.StopListener();
+ }
+ if (m_controllableEntry) {
+ m_controllableEntry.SetBoolean(false);
+ }
}
void SendableBuilderImpl::StartLiveWindowMode() {
- if (m_safeState) m_safeState();
+ if (m_safeState) {
+ m_safeState();
+ }
StartListeners();
}
void SendableBuilderImpl::StopLiveWindowMode() {
StopListeners();
- if (m_safeState) m_safeState();
+ if (m_safeState) {
+ m_safeState();
+ }
}
-void SendableBuilderImpl::ClearProperties() { m_properties.clear(); }
+void SendableBuilderImpl::ClearProperties() {
+ m_properties.clear();
+}
-void SendableBuilderImpl::SetSmartDashboardType(const wpi::Twine& type) {
+void SendableBuilderImpl::SetSmartDashboardType(std::string_view type) {
m_table->GetEntry(".type").SetString(type);
}
@@ -76,11 +93,11 @@
m_updateTables.emplace_back(std::move(func));
}
-nt::NetworkTableEntry SendableBuilderImpl::GetEntry(const wpi::Twine& key) {
+nt::NetworkTableEntry SendableBuilderImpl::GetEntry(std::string_view key) {
return m_table->GetEntry(key);
}
-void SendableBuilderImpl::AddBooleanProperty(const wpi::Twine& key,
+void SendableBuilderImpl::AddBooleanProperty(std::string_view key,
std::function<bool()> getter,
std::function<void(bool)> setter) {
m_properties.emplace_back(*m_table, key);
@@ -95,7 +112,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsBoolean()) return;
+ if (!event.value->IsBoolean()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetBoolean()); });
},
@@ -105,7 +124,7 @@
}
void SendableBuilderImpl::AddDoubleProperty(
- const wpi::Twine& key, std::function<double()> getter,
+ std::string_view key, std::function<double()> getter,
std::function<void(double)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
@@ -119,7 +138,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsDouble()) return;
+ if (!event.value->IsDouble()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetDouble()); });
},
@@ -129,8 +150,8 @@
}
void SendableBuilderImpl::AddStringProperty(
- const wpi::Twine& key, std::function<std::string()> getter,
- std::function<void(wpi::StringRef)> setter) {
+ std::string_view key, std::function<std::string()> getter,
+ std::function<void(std::string_view)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -143,7 +164,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsString()) return;
+ if (!event.value->IsString()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetString()); });
},
@@ -153,8 +176,8 @@
}
void SendableBuilderImpl::AddBooleanArrayProperty(
- const wpi::Twine& key, std::function<std::vector<int>()> getter,
- std::function<void(wpi::ArrayRef<int>)> setter) {
+ std::string_view key, std::function<std::vector<int>()> getter,
+ std::function<void(wpi::span<const int>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -167,7 +190,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsBooleanArray()) return;
+ if (!event.value->IsBooleanArray()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetBooleanArray()); });
},
@@ -177,8 +202,8 @@
}
void SendableBuilderImpl::AddDoubleArrayProperty(
- const wpi::Twine& key, std::function<std::vector<double>()> getter,
- std::function<void(wpi::ArrayRef<double>)> setter) {
+ std::string_view key, std::function<std::vector<double>()> getter,
+ std::function<void(wpi::span<const double>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -191,7 +216,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsDoubleArray()) return;
+ if (!event.value->IsDoubleArray()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetDoubleArray()); });
},
@@ -201,8 +228,8 @@
}
void SendableBuilderImpl::AddStringArrayProperty(
- const wpi::Twine& key, std::function<std::vector<std::string>()> getter,
- std::function<void(wpi::ArrayRef<std::string>)> setter) {
+ std::string_view key, std::function<std::vector<std::string>()> getter,
+ std::function<void(wpi::span<const std::string>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -215,7 +242,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsStringArray()) return;
+ if (!event.value->IsStringArray()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetStringArray()); });
},
@@ -225,8 +254,8 @@
}
void SendableBuilderImpl::AddRawProperty(
- const wpi::Twine& key, std::function<std::string()> getter,
- std::function<void(wpi::StringRef)> setter) {
+ std::string_view key, std::function<std::string()> getter,
+ std::function<void(std::string_view)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -239,7 +268,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsRaw()) return;
+ if (!event.value->IsRaw()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetRaw()); });
},
@@ -249,7 +280,7 @@
}
void SendableBuilderImpl::AddValueProperty(
- const wpi::Twine& key, std::function<std::shared_ptr<nt::Value>()> getter,
+ std::string_view key, std::function<std::shared_ptr<nt::Value>()> getter,
std::function<void(std::shared_ptr<nt::Value>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
@@ -271,9 +302,9 @@
}
void SendableBuilderImpl::AddSmallStringProperty(
- const wpi::Twine& key,
- std::function<wpi::StringRef(wpi::SmallVectorImpl<char>& buf)> getter,
- std::function<void(wpi::StringRef)> setter) {
+ std::string_view key,
+ std::function<std::string_view(wpi::SmallVectorImpl<char>& buf)> getter,
+ std::function<void(std::string_view)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -287,7 +318,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsString()) return;
+ if (!event.value->IsString()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetString()); });
},
@@ -297,9 +330,9 @@
}
void SendableBuilderImpl::AddSmallBooleanArrayProperty(
- const wpi::Twine& key,
- std::function<wpi::ArrayRef<int>(wpi::SmallVectorImpl<int>& buf)> getter,
- std::function<void(wpi::ArrayRef<int>)> setter) {
+ std::string_view key,
+ std::function<wpi::span<const int>(wpi::SmallVectorImpl<int>& buf)> getter,
+ std::function<void(wpi::span<const int>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -313,7 +346,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsBooleanArray()) return;
+ if (!event.value->IsBooleanArray()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetBooleanArray()); });
},
@@ -323,10 +358,10 @@
}
void SendableBuilderImpl::AddSmallDoubleArrayProperty(
- const wpi::Twine& key,
- std::function<wpi::ArrayRef<double>(wpi::SmallVectorImpl<double>& buf)>
+ std::string_view key,
+ std::function<wpi::span<const double>(wpi::SmallVectorImpl<double>& buf)>
getter,
- std::function<void(wpi::ArrayRef<double>)> setter) {
+ std::function<void(wpi::span<const double>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -340,7 +375,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsDoubleArray()) return;
+ if (!event.value->IsDoubleArray()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetDoubleArray()); });
},
@@ -350,11 +387,11 @@
}
void SendableBuilderImpl::AddSmallStringArrayProperty(
- const wpi::Twine& key,
+ std::string_view key,
std::function<
- wpi::ArrayRef<std::string>(wpi::SmallVectorImpl<std::string>& buf)>
+ wpi::span<const std::string>(wpi::SmallVectorImpl<std::string>& buf)>
getter,
- std::function<void(wpi::ArrayRef<std::string>)> setter) {
+ std::function<void(wpi::span<const std::string>)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -368,7 +405,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsStringArray()) return;
+ if (!event.value->IsStringArray()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetStringArray()); });
},
@@ -378,9 +417,9 @@
}
void SendableBuilderImpl::AddSmallRawProperty(
- const wpi::Twine& key,
- std::function<wpi::StringRef(wpi::SmallVectorImpl<char>& buf)> getter,
- std::function<void(wpi::StringRef)> setter) {
+ std::string_view key,
+ std::function<std::string_view(wpi::SmallVectorImpl<char>& buf)> getter,
+ std::function<void(std::string_view)> setter) {
m_properties.emplace_back(*m_table, key);
if (getter) {
m_properties.back().update = [=](nt::NetworkTableEntry entry,
@@ -394,7 +433,9 @@
[=](nt::NetworkTableEntry entry) -> NT_EntryListener {
return entry.AddListener(
[=](const nt::EntryNotification& event) {
- if (!event.value->IsRaw()) return;
+ if (!event.value->IsRaw()) {
+ return;
+ }
SmartDashboard::PostListenerTask(
[=] { setter(event.value->GetRaw()); });
},
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableChooserBase.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableChooserBase.cpp
index 2f7af9c..550d40c 100644
--- a/wpilibc/src/main/native/cpp/smartdashboard/SendableChooserBase.cpp
+++ b/wpilibc/src/main/native/cpp/smartdashboard/SendableChooserBase.cpp
@@ -1,20 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/smartdashboard/SendableChooserBase.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <wpi/sendable/SendableRegistry.h>
using namespace frc;
std::atomic_int SendableChooserBase::s_instances{0};
SendableChooserBase::SendableChooserBase() : m_instance{s_instances++} {
- SendableRegistry::GetInstance().Add(this, "SendableChooser", m_instance);
+ wpi::SendableRegistry::Add(this, "SendableChooser", m_instance);
}
SendableChooserBase::SendableChooserBase(SendableChooserBase&& oth)
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp
deleted file mode 100644
index 4480313..0000000
--- a/wpilibc/src/main/native/cpp/smartdashboard/SendableRegistry.cpp
+++ /dev/null
@@ -1,372 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-#include <memory>
-
-#include <wpi/DenseMap.h>
-#include <wpi/SmallVector.h>
-#include <wpi/UidVector.h>
-#include <wpi/mutex.h>
-
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableBuilderImpl.h"
-
-using namespace frc;
-
-struct SendableRegistry::Impl {
- struct Component {
- Sendable* sendable = nullptr;
- SendableBuilderImpl builder;
- std::string name;
- std::string subsystem = "Ungrouped";
- Sendable* parent = nullptr;
- bool liveWindow = false;
- wpi::SmallVector<std::shared_ptr<void>, 2> data;
-
- void SetName(const wpi::Twine& moduleType, int channel) {
- name =
- (moduleType + wpi::Twine('[') + wpi::Twine(channel) + wpi::Twine(']'))
- .str();
- }
-
- void SetName(const wpi::Twine& moduleType, int moduleNumber, int channel) {
- name = (moduleType + wpi::Twine('[') + wpi::Twine(moduleNumber) +
- wpi::Twine(',') + wpi::Twine(channel) + wpi::Twine(']'))
- .str();
- }
- };
-
- wpi::recursive_mutex mutex;
-
- wpi::UidVector<std::unique_ptr<Component>, 32> components;
- wpi::DenseMap<void*, UID> componentMap;
- int nextDataHandle = 0;
-
- Component& GetOrAdd(void* sendable, UID* uid = nullptr);
-};
-
-SendableRegistry::Impl::Component& SendableRegistry::Impl::GetOrAdd(
- void* sendable, UID* uid) {
- UID& compUid = componentMap[sendable];
- if (compUid == 0)
- compUid = components.emplace_back(std::make_unique<Component>()) + 1;
- if (uid) *uid = compUid;
-
- return *components[compUid - 1];
-}
-
-SendableRegistry& SendableRegistry::GetInstance() {
- static SendableRegistry instance;
- return instance;
-}
-
-void SendableRegistry::Add(Sendable* sendable, const wpi::Twine& name) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.name = name.str();
-}
-
-void SendableRegistry::Add(Sendable* sendable, const wpi::Twine& moduleType,
- int channel) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.SetName(moduleType, channel);
-}
-
-void SendableRegistry::Add(Sendable* sendable, const wpi::Twine& moduleType,
- int moduleNumber, int channel) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.SetName(moduleType, moduleNumber, channel);
-}
-
-void SendableRegistry::Add(Sendable* sendable, const wpi::Twine& subsystem,
- const wpi::Twine& name) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.name = name.str();
- comp.subsystem = subsystem.str();
-}
-
-void SendableRegistry::AddLW(Sendable* sendable, const wpi::Twine& name) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.liveWindow = true;
- comp.name = name.str();
-}
-
-void SendableRegistry::AddLW(Sendable* sendable, const wpi::Twine& moduleType,
- int channel) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.liveWindow = true;
- comp.SetName(moduleType, channel);
-}
-
-void SendableRegistry::AddLW(Sendable* sendable, const wpi::Twine& moduleType,
- int moduleNumber, int channel) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.liveWindow = true;
- comp.SetName(moduleType, moduleNumber, channel);
-}
-
-void SendableRegistry::AddLW(Sendable* sendable, const wpi::Twine& subsystem,
- const wpi::Twine& name) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(sendable);
- comp.sendable = sendable;
- comp.liveWindow = true;
- comp.name = name.str();
- comp.subsystem = subsystem.str();
-}
-
-void SendableRegistry::AddChild(Sendable* parent, Sendable* child) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(child);
- comp.parent = parent;
-}
-
-void SendableRegistry::AddChild(Sendable* parent, void* child) {
- std::scoped_lock lock(m_impl->mutex);
- auto& comp = m_impl->GetOrAdd(child);
- comp.parent = parent;
-}
-
-bool SendableRegistry::Remove(Sendable* sendable) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end()) return false;
- UID compUid = it->getSecond();
- m_impl->components.erase(compUid - 1);
- m_impl->componentMap.erase(it);
- // update any parent pointers
- for (auto&& comp : m_impl->components) {
- if (comp->parent == sendable) comp->parent = nullptr;
- }
- return true;
-}
-
-void SendableRegistry::Move(Sendable* to, Sendable* from) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(from);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- UID compUid = it->getSecond();
- m_impl->componentMap.erase(it);
- m_impl->componentMap[to] = compUid;
- auto& comp = *m_impl->components[compUid - 1];
- comp.sendable = to;
- if (comp.builder.HasTable()) {
- // rebuild builder, as lambda captures can point to "from"
- comp.builder.ClearProperties();
- to->InitSendable(comp.builder);
- }
- // update any parent pointers
- for (auto&& comp : m_impl->components) {
- if (comp->parent == from) comp->parent = to;
- }
-}
-
-bool SendableRegistry::Contains(const Sendable* sendable) const {
- std::scoped_lock lock(m_impl->mutex);
- return m_impl->componentMap.count(sendable) != 0;
-}
-
-std::string SendableRegistry::GetName(const Sendable* sendable) const {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return std::string{};
- return m_impl->components[it->getSecond() - 1]->name;
-}
-
-void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& name) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- m_impl->components[it->getSecond() - 1]->name = name.str();
-}
-
-void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& moduleType,
- int channel) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- m_impl->components[it->getSecond() - 1]->SetName(moduleType, channel);
-}
-
-void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& moduleType,
- int moduleNumber, int channel) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- m_impl->components[it->getSecond() - 1]->SetName(moduleType, moduleNumber,
- channel);
-}
-
-void SendableRegistry::SetName(Sendable* sendable, const wpi::Twine& subsystem,
- const wpi::Twine& name) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- auto& comp = *m_impl->components[it->getSecond() - 1];
- comp.name = name.str();
- comp.subsystem = subsystem.str();
-}
-
-std::string SendableRegistry::GetSubsystem(const Sendable* sendable) const {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return std::string{};
- return m_impl->components[it->getSecond() - 1]->subsystem;
-}
-
-void SendableRegistry::SetSubsystem(Sendable* sendable,
- const wpi::Twine& subsystem) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- m_impl->components[it->getSecond() - 1]->subsystem = subsystem.str();
-}
-
-int SendableRegistry::GetDataHandle() {
- std::scoped_lock lock(m_impl->mutex);
- return m_impl->nextDataHandle++;
-}
-
-std::shared_ptr<void> SendableRegistry::SetData(Sendable* sendable, int handle,
- std::shared_ptr<void> data) {
- assert(handle >= 0);
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return nullptr;
- auto& comp = *m_impl->components[it->getSecond() - 1];
- std::shared_ptr<void> rv;
- if (static_cast<size_t>(handle) < comp.data.size())
- rv = std::move(comp.data[handle]);
- else
- comp.data.resize(handle + 1);
- comp.data[handle] = std::move(data);
- return rv;
-}
-
-std::shared_ptr<void> SendableRegistry::GetData(Sendable* sendable,
- int handle) {
- assert(handle >= 0);
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return nullptr;
- auto& comp = *m_impl->components[it->getSecond() - 1];
- if (static_cast<size_t>(handle) >= comp.data.size()) return nullptr;
- return comp.data[handle];
-}
-
-void SendableRegistry::EnableLiveWindow(Sendable* sendable) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- m_impl->components[it->getSecond() - 1]->liveWindow = true;
-}
-
-void SendableRegistry::DisableLiveWindow(Sendable* sendable) {
- std::scoped_lock lock(m_impl->mutex);
- auto it = m_impl->componentMap.find(sendable);
- if (it == m_impl->componentMap.end() ||
- !m_impl->components[it->getSecond() - 1])
- return;
- m_impl->components[it->getSecond() - 1]->liveWindow = false;
-}
-
-SendableRegistry::UID SendableRegistry::GetUniqueId(Sendable* sendable) {
- std::scoped_lock lock(m_impl->mutex);
- UID uid;
- auto& comp = m_impl->GetOrAdd(sendable, &uid);
- comp.sendable = sendable;
- return uid;
-}
-
-Sendable* SendableRegistry::GetSendable(UID uid) {
- if (uid == 0) return nullptr;
- std::scoped_lock lock(m_impl->mutex);
- if ((uid - 1) >= m_impl->components.size() || !m_impl->components[uid - 1])
- return nullptr;
- return m_impl->components[uid - 1]->sendable;
-}
-
-void SendableRegistry::Publish(UID sendableUid,
- std::shared_ptr<NetworkTable> table) {
- std::scoped_lock lock(m_impl->mutex);
- if (sendableUid == 0 || (sendableUid - 1) >= m_impl->components.size() ||
- !m_impl->components[sendableUid - 1])
- return;
- auto& comp = *m_impl->components[sendableUid - 1];
- comp.builder = SendableBuilderImpl{}; // clear any current builder
- comp.builder.SetTable(table);
- comp.sendable->InitSendable(comp.builder);
- comp.builder.UpdateTable();
- comp.builder.StartListeners();
-}
-
-void SendableRegistry::Update(UID sendableUid) {
- if (sendableUid == 0) return;
- std::scoped_lock lock(m_impl->mutex);
- if ((sendableUid - 1) >= m_impl->components.size() ||
- !m_impl->components[sendableUid - 1])
- return;
- m_impl->components[sendableUid - 1]->builder.UpdateTable();
-}
-
-void SendableRegistry::ForeachLiveWindow(
- int dataHandle,
- wpi::function_ref<void(CallbackData& data)> callback) const {
- assert(dataHandle >= 0);
- std::scoped_lock lock(m_impl->mutex);
- wpi::SmallVector<Impl::Component*, 128> components;
- for (auto&& comp : m_impl->components) components.emplace_back(comp.get());
- for (auto comp : components) {
- if (comp && comp->sendable && comp->liveWindow) {
- if (static_cast<size_t>(dataHandle) >= comp->data.size())
- comp->data.resize(dataHandle + 1);
- CallbackData cbdata{comp->sendable, comp->name,
- comp->subsystem, comp->parent,
- comp->data[dataHandle], comp->builder};
- callback(cbdata);
- }
- }
-}
-
-SendableRegistry::SendableRegistry() : m_impl(new Impl) {}
diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp
index 5e70a4c..25bb61f 100644
--- a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp
+++ b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/smartdashboard/SmartDashboard.h"
@@ -12,252 +9,239 @@
#include <networktables/NetworkTableInstance.h>
#include <wpi/StringMap.h>
#include <wpi/mutex.h>
+#include <wpi/sendable/SendableRegistry.h>
-#include "frc/WPIErrors.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include "frc/Errors.h"
+#include "frc/smartdashboard/ListenerExecutor.h"
+#include "frc/smartdashboard/SendableBuilderImpl.h"
using namespace frc;
namespace {
-class Singleton {
- public:
- static Singleton& GetInstance();
-
- std::shared_ptr<nt::NetworkTable> table;
- wpi::StringMap<SendableRegistry::UID> tablesToData;
+struct Instance {
+ detail::ListenerExecutor listenerExecutor;
+ std::shared_ptr<nt::NetworkTable> table =
+ nt::NetworkTableInstance::GetDefault().GetTable("SmartDashboard");
+ wpi::StringMap<wpi::SendableRegistry::UID> tablesToData;
wpi::mutex tablesToDataMutex;
-
- private:
- Singleton() {
- table = nt::NetworkTableInstance::GetDefault().GetTable("SmartDashboard");
- HAL_Report(HALUsageReporting::kResourceType_SmartDashboard, 0);
- }
- Singleton(const Singleton&) = delete;
- Singleton& operator=(const Singleton&) = delete;
};
-
} // namespace
-Singleton& Singleton::GetInstance() {
- static Singleton instance;
+static Instance& GetInstance() {
+ HAL_Report(HALUsageReporting::kResourceType_SmartDashboard, 0);
+ static Instance instance;
return instance;
}
-void SmartDashboard::init() { Singleton::GetInstance(); }
+void SmartDashboard::init() {
+ GetInstance();
+}
-bool SmartDashboard::ContainsKey(wpi::StringRef key) {
- return Singleton::GetInstance().table->ContainsKey(key);
+bool SmartDashboard::ContainsKey(std::string_view key) {
+ return GetInstance().table->ContainsKey(key);
}
std::vector<std::string> SmartDashboard::GetKeys(int types) {
- return Singleton::GetInstance().table->GetKeys(types);
+ return GetInstance().table->GetKeys(types);
}
-void SmartDashboard::SetPersistent(wpi::StringRef key) {
- Singleton::GetInstance().table->GetEntry(key).SetPersistent();
+void SmartDashboard::SetPersistent(std::string_view key) {
+ GetInstance().table->GetEntry(key).SetPersistent();
}
-void SmartDashboard::ClearPersistent(wpi::StringRef key) {
- Singleton::GetInstance().table->GetEntry(key).ClearPersistent();
+void SmartDashboard::ClearPersistent(std::string_view key) {
+ GetInstance().table->GetEntry(key).ClearPersistent();
}
-bool SmartDashboard::IsPersistent(wpi::StringRef key) {
- return Singleton::GetInstance().table->GetEntry(key).IsPersistent();
+bool SmartDashboard::IsPersistent(std::string_view key) {
+ return GetInstance().table->GetEntry(key).IsPersistent();
}
-void SmartDashboard::SetFlags(wpi::StringRef key, unsigned int flags) {
- Singleton::GetInstance().table->GetEntry(key).SetFlags(flags);
+void SmartDashboard::SetFlags(std::string_view key, unsigned int flags) {
+ GetInstance().table->GetEntry(key).SetFlags(flags);
}
-void SmartDashboard::ClearFlags(wpi::StringRef key, unsigned int flags) {
- Singleton::GetInstance().table->GetEntry(key).ClearFlags(flags);
+void SmartDashboard::ClearFlags(std::string_view key, unsigned int flags) {
+ GetInstance().table->GetEntry(key).ClearFlags(flags);
}
-unsigned int SmartDashboard::GetFlags(wpi::StringRef key) {
- return Singleton::GetInstance().table->GetEntry(key).GetFlags();
+unsigned int SmartDashboard::GetFlags(std::string_view key) {
+ return GetInstance().table->GetEntry(key).GetFlags();
}
-void SmartDashboard::Delete(wpi::StringRef key) {
- Singleton::GetInstance().table->Delete(key);
+void SmartDashboard::Delete(std::string_view key) {
+ GetInstance().table->Delete(key);
}
-nt::NetworkTableEntry SmartDashboard::GetEntry(wpi::StringRef key) {
- return Singleton::GetInstance().table->GetEntry(key);
+nt::NetworkTableEntry SmartDashboard::GetEntry(std::string_view key) {
+ return GetInstance().table->GetEntry(key);
}
-void SmartDashboard::PutData(wpi::StringRef key, Sendable* data) {
- if (data == nullptr) {
- wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
- return;
+void SmartDashboard::PutData(std::string_view key, wpi::Sendable* data) {
+ if (!data) {
+ throw FRC_MakeError(err::NullParameter, "{}", "value");
}
- auto& inst = Singleton::GetInstance();
+ auto& inst = GetInstance();
std::scoped_lock lock(inst.tablesToDataMutex);
auto& uid = inst.tablesToData[key];
- auto& registry = SendableRegistry::GetInstance();
- Sendable* sddata = registry.GetSendable(uid);
+ wpi::Sendable* sddata = wpi::SendableRegistry::GetSendable(uid);
if (sddata != data) {
- uid = registry.GetUniqueId(data);
+ uid = wpi::SendableRegistry::GetUniqueId(data);
auto dataTable = inst.table->GetSubTable(key);
- registry.Publish(uid, dataTable);
+ auto builder = std::make_unique<SendableBuilderImpl>();
+ auto builderPtr = builder.get();
+ builderPtr->SetTable(dataTable);
+ wpi::SendableRegistry::Publish(uid, std::move(builder));
+ builderPtr->StartListeners();
dataTable->GetEntry(".name").SetString(key);
}
}
-void SmartDashboard::PutData(Sendable* value) {
- if (value == nullptr) {
- wpi_setGlobalWPIErrorWithContext(NullParameter, "value");
- return;
+void SmartDashboard::PutData(wpi::Sendable* value) {
+ if (!value) {
+ throw FRC_MakeError(err::NullParameter, "{}", "value");
}
- auto name = SendableRegistry::GetInstance().GetName(value);
- if (!name.empty()) PutData(name, value);
+ auto name = wpi::SendableRegistry::GetName(value);
+ if (!name.empty()) {
+ PutData(name, value);
+ }
}
-Sendable* SmartDashboard::GetData(wpi::StringRef key) {
- auto& inst = Singleton::GetInstance();
+wpi::Sendable* SmartDashboard::GetData(std::string_view key) {
+ auto& inst = GetInstance();
std::scoped_lock lock(inst.tablesToDataMutex);
auto it = inst.tablesToData.find(key);
if (it == inst.tablesToData.end()) {
- wpi_setGlobalWPIErrorWithContext(SmartDashboardMissingKey, key);
- return nullptr;
+ throw FRC_MakeError(err::SmartDashboardMissingKey, "{}", key);
}
- return SendableRegistry::GetInstance().GetSendable(it->getValue());
+ return wpi::SendableRegistry::GetSendable(it->getValue());
}
-bool SmartDashboard::PutBoolean(wpi::StringRef keyName, bool value) {
- return Singleton::GetInstance().table->GetEntry(keyName).SetBoolean(value);
+bool SmartDashboard::PutBoolean(std::string_view keyName, bool value) {
+ return GetInstance().table->GetEntry(keyName).SetBoolean(value);
}
-bool SmartDashboard::SetDefaultBoolean(wpi::StringRef key, bool defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultBoolean(
- defaultValue);
+bool SmartDashboard::SetDefaultBoolean(std::string_view key,
+ bool defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultBoolean(defaultValue);
}
-bool SmartDashboard::GetBoolean(wpi::StringRef keyName, bool defaultValue) {
- return Singleton::GetInstance().table->GetEntry(keyName).GetBoolean(
- defaultValue);
+bool SmartDashboard::GetBoolean(std::string_view keyName, bool defaultValue) {
+ return GetInstance().table->GetEntry(keyName).GetBoolean(defaultValue);
}
-bool SmartDashboard::PutNumber(wpi::StringRef keyName, double value) {
- return Singleton::GetInstance().table->GetEntry(keyName).SetDouble(value);
+bool SmartDashboard::PutNumber(std::string_view keyName, double value) {
+ return GetInstance().table->GetEntry(keyName).SetDouble(value);
}
-bool SmartDashboard::SetDefaultNumber(wpi::StringRef key, double defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultDouble(
- defaultValue);
+bool SmartDashboard::SetDefaultNumber(std::string_view key,
+ double defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultDouble(defaultValue);
}
-double SmartDashboard::GetNumber(wpi::StringRef keyName, double defaultValue) {
- return Singleton::GetInstance().table->GetEntry(keyName).GetDouble(
- defaultValue);
+double SmartDashboard::GetNumber(std::string_view keyName,
+ double defaultValue) {
+ return GetInstance().table->GetEntry(keyName).GetDouble(defaultValue);
}
-bool SmartDashboard::PutString(wpi::StringRef keyName, wpi::StringRef value) {
- return Singleton::GetInstance().table->GetEntry(keyName).SetString(value);
+bool SmartDashboard::PutString(std::string_view keyName,
+ std::string_view value) {
+ return GetInstance().table->GetEntry(keyName).SetString(value);
}
-bool SmartDashboard::SetDefaultString(wpi::StringRef key,
- wpi::StringRef defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultString(
- defaultValue);
+bool SmartDashboard::SetDefaultString(std::string_view key,
+ std::string_view defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultString(defaultValue);
}
-std::string SmartDashboard::GetString(wpi::StringRef keyName,
- wpi::StringRef defaultValue) {
- return Singleton::GetInstance().table->GetEntry(keyName).GetString(
- defaultValue);
+std::string SmartDashboard::GetString(std::string_view keyName,
+ std::string_view defaultValue) {
+ return GetInstance().table->GetEntry(keyName).GetString(defaultValue);
}
-bool SmartDashboard::PutBooleanArray(wpi::StringRef key,
- wpi::ArrayRef<int> value) {
- return Singleton::GetInstance().table->GetEntry(key).SetBooleanArray(value);
+bool SmartDashboard::PutBooleanArray(std::string_view key,
+ wpi::span<const int> value) {
+ return GetInstance().table->GetEntry(key).SetBooleanArray(value);
}
-bool SmartDashboard::SetDefaultBooleanArray(wpi::StringRef key,
- wpi::ArrayRef<int> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultBooleanArray(
+bool SmartDashboard::SetDefaultBooleanArray(std::string_view key,
+ wpi::span<const int> defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultBooleanArray(
defaultValue);
}
std::vector<int> SmartDashboard::GetBooleanArray(
- wpi::StringRef key, wpi::ArrayRef<int> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).GetBooleanArray(
- defaultValue);
+ std::string_view key, wpi::span<const int> defaultValue) {
+ return GetInstance().table->GetEntry(key).GetBooleanArray(defaultValue);
}
-bool SmartDashboard::PutNumberArray(wpi::StringRef key,
- wpi::ArrayRef<double> value) {
- return Singleton::GetInstance().table->GetEntry(key).SetDoubleArray(value);
+bool SmartDashboard::PutNumberArray(std::string_view key,
+ wpi::span<const double> value) {
+ return GetInstance().table->GetEntry(key).SetDoubleArray(value);
}
-bool SmartDashboard::SetDefaultNumberArray(wpi::StringRef key,
- wpi::ArrayRef<double> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultDoubleArray(
- defaultValue);
+bool SmartDashboard::SetDefaultNumberArray(
+ std::string_view key, wpi::span<const double> defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultDoubleArray(defaultValue);
}
std::vector<double> SmartDashboard::GetNumberArray(
- wpi::StringRef key, wpi::ArrayRef<double> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).GetDoubleArray(
- defaultValue);
+ std::string_view key, wpi::span<const double> defaultValue) {
+ return GetInstance().table->GetEntry(key).GetDoubleArray(defaultValue);
}
-bool SmartDashboard::PutStringArray(wpi::StringRef key,
- wpi::ArrayRef<std::string> value) {
- return Singleton::GetInstance().table->GetEntry(key).SetStringArray(value);
+bool SmartDashboard::PutStringArray(std::string_view key,
+ wpi::span<const std::string> value) {
+ return GetInstance().table->GetEntry(key).SetStringArray(value);
}
bool SmartDashboard::SetDefaultStringArray(
- wpi::StringRef key, wpi::ArrayRef<std::string> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultStringArray(
- defaultValue);
+ std::string_view key, wpi::span<const std::string> defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultStringArray(defaultValue);
}
std::vector<std::string> SmartDashboard::GetStringArray(
- wpi::StringRef key, wpi::ArrayRef<std::string> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).GetStringArray(
- defaultValue);
+ std::string_view key, wpi::span<const std::string> defaultValue) {
+ return GetInstance().table->GetEntry(key).GetStringArray(defaultValue);
}
-bool SmartDashboard::PutRaw(wpi::StringRef key, wpi::StringRef value) {
- return Singleton::GetInstance().table->GetEntry(key).SetRaw(value);
+bool SmartDashboard::PutRaw(std::string_view key, std::string_view value) {
+ return GetInstance().table->GetEntry(key).SetRaw(value);
}
-bool SmartDashboard::SetDefaultRaw(wpi::StringRef key,
- wpi::StringRef defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultRaw(
- defaultValue);
+bool SmartDashboard::SetDefaultRaw(std::string_view key,
+ std::string_view defaultValue) {
+ return GetInstance().table->GetEntry(key).SetDefaultRaw(defaultValue);
}
-std::string SmartDashboard::GetRaw(wpi::StringRef key,
- wpi::StringRef defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).GetRaw(defaultValue);
+std::string SmartDashboard::GetRaw(std::string_view key,
+ std::string_view defaultValue) {
+ return GetInstance().table->GetEntry(key).GetRaw(defaultValue);
}
-bool SmartDashboard::PutValue(wpi::StringRef keyName,
+bool SmartDashboard::PutValue(std::string_view keyName,
std::shared_ptr<nt::Value> value) {
- return Singleton::GetInstance().table->GetEntry(keyName).SetValue(value);
+ return GetInstance().table->GetEntry(keyName).SetValue(value);
}
-bool SmartDashboard::SetDefaultValue(wpi::StringRef key,
+bool SmartDashboard::SetDefaultValue(std::string_view key,
std::shared_ptr<nt::Value> defaultValue) {
- return Singleton::GetInstance().table->GetEntry(key).SetDefaultValue(
- defaultValue);
+ return GetInstance().table->GetEntry(key).SetDefaultValue(defaultValue);
}
-std::shared_ptr<nt::Value> SmartDashboard::GetValue(wpi::StringRef keyName) {
- return Singleton::GetInstance().table->GetEntry(keyName).GetValue();
+std::shared_ptr<nt::Value> SmartDashboard::GetValue(std::string_view keyName) {
+ return GetInstance().table->GetEntry(keyName).GetValue();
}
-detail::ListenerExecutor SmartDashboard::listenerExecutor;
-
void SmartDashboard::PostListenerTask(std::function<void()> task) {
- listenerExecutor.Execute(task);
+ GetInstance().listenerExecutor.Execute(task);
}
void SmartDashboard::UpdateValues() {
- auto& registry = SendableRegistry::GetInstance();
- auto& inst = Singleton::GetInstance();
+ auto& inst = GetInstance();
+ inst.listenerExecutor.RunListenerTasks();
std::scoped_lock lock(inst.tablesToDataMutex);
- for (auto& i : inst.tablesToData) registry.Update(i.getValue());
- listenerExecutor.RunListenerTasks();
+ for (auto& i : inst.tablesToData) {
+ wpi::SendableRegistry::Update(i.getValue());
+ }
}
diff --git a/wpilibc/src/main/native/cppcs/RobotBase.cpp b/wpilibc/src/main/native/cppcs/RobotBase.cpp
index 5f34e77..78c286c 100644
--- a/wpilibc/src/main/native/cppcs/RobotBase.cpp
+++ b/wpilibc/src/main/native/cppcs/RobotBase.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/RobotBase.h"
@@ -14,6 +11,7 @@
#include <cstdio>
#include <cameraserver/CameraServerShared.h>
+#include <fmt/format.h>
#include <hal/FRCUsageReporting.h>
#include <hal/HALBase.h>
#include <networktables/NetworkTableInstance.h>
@@ -21,24 +19,37 @@
#include "WPILibVersion.h"
#include "frc/DriverStation.h"
+#include "frc/Errors.h"
+#include "frc/Notifier.h"
#include "frc/RobotState.h"
-#include "frc/Utility.h"
-#include "frc/WPIErrors.h"
#include "frc/livewindow/LiveWindow.h"
#include "frc/smartdashboard/SmartDashboard.h"
-typedef void (*SetCameraServerSharedFP)(frc::CameraServerShared* shared);
+static_assert(frc::RuntimeType::kRoboRIO ==
+ static_cast<frc::RuntimeType>(HAL_Runtime_RoboRIO));
+static_assert(frc::RuntimeType::kRoboRIO2 ==
+ static_cast<frc::RuntimeType>(HAL_Runtime_RoboRIO2));
+static_assert(frc::RuntimeType::kSimulation ==
+ static_cast<frc::RuntimeType>(HAL_Runtime_Simulation));
+
+using SetCameraServerSharedFP = void (*)(frc::CameraServerShared*);
using namespace frc;
int frc::RunHALInitialization() {
if (!HAL_Initialize(500, 0)) {
- wpi::errs() << "FATAL ERROR: HAL could not be initialized\n";
+ std::puts("FATAL ERROR: HAL could not be initialized");
return -1;
}
HAL_Report(HALUsageReporting::kResourceType_Language,
HALUsageReporting::kLanguage_CPlusPlus, 0, GetWPILibVersion());
- wpi::outs() << "\n********** Robot program starting **********\n";
+
+ if (!frc::Notifier::SetHALThreadPriority(true, 40)) {
+ FRC_ReportError(warn::Warning, "{}",
+ "Setting HAL Notifier RT priority to 40 failed\n");
+ }
+
+ std::puts("\n********** Robot program starting **********");
return 0;
}
@@ -56,14 +67,18 @@
void ReportVideoServer(int id) override {
HAL_Report(HALUsageReporting::kResourceType_PCVideoServer, id);
}
- void SetCameraServerError(const wpi::Twine& error) override {
- wpi_setGlobalWPIErrorWithContext(CameraServerError, error);
+ void SetCameraServerErrorV(fmt::string_view format,
+ fmt::format_args args) override {
+ ReportErrorV(err::CameraServerError, __FILE__, __LINE__, __FUNCTION__,
+ format, args);
}
- void SetVisionRunnerError(const wpi::Twine& error) override {
- wpi_setGlobalErrorWithContext(-1, error);
+ void SetVisionRunnerErrorV(fmt::string_view format,
+ fmt::format_args args) override {
+ ReportErrorV(err::Error, __FILE__, __LINE__, __FUNCTION__, format, args);
}
- void ReportDriverStationError(const wpi::Twine& error) override {
- DriverStation::ReportError(error);
+ void ReportDriverStationErrorV(fmt::string_view format,
+ fmt::format_args args) override {
+ ReportErrorV(err::Error, __FILE__, __LINE__, __FUNCTION__, format, args);
}
std::pair<std::thread::id, bool> GetRobotMainThreadId() const override {
return std::make_pair(RobotBase::GetThreadId(), true);
@@ -71,8 +86,14 @@
};
class WPILibMathShared : public wpi::math::MathShared {
public:
- void ReportError(const wpi::Twine& error) override {
- DriverStation::ReportError(error);
+ void ReportErrorV(fmt::string_view format, fmt::format_args args) override {
+ frc::ReportErrorV(err::Error, __FILE__, __LINE__, __FUNCTION__, format,
+ args);
+ }
+
+ void ReportWarningV(fmt::string_view format, fmt::format_args args) override {
+ frc::ReportErrorV(warn::Warning, __FILE__, __LINE__, __FUNCTION__, format,
+ args);
}
void ReportUsage(wpi::math::MathUsageId id, int count) override {
@@ -107,6 +128,13 @@
HAL_Report(HALUsageReporting::kResourceType_Odometry,
HALUsageReporting::kOdometry_MecanumDrive);
break;
+ case wpi::math::MathUsageId::kController_PIDController2:
+ HAL_Report(HALUsageReporting::kResourceType_PIDController2, count);
+ break;
+ case wpi::math::MathUsageId::kController_ProfiledPIDController:
+ HAL_Report(HALUsageReporting::kResourceType_ProfiledPIDController,
+ count);
+ break;
}
}
};
@@ -122,8 +150,8 @@
#endif
if (!cameraServerLib) {
- wpi::outs() << "Camera Server Library Not Found\n";
- wpi::outs().flush();
+ std::puts("Camera Server Library Not Found");
+ std::fflush(stdout);
return;
}
auto symbol = dlsym(cameraServerLib, "CameraServer_SetCameraServerShared");
@@ -131,15 +159,15 @@
auto setCameraServerShared = (SetCameraServerSharedFP)symbol;
setCameraServerShared(new WPILibCameraServerShared{});
} else {
- wpi::outs() << "Camera Server Shared Symbol Missing\n";
- wpi::outs().flush();
+ std::puts("Camera Server Shared Symbol Missing");
+ std::fflush(stdout);
}
#else
CameraServer_SetCameraServerShared(new WPILibCameraServerShared{});
#endif
#else
- wpi::outs() << "Not loading CameraServerShared\n";
- wpi::outs().flush();
+ std::puts("Not loading CameraServerShared");
+ std::fflush(stdout);
#endif
}
@@ -148,29 +176,55 @@
std::make_unique<WPILibMathShared>());
}
-bool RobotBase::IsEnabled() const { return m_ds.IsEnabled(); }
+bool RobotBase::IsEnabled() const {
+ return DriverStation::IsEnabled();
+}
-bool RobotBase::IsDisabled() const { return m_ds.IsDisabled(); }
+bool RobotBase::IsDisabled() const {
+ return DriverStation::IsDisabled();
+}
-bool RobotBase::IsAutonomous() const { return m_ds.IsAutonomous(); }
+bool RobotBase::IsAutonomous() const {
+ return DriverStation::IsAutonomous();
+}
bool RobotBase::IsAutonomousEnabled() const {
- return m_ds.IsAutonomousEnabled();
+ return DriverStation::IsAutonomousEnabled();
}
-bool RobotBase::IsOperatorControl() const { return m_ds.IsOperatorControl(); }
+bool RobotBase::IsOperatorControl() const {
+ return DriverStation::IsTeleop();
+}
+
+bool RobotBase::IsTeleop() const {
+ return DriverStation::IsTeleop();
+}
bool RobotBase::IsOperatorControlEnabled() const {
- return m_ds.IsOperatorControlEnabled();
+ return DriverStation::IsTeleopEnabled();
}
-bool RobotBase::IsTest() const { return m_ds.IsTest(); }
+bool RobotBase::IsTeleopEnabled() const {
+ return DriverStation::IsTeleopEnabled();
+}
-bool RobotBase::IsNewDataAvailable() const { return m_ds.IsNewControlData(); }
+bool RobotBase::IsTest() const {
+ return DriverStation::IsTest();
+}
-std::thread::id RobotBase::GetThreadId() { return m_threadId; }
+bool RobotBase::IsNewDataAvailable() const {
+ return DriverStation::IsNewControlData();
+}
-RobotBase::RobotBase() : m_ds(DriverStation::GetInstance()) {
+std::thread::id RobotBase::GetThreadId() {
+ return m_threadId;
+}
+
+RuntimeType RobotBase::GetRuntimeType() {
+ return static_cast<RuntimeType>(HAL_GetRuntimeType());
+}
+
+RobotBase::RobotBase() {
m_threadId = std::this_thread::get_id();
SetupCameraServerShared();
@@ -203,12 +257,5 @@
->GetEntry("LW Enabled")
.SetBoolean(false);
- LiveWindow::GetInstance()->SetEnabled(false);
+ LiveWindow::SetEnabled(false);
}
-
-RobotBase::RobotBase(RobotBase&&) noexcept
- : m_ds(DriverStation::GetInstance()) {}
-
-RobotBase::~RobotBase() {}
-
-RobotBase& RobotBase::operator=(RobotBase&&) noexcept { return *this; }
diff --git a/wpilibc/src/main/native/include/WPILibVersion.h b/wpilibc/src/main/native/include/WPILibVersion.h
index 8aab880..c11bef9 100644
--- a/wpilibc/src/main/native/include/WPILibVersion.h
+++ b/wpilibc/src/main/native/include/WPILibVersion.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/ADXL345_I2C.h b/wpilibc/src/main/native/include/frc/ADXL345_I2C.h
index 202acbb..c997327 100644
--- a/wpilibc/src/main/native/include/frc/ADXL345_I2C.h
+++ b/wpilibc/src/main/native/include/frc/ADXL345_I2C.h
@@ -1,24 +1,18 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/SimDevice.h>
+#include <networktables/NTSendable.h>
+#include <wpi/sendable/SendableHelper.h>
-#include "frc/ErrorBase.h"
#include "frc/I2C.h"
#include "frc/interfaces/Accelerometer.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* ADXL345 Accelerometer on I2C.
*
@@ -26,10 +20,9 @@
* an I2C bus. This class assumes the default (not alternate) sensor address of
* 0x1D (7-bit address).
*/
-class ADXL345_I2C : public ErrorBase,
- public Accelerometer,
- public Sendable,
- public SendableHelper<ADXL345_I2C> {
+class ADXL345_I2C : public Accelerometer,
+ public nt::NTSendable,
+ public wpi::SendableHelper<ADXL345_I2C> {
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
@@ -53,8 +46,11 @@
ADXL345_I2C(ADXL345_I2C&&) = default;
ADXL345_I2C& operator=(ADXL345_I2C&&) = default;
+ I2C::Port GetI2CPort() const;
+ int GetI2CDeviceAddress() const;
+
// Accelerometer interface
- void SetRange(Range range) override;
+ void SetRange(Range range) final;
double GetX() override;
double GetY() override;
double GetZ() override;
@@ -75,7 +71,7 @@
*/
virtual AllAxes GetAccelerations();
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(nt::NTSendableBuilder& builder) override;
protected:
I2C m_i2c;
diff --git a/wpilibc/src/main/native/include/frc/ADXL345_SPI.h b/wpilibc/src/main/native/include/frc/ADXL345_SPI.h
index 90454c0..18d48a3 100644
--- a/wpilibc/src/main/native/include/frc/ADXL345_SPI.h
+++ b/wpilibc/src/main/native/include/frc/ADXL345_SPI.h
@@ -1,19 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/SimDevice.h>
+#include <networktables/NTSendable.h>
+#include <wpi/sendable/SendableHelper.h>
-#include "frc/ErrorBase.h"
#include "frc/SPI.h"
#include "frc/interfaces/Accelerometer.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
@@ -23,10 +19,9 @@
* This class allows access to an Analog Devices ADXL345 3-axis accelerometer
* via SPI. This class assumes the sensor is wired in 4-wire SPI mode.
*/
-class ADXL345_SPI : public ErrorBase,
- public Accelerometer,
- public Sendable,
- public SendableHelper<ADXL345_SPI> {
+class ADXL345_SPI : public Accelerometer,
+ public nt::NTSendable,
+ public wpi::SendableHelper<ADXL345_SPI> {
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
@@ -49,8 +44,10 @@
ADXL345_SPI(ADXL345_SPI&&) = default;
ADXL345_SPI& operator=(ADXL345_SPI&&) = default;
+ SPI::Port GetSpiPort() const;
+
// Accelerometer interface
- void SetRange(Range range) override;
+ void SetRange(Range range) final;
double GetX() override;
double GetY() override;
double GetZ() override;
@@ -71,7 +68,7 @@
*/
virtual AllAxes GetAccelerations();
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(nt::NTSendableBuilder& builder) override;
protected:
SPI m_spi;
diff --git a/wpilibc/src/main/native/include/frc/ADXL362.h b/wpilibc/src/main/native/include/frc/ADXL362.h
index e1d659b..451b5fb 100644
--- a/wpilibc/src/main/native/include/frc/ADXL362.h
+++ b/wpilibc/src/main/native/include/frc/ADXL362.h
@@ -1,33 +1,26 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/SimDevice.h>
+#include <networktables/NTSendable.h>
+#include <wpi/sendable/SendableHelper.h>
-#include "frc/ErrorBase.h"
#include "frc/SPI.h"
#include "frc/interfaces/Accelerometer.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* ADXL362 SPI Accelerometer.
*
* This class allows access to an Analog Devices ADXL362 3-axis accelerometer.
*/
-class ADXL362 : public ErrorBase,
- public Accelerometer,
- public Sendable,
- public SendableHelper<ADXL362> {
+class ADXL362 : public Accelerometer,
+ public nt::NTSendable,
+ public wpi::SendableHelper<ADXL362> {
public:
enum Axes { kAxis_X = 0x00, kAxis_Y = 0x02, kAxis_Z = 0x04 };
struct AllAxes {
@@ -57,8 +50,10 @@
ADXL362(ADXL362&&) = default;
ADXL362& operator=(ADXL362&&) = default;
+ SPI::Port GetSpiPort() const;
+
// Accelerometer interface
- void SetRange(Range range) override;
+ void SetRange(Range range) final;
double GetX() override;
double GetY() override;
double GetZ() override;
@@ -79,7 +74,7 @@
*/
virtual AllAxes GetAccelerations();
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(nt::NTSendableBuilder& builder) override;
private:
SPI m_spi;
diff --git a/wpilibc/src/main/native/include/frc/ADXRS450_Gyro.h b/wpilibc/src/main/native/include/frc/ADXRS450_Gyro.h
index 309fab3..cb0dff8 100644
--- a/wpilibc/src/main/native/include/frc/ADXRS450_Gyro.h
+++ b/wpilibc/src/main/native/include/frc/ADXRS450_Gyro.h
@@ -1,25 +1,24 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <stdint.h>
#include <hal/SimDevice.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
-#include "frc/GyroBase.h"
#include "frc/SPI.h"
+#include "frc/interfaces/Gyro.h"
namespace frc {
/**
* Use a rate gyro to return the robots heading relative to a starting position.
*
- * The Gyro class tracks the robots heading based on the starting position. As
+ * The %Gyro class tracks the robots heading based on the starting position. As
* the robot rotates the new heading is computed by integrating the rate of
* rotation returned by the sensor. When the class is instantiated, it does a
* short calibration routine where it samples the gyro while at rest to
@@ -27,17 +26,19 @@
* determine the heading.
*
* This class is for the digital ADXRS450 gyro sensor that connects via SPI.
- * Only one instance of an ADXRS Gyro is supported.
+ * Only one instance of an ADXRS %Gyro is supported.
*/
-class ADXRS450_Gyro : public GyroBase {
+class ADXRS450_Gyro : public Gyro,
+ public wpi::Sendable,
+ public wpi::SendableHelper<ADXRS450_Gyro> {
public:
/**
- * Gyro constructor on onboard CS0.
+ * %Gyro constructor on onboard CS0.
*/
ADXRS450_Gyro();
/**
- * Gyro constructor on the specified SPI port.
+ * %Gyro constructor on the specified SPI port.
*
* @param port The SPI port the gyro is attached to.
*/
@@ -90,7 +91,7 @@
* robot is first turned on while it's sitting at rest before the competition
* starts.
*/
- void Calibrate() override;
+ void Calibrate() final;
/**
* Get the SPI port number.
@@ -99,6 +100,8 @@
*/
int GetPort() const;
+ void InitSendable(wpi::SendableBuilder& builder) override;
+
private:
SPI m_spi;
SPI::Port m_port;
diff --git a/wpilibc/src/main/native/include/frc/AddressableLED.h b/wpilibc/src/main/native/include/frc/AddressableLED.h
index 3bcbab5..561eb37 100644
--- a/wpilibc/src/main/native/include/frc/AddressableLED.h
+++ b/wpilibc/src/main/native/include/frc/AddressableLED.h
@@ -1,20 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <memory>
+#include <initializer_list>
#include <hal/AddressableLEDTypes.h>
#include <hal/Types.h>
#include <units/time.h>
-#include <wpi/ArrayRef.h>
+#include <wpi/span.h>
-#include "frc/ErrorBase.h"
#include "util/Color.h"
#include "util/Color8Bit.h"
@@ -25,7 +21,7 @@
*
* <p>Only 1 LED driver is currently supported by the roboRIO.
*/
-class AddressableLED : public ErrorBase {
+class AddressableLED {
public:
class LEDData : public HAL_AddressableLEDData {
public:
@@ -89,7 +85,7 @@
*/
explicit AddressableLED(int port);
- ~AddressableLED() override;
+ ~AddressableLED();
/**
* Sets the length of the LED strip.
@@ -111,7 +107,7 @@
*
* @param ledData the buffer to write
*/
- void SetData(wpi::ArrayRef<LEDData> ledData);
+ void SetData(wpi::span<const LEDData> ledData);
/**
* Sets the led output data.
@@ -144,7 +140,7 @@
* <p>The sync time is the time to hold output so LEDs enable. Default set for
* WS2812.
*
- * @param syncTimeMicroSeconds the sync time
+ * @param syncTime the sync time
*/
void SetSyncTime(units::microsecond_t syncTime);
@@ -163,5 +159,6 @@
private:
hal::Handle<HAL_DigitalHandle> m_pwmHandle;
hal::Handle<HAL_AddressableLEDHandle> m_handle;
+ int m_port;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/AnalogAccelerometer.h b/wpilibc/src/main/native/include/frc/AnalogAccelerometer.h
index 27015e4..b14ff7c 100644
--- a/wpilibc/src/main/native/include/frc/AnalogAccelerometer.h
+++ b/wpilibc/src/main/native/include/frc/AnalogAccelerometer.h
@@ -1,24 +1,18 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
#include "frc/AnalogInput.h"
-#include "frc/ErrorBase.h"
-#include "frc/PIDSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* Handle operation of an analog accelerometer.
*
@@ -26,10 +20,8 @@
* sensors have multiple axis and can be treated as multiple devices. Each is
* calibrated by finding the center value over a period of time.
*/
-class AnalogAccelerometer : public ErrorBase,
- public PIDSource,
- public Sendable,
- public SendableHelper<AnalogAccelerometer> {
+class AnalogAccelerometer : public wpi::Sendable,
+ public wpi::SendableHelper<AnalogAccelerometer> {
public:
/**
* Create a new instance of an accelerometer.
@@ -100,14 +92,7 @@
*/
void SetZero(double zero);
- /**
- * Get the Acceleration for the PID Source parent.
- *
- * @return The current acceleration in Gs.
- */
- double PIDGet() override;
-
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
/**
diff --git a/wpilibc/src/main/native/include/frc/AnalogEncoder.h b/wpilibc/src/main/native/include/frc/AnalogEncoder.h
index 3dc22ea..6f12cb8 100644
--- a/wpilibc/src/main/native/include/frc/AnalogEncoder.h
+++ b/wpilibc/src/main/native/include/frc/AnalogEncoder.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -12,12 +9,11 @@
#include <hal/SimDevice.h>
#include <hal/Types.h>
#include <units/angle.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/AnalogTrigger.h"
#include "frc/Counter.h"
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
class AnalogInput;
@@ -25,11 +21,17 @@
/**
* Class for supporting continuous analog encoders, such as the US Digital MA3.
*/
-class AnalogEncoder : public ErrorBase,
- public Sendable,
- public SendableHelper<AnalogEncoder> {
+class AnalogEncoder : public wpi::Sendable,
+ public wpi::SendableHelper<AnalogEncoder> {
public:
/**
+ * Construct a new AnalogEncoder attached to a specific AnalogIn channel.
+ *
+ * @param channel the analog input channel to attach to
+ */
+ explicit AnalogEncoder(int channel);
+
+ /**
* Construct a new AnalogEncoder attached to a specific AnalogInput.
*
* @param analogInput the analog input to attach to
@@ -115,7 +117,7 @@
*/
int GetChannel() const;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
void Init();
diff --git a/wpilibc/src/main/native/include/frc/AnalogGyro.h b/wpilibc/src/main/native/include/frc/AnalogGyro.h
index b59df5b..6565c93 100644
--- a/wpilibc/src/main/native/include/frc/AnalogGyro.h
+++ b/wpilibc/src/main/native/include/frc/AnalogGyro.h
@@ -1,19 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Types.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
-#include "frc/GyroBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include "frc/interfaces/Gyro.h"
namespace frc {
@@ -32,7 +29,9 @@
*
* This class is for gyro sensors that connect to an analog input.
*/
-class AnalogGyro : public GyroBase {
+class AnalogGyro : public Gyro,
+ public wpi::Sendable,
+ public wpi::SendableHelper<AnalogGyro> {
public:
static constexpr int kOversampleBits = 10;
static constexpr int kAverageBits = 0;
@@ -41,7 +40,7 @@
static constexpr double kDefaultVoltsPerDegreePerSecond = 0.007;
/**
- * Gyro constructor using the Analog Input channel number.
+ * %Gyro constructor using the Analog Input channel number.
*
* @param channel The analog channel the gyro is connected to. Gyros can only
* be used on on-board Analog Inputs 0-1.
@@ -63,7 +62,7 @@
explicit AnalogGyro(AnalogInput* channel);
/**
- * Gyro constructor with a precreated AnalogInput object.
+ * %Gyro constructor with a precreated AnalogInput object.
*
* Use this constructor when the analog channel needs to be shared.
* This object will not clean up the AnalogInput object when using this
@@ -75,7 +74,7 @@
explicit AnalogGyro(std::shared_ptr<AnalogInput> channel);
/**
- * Gyro constructor using the Analog Input channel number with parameters for
+ * %Gyro constructor using the Analog Input channel number with parameters for
* presetting the center and offset values. Bypasses calibration.
*
* @param channel The analog channel the gyro is connected to. Gyros can only
@@ -87,7 +86,7 @@
AnalogGyro(int channel, int center, double offset);
/**
- * Gyro constructor with a precreated AnalogInput object and calibrated
+ * %Gyro constructor with a precreated AnalogInput object and calibrated
* parameters.
*
* Use this constructor when the analog channel needs to be shared.
@@ -104,8 +103,8 @@
~AnalogGyro() override;
- AnalogGyro(AnalogGyro&& rhs);
- AnalogGyro& operator=(AnalogGyro&& rhs);
+ AnalogGyro(AnalogGyro&& rhs) = default;
+ AnalogGyro& operator=(AnalogGyro&& rhs) = default;
/**
* Return the actual angle in degrees that the robot is currently facing.
@@ -175,16 +174,16 @@
* significant drift in the gyro and it needs to be recalibrated after it has
* been running.
*/
- void Reset() override;
+ void Reset() final;
/**
* Initialize the gyro.
*
* Calibration is handled by Calibrate().
*/
- virtual void InitGyro();
+ void InitGyro();
- void Calibrate() override;
+ void Calibrate() final;
/**
* Gets the analog input for the gyro.
@@ -193,6 +192,8 @@
*/
std::shared_ptr<AnalogInput> GetAnalogInput() const;
+ void InitSendable(wpi::SendableBuilder& builder) override;
+
protected:
std::shared_ptr<AnalogInput> m_analog;
diff --git a/wpilibc/src/main/native/include/frc/AnalogInput.h b/wpilibc/src/main/native/include/frc/AnalogInput.h
index 3d14c4c..ebc4e70 100644
--- a/wpilibc/src/main/native/include/frc/AnalogInput.h
+++ b/wpilibc/src/main/native/include/frc/AnalogInput.h
@@ -1,24 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <stdint.h>
#include <hal/Types.h>
-
-#include "frc/ErrorBase.h"
-#include "frc/PIDSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
namespace frc {
-class SendableBuilder;
class DMA;
class DMASample;
@@ -34,10 +27,8 @@
* are divided by the number of samples to retain the resolution, but get more
* stable values.
*/
-class AnalogInput : public ErrorBase,
- public PIDSource,
- public Sendable,
- public SendableHelper<AnalogInput> {
+class AnalogInput : public wpi::Sendable,
+ public wpi::SendableHelper<AnalogInput> {
friend class AnalogTrigger;
friend class AnalogGyro;
friend class DMA;
@@ -207,8 +198,7 @@
*
* This will be added to all values returned to the user.
*
- * @param initialValue The value that the accumulator should start from when
- * reset.
+ * @param value The value that the accumulator should start from when reset.
*/
void SetAccumulatorInitialValue(int64_t value);
@@ -284,20 +274,13 @@
static double GetSampleRate();
/**
- * Get the Average value for the PID Source base object.
- *
- * @return The average voltage.
- */
- double PIDGet() override;
-
- /**
* Indicates this input is used by a simulated device.
*
* @param device simulated device handle
*/
void SetSimDevice(HAL_SimDeviceHandle device);
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
int m_channel;
diff --git a/wpilibc/src/main/native/include/frc/AnalogOutput.h b/wpilibc/src/main/native/include/frc/AnalogOutput.h
index 026986b..ccb3c9c 100644
--- a/wpilibc/src/main/native/include/frc/AnalogOutput.h
+++ b/wpilibc/src/main/native/include/frc/AnalogOutput.h
@@ -1,28 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/Types.h>
-
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
namespace frc {
-class SendableBuilder;
-
/**
* MXP analog output class.
*/
-class AnalogOutput : public ErrorBase,
- public Sendable,
- public SendableHelper<AnalogOutput> {
+class AnalogOutput : public wpi::Sendable,
+ public wpi::SendableHelper<AnalogOutput> {
public:
/**
* Construct an analog output on the given channel.
@@ -57,7 +49,7 @@
*/
int GetChannel() const;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
protected:
int m_channel;
diff --git a/wpilibc/src/main/native/include/frc/AnalogPotentiometer.h b/wpilibc/src/main/native/include/frc/AnalogPotentiometer.h
index ed943f7..3d0588d 100644
--- a/wpilibc/src/main/native/include/frc/AnalogPotentiometer.h
+++ b/wpilibc/src/main/native/include/frc/AnalogPotentiometer.h
@@ -1,34 +1,26 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
#include "frc/AnalogInput.h"
-#include "frc/ErrorBase.h"
-#include "frc/interfaces/Potentiometer.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* Class for reading analog potentiometers. Analog potentiometers read in an
* analog voltage that corresponds to a position. The position is in whichever
* units you choose, by way of the scaling and offset constants passed to the
* constructor.
*/
-class AnalogPotentiometer : public ErrorBase,
- public Potentiometer,
- public Sendable,
- public SendableHelper<AnalogPotentiometer> {
+class AnalogPotentiometer : public wpi::Sendable,
+ public wpi::SendableHelper<AnalogPotentiometer> {
public:
/**
* Construct an Analog Potentiometer object from a channel number.
@@ -66,7 +58,7 @@
* This will calculate the result from the fullRange times the fraction of the
* supply voltage, plus the offset.
*
- * @param channel The existing Analog Input pointer
+ * @param input The existing Analog Input pointer
* @param fullRange The value (in desired units) representing the full
* 0-5V range of the input.
* @param offset The value (in desired units) representing the
@@ -88,7 +80,7 @@
* This will calculate the result from the fullRange times the fraction of the
* supply voltage, plus the offset.
*
- * @param channel The existing Analog Input pointer
+ * @param input The existing Analog Input pointer
* @param fullRange The value (in desired units) representing the full
* 0-5V range of the input.
* @param offset The value (in desired units) representing the
@@ -108,16 +100,9 @@
* @return The current position of the potentiometer (in the units used for
* fullRange and offset).
*/
- double Get() const override;
+ double Get() const;
- /**
- * Implement the PIDSource interface.
- *
- * @return The current reading.
- */
- double PIDGet() override;
-
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
std::shared_ptr<AnalogInput> m_analog_input;
diff --git a/wpilibc/src/main/native/include/frc/AnalogTrigger.h b/wpilibc/src/main/native/include/frc/AnalogTrigger.h
index d465652..f9c5602 100644
--- a/wpilibc/src/main/native/include/frc/AnalogTrigger.h
+++ b/wpilibc/src/main/native/include/frc/AnalogTrigger.h
@@ -1,30 +1,24 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Types.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/AnalogTriggerOutput.h"
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
class AnalogInput;
class DutyCycle;
-class SendableBuilder;
-class AnalogTrigger : public ErrorBase,
- public Sendable,
- public SendableHelper<AnalogTrigger> {
+class AnalogTrigger : public wpi::Sendable,
+ public wpi::SendableHelper<AnalogTrigger> {
friend class AnalogTriggerOutput;
public:
@@ -42,21 +36,21 @@
* This should be used in the case of sharing an analog channel between the
* trigger and an analog input object.
*
- * @param channel The pointer to the existing AnalogInput object
+ * @param input The pointer to the existing AnalogInput object
*/
- explicit AnalogTrigger(AnalogInput* channel);
+ explicit AnalogTrigger(AnalogInput* input);
/**
* Construct an analog trigger given a duty cycle input.
*
- * @param channel The pointer to the existing DutyCycle object
+ * @param dutyCycle The pointer to the existing DutyCycle object
*/
explicit AnalogTrigger(DutyCycle* dutyCycle);
~AnalogTrigger() override;
- AnalogTrigger(AnalogTrigger&& rhs);
- AnalogTrigger& operator=(AnalogTrigger&& rhs);
+ AnalogTrigger(AnalogTrigger&&) = default;
+ AnalogTrigger& operator=(AnalogTrigger&&) = default;
/**
* Set the upper and lower limits of the analog trigger.
@@ -154,9 +148,11 @@
std::shared_ptr<AnalogTriggerOutput> CreateOutput(
AnalogTriggerType type) const;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
+ int GetSourceChannel() const;
+
hal::Handle<HAL_AnalogTriggerHandle> m_trigger;
AnalogInput* m_analogInput = nullptr;
DutyCycle* m_dutyCycle = nullptr;
diff --git a/wpilibc/src/main/native/include/frc/AnalogTriggerOutput.h b/wpilibc/src/main/native/include/frc/AnalogTriggerOutput.h
index 989a93f..6f52cab 100644
--- a/wpilibc/src/main/native/include/frc/AnalogTriggerOutput.h
+++ b/wpilibc/src/main/native/include/frc/AnalogTriggerOutput.h
@@ -1,15 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
#include "frc/DigitalSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
@@ -47,8 +45,8 @@
* may help with this, but rotational speeds of the sensor will then be limited.
*/
class AnalogTriggerOutput : public DigitalSource,
- public Sendable,
- public SendableHelper<AnalogTriggerOutput> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<AnalogTriggerOutput> {
friend class AnalogTrigger;
public:
@@ -80,7 +78,7 @@
*/
int GetChannel() const override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
protected:
/**
diff --git a/wpilibc/src/main/native/include/frc/AnalogTriggerType.h b/wpilibc/src/main/native/include/frc/AnalogTriggerType.h
index f15fb03..c706c34 100644
--- a/wpilibc/src/main/native/include/frc/AnalogTriggerType.h
+++ b/wpilibc/src/main/native/include/frc/AnalogTriggerType.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/AsynchronousInterrupt.h b/wpilibc/src/main/native/include/frc/AsynchronousInterrupt.h
new file mode 100644
index 0000000..4531dfd
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/AsynchronousInterrupt.h
@@ -0,0 +1,177 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <frc/SynchronousInterrupt.h>
+
+#include <atomic>
+#include <functional>
+#include <memory>
+#include <thread>
+#include <utility>
+
+#include <units/time.h>
+
+namespace frc {
+/**
+ * Class for handling asynchronous interrupts using a callback thread.
+ *
+ * <p> By default, interrupts will occur on rising edge. Callbacks are disabled
+ * by default, and Enable() must be called before they will occur.
+ *
+ * <p> Both rising and falling edges can be indicated in one callback if both a
+ * rising and falling edge occurred since the previous callback.
+ *
+ * <p>Synchronous (blocking) interrupts are handled by the SynchronousInterrupt
+ * class.
+ */
+class AsynchronousInterrupt {
+ public:
+ /**
+ * Construct an Asynchronous Interrupt from a Digital Source.
+ *
+ * <p> At construction, the interrupt will trigger on the rising edge.
+ *
+ * <p> The first bool in the callback indicates the rising edge triggered the
+ * interrupt, the second bool is falling edge.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ * @param callback the callback function to call when the interrupt is
+ * triggered
+ */
+ AsynchronousInterrupt(DigitalSource& source,
+ std::function<void(bool, bool)> callback);
+
+ /**
+ * Construct an Asynchronous Interrupt from a Digital Source.
+ *
+ * <p> At construction, the interrupt will trigger on the rising edge.
+ *
+ * <p> The first bool in the callback indicates the rising edge triggered the
+ * interrupt, the second bool is falling edge.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ * @param callback the callback function to call when the interrupt is
+ * triggered
+ */
+ AsynchronousInterrupt(DigitalSource* source,
+ std::function<void(bool, bool)> callback);
+
+ /**
+ * Construct an Asynchronous Interrupt from a Digital Source.
+ *
+ * <p> At construction, the interrupt will trigger on the rising edge.
+ *
+ * <p> The first bool in the callback indicates the rising edge triggered the
+ * interrupt, the second bool is falling edge.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ * @param callback the callback function to call when the interrupt is
+ * triggered
+ */
+ AsynchronousInterrupt(std::shared_ptr<DigitalSource> source,
+ std::function<void(bool, bool)> callback);
+
+ /**
+ * Construct an Asynchronous Interrupt from a Digital Source.
+ *
+ * <p> At construction, the interrupt will trigger on the rising edge.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ * @param f the callback function to call when the interrupt is triggered
+ * @param arg the first argument, interrupt was triggered on rising edge
+ * @param args the remaing arguments, interrupt was triggered on falling edge
+ */
+ template <typename Callable, typename Arg, typename... Args>
+ AsynchronousInterrupt(DigitalSource& source, Callable&& f, Arg&& arg,
+ Args&&... args)
+ : AsynchronousInterrupt(
+ source, std::bind(std::forward<Callable>(f), std::forward<Arg>(arg),
+ std::forward<Args>(args)...)) {}
+
+ /**
+ * Construct an Asynchronous Interrupt from a Digital Source.
+ *
+ * <p> At construction, the interrupt will trigger on the rising edge.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ * @param f the callback function to call when the interrupt is triggered
+ * @param arg the first argument, interrupt was triggered on rising edge
+ * @param args the remaing arguments, interrupt was triggered on falling edge
+ */
+ template <typename Callable, typename Arg, typename... Args>
+ AsynchronousInterrupt(DigitalSource* source, Callable&& f, Arg&& arg,
+ Args&&... args)
+ : AsynchronousInterrupt(
+ source, std::bind(std::forward<Callable>(f), std::forward<Arg>(arg),
+ std::forward<Args>(args)...)) {}
+
+ /**
+ * Construct an Asynchronous Interrupt from a Digital Source.
+ *
+ * <p> At construction, the interrupt will trigger on the rising edge.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ * @param f the callback function to call when the interrupt is triggered
+ * @param arg the first argument, interrupt was triggered on rising edge
+ * @param args the remaing arguments, interrupt was triggered on falling edge
+ */
+ template <typename Callable, typename Arg, typename... Args>
+ AsynchronousInterrupt(std::shared_ptr<DigitalSource> source, Callable&& f,
+ Arg&& arg, Args&&... args)
+ : AsynchronousInterrupt(
+ source, std::bind(std::forward<Callable>(f), std::forward<Arg>(arg),
+ std::forward<Args>(args)...)) {}
+
+ ~AsynchronousInterrupt();
+
+ /**
+ * Enables interrupt callbacks. Before this, callbacks will not occur. Does
+ * nothing if already enabled.
+ */
+ void Enable();
+
+ /**
+ * Disables interrupt callbacks. Does nothing if already disabled.
+ */
+ void Disable();
+
+ /**
+ * Set which edges to trigger the interrupt on.
+ *
+ * @param risingEdge %Trigger on rising edge
+ * @param fallingEdge %Trigger on falling edge
+ */
+ void SetInterruptEdges(bool risingEdge, bool fallingEdge);
+
+ /**
+ * Get the timestamp of the last rising edge.
+ *
+ * <p>This function does not require the interrupt to be enabled to work.
+ *
+ * <p>This only works if rising edge was configured using SetInterruptEdges.
+ * @return the timestamp in seconds relative to GetFPGATime
+ */
+ units::second_t GetRisingTimestamp();
+
+ /**
+ * Get the timestamp of the last falling edge.
+ *
+ * <p>This function does not require the interrupt to be enabled to work.
+ *
+ * <p>This only works if falling edge was configured using SetInterruptEdges.
+ * @return the timestamp in seconds relative to GetFPGATime
+ */
+ units::second_t GetFallingTimestamp();
+
+ private:
+ void ThreadMain();
+
+ std::atomic_bool m_keepRunning{false};
+ std::thread m_thread;
+ SynchronousInterrupt m_interrupt;
+ std::function<void(bool, bool)> m_callback;
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Base.h b/wpilibc/src/main/native/include/frc/Base.h
deleted file mode 100644
index 1fdbe5d..0000000
--- a/wpilibc/src/main/native/include/frc/Base.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
-static_assert(0,
- "GCC must be 5 or greater. If building for the roboRIO, please "
- "update to the 2018 toolchains.");
-#endif
-
-#if defined(_MSC_VER) && _MSC_VER < 1900
-static_assert(0, "Visual Studio 2015 or greater required.");
-#endif
-
-/** WPILib FRC namespace */
-namespace frc {
-
-// A struct to use as a deleter when a std::shared_ptr must wrap a raw pointer
-// that is being deleted by someone else.
-template <class T>
-struct NullDeleter {
- void operator()(T*) const noexcept {};
-};
-
-} // namespace frc
-
-// For backwards compatibility
-#ifdef NO_NAMESPACED_WPILIB
-using namespace frc; // NOLINT
-#endif
diff --git a/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h b/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h
index 8148e72..0e5bee6 100644
--- a/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h
+++ b/wpilibc/src/main/native/include/frc/BuiltInAccelerometer.h
@@ -1,30 +1,24 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/ErrorBase.h"
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
#include "frc/interfaces/Accelerometer.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* Built-in accelerometer.
*
* This class allows access to the roboRIO's internal accelerometer.
*/
-class BuiltInAccelerometer : public ErrorBase,
- public Accelerometer,
- public Sendable,
- public SendableHelper<BuiltInAccelerometer> {
+class BuiltInAccelerometer : public Accelerometer,
+ public wpi::Sendable,
+ public wpi::SendableHelper<BuiltInAccelerometer> {
public:
/**
* Constructor.
@@ -44,7 +38,7 @@
* accelerometer will measure. Not all accelerometers support all
* ranges.
*/
- void SetRange(Range range) override;
+ void SetRange(Range range) final;
/**
* @return The acceleration of the roboRIO along the X axis in g-forces
@@ -61,7 +55,7 @@
*/
double GetZ() override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/CAN.h b/wpilibc/src/main/native/include/frc/CAN.h
index 612d533..4c9b9bd 100644
--- a/wpilibc/src/main/native/include/frc/CAN.h
+++ b/wpilibc/src/main/native/include/frc/CAN.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -11,8 +8,6 @@
#include <hal/CANAPITypes.h>
-#include "frc/ErrorBase.h"
-
namespace frc {
struct CANData {
uint8_t data[8];
@@ -30,7 +25,7 @@
* All methods are thread save, however the buffer objects passed in
* by the user need to not be modified for the duration of their calls.
*/
-class CAN : public ErrorBase {
+class CAN {
public:
/**
* Create a new CAN communication interface with the specific device ID.
@@ -55,7 +50,7 @@
/**
* Closes the CAN communication.
*/
- ~CAN() override;
+ ~CAN();
CAN(CAN&&) = default;
CAN& operator=(CAN&&) = default;
diff --git a/wpilibc/src/main/native/include/frc/Compressor.h b/wpilibc/src/main/native/include/frc/Compressor.h
index d1a4dca..cc065ff 100644
--- a/wpilibc/src/main/native/include/frc/Compressor.h
+++ b/wpilibc/src/main/native/include/frc/Compressor.h
@@ -1,28 +1,25 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <hal/Types.h>
+#include <memory>
-#include "frc/ErrorBase.h"
+#include <hal/Types.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/PneumaticsBase.h"
+#include "frc/PneumaticsModuleType.h"
#include "frc/SensorUtil.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
- * Class for operating a compressor connected to a %PCM (Pneumatic Control
- * Module).
+ * Class for operating a compressor connected to a pneumatics module.
*
- * The PCM will automatically run in closed loop mode by default whenever a
+ * The module will automatically run in closed loop mode by default whenever a
* Solenoid object is created. For most cases, a Compressor object does not need
* to be instantiated or used in a robot program. This class is only required in
* cases where the robot program needs a more detailed status of the compressor
@@ -33,18 +30,28 @@
* loop control. You can only turn off closed loop control, thereby stopping
* the compressor from operating.
*/
-class Compressor : public ErrorBase,
- public Sendable,
- public SendableHelper<Compressor> {
+class Compressor : public wpi::Sendable,
+ public wpi::SendableHelper<Compressor> {
public:
/**
- * Constructor. The default PCM ID is 0.
+ * Constructs a compressor for a specified module and type.
*
- * @param module The PCM ID to use (0-62)
+ * @param module The module ID to use.
+ * @param moduleType The module type to use.
*/
- explicit Compressor(int pcmID = SensorUtil::GetDefaultSolenoidModule());
+ Compressor(int module, PneumaticsModuleType moduleType);
- ~Compressor() override = default;
+ /**
+ * Constructs a compressor for a default module and specified type.
+ *
+ * @param moduleType The module type to use.
+ */
+ explicit Compressor(PneumaticsModuleType moduleType);
+
+ ~Compressor() override;
+
+ Compressor(const Compressor&) = delete;
+ Compressor& operator=(const Compressor&) = delete;
Compressor(Compressor&&) = default;
Compressor& operator=(Compressor&&) = default;
@@ -100,92 +107,10 @@
*/
bool GetClosedLoopControl() const;
- /**
- * Query if the compressor output has been disabled due to high current draw.
- *
- * @return true if PCM is in fault state : Compressor Drive is
- * disabled due to compressor current being too high.
- */
- bool GetCompressorCurrentTooHighFault() const;
-
- /**
- * Query if the compressor output has been disabled due to high current draw
- * (sticky).
- *
- * A sticky fault will not clear on device reboot, it must be cleared through
- * code or the webdash.
- *
- * @return true if PCM sticky fault is set : Compressor Drive is
- * disabled due to compressor current being too high.
- */
- bool GetCompressorCurrentTooHighStickyFault() const;
-
- /**
- * Query if the compressor output has been disabled due to a short circuit
- * (sticky).
- *
- * A sticky fault will not clear on device reboot, it must be cleared through
- * code or the webdash.
- *
- * @return true if PCM sticky fault is set : Compressor output
- * appears to be shorted.
- */
- bool GetCompressorShortedStickyFault() const;
-
- /**
- * Query if the compressor output has been disabled due to a short circuit.
- *
- * @return true if PCM is in fault state : Compressor output
- * appears to be shorted.
- */
- bool GetCompressorShortedFault() const;
-
- /**
- * Query if the compressor output does not appear to be wired (sticky).
- *
- * A sticky fault will not clear on device reboot, it must be cleared through
- * code or the webdash.
- *
- * @return true if PCM sticky fault is set : Compressor does not
- * appear to be wired, i.e. compressor is not drawing enough current.
- */
- bool GetCompressorNotConnectedStickyFault() const;
-
- /**
- * Query if the compressor output does not appear to be wired.
- *
- * @return true if PCM is in fault state : Compressor does not
- * appear to be wired, i.e. compressor is not drawing enough current.
- */
- bool GetCompressorNotConnectedFault() const;
-
- /**
- * Clear ALL sticky faults inside PCM that Compressor is wired to.
- *
- * If a sticky fault is set, then it will be persistently cleared. Compressor
- * drive maybe momentarily disable while flags are being cleared. Care should
- * be taken to not call this too frequently, otherwise normal compressor
- * functionality may be prevented.
- *
- * If no sticky faults are set then this call will have no effect.
- */
- void ClearAllPCMStickyFaults();
-
- /**
- * Gets module number (CAN ID).
- *
- * @return Module number
- */
- int GetModule() const;
-
- void InitSendable(SendableBuilder& builder) override;
-
- protected:
- hal::Handle<HAL_CompressorHandle> m_compressorHandle;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
- void SetCompressor(bool on);
- int m_module;
+ std::shared_ptr<PneumaticsBase> m_module;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Controller.h b/wpilibc/src/main/native/include/frc/Controller.h
index c6b25ab..d750a0e 100644
--- a/wpilibc/src/main/native/include/frc/Controller.h
+++ b/wpilibc/src/main/native/include/frc/Controller.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/Counter.h b/wpilibc/src/main/native/include/frc/Counter.h
index 2770a02..d501b7e 100644
--- a/wpilibc/src/main/native/include/frc/Counter.h
+++ b/wpilibc/src/main/native/include/frc/Counter.h
@@ -1,26 +1,22 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Types.h>
+#include <units/time.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/AnalogTrigger.h"
#include "frc/CounterBase.h"
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
class DigitalGlitchFilter;
-class SendableBuilder;
class DMA;
class DMASample;
@@ -34,10 +30,9 @@
* All counters will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
-class Counter : public ErrorBase,
- public CounterBase,
- public Sendable,
- public SendableHelper<Counter> {
+class Counter : public CounterBase,
+ public wpi::Sendable,
+ public wpi::SendableHelper<Counter> {
friend class DMA;
friend class DMASample;
@@ -82,7 +77,7 @@
*
* This is used if an existing digital input is to be shared by multiple other
* objects such as encoders or if the Digital Source is not a Digital Input
- * channel (such as an Analog Trigger).
+ * channel (such as an Analog %Trigger).
*
* The counter will start counting immediately.
* @param source A pointer to the existing DigitalSource object. It will be
@@ -96,7 +91,7 @@
*
* This is used if an existing digital input is to be shared by multiple other
* objects such as encoders or if the Digital Source is not a Digital Input
- * channel (such as an Analog Trigger).
+ * channel (such as an Analog %Trigger).
*
* The counter will start counting immediately.
*
@@ -373,7 +368,7 @@
*
* @returns The period between the last two pulses in units of seconds.
*/
- double GetPeriod() const override;
+ units::second_t GetPeriod() const override;
/**
* Set the maximum period where the device is still considered "moving".
@@ -385,7 +380,7 @@
* @param maxPeriod The maximum period where the counted device is considered
* moving in seconds.
*/
- void SetMaxPeriod(double maxPeriod) override;
+ void SetMaxPeriod(units::second_t maxPeriod) final;
/**
* Select whether you want to continue updating the event timer output when
@@ -425,7 +420,7 @@
*/
bool GetDirection() const override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
protected:
// Makes the counter count up.
diff --git a/wpilibc/src/main/native/include/frc/CounterBase.h b/wpilibc/src/main/native/include/frc/CounterBase.h
index 7fde3ac..33febbf 100644
--- a/wpilibc/src/main/native/include/frc/CounterBase.h
+++ b/wpilibc/src/main/native/include/frc/CounterBase.h
@@ -1,12 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
+#include <units/time.h>
+
namespace frc {
/**
@@ -30,8 +29,8 @@
virtual int Get() const = 0;
virtual void Reset() = 0;
- virtual double GetPeriod() const = 0;
- virtual void SetMaxPeriod(double maxPeriod) = 0;
+ virtual units::second_t GetPeriod() const = 0;
+ virtual void SetMaxPeriod(units::second_t maxPeriod) = 0;
virtual bool GetStopped() const = 0;
virtual bool GetDirection() const = 0;
};
diff --git a/wpilibc/src/main/native/include/frc/DMA.h b/wpilibc/src/main/native/include/frc/DMA.h
index 57cdd27..1bbf268 100644
--- a/wpilibc/src/main/native/include/frc/DMA.h
+++ b/wpilibc/src/main/native/include/frc/DMA.h
@@ -1,15 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/Types.h>
-
-#include "frc/ErrorBase.h"
+#include <units/time.h>
namespace frc {
class Encoder;
@@ -18,19 +14,22 @@
class DutyCycle;
class AnalogInput;
class DMASample;
+class PWM;
+class PWMMotorController;
-class DMA : public ErrorBase {
+class DMA {
friend class DMASample;
public:
DMA();
- ~DMA() override;
+ ~DMA();
DMA& operator=(DMA&& other) = default;
DMA(DMA&& other) = default;
void SetPause(bool pause);
- void SetRate(int cycles);
+ void SetTimedTrigger(units::second_t seconds);
+ void SetTimedTriggerCycles(int cycles);
void AddEncoder(const Encoder* encoder);
void AddEncoderPeriod(const Encoder* encoder);
@@ -46,10 +45,15 @@
void AddAveragedAnalogInput(const AnalogInput* analogInput);
void AddAnalogAccumulator(const AnalogInput* analogInput);
- void SetExternalTrigger(DigitalSource* source, bool rising, bool falling);
+ int SetExternalTrigger(DigitalSource* source, bool rising, bool falling);
+ int SetPwmEdgeTrigger(PWM* pwm, bool rising, bool falling);
+ int SetPwmEdgeTrigger(PWMMotorController* pwm, bool rising, bool falling);
- void StartDMA(int queueDepth);
- void StopDMA();
+ void ClearSensors();
+ void ClearExternalTriggers();
+
+ void Start(int queueDepth);
+ void Stop();
private:
hal::Handle<HAL_DMAHandle> dmaHandle;
diff --git a/wpilibc/src/main/native/include/frc/DMASample.h b/wpilibc/src/main/native/include/frc/DMASample.h
index c286c8d..48a0a9e 100644
--- a/wpilibc/src/main/native/include/frc/DMASample.h
+++ b/wpilibc/src/main/native/include/frc/DMASample.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -22,11 +19,16 @@
namespace frc {
class DMASample : public HAL_DMASample {
public:
- HAL_DMAReadStatus Update(const DMA* dma, units::second_t timeout,
- int32_t* remaining, int32_t* status) {
- units::millisecond_t ms = timeout;
- auto timeoutMs = ms.to<int32_t>();
- return HAL_ReadDMA(dma->dmaHandle, this, timeoutMs, remaining, status);
+ enum class DMAReadStatus {
+ kOk = HAL_DMA_OK,
+ kTimeout = HAL_DMA_TIMEOUT,
+ kError = HAL_DMA_ERROR
+ };
+
+ DMAReadStatus Update(const DMA* dma, units::second_t timeout,
+ int32_t* remaining, int32_t* status) {
+ return static_cast<DMAReadStatus>(
+ HAL_ReadDMA(dma->dmaHandle, this, timeout.value(), remaining, status));
}
uint64_t GetTime() const { return timeStamp; }
diff --git a/wpilibc/src/main/native/include/frc/DSControlWord.h b/wpilibc/src/main/native/include/frc/DSControlWord.h
new file mode 100644
index 0000000..fb0709f
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/DSControlWord.h
@@ -0,0 +1,102 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <hal/DriverStationTypes.h>
+
+namespace frc {
+
+/**
+ * A wrapper around Driver Station control word.
+ */
+class DSControlWord {
+ public:
+ /**
+ * DSControlWord constructor.
+ *
+ * Upon construction, the current Driver Station control word is read and
+ * stored internally.
+ */
+ DSControlWord();
+
+ /**
+ * Check if the DS has enabled the robot.
+ *
+ * @return True if the robot is enabled and the DS is connected
+ */
+ bool IsEnabled() const;
+
+ /**
+ * Check if the robot is disabled.
+ *
+ * @return True if the robot is explicitly disabled or the DS is not connected
+ */
+ bool IsDisabled() const;
+
+ /**
+ * Check if the robot is e-stopped.
+ *
+ * @return True if the robot is e-stopped
+ */
+ bool IsEStopped() const;
+
+ /**
+ * Check if the DS is commanding autonomous mode.
+ *
+ * @return True if the robot is being commanded to be in autonomous mode
+ */
+ bool IsAutonomous() const;
+
+ /**
+ * Check if the DS is commanding autonomous mode and if it has enabled the
+ * robot.
+ *
+ * @return True if the robot is being commanded to be in autonomous mode and
+ * enabled.
+ */
+ bool IsAutonomousEnabled() const;
+
+ /**
+ * Check if the DS is commanding teleop mode.
+ *
+ * @return True if the robot is being commanded to be in teleop mode
+ */
+ bool IsTeleop() const;
+
+ /**
+ * Check if the DS is commanding teleop mode and if it has enabled the robot.
+ *
+ * @return True if the robot is being commanded to be in teleop mode and
+ * enabled.
+ */
+ bool IsTeleopEnabled() const;
+
+ /**
+ * Check if the DS is commanding test mode.
+ *
+ * @return True if the robot is being commanded to be in test mode
+ */
+ bool IsTest() const;
+
+ /**
+ * Check if the DS is attached.
+ *
+ * @return True if the DS is connected to the robot
+ */
+ bool IsDSAttached() const;
+
+ /**
+ * Is the driver station attached to a Field Management System?
+ *
+ * @return True if the robot is competing on a field being controlled by a
+ * Field Management System
+ */
+ bool IsFMSAttached() const;
+
+ private:
+ HAL_ControlWord m_controlWord;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Debouncer.h b/wpilibc/src/main/native/include/frc/Debouncer.h
new file mode 100644
index 0000000..8f583f0
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/Debouncer.h
@@ -0,0 +1,46 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <units/time.h>
+
+#include "frc/Timer.h"
+
+namespace frc {
+/**
+ * A simple debounce filter for boolean streams. Requires that the boolean
+ * change value from baseline for a specified period of time before the filtered
+ * value changes.
+ */
+class Debouncer {
+ public:
+ enum DebounceType { kRising, kFalling, kBoth };
+
+ /**
+ * Creates a new Debouncer.
+ *
+ * @param debounceTime The number of seconds the value must change from
+ * baseline for the filtered value to change.
+ * @param type Which type of state change the debouncing will be
+ * performed on.
+ */
+ explicit Debouncer(units::second_t debounceTime,
+ DebounceType type = DebounceType::kRising);
+
+ /**
+ * Applies the debouncer to the input stream.
+ *
+ * @param input The current value of the input stream.
+ * @return The debounced value of the input stream.
+ */
+ bool Calculate(bool input);
+
+ private:
+ frc::Timer m_timer;
+ units::second_t m_debounceTime;
+ bool m_baseline;
+ DebounceType m_debounceType;
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/DigitalGlitchFilter.h b/wpilibc/src/main/native/include/frc/DigitalGlitchFilter.h
index 0690e53..7172f21 100644
--- a/wpilibc/src/main/native/include/frc/DigitalGlitchFilter.h
+++ b/wpilibc/src/main/native/include/frc/DigitalGlitchFilter.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -12,11 +9,10 @@
#include <array>
#include <wpi/mutex.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/DigitalSource.h"
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
@@ -30,15 +26,14 @@
* filter. The filter lets the user configure the time that an input must remain
* high or low before it is classified as high or low.
*/
-class DigitalGlitchFilter : public ErrorBase,
- public Sendable,
- public SendableHelper<DigitalGlitchFilter> {
+class DigitalGlitchFilter : public wpi::Sendable,
+ public wpi::SendableHelper<DigitalGlitchFilter> {
public:
DigitalGlitchFilter();
~DigitalGlitchFilter() override;
- DigitalGlitchFilter(DigitalGlitchFilter&& rhs);
- DigitalGlitchFilter& operator=(DigitalGlitchFilter&& rhs);
+ DigitalGlitchFilter(DigitalGlitchFilter&&) = default;
+ DigitalGlitchFilter& operator=(DigitalGlitchFilter&&) = default;
/**
* Assigns the DigitalSource to this glitch filter.
@@ -119,7 +114,7 @@
*/
uint64_t GetPeriodNanoSeconds();
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
// Sets the filter for the input to be the requested index. A value of 0
diff --git a/wpilibc/src/main/native/include/frc/DigitalInput.h b/wpilibc/src/main/native/include/frc/DigitalInput.h
index 33aa716..cee31fd 100644
--- a/wpilibc/src/main/native/include/frc/DigitalInput.h
+++ b/wpilibc/src/main/native/include/frc/DigitalInput.h
@@ -1,20 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
#include "frc/DigitalSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
class DigitalGlitchFilter;
-class SendableBuilder;
/**
* Class to read a digital input.
@@ -26,8 +23,8 @@
* implemented anywhere else.
*/
class DigitalInput : public DigitalSource,
- public Sendable,
- public SendableHelper<DigitalInput> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<DigitalInput> {
public:
/**
* Create an instance of a Digital Input class.
@@ -78,7 +75,7 @@
*/
void SetSimDevice(HAL_SimDeviceHandle device);
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
int m_channel;
diff --git a/wpilibc/src/main/native/include/frc/DigitalOutput.h b/wpilibc/src/main/native/include/frc/DigitalOutput.h
index 1d1d152..0e124f1 100644
--- a/wpilibc/src/main/native/include/frc/DigitalOutput.h
+++ b/wpilibc/src/main/native/include/frc/DigitalOutput.h
@@ -1,22 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/Types.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/DigitalSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* Class to write to digital outputs.
*
@@ -25,8 +20,8 @@
* shouldn't be done here.
*/
class DigitalOutput : public DigitalSource,
- public Sendable,
- public SendableHelper<DigitalOutput> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<DigitalOutput> {
public:
/**
* Create an instance of a digital output.
@@ -148,7 +143,7 @@
*/
void SetSimDevice(HAL_SimDeviceHandle device);
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
int m_channel;
diff --git a/wpilibc/src/main/native/include/frc/DigitalSource.h b/wpilibc/src/main/native/include/frc/DigitalSource.h
index 5d77daa..0dd35d6 100644
--- a/wpilibc/src/main/native/include/frc/DigitalSource.h
+++ b/wpilibc/src/main/native/include/frc/DigitalSource.h
@@ -1,15 +1,12 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <hal/Types.h>
-#include "frc/InterruptableSensorBase.h"
+#include "frc/AnalogTriggerType.h"
namespace frc {
@@ -22,7 +19,7 @@
* constructed and freed when finished for the source. The source can either be
* a digital input or analog trigger but not both.
*/
-class DigitalSource : public InterruptableSensorBase {
+class DigitalSource {
public:
DigitalSource() = default;
DigitalSource(DigitalSource&&) = default;
diff --git a/wpilibc/src/main/native/include/frc/DoubleSolenoid.h b/wpilibc/src/main/native/include/frc/DoubleSolenoid.h
index 302c52c..381e3a1 100644
--- a/wpilibc/src/main/native/include/frc/DoubleSolenoid.h
+++ b/wpilibc/src/main/native/include/frc/DoubleSolenoid.h
@@ -1,53 +1,54 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <hal/Types.h>
+#include <memory>
-#include "frc/SolenoidBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <hal/Types.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/PneumaticsBase.h"
+#include "frc/PneumaticsModuleType.h"
namespace frc {
-class SendableBuilder;
-
/**
* DoubleSolenoid class for running 2 channels of high voltage Digital Output
- * (PCM).
+ * on a pneumatics module.
*
* The DoubleSolenoid class is typically used for pneumatics solenoids that
* have two positions controlled by two separate channels.
*/
-class DoubleSolenoid : public SolenoidBase,
- public Sendable,
- public SendableHelper<DoubleSolenoid> {
+class DoubleSolenoid : public wpi::Sendable,
+ public wpi::SendableHelper<DoubleSolenoid> {
public:
enum Value { kOff, kForward, kReverse };
/**
- * Constructor.
+ * Constructs a double solenoid for a specified module of a specific module
+ * type.
*
- * Uses the default PCM ID of 0.
- *
- * @param forwardChannel The forward channel number on the PCM (0..7).
- * @param reverseChannel The reverse channel number on the PCM (0..7).
+ * @param module The module of the solenoid module to use.
+ * @param moduleType The module type to use.
+ * @param forwardChannel The forward channel on the module to control.
+ * @param reverseChannel The reverse channel on the module to control.
*/
- explicit DoubleSolenoid(int forwardChannel, int reverseChannel);
+ DoubleSolenoid(int module, PneumaticsModuleType moduleType,
+ int forwardChannel, int reverseChannel);
/**
- * Constructor.
+ * Constructs a double solenoid for a default module of a specific module
+ * type.
*
- * @param moduleNumber The CAN ID of the PCM.
- * @param forwardChannel The forward channel on the PCM to control (0..7).
- * @param reverseChannel The reverse channel on the PCM to control (0..7).
+ * @param moduleType The module type to use.
+ * @param forwardChannel The forward channel on the module to control.
+ * @param reverseChannel The reverse channel on the module to control.
*/
- DoubleSolenoid(int moduleNumber, int forwardChannel, int reverseChannel);
+ DoubleSolenoid(PneumaticsModuleType moduleType, int forwardChannel,
+ int reverseChannel);
~DoubleSolenoid() override;
@@ -78,36 +79,50 @@
void Toggle();
/**
- * Check if the forward solenoid is blacklisted.
+ * Get the forward channel.
*
- * If a solenoid is shorted, it is added to the blacklist and disabled until
- * power cycle, or until faults are cleared.
- *
- * @see ClearAllPCMStickyFaults()
- * @return If solenoid is disabled due to short.
+ * @return the forward channel.
*/
- bool IsFwdSolenoidBlackListed() const;
+ int GetFwdChannel() const;
/**
- * Check if the reverse solenoid is blacklisted.
+ * Get the reverse channel.
*
- * If a solenoid is shorted, it is added to the blacklist and disabled until
- * power cycle, or until faults are cleared.
+ * @return the reverse channel.
+ */
+ int GetRevChannel() const;
+
+ /**
+ * Check if the forward solenoid is Disabled.
+ *
+ * If a solenoid is shorted, it is added to the DisabledList and disabled
+ * until power cycle, or until faults are cleared.
*
* @see ClearAllPCMStickyFaults()
* @return If solenoid is disabled due to short.
*/
- bool IsRevSolenoidBlackListed() const;
+ bool IsFwdSolenoidDisabled() const;
- void InitSendable(SendableBuilder& builder) override;
+ /**
+ * Check if the reverse solenoid is Disabled.
+ *
+ * If a solenoid is shorted, it is added to the DisabledList and disabled
+ * until power cycle, or until faults are cleared.
+ *
+ * @see ClearAllPCMStickyFaults()
+ * @return If solenoid is disabled due to short.
+ */
+ bool IsRevSolenoidDisabled() const;
+
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
+ std::shared_ptr<PneumaticsBase> m_module;
int m_forwardChannel; // The forward channel on the module to control.
int m_reverseChannel; // The reverse channel on the module to control.
int m_forwardMask; // The mask for the forward channel.
int m_reverseMask; // The mask for the reverse channel.
- hal::Handle<HAL_SolenoidHandle> m_forwardHandle;
- hal::Handle<HAL_SolenoidHandle> m_reverseHandle;
+ int m_mask;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/DriverStation.h b/wpilibc/src/main/native/include/frc/DriverStation.h
index a6c40d6..30bf4fc 100644
--- a/wpilibc/src/main/native/include/frc/DriverStation.h
+++ b/wpilibc/src/main/native/include/frc/DriverStation.h
@@ -1,102 +1,64 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <array>
-#include <atomic>
-#include <memory>
#include <string>
-#include <thread>
-#include <hal/DriverStationTypes.h>
-#include <wpi/Twine.h>
-#include <wpi/condition_variable.h>
-#include <wpi/mutex.h>
-
-#include "frc/ErrorBase.h"
+#include <units/time.h>
+#include <wpi/deprecated.h>
namespace frc {
-class MatchDataSender;
-
/**
* Provide access to the network communication data to / from the Driver
* Station.
*/
-class DriverStation : public ErrorBase {
+class DriverStation {
public:
enum Alliance { kRed, kBlue, kInvalid };
enum MatchType { kNone, kPractice, kQualification, kElimination };
- ~DriverStation() override;
-
- DriverStation(const DriverStation&) = delete;
- DriverStation& operator=(const DriverStation&) = delete;
-
/**
* Return a reference to the singleton DriverStation.
*
* @return Reference to the DS instance
+ * @deprecated Use the static methods
*/
+ WPI_DEPRECATED("Use static methods")
static DriverStation& GetInstance();
- /**
- * Report an error to the DriverStation messages window.
- *
- * The error is also printed to the program console.
- */
- static void ReportError(const wpi::Twine& error);
-
- /**
- * Report a warning to the DriverStation messages window.
- *
- * The warning is also printed to the program console.
- */
- static void ReportWarning(const wpi::Twine& error);
-
- /**
- * Report an error to the DriverStation messages window.
- *
- * The error is also printed to the program console.
- */
- static void ReportError(bool isError, int code, const wpi::Twine& error,
- const wpi::Twine& location, const wpi::Twine& stack);
-
static constexpr int kJoystickPorts = 6;
/**
- * The state of one joystick button. Button indexes begin at 1.
+ * The state of one joystick button. %Button indexes begin at 1.
*
* @param stick The joystick to read.
* @param button The button index, beginning at 1.
* @return The state of the joystick button.
*/
- bool GetStickButton(int stick, int button);
+ static bool GetStickButton(int stick, int button);
/**
- * Whether one joystick button was pressed since the last check. Button
+ * Whether one joystick button was pressed since the last check. %Button
* indexes begin at 1.
*
* @param stick The joystick to read.
* @param button The button index, beginning at 1.
* @return Whether the joystick button was pressed since the last check.
*/
- bool GetStickButtonPressed(int stick, int button);
+ static bool GetStickButtonPressed(int stick, int button);
/**
- * Whether one joystick button was released since the last check. Button
+ * Whether one joystick button was released since the last check. %Button
* indexes begin at 1.
*
* @param stick The joystick to read.
* @param button The button index, beginning at 1.
* @return Whether the joystick button was released since the last check.
*/
- bool GetStickButtonReleased(int stick, int button);
+ static bool GetStickButtonReleased(int stick, int button);
/**
* Get the value of the axis on a joystick.
@@ -108,14 +70,14 @@
* @param axis The analog axis value to read from the joystick.
* @return The value of the axis on the joystick.
*/
- double GetStickAxis(int stick, int axis);
+ static double GetStickAxis(int stick, int axis);
/**
* Get the state of a POV on the joystick.
*
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
- int GetStickPOV(int stick, int pov);
+ static int GetStickPOV(int stick, int pov);
/**
* The state of the buttons on the joystick.
@@ -123,7 +85,7 @@
* @param stick The joystick to read.
* @return The state of the buttons on the joystick.
*/
- int GetStickButtons(int stick) const;
+ static int GetStickButtons(int stick);
/**
* Returns the number of axes on a given joystick port.
@@ -131,7 +93,7 @@
* @param stick The joystick port number
* @return The number of axes on the indicated joystick
*/
- int GetStickAxisCount(int stick) const;
+ static int GetStickAxisCount(int stick);
/**
* Returns the number of POVs on a given joystick port.
@@ -139,7 +101,7 @@
* @param stick The joystick port number
* @return The number of POVs on the indicated joystick
*/
- int GetStickPOVCount(int stick) const;
+ static int GetStickPOVCount(int stick);
/**
* Returns the number of buttons on a given joystick port.
@@ -147,7 +109,7 @@
* @param stick The joystick port number
* @return The number of buttons on the indicated joystick
*/
- int GetStickButtonCount(int stick) const;
+ static int GetStickButtonCount(int stick);
/**
* Returns a boolean indicating if the controller is an xbox controller.
@@ -155,7 +117,7 @@
* @param stick The joystick port number
* @return A boolean that is true if the controller is an xbox controller.
*/
- bool GetJoystickIsXbox(int stick) const;
+ static bool GetJoystickIsXbox(int stick);
/**
* Returns the type of joystick at a given port.
@@ -163,7 +125,7 @@
* @param stick The joystick port number
* @return The HID type of joystick at the given port
*/
- int GetJoystickType(int stick) const;
+ static int GetJoystickType(int stick);
/**
* Returns the name of the joystick at the given port.
@@ -171,15 +133,16 @@
* @param stick The joystick port number
* @return The name of the joystick at the given port
*/
- std::string GetJoystickName(int stick) const;
+ static std::string GetJoystickName(int stick);
/**
* Returns the types of Axes on a given joystick port.
*
* @param stick The joystick port number and the target axis
+ * @param axis The analog axis value to read from the joystick.
* @return What type of axis the axis is reporting to be
*/
- int GetJoystickAxisType(int stick, int axis) const;
+ static int GetJoystickAxisType(int stick, int axis);
/**
* Returns if a joystick is connected to the Driver Station.
@@ -190,35 +153,35 @@
* @param stick The joystick port number
* @return true if a joystick is connected
*/
- bool IsJoystickConnected(int stick) const;
+ static bool IsJoystickConnected(int stick);
/**
* Check if the DS has enabled the robot.
*
* @return True if the robot is enabled and the DS is connected
*/
- bool IsEnabled() const;
+ static bool IsEnabled();
/**
* Check if the robot is disabled.
*
* @return True if the robot is explicitly disabled or the DS is not connected
*/
- bool IsDisabled() const;
+ static bool IsDisabled();
/**
* Check if the robot is e-stopped.
*
* @return True if the robot is e-stopped
*/
- bool IsEStopped() const;
+ static bool IsEStopped();
/**
* Check if the DS is commanding autonomous mode.
*
* @return True if the robot is being commanded to be in autonomous mode
*/
- bool IsAutonomous() const;
+ static bool IsAutonomous();
/**
* Check if the DS is commanding autonomous mode and if it has enabled the
@@ -227,14 +190,33 @@
* @return True if the robot is being commanded to be in autonomous mode and
* enabled.
*/
- bool IsAutonomousEnabled() const;
+ static bool IsAutonomousEnabled();
+
+ /**
+ * Check if the DS is commanding teleop mode.
+ *
+ * @return True if the robot is being commanded to be in teleop mode
+ * @deprecated Use IsTeleop() instead.
+ */
+ WPI_DEPRECATED("Use IsTeleop() instead")
+ static bool IsOperatorControl();
/**
* Check if the DS is commanding teleop mode.
*
* @return True if the robot is being commanded to be in teleop mode
*/
- bool IsOperatorControl() const;
+ static bool IsTeleop();
+
+ /**
+ * Check if the DS is commanding teleop mode and if it has enabled the robot.
+ *
+ * @return True if the robot is being commanded to be in teleop mode and
+ * enabled.
+ * @deprecated Use IsTeleopEnabled() instead.
+ */
+ WPI_DEPRECATED("Use IsTeleopEnabled() instead")
+ static bool IsOperatorControlEnabled();
/**
* Check if the DS is commanding teleop mode and if it has enabled the robot.
@@ -242,21 +224,21 @@
* @return True if the robot is being commanded to be in teleop mode and
* enabled.
*/
- bool IsOperatorControlEnabled() const;
+ static bool IsTeleopEnabled();
/**
* Check if the DS is commanding test mode.
*
* @return True if the robot is being commanded to be in test mode
*/
- bool IsTest() const;
+ static bool IsTest();
/**
* Check if the DS is attached.
*
* @return True if the DS is connected to the robot
*/
- bool IsDSAttached() const;
+ static bool IsDSAttached();
/**
* Has a new control packet from the driver station arrived since the last
@@ -267,7 +249,7 @@
*
* @return True if the control data has been updated since the last call.
*/
- bool IsNewControlData() const;
+ static bool IsNewControlData();
/**
* Is the driver station attached to a Field Management System?
@@ -275,21 +257,21 @@
* @return True if the robot is competing on a field being controlled by a
* Field Management System
*/
- bool IsFMSAttached() const;
+ static bool IsFMSAttached();
/**
* Returns the game specific message provided by the FMS.
*
* @return A string containing the game specific message.
*/
- std::string GetGameSpecificMessage() const;
+ static std::string GetGameSpecificMessage();
/**
* Returns the name of the competition event provided by the FMS.
*
* @return A string containing the event name
*/
- std::string GetEventName() const;
+ static std::string GetEventName();
/**
* Returns the type of match being played provided by the FMS.
@@ -297,14 +279,14 @@
* @return The match type enum (kNone, kPractice, kQualification,
* kElimination)
*/
- MatchType GetMatchType() const;
+ static MatchType GetMatchType();
/**
* Returns the match number provided by the FMS.
*
* @return The number of the match
*/
- int GetMatchNumber() const;
+ static int GetMatchNumber();
/**
* Returns the number of times the current match has been replayed from the
@@ -312,7 +294,7 @@
*
* @return The number of replays
*/
- int GetReplayNumber() const;
+ static int GetReplayNumber();
/**
* Return the alliance that the driver station says it is on.
@@ -321,7 +303,7 @@
*
* @return The Alliance enum (kRed, kBlue or kInvalid)
*/
- Alliance GetAlliance() const;
+ static Alliance GetAlliance();
/**
* Return the driver station location on the field.
@@ -330,7 +312,7 @@
*
* @return The location of the driver station (1-3, 0 for invalid)
*/
- int GetLocation() const;
+ static int GetLocation();
/**
* Wait until a new packet comes from the driver station.
@@ -343,7 +325,7 @@
* Checks if new control data has arrived since the last waitForData call
* on the current thread. If new data has not arrived, returns immediately.
*/
- void WaitForData();
+ static void WaitForData();
/**
* Wait until a new packet comes from the driver station, or wait for a
@@ -361,11 +343,11 @@
* This is a good way to delay processing until there is new driver station
* data to act on.
*
- * @param timeout Timeout time in seconds
+ * @param timeout Timeout
*
* @return true if new data, otherwise false
*/
- bool WaitForData(double timeout);
+ static bool WaitForData(units::second_t timeout);
/**
* Return the approximate match time.
@@ -382,14 +364,14 @@
*
* @return Time remaining in current match period (auto or teleop)
*/
- double GetMatchTime() const;
+ static double GetMatchTime();
/**
* Read the battery voltage.
*
* @return The battery voltage in Volts.
*/
- double GetBatteryVoltage() const;
+ static double GetBatteryVoltage();
/**
* Only to be used to tell the Driver Station what code you claim to be
@@ -398,7 +380,7 @@
* @param entering If true, starting disabled code; if false, leaving disabled
* code.
*/
- void InDisabled(bool entering) { m_userInDisabled = entering; }
+ static void InDisabled(bool entering);
/**
* Only to be used to tell the Driver Station what code you claim to be
@@ -407,7 +389,18 @@
* @param entering If true, starting autonomous code; if false, leaving
* autonomous code.
*/
- void InAutonomous(bool entering) { m_userInAutonomous = entering; }
+ static void InAutonomous(bool entering);
+
+ /**
+ * Only to be used to tell the Driver Station what code you claim to be
+ * executing for diagnostic purposes only.
+ *
+ * @param entering If true, starting teleop code; if false, leaving teleop
+ * code.
+ * @deprecated Use InTeleop() instead.
+ */
+ WPI_DEPRECATED("Use InTeleop() instead")
+ static void InOperatorControl(bool entering);
/**
* Only to be used to tell the Driver Station what code you claim to be
@@ -416,7 +409,7 @@
* @param entering If true, starting teleop code; if false, leaving teleop
* code.
*/
- void InOperatorControl(bool entering) { m_userInTeleop = entering; }
+ static void InTeleop(bool entering);
/**
* Only to be used to tell the Driver Station what code you claim to be
@@ -424,12 +417,12 @@
*
* @param entering If true, starting test code; if false, leaving test code.
*/
- void InTest(bool entering) { m_userInTest = entering; }
+ static void InTest(bool entering);
/**
* Forces WaitForData() to return immediately.
*/
- void WakeupWaitForData();
+ static void WakeupWaitForData();
/**
* Allows the user to specify whether they want joystick connection warnings
@@ -438,7 +431,7 @@
*
* @param silence Whether warning messages should be silenced.
*/
- void SilenceJoystickConnectionWarning(bool silence);
+ static void SilenceJoystickConnectionWarning(bool silence);
/**
* Returns whether joystick connection warnings are silenced. This will
@@ -446,68 +439,10 @@
*
* @return Whether joystick connection warnings are silenced.
*/
- bool IsJoystickConnectionWarningSilenced() const;
-
- protected:
- /**
- * Copy data from the DS task for the user.
- *
- * If no new data exists, it will just be returned, otherwise
- * the data will be copied from the DS polling loop.
- */
- void GetData();
+ static bool IsJoystickConnectionWarningSilenced();
private:
- /**
- * DriverStation constructor.
- *
- * This is only called once the first time GetInstance() is called
- */
- DriverStation();
-
- /**
- * Reports errors related to unplugged joysticks.
- *
- * Throttles the errors so that they don't overwhelm the DS.
- */
- void ReportJoystickUnpluggedError(const wpi::Twine& message);
-
- /**
- * Reports errors related to unplugged joysticks.
- *
- * Throttles the errors so that they don't overwhelm the DS.
- */
- void ReportJoystickUnpluggedWarning(const wpi::Twine& message);
-
- void Run();
-
- void SendMatchData();
-
- std::unique_ptr<MatchDataSender> m_matchDataSender;
-
- // Joystick button rising/falling edge flags
- wpi::mutex m_buttonEdgeMutex;
- std::array<HAL_JoystickButtons, kJoystickPorts> m_previousButtonStates;
- std::array<uint32_t, kJoystickPorts> m_joystickButtonsPressed;
- std::array<uint32_t, kJoystickPorts> m_joystickButtonsReleased;
-
- // Internal Driver Station thread
- std::thread m_dsThread;
- std::atomic<bool> m_isRunning{false};
-
- mutable wpi::mutex m_waitForDataMutex;
- wpi::condition_variable m_waitForDataCond;
- int m_waitForDataCounter;
-
- bool m_silenceJoystickWarning = false;
-
- // Robot state status variables
- bool m_userInDisabled = false;
- bool m_userInAutonomous = false;
- bool m_userInTeleop = false;
- bool m_userInTest = false;
-
- double m_nextMessageTime = 0;
+ DriverStation() = default;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/DutyCycle.h b/wpilibc/src/main/native/include/frc/DutyCycle.h
index f0fc2d8..7f45d06 100644
--- a/wpilibc/src/main/native/include/frc/DutyCycle.h
+++ b/wpilibc/src/main/native/include/frc/DutyCycle.h
@@ -1,19 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Types.h>
-
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
namespace frc {
class DigitalSource;
@@ -32,9 +27,7 @@
* order to implement rollover checking.
*
*/
-class DutyCycle : public ErrorBase,
- public Sendable,
- public SendableHelper<DutyCycle> {
+class DutyCycle : public wpi::Sendable, public wpi::SendableHelper<DutyCycle> {
friend class AnalogTrigger;
friend class DMA;
friend class DMASample;
@@ -125,7 +118,7 @@
int GetSourceChannel() const;
protected:
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
void InitDutyCycle();
diff --git a/wpilibc/src/main/native/include/frc/DutyCycleEncoder.h b/wpilibc/src/main/native/include/frc/DutyCycleEncoder.h
index 17b038f..ccf56ad 100644
--- a/wpilibc/src/main/native/include/frc/DutyCycleEncoder.h
+++ b/wpilibc/src/main/native/include/frc/DutyCycleEncoder.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -12,12 +9,11 @@
#include <hal/SimDevice.h>
#include <hal/Types.h>
#include <units/angle.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/AnalogTrigger.h"
#include "frc/Counter.h"
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
class DutyCycle;
@@ -28,9 +24,8 @@
* PWM Output, the CTRE Mag Encoder, the Rev Hex Encoder, and the AM Mag
* Encoder.
*/
-class DutyCycleEncoder : public ErrorBase,
- public Sendable,
- public SendableHelper<DutyCycleEncoder> {
+class DutyCycleEncoder : public wpi::Sendable,
+ public wpi::SendableHelper<DutyCycleEncoder> {
public:
/**
* Construct a new DutyCycleEncoder on a specific channel.
@@ -63,21 +58,21 @@
/**
* Construct a new DutyCycleEncoder attached to a DigitalSource object.
*
- * @param source the digital source to attach to
+ * @param digitalSource the digital source to attach to
*/
explicit DutyCycleEncoder(DigitalSource& digitalSource);
/**
* Construct a new DutyCycleEncoder attached to a DigitalSource object.
*
- * @param source the digital source to attach to
+ * @param digitalSource the digital source to attach to
*/
explicit DutyCycleEncoder(DigitalSource* digitalSource);
/**
* Construct a new DutyCycleEncoder attached to a DigitalSource object.
*
- * @param source the digital source to attach to
+ * @param digitalSource the digital source to attach to
*/
explicit DutyCycleEncoder(std::shared_ptr<DigitalSource> digitalSource);
@@ -168,7 +163,7 @@
*/
int GetSourceChannel() const;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
void Init();
diff --git a/wpilibc/src/main/native/include/frc/Encoder.h b/wpilibc/src/main/native/include/frc/Encoder.h
index 76f9d1c..f6753c2 100644
--- a/wpilibc/src/main/native/include/frc/Encoder.h
+++ b/wpilibc/src/main/native/include/frc/Encoder.h
@@ -1,28 +1,23 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <hal/Types.h>
+#include <wpi/deprecated.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/Counter.h"
#include "frc/CounterBase.h"
-#include "frc/ErrorBase.h"
-#include "frc/PIDSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
class DigitalSource;
class DigitalGlitchFilter;
-class SendableBuilder;
class DMA;
class DMASample;
@@ -41,11 +36,9 @@
* All encoders will immediately start counting - Reset() them if you need them
* to be zeroed before use.
*/
-class Encoder : public ErrorBase,
- public CounterBase,
- public PIDSource,
- public Sendable,
- public SendableHelper<Encoder> {
+class Encoder : public CounterBase,
+ public wpi::Sendable,
+ public wpi::SendableHelper<Encoder> {
friend class DMA;
friend class DMASample;
@@ -174,7 +167,7 @@
*
* @return Period in seconds of the most recent pulse.
*/
- double GetPeriod() const override;
+ units::second_t GetPeriod() const override;
/**
* Sets the maximum period for stopped detection.
@@ -195,7 +188,7 @@
WPI_DEPRECATED(
"Use SetMinRate() in favor of this method. This takes unscaled periods "
"and SetMinRate() scales using value from SetDistancePerPulse().")
- void SetMaxPeriod(double maxPeriod) override;
+ void SetMaxPeriod(units::second_t maxPeriod) override;
/**
* Determine if the encoder is stopped.
@@ -317,8 +310,6 @@
*/
int GetSamplesToAverage() const;
- double PIDGet() override;
-
/**
* Set the index source for the encoder.
*
@@ -334,8 +325,8 @@
*
* When this source is activated, the encoder count automatically resets.
*
- * @param channel A digital source to set as the encoder index
- * @param type The state that will cause the encoder to reset
+ * @param source A digital source to set as the encoder index
+ * @param type The state that will cause the encoder to reset
*/
void SetIndexSource(const DigitalSource& source,
IndexingType type = kResetOnRisingEdge);
@@ -349,7 +340,7 @@
int GetFPGAIndex() const;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
/**
diff --git a/wpilibc/src/main/native/include/frc/Error.h b/wpilibc/src/main/native/include/frc/Error.h
deleted file mode 100644
index d63fb62..0000000
--- a/wpilibc/src/main/native/include/frc/Error.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <string>
-
-#include <wpi/StringRef.h>
-#include <wpi/Twine.h>
-
-#ifdef _WIN32
-#pragma push_macro("GetMessage")
-#undef GetMessage
-#endif
-
-namespace frc {
-
-class ErrorBase;
-
-/**
- * Error object represents a library error.
- */
-class Error {
- public:
- using Code = int;
-
- Error() = default;
- Error(Code code, const wpi::Twine& contextMessage, wpi::StringRef filename,
- wpi::StringRef function, int lineNumber,
- const ErrorBase* originatingObject);
-
- bool operator<(const Error& rhs) const;
-
- Code GetCode() const;
- std::string GetMessage() const;
- std::string GetFilename() const;
- std::string GetFunction() const;
- int GetLineNumber() const;
- const ErrorBase* GetOriginatingObject() const;
- double GetTimestamp() const;
- void Clear();
- void Set(Code code, const wpi::Twine& contextMessage, wpi::StringRef filename,
- wpi::StringRef function, int lineNumber,
- const ErrorBase* originatingObject);
-
- private:
- void Report();
-
- Code m_code = 0;
- std::string m_message;
- std::string m_filename;
- std::string m_function;
- int m_lineNumber = 0;
- const ErrorBase* m_originatingObject = nullptr;
- double m_timestamp = 0.0;
-};
-
-} // namespace frc
-
-#ifdef _WIN32
-#pragma pop_macro("GetMessage")
-#endif
diff --git a/wpilibc/src/main/native/include/frc/ErrorBase.h b/wpilibc/src/main/native/include/frc/ErrorBase.h
deleted file mode 100644
index 0ced9a2..0000000
--- a/wpilibc/src/main/native/include/frc/ErrorBase.h
+++ /dev/null
@@ -1,242 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <vector>
-
-#include <wpi/StringRef.h>
-#include <wpi/Twine.h>
-
-#include "frc/Error.h"
-
-// Forward declared manually to avoid needing to pull in entire HAL header.
-extern "C" const char* HAL_GetErrorMessage(int32_t code);
-
-#define wpi_setErrnoErrorWithContext(context) \
- this->SetErrnoError((context), __FILE__, __FUNCTION__, __LINE__)
-#define wpi_setErrnoError() wpi_setErrnoErrorWithContext("")
-#define wpi_setImaqErrorWithContext(code, context) \
- do { \
- if ((code) != 0) \
- this->SetImaqError((code), (context), __FILE__, __FUNCTION__, __LINE__); \
- } while (0)
-#define wpi_setErrorWithContext(code, context) \
- do { \
- if ((code) != 0) \
- this->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__); \
- } while (0)
-#define wpi_setErrorWithContextRange(code, min, max, req, context) \
- do { \
- if ((code) != 0) \
- this->SetErrorRange((code), (min), (max), (req), (context), __FILE__, \
- __FUNCTION__, __LINE__); \
- } while (0)
-
-#define wpi_setHALError(code) \
- do { \
- if ((code) != 0) \
- this->SetError((code), HAL_GetErrorMessage(code), __FILE__, \
- __FUNCTION__, __LINE__); \
- } while (0)
-
-#define wpi_setHALErrorWithRange(code, min, max, req) \
- do { \
- if ((code) != 0) \
- this->SetErrorRange((code), (min), (max), (req), \
- HAL_GetErrorMessage(code), __FILE__, __FUNCTION__, \
- __LINE__); \
- } while (0)
-
-#define wpi_setError(code) wpi_setErrorWithContext(code, "")
-#define wpi_setStaticErrorWithContext(object, code, context) \
- do { \
- if ((code) != 0) \
- object->SetError((code), (context), __FILE__, __FUNCTION__, __LINE__); \
- } while (0)
-#define wpi_setStaticError(object, code) \
- wpi_setStaticErrorWithContext(object, code, "")
-
-#define wpi_setGlobalErrorWithContext(code, context) \
- do { \
- if ((code) != 0) \
- ::frc::ErrorBase::SetGlobalError((code), (context), __FILE__, \
- __FUNCTION__, __LINE__); \
- } while (0)
-
-#define wpi_setGlobalHALError(code) \
- do { \
- if ((code) != 0) \
- ::frc::ErrorBase::SetGlobalError((code), HAL_GetErrorMessage(code), \
- __FILE__, __FUNCTION__, __LINE__); \
- } while (0)
-
-#define wpi_setGlobalError(code) wpi_setGlobalErrorWithContext(code, "")
-#define wpi_setWPIErrorWithContext(error, context) \
- this->SetWPIError(wpi_error_s_##error(), wpi_error_value_##error(), \
- (context), __FILE__, __FUNCTION__, __LINE__)
-#define wpi_setWPIError(error) (wpi_setWPIErrorWithContext(error, ""))
-#define wpi_setStaticWPIErrorWithContext(object, error, context) \
- object->SetWPIError(wpi_error_s_##error(), (context), __FILE__, \
- __FUNCTION__, __LINE__)
-#define wpi_setStaticWPIError(object, error) \
- wpi_setStaticWPIErrorWithContext(object, error, "")
-#define wpi_setGlobalWPIErrorWithContext(error, context) \
- ::frc::ErrorBase::SetGlobalWPIError(wpi_error_s_##error(), (context), \
- __FILE__, __FUNCTION__, __LINE__)
-#define wpi_setGlobalWPIError(error) wpi_setGlobalWPIErrorWithContext(error, "")
-
-namespace frc {
-
-/**
- * Base class for most objects.
- *
- * ErrorBase is the base class for most objects since it holds the generated
- * error for that object. In addition, there is a single instance of a global
- * error object.
- */
-class ErrorBase {
- // TODO: Consider initializing instance variables and cleanup in destructor
- public:
- ErrorBase();
- virtual ~ErrorBase() = default;
-
- ErrorBase(const ErrorBase&) = default;
- ErrorBase& operator=(const ErrorBase&) = default;
- ErrorBase(ErrorBase&&) = default;
- ErrorBase& operator=(ErrorBase&&) = default;
-
- /**
- * @brief Retrieve the current error.
- *
- * Get the current error information associated with this sensor.
- */
- virtual Error& GetError();
-
- /**
- * @brief Retrieve the current error.
- *
- * Get the current error information associated with this sensor.
- */
- virtual const Error& GetError() const;
-
- /**
- * @brief Clear the current error information associated with this sensor.
- */
- virtual void ClearError() const;
-
- /**
- * @brief Set error information associated with a C library call that set an
- * error to the "errno" global variable.
- *
- * @param contextMessage A custom message from the code that set the error.
- * @param filename Filename of the error source
- * @param function Function of the error source
- * @param lineNumber Line number of the error source
- */
- virtual void SetErrnoError(const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const;
-
- /**
- * @brief Set the current error information associated from the nivision Imaq
- * API.
- *
- * @param success The return from the function
- * @param contextMessage A custom message from the code that set the error.
- * @param filename Filename of the error source
- * @param function Function of the error source
- * @param lineNumber Line number of the error source
- */
- virtual void SetImaqError(int success, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const;
-
- /**
- * @brief Set the current error information associated with this sensor.
- *
- * @param code The error code
- * @param contextMessage A custom message from the code that set the error.
- * @param filename Filename of the error source
- * @param function Function of the error source
- * @param lineNumber Line number of the error source
- */
- virtual void SetError(Error::Code code, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const;
-
- /**
- * @brief Set the current error information associated with this sensor.
- * Range versions use for initialization code.
- *
- * @param code The error code
- * @param minRange The minimum allowed allocation range
- * @param maxRange The maximum allowed allocation range
- * @param requestedValue The requested value to allocate
- * @param contextMessage A custom message from the code that set the error.
- * @param filename Filename of the error source
- * @param function Function of the error source
- * @param lineNumber Line number of the error source
- */
- virtual void SetErrorRange(Error::Code code, int32_t minRange,
- int32_t maxRange, int32_t requestedValue,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const;
-
- /**
- * @brief Set the current error information associated with this sensor.
- *
- * @param errorMessage The error message from WPIErrors.h
- * @param contextMessage A custom message from the code that set the error.
- * @param filename Filename of the error source
- * @param function Function of the error source
- * @param lineNumber Line number of the error source
- */
- virtual void SetWPIError(const wpi::Twine& errorMessage, Error::Code code,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber) const;
-
- virtual void CloneError(const ErrorBase& rhs) const;
-
- /**
- * @brief Check if the current error code represents a fatal error.
- *
- * @return true if the current error is fatal.
- */
- virtual bool StatusIsFatal() const;
-
- static void SetGlobalError(Error::Code code, const wpi::Twine& contextMessage,
- wpi::StringRef filename, wpi::StringRef function,
- int lineNumber);
-
- static void SetGlobalWPIError(const wpi::Twine& errorMessage,
- const wpi::Twine& contextMessage,
- wpi::StringRef filename,
- wpi::StringRef function, int lineNumber);
-
- /**
- * Retrieve the last global error.
- */
- static Error GetGlobalError();
-
- /**
- * Retrieve all global errors.
- */
- static std::vector<Error> GetGlobalErrors();
-
- /**
- * Clear global errors.
- */
- void ClearGlobalErrors();
-
- protected:
- mutable Error m_error;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Errors.h b/wpilibc/src/main/native/include/frc/Errors.h
new file mode 100644
index 0000000..84edc18
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/Errors.h
@@ -0,0 +1,177 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <stdint.h>
+
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+#include <fmt/format.h>
+
+namespace frc {
+
+/**
+ * Runtime error exception.
+ */
+class RuntimeError : public std::runtime_error {
+ public:
+ RuntimeError(int32_t code, std::string&& loc, std::string&& stack,
+ std::string&& message);
+ RuntimeError(int32_t code, const char* fileName, int lineNumber,
+ const char* funcName, std::string&& stack,
+ std::string&& message);
+
+ int32_t code() const noexcept { return m_data->code; }
+ const char* loc() const noexcept { return m_data->loc.c_str(); }
+ const char* stack() const noexcept { return m_data->stack.c_str(); }
+
+ /**
+ * Reports error to Driver Station (using HAL_SendError).
+ */
+ void Report() const;
+
+ private:
+ struct Data {
+ int32_t code;
+ std::string loc;
+ std::string stack;
+ };
+ std::shared_ptr<Data> m_data;
+};
+
+/**
+ * Gets error message string for an error code.
+ */
+const char* GetErrorMessage(int32_t* code);
+
+/**
+ * Reports an error to the driver station (using HAL_SendError).
+ * Generally the FRC_ReportError wrapper macro should be used instead.
+ *
+ * @param[out] status error code
+ * @param[in] fileName source file name
+ * @param[in] lineNumber source line number
+ * @param[in] funcName source function name
+ * @param[in] format error message format
+ * @param[in] args error message format args
+ */
+void ReportErrorV(int32_t status, const char* fileName, int lineNumber,
+ const char* funcName, fmt::string_view format,
+ fmt::format_args args);
+
+/**
+ * Reports an error to the driver station (using HAL_SendError).
+ * Generally the FRC_ReportError wrapper macro should be used instead.
+ *
+ * @param[out] status error code
+ * @param[in] fileName source file name
+ * @param[in] lineNumber source line number
+ * @param[in] funcName source function name
+ * @param[in] format error message format
+ * @param[in] args error message format args
+ */
+template <typename S, typename... Args>
+inline void ReportError(int32_t status, const char* fileName, int lineNumber,
+ const char* funcName, const S& format, Args&&... args) {
+ ReportErrorV(status, fileName, lineNumber, funcName, format,
+ fmt::make_args_checked<Args...>(format, args...));
+}
+
+/**
+ * Makes a runtime error exception object. This object should be thrown
+ * by the caller. Generally the FRC_MakeError wrapper macro should be used
+ * instead.
+ *
+ * @param[out] status error code
+ * @param[in] fileName source file name
+ * @param[in] lineNumber source line number
+ * @param[in] funcName source function name
+ * @param[in] format error message format
+ * @param[in] args error message format args
+ * @return runtime error object
+ */
+[[nodiscard]] RuntimeError MakeErrorV(int32_t status, const char* fileName,
+ int lineNumber, const char* funcName,
+ fmt::string_view format,
+ fmt::format_args args);
+
+template <typename S, typename... Args>
+[[nodiscard]] inline RuntimeError MakeError(int32_t status,
+ const char* fileName,
+ int lineNumber,
+ const char* funcName,
+ const S& format, Args&&... args) {
+ return MakeErrorV(status, fileName, lineNumber, funcName, format,
+ fmt::make_args_checked<Args...>(format, args...));
+}
+
+namespace err {
+#define S(label, offset, message) inline constexpr int label = offset;
+#include "frc/WPIErrors.mac"
+#undef S
+} // namespace err
+
+namespace warn {
+#define S(label, offset, message) inline constexpr int label = offset;
+#include "frc/WPIWarnings.mac"
+#undef S
+} // namespace warn
+} // namespace frc
+
+/**
+ * Reports an error to the driver station (using HAL_SendError).
+ *
+ * @param[out] status error code
+ * @param[in] format error message format
+ */
+#define FRC_ReportError(status, format, ...) \
+ do { \
+ if ((status) != 0) { \
+ ::frc::ReportError(status, __FILE__, __LINE__, __FUNCTION__, \
+ FMT_STRING(format), __VA_ARGS__); \
+ } \
+ } while (0)
+
+/**
+ * Makes a runtime error exception object. This object should be thrown
+ * by the caller.
+ *
+ * @param[out] status error code
+ * @param[in] format error message format
+ * @return runtime error object
+ */
+#define FRC_MakeError(status, format, ...) \
+ ::frc::MakeError(status, __FILE__, __LINE__, __FUNCTION__, \
+ FMT_STRING(format), __VA_ARGS__)
+
+/**
+ * Checks a status code and depending on its value, either throws a
+ * RuntimeError exception, calls ReportError, or does nothing (if no error).
+ *
+ * @param[out] status error code
+ * @param[in] format error message format
+ */
+#define FRC_CheckErrorStatus(status, format, ...) \
+ do { \
+ if ((status) < 0) { \
+ throw ::frc::MakeError(status, __FILE__, __LINE__, __FUNCTION__, \
+ FMT_STRING(format), __VA_ARGS__); \
+ } else if ((status) > 0) { \
+ ::frc::ReportError(status, __FILE__, __LINE__, __FUNCTION__, \
+ FMT_STRING(format), __VA_ARGS__); \
+ } \
+ } while (0)
+
+#define FRC_AssertMessage(condition, format, ...) \
+ do { \
+ if (!(condition)) { \
+ throw ::frc::MakeError(err::AssertionFailure, __FILE__, __LINE__, \
+ __FUNCTION__, FMT_STRING(format), __VA_ARGS__); \
+ } \
+ } while (0)
+
+#define FRC_Assert(condition) FRC_AssertMessage(condition, "{}", #condition)
diff --git a/wpilibc/src/main/native/include/frc/Filesystem.h b/wpilibc/src/main/native/include/frc/Filesystem.h
index f196f7a..fbfc681 100644
--- a/wpilibc/src/main/native/include/frc/Filesystem.h
+++ b/wpilibc/src/main/native/include/frc/Filesystem.h
@@ -1,34 +1,30 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/SmallVector.h>
+#include <string>
-namespace frc {
/** WPILib FileSystem namespace */
-namespace filesystem {
+namespace frc::filesystem {
/**
* Obtains the current working path that the program was launched with.
* This is analogous to the `pwd` command on unix.
*
- * @param result The result of the current working path lookup.
+ * @return The result of the current working path lookup.
*/
-void GetLaunchDirectory(wpi::SmallVectorImpl<char>& result);
+std::string GetLaunchDirectory();
/**
* Obtains the operating directory of the program. On the roboRIO, this
* is /home/lvuser. In simulation, it is where the simulation was launched
* from (`pwd`).
*
- * @param result The result of the operating directory lookup.
+ * @return The result of the operating directory lookup.
*/
-void GetOperatingDirectory(wpi::SmallVectorImpl<char>& result);
+std::string GetOperatingDirectory();
/**
* Obtains the deploy directory of the program, which is the remote location
@@ -36,9 +32,8 @@
* /home/lvuser/deploy. In simulation, it is where the simulation was launched
* from, in the subdirectory "src/main/deploy" (`pwd`/src/main/deploy).
*
- * @param result The result of the operating directory lookup
+ * @return The result of the operating directory lookup
*/
-void GetDeployDirectory(wpi::SmallVectorImpl<char>& result);
+std::string GetDeployDirectory();
-} // namespace filesystem
-} // namespace frc
+} // namespace frc::filesystem
diff --git a/wpilibc/src/main/native/include/frc/GearTooth.h b/wpilibc/src/main/native/include/frc/GearTooth.h
deleted file mode 100644
index 2d1f792..0000000
--- a/wpilibc/src/main/native/include/frc/GearTooth.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-#include <string>
-
-#include <wpi/deprecated.h>
-
-#include "frc/Counter.h"
-
-namespace frc {
-
-/**
- * Alias for counter class.
- *
- * Implements the gear tooth sensor supplied by FIRST. Currently there is no
- * reverse sensing on the gear tooth sensor, but in future versions we might
- * implement the necessary timing in the FPGA to sense direction.
- *
- * @deprecated No longer used per FMS usage reporting
- */
-class GearTooth : public Counter {
- public:
- // 55 uSec for threshold
- static constexpr double kGearToothThreshold = 55e-6;
-
- /**
- * Construct a GearTooth sensor given a channel.
- *
- * @param channel The DIO channel that the sensor is connected to.
- * 0-9 are on-board, 10-25 are on the MXP.
- * @param directionSensitive True to enable the pulse length decoding in
- * hardware to specify count direction.
- */
- WPI_DEPRECATED(
- "The only sensor this works with is no longer available and no teams use "
- "it according to FMS usage reporting.")
- explicit GearTooth(int channel, bool directionSensitive = false);
-
- /**
- * Construct a GearTooth sensor given a digital input.
- *
- * This should be used when sharing digital inputs.
- *
- * @param source A pointer to the existing DigitalSource object
- * (such as a DigitalInput)
- * @param directionSensitive True to enable the pulse length decoding in
- * hardware to specify count direction.
- */
- WPI_DEPRECATED(
- "The only sensor this works with is no longer available and no teams use "
- "it according to FMS usage reporting.")
- explicit GearTooth(DigitalSource* source, bool directionSensitive = false);
-
- /**
- * Construct a GearTooth sensor given a digital input.
- *
- * This should be used when sharing digital inputs.
- *
- * @param source A reference to the existing DigitalSource object
- * (such as a DigitalInput)
- * @param directionSensitive True to enable the pulse length decoding in
- * hardware to specify count direction.
- */
- WPI_DEPRECATED(
- "The only sensor this works with is no longer available and no teams use "
- "it according to FMS usage reporting.")
- explicit GearTooth(std::shared_ptr<DigitalSource> source,
- bool directionSensitive = false);
-
- GearTooth(GearTooth&&) = default;
- GearTooth& operator=(GearTooth&&) = default;
-
- /**
- * Common code called by the constructors.
- */
- void EnableDirectionSensing(bool directionSensitive);
-
- void InitSendable(SendableBuilder& builder) override;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/GenericHID.h b/wpilibc/src/main/native/include/frc/GenericHID.h
index 001b984..b6c18d3 100644
--- a/wpilibc/src/main/native/include/frc/GenericHID.h
+++ b/wpilibc/src/main/native/include/frc/GenericHID.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -11,16 +8,19 @@
#include <string>
-#include "frc/ErrorBase.h"
-
namespace frc {
class DriverStation;
/**
- * GenericHID Interface.
+ * Handle input from standard HID devices connected to the Driver Station.
+ *
+ * <p>This class handles standard input that comes from the Driver Station. Each
+ * time a value is requested the most recent value is returned. There is a
+ * single class instance for each device and the mapping of ports to hardware
+ * buttons depends on the code in the Driver Station.
*/
-class GenericHID : public ErrorBase {
+class GenericHID {
public:
enum RumbleType { kLeftRumble, kRightRumble };
@@ -44,17 +44,12 @@
kHID1stPerson = 24
};
- enum JoystickHand { kLeftHand = 0, kRightHand = 1 };
-
explicit GenericHID(int port);
virtual ~GenericHID() = default;
GenericHID(GenericHID&&) = default;
GenericHID& operator=(GenericHID&&) = default;
- virtual double GetX(JoystickHand hand = kRightHand) const = 0;
- virtual double GetY(JoystickHand hand = kRightHand) const = 0;
-
/**
* Get the button value (starting at button 1).
*
@@ -71,7 +66,7 @@
bool GetRawButton(int button) const;
/**
- * Whether the button was pressed since the last check. Button indexes begin
+ * Whether the button was pressed since the last check. %Button indexes begin
* at 1.
*
* This method returns true if the button went from not pressed to held down
@@ -84,7 +79,7 @@
bool GetRawButtonPressed(int button);
/**
- * Whether the button was released since the last check. Button indexes begin
+ * Whether the button was released since the last check. %Button indexes begin
* at 1.
*
* This method returns true if the button went from held down to not pressed
@@ -197,7 +192,6 @@
void SetRumble(RumbleType type, double value);
private:
- DriverStation* m_ds;
int m_port;
int m_outputs = 0;
uint16_t m_leftRumble = 0;
diff --git a/wpilibc/src/main/native/include/frc/GyroBase.h b/wpilibc/src/main/native/include/frc/GyroBase.h
deleted file mode 100644
index 037686f..0000000
--- a/wpilibc/src/main/native/include/frc/GyroBase.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/ErrorBase.h"
-#include "frc/PIDSource.h"
-#include "frc/interfaces/Gyro.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
-
-namespace frc {
-
-/**
- * GyroBase is the common base class for Gyro implementations such as
- * AnalogGyro.
- */
-class GyroBase : public Gyro,
- public ErrorBase,
- public PIDSource,
- public Sendable,
- public SendableHelper<GyroBase> {
- public:
- GyroBase() = default;
- GyroBase(GyroBase&&) = default;
- GyroBase& operator=(GyroBase&&) = default;
-
- // PIDSource interface
- /**
- * Get the PIDOutput for the PIDSource base object. Can be set to return
- * angle or rate using SetPIDSourceType(). Defaults to angle.
- *
- * @return The PIDOutput (angle or rate, defaults to angle)
- */
- double PIDGet() override;
-
- void InitSendable(SendableBuilder& builder) override;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/I2C.h b/wpilibc/src/main/native/include/frc/I2C.h
index 2f12615..d874a46 100644
--- a/wpilibc/src/main/native/include/frc/I2C.h
+++ b/wpilibc/src/main/native/include/frc/I2C.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -11,8 +8,6 @@
#include <hal/I2CTypes.h>
-#include "frc/ErrorBase.h"
-
namespace frc {
/**
@@ -21,7 +16,7 @@
* This class is intended to be used by sensor (and other I2C device) drivers.
* It probably should not be used directly.
*/
-class I2C : public ErrorBase {
+class I2C {
public:
enum Port { kOnboard = 0, kMXP };
@@ -33,11 +28,14 @@
*/
I2C(Port port, int deviceAddress);
- ~I2C() override;
+ ~I2C();
I2C(I2C&&) = default;
I2C& operator=(I2C&&) = default;
+ Port GetPort() const;
+ int GetDeviceAddress() const;
+
/**
* Generic transaction.
*
@@ -100,7 +98,7 @@
*
* @param registerAddress The register to read first in the transaction.
* @param count The number of bytes to read in the transaction.
- * @param buffer A pointer to the array of bytes to store the data
+ * @param data A pointer to the array of bytes to store the data
* read from the device.
* @return Transfer Aborted... false for success, true for aborted.
*/
diff --git a/wpilibc/src/main/native/include/frc/InterruptableSensorBase.h b/wpilibc/src/main/native/include/frc/InterruptableSensorBase.h
deleted file mode 100644
index 42b7434..0000000
--- a/wpilibc/src/main/native/include/frc/InterruptableSensorBase.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <functional>
-#include <memory>
-
-#include <hal/Interrupts.h>
-
-#include "frc/AnalogTriggerType.h"
-#include "frc/ErrorBase.h"
-
-namespace frc {
-
-class InterruptableSensorBase : public ErrorBase {
- public:
- enum WaitResult {
- kTimeout = 0x0,
- kRisingEdge = 0x1,
- kFallingEdge = 0x100,
- kBoth = 0x101,
- };
-
- /**
- * Handler for interrupts.
- *
- * First parameter is if rising, 2nd is if falling.
- */
- using InterruptEventHandler = std::function<void(WaitResult)>;
-
- InterruptableSensorBase() = default;
-
- /**
- * Free the resources for an interrupt event.
- */
- virtual ~InterruptableSensorBase();
-
- InterruptableSensorBase(InterruptableSensorBase&&) = default;
- InterruptableSensorBase& operator=(InterruptableSensorBase&&) = default;
-
- virtual HAL_Handle GetPortHandleForRouting() const = 0;
- virtual AnalogTriggerType GetAnalogTriggerTypeForRouting() const = 0;
-
- /**
- * Request one of the 8 interrupts asynchronously on this digital input.
- *
- * Request interrupts in asynchronous mode where the user's interrupt handler
- * will be called when the interrupt fires. Users that want control over the
- * thread priority should use the synchronous method with their own spawned
- * thread. The default is interrupt on rising edges only.
- */
- virtual void RequestInterrupts(HAL_InterruptHandlerFunction handler,
- void* param);
-
- /**
- * Request one of the 8 interrupts asynchronously on this digital input.
- *
- * Request interrupts in asynchronous mode where the user's interrupt handler
- * will be called when the interrupt fires. Users that want control over the
- * thread priority should use the synchronous method with their own spawned
- * thread. The default is interrupt on rising edges only.
- */
- virtual void RequestInterrupts(InterruptEventHandler handler);
-
- /**
- * Request one of the 8 interrupts synchronously on this digital input.
- *
- * Request interrupts in synchronous mode where the user program will have to
- * explicitly wait for the interrupt to occur using WaitForInterrupt.
- * The default is interrupt on rising edges only.
- */
- virtual void RequestInterrupts();
-
- /**
- * Cancel interrupts on this device.
- *
- * This deallocates all the chipobject structures and disables any interrupts.
- */
- virtual void CancelInterrupts();
-
- /**
- * In synchronous mode, wait for the defined interrupt to occur.
- *
- * You should <b>NOT</b> attempt to read the sensor from another thread while
- * waiting for an interrupt. This is not threadsafe, and can cause memory
- * corruption
- *
- * @param timeout Timeout in seconds
- * @param ignorePrevious If true, ignore interrupts that happened before
- * WaitForInterrupt was called.
- * @return What interrupts fired
- */
- virtual WaitResult WaitForInterrupt(double timeout,
- bool ignorePrevious = true);
-
- /**
- * Enable interrupts to occur on this input.
- *
- * Interrupts are disabled when the RequestInterrupt call is made. This gives
- * time to do the setup of the other options before starting to field
- * interrupts.
- */
- virtual void EnableInterrupts();
-
- /**
- * Disable Interrupts without without deallocating structures.
- */
- virtual void DisableInterrupts();
-
- /**
- * Return the timestamp for the rising interrupt that occurred most recently.
- *
- * This is in the same time domain as GetClock(). The rising-edge interrupt
- * should be enabled with SetUpSourceEdge().
- *
- * @return Timestamp in seconds since boot.
- */
- virtual double ReadRisingTimestamp();
-
- /**
- * Return the timestamp for the falling interrupt that occurred most recently.
- *
- * This is in the same time domain as GetClock().
- * The falling-edge interrupt should be enabled with
- * {@link #DigitalInput.SetUpSourceEdge}
- *
- * @return Timestamp in seconds since boot.
- */
- virtual double ReadFallingTimestamp();
-
- /**
- * Set which edge to trigger interrupts on
- *
- * @param risingEdge true to interrupt on rising edge
- * @param fallingEdge true to interrupt on falling edge
- */
- virtual void SetUpSourceEdge(bool risingEdge, bool fallingEdge);
-
- protected:
- hal::Handle<HAL_InterruptHandle> m_interrupt;
- std::unique_ptr<InterruptEventHandler> m_interruptHandler{nullptr};
-
- void AllocateInterrupts(bool watcher);
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/IterativeRobot.h b/wpilibc/src/main/native/include/frc/IterativeRobot.h
deleted file mode 100644
index 24fdba3..0000000
--- a/wpilibc/src/main/native/include/frc/IterativeRobot.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <atomic>
-
-#include "frc/IterativeRobotBase.h"
-
-namespace frc {
-
-/**
- * IterativeRobot implements the IterativeRobotBase robot program framework.
- *
- * The IterativeRobot class is intended to be subclassed by a user creating a
- * robot program.
- *
- * Periodic() functions from the base class are called each time a new packet is
- * received from the driver station.
- *
- * @deprecated Use TimedRobot instead. It's a drop-in replacement that provides
- * more regular execution periods.
- */
-class IterativeRobot : public IterativeRobotBase {
- public:
- WPI_DEPRECATED(
- "Use TimedRobot instead. It's a drop-in replacement that provides more "
- "regular execution periods.")
- IterativeRobot();
- virtual ~IterativeRobot() = default;
-
- /**
- * Provide an alternate "main loop" via StartCompetition().
- *
- * This specific StartCompetition() implements "main loop" behavior synced
- * with the DS packets.
- */
- void StartCompetition() override;
-
- /**
- * Ends the main loop in StartCompetition().
- */
- void EndCompetition() override;
-
- private:
- std::atomic<bool> m_exit{false};
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/IterativeRobotBase.h b/wpilibc/src/main/native/include/frc/IterativeRobotBase.h
index 66897aa..c4253ef 100644
--- a/wpilibc/src/main/native/include/frc/IterativeRobotBase.h
+++ b/wpilibc/src/main/native/include/frc/IterativeRobotBase.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -28,22 +25,32 @@
* RobotInit() -- provide for initialization at robot power-on
*
* Init() functions -- each of the following functions is called once when the
- * appropriate mode is entered:
- * - DisabledInit() -- called each and every time disabled is entered from
- * another mode
- * - AutonomousInit() -- called each and every time autonomous is entered from
- * another mode
- * - TeleopInit() -- called each and every time teleop is entered from
- * another mode
- * - TestInit() -- called each and every time test is entered from
- * another mode
+ * appropriate mode is entered:
+ *
+ * \li DisabledInit() -- called each and every time disabled is entered from
+ * another mode
+ * \li AutonomousInit() -- called each and every time autonomous is entered from
+ * another mode
+ * \li TeleopInit() -- called each and every time teleop is entered from another
+ * mode
+ * \li TestInit() -- called each and every time test is entered from another
+ * mode
*
* Periodic() functions -- each of these functions is called on an interval:
- * - RobotPeriodic()
- * - DisabledPeriodic()
- * - AutonomousPeriodic()
- * - TeleopPeriodic()
- * - TestPeriodic()
+ *
+ * \li RobotPeriodic()
+ * \li DisabledPeriodic()
+ * \li AutonomousPeriodic()
+ * \li TeleopPeriodic()
+ * \li TestPeriodic()
+ *
+ * Exit() functions -- each of the following functions is called once when the
+ * appropriate mode is exited:
+ *
+ * \li DisabledExit() -- called each and every time disabled is exited
+ * \li AutonomousExit() -- called each and every time autonomous is exited
+ * \li TeleopExit() -- called each and every time teleop is exited
+ * \li TestExit() -- called each and every time test is exited
*/
class IterativeRobotBase : public RobotBase {
public:
@@ -156,6 +163,51 @@
virtual void TestPeriodic();
/**
+ * Exit code for disabled mode should go here.
+ *
+ * Users should override this method for code which will be called each time
+ * the robot exits disabled mode.
+ */
+ virtual void DisabledExit();
+
+ /**
+ * Exit code for autonomous mode should go here.
+ *
+ * Users should override this method for code which will be called each time
+ * the robot exits autonomous mode.
+ */
+ virtual void AutonomousExit();
+
+ /**
+ * Exit code for teleop mode should go here.
+ *
+ * Users should override this method for code which will be called each time
+ * the robot exits teleop mode.
+ */
+ virtual void TeleopExit();
+
+ /**
+ * Exit code for test mode should go here.
+ *
+ * Users should override this method for code which will be called each time
+ * the robot exits test mode.
+ */
+ virtual void TestExit();
+
+ /**
+ * Enables or disables flushing NetworkTables every loop iteration.
+ * By default, this is disabled.
+ *
+ * @param enabled True to enable, false to disable
+ */
+ void SetNetworkTablesFlushEnabled(bool enabled);
+
+ /**
+ * Gets time period between calls to Periodic() functions.
+ */
+ units::second_t GetPeriod() const;
+
+ /**
* Constructor for IterativeRobotBase.
*
* @param period Period in seconds.
@@ -173,7 +225,7 @@
*/
explicit IterativeRobotBase(units::second_t period);
- virtual ~IterativeRobotBase() = default;
+ ~IterativeRobotBase() override = default;
protected:
IterativeRobotBase(IterativeRobotBase&&) = default;
@@ -181,13 +233,13 @@
void LoopFunc();
- units::second_t m_period;
-
private:
enum class Mode { kNone, kDisabled, kAutonomous, kTeleop, kTest };
Mode m_lastMode = Mode::kNone;
+ units::second_t m_period;
Watchdog m_watchdog;
+ bool m_ntFlushEnabled = false;
void PrintLoopOverrunMessage();
};
diff --git a/wpilibc/src/main/native/include/frc/Joystick.h b/wpilibc/src/main/native/include/frc/Joystick.h
index 0975e6d..0d63e4e 100644
--- a/wpilibc/src/main/native/include/frc/Joystick.h
+++ b/wpilibc/src/main/native/include/frc/Joystick.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -42,7 +39,7 @@
*/
explicit Joystick(int port);
- virtual ~Joystick() = default;
+ ~Joystick() override = default;
Joystick(Joystick&&) = default;
Joystick& operator=(Joystick&&) = default;
@@ -57,7 +54,6 @@
/**
* Set the channel associated with the Y axis.
*
- * @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
void SetYChannel(int channel);
@@ -65,7 +61,6 @@
/**
* Set the channel associated with the Z axis.
*
- * @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
void SetZChannel(int channel);
@@ -73,7 +68,6 @@
/**
* Set the channel associated with the twist axis.
*
- * @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
void SetTwistChannel(int channel);
@@ -81,7 +75,6 @@
/**
* Set the channel associated with the throttle axis.
*
- * @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
void SetThrottleChannel(int channel);
@@ -122,24 +115,18 @@
int GetThrottleChannel() const;
/**
- * Get the X value of the joystick.
+ * Get the X value of the current joystick.
*
* This depends on the mapping of the joystick connected to the current port.
- *
- * @param hand This parameter is ignored for the Joystick class and is only
- * here to complete the GenericHID interface.
*/
- double GetX(JoystickHand hand = kRightHand) const override;
+ double GetX() const;
/**
- * Get the Y value of the joystick.
+ * Get the Y value of the current joystick.
*
* This depends on the mapping of the joystick connected to the current port.
- *
- * @param hand This parameter is ignored for the Joystick class and is only
- * here to complete the GenericHID interface.
*/
- double GetY(JoystickHand hand = kRightHand) const override;
+ double GetY() const;
/**
* Get the Z value of the current joystick.
diff --git a/wpilibc/src/main/native/include/frc/MotorSafety.h b/wpilibc/src/main/native/include/frc/MotorSafety.h
index afd0853..f84af17 100644
--- a/wpilibc/src/main/native/include/frc/MotorSafety.h
+++ b/wpilibc/src/main/native/include/frc/MotorSafety.h
@@ -1,16 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/mutex.h>
-#include <wpi/raw_ostream.h>
+#include <string>
-#include "frc/ErrorBase.h"
+#include <units/time.h>
+#include <wpi/mutex.h>
+
#include "frc/Timer.h"
namespace frc {
@@ -21,7 +19,7 @@
*
* The subclass should call Feed() whenever the motor value is updated.
*/
-class MotorSafety : public ErrorBase {
+class MotorSafety {
public:
MotorSafety();
virtual ~MotorSafety();
@@ -39,16 +37,16 @@
/**
* Set the expiration time for the corresponding motor safety object.
*
- * @param expirationTime The timeout value in seconds.
+ * @param expirationTime The timeout value.
*/
- void SetExpiration(double expirationTime);
+ void SetExpiration(units::second_t expirationTime);
/**
* Retrieve the timeout value for the corresponding motor safety object.
*
- * @return the timeout value in seconds.
+ * @return the timeout value.
*/
- double GetExpiration() const;
+ units::second_t GetExpiration() const;
/**
* Determine if the motor is still operating or has timed out.
@@ -93,19 +91,19 @@
static void CheckMotors();
virtual void StopMotor() = 0;
- virtual void GetDescription(wpi::raw_ostream& desc) const = 0;
+ virtual std::string GetDescription() const = 0;
private:
- static constexpr double kDefaultSafetyExpiration = 0.1;
+ static constexpr auto kDefaultSafetyExpiration = 100_ms;
// The expiration time for this object
- double m_expiration = kDefaultSafetyExpiration;
+ units::second_t m_expiration = kDefaultSafetyExpiration;
// True if motor safety is enabled for this motor
bool m_enabled = false;
// The FPGA clock value when the motor has expired
- double m_stopTime = Timer::GetFPGATimestamp();
+ units::second_t m_stopTime = Timer::GetFPGATimestamp();
mutable wpi::mutex m_thisMutex;
};
diff --git a/wpilibc/src/main/native/include/frc/Notifier.h b/wpilibc/src/main/native/include/frc/Notifier.h
index c9348a6..61b7fbb 100644
--- a/wpilibc/src/main/native/include/frc/Notifier.h
+++ b/wpilibc/src/main/native/include/frc/Notifier.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -11,21 +8,18 @@
#include <atomic>
#include <functional>
+#include <string_view>
#include <thread>
#include <type_traits>
#include <utility>
#include <hal/Types.h>
#include <units/time.h>
-#include <wpi/Twine.h>
-#include <wpi/deprecated.h>
#include <wpi/mutex.h>
-#include "frc/ErrorBase.h"
-
namespace frc {
-class Notifier : public ErrorBase {
+class Notifier {
public:
/**
* Create a Notifier for timer event notification.
@@ -49,8 +43,9 @@
* This is useful for reducing scheduling jitter on processes which are
* sensitive to timing variance, like model-based control.
*
- * @param priority The FIFO real-time scheduler priority ([0..100] where a
- * lower number represents higher priority).
+ * @param priority The FIFO real-time scheduler priority ([1..99] where a
+ * higher number represents higher priority). See "man 7
+ * sched" for more details.
* @param handler The handler is called at the notification time which is set
* using StartSingle or StartPeriodic.
*/
@@ -65,7 +60,7 @@
/**
* Free the resources for a timer event.
*/
- virtual ~Notifier();
+ ~Notifier();
Notifier(Notifier&& rhs);
Notifier& operator=(Notifier&& rhs);
@@ -75,7 +70,7 @@
*
* @param name Name
*/
- void SetName(const wpi::Twine& name);
+ void SetName(std::string_view name);
/**
* Change the handler function.
@@ -89,19 +84,6 @@
*
* A timer event is queued for a single event after the specified delay.
*
- * @deprecated Use unit-safe StartSingle(units::second_t delay) method
- * instead.
- *
- * @param delay Seconds to wait before the handler is called.
- */
- WPI_DEPRECATED("Use unit-safe StartSingle method instead.")
- void StartSingle(double delay);
-
- /**
- * Register for single event notification.
- *
- * A timer event is queued for a single event after the specified delay.
- *
* @param delay Amount of time to wait before the handler is called.
*/
void StartSingle(units::second_t delay);
@@ -113,22 +95,6 @@
* interrupt occurs, the event will be immediately requeued for the same time
* interval.
*
- * @deprecated Use unit-safe StartPeriodic(units::second_t period) method
- * instead
- *
- * @param period Period in seconds to call the handler starting one period
- * after the call to this method.
- */
- WPI_DEPRECATED("Use unit-safe StartPeriodic method instead.")
- void StartPeriodic(double period);
-
- /**
- * Register for periodic event notification.
- *
- * A timer event is queued for periodic event notification. Each time the
- * interrupt occurs, the event will be immediately requeued for the same time
- * interval.
- *
* @param period Period to call the handler starting one period
* after the call to this method.
*/
@@ -145,6 +111,23 @@
*/
void Stop();
+ /**
+ * Sets the HAL notifier thread priority.
+ *
+ * The HAL notifier thread is responsible for managing the FPGA's notifier
+ * interrupt and waking up user's Notifiers when it's their time to run.
+ * Giving the HAL notifier thread real-time priority helps ensure the user's
+ * real-time Notifiers, if any, are notified to run in a timely manner.
+ *
+ * @param realTime Set to true to set a real-time priority, false for standard
+ * priority.
+ * @param priority Priority to set the thread to. For real-time, this is 1-99
+ * with 99 being highest. For non-real-time, this is forced to
+ * 0. See "man 7 sched" for more details.
+ * @return True on success.
+ */
+ static bool SetHALThreadPriority(bool realTime, int32_t priority);
+
private:
/**
* Update the HAL alarm time.
@@ -171,10 +154,10 @@
std::function<void()> m_handler;
// The absolute expiration time
- double m_expirationTime = 0;
+ units::second_t m_expirationTime = 0_s;
// The relative time (either periodic or single)
- double m_period = 0;
+ units::second_t m_period = 0_s;
// True if this is a periodic event
bool m_periodic = false;
diff --git a/wpilibc/src/main/native/include/frc/PIDBase.h b/wpilibc/src/main/native/include/frc/PIDBase.h
deleted file mode 100644
index 79d8eba..0000000
--- a/wpilibc/src/main/native/include/frc/PIDBase.h
+++ /dev/null
@@ -1,410 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-#include <string>
-
-#include <wpi/deprecated.h>
-#include <wpi/mutex.h>
-
-#include "frc/Base.h"
-#include "frc/LinearFilter.h"
-#include "frc/PIDInterface.h"
-#include "frc/PIDOutput.h"
-#include "frc/PIDSource.h"
-#include "frc/Timer.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
-
-namespace frc {
-
-class SendableBuilder;
-
-/**
- * Class implements a PID Control Loop.
- *
- * Creates a separate thread which reads the given PIDSource and takes care of
- * the integral calculations, as well as writing the given PIDOutput.
- *
- * This feedback controller runs in discrete time, so time deltas are not used
- * in the integral and derivative calculations. Therefore, the sample rate
- * affects the controller's behavior for a given set of PID constants.
- *
- * @deprecated All APIs which use this have been deprecated.
- */
-class PIDBase : public PIDInterface,
- public PIDOutput,
- public Sendable,
- public SendableHelper<PIDBase> {
- public:
- /**
- * Allocate a PID object with the given constants for P, I, D.
- *
- * @param Kp the proportional coefficient
- * @param Ki the integral coefficient
- * @param Kd the derivative coefficient
- * @param source The PIDSource object that is used to get values
- * @param output The PIDOutput object that is set to the output value
- */
- WPI_DEPRECATED("All APIs which use this have been deprecated.")
- PIDBase(double p, double i, double d, PIDSource& source, PIDOutput& output);
-
- /**
- * Allocate a PID object with the given constants for P, I, D.
- *
- * @param Kp the proportional coefficient
- * @param Ki the integral coefficient
- * @param Kd the derivative coefficient
- * @param source The PIDSource object that is used to get values
- * @param output The PIDOutput object that is set to the output value
- */
- WPI_DEPRECATED("All APIs which use this have been deprecated.")
- PIDBase(double p, double i, double d, double f, PIDSource& source,
- PIDOutput& output);
-
- virtual ~PIDBase() = default;
-
- /**
- * Return the current PID result.
- *
- * This is always centered on zero and constrained the the max and min outs.
- *
- * @return the latest calculated output
- */
- virtual double Get() const;
-
- /**
- * Set the PID controller to consider the input to be continuous,
- *
- * Rather then using the max and min input range as constraints, it considers
- * them to be the same point and automatically calculates the shortest route
- * to the setpoint.
- *
- * @param continuous true turns on continuous, false turns off continuous
- */
- virtual void SetContinuous(bool continuous = true);
-
- /**
- * Sets the maximum and minimum values expected from the input.
- *
- * @param minimumInput the minimum value expected from the input
- * @param maximumInput the maximum value expected from the output
- */
- virtual void SetInputRange(double minimumInput, double maximumInput);
-
- /**
- * Sets the minimum and maximum values to write.
- *
- * @param minimumOutput the minimum value to write to the output
- * @param maximumOutput the maximum value to write to the output
- */
- virtual void SetOutputRange(double minimumOutput, double maximumOutput);
-
- /**
- * Set the PID Controller gain parameters.
- *
- * Set the proportional, integral, and differential coefficients.
- *
- * @param p Proportional coefficient
- * @param i Integral coefficient
- * @param d Differential coefficient
- */
- void SetPID(double p, double i, double d) override;
-
- /**
- * Set the PID Controller gain parameters.
- *
- * Set the proportional, integral, and differential coefficients.
- *
- * @param p Proportional coefficient
- * @param i Integral coefficient
- * @param d Differential coefficient
- * @param f Feed forward coefficient
- */
- virtual void SetPID(double p, double i, double d, double f);
-
- /**
- * Set the Proportional coefficient of the PID controller gain.
- *
- * @param p proportional coefficient
- */
- void SetP(double p);
-
- /**
- * Set the Integral coefficient of the PID controller gain.
- *
- * @param i integral coefficient
- */
- void SetI(double i);
-
- /**
- * Set the Differential coefficient of the PID controller gain.
- *
- * @param d differential coefficient
- */
- void SetD(double d);
-
- /**
- * Get the Feed forward coefficient of the PID controller gain.
- *
- * @param f Feed forward coefficient
- */
- void SetF(double f);
-
- /**
- * Get the Proportional coefficient.
- *
- * @return proportional coefficient
- */
- double GetP() const override;
-
- /**
- * Get the Integral coefficient.
- *
- * @return integral coefficient
- */
- double GetI() const override;
-
- /**
- * Get the Differential coefficient.
- *
- * @return differential coefficient
- */
- double GetD() const override;
-
- /**
- * Get the Feed forward coefficient.
- *
- * @return Feed forward coefficient
- */
- virtual double GetF() const;
-
- /**
- * Set the setpoint for the PIDBase.
- *
- * @param setpoint the desired setpoint
- */
- void SetSetpoint(double setpoint) override;
-
- /**
- * Returns the current setpoint of the PIDBase.
- *
- * @return the current setpoint
- */
- double GetSetpoint() const override;
-
- /**
- * Returns the change in setpoint over time of the PIDBase.
- *
- * @return the change in setpoint over time
- */
- double GetDeltaSetpoint() const;
-
- /**
- * Returns the current difference of the input from the setpoint.
- *
- * @return the current error
- */
- virtual double GetError() const;
-
- /**
- * Returns the current average of the error over the past few iterations.
- *
- * You can specify the number of iterations to average with
- * SetToleranceBuffer() (defaults to 1). This is the same value that is used
- * for OnTarget().
- *
- * @return the average error
- */
- WPI_DEPRECATED("Use a LinearFilter as the input and GetError().")
- virtual double GetAvgError() const;
-
- /**
- * Sets what type of input the PID controller will use.
- */
- virtual void SetPIDSourceType(PIDSourceType pidSource);
-
- /**
- * Returns the type of input the PID controller is using.
- *
- * @return the PID controller input type
- */
- virtual PIDSourceType GetPIDSourceType() const;
-
- /**
- * Set the percentage error which is considered tolerable for use with
- * OnTarget.
- *
- * @param percentage error which is tolerable
- */
- WPI_DEPRECATED("Use SetPercentTolerance() instead.")
- virtual void SetTolerance(double percent);
-
- /**
- * Set the absolute error which is considered tolerable for use with
- * OnTarget.
- *
- * @param percentage error which is tolerable
- */
- virtual void SetAbsoluteTolerance(double absValue);
-
- /**
- * Set the percentage error which is considered tolerable for use with
- * OnTarget.
- *
- * @param percentage error which is tolerable
- */
- virtual void SetPercentTolerance(double percentValue);
-
- /**
- * Set the number of previous error samples to average for tolerancing. When
- * determining whether a mechanism is on target, the user may want to use a
- * rolling average of previous measurements instead of a precise position or
- * velocity. This is useful for noisy sensors which return a few erroneous
- * measurements when the mechanism is on target. However, the mechanism will
- * not register as on target for at least the specified bufLength cycles.
- *
- * @param bufLength Number of previous cycles to average. Defaults to 1.
- */
- WPI_DEPRECATED("Use a LinearDigitalFilter as the input.")
- virtual void SetToleranceBuffer(int buf = 1);
-
- /**
- * Return true if the error is within the percentage of the total input range,
- * determined by SetTolerance. This asssumes that the maximum and minimum
- * input were set using SetInput.
- *
- * Currently this just reports on target as the actual value passes through
- * the setpoint. Ideally it should be based on being within the tolerance for
- * some period of time.
- *
- * This will return false until at least one input value has been computed.
- */
- virtual bool OnTarget() const;
-
- /**
- * Reset the previous error, the integral term, and disable the controller.
- */
- void Reset() override;
-
- /**
- * Passes the output directly to SetSetpoint().
- *
- * PIDControllers can be nested by passing a PIDController as another
- * PIDController's output. In that case, the output of the parent controller
- * becomes the input (i.e., the reference) of the child.
- *
- * It is the caller's responsibility to put the data into a valid form for
- * SetSetpoint().
- */
- void PIDWrite(double output) override;
-
- void InitSendable(SendableBuilder& builder) override;
-
- protected:
- // Is the pid controller enabled
- bool m_enabled = false;
-
- mutable wpi::mutex m_thisMutex;
-
- // Ensures when Disable() is called, PIDWrite() won't run if Calculate()
- // is already running at that time.
- mutable wpi::mutex m_pidWriteMutex;
-
- PIDSource* m_pidInput;
- PIDOutput* m_pidOutput;
- Timer m_setpointTimer;
-
- /**
- * Read the input, calculate the output accordingly, and write to the output.
- * This should only be called by the Notifier.
- */
- virtual void Calculate();
-
- /**
- * Calculate the feed forward term.
- *
- * Both of the provided feed forward calculations are velocity feed forwards.
- * If a different feed forward calculation is desired, the user can override
- * this function and provide his or her own. This function does no
- * synchronization because the PIDBase class only calls it in synchronized
- * code, so be careful if calling it oneself.
- *
- * If a velocity PID controller is being used, the F term should be set to 1
- * over the maximum setpoint for the output. If a position PID controller is
- * being used, the F term should be set to 1 over the maximum speed for the
- * output measured in setpoint units per this controller's update period (see
- * the default period in this class's constructor).
- */
- virtual double CalculateFeedForward();
-
- /**
- * Wraps error around for continuous inputs. The original error is returned if
- * continuous mode is disabled. This is an unsynchronized function.
- *
- * @param error The current error of the PID controller.
- * @return Error for continuous inputs.
- */
- double GetContinuousError(double error) const;
-
- private:
- // Factor for "proportional" control
- double m_P;
-
- // Factor for "integral" control
- double m_I;
-
- // Factor for "derivative" control
- double m_D;
-
- // Factor for "feed forward" control
- double m_F;
-
- // |maximum output|
- double m_maximumOutput = 1.0;
-
- // |minimum output|
- double m_minimumOutput = -1.0;
-
- // Maximum input - limit setpoint to this
- double m_maximumInput = 0;
-
- // Minimum input - limit setpoint to this
- double m_minimumInput = 0;
-
- // input range - difference between maximum and minimum
- double m_inputRange = 0;
-
- // Do the endpoints wrap around? eg. Absolute encoder
- bool m_continuous = false;
-
- // The prior error (used to compute velocity)
- double m_prevError = 0;
-
- // The sum of the errors for use in the integral calc
- double m_totalError = 0;
-
- enum {
- kAbsoluteTolerance,
- kPercentTolerance,
- kNoTolerance
- } m_toleranceType = kNoTolerance;
-
- // The percetage or absolute error that is considered on target.
- double m_tolerance = 0.05;
-
- double m_setpoint = 0;
- double m_prevSetpoint = 0;
- double m_error = 0;
- double m_result = 0;
-
- LinearFilter<double> m_filter{{}, {}};
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PIDController.h b/wpilibc/src/main/native/include/frc/PIDController.h
deleted file mode 100644
index 39e4deb..0000000
--- a/wpilibc/src/main/native/include/frc/PIDController.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-#include <string>
-
-#include <wpi/deprecated.h>
-#include <wpi/mutex.h>
-
-#include "frc/Base.h"
-#include "frc/Controller.h"
-#include "frc/Notifier.h"
-#include "frc/PIDBase.h"
-#include "frc/PIDSource.h"
-#include "frc/Timer.h"
-
-namespace frc {
-
-class PIDOutput;
-
-/**
- * Class implements a PID Control Loop.
- *
- * Creates a separate thread which reads the given PIDSource and takes care of
- * the integral calculations, as well as writing the given PIDOutput.
- *
- * This feedback controller runs in discrete time, so time deltas are not used
- * in the integral and derivative calculations. Therefore, the sample rate
- * affects the controller's behavior for a given set of PID constants.
- *
- * @deprecated Use frc2::PIDController class instead.
- */
-class PIDController : public PIDBase, public Controller {
- public:
- /**
- * Allocate a PID object with the given constants for P, I, D.
- *
- * @param Kp the proportional coefficient
- * @param Ki the integral coefficient
- * @param Kd the derivative coefficient
- * @param source The PIDSource object that is used to get values
- * @param output The PIDOutput object that is set to the output value
- * @param period the loop time for doing calculations in seconds. This
- * particularly affects calculations of the integral and
- * differential terms. The default is 0.05 (50ms).
- */
- WPI_DEPRECATED("Use frc2::PIDController class instead.")
- PIDController(double p, double i, double d, PIDSource* source,
- PIDOutput* output, double period = 0.05);
-
- /**
- * Allocate a PID object with the given constants for P, I, D.
- *
- * @param Kp the proportional coefficient
- * @param Ki the integral coefficient
- * @param Kd the derivative coefficient
- * @param source The PIDSource object that is used to get values
- * @param output The PIDOutput object that is set to the output value
- * @param period the loop time for doing calculations in seconds. This
- * particularly affects calculations of the integral and
- * differential terms. The default is 0.05 (50ms).
- */
- WPI_DEPRECATED("Use frc2::PIDController class instead.")
- PIDController(double p, double i, double d, double f, PIDSource* source,
- PIDOutput* output, double period = 0.05);
-
- /**
- * Allocate a PID object with the given constants for P, I, D.
- *
- * @param Kp the proportional coefficient
- * @param Ki the integral coefficient
- * @param Kd the derivative coefficient
- * @param source The PIDSource object that is used to get values
- * @param output The PIDOutput object that is set to the output value
- * @param period the loop time for doing calculations in seconds. This
- * particularly affects calculations of the integral and
- * differential terms. The default is 0.05 (50ms).
- */
- WPI_DEPRECATED("Use frc2::PIDController class instead.")
- PIDController(double p, double i, double d, PIDSource& source,
- PIDOutput& output, double period = 0.05);
-
- /**
- * Allocate a PID object with the given constants for P, I, D.
- *
- * @param Kp the proportional coefficient
- * @param Ki the integral coefficient
- * @param Kd the derivative coefficient
- * @param source The PIDSource object that is used to get values
- * @param output The PIDOutput object that is set to the output value
- * @param period the loop time for doing calculations in seconds. This
- * particularly affects calculations of the integral and
- * differential terms. The default is 0.05 (50ms).
- */
- WPI_DEPRECATED("Use frc2::PIDController class instead.")
- PIDController(double p, double i, double d, double f, PIDSource& source,
- PIDOutput& output, double period = 0.05);
-
- ~PIDController() override;
-
- /**
- * Begin running the PIDController.
- */
- void Enable() override;
-
- /**
- * Stop running the PIDController, this sets the output to zero before
- * stopping.
- */
- void Disable() override;
-
- /**
- * Set the enabled state of the PIDController.
- */
- void SetEnabled(bool enable);
-
- /**
- * Return true if PIDController is enabled.
- */
- bool IsEnabled() const;
-
- /**
- * Reset the previous error, the integral term, and disable the controller.
- */
- void Reset() override;
-
- void InitSendable(SendableBuilder& builder) override;
-
- private:
- std::unique_ptr<Notifier> m_controlLoop;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PIDInterface.h b/wpilibc/src/main/native/include/frc/PIDInterface.h
deleted file mode 100644
index 8d847a6..0000000
--- a/wpilibc/src/main/native/include/frc/PIDInterface.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <wpi/deprecated.h>
-
-namespace frc {
-
-/**
- * Interface for PID Control Loop.
- *
- * @deprecated All APIs which use this have been deprecated.
- */
-class PIDInterface {
- public:
- WPI_DEPRECATED("All APIs which use this have been deprecated.")
- PIDInterface() = default;
- PIDInterface(PIDInterface&&) = default;
- PIDInterface& operator=(PIDInterface&&) = default;
-
- virtual void SetPID(double p, double i, double d) = 0;
- virtual double GetP() const = 0;
- virtual double GetI() const = 0;
- virtual double GetD() const = 0;
-
- virtual void SetSetpoint(double setpoint) = 0;
- virtual double GetSetpoint() const = 0;
-
- virtual void Reset() = 0;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PIDOutput.h b/wpilibc/src/main/native/include/frc/PIDOutput.h
deleted file mode 100644
index 37fb2a1..0000000
--- a/wpilibc/src/main/native/include/frc/PIDOutput.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/Base.h"
-
-namespace frc {
-
-/**
- * PIDOutput interface is a generic output for the PID class.
- *
- * PWMs use this class. Users implement this interface to allow for a
- * PIDController to read directly from the inputs.
- */
-class PIDOutput {
- public:
- virtual void PIDWrite(double output) = 0;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PIDSource.h b/wpilibc/src/main/native/include/frc/PIDSource.h
deleted file mode 100644
index 1a807b1..0000000
--- a/wpilibc/src/main/native/include/frc/PIDSource.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-namespace frc {
-
-enum class PIDSourceType { kDisplacement, kRate };
-
-/**
- * PIDSource interface is a generic sensor source for the PID class.
- *
- * All sensors that can be used with the PID class will implement the PIDSource
- * that returns a standard value that will be used in the PID code.
- */
-class PIDSource {
- public:
- virtual ~PIDSource() = default;
-
- /**
- * Set which parameter you are using as a process control variable.
- *
- * @param pidSource An enum to select the parameter.
- */
- virtual void SetPIDSourceType(PIDSourceType pidSource);
-
- virtual PIDSourceType GetPIDSourceType() const;
-
- virtual double PIDGet() = 0;
-
- protected:
- PIDSourceType m_pidSource = PIDSourceType::kDisplacement;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PS4Controller.h b/wpilibc/src/main/native/include/frc/PS4Controller.h
new file mode 100644
index 0000000..ee87501
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/PS4Controller.h
@@ -0,0 +1,403 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/GenericHID.h"
+
+namespace frc {
+
+/**
+ * Handle input from PS4 controllers connected to the Driver Station.
+ *
+ * <p>This class handles PS4 input that comes from the Driver Station. Each time
+ * a value is requested the most recent value is returned. There is a single
+ * class instance for each controller and the mapping of ports to hardware
+ * buttons depends on the code in the Driver Station.
+ */
+class PS4Controller : public GenericHID {
+ public:
+ /**
+ * Construct an instance of an PS4 controller.
+ *
+ * The controller index is the USB port on the Driver Station.
+ *
+ * @param port The port on the Driver Station that the controller is plugged
+ * into (0-5).
+ */
+ explicit PS4Controller(int port);
+
+ ~PS4Controller() override = default;
+
+ PS4Controller(PS4Controller&&) = default;
+ PS4Controller& operator=(PS4Controller&&) = default;
+
+ /**
+ * Get the X axis value of left side of the controller.
+ *
+ * @return the axis value.
+ */
+ double GetLeftX() const;
+
+ /**
+ * Get the X axis value of right side of the controller.
+ *
+ * @return the axis value.
+ */
+ double GetRightX() const;
+
+ /**
+ * Get the Y axis value of left side of the controller.
+ *
+ * @return the axis value.
+ */
+ double GetLeftY() const;
+
+ /**
+ * Get the Y axis value of right side of the controller.
+ *
+ * @return the axis value.
+ */
+ double GetRightY() const;
+
+ /**
+ * Get the L2 axis value of the controller. Note that this axis is bound to
+ * the range of [0, 1] as opposed to the usual [-1, 1].
+ *
+ * @return the axis value.
+ */
+ double GetL2Axis() const;
+
+ /**
+ * Get the R2 axis value of the controller. Note that this axis is bound to
+ * the range of [0, 1] as opposed to the usual [-1, 1].
+ *
+ * @return the axis value.
+ */
+ double GetR2Axis() const;
+
+ /**
+ * Read the value of the Square button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetSquareButton() const;
+
+ /**
+ * Whether the Square button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetSquareButtonPressed();
+
+ /**
+ * Whether the Square button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetSquareButtonReleased();
+
+ /**
+ * Read the value of the Cross button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetCrossButton() const;
+
+ /**
+ * Whether the Cross button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetCrossButtonPressed();
+
+ /**
+ * Whether the Cross button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetCrossButtonReleased();
+
+ /**
+ * Read the value of the Circle button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetCircleButton() const;
+
+ /**
+ * Whether the Circle button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetCircleButtonPressed();
+
+ /**
+ * Whether the Circle button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetCircleButtonReleased();
+
+ /**
+ * Read the value of the Triangle button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetTriangleButton() const;
+
+ /**
+ * Whether the Triangle button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetTriangleButtonPressed();
+
+ /**
+ * Whether the Triangle button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetTriangleButtonReleased();
+
+ /**
+ * Read the value of the L1 button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetL1Button() const;
+
+ /**
+ * Whether the L1 button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetL1ButtonPressed();
+
+ /**
+ * Whether the L1 button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetL1ButtonReleased();
+
+ /**
+ * Read the value of the R1 button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetR1Button() const;
+
+ /**
+ * Whether the R1 button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetR1ButtonPressed();
+
+ /**
+ * Whether the R1 button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetR1ButtonReleased();
+
+ /**
+ * Read the value of the L2 button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetL2Button() const;
+
+ /**
+ * Whether the L2 button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetL2ButtonPressed();
+
+ /**
+ * Whether the L2 button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetL2ButtonReleased();
+
+ /**
+ * Read the value of the R2 button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetR2Button() const;
+
+ /**
+ * Whether the R2 button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetR2ButtonPressed();
+
+ /**
+ * Whether the R2 button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetR2ButtonReleased();
+
+ /**
+ * Read the value of the Share button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetShareButton() const;
+
+ /**
+ * Whether the Share button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetShareButtonPressed();
+
+ /**
+ * Whether the Share button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetShareButtonReleased();
+
+ /**
+ * Read the value of the Options button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetOptionsButton() const;
+
+ /**
+ * Whether the Options button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetOptionsButtonPressed();
+
+ /**
+ * Whether the Options button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetOptionsButtonReleased();
+
+ /**
+ * Read the value of the L3 button (pressing the left analog stick) on the
+ * controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetL3Button() const;
+
+ /**
+ * Whether the L3 (left stick) button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetL3ButtonPressed();
+
+ /**
+ * Whether the L3 (left stick) button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetL3ButtonReleased();
+
+ /**
+ * Read the value of the R3 button (pressing the right analog stick) on the
+ * controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetR3Button() const;
+
+ /**
+ * Whether the R3 (right stick) button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetR3ButtonPressed();
+
+ /**
+ * Whether the R3 (right stick) button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetR3ButtonReleased();
+
+ /**
+ * Read the value of the PS button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetPSButton() const;
+
+ /**
+ * Whether the PS button was pressed since the last check.
+ *
+ * @return Whether the button was pressed since the last check.
+ */
+ bool GetPSButtonPressed();
+
+ /**
+ * Whether the PS button was released since the last check.
+ *
+ * @return Whether the button was released since the last check.
+ */
+ bool GetPSButtonReleased();
+
+ /**
+ * Read the value of the touchpad button on the controller.
+ *
+ * @return The state of the button.
+ */
+ bool GetTouchpad() const;
+
+ /**
+ * Whether the touchpad was pressed since the last check.
+ *
+ * @return Whether the touchpad was pressed since the last check.
+ */
+ bool GetTouchpadPressed();
+
+ /**
+ * Whether the touchpad was released since the last check.
+ *
+ * @return Whether the touchpad was released since the last check.
+ */
+ bool GetTouchpadReleased();
+
+ struct Button {
+ static constexpr int kSquare = 1;
+ static constexpr int kCross = 2;
+ static constexpr int kCircle = 3;
+ static constexpr int kTriangle = 4;
+ static constexpr int kL1 = 5;
+ static constexpr int kR1 = 6;
+ static constexpr int kL2 = 7;
+ static constexpr int kR2 = 8;
+ static constexpr int kShare = 9;
+ static constexpr int kOptions = 10;
+ static constexpr int kL3 = 11;
+ static constexpr int kR3 = 12;
+ static constexpr int kPS = 13;
+ static constexpr int kTouchpad = 14;
+ };
+
+ struct Axis {
+ static constexpr int kLeftX = 0;
+ static constexpr int kLeftY = 1;
+ static constexpr int kRightX = 2;
+ static constexpr int kRightY = 5;
+ static constexpr int kL2 = 3;
+ static constexpr int kR2 = 4;
+ };
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PWM.h b/wpilibc/src/main/native/include/frc/PWM.h
index 406a93e..efff540 100644
--- a/wpilibc/src/main/native/include/frc/PWM.h
+++ b/wpilibc/src/main/native/include/frc/PWM.h
@@ -1,24 +1,18 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <stdint.h>
#include <hal/Types.h>
-#include <wpi/raw_ostream.h>
-
-#include "frc/MotorSafety.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
namespace frc {
class AddressableLED;
-class SendableBuilder;
+class DMA;
/**
* Class implements the PWM generation in the FPGA.
@@ -37,9 +31,10 @@
* - 1 = minimum pulse width (currently 0.5ms)
* - 0 = disabled (i.e. PWM output is held low)
*/
-class PWM : public MotorSafety, public Sendable, public SendableHelper<PWM> {
+class PWM : public wpi::Sendable, public wpi::SendableHelper<PWM> {
public:
friend class AddressableLED;
+ friend class DMA;
/**
* Represents the amount to multiply the minimum servo-pulse pwm period by.
*/
@@ -67,8 +62,10 @@
*
* @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the
* MXP port
+ * @param registerSendable If true, adds this instance to SendableRegistry
+ * and LiveWindow
*/
- explicit PWM(int channel);
+ explicit PWM(int channel, bool registerSendable = true);
/**
* Free the PWM channel.
@@ -80,10 +77,6 @@
PWM(PWM&&) = default;
PWM& operator=(PWM&&) = default;
- // MotorSafety interface
- void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
-
/**
* Set the PWM value directly to the hardware.
*
@@ -129,7 +122,7 @@
/**
* Set the PWM value based on a speed.
*
- * This is intended to be used by speed controllers.
+ * This is intended to be used by motor controllers.
*
* @pre SetMaxPositivePwm() called.
* @pre SetMinPositivePwm() called.
@@ -137,14 +130,14 @@
* @pre SetMaxNegativePwm() called.
* @pre SetMinNegativePwm() called.
*
- * @param speed The speed to set the speed controller between -1.0 and 1.0.
+ * @param speed The speed to set the motor controller between -1.0 and 1.0.
*/
virtual void SetSpeed(double speed);
/**
* Get the PWM value in terms of speed.
*
- * This is intended to be used by speed controllers.
+ * This is intended to be used by motor controllers.
*
* @pre SetMaxPositivePwm() called.
* @pre SetMinPositivePwm() called.
@@ -171,12 +164,12 @@
void SetZeroLatch();
/**
- * Optionally eliminate the deadband from a speed controller.
+ * Optionally eliminate the deadband from a motor controller.
*
- * @param eliminateDeadband If true, set the motor curve on the Jaguar to
- * eliminate the deadband in the middle of the range.
- * Otherwise, keep the full range without modifying
- * any values.
+ * @param eliminateDeadband If true, set the motor curve on the speed
+ * controller to eliminate the deadband in the middle
+ * of the range. Otherwise, keep the full range
+ * without modifying any values.
*/
void EnableDeadbandElimination(bool eliminateDeadband);
@@ -231,7 +224,7 @@
int GetChannel() const;
protected:
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
int m_channel;
diff --git a/wpilibc/src/main/native/include/frc/PWMSpeedController.h b/wpilibc/src/main/native/include/frc/PWMSpeedController.h
deleted file mode 100644
index b827d30..0000000
--- a/wpilibc/src/main/native/include/frc/PWMSpeedController.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWM.h"
-#include "frc/SpeedController.h"
-
-namespace frc {
-
-/**
- * Common base class for all PWM Speed Controllers.
- */
-class PWMSpeedController : public PWM, public SpeedController {
- public:
- PWMSpeedController(PWMSpeedController&&) = default;
- PWMSpeedController& operator=(PWMSpeedController&&) = default;
-
- /**
- * Set the PWM value.
- *
- * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
- * the value for the FPGA.
- *
- * @param speed The speed value between -1.0 and 1.0 to set.
- */
- void Set(double value) override;
-
- /**
- * Get the recently set value of the PWM.
- *
- * @return The most recently set value for the PWM between -1.0 and 1.0.
- */
- double Get() const override;
-
- void SetInverted(bool isInverted) override;
-
- bool GetInverted() const override;
-
- void Disable() override;
-
- void StopMotor() override;
-
- /**
- * Write out the PID value as seen in the PIDOutput base object.
- *
- * @param output Write out the PWM value as was found in the PIDController
- */
- void PIDWrite(double output) override;
-
- protected:
- /**
- * Constructor for a PWM Speed Controller connected via PWM.
- *
- * @param channel The PWM channel that the controller is attached to. 0-9 are
- * on-board, 10-19 are on the MXP port
- */
- explicit PWMSpeedController(int channel);
-
- void InitSendable(SendableBuilder& builder) override;
-
- private:
- bool m_isInverted = false;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PWMTalonFX.h b/wpilibc/src/main/native/include/frc/PWMTalonFX.h
deleted file mode 100644
index d85c7ca..0000000
--- a/wpilibc/src/main/native/include/frc/PWMTalonFX.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWMSpeedController.h"
-
-namespace frc {
-
-/**
- * Cross the Road Electronics (CTRE) Talon FX Speed Controller with PWM
- * control.
- *
- * Note that the Talon FX uses the following bounds for PWM values. These
- * values should work reasonably well for most controllers, but if users
- * experience issues such as asymmetric behavior around the deadband or
- * inability to saturate the controller in either direction, calibration is
- * recommended. The calibration procedure can be found in the Talon FX User
- * Manual available from Cross The Road Electronics.
- *
- * \li 2.004ms = full "forward"
- * \li 1.520ms = the "high end" of the deadband range
- * \li 1.500ms = center of the deadband range (off)
- * \li 1.480ms = the "low end" of the deadband range
- * \li 0.997ms = full "reverse"
- */
-class PWMTalonFX : public PWMSpeedController {
- public:
- /**
- * Construct a Talon FX connected via PWM.
- *
- * @param channel The PWM channel that the Talon FX is attached to. 0-9 are
- * on-board, 10-19 are on the MXP port
- */
- explicit PWMTalonFX(int channel);
-
- PWMTalonFX(PWMTalonFX&&) = default;
- PWMTalonFX& operator=(PWMTalonFX&&) = default;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PWMTalonSRX.h b/wpilibc/src/main/native/include/frc/PWMTalonSRX.h
deleted file mode 100644
index b9c8369..0000000
--- a/wpilibc/src/main/native/include/frc/PWMTalonSRX.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWMSpeedController.h"
-
-namespace frc {
-
-/**
- * Cross the Road Electronics (CTRE) Talon SRX Speed Controller with PWM
- * control.
- *
- * Note that the Talon SRX uses the following bounds for PWM values. These
- * values should work reasonably well for most controllers, but if users
- * experience issues such as asymmetric behavior around the deadband or
- * inability to saturate the controller in either direction, calibration is
- * recommended. The calibration procedure can be found in the Talon SRX User
- * Manual available from Cross The Road Electronics.
- *
- * \li 2.004ms = full "forward"
- * \li 1.520ms = the "high end" of the deadband range
- * \li 1.500ms = center of the deadband range (off)
- * \li 1.480ms = the "low end" of the deadband range
- * \li 0.997ms = full "reverse"
- */
-class PWMTalonSRX : public PWMSpeedController {
- public:
- /**
- * Construct a Talon SRX connected via PWM.
- *
- * @param channel The PWM channel that the Talon SRX is attached to. 0-9 are
- * on-board, 10-19 are on the MXP port
- */
- explicit PWMTalonSRX(int channel);
-
- PWMTalonSRX(PWMTalonSRX&&) = default;
- PWMTalonSRX& operator=(PWMTalonSRX&&) = default;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PWMVictorSPX.h b/wpilibc/src/main/native/include/frc/PWMVictorSPX.h
deleted file mode 100644
index a19e704..0000000
--- a/wpilibc/src/main/native/include/frc/PWMVictorSPX.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWMSpeedController.h"
-
-namespace frc {
-
-/**
- * Cross the Road Electronics (CTRE) Victor SPX Speed Controller with PWM
- * control.
- *
- * Note that the Victor SPX uses the following bounds for PWM values. These
- * values should work reasonably well for most controllers, but if users
- * experience issues such as asymmetric behavior around the deadband or
- * inability to saturate the controller in either direction, calibration is
- * recommended. The calibration procedure can be found in the Victor SPX User
- * Manual available from Cross The Road Electronics.
- *
- * \li 2.004ms = full "forward"
- * \li 1.520ms = the "high end" of the deadband range
- * \li 1.500ms = center of the deadband range (off)
- * \li 1.480ms = the "low end" of the deadband range
- * \li 0.997ms = full "reverse"
- */
-class PWMVictorSPX : public PWMSpeedController {
- public:
- /**
- * Construct a Victor SPX connected via PWM.
- *
- * @param channel The PWM channel that the Victor SPX is attached to. 0-9
- * are on-board, 10-19 are on the MXP port
- */
- explicit PWMVictorSPX(int channel);
-
- PWMVictorSPX(PWMVictorSPX&&) = default;
- PWMVictorSPX& operator=(PWMVictorSPX&&) = default;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PneumaticHub.h b/wpilibc/src/main/native/include/frc/PneumaticHub.h
new file mode 100644
index 0000000..857ed51
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/PneumaticHub.h
@@ -0,0 +1,77 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include <hal/Types.h>
+#include <wpi/DenseMap.h>
+#include <wpi/mutex.h>
+
+#include "PneumaticsBase.h"
+
+namespace frc {
+class PneumaticHub : public PneumaticsBase {
+ public:
+ PneumaticHub();
+ explicit PneumaticHub(int module);
+
+ ~PneumaticHub() override = default;
+
+ bool GetCompressor() const override;
+
+ void SetClosedLoopControl(bool enabled) override;
+
+ bool GetClosedLoopControl() const override;
+
+ bool GetPressureSwitch() const override;
+
+ double GetCompressorCurrent() const override;
+
+ void SetSolenoids(int mask, int values) override;
+
+ int GetSolenoids() const override;
+
+ int GetModuleNumber() const override;
+
+ int GetSolenoidDisabledList() const override;
+
+ void FireOneShot(int index) override;
+
+ void SetOneShotDuration(int index, units::second_t duration) override;
+
+ bool CheckSolenoidChannel(int channel) const override;
+
+ int CheckAndReserveSolenoids(int mask) override;
+
+ void UnreserveSolenoids(int mask) override;
+
+ bool ReserveCompressor() override;
+
+ void UnreserveCompressor() override;
+
+ Solenoid MakeSolenoid(int channel) override;
+ DoubleSolenoid MakeDoubleSolenoid(int forwardChannel,
+ int reverseChannel) override;
+ Compressor MakeCompressor() override;
+
+ private:
+ class DataStore;
+ friend class DataStore;
+ friend class PneumaticsBase;
+ PneumaticHub(HAL_REVPHHandle handle, int module);
+
+ static std::shared_ptr<PneumaticsBase> GetForModule(int module);
+
+ std::shared_ptr<DataStore> m_dataStore;
+ HAL_REVPHHandle m_handle;
+ int m_module;
+
+ static wpi::mutex m_handleLock;
+ static std::unique_ptr<wpi::DenseMap<int, std::weak_ptr<DataStore>>>
+ m_handleMap;
+ static std::weak_ptr<DataStore>& GetDataStore(int module);
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PneumaticsBase.h b/wpilibc/src/main/native/include/frc/PneumaticsBase.h
new file mode 100644
index 0000000..06cad5d
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/PneumaticsBase.h
@@ -0,0 +1,62 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include <units/time.h>
+
+#include "frc/PneumaticsModuleType.h"
+
+namespace frc {
+class Solenoid;
+class DoubleSolenoid;
+class Compressor;
+class PneumaticsBase {
+ public:
+ virtual ~PneumaticsBase() = default;
+
+ virtual bool GetCompressor() const = 0;
+
+ virtual bool GetPressureSwitch() const = 0;
+
+ virtual double GetCompressorCurrent() const = 0;
+
+ virtual void SetClosedLoopControl(bool on) = 0;
+
+ virtual bool GetClosedLoopControl() const = 0;
+
+ virtual void SetSolenoids(int mask, int values) = 0;
+
+ virtual int GetSolenoids() const = 0;
+
+ virtual int GetModuleNumber() const = 0;
+
+ virtual int GetSolenoidDisabledList() const = 0;
+
+ virtual void FireOneShot(int index) = 0;
+
+ virtual void SetOneShotDuration(int index, units::second_t duration) = 0;
+
+ virtual bool CheckSolenoidChannel(int channel) const = 0;
+
+ virtual int CheckAndReserveSolenoids(int mask) = 0;
+
+ virtual void UnreserveSolenoids(int mask) = 0;
+
+ virtual bool ReserveCompressor() = 0;
+
+ virtual void UnreserveCompressor() = 0;
+
+ virtual Solenoid MakeSolenoid(int channel) = 0;
+ virtual DoubleSolenoid MakeDoubleSolenoid(int forwardChannel,
+ int reverseChannel) = 0;
+ virtual Compressor MakeCompressor() = 0;
+
+ static std::shared_ptr<PneumaticsBase> GetForType(
+ int module, PneumaticsModuleType moduleType);
+ static int GetDefaultForType(PneumaticsModuleType moduleType);
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PneumaticsControlModule.h b/wpilibc/src/main/native/include/frc/PneumaticsControlModule.h
new file mode 100644
index 0000000..64686d6
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/PneumaticsControlModule.h
@@ -0,0 +1,89 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include <hal/Types.h>
+#include <wpi/DenseMap.h>
+#include <wpi/mutex.h>
+
+#include "PneumaticsBase.h"
+
+namespace frc {
+class PneumaticsControlModule : public PneumaticsBase {
+ public:
+ PneumaticsControlModule();
+ explicit PneumaticsControlModule(int module);
+
+ ~PneumaticsControlModule() override = default;
+
+ bool GetCompressor() const override;
+
+ void SetClosedLoopControl(bool enabled) override;
+
+ bool GetClosedLoopControl() const override;
+
+ bool GetPressureSwitch() const override;
+
+ double GetCompressorCurrent() const override;
+
+ bool GetCompressorCurrentTooHighFault() const;
+ bool GetCompressorCurrentTooHighStickyFault() const;
+ bool GetCompressorShortedFault() const;
+ bool GetCompressorShortedStickyFault() const;
+ bool GetCompressorNotConnectedFault() const;
+ bool GetCompressorNotConnectedStickyFault() const;
+
+ bool GetSolenoidVoltageFault() const;
+ bool GetSolenoidVoltageStickyFault() const;
+
+ void ClearAllStickyFaults();
+
+ void SetSolenoids(int mask, int values) override;
+
+ int GetSolenoids() const override;
+
+ int GetModuleNumber() const override;
+
+ int GetSolenoidDisabledList() const override;
+
+ void FireOneShot(int index) override;
+
+ void SetOneShotDuration(int index, units::second_t duration) override;
+
+ bool CheckSolenoidChannel(int channel) const override;
+
+ int CheckAndReserveSolenoids(int mask) override;
+
+ void UnreserveSolenoids(int mask) override;
+
+ bool ReserveCompressor() override;
+
+ void UnreserveCompressor() override;
+
+ Solenoid MakeSolenoid(int channel) override;
+ DoubleSolenoid MakeDoubleSolenoid(int forwardChannel,
+ int reverseChannel) override;
+ Compressor MakeCompressor() override;
+
+ private:
+ class DataStore;
+ friend class DataStore;
+ friend class PneumaticsBase;
+ PneumaticsControlModule(HAL_CTREPCMHandle handle, int module);
+
+ static std::shared_ptr<PneumaticsBase> GetForModule(int module);
+
+ std::shared_ptr<DataStore> m_dataStore;
+ HAL_CTREPCMHandle m_handle;
+ int m_module;
+
+ static wpi::mutex m_handleLock;
+ static std::unique_ptr<wpi::DenseMap<int, std::weak_ptr<DataStore>>>
+ m_handleMap;
+ static std::weak_ptr<DataStore>& GetDataStore(int module);
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h b/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h
new file mode 100644
index 0000000..7f70662
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/PneumaticsModuleType.h
@@ -0,0 +1,9 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+namespace frc {
+enum class PneumaticsModuleType { CTREPCM, REVPH };
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PowerDistribution.h b/wpilibc/src/main/native/include/frc/PowerDistribution.h
new file mode 100644
index 0000000..2863daf
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/PowerDistribution.h
@@ -0,0 +1,112 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <hal/Types.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+namespace frc {
+
+/**
+ * Class for getting voltage, current, temperature, power and energy from the
+ * CAN PDP.
+ */
+class PowerDistribution : public wpi::Sendable,
+ public wpi::SendableHelper<PowerDistribution> {
+ public:
+ static constexpr int kDefaultModule = -1;
+ enum class ModuleType { kAutomatic = 0, kCTRE = 1, kRev = 2 };
+
+ /**
+ * Constructs a PowerDistribution.
+ *
+ * Uses the default CAN ID.
+ */
+ PowerDistribution();
+
+ /**
+ * Constructs a PowerDistribution.
+ *
+ * @param module The CAN ID of the PDP
+ * @param moduleType The type of module
+ */
+ PowerDistribution(int module, ModuleType moduleType);
+
+ ~PowerDistribution() override;
+ PowerDistribution(PowerDistribution&&) = default;
+ PowerDistribution& operator=(PowerDistribution&&) = default;
+
+ /**
+ * Query the input voltage of the PDP.
+ *
+ * @return The voltage of the PDP in volts
+ */
+ double GetVoltage() const;
+
+ /**
+ * Query the temperature of the PDP.
+ *
+ * @return The temperature of the PDP in degrees Celsius
+ */
+ double GetTemperature() const;
+
+ /**
+ * Query the current of a single channel of the PDP.
+ *
+ * @return The current of one of the PDP channels (channels 0-15) in Amperes
+ */
+ double GetCurrent(int channel) const;
+
+ /**
+ * Query the total current of all monitored PDP channels (0-15).
+ *
+ * @return The the total current drawn from the PDP channels in Amperes
+ */
+ double GetTotalCurrent() const;
+
+ /**
+ * Query the total power drawn from the monitored PDP channels.
+ *
+ * @return The the total power drawn from the PDP channels in Watts
+ */
+ double GetTotalPower() const;
+
+ /**
+ * Query the total energy drawn from the monitored PDP channels.
+ *
+ * @return The the total energy drawn from the PDP channels in Joules
+ */
+ double GetTotalEnergy() const;
+
+ /**
+ * Reset the total energy drawn from the PDP.
+ *
+ * @see PowerDistribution#GetTotalEnergy
+ */
+ void ResetTotalEnergy();
+
+ /**
+ * Remove all of the fault flags on the PDP.
+ */
+ void ClearStickyFaults();
+
+ /**
+ * Gets module number (CAN ID).
+ */
+ int GetModule() const;
+
+ bool GetSwitchableChannel() const;
+
+ void SetSwitchableChannel(bool enabled);
+
+ void InitSendable(wpi::SendableBuilder& builder) override;
+
+ private:
+ hal::Handle<HAL_PowerDistributionHandle> m_handle;
+ int m_module;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PowerDistributionPanel.h b/wpilibc/src/main/native/include/frc/PowerDistributionPanel.h
deleted file mode 100644
index 9ec00a3..0000000
--- a/wpilibc/src/main/native/include/frc/PowerDistributionPanel.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <hal/Types.h>
-
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
-
-namespace frc {
-
-class SendableBuilder;
-
-/**
- * Class for getting voltage, current, temperature, power and energy from the
- * CAN PDP.
- */
-class PowerDistributionPanel : public ErrorBase,
- public Sendable,
- public SendableHelper<PowerDistributionPanel> {
- public:
- PowerDistributionPanel();
- explicit PowerDistributionPanel(int module);
-
- PowerDistributionPanel(PowerDistributionPanel&&) = default;
- PowerDistributionPanel& operator=(PowerDistributionPanel&&) = default;
-
- /**
- * Query the input voltage of the PDP.
- *
- * @return The voltage of the PDP in volts
- */
- double GetVoltage() const;
-
- /**
- * Query the temperature of the PDP.
- *
- * @return The temperature of the PDP in degrees Celsius
- */
- double GetTemperature() const;
-
- /**
- * Query the current of a single channel of the PDP.
- *
- * @return The current of one of the PDP channels (channels 0-15) in Amperes
- */
- double GetCurrent(int channel) const;
-
- /**
- * Query the total current of all monitored PDP channels (0-15).
- *
- * @return The the total current drawn from the PDP channels in Amperes
- */
- double GetTotalCurrent() const;
-
- /**
- * Query the total power drawn from the monitored PDP channels.
- *
- * @return The the total power drawn from the PDP channels in Watts
- */
- double GetTotalPower() const;
-
- /**
- * Query the total energy drawn from the monitored PDP channels.
- *
- * @return The the total energy drawn from the PDP channels in Joules
- */
- double GetTotalEnergy() const;
-
- /**
- * Reset the total energy drawn from the PDP.
- *
- * @see PowerDistributionPanel#GetTotalEnergy
- */
- void ResetTotalEnergy();
-
- /**
- * Remove all of the fault flags on the PDP.
- */
- void ClearStickyFaults();
-
- /**
- * Gets module number (CAN ID).
- */
- int GetModule() const;
-
- void InitSendable(SendableBuilder& builder) override;
-
- private:
- hal::Handle<HAL_PDPHandle> m_handle;
- int m_module;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Preferences.h b/wpilibc/src/main/native/include/frc/Preferences.h
index f04b012..b939d9e 100644
--- a/wpilibc/src/main/native/include/frc/Preferences.h
+++ b/wpilibc/src/main/native/include/frc/Preferences.h
@@ -1,21 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <stdint.h>
-#include <memory>
#include <string>
+#include <string_view>
#include <vector>
-#include <networktables/NetworkTable.h>
-
-#include "frc/ErrorBase.h"
+#include <wpi/deprecated.h>
namespace frc {
@@ -30,16 +25,18 @@
*
* This class is thread safe.
*
- * This will also interact with {@link NetworkTable} by creating a table called
+ * This will also interact with NetworkTable by creating a table called
* "Preferences" with all the key-value pairs.
*/
-class Preferences : public ErrorBase {
+class Preferences {
public:
/**
* Get the one and only {@link Preferences} object.
*
* @return pointer to the {@link Preferences}
+ * @deprecated Use the static methods
*/
+ WPI_DEPRECATED("Use static methods")
static Preferences* GetInstance();
/**
@@ -47,7 +44,7 @@
*
* @return a vector of the keys
*/
- std::vector<std::string> GetKeys();
+ static std::vector<std::string> GetKeys();
/**
* Returns the string at the given key. If this table does not have a value
@@ -57,7 +54,8 @@
* @param defaultValue the value to return if none exists in the table
* @return either the value in the table, or the defaultValue
*/
- std::string GetString(wpi::StringRef key, wpi::StringRef defaultValue = "");
+ static std::string GetString(std::string_view key,
+ std::string_view defaultValue = "");
/**
* Returns the int at the given key. If this table does not have a value for
@@ -67,7 +65,7 @@
* @param defaultValue the value to return if none exists in the table
* @return either the value in the table, or the defaultValue
*/
- int GetInt(wpi::StringRef key, int defaultValue = 0);
+ static int GetInt(std::string_view key, int defaultValue = 0);
/**
* Returns the double at the given key. If this table does not have a value
@@ -77,7 +75,7 @@
* @param defaultValue the value to return if none exists in the table
* @return either the value in the table, or the defaultValue
*/
- double GetDouble(wpi::StringRef key, double defaultValue = 0.0);
+ static double GetDouble(std::string_view key, double defaultValue = 0.0);
/**
* Returns the float at the given key. If this table does not have a value
@@ -87,7 +85,7 @@
* @param defaultValue the value to return if none exists in the table
* @return either the value in the table, or the defaultValue
*/
- float GetFloat(wpi::StringRef key, float defaultValue = 0.0);
+ static float GetFloat(std::string_view key, float defaultValue = 0.0);
/**
* Returns the boolean at the given key. If this table does not have a value
@@ -97,7 +95,7 @@
* @param defaultValue the value to return if none exists in the table
* @return either the value in the table, or the defaultValue
*/
- bool GetBoolean(wpi::StringRef key, bool defaultValue = false);
+ static bool GetBoolean(std::string_view key, bool defaultValue = false);
/**
* Returns the long (int64_t) at the given key. If this table does not have a
@@ -108,7 +106,7 @@
* @param defaultValue the value to return if none exists in the table
* @return either the value in the table, or the defaultValue
*/
- int64_t GetLong(wpi::StringRef key, int64_t defaultValue = 0);
+ static int64_t GetLong(std::string_view key, int64_t defaultValue = 0);
/**
* Puts the given string into the preferences table.
@@ -119,13 +117,25 @@
* @param key the key
* @param value the value
*/
- void PutString(wpi::StringRef key, wpi::StringRef value);
+ static void SetString(std::string_view key, std::string_view value);
+
+ /**
+ * Puts the given string into the preferences table.
+ *
+ * The value may not have quotation marks, nor may the key have any whitespace
+ * nor an equals sign.
+ *
+ * @param key the key
+ * @param value the value
+ */
+ WPI_DEPRECATED("Use SetString instead.")
+ static void PutString(std::string_view key, std::string_view value);
/**
* Puts the given string into the preferences table if it doesn't
* already exist.
*/
- void InitString(wpi::StringRef key, wpi::StringRef value);
+ static void InitString(std::string_view key, std::string_view value);
/**
* Puts the given int into the preferences table.
@@ -135,13 +145,24 @@
* @param key the key
* @param value the value
*/
- void PutInt(wpi::StringRef key, int value);
+ static void SetInt(std::string_view key, int value);
+
+ /**
+ * Puts the given int into the preferences table.
+ *
+ * The key may not have any whitespace nor an equals sign.
+ *
+ * @param key the key
+ * @param value the value
+ */
+ WPI_DEPRECATED("Use SetInt instead.")
+ static void PutInt(std::string_view key, int value);
/**
* Puts the given int into the preferences table if it doesn't
* already exist.
*/
- void InitInt(wpi::StringRef key, int value);
+ static void InitInt(std::string_view key, int value);
/**
* Puts the given double into the preferences table.
@@ -151,13 +172,24 @@
* @param key the key
* @param value the value
*/
- void PutDouble(wpi::StringRef key, double value);
+ static void SetDouble(std::string_view key, double value);
+
+ /**
+ * Puts the given double into the preferences table.
+ *
+ * The key may not have any whitespace nor an equals sign.
+ *
+ * @param key the key
+ * @param value the value
+ */
+ WPI_DEPRECATED("Use SetDouble instead.")
+ static void PutDouble(std::string_view key, double value);
/**
* Puts the given double into the preferences table if it doesn't
* already exist.
*/
- void InitDouble(wpi::StringRef key, double value);
+ static void InitDouble(std::string_view key, double value);
/**
* Puts the given float into the preferences table.
@@ -167,13 +199,24 @@
* @param key the key
* @param value the value
*/
- void PutFloat(wpi::StringRef key, float value);
+ static void SetFloat(std::string_view key, float value);
+
+ /**
+ * Puts the given float into the preferences table.
+ *
+ * The key may not have any whitespace nor an equals sign.
+ *
+ * @param key the key
+ * @param value the value
+ */
+ WPI_DEPRECATED("Use SetFloat instead.")
+ static void PutFloat(std::string_view key, float value);
/**
* Puts the given float into the preferences table if it doesn't
* already exist.
*/
- void InitFloat(wpi::StringRef key, float value);
+ static void InitFloat(std::string_view key, float value);
/**
* Puts the given boolean into the preferences table.
@@ -183,13 +226,24 @@
* @param key the key
* @param value the value
*/
- void PutBoolean(wpi::StringRef key, bool value);
+ static void SetBoolean(std::string_view key, bool value);
+
+ /**
+ * Puts the given boolean into the preferences table.
+ *
+ * The key may not have any whitespace nor an equals sign.
+ *
+ * @param key the key
+ * @param value the value
+ */
+ WPI_DEPRECATED("Use SetBoolean instead.")
+ static void PutBoolean(std::string_view key, bool value);
/**
* Puts the given boolean into the preferences table if it doesn't
* already exist.
*/
- void InitBoolean(wpi::StringRef key, bool value);
+ static void InitBoolean(std::string_view key, bool value);
/**
* Puts the given long (int64_t) into the preferences table.
@@ -199,13 +253,24 @@
* @param key the key
* @param value the value
*/
- void PutLong(wpi::StringRef key, int64_t value);
+ static void SetLong(std::string_view key, int64_t value);
+
+ /**
+ * Puts the given long (int64_t) into the preferences table.
+ *
+ * The key may not have any whitespace nor an equals sign.
+ *
+ * @param key the key
+ * @param value the value
+ */
+ WPI_DEPRECATED("Use SetLong instead.")
+ static void PutLong(std::string_view key, int64_t value);
/**
* Puts the given long into the preferences table if it doesn't
* already exist.
*/
- void InitLong(wpi::StringRef key, int64_t value);
+ static void InitLong(std::string_view key, int64_t value);
/**
* Returns whether or not there is a key with the given name.
@@ -213,30 +278,22 @@
* @param key the key
* @return if there is a value at the given key
*/
- bool ContainsKey(wpi::StringRef key);
+ static bool ContainsKey(std::string_view key);
/**
* Remove a preference.
*
* @param key the key
*/
- void Remove(wpi::StringRef key);
+ static void Remove(std::string_view key);
/**
* Remove all preferences.
*/
- void RemoveAll();
-
- protected:
- Preferences();
- virtual ~Preferences() = default;
-
- Preferences(Preferences&&) = default;
- Preferences& operator=(Preferences&&) = default;
+ static void RemoveAll();
private:
- std::shared_ptr<nt::NetworkTable> m_table;
- NT_EntryListener m_listener;
+ Preferences() = default;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Relay.h b/wpilibc/src/main/native/include/frc/Relay.h
index c903fc0..4765c64 100644
--- a/wpilibc/src/main/native/include/frc/Relay.h
+++ b/wpilibc/src/main/native/include/frc/Relay.h
@@ -1,26 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string>
#include <hal/Types.h>
-#include <wpi/raw_ostream.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
-#include "frc/ErrorBase.h"
#include "frc/MotorSafety.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
-class SendableBuilder;
-
/**
* Class for Spike style relay outputs.
*
@@ -34,8 +28,8 @@
* a solenoid).
*/
class Relay : public MotorSafety,
- public Sendable,
- public SendableHelper<Relay> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<Relay> {
public:
enum Value { kOff, kOn, kForward, kReverse };
enum Direction { kBothDirections, kForwardOnly, kReverseOnly };
@@ -95,9 +89,9 @@
// MotorSafety interface
void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
+ std::string GetDescription() const override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
int m_channel;
diff --git a/wpilibc/src/main/native/include/frc/Resource.h b/wpilibc/src/main/native/include/frc/Resource.h
index e9759d5..4109cc4 100644
--- a/wpilibc/src/main/native/include/frc/Resource.h
+++ b/wpilibc/src/main/native/include/frc/Resource.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -15,8 +12,6 @@
#include <wpi/mutex.h>
-#include "frc/ErrorBase.h"
-
namespace frc {
/**
@@ -29,7 +24,7 @@
* resources; it just tracks which indices were marked in use by Allocate and
* not yet freed by Free.
*/
-class Resource : public ErrorBase {
+class Resource {
public:
virtual ~Resource() = default;
diff --git a/wpilibc/src/main/native/include/frc/RobotBase.h b/wpilibc/src/main/native/include/frc/RobotBase.h
index 66d5637..70c6093 100644
--- a/wpilibc/src/main/native/include/frc/RobotBase.h
+++ b/wpilibc/src/main/native/include/frc/RobotBase.h
@@ -1,39 +1,50 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <chrono>
#include <thread>
+#include <hal/DriverStation.h>
#include <hal/HALBase.h>
#include <hal/Main.h>
#include <wpi/condition_variable.h>
+#include <wpi/deprecated.h>
#include <wpi/mutex.h>
-#include <wpi/raw_ostream.h>
-#include "frc/Base.h"
+#include "frc/Errors.h"
+#include "frc/RuntimeType.h"
namespace frc {
-class DriverStation;
-
int RunHALInitialization();
namespace impl {
template <class Robot>
void RunRobot(wpi::mutex& m, Robot** robot) {
- static Robot theRobot;
- {
- std::scoped_lock lock{m};
- *robot = &theRobot;
+ try {
+ static Robot theRobot;
+ {
+ std::scoped_lock lock{m};
+ *robot = &theRobot;
+ }
+ theRobot.StartCompetition();
+ } catch (const frc::RuntimeError& e) {
+ e.Report();
+ FRC_ReportError(
+ err::Error, "{}",
+ "The robot program quit unexpectedly."
+ " This is usually due to a code error.\n"
+ " The above stacktrace can help determine where the error occurred.\n"
+ " See https://wpilib.org/stacktrace for more information.\n");
+ throw;
+ } catch (const std::exception& e) {
+ HAL_SendError(1, err::Error, 0, e.what(), "", "", 1);
+ throw;
}
- theRobot.StartCompetition();
}
} // namespace impl
@@ -77,15 +88,18 @@
HAL_RunMain();
// signal loop to exit
- if (robot) robot->EndCompetition();
+ if (robot) {
+ robot->EndCompetition();
+ }
// prefer to join, but detach to exit if it doesn't exit in a timely manner
using namespace std::chrono_literals;
std::unique_lock lock{m};
- if (cv.wait_for(lock, 1s, [] { return exited; }))
+ if (cv.wait_for(lock, 1s, [] { return exited; })) {
thr.join();
- else
+ } else {
thr.detach();
+ }
} else {
impl::RunRobot<Robot>(m, &robot);
}
@@ -95,13 +109,6 @@
return 0;
}
-#define START_ROBOT_CLASS(_ClassName_) \
- WPI_DEPRECATED("Call frc::StartRobot<" #_ClassName_ \
- ">() in your own main() instead of using the " \
- "START_ROBOT_CLASS(" #_ClassName_ ") macro.") \
- int StartRobotClassImpl() { return frc::StartRobot<_ClassName_>(); } \
- int main() { return StartRobotClassImpl(); }
-
/**
* Implement a Robot Program framework.
*
@@ -149,16 +156,36 @@
*
* @return True if the robot is currently operating in Tele-Op mode as
* determined by the field controls.
+ * @deprecated Use IsTeleop() instead.
*/
+ WPI_DEPRECATED("Use IsTeleop() instead")
bool IsOperatorControl() const;
/**
+ * Determine if the robot is currently in Operator Control mode.
+ *
+ * @return True if the robot is currently operating in Tele-Op mode as
+ * determined by the field controls.
+ */
+ bool IsTeleop() const;
+
+ /**
+ * Determine if the robot is current in Operator Control mode and enabled.
+ *
+ * @return True if the robot is currently operating in Tele-Op mode while
+ * enabled as determined by the field-controls.
+ * @deprecated Use IsTeleopEnabled() instead.
+ */
+ WPI_DEPRECATED("Use IsTeleopEnabled() instead")
+ bool IsOperatorControlEnabled() const;
+
+ /**
* Determine if the robot is current in Operator Control mode and enabled.
*
* @return True if the robot is currently operating in Tele-Op mode while
* wnabled as determined by the field-controls.
*/
- bool IsOperatorControlEnabled() const;
+ bool IsTeleopEnabled() const;
/**
* Determine if the robot is currently in Test mode.
@@ -186,6 +213,13 @@
virtual void EndCompetition() = 0;
/**
+ * Get the current runtime type.
+ *
+ * @return Current runtime type.
+ */
+ static RuntimeType GetRuntimeType();
+
+ /**
* Get if the robot is real.
*
* @return If the robot is running in the real world.
@@ -218,15 +252,11 @@
*/
RobotBase();
- virtual ~RobotBase();
+ virtual ~RobotBase() = default;
protected:
- // m_ds isn't moved in these because DriverStation is a singleton; every
- // instance of RobotBase has a reference to the same object.
- RobotBase(RobotBase&&) noexcept;
- RobotBase& operator=(RobotBase&&) noexcept;
-
- DriverStation& m_ds;
+ RobotBase(RobotBase&&) = default;
+ RobotBase& operator=(RobotBase&&) = default;
static std::thread::id m_threadId;
};
diff --git a/wpilibc/src/main/native/include/frc/RobotController.h b/wpilibc/src/main/native/include/frc/RobotController.h
index fae136b..e9750f0 100644
--- a/wpilibc/src/main/native/include/frc/RobotController.h
+++ b/wpilibc/src/main/native/include/frc/RobotController.h
@@ -1,14 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <stdint.h>
+#include <units/voltage.h>
+
namespace frc {
struct CANStatus {
@@ -59,6 +58,13 @@
static bool GetUserButton();
/**
+ * Read the battery voltage.
+ *
+ * @return The battery voltage in Volts.
+ */
+ static units::volt_t GetBatteryVoltage();
+
+ /**
* Check if the FPGA outputs are enabled.
*
* The outputs may be disabled if the robot is disabled or e-stopped, the
@@ -182,6 +188,28 @@
*/
static int GetFaultCount6V();
+ /**
+ * Get the current brownout voltage setting.
+ *
+ * @return The brownout voltage
+ */
+ static units::volt_t GetBrownoutVoltage();
+
+ /**
+ * Set the voltage the roboRIO will brownout and disable all outputs.
+ *
+ * Note that this only does anything on the roboRIO 2.
+ * On the roboRIO it is a no-op.
+ *
+ * @param brownoutVoltage The brownout voltage
+ */
+ static void SetBrownoutVoltage(units::volt_t brownoutVoltage);
+
+ /**
+ * Get the current status of the CAN bus.
+ *
+ * @return The status of the CAN bus
+ */
static CANStatus GetCANStatus();
};
diff --git a/wpilibc/src/main/native/include/frc/RobotDrive.h b/wpilibc/src/main/native/include/frc/RobotDrive.h
deleted file mode 100644
index a8b63e6..0000000
--- a/wpilibc/src/main/native/include/frc/RobotDrive.h
+++ /dev/null
@@ -1,456 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-
-#include <wpi/deprecated.h>
-#include <wpi/raw_ostream.h>
-
-#include "frc/ErrorBase.h"
-#include "frc/MotorSafety.h"
-
-namespace frc {
-
-class SpeedController;
-class GenericHID;
-
-/**
- * Utility class for handling Robot drive based on a definition of the motor
- * configuration.
- *
- * The robot drive class handles basic driving for a robot. Currently, 2 and 4
- * motor tank and mecanum drive trains are supported. In the future other drive
- * types like swerve might be implemented. Motor channel numbers are passed
- * supplied on creation of the class. Those are used for either the Drive
- * function (intended for hand created drive code, such as autonomous) or with
- * the Tank/Arcade functions intended to be used for Operator Control driving.
- *
- * @deprecated Use DifferentialDrive or MecanumDrive classes instead.
- *
- */
-class RobotDrive : public MotorSafety {
- public:
- enum MotorType {
- kFrontLeftMotor = 0,
- kFrontRightMotor = 1,
- kRearLeftMotor = 2,
- kRearRightMotor = 3
- };
-
- /**
- * Constructor for RobotDrive with 2 motors specified with channel numbers.
- *
- * Set up parameters for a two wheel drive system where the
- * left and right motor pwm channels are specified in the call.
- * This call assumes Talons for controlling the motors.
- *
- * @param leftMotorChannel The PWM channel number that drives the left motor.
- * 0-9 are on-board, 10-19 are on the MXP port
- * @param rightMotorChannel The PWM channel number that drives the right
- * motor. 0-9 are on-board, 10-19 are on the MXP port
- */
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(int leftMotorChannel, int rightMotorChannel);
-
- /**
- * Constructor for RobotDrive with 4 motors specified with channel numbers.
- *
- * Set up parameters for a four wheel drive system where all four motor
- * pwm channels are specified in the call.
- * This call assumes Talons for controlling the motors.
- *
- * @param frontLeftMotor Front left motor channel number. 0-9 are on-board,
- * 10-19 are on the MXP port
- * @param rearLeftMotor Rear Left motor channel number. 0-9 are on-board,
- * 10-19 are on the MXP port
- * @param frontRightMotor Front right motor channel number. 0-9 are on-board,
- * 10-19 are on the MXP port
- * @param rearRightMotor Rear Right motor channel number. 0-9 are on-board,
- * 10-19 are on the MXP port
- */
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(int frontLeftMotorChannel, int rearLeftMotorChannel,
- int frontRightMotorChannel, int rearRightMotorChannel);
-
- /**
- * Constructor for RobotDrive with 2 motors specified as SpeedController
- * objects.
- *
- * The SpeedController version of the constructor enables programs to use the
- * RobotDrive classes with subclasses of the SpeedController objects, for
- * example, versions with ramping or reshaping of the curve to suit motor bias
- * or deadband elimination.
- *
- * @param leftMotor The left SpeedController object used to drive the robot.
- * @param rightMotor The right SpeedController object used to drive the robot.
- */
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(SpeedController* leftMotor, SpeedController* rightMotor);
-
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(SpeedController& leftMotor, SpeedController& rightMotor);
-
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(std::shared_ptr<SpeedController> leftMotor,
- std::shared_ptr<SpeedController> rightMotor);
-
- /**
- * Constructor for RobotDrive with 4 motors specified as SpeedController
- * objects.
- *
- * Speed controller input version of RobotDrive (see previous comments).
- *
- * @param frontLeftMotor The front left SpeedController object used to drive
- * the robot.
- * @param rearLeftMotor The back left SpeedController object used to drive
- * the robot.
- * @param frontRightMotor The front right SpeedController object used to drive
- * the robot.
- * @param rearRightMotor The back right SpeedController object used to drive
- * the robot.
- */
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(SpeedController* frontLeftMotor, SpeedController* rearLeftMotor,
- SpeedController* frontRightMotor, SpeedController* rearRightMotor);
-
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(SpeedController& frontLeftMotor, SpeedController& rearLeftMotor,
- SpeedController& frontRightMotor, SpeedController& rearRightMotor);
-
- WPI_DEPRECATED("Use DifferentialDrive or MecanumDrive classes instead.")
- RobotDrive(std::shared_ptr<SpeedController> frontLeftMotor,
- std::shared_ptr<SpeedController> rearLeftMotor,
- std::shared_ptr<SpeedController> frontRightMotor,
- std::shared_ptr<SpeedController> rearRightMotor);
-
- virtual ~RobotDrive() = default;
-
- RobotDrive(RobotDrive&&) = default;
- RobotDrive& operator=(RobotDrive&&) = default;
-
- /**
- * Drive the motors at "outputMagnitude" and "curve".
- *
- * Both outputMagnitude and curve are -1.0 to +1.0 values, where 0.0
- * represents stopped and not turning. curve < 0 will turn left and curve > 0
- * will turn right.
- *
- * The algorithm for steering provides a constant turn radius for any normal
- * speed range, both forward and backward. Increasing m_sensitivity causes
- * sharper turns for fixed values of curve.
- *
- * This function will most likely be used in an autonomous routine.
- *
- * @param outputMagnitude The speed setting for the outside wheel in a turn,
- * forward or backwards, +1 to -1.
- * @param curve The rate of turn, constant for different forward
- * speeds. Set curve < 0 for left turn or curve > 0 for
- * right turn.
- *
- * Set curve = e^(-r/w) to get a turn radius r for wheelbase w of your robot.
- * Conversely, turn radius r = -ln(curve)*w for a given value of curve and
- * wheelbase w.
- */
- void Drive(double outputMagnitude, double curve);
-
- /**
- * Provide tank steering using the stored robot configuration.
- *
- * Drive the robot using two joystick inputs. The Y-axis will be selected from
- * each Joystick object.
- *
- * @param leftStick The joystick to control the left side of the robot.
- * @param rightStick The joystick to control the right side of the robot.
- * @param squaredInputs If true, the sensitivity will be decreased for small
- * values
- */
- void TankDrive(GenericHID* leftStick, GenericHID* rightStick,
- bool squaredInputs = true);
-
- /**
- * Provide tank steering using the stored robot configuration.
- *
- * Drive the robot using two joystick inputs. The Y-axis will be selected from
- * each Joystick object.
- *
- * @param leftStick The joystick to control the left side of the robot.
- * @param rightStick The joystick to control the right side of the robot.
- * @param squaredInputs If true, the sensitivity will be decreased for small
- * values
- */
- void TankDrive(GenericHID& leftStick, GenericHID& rightStick,
- bool squaredInputs = true);
-
- /**
- * Provide tank steering using the stored robot configuration.
- *
- * This function lets you pick the axis to be used on each Joystick object for
- * the left and right sides of the robot.
- *
- * @param leftStick The Joystick object to use for the left side of the
- * robot.
- * @param leftAxis The axis to select on the left side Joystick object.
- * @param rightStick The Joystick object to use for the right side of the
- * robot.
- * @param rightAxis The axis to select on the right side Joystick object.
- * @param squaredInputs If true, the sensitivity will be decreased for small
- * values
- */
- void TankDrive(GenericHID* leftStick, int leftAxis, GenericHID* rightStick,
- int rightAxis, bool squaredInputs = true);
-
- void TankDrive(GenericHID& leftStick, int leftAxis, GenericHID& rightStick,
- int rightAxis, bool squaredInputs = true);
-
- /**
- * Provide tank steering using the stored robot configuration.
- *
- * This function lets you directly provide joystick values from any source.
- *
- * @param leftValue The value of the left stick.
- * @param rightValue The value of the right stick.
- * @param squaredInputs If true, the sensitivity will be decreased for small
- * values
- */
- void TankDrive(double leftValue, double rightValue,
- bool squaredInputs = true);
-
- /**
- * Arcade drive implements single stick driving.
- *
- * Given a single Joystick, the class assumes the Y axis for the move value
- * and the X axis for the rotate value. (Should add more information here
- * regarding the way that arcade drive works.)
- *
- * @param stick The joystick to use for Arcade single-stick driving.
- * The Y-axis will be selected for forwards/backwards and
- * the X-axis will be selected for rotation rate.
- * @param squaredInputs If true, the sensitivity will be decreased for small
- * values
- */
- void ArcadeDrive(GenericHID* stick, bool squaredInputs = true);
-
- /**
- * Arcade drive implements single stick driving.
- *
- * Given a single Joystick, the class assumes the Y axis for the move value
- * and the X axis for the rotate value. (Should add more information here
- * regarding the way that arcade drive works.)
- *
- * @param stick The joystick to use for Arcade single-stick driving.
- * The Y-axis will be selected for forwards/backwards and
- * the X-axis will be selected for rotation rate.
- * @param squaredInputs If true, the sensitivity will be decreased for small
- * values
- */
- void ArcadeDrive(GenericHID& stick, bool squaredInputs = true);
-
- /**
- * Arcade drive implements single stick driving.
- *
- * Given two joystick instances and two axis, compute the values to send to
- * either two or four motors.
- *
- * @param moveStick The Joystick object that represents the
- * forward/backward direction
- * @param moveAxis The axis on the moveStick object to use for
- * forwards/backwards (typically Y_AXIS)
- * @param rotateStick The Joystick object that represents the rotation value
- * @param rotateAxis The axis on the rotation object to use for the rotate
- * right/left (typically X_AXIS)
- * @param squaredInputs Setting this parameter to true increases the
- * sensitivity at lower speeds
- */
- void ArcadeDrive(GenericHID* moveStick, int moveChannel,
- GenericHID* rotateStick, int rotateChannel,
- bool squaredInputs = true);
-
- /**
- * Arcade drive implements single stick driving.
- *
- * Given two joystick instances and two axis, compute the values to send to
- * either two or four motors.
- *
- * @param moveStick The Joystick object that represents the
- * forward/backward direction
- * @param moveAxis The axis on the moveStick object to use for
- * forwards/backwards (typically Y_AXIS)
- * @param rotateStick The Joystick object that represents the rotation value
- * @param rotateAxis The axis on the rotation object to use for the rotate
- * right/left (typically X_AXIS)
- * @param squaredInputs Setting this parameter to true increases the
- * sensitivity at lower speeds
- */
- void ArcadeDrive(GenericHID& moveStick, int moveChannel,
- GenericHID& rotateStick, int rotateChannel,
- bool squaredInputs = true);
-
- /**
- * Arcade drive implements single stick driving.
- *
- * This function lets you directly provide joystick values from any source.
- *
- * @param moveValue The value to use for fowards/backwards
- * @param rotateValue The value to use for the rotate right/left
- * @param squaredInputs If set, increases the sensitivity at low speeds
- */
- void ArcadeDrive(double moveValue, double rotateValue,
- bool squaredInputs = true);
-
- /**
- * Drive method for Mecanum wheeled robots.
- *
- * A method for driving with Mecanum wheeled robots. There are 4 wheels
- * on the robot, arranged so that the front and back wheels are toed in 45
- * degrees.
- * When looking at the wheels from the top, the roller axles should form an X
- * across the robot.
- *
- * This is designed to be directly driven by joystick axes.
- *
- * @param x The speed that the robot should drive in the X direction.
- * [-1.0..1.0]
- * @param y The speed that the robot should drive in the Y direction.
- * This input is inverted to match the forward == -1.0 that
- * joysticks produce. [-1.0..1.0]
- * @param rotation The rate of rotation for the robot that is completely
- * independent of the translation. [-1.0..1.0]
- * @param gyroAngle The current angle reading from the gyro. Use this to
- * implement field-oriented controls.
- */
- void MecanumDrive_Cartesian(double x, double y, double rotation,
- double gyroAngle = 0.0);
-
- /**
- * Drive method for Mecanum wheeled robots.
- *
- * A method for driving with Mecanum wheeled robots. There are 4 wheels
- * on the robot, arranged so that the front and back wheels are toed in 45
- * degrees.
- * When looking at the wheels from the top, the roller axles should form an X
- * across the robot.
- *
- * @param magnitude The speed that the robot should drive in a given
- * direction. [-1.0..1.0]
- * @param direction The direction the robot should drive in degrees. The
- * direction and maginitute are independent of the rotation
- * rate.
- * @param rotation The rate of rotation for the robot that is completely
- * independent of the magnitute or direction. [-1.0..1.0]
- */
- void MecanumDrive_Polar(double magnitude, double direction, double rotation);
-
- /**
- * Holonomic Drive method for Mecanum wheeled robots.
- *
- * This is an alias to MecanumDrive_Polar() for backward compatibility
- *
- * @param magnitude The speed that the robot should drive in a given
- * direction. [-1.0..1.0]
- * @param direction The direction the robot should drive. The direction and
- * magnitude are independent of the rotation rate.
- * @param rotation The rate of rotation for the robot that is completely
- * independent of the magnitude or direction. [-1.0..1.0]
- */
- void HolonomicDrive(double magnitude, double direction, double rotation);
-
- /**
- * Set the speed of the right and left motors.
- *
- * This is used once an appropriate drive setup function is called such as
- * TwoWheelDrive(). The motors are set to "leftOutput" and "rightOutput"
- * and includes flipping the direction of one side for opposing motors.
- *
- * @param leftOutput The speed to send to the left side of the robot.
- * @param rightOutput The speed to send to the right side of the robot.
- */
- virtual void SetLeftRightMotorOutputs(double leftOutput, double rightOutput);
-
- /*
- * Invert a motor direction.
- *
- * This is used when a motor should run in the opposite direction as the drive
- * code would normally run it. Motors that are direct drive would be inverted,
- * the Drive code assumes that the motors are geared with one reversal.
- *
- * @param motor The motor index to invert.
- * @param isInverted True if the motor should be inverted when operated.
- */
- void SetInvertedMotor(MotorType motor, bool isInverted);
-
- /**
- * Set the turning sensitivity.
- *
- * This only impacts the Drive() entry-point.
- *
- * @param sensitivity Effectively sets the turning sensitivity (or turn radius
- * for a given value)
- */
- void SetSensitivity(double sensitivity);
-
- /**
- * Configure the scaling factor for using RobotDrive with motor controllers in
- * a mode other than PercentVbus.
- *
- * @param maxOutput Multiplied with the output percentage computed by the
- * drive functions.
- */
- void SetMaxOutput(double maxOutput);
-
- void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
-
- protected:
- /**
- * Common function to initialize all the robot drive constructors.
- *
- * Create a motor safety object (the real reason for the common code) and
- * initialize all the motor assignments. The default timeout is set for the
- * robot drive.
- */
- void InitRobotDrive();
-
- /**
- * Limit motor values to the -1.0 to +1.0 range.
- */
- double Limit(double number);
-
- /**
- * Normalize all wheel speeds if the magnitude of any wheel is greater than
- * 1.0.
- */
- void Normalize(double* wheelSpeeds);
-
- /**
- * Rotate a vector in Cartesian space.
- */
- void RotateVector(double& x, double& y, double angle);
-
- static constexpr int kMaxNumberOfMotors = 4;
-
- double m_sensitivity = 0.5;
- double m_maxOutput = 1.0;
-
- std::shared_ptr<SpeedController> m_frontLeftMotor;
- std::shared_ptr<SpeedController> m_frontRightMotor;
- std::shared_ptr<SpeedController> m_rearLeftMotor;
- std::shared_ptr<SpeedController> m_rearRightMotor;
-
- private:
- int GetNumMotors() {
- int motors = 0;
- if (m_frontLeftMotor) motors++;
- if (m_frontRightMotor) motors++;
- if (m_rearLeftMotor) motors++;
- if (m_rearRightMotor) motors++;
- return motors;
- }
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/RobotState.h b/wpilibc/src/main/native/include/frc/RobotState.h
index 5f1c136..cb97b13 100644
--- a/wpilibc/src/main/native/include/frc/RobotState.h
+++ b/wpilibc/src/main/native/include/frc/RobotState.h
@@ -1,12 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
+#include <wpi/deprecated.h>
+
namespace frc {
class RobotState {
@@ -16,7 +15,9 @@
static bool IsDisabled();
static bool IsEnabled();
static bool IsEStopped();
+ WPI_DEPRECATED("Use IsTeleop() instead")
static bool IsOperatorControl();
+ static bool IsTeleop();
static bool IsAutonomous();
static bool IsTest();
};
diff --git a/wpilibc/src/main/native/include/frc/RuntimeType.h b/wpilibc/src/main/native/include/frc/RuntimeType.h
new file mode 100644
index 0000000..c3a8a0b
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/RuntimeType.h
@@ -0,0 +1,9 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+namespace frc {
+enum RuntimeType { kRoboRIO, kRoboRIO2, kSimulation };
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/SPI.h b/wpilibc/src/main/native/include/frc/SPI.h
index 3592775..36c82e4 100644
--- a/wpilibc/src/main/native/include/frc/SPI.h
+++ b/wpilibc/src/main/native/include/frc/SPI.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -13,10 +10,8 @@
#include <hal/SPITypes.h>
#include <units/time.h>
-#include <wpi/ArrayRef.h>
#include <wpi/deprecated.h>
-
-#include "frc/ErrorBase.h"
+#include <wpi/span.h>
namespace frc {
@@ -29,7 +24,7 @@
* It probably should not be used directly.
*
*/
-class SPI : public ErrorBase {
+class SPI {
public:
enum Port { kOnboardCS0 = 0, kOnboardCS1, kOnboardCS2, kOnboardCS3, kMXP };
@@ -40,11 +35,13 @@
*/
explicit SPI(Port port);
- ~SPI() override;
+ ~SPI();
SPI(SPI&&) = default;
SPI& operator=(SPI&&) = default;
+ Port GetPort() const;
+
/**
* Configure the rate of the generated clock signal.
*
@@ -138,10 +135,12 @@
* If the receive FIFO is empty, there is no active transfer, and initiate
* is false, errors.
*
- * @param initiate If true, this function pushes "0" into the transmit buffer
- * and initiates a transfer. If false, this function assumes
- * that data is already in the receive FIFO from a previous
- * write.
+ * @param initiate If true, this function pushes "0" into the transmit
+ * buffer and initiates a transfer. If false, this
+ * function assumes that data is already in the receive
+ * FIFO from a previous write.
+ * @param dataReceived Buffer to receive data from the device
+ * @param size The length of the transaction, in bytes
*/
virtual int Read(bool initiate, uint8_t* dataReceived, int size);
@@ -178,7 +177,7 @@
* @param dataToSend data to send (maximum 16 bytes)
* @param zeroSize number of zeros to send after the data
*/
- void SetAutoTransmitData(wpi::ArrayRef<uint8_t> dataToSend, int zeroSize);
+ void SetAutoTransmitData(wpi::span<const uint8_t> dataToSend, int zeroSize);
/**
* Start running the automatic SPI transfer engine at a periodic rate.
@@ -248,32 +247,6 @@
units::second_t timeout);
/**
- * Read data that has been transferred by the automatic SPI transfer engine.
- *
- * Transfers may be made a byte at a time, so it's necessary for the caller
- * to handle cases where an entire transfer has not been completed.
- *
- * Each received data sequence consists of a timestamp followed by the
- * received data bytes, one byte per word (in the least significant byte).
- * The length of each received data sequence is the same as the combined
- * size of the data and zeroSize set in SetAutoTransmitData().
- *
- * Blocks until numToRead words have been read or timeout expires.
- * May be called with numToRead=0 to retrieve how many words are available.
- *
- * @deprecated Use unit safe version instead.
- * ReadAutoReceivedData(uint32_t* buffer, int numToRead, <!--
- * --> units::second_t timeout)
- *
- * @param buffer buffer where read words are stored
- * @param numToRead number of words to read
- * @param timeout timeout in seconds (ms resolution)
- * @return Number of words remaining to be read
- */
- WPI_DEPRECATED("Use ReadAutoReceivedData with unit-safety instead")
- int ReadAutoReceivedData(uint32_t* buffer, int numToRead, double timeout);
-
- /**
* Get the number of bytes dropped by the automatic SPI transfer engine due
* to the receive buffer being full.
*
@@ -297,17 +270,17 @@
/**
* Initialize the accumulator.
*
- * @param period Time between reads
- * @param cmd SPI command to send to request data
- * @param xferSize SPI transfer size, in bytes
- * @param validMask Mask to apply to received data for validity checking
- * @param validData After valid_mask is applied, required matching value for
- * validity checking
- * @param dataShift Bit shift to apply to received data to get actual data
- * value
- * @param dataSize Size (in bits) of data field
- * @param isSigned Is data field signed?
- * @param bigEndian Is device big endian?
+ * @param period Time between reads
+ * @param cmd SPI command to send to request data
+ * @param xferSize SPI transfer size, in bytes
+ * @param validMask Mask to apply to received data for validity checking
+ * @param validValue After valid_mask is applied, required matching value for
+ * validity checking
+ * @param dataShift Bit shift to apply to received data to get actual data
+ * value
+ * @param dataSize Size (in bits) of data field
+ * @param isSigned Is data field signed?
+ * @param bigEndian Is device big endian?
*/
void InitAccumulator(units::second_t period, int cmd, int xferSize,
int validMask, int validValue, int dataShift,
@@ -321,17 +294,17 @@
* --> xferSize, int validMask, int validValue, int dataShift, <!--
* --> int dataSize, bool isSigned, bool bigEndian)
*
- * @param period Time between reads
- * @param cmd SPI command to send to request data
- * @param xferSize SPI transfer size, in bytes
- * @param validMask Mask to apply to received data for validity checking
- * @param validData After valid_mask is applied, required matching value for
- * validity checking
- * @param dataShift Bit shift to apply to received data to get actual data
- * value
- * @param dataSize Size (in bits) of data field
- * @param isSigned Is data field signed?
- * @param bigEndian Is device big endian?
+ * @param period Time between reads
+ * @param cmd SPI command to send to request data
+ * @param xferSize SPI transfer size, in bytes
+ * @param validMask Mask to apply to received data for validity checking
+ * @param validValue After valid_mask is applied, required matching value for
+ * validity checking
+ * @param dataShift Bit shift to apply to received data to get actual data
+ * value
+ * @param dataSize Size (in bits) of data field
+ * @param isSigned Is data field signed?
+ * @param bigEndian Is device big endian?
*/
WPI_DEPRECATED("Use InitAccumulator with unit-safety instead")
void InitAccumulator(double period, int cmd, int xferSize, int validMask,
diff --git a/wpilibc/src/main/native/include/frc/ScopedTracer.h b/wpilibc/src/main/native/include/frc/ScopedTracer.h
index 8634c1e..e700616 100644
--- a/wpilibc/src/main/native/include/frc/ScopedTracer.h
+++ b/wpilibc/src/main/native/include/frc/ScopedTracer.h
@@ -1,16 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <string>
-
-#include <wpi/StringRef.h>
-#include <wpi/Twine.h>
+#include <string_view>
#include "frc/Tracer.h"
@@ -34,7 +29,7 @@
* @param name The name of the epoch.
* @param os A reference to the raw_ostream to print data to.
*/
- ScopedTracer(wpi::Twine name, wpi::raw_ostream& os);
+ ScopedTracer(std::string_view name, wpi::raw_ostream& os);
~ScopedTracer();
ScopedTracer(const ScopedTracer&) = delete;
diff --git a/wpilibc/src/main/native/include/frc/SensorUtil.h b/wpilibc/src/main/native/include/frc/SensorUtil.h
index ab471b1..60536b1 100644
--- a/wpilibc/src/main/native/include/frc/SensorUtil.h
+++ b/wpilibc/src/main/native/include/frc/SensorUtil.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -22,14 +19,14 @@
*
* @return The number of the default solenoid module.
*/
- static int GetDefaultSolenoidModule();
+ static int GetDefaultCTREPCMModule();
/**
- * Check that the solenoid module number is valid. module numbers are 0-based
+ * Get the number of the default solenoid module.
*
- * @return Solenoid module is valid and present
+ * @return The number of the default solenoid module.
*/
- static bool CheckSolenoidModule(int moduleNumber);
+ static int GetDefaultREVPHModule();
/**
* Check that the digital channel number is valid.
@@ -81,36 +78,11 @@
*/
static bool CheckAnalogOutputChannel(int channel);
- /**
- * Verify that the solenoid channel number is within limits.
- *
- * @return Solenoid channel is valid
- */
- static bool CheckSolenoidChannel(int channel);
-
- /**
- * Verify that the power distribution channel number is within limits.
- *
- * @return PDP channel is valid
- */
- static bool CheckPDPChannel(int channel);
-
- /**
- * Verify that the PDP module number is within limits. module numbers are
- * 0-based
- *
- * @return PDP module is valid
- */
- static bool CheckPDPModule(int module);
-
static const int kDigitalChannels;
static const int kAnalogInputs;
static const int kAnalogOutputs;
- static const int kSolenoidChannels;
- static const int kSolenoidModules;
static const int kPwmChannels;
static const int kRelayChannels;
- static const int kPDPChannels;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/SerialPort.h b/wpilibc/src/main/native/include/frc/SerialPort.h
index 7c44c75..7fff14a 100644
--- a/wpilibc/src/main/native/include/frc/SerialPort.h
+++ b/wpilibc/src/main/native/include/frc/SerialPort.h
@@ -1,20 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <string>
+#include <string_view>
#include <hal/Types.h>
-#include <wpi/StringRef.h>
-#include <wpi/Twine.h>
-#include <wpi/deprecated.h>
-
-#include "frc/ErrorBase.h"
+#include <units/time.h>
namespace frc {
@@ -30,7 +24,7 @@
* and the NI-VISA Programmer's Reference Manual here:
* http://www.ni.com/pdf/manuals/370132c.pdf
*/
-class SerialPort : public ErrorBase {
+class SerialPort {
public:
enum Parity {
kParity_None = 0,
@@ -68,8 +62,9 @@
* @param stopBits The number of stop bits to use as defined by the enum
* StopBits.
*/
- SerialPort(int baudRate, Port port = kOnboard, int dataBits = 8,
- Parity parity = kParity_None, StopBits stopBits = kStopBits_One);
+ explicit SerialPort(int baudRate, Port port = kOnboard, int dataBits = 8,
+ Parity parity = kParity_None,
+ StopBits stopBits = kStopBits_One);
/**
* Create an instance of a Serial Port class.
@@ -86,7 +81,7 @@
* @param stopBits The number of stop bits to use as defined by the enum
* StopBits.
*/
- SerialPort(int baudRate, const wpi::Twine& portName, Port port = kOnboard,
+ SerialPort(int baudRate, std::string_view portName, Port port = kOnboard,
int dataBits = 8, Parity parity = kParity_None,
StopBits stopBits = kStopBits_One);
@@ -149,10 +144,10 @@
* Use Write({data, len}) to get a buffer that is shorter than the length of
* the string.
*
- * @param buffer StringRef to the buffer to read the bytes from.
+ * @param buffer the buffer to read the bytes from.
* @return The number of bytes actually written into the port.
*/
- int Write(wpi::StringRef buffer);
+ int Write(std::string_view buffer);
/**
* Configure the timeout of the serial port.
@@ -160,9 +155,9 @@
* This defines the timeout for transactions with the hardware.
* It will affect reads and very large writes.
*
- * @param timeout The number of seconds to to wait for I/O.
+ * @param timeout The time to wait for I/O.
*/
- void SetTimeout(double timeout);
+ void SetTimeout(units::second_t timeout);
/**
* Specify the size of the input buffer.
diff --git a/wpilibc/src/main/native/include/frc/Servo.h b/wpilibc/src/main/native/include/frc/Servo.h
index 16b4281..b1df655 100644
--- a/wpilibc/src/main/native/include/frc/Servo.h
+++ b/wpilibc/src/main/native/include/frc/Servo.h
@@ -1,14 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include "frc/PWM.h"
-#include "frc/SpeedController.h"
namespace frc {
@@ -68,7 +64,7 @@
* X being set and angles of more than Y degrees result in an angle of Y being
* set.
*
- * @param degrees The angle in degrees to set the servo.
+ * @param angle The angle in degrees to set the servo.
*/
void SetAngle(double angle);
@@ -96,7 +92,7 @@
*/
double GetMinAngle() const;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
double GetServoAngleRange() const;
diff --git a/wpilibc/src/main/native/include/frc/SlewRateLimiter.h b/wpilibc/src/main/native/include/frc/SlewRateLimiter.h
deleted file mode 100644
index d18fb09..0000000
--- a/wpilibc/src/main/native/include/frc/SlewRateLimiter.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <frc2/Timer.h>
-
-#include <algorithm>
-
-#include <units/time.h>
-
-namespace frc {
-/**
- * A class that limits the rate of change of an input value. Useful for
- * implementing voltage, setpoint, and/or output ramps. A slew-rate limit
- * is most appropriate when the quantity being controlled is a velocity or
- * a voltage; when controlling a position, consider using a TrapezoidProfile
- * instead.
- *
- * @see TrapezoidProfile
- */
-template <class Unit>
-class SlewRateLimiter {
- public:
- using Unit_t = units::unit_t<Unit>;
- using Rate = units::compound_unit<Unit, units::inverse<units::seconds>>;
- using Rate_t = units::unit_t<Rate>;
-
- /**
- * Creates a new SlewRateLimiter with the given rate limit and initial value.
- *
- * @param rateLimit The rate-of-change limit.
- * @param initialValue The initial value of the input.
- */
- explicit SlewRateLimiter(Rate_t rateLimit, Unit_t initialValue = Unit_t{0})
- : m_rateLimit{rateLimit},
- m_prevVal{initialValue},
- m_prevTime{frc2::Timer::GetFPGATimestamp()} {}
-
- /**
- * Filters the input to limit its slew rate.
- *
- * @param input The input value whose slew rate is to be limited.
- * @return The filtered value, which will not change faster than the slew
- * rate.
- */
- Unit_t Calculate(Unit_t input) {
- units::second_t currentTime = frc2::Timer::GetFPGATimestamp();
- units::second_t elapsedTime = currentTime - m_prevTime;
- m_prevVal += std::clamp(input - m_prevVal, -m_rateLimit * elapsedTime,
- m_rateLimit * elapsedTime);
- m_prevTime = currentTime;
- return m_prevVal;
- }
-
- /**
- * Resets the slew rate limiter to the specified value; ignores the rate limit
- * when doing so.
- *
- * @param value The value to reset to.
- */
- void Reset(Unit_t value) {
- m_prevVal = value;
- m_prevTime = frc2::Timer::GetFPGATimestamp();
- }
-
- private:
- Rate_t m_rateLimit;
- Unit_t m_prevVal;
- units::second_t m_prevTime;
-};
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Solenoid.h b/wpilibc/src/main/native/include/frc/Solenoid.h
index 9939b41..a09ffc0 100644
--- a/wpilibc/src/main/native/include/frc/Solenoid.h
+++ b/wpilibc/src/main/native/include/frc/Solenoid.h
@@ -1,46 +1,46 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <hal/Types.h>
+#include <memory>
-#include "frc/SolenoidBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <hal/Types.h>
+#include <units/time.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/PneumaticsBase.h"
+#include "frc/PneumaticsModuleType.h"
namespace frc {
-class SendableBuilder;
-
/**
- * Solenoid class for running high voltage Digital Output (PCM).
+ * Solenoid class for running high voltage Digital Output on a pneumatics
+ * module.
*
* The Solenoid class is typically used for pneumatics solenoids, but could be
- * used for any device within the current spec of the PCM.
+ * used for any device within the current spec of the module.
*/
-class Solenoid : public SolenoidBase,
- public Sendable,
- public SendableHelper<Solenoid> {
+class Solenoid : public wpi::Sendable, public wpi::SendableHelper<Solenoid> {
public:
/**
- * Constructor using the default PCM ID (0).
+ * Constructs a solenoid for a specified module and type.
*
- * @param channel The channel on the PCM to control (0..7).
+ * @param module The module ID to use.
+ * @param moduleType The module type to use.
+ * @param channel The channel the solenoid is on.
*/
- explicit Solenoid(int channel);
+ Solenoid(int module, PneumaticsModuleType moduleType, int channel);
/**
- * Constructor.
+ * Constructs a solenoid for a default module and specified type.
*
- * @param moduleNumber The CAN ID of the PCM the solenoid is attached to
- * @param channel The channel on the PCM to control (0..7).
+ * @param moduleType The module type to use.
+ * @param channel The channel the solenoid is on.
*/
- Solenoid(int moduleNumber, int channel);
+ Solenoid(PneumaticsModuleType moduleType, int channel);
~Solenoid() override;
@@ -70,42 +70,47 @@
void Toggle();
/**
- * Check if solenoid is blacklisted.
+ * Get the channel this solenoid is connected to.
+ */
+ int GetChannel() const;
+
+ /**
+ * Check if solenoid is Disabled.
*
- * If a solenoid is shorted, it is added to the blacklist and
+ * If a solenoid is shorted, it is added to the DisabledList and
* disabled until power cycle, or until faults are cleared.
*
* @see ClearAllPCMStickyFaults()
*
* @return If solenoid is disabled due to short.
*/
- bool IsBlackListed() const;
+ bool IsDisabled() const;
/**
* Set the pulse duration in the PCM. This is used in conjunction with
* the startPulse method to allow the PCM to control the timing of a pulse.
* The timing can be controlled in 0.01 second increments.
*
- * @param durationSeconds The duration of the pulse, from 0.01 to 2.55
- * seconds.
+ * @param duration The duration of the pulse, from 0.01 to 2.55 seconds.
*
* @see startPulse()
*/
- void SetPulseDuration(double durationSeconds);
+ void SetPulseDuration(units::second_t duration);
/**
- * Trigger the PCM to generate a pulse of the duration set in
+ * %Trigger the PCM to generate a pulse of the duration set in
* setPulseDuration.
*
* @see setPulseDuration()
*/
void StartPulse();
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
- hal::Handle<HAL_SolenoidHandle> m_solenoidHandle;
- int m_channel; // The channel on the module to control
+ std::shared_ptr<PneumaticsBase> m_module;
+ int m_mask;
+ int m_channel;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/SolenoidBase.h b/wpilibc/src/main/native/include/frc/SolenoidBase.h
deleted file mode 100644
index 314df5c..0000000
--- a/wpilibc/src/main/native/include/frc/SolenoidBase.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/ErrorBase.h"
-
-namespace frc {
-
-/**
- * SolenoidBase class is the common base class for the Solenoid and
- * DoubleSolenoid classes.
- */
-class SolenoidBase : public ErrorBase {
- public:
- /**
- * Read all 8 solenoids as a single byte
- *
- * @param module the module to read from
- * @return The current value of all 8 solenoids on the module.
- */
- static int GetAll(int module);
-
- /**
- * Read all 8 solenoids as a single byte
- *
- * @return The current value of all 8 solenoids on the module.
- */
- int GetAll() const;
-
- /**
- * Reads complete solenoid blacklist for all 8 solenoids as a single byte.
- *
- * If a solenoid is shorted, it is added to the blacklist and
- * disabled until power cycle, or until faults are cleared.
- * @see ClearAllPCMStickyFaults()
- *
- * @param module the module to read from
- * @return The solenoid blacklist of all 8 solenoids on the module.
- */
- static int GetPCMSolenoidBlackList(int module);
-
- /**
- * Reads complete solenoid blacklist for all 8 solenoids as a single byte.
- *
- * If a solenoid is shorted, it is added to the blacklist and
- * disabled until power cycle, or until faults are cleared.
- * @see ClearAllPCMStickyFaults()
- *
- * @return The solenoid blacklist of all 8 solenoids on the module.
- */
- int GetPCMSolenoidBlackList() const;
-
- /**
- * @param module the module to read from
- * @return true if PCM sticky fault is set : The common highside solenoid
- * voltage rail is too low, most likely a solenoid channel is shorted.
- */
- static bool GetPCMSolenoidVoltageStickyFault(int module);
-
- /**
- * @return true if PCM sticky fault is set : The common highside solenoid
- * voltage rail is too low, most likely a solenoid channel is shorted.
- */
- bool GetPCMSolenoidVoltageStickyFault() const;
-
- /**
- * @param module the module to read from
- * @return true if PCM is in fault state : The common highside solenoid
- * voltage rail is too low, most likely a solenoid channel is shorted.
- */
- static bool GetPCMSolenoidVoltageFault(int module);
-
- /**
- * @return true if PCM is in fault state : The common highside solenoid
- * voltage rail is too low, most likely a solenoid channel is shorted.
- */
- bool GetPCMSolenoidVoltageFault() const;
-
- /**
- * Clear ALL sticky faults inside PCM that Compressor is wired to.
- *
- * If a sticky fault is set, then it will be persistently cleared. Compressor
- * drive maybe momentarily disable while flags are being cleared. Care should
- * be taken to not call this too frequently, otherwise normal compressor
- * functionality may be prevented.
- *
- * If no sticky faults are set then this call will have no effect.
- *
- * @param module the module to read from
- */
- static void ClearAllPCMStickyFaults(int module);
-
- /**
- * Clear ALL sticky faults inside PCM that Compressor is wired to.
- *
- * If a sticky fault is set, then it will be persistently cleared. Compressor
- * drive maybe momentarily disable while flags are being cleared. Care should
- * be taken to not call this too frequently, otherwise normal compressor
- * functionality may be prevented.
- *
- * If no sticky faults are set then this call will have no effect.
- */
- void ClearAllPCMStickyFaults();
-
- protected:
- /**
- * Constructor.
- *
- * @param moduleNumber The CAN PCM ID.
- */
- explicit SolenoidBase(int pcmID);
-
- SolenoidBase(SolenoidBase&&) = default;
- SolenoidBase& operator=(SolenoidBase&&) = default;
-
- static constexpr int m_maxModules = 63;
- static constexpr int m_maxPorts = 8;
-
- int m_moduleNumber; // PCM module number
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/SpeedController.h b/wpilibc/src/main/native/include/frc/SpeedController.h
index 3053c3b..8473015 100644
--- a/wpilibc/src/main/native/include/frc/SpeedController.h
+++ b/wpilibc/src/main/native/include/frc/SpeedController.h
@@ -1,22 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <units/voltage.h>
-
-#include "frc/PIDOutput.h"
+#include <wpi/deprecated.h>
namespace frc {
/**
* Interface for speed controlling devices.
+ *
+ * @deprecated Use MotorController.
*/
-class SpeedController : public PIDOutput {
+class WPI_DEPRECATED("use MotorController") SpeedController {
public:
virtual ~SpeedController() = default;
diff --git a/wpilibc/src/main/native/include/frc/SpeedControllerGroup.h b/wpilibc/src/main/native/include/frc/SpeedControllerGroup.h
index e62563c..5a097b5 100644
--- a/wpilibc/src/main/native/include/frc/SpeedControllerGroup.h
+++ b/wpilibc/src/main/native/include/frc/SpeedControllerGroup.h
@@ -1,24 +1,29 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
#include <vector>
-#include "frc/SpeedController.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/deprecated.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/motorcontrol/MotorController.h"
namespace frc {
-class SpeedControllerGroup : public Sendable,
- public SpeedController,
- public SendableHelper<SpeedControllerGroup> {
+/**
+ * Allows multiple SpeedController objects to be linked together.
+ *
+ * @deprecated Use MotorControllerGroup.
+ */
+class WPI_DEPRECATED("use MotorControllerGroup") SpeedControllerGroup
+ : public wpi::Sendable,
+ public MotorController,
+ public wpi::SendableHelper<SpeedControllerGroup> {
public:
template <class... SpeedControllers>
explicit SpeedControllerGroup(SpeedController& speedController,
@@ -35,9 +40,8 @@
bool GetInverted() const override;
void Disable() override;
void StopMotor() override;
- void PIDWrite(double output) override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
bool m_isInverted = false;
diff --git a/wpilibc/src/main/native/include/frc/SpeedControllerGroup.inc b/wpilibc/src/main/native/include/frc/SpeedControllerGroup.inc
index d9e773d..d5f17b4 100644
--- a/wpilibc/src/main/native/include/frc/SpeedControllerGroup.inc
+++ b/wpilibc/src/main/native/include/frc/SpeedControllerGroup.inc
@@ -1,15 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
#include <vector>
+#include "frc/SpeedControllerGroup.h"
+
namespace frc {
template <class... SpeedControllers>
diff --git a/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h b/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h
new file mode 100644
index 0000000..03cc4f8
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/SynchronousInterrupt.h
@@ -0,0 +1,106 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include <hal/Types.h>
+#include <units/time.h>
+
+namespace frc {
+class DigitalSource;
+
+/**
+ * Class for handling synchronous (blocking) interrupts.
+ *
+ * <p> By default, interrupts will occur on rising edge.
+ *
+ * <p> Asynchronous interrupts are handled by the AsynchronousInterrupt class.
+ */
+class SynchronousInterrupt {
+ public:
+ enum WaitResult {
+ kTimeout = 0x0,
+ kRisingEdge = 0x1,
+ kFallingEdge = 0x100,
+ kBoth = 0x101,
+ };
+
+ /**
+ * Construct a Synchronous Interrupt from a Digital Source.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ */
+ explicit SynchronousInterrupt(DigitalSource& source);
+
+ /**
+ * Construct a Synchronous Interrupt from a Digital Source.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ */
+ explicit SynchronousInterrupt(DigitalSource* source);
+
+ /**
+ * Construct a Synchronous Interrupt from a Digital Source.
+ *
+ * @param source the DigitalSource the interrupts are triggered from
+ */
+ explicit SynchronousInterrupt(std::shared_ptr<DigitalSource> source);
+
+ ~SynchronousInterrupt();
+
+ SynchronousInterrupt(SynchronousInterrupt&&) = default;
+ SynchronousInterrupt& operator=(SynchronousInterrupt&&) = default;
+
+ /**
+ * Wait for an interrupt to occur.
+ *
+ * <p> Both rising and falling edge can be returned if both a rising and
+ * falling happened between calls, and ignorePrevious is false.
+ *
+ * @param timeout The timeout to wait for. 0s or less will return immediately.
+ * @param ignorePrevious True to ignore any previous interrupts, false to
+ * return interrupt value if an interrupt has occured since last call.
+ * @return The edge(s) that were triggered, or timeout.
+ */
+ WaitResult WaitForInterrupt(units::second_t timeout,
+ bool ignorePrevious = true);
+
+ /**
+ * Set which edges cause an interrupt to occur.
+ *
+ * @param risingEdge true to trigger on rising edge, false otherwise.
+ * @param fallingEdge true to trigger on falling edge, false otherwise
+ */
+ void SetInterruptEdges(bool risingEdge, bool fallingEdge);
+
+ /**
+ * Get the timestamp (relative to FPGA Time) of the last rising edge.
+ *
+ * @return the timestamp in seconds relative to getFPGATime
+ */
+ units::second_t GetRisingTimestamp();
+
+ /**
+ * Get the timestamp of the last falling edge.
+ *
+ * <p>This function does not require the interrupt to be enabled to work.
+ *
+ * <p>This only works if falling edge was configured using setInterruptEdges.
+ * @return the timestamp in seconds relative to getFPGATime
+ */
+ units::second_t GetFallingTimestamp();
+
+ /**
+ * Wake up an existing wait call. Can be called from any thread.
+ */
+ void WakeupWaitingInterrupt();
+
+ private:
+ void InitSynchronousInterrupt();
+ std::shared_ptr<DigitalSource> m_source;
+ hal::Handle<HAL_InterruptHandle> m_handle;
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Talon.h b/wpilibc/src/main/native/include/frc/Talon.h
deleted file mode 100644
index 6e92dfc..0000000
--- a/wpilibc/src/main/native/include/frc/Talon.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWMSpeedController.h"
-
-namespace frc {
-
-/**
- * Cross the Road Electronics (CTRE) Talon and Talon SR Speed Controller.
- *
- * Note that the Talon uses the following bounds for PWM values. These values
- * should work reasonably well for most controllers, but if users experience
- * issues such as asymmetric behavior around the deadband or inability to
- * saturate the controller in either direction, calibration is recommended.
- * The calibration procedure can be found in the Talon User Manual available
- * from CTRE.
- *
- * \li 2.037ms = full "forward"
- * \li 1.539ms = the "high end" of the deadband range
- * \li 1.513ms = center of the deadband range (off)
- * \li 1.487ms = the "low end" of the deadband range
- * \li 0.989ms = full "reverse"
- */
-class Talon : public PWMSpeedController {
- public:
- /**
- * Constructor for a Talon (original or Talon SR).
- *
- * @param channel The PWM channel number that the Talon is attached to. 0-9
- * are on-board, 10-19 are on the MXP port
- */
- explicit Talon(int channel);
-
- Talon(Talon&&) = default;
- Talon& operator=(Talon&&) = default;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Threads.h b/wpilibc/src/main/native/include/frc/Threads.h
index 3c44961..5822670 100644
--- a/wpilibc/src/main/native/include/frc/Threads.h
+++ b/wpilibc/src/main/native/include/frc/Threads.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -15,43 +12,45 @@
* Get the thread priority for the specified thread.
*
* @param thread Reference to the thread to get the priority for.
- * @param isRealTime Set to true if thread is realtime, otherwise false.
- * @return The current thread priority. Scaled 1-99, with 1 being highest.
+ * @param isRealTime Set to true if thread is real-time, otherwise false.
+ * @return The current thread priority. For real-time, this is 1-99
+ * with 99 being highest. For non-real-time, this is 0. See
+ * "man 7 sched" for details.
*/
int GetThreadPriority(std::thread& thread, bool* isRealTime);
/**
- * Get the thread priority for the current thread
+ * Get the thread priority for the current thread.
*
- * @param isRealTime Set to true if thread is realtime, otherwise false.
- * @return The current thread priority. Scaled 1-99.
+ * @param isRealTime Set to true if thread is real-time, otherwise false.
+ * @return The current thread priority. For real-time, this is 1-99
+ * with 99 being highest. For non-real-time, this is 0. See
+ * "man 7 sched" for details.
*/
int GetCurrentThreadPriority(bool* isRealTime);
/**
- * Sets the thread priority for the specified thread
+ * Sets the thread priority for the specified thread.
*
* @param thread Reference to the thread to set the priority of.
- * @param realTime Set to true to set a realtime priority, false for standard
+ * @param realTime Set to true to set a real-time priority, false for standard
* priority.
- * @param priority Priority to set the thread to. Scaled 1-99, with 1 being
- * highest. On RoboRIO, priority is ignored for non realtime
- * setting.
- *
- * @return The success state of setting the priority
+ * @param priority Priority to set the thread to. For real-time, this is 1-99
+ * with 99 being highest. For non-real-time, this is forced to
+ * 0. See "man 7 sched" for more details.
+ * @return True on success.
*/
bool SetThreadPriority(std::thread& thread, bool realTime, int priority);
/**
- * Sets the thread priority for the current thread
+ * Sets the thread priority for the current thread.
*
- * @param realTime Set to true to set a realtime priority, false for standard
+ * @param realTime Set to true to set a real-time priority, false for standard
* priority.
- * @param priority Priority to set the thread to. Scaled 1-99, with 1 being
- * highest. On RoboRIO, priority is ignored for non realtime
- * setting.
- *
- * @return The success state of setting the priority
+ * @param priority Priority to set the thread to. For real-time, this is 1-99
+ * with 99 being highest. For non-real-time, this is forced to
+ * 0. See "man 7 sched" for more details.
+ * @return True on success.
*/
bool SetCurrentThreadPriority(bool realTime, int priority);
diff --git a/wpilibc/src/main/native/include/frc/TimedRobot.h b/wpilibc/src/main/native/include/frc/TimedRobot.h
index 9dbc3f2..cc64c03 100644
--- a/wpilibc/src/main/native/include/frc/TimedRobot.h
+++ b/wpilibc/src/main/native/include/frc/TimedRobot.h
@@ -1,13 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
+#include <utility>
#include <vector>
#include <hal/Types.h>
@@ -16,9 +14,8 @@
#include <wpi/deprecated.h>
#include <wpi/priority_queue.h>
-#include "frc/ErrorBase.h"
#include "frc/IterativeRobotBase.h"
-#include "frc2/Timer.h"
+#include "frc/Timer.h"
namespace frc {
@@ -31,9 +28,9 @@
* Periodic() functions from the base class are called on an interval by a
* Notifier instance.
*/
-class TimedRobot : public IterativeRobotBase, public ErrorBase {
+class TimedRobot : public IterativeRobotBase {
public:
- static constexpr units::second_t kDefaultPeriod = 20_ms;
+ static constexpr auto kDefaultPeriod = 20_ms;
/**
* Provide an alternate "main loop" via StartCompetition().
@@ -46,11 +43,6 @@
void EndCompetition() override;
/**
- * Get the time period between calls to Periodic() functions.
- */
- units::second_t GetPeriod() const;
-
- /**
* Constructor for TimedRobot.
*
* @deprecated use unit safe constructor instead.
@@ -105,14 +97,13 @@
*/
Callback(std::function<void()> func, units::second_t startTime,
units::second_t period, units::second_t offset)
- : func{func},
+ : func{std::move(func)},
period{period},
- expirationTime{
- startTime + offset +
- units::math::floor((frc2::Timer::GetFPGATimestamp() - startTime) /
- period) *
- period +
- period} {}
+ expirationTime{startTime + offset +
+ units::math::floor(
+ (Timer::GetFPGATimestamp() - startTime) / period) *
+ period +
+ period} {}
bool operator>(const Callback& rhs) const {
return expirationTime > rhs.expirationTime;
diff --git a/wpilibc/src/main/native/include/frc/Timer.h b/wpilibc/src/main/native/include/frc/Timer.h
index ac166c5..0aed658 100644
--- a/wpilibc/src/main/native/include/frc/Timer.h
+++ b/wpilibc/src/main/native/include/frc/Timer.h
@@ -1,13 +1,11 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc2/Timer.h"
+#include <units/time.h>
+#include <wpi/deprecated.h>
namespace frc {
@@ -21,23 +19,20 @@
*
* @param seconds Length of time to pause, in seconds.
*/
-void Wait(double seconds);
+void Wait(units::second_t seconds);
/**
* @brief Gives real-time clock system time with nanosecond resolution
* @return The time, just in case you want the robot to start autonomous at 8pm
* on Saturday.
*/
-double GetTime();
+units::second_t GetTime();
/**
- * Timer objects measure accumulated time in seconds.
+ * A timer class.
*
- * The timer object functions like a stopwatch. It can be started, stopped, and
- * cleared. When the timer is running its value counts up in seconds. When
- * stopped, the timer holds the current value. The implementation simply records
- * the time when started and subtracts the current time whenever the value is
- * requested.
+ * Note that if the user calls frc::sim::RestartTiming(), they should also reset
+ * the timer so Get() won't return a negative duration.
*/
class Timer {
public:
@@ -51,10 +46,10 @@
virtual ~Timer() = default;
- Timer(const Timer& rhs) = default;
- Timer& operator=(const Timer& rhs) = default;
- Timer(Timer&& rhs) = default;
- Timer& operator=(Timer&& rhs) = default;
+ Timer(const Timer&) = default;
+ Timer& operator=(const Timer&) = default;
+ Timer(Timer&&) = default;
+ Timer& operator=(Timer&&) = default;
/**
* Get the current time from the timer. If the clock is running it is derived
@@ -63,7 +58,7 @@
*
* @return Current time value for this timer in seconds
*/
- double Get() const;
+ units::second_t Get() const;
/**
* Reset the timer by setting the time to 0.
@@ -77,7 +72,8 @@
* Start the timer running.
*
* Just set the running flag to true indicating that all time requests should
- * be relative to the system clock.
+ * be relative to the system clock. Note that this method is a no-op if the
+ * timer is already running.
*/
void Start();
@@ -91,14 +87,34 @@
void Stop();
/**
+ * Check if the period specified has passed.
+ *
+ * @param period The period to check.
+ * @return True if the period has passed.
+ */
+ bool HasElapsed(units::second_t period) const;
+
+ /**
* Check if the period specified has passed and if it has, advance the start
* time by that period. This is useful to decide if it's time to do periodic
* work without drifting later by the time it took to get around to checking.
*
- * @param period The period to check for (in seconds).
+ * @param period The period to check for.
+ * @return True if the period has passed.
+ * @deprecated Use AdvanceIfElapsed() instead.
+ */
+ WPI_DEPRECATED("Use AdvanceIfElapsed() instead.")
+ bool HasPeriodPassed(units::second_t period);
+
+ /**
+ * Check if the period specified has passed and if it has, advance the start
+ * time by that period. This is useful to decide if it's time to do periodic
+ * work without drifting later by the time it took to get around to checking.
+ *
+ * @param period The period to check for.
* @return True if the period has passed.
*/
- bool HasPeriodPassed(double period);
+ bool AdvanceIfElapsed(units::second_t period);
/**
* Return the FPGA system clock time in seconds.
@@ -108,7 +124,7 @@
*
* @returns Robot running time in seconds.
*/
- static double GetFPGATimestamp();
+ static units::second_t GetFPGATimestamp();
/**
* Return the approximate match time.
@@ -125,10 +141,12 @@
*
* @return Time remaining in current match period (auto or teleop)
*/
- static double GetMatchTime();
+ static units::second_t GetMatchTime();
private:
- frc2::Timer m_timer;
+ units::second_t m_startTime = 0_s;
+ units::second_t m_accumulatedTime = 0_s;
+ bool m_running = false;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/TimesliceRobot.h b/wpilibc/src/main/native/include/frc/TimesliceRobot.h
new file mode 100644
index 0000000..bc045d5
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/TimesliceRobot.h
@@ -0,0 +1,120 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <functional>
+
+#include <units/time.h>
+
+#include "frc/TimedRobot.h"
+
+namespace frc {
+
+/**
+ * TimesliceRobot extends the TimedRobot robot program framework to provide
+ * timeslice scheduling of periodic functions.
+ *
+ * The TimesliceRobot class is intended to be subclassed by a user creating a
+ * robot program.
+ *
+ * This class schedules robot operations serially in a timeslice format.
+ * TimedRobot's periodic functions are the first in the timeslice table with 0
+ * ms offset and 20 ms period. You can schedule additional controller periodic
+ * functions at a shorter period (5 ms by default). You give each one a
+ * timeslice duration, then they're run sequentially. The main benefit of this
+ * approach is consistent starting times for each controller periodic, which can
+ * make odometry and estimators more accurate and controller outputs change more
+ * consistently.
+ *
+ * Here's an example of measured subsystem durations and their timeslice
+ * allocations:
+ *
+ * <table>
+ * <tr>
+ * <td><b>Subsystem</b></td>
+ * <td><b>Duration (ms)</b></td>
+ * <td><b>Allocation (ms)</b></td>
+ * </tr>
+ * <tr>
+ * <td><b>Total</b></td>
+ * <td>5.0</td>
+ * <td>5.0</td>
+ * </tr>
+ * <tr>
+ * <td>TimedRobot</td>
+ * <td>?</td>
+ * <td>2.0</td>
+ * </tr>
+ * <tr>
+ * <td>Drivetrain</td>
+ * <td>1.32</td>
+ * <td>1.5</td>
+ * </tr>
+ * <tr>
+ * <td>Flywheel</td>
+ * <td>0.6</td>
+ * <td>0.7</td>
+ * </tr>
+ * <tr>
+ * <td>Turret</td>
+ * <td>0.6</td>
+ * <td>0.8</td>
+ * </tr>
+ * <tr>
+ * <td><b>Free</b></td>
+ * <td>0.0</td>
+ * <td>N/A</td>
+ * </tr>
+ * </table>
+ *
+ * Since TimedRobot periodic functions only run every 20ms, that leaves a 2 ms
+ * empty spot in the allocation table for three of the four 5 ms cycles
+ * comprising 20 ms. That's OK because the OS needs time to do other things.
+ *
+ * If the robot periodic functions and the controller periodic functions have a
+ * lot of scheduling jitter that cause them to occasionally overlap with later
+ * timeslices, consider giving the main robot thread a real-time priority using
+ * frc::SetCurrentThreadPriority(). An RT priority of 15 is a reasonable choice.
+ *
+ * If you do enable RT though, <i>make sure your periodic functions do not
+ * block</i>. If they do, the operating system will lock up, and you'll have to
+ * boot the roboRIO into safe mode and delete the robot program to recover.
+ */
+class TimesliceRobot : public TimedRobot {
+ public:
+ /**
+ * Constructor for TimesliceRobot.
+ *
+ * @param robotPeriodicAllocation The allocation to give the TimesliceRobot
+ * periodic functions.
+ * @param controllerPeriod The controller period. The sum of all scheduler
+ * allocations should be less than or equal to this
+ * value.
+ */
+ explicit TimesliceRobot(units::second_t robotPeriodicAllocation,
+ units::second_t controllerPeriod);
+
+ /**
+ * Schedule a periodic function with the constructor's controller period and
+ * the given allocation. The function's runtime allocation will be placed
+ * after the end of the previous one's.
+ *
+ * If a call to this function makes the allocations exceed the controller
+ * period, an exception will be thrown since that means the TimesliceRobot
+ * periodic functions and the given function will have conflicting
+ * timeslices.
+ *
+ * @param func Function to schedule.
+ * @param allocation The function's runtime allocation out of the controller
+ * period.
+ */
+ void Schedule(std::function<void()> func, units::second_t allocation);
+
+ private:
+ units::second_t m_nextOffset;
+ units::second_t m_controllerPeriod;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/Tracer.h b/wpilibc/src/main/native/include/frc/Tracer.h
index 627b07b..2acb017 100644
--- a/wpilibc/src/main/native/include/frc/Tracer.h
+++ b/wpilibc/src/main/native/include/frc/Tracer.h
@@ -1,17 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <chrono>
+#include <string_view>
#include <hal/cpp/fpga_clock.h>
#include <wpi/StringMap.h>
-#include <wpi/StringRef.h>
namespace wpi {
class raw_ostream;
@@ -51,7 +48,7 @@
*
* @param epochName The name to associate with the epoch.
*/
- void AddEpoch(wpi::StringRef epochName);
+ void AddEpoch(std::string_view epochName);
/**
* Prints list of epochs added so far and their times to the DriverStation.
diff --git a/wpilibc/src/main/native/include/frc/Ultrasonic.h b/wpilibc/src/main/native/include/frc/Ultrasonic.h
index f6d301b..253192f 100644
--- a/wpilibc/src/main/native/include/frc/Ultrasonic.h
+++ b/wpilibc/src/main/native/include/frc/Ultrasonic.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -13,12 +10,13 @@
#include <vector>
#include <hal/SimDevice.h>
+#include <units/length.h>
+#include <units/time.h>
+#include <units/velocity.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/Counter.h"
-#include "frc/ErrorBase.h"
-#include "frc/PIDSource.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
@@ -37,13 +35,9 @@
* received. The time that the line is high determines the round trip distance
* (time of flight).
*/
-class Ultrasonic : public ErrorBase,
- public Sendable,
- public PIDSource,
- public SendableHelper<Ultrasonic> {
+class Ultrasonic : public wpi::Sendable,
+ public wpi::SendableHelper<Ultrasonic> {
public:
- enum DistanceUnit { kInches = 0, kMilliMeters = 1 };
-
/**
* Create an instance of the Ultrasonic Sensor.
*
@@ -54,9 +48,8 @@
* @param echoChannel The digital input channel that receives the echo. The
* length of time that the echo is high represents the
* round trip time of the ping, and the distance.
- * @param units The units returned in either kInches or kMilliMeters
*/
- Ultrasonic(int pingChannel, int echoChannel, DistanceUnit units = kInches);
+ Ultrasonic(int pingChannel, int echoChannel);
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
@@ -66,10 +59,8 @@
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
- * @param units The units returned in either kInches or kMilliMeters
*/
- Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel,
- DistanceUnit units = kInches);
+ Ultrasonic(DigitalOutput* pingChannel, DigitalInput* echoChannel);
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
@@ -79,10 +70,8 @@
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
- * @param units The units returned in either kInches or kMilliMeters
*/
- Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel,
- DistanceUnit units = kInches);
+ Ultrasonic(DigitalOutput& pingChannel, DigitalInput& echoChannel);
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
@@ -92,17 +81,17 @@
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
- * @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
- std::shared_ptr<DigitalInput> echoChannel,
- DistanceUnit units = kInches);
+ std::shared_ptr<DigitalInput> echoChannel);
~Ultrasonic() override;
Ultrasonic(Ultrasonic&&) = default;
Ultrasonic& operator=(Ultrasonic&&) = default;
+ int GetEchoChannel() const;
+
/**
* Single ping to ultrasonic sensor.
*
@@ -138,52 +127,19 @@
static void SetAutomaticMode(bool enabling);
/**
- * Get the range in inches from the ultrasonic sensor.
+ * Get the range from the ultrasonic sensor.
*
- * @return Range in inches of the target returned from the ultrasonic sensor.
- * If there is no valid value yet, i.e. at least one measurement
- * hasn't completed, then return 0.
+ * @return Range of the target returned from the ultrasonic sensor. If there
+ * is no valid value yet, i.e. at least one measurement hasn't
+ * completed, then return 0.
*/
- double GetRangeInches() const;
-
- /**
- * Get the range in millimeters from the ultrasonic sensor.
- *
- * @return Range in millimeters of the target returned by the ultrasonic
- * sensor. If there is no valid value yet, i.e. at least one
- * measurement hasn't completed, then return 0.
- */
- double GetRangeMM() const;
+ units::meter_t GetRange() const;
bool IsEnabled() const;
void SetEnabled(bool enable);
- /**
- * Set the current DistanceUnit that should be used for the PIDSource base
- * object.
- *
- * @param units The DistanceUnit that should be used.
- */
- void SetDistanceUnits(DistanceUnit units);
-
- /**
- * Get the current DistanceUnit that is used for the PIDSource base object.
- *
- * @return The type of DistanceUnit that is being used.
- */
- DistanceUnit GetDistanceUnits() const;
-
- /**
- * Get the range in the current DistanceUnit for the PIDSource base object.
- *
- * @return The range in DistanceUnit
- */
- double PIDGet() override;
-
- void SetPIDSourceType(PIDSourceType pidSource) override;
-
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
/**
@@ -215,8 +171,8 @@
static constexpr int kPriority = 64;
// Max time (ms) between readings.
- static constexpr double kMaxUltrasonicTime = 0.1;
- static constexpr double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0;
+ static constexpr auto kMaxUltrasonicTime = 0.1_s;
+ static constexpr auto kSpeedOfSound = 1130_fps;
// Thread doing the round-robin automatic sensing
static std::thread m_thread;
@@ -231,7 +187,6 @@
std::shared_ptr<DigitalInput> m_echoChannel;
bool m_enabled = false;
Counter m_counter;
- DistanceUnit m_units;
hal::SimDevice m_simDevice;
hal::SimBoolean m_simRangeValid;
diff --git a/wpilibc/src/main/native/include/frc/Utility.h b/wpilibc/src/main/native/include/frc/Utility.h
deleted file mode 100644
index a02e583..0000000
--- a/wpilibc/src/main/native/include/frc/Utility.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-/**
- * @file Contains global utility functions
- */
-
-#include <wpi/StringRef.h>
-#include <wpi/Twine.h>
-
-#define wpi_assert(condition) \
- wpi_assert_impl(condition, #condition, "", __FILE__, __LINE__, __FUNCTION__)
-#define wpi_assertWithMessage(condition, message) \
- wpi_assert_impl(condition, #condition, message, __FILE__, __LINE__, \
- __FUNCTION__)
-
-#define wpi_assertEqual(a, b) \
- wpi_assertEqual_impl(a, b, #a, #b, "", __FILE__, __LINE__, __FUNCTION__)
-#define wpi_assertEqualWithMessage(a, b, message) \
- wpi_assertEqual_impl(a, b, #a, #b, message, __FILE__, __LINE__, __FUNCTION__)
-
-#define wpi_assertNotEqual(a, b) \
- wpi_assertNotEqual_impl(a, b, #a, #b, "", __FILE__, __LINE__, __FUNCTION__)
-#define wpi_assertNotEqualWithMessage(a, b, message) \
- wpi_assertNotEqual_impl(a, b, #a, #b, message, __FILE__, __LINE__, \
- __FUNCTION__)
-
-/**
- * Assert implementation.
- *
- * This allows breakpoints to be set on an assert. The users don't call this,
- * but instead use the wpi_assert macros in Utility.h.
- */
-bool wpi_assert_impl(bool conditionValue, const wpi::Twine& conditionText,
- const wpi::Twine& message, wpi::StringRef fileName,
- int lineNumber, wpi::StringRef funcName);
-
-/**
- * Assert equal implementation.
- *
- * This determines whether the two given integers are equal. If not, the value
- * of each is printed along with an optional message string. The users don't
- * call this, but instead use the wpi_assertEqual macros in Utility.h.
- */
-bool wpi_assertEqual_impl(int valueA, int valueB,
- const wpi::Twine& valueAString,
- const wpi::Twine& valueBString,
- const wpi::Twine& message, wpi::StringRef fileName,
- int lineNumber, wpi::StringRef funcName);
-
-/**
- * Assert not equal implementation.
- *
- * This determines whether the two given integers are equal. If so, the value of
- * each is printed along with an optional message string. The users don't call
- * this, but instead use the wpi_assertNotEqual macros in Utility.h.
- */
-bool wpi_assertNotEqual_impl(int valueA, int valueB,
- const wpi::Twine& valueAString,
- const wpi::Twine& valueBString,
- const wpi::Twine& message, wpi::StringRef fileName,
- int lineNumber, wpi::StringRef funcName);
diff --git a/wpilibc/src/main/native/include/frc/Victor.h b/wpilibc/src/main/native/include/frc/Victor.h
deleted file mode 100644
index 89c4a89..0000000
--- a/wpilibc/src/main/native/include/frc/Victor.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWMSpeedController.h"
-
-namespace frc {
-
-/**
- * Vex Robotics Victor 888 Speed Controller.
- *
- * The Vex Robotics Victor 884 Speed Controller can also be used with this
- * class but may need to be calibrated per the Victor 884 user manual.
- *
- * Note that the Victor uses the following bounds for PWM values. These
- * values were determined empirically and optimized for the Victor 888. These
- * values should work reasonably well for Victor 884 controllers as well but
- * if users experience issues such as asymmetric behavior around the deadband
- * or inability to saturate the controller in either direction, calibration is
- * recommended. The calibration procedure can be found in the Victor 884 User
- * Manual available from Vex.
- *
- * \li 2.027ms = full "forward"
- * \li 1.525ms = the "high end" of the deadband range
- * \li 1.507ms = center of the deadband range (off)
- * \li 1.490ms = the "low end" of the deadband range
- * \li 1.026ms = full "reverse"
- */
-class Victor : public PWMSpeedController {
- public:
- /**
- * Constructor for a Victor.
- *
- * @param channel The PWM channel number that the Victor is attached to. 0-9
- * are on-board, 10-19 are on the MXP port
- */
- explicit Victor(int channel);
-
- Victor(Victor&&) = default;
- Victor& operator=(Victor&&) = default;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/VictorSP.h b/wpilibc/src/main/native/include/frc/VictorSP.h
deleted file mode 100644
index d8aa8e8..0000000
--- a/wpilibc/src/main/native/include/frc/VictorSP.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PWMSpeedController.h"
-
-namespace frc {
-
-/**
- * Vex Robotics Victor SP Speed Controller.
- *
- * Note that the Victor SP uses the following bounds for PWM values. These
- * values should work reasonably well for most controllers, but if users
- * experience issues such as asymmetric behavior around the deadband or
- * inability to saturate the controller in either direction, calibration is
- * recommended. The calibration procedure can be found in the Victor SP User
- * Manual available from Vex.
- *
- * \li 2.004ms = full "forward"
- * \li 1.520ms = the "high end" of the deadband range
- * \li 1.500ms = center of the deadband range (off)
- * \li 1.480ms = the "low end" of the deadband range
- * \li 0.997ms = full "reverse"
- */
-class VictorSP : public PWMSpeedController {
- public:
- /**
- * Constructor for a Victor SP.
- *
- * @param channel The PWM channel that the VictorSP is attached to. 0-9 are
- * on-board, 10-19 are on the MXP port
- */
- explicit VictorSP(int channel);
-
- VictorSP(VictorSP&&) = default;
- VictorSP& operator=(VictorSP&&) = default;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/WPIErrors.h b/wpilibc/src/main/native/include/frc/WPIErrors.h
deleted file mode 100644
index 8325c92..0000000
--- a/wpilibc/src/main/native/include/frc/WPIErrors.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <stdint.h>
-
-#define S(label, offset, message) \
- constexpr inline const char* wpi_error_s_##label() { return message; } \
- constexpr inline int wpi_error_value_##label() { return offset; }
-
-// Fatal errors
-S(ModuleIndexOutOfRange, -1,
- "Allocating module that is out of range or not found")
-S(ChannelIndexOutOfRange, -1, "Allocating channel that is out of range")
-S(NotAllocated, -2, "Attempting to free unallocated resource")
-S(ResourceAlreadyAllocated, -3, "Attempted to reuse an allocated resource")
-S(NoAvailableResources, -4, "No available resources to allocate")
-S(NullParameter, -5, "A pointer parameter to a method is nullptr")
-S(Timeout, -6, "A timeout has been exceeded")
-S(CompassManufacturerError, -7, "Compass manufacturer doesn't match HiTechnic")
-S(CompassTypeError, -8,
- "Compass type doesn't match expected type for HiTechnic compass")
-S(IncompatibleMode, -9, "The object is in an incompatible mode")
-S(AnalogTriggerLimitOrderError, -10,
- "AnalogTrigger limits error. Lower limit > Upper Limit")
-S(AnalogTriggerPulseOutputError, -11,
- "Attempted to read AnalogTrigger pulse output.")
-S(TaskError, -12, "Task can't be started")
-S(TaskIDError, -13, "Task error: Invalid ID.")
-S(TaskDeletedError, -14, "Task error: Task already deleted.")
-S(TaskOptionsError, -15, "Task error: Invalid options.")
-S(TaskMemoryError, -16, "Task can't be started due to insufficient memory.")
-S(TaskPriorityError, -17, "Task error: Invalid priority [1-255].")
-S(DriveUninitialized, -18, "RobotDrive not initialized for the C interface")
-S(CompressorNonMatching, -19,
- "Compressor slot/channel doesn't match previous instance")
-S(CompressorAlreadyDefined, -20, "Creating a second compressor instance")
-S(CompressorUndefined, -21,
- "Using compressor functions without defining compressor")
-S(InconsistentArrayValueAdded, -22,
- "When packing data into an array to the dashboard, not all values added were "
- "of the same type.")
-S(MismatchedComplexTypeClose, -23,
- "When packing data to the dashboard, a Close for a complex type was called "
- "without a matching Open.")
-S(DashboardDataOverflow, -24,
- "When packing data to the dashboard, too much data was packed and the buffer "
- "overflowed.")
-S(DashboardDataCollision, -25,
- "The same buffer was used for packing data and for printing.")
-S(EnhancedIOMissing, -26, "IO is not attached or Enhanced IO is not enabled.")
-S(LineNotOutput, -27,
- "Cannot SetDigitalOutput for a line not configured for output.")
-S(ParameterOutOfRange, -28, "A parameter is out of range.")
-S(SPIClockRateTooLow, -29, "SPI clock rate was below the minimum supported")
-S(JaguarVersionError, -30, "Jaguar firmware version error")
-S(JaguarMessageNotFound, -31, "Jaguar message not found")
-S(NetworkTablesReadError, -40, "Error reading NetworkTables socket")
-S(NetworkTablesBufferFull, -41, "Buffer full writing to NetworkTables socket")
-S(NetworkTablesWrongType, -42,
- "The wrong type was read from the NetworkTables entry")
-S(NetworkTablesCorrupt, -43, "NetworkTables data stream is corrupt")
-S(SmartDashboardMissingKey, -43, "SmartDashboard data does not exist")
-S(CommandIllegalUse, -50, "Illegal use of Command")
-S(UnsupportedInSimulation, -80, "Unsupported in simulation")
-S(CameraServerError, -90, "CameraServer error")
-S(InvalidParameter, -100, "Invalid parameter value")
-
-// Warnings
-S(SampleRateTooHigh, 1, "Analog module sample rate is too high")
-S(VoltageOutOfRange, 2,
- "Voltage to convert to raw value is out of range [-10; 10]")
-S(CompressorTaskError, 3, "Compressor task won't start")
-S(LoopTimingError, 4, "Digital module loop timing is not the expected value")
-S(NonBinaryDigitalValue, 5, "Digital output value is not 0 or 1")
-S(IncorrectBatteryChannel, 6,
- "Battery measurement channel is not correct value")
-S(BadJoystickIndex, 7, "Joystick index is out of range, should be 0-3")
-S(BadJoystickAxis, 8, "Joystick axis or POV is out of range")
-S(InvalidMotorIndex, 9, "Motor index is out of range, should be 0-3")
-S(DriverStationTaskError, 10, "Driver Station task won't start")
-S(EnhancedIOPWMPeriodOutOfRange, 11,
- "Driver Station Enhanced IO PWM Output period out of range.")
-S(SPIWriteNoMOSI, 12, "Cannot write to SPI port with no MOSI output")
-S(SPIReadNoMISO, 13, "Cannot read from SPI port with no MISO input")
-S(SPIReadNoData, 14, "No data available to read from SPI")
-S(IncompatibleState, 15,
- "Incompatible State: The operation cannot be completed")
-
-#undef S
diff --git a/wpilibc/src/main/native/include/frc/WPIErrors.mac b/wpilibc/src/main/native/include/frc/WPIErrors.mac
new file mode 100644
index 0000000..c6c96e9
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/WPIErrors.mac
@@ -0,0 +1,62 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+S(ModuleIndexOutOfRange, -1,
+ "Allocating module that is out of range or not found")
+S(ChannelIndexOutOfRange, -45, "Allocating channel that is out of range")
+S(NotAllocated, -2, "Attempting to free unallocated resource")
+S(ResourceAlreadyAllocated, -3, "Attempted to reuse an allocated resource")
+S(NoAvailableResources, -4, "No available resources to allocate")
+S(NullParameter, -5, "A pointer parameter to a method is nullptr")
+S(Timeout, -6, "A timeout has been exceeded")
+S(CompassManufacturerError, -7, "Compass manufacturer doesn't match HiTechnic")
+S(CompassTypeError, -8,
+ "Compass type doesn't match expected type for HiTechnic compass")
+S(IncompatibleMode, -9, "The object is in an incompatible mode")
+S(AnalogTriggerLimitOrderError, -10,
+ "AnalogTrigger limits error. Lower limit > Upper Limit")
+S(AnalogTriggerPulseOutputError, -11,
+ "Attempted to read AnalogTrigger pulse output")
+S(TaskError, -12, "Task can't be started")
+S(TaskIDError, -13, "Task error: Invalid ID")
+S(TaskDeletedError, -14, "Task error: Task already deleted")
+S(TaskOptionsError, -15, "Task error: Invalid options")
+S(TaskMemoryError, -16, "Task can't be started due to insufficient memory")
+S(TaskPriorityError, -17, "Task error: Invalid priority [1-255]")
+S(DriveUninitialized, -18, "RobotDrive not initialized for the C interface")
+S(CompressorNonMatching, -19,
+ "Compressor slot/channel doesn't match previous instance")
+S(CompressorAlreadyDefined, -20, "Creating a second compressor instance")
+S(CompressorUndefined, -21,
+ "Using compressor functions without defining compressor")
+S(InconsistentArrayValueAdded, -22,
+ "When packing data into an array to the dashboard, not all values added were "
+ "of the same type")
+S(MismatchedComplexTypeClose, -23,
+ "When packing data to the dashboard, a Close for a complex type was called "
+ "without a matching Open")
+S(DashboardDataOverflow, -24,
+ "When packing data to the dashboard, too much data was packed and the buffer "
+ "overflowed")
+S(DashboardDataCollision, -25,
+ "The same buffer was used for packing data and for printing")
+S(EnhancedIOMissing, -26, "IO is not attached or Enhanced IO is not enabled")
+S(LineNotOutput, -27,
+ "Cannot SetDigitalOutput for a line not configured for output")
+S(ParameterOutOfRange, -28, "A parameter is out of range")
+S(SPIClockRateTooLow, -29, "SPI clock rate was below the minimum supported")
+S(JaguarVersionError, -30, "Jaguar firmware version error")
+S(JaguarMessageNotFound, -31, "Jaguar message not found")
+S(NetworkTablesReadError, -40, "Error reading NetworkTables socket")
+S(NetworkTablesBufferFull, -41, "Buffer full writing to NetworkTables socket")
+S(NetworkTablesWrongType, -42,
+ "The wrong type was read from the NetworkTables entry")
+S(NetworkTablesCorrupt, -43, "NetworkTables data stream is corrupt")
+S(SmartDashboardMissingKey, -44, "SmartDashboard data does not exist")
+S(CommandIllegalUse, -50, "Illegal use of Command")
+S(UnsupportedInSimulation, -80, "Unsupported in simulation")
+S(CameraServerError, -90, "CameraServer error")
+S(InvalidParameter, -100, "Invalid parameter value")
+S(AssertionFailure, -110, "Assertion failed")
+S(Error, -111, "Error")
diff --git a/wpilibc/src/main/native/include/frc/WPILib.h b/wpilibc/src/main/native/include/frc/WPILib.h
deleted file mode 100644
index 634d0f5..0000000
--- a/wpilibc/src/main/native/include/frc/WPILib.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-// clang-format off
-#ifdef _MSC_VER
-#pragma message("warning: Including this header drastically increases compilation times and is bad style. Include only what you use instead.")
-#else
-#warning "Including this header drastically increases compilation times and is bad style. Include only what you use instead."
-#endif
-
-// clang-format on
-
-#if __has_include(<cameraserver/CameraServer.h>)
-#include <cameraserver/CameraServer.h>
-#include <vision/VisionRunner.h>
-#endif
-
-#include "frc/ADXL345_I2C.h"
-#include "frc/ADXL345_SPI.h"
-#include "frc/ADXL362.h"
-#include "frc/ADXRS450_Gyro.h"
-#include "frc/AnalogAccelerometer.h"
-#include "frc/AnalogGyro.h"
-#include "frc/AnalogInput.h"
-#include "frc/AnalogOutput.h"
-#include "frc/AnalogPotentiometer.h"
-#include "frc/AnalogTrigger.h"
-#include "frc/AnalogTriggerOutput.h"
-#include "frc/BuiltInAccelerometer.h"
-#include "frc/Compressor.h"
-#include "frc/Counter.h"
-#include "frc/DMC60.h"
-#include "frc/DigitalInput.h"
-#include "frc/DigitalOutput.h"
-#include "frc/DigitalSource.h"
-#include "frc/DoubleSolenoid.h"
-#include "frc/DriverStation.h"
-#include "frc/Encoder.h"
-#include "frc/ErrorBase.h"
-#include "frc/GearTooth.h"
-#include "frc/GenericHID.h"
-#include "frc/I2C.h"
-#include "frc/InterruptableSensorBase.h"
-#include "frc/IterativeRobot.h"
-#include "frc/Jaguar.h"
-#include "frc/Joystick.h"
-#include "frc/NidecBrushless.h"
-#include "frc/Notifier.h"
-#include "frc/PIDController.h"
-#include "frc/PIDOutput.h"
-#include "frc/PIDSource.h"
-#include "frc/PWM.h"
-#include "frc/PWMSpeedController.h"
-#include "frc/PWMTalonSRX.h"
-#include "frc/PWMVictorSPX.h"
-#include "frc/PowerDistributionPanel.h"
-#include "frc/Preferences.h"
-#include "frc/Relay.h"
-#include "frc/RobotBase.h"
-#include "frc/RobotController.h"
-#include "frc/RobotDrive.h"
-#include "frc/SD540.h"
-#include "frc/SPI.h"
-#include "frc/SensorUtil.h"
-#include "frc/SerialPort.h"
-#include "frc/Servo.h"
-#include "frc/Solenoid.h"
-#include "frc/Spark.h"
-#include "frc/SpeedController.h"
-#include "frc/SpeedControllerGroup.h"
-#include "frc/Talon.h"
-#include "frc/Threads.h"
-#include "frc/TimedRobot.h"
-#include "frc/Timer.h"
-#include "frc/Ultrasonic.h"
-#include "frc/Utility.h"
-#include "frc/Victor.h"
-#include "frc/VictorSP.h"
-#include "frc/WPIErrors.h"
-#include "frc/XboxController.h"
-#if __has_include("frc/buttons/InternalButton.h")
-#include "frc/buttons/InternalButton.h"
-#include "frc/buttons/JoystickButton.h"
-#include "frc/buttons/NetworkButton.h"
-#include "frc/commands/Command.h"
-#include "frc/commands/CommandGroup.h"
-#include "frc/commands/PIDCommand.h"
-#include "frc/commands/PIDSubsystem.h"
-#include "frc/commands/PrintCommand.h"
-#include "frc/commands/StartCommand.h"
-#include "frc/commands/Subsystem.h"
-#include "frc/commands/WaitCommand.h"
-#include "frc/commands/WaitForChildren.h"
-#include "frc/commands/WaitUntilCommand.h"
-#endif
-#include "frc/drive/DifferentialDrive.h"
-#include "frc/drive/KilloughDrive.h"
-#include "frc/drive/MecanumDrive.h"
-#include "frc/filters/LinearDigitalFilter.h"
-#include "frc/interfaces/Accelerometer.h"
-#include "frc/interfaces/Gyro.h"
-#include "frc/interfaces/Potentiometer.h"
-#include "frc/smartdashboard/SendableChooser.h"
-#include "frc/smartdashboard/SmartDashboard.h"
diff --git a/wpilibc/src/main/native/include/frc/WPIWarnings.mac b/wpilibc/src/main/native/include/frc/WPIWarnings.mac
new file mode 100644
index 0000000..fa63494
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/WPIWarnings.mac
@@ -0,0 +1,24 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+S(SampleRateTooHigh, 1, "Analog module sample rate is too high")
+S(VoltageOutOfRange, 2,
+ "Voltage to convert to raw value is out of range [-10; 10]")
+S(CompressorTaskError, 3, "Compressor task won't start")
+S(LoopTimingError, 4, "Digital module loop timing is not the expected value")
+S(NonBinaryDigitalValue, 5, "Digital output value is not 0 or 1")
+S(IncorrectBatteryChannel, 6,
+ "Battery measurement channel is not correct value")
+S(BadJoystickIndex, 7, "Joystick index is out of range, should be 0-3")
+S(BadJoystickAxis, 8, "Joystick axis or POV is out of range")
+S(InvalidMotorIndex, 9, "Motor index is out of range, should be 0-3")
+S(DriverStationTaskError, 10, "Driver Station task won't start")
+S(EnhancedIOPWMPeriodOutOfRange, 11,
+ "Driver Station Enhanced IO PWM Output period out of range")
+S(SPIWriteNoMOSI, 12, "Cannot write to SPI port with no MOSI output")
+S(SPIReadNoMISO, 13, "Cannot read from SPI port with no MISO input")
+S(SPIReadNoData, 14, "No data available to read from SPI")
+S(IncompatibleState, 15,
+ "Incompatible State: The operation cannot be completed")
+S(Warning, 16, "Warning")
diff --git a/wpilibc/src/main/native/include/frc/Watchdog.h b/wpilibc/src/main/native/include/frc/Watchdog.h
index 6fc3793..d85674d 100644
--- a/wpilibc/src/main/native/include/frc/Watchdog.h
+++ b/wpilibc/src/main/native/include/frc/Watchdog.h
@@ -1,18 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
+#include <string_view>
#include <utility>
#include <units/time.h>
-#include <wpi/StringRef.h>
-#include <wpi/deprecated.h>
#include "frc/Tracer.h"
@@ -32,19 +28,6 @@
/**
* Watchdog constructor.
*
- * @deprecated use unit-safe version instead.
- * Watchdog(units::second_t timeout, std::function<void()> callback)
- *
- * @param timeout The watchdog's timeout in seconds with microsecond
- * resolution.
- * @param callback This function is called when the timeout expires.
- */
- WPI_DEPRECATED("Use unit-safe version instead")
- Watchdog(double timeout, std::function<void()> callback);
-
- /**
- * Watchdog constructor.
- *
* @param timeout The watchdog's timeout in seconds with microsecond
* resolution.
* @param callback This function is called when the timeout expires.
@@ -52,11 +35,6 @@
Watchdog(units::second_t timeout, std::function<void()> callback);
template <typename Callable, typename Arg, typename... Args>
- WPI_DEPRECATED("Use unit-safe version instead")
- Watchdog(double timeout, Callable&& f, Arg&& arg, Args&&... args)
- : Watchdog(units::second_t{timeout}, arg, args...) {}
-
- template <typename Callable, typename Arg, typename... Args>
Watchdog(units::second_t timeout, Callable&& f, Arg&& arg, Args&&... args)
: Watchdog(timeout,
std::bind(std::forward<Callable>(f), std::forward<Arg>(arg),
@@ -68,21 +46,9 @@
Watchdog& operator=(Watchdog&& rhs);
/**
- * Returns the time in seconds since the watchdog was last fed.
+ * Returns the time since the watchdog was last fed.
*/
- double GetTime() const;
-
- /**
- * Sets the watchdog's timeout.
- *
- * @deprecated use the unit safe version instead.
- * SetTimeout(units::second_t timeout)
- *
- * @param timeout The watchdog's timeout in seconds with microsecond
- * resolution.
- */
- WPI_DEPRECATED("Use unit-safe version instead")
- void SetTimeout(double timeout);
+ units::second_t GetTime() const;
/**
* Sets the watchdog's timeout.
@@ -93,9 +59,9 @@
void SetTimeout(units::second_t timeout);
/**
- * Returns the watchdog's timeout in seconds.
+ * Returns the watchdog's timeout.
*/
- double GetTimeout() const;
+ units::second_t GetTimeout() const;
/**
* Returns true if the watchdog timer has expired.
@@ -110,7 +76,7 @@
*
* @param epochName The name to associate with the epoch.
*/
- void AddEpoch(wpi::StringRef epochName);
+ void AddEpoch(std::string_view epochName);
/**
* Prints list of epochs added so far and their times.
@@ -146,7 +112,7 @@
private:
// Used for timeout print rate-limiting
- static constexpr units::second_t kMinPrintPeriod = 1_s;
+ static constexpr auto kMinPrintPeriod = 1_s;
units::second_t m_startTime = 0_s;
units::second_t m_timeout;
diff --git a/wpilibc/src/main/native/include/frc/XboxController.h b/wpilibc/src/main/native/include/frc/XboxController.h
index ddf4dc2..cbdc7d7 100644
--- a/wpilibc/src/main/native/include/frc/XboxController.h
+++ b/wpilibc/src/main/native/include/frc/XboxController.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2016-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -32,78 +29,102 @@
*/
explicit XboxController(int port);
- virtual ~XboxController() = default;
+ ~XboxController() override = default;
XboxController(XboxController&&) = default;
XboxController& operator=(XboxController&&) = default;
/**
- * Get the X axis value of the controller.
- *
- * @param hand Side of controller whose value should be returned.
+ * Get the X axis value of left side of the controller.
*/
- double GetX(JoystickHand hand) const override;
+ double GetLeftX() const;
/**
- * Get the Y axis value of the controller.
- *
- * @param hand Side of controller whose value should be returned.
+ * Get the X axis value of right side of the controller.
*/
- double GetY(JoystickHand hand) const override;
+ double GetRightX() const;
/**
- * Get the trigger axis value of the controller.
- *
- * @param hand Side of controller whose value should be returned.
+ * Get the Y axis value of left side of the controller.
*/
- double GetTriggerAxis(JoystickHand hand) const;
+ double GetLeftY() const;
/**
- * Read the value of the bumper button on the controller.
- *
- * @param hand Side of controller whose value should be returned.
+ * Get the Y axis value of right side of the controller.
*/
- bool GetBumper(JoystickHand hand) const;
+ double GetRightY() const;
/**
- * Whether the bumper was pressed since the last check.
- *
- * @param hand Side of controller whose value should be returned.
- * @return Whether the button was pressed since the last check.
+ * Get the left trigger (LT) axis value of the controller. Note that this axis
+ * is bound to the range of [0, 1] as opposed to the usual [-1, 1].
*/
- bool GetBumperPressed(JoystickHand hand);
+ double GetLeftTriggerAxis() const;
/**
- * Whether the bumper was released since the last check.
- *
- * @param hand Side of controller whose value should be returned.
- * @return Whether the button was released since the last check.
+ * Get the right trigger (RT) axis value of the controller. Note that this
+ * axis is bound to the range of [0, 1] as opposed to the usual [-1, 1].
*/
- bool GetBumperReleased(JoystickHand hand);
+ double GetRightTriggerAxis() const;
/**
- * Read the value of the stick button on the controller.
- *
- * @param hand Side of controller whose value should be returned.
- * @return The state of the button.
+ * Read the value of the left bumper (LB) button on the controller.
*/
- bool GetStickButton(JoystickHand hand) const;
+ bool GetLeftBumper() const;
/**
- * Whether the stick button was pressed since the last check.
- *
- * @param hand Side of controller whose value should be returned.
- * @return Whether the button was pressed since the last check.
+ * Read the value of the right bumper (RB) button on the controller.
*/
- bool GetStickButtonPressed(JoystickHand hand);
+ bool GetRightBumper() const;
/**
- * Whether the stick button was released since the last check.
- *
- * @param hand Side of controller whose value should be returned.
- * @return Whether the button was released since the last check.
+ * Whether the left bumper (LB) was pressed since the last check.
*/
- bool GetStickButtonReleased(JoystickHand hand);
+ bool GetLeftBumperPressed();
+
+ /**
+ * Whether the right bumper (RB) was pressed since the last check.
+ */
+ bool GetRightBumperPressed();
+
+ /**
+ * Whether the left bumper (LB) was released since the last check.
+ */
+ bool GetLeftBumperReleased();
+
+ /**
+ * Whether the right bumper (RB) was released since the last check.
+ */
+ bool GetRightBumperReleased();
+
+ /**
+ * Read the value of the left stick button (LSB) on the controller.
+ */
+ bool GetLeftStickButton() const;
+
+ /**
+ * Read the value of the right stick button (RSB) on the controller.
+ */
+ bool GetRightStickButton() const;
+
+ /**
+ * Whether the left stick button (LSB) was pressed since the last check.
+ */
+ bool GetLeftStickButtonPressed();
+
+ /**
+ * Whether the right stick button (RSB) was pressed since the last check.
+ */
+ bool GetRightStickButtonPressed();
+
+ /**
+ * Whether the left stick button (LSB) was released since the last check.
+ */
+ bool GetLeftStickButtonReleased();
+
+ /**
+ * Whether the right stick button (RSB) was released since the last check.
+ */
+ bool GetRightStickButtonReleased();
/**
* Read the value of the A button on the controller.
@@ -213,7 +234,6 @@
/**
* Read the value of the start button on the controller.
*
- * @param hand Side of controller whose value should be returned.
* @return The state of the button.
*/
bool GetStartButton() const;
@@ -232,26 +252,26 @@
*/
bool GetStartButtonReleased();
- enum class Button {
- kBumperLeft = 5,
- kBumperRight = 6,
- kStickLeft = 9,
- kStickRight = 10,
- kA = 1,
- kB = 2,
- kX = 3,
- kY = 4,
- kBack = 7,
- kStart = 8
+ struct Button {
+ static constexpr int kLeftBumper = 5;
+ static constexpr int kRightBumper = 6;
+ static constexpr int kLeftStick = 9;
+ static constexpr int kRightStick = 10;
+ static constexpr int kA = 1;
+ static constexpr int kB = 2;
+ static constexpr int kX = 3;
+ static constexpr int kY = 4;
+ static constexpr int kBack = 7;
+ static constexpr int kStart = 8;
};
- enum class Axis {
- kLeftX = 0,
- kRightX = 4,
- kLeftY = 1,
- kRightY = 5,
- kLeftTrigger = 2,
- kRightTrigger = 3
+ struct Axis {
+ static constexpr int kLeftX = 0;
+ static constexpr int kRightX = 4;
+ static constexpr int kLeftY = 1;
+ static constexpr int kRightY = 5;
+ static constexpr int kLeftTrigger = 2;
+ static constexpr int kRightTrigger = 3;
};
};
diff --git a/wpilibc/src/main/native/include/frc/controller/ControllerUtil.h b/wpilibc/src/main/native/include/frc/controller/ControllerUtil.h
deleted file mode 100644
index 7603fde..0000000
--- a/wpilibc/src/main/native/include/frc/controller/ControllerUtil.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <cmath>
-#include <type_traits>
-
-#include <units/math.h>
-
-namespace frc {
-
-/**
- * Returns modulus of error where error is the difference between the reference
- * and a measurement.
- *
- * @param reference Reference input of a controller.
- * @param measurement The current measurement.
- * @param minimumInput The minimum value expected from the input.
- * @param maximumInput The maximum value expected from the input.
- */
-template <typename T>
-T GetModulusError(T reference, T measurement, T minimumInput, T maximumInput) {
- T error = reference - measurement;
- T modulus = maximumInput - minimumInput;
-
- // Wrap error above maximum input
- int numMax = (error + maximumInput) / modulus;
- error -= numMax * modulus;
-
- // Wrap error below minimum input
- int numMin = (error + minimumInput) / modulus;
- error -= numMin * modulus;
-
- return error;
-}
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/controller/HolonomicDriveController.h b/wpilibc/src/main/native/include/frc/controller/HolonomicDriveController.h
deleted file mode 100644
index 916e1a9..0000000
--- a/wpilibc/src/main/native/include/frc/controller/HolonomicDriveController.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <units/angle.h>
-#include <units/velocity.h>
-
-#include "frc/controller/PIDController.h"
-#include "frc/controller/ProfiledPIDController.h"
-#include "frc/geometry/Pose2d.h"
-#include "frc/geometry/Rotation2d.h"
-#include "frc/kinematics/ChassisSpeeds.h"
-#include "frc/trajectory/Trajectory.h"
-
-namespace frc {
-/**
- * This holonomic drive controller can be used to follow trajectories using a
- * holonomic drive train (i.e. swerve or mecanum). Holonomic trajectory
- * following is a much simpler problem to solve compared to skid-steer style
- * drivetrains because it is possible to individually control forward, sideways,
- * and angular velocity.
- *
- * The holonomic drive controller takes in one PID controller for each
- * direction, forward and sideways, and one profiled PID controller for the
- * angular direction. Because the heading dynamics are decoupled from
- * translations, users can specify a custom heading that the drivetrain should
- * point toward. This heading reference is profiled for smoothness.
- */
-class HolonomicDriveController {
- public:
- /**
- * Constructs a holonomic drive controller.
- *
- * @param xController A PID Controller to respond to error in the
- * field-relative x direction.
- * @param yController A PID Controller to respond to error in the
- * field-relative y direction.
- * @param thetaController A profiled PID controller to respond to error in
- * angle.
- */
- HolonomicDriveController(
- const frc2::PIDController& xController,
- const frc2::PIDController& yController,
- const ProfiledPIDController<units::radian>& thetaController);
-
- /**
- * Returns true if the pose error is within tolerance of the reference.
- */
- bool AtReference() const;
-
- /**
- * Sets the pose error which is considered tolerable for use with
- * AtReference().
- *
- * @param poseTolerance Pose error which is tolerable.
- */
- void SetTolerance(const Pose2d& tolerance);
-
- /**
- * Returns the next output of the holonomic drive controller.
- *
- * The reference pose, linear velocity, and angular velocity should come from
- * a drivetrain trajectory.
- *
- * @param currentPose The current pose.
- * @param poseRef The desired pose.
- * @param linearVelocityRef The desired linear velocity.
- * @param angleRef The desired ending angle.
- */
- ChassisSpeeds Calculate(const Pose2d& currentPose, const Pose2d& poseRef,
- units::meters_per_second_t linearVelocityRef,
- const Rotation2d& angleRef);
-
- /**
- * Returns the next output of the holonomic drive controller.
- *
- * The reference pose, linear velocity, and angular velocity should come from
- * a drivetrain trajectory.
- *
- * @param currentPose The current pose.
- * @param desiredState The desired pose, linear velocity, and angular velocity
- * from a trajectory.
- * @param angleRef The desired ending angle.
- */
- ChassisSpeeds Calculate(const Pose2d& currentPose,
- const Trajectory::State& desiredState,
- const Rotation2d& angleRef);
-
- /**
- * Enables and disables the controller for troubleshooting purposes. When
- * Calculate() is called on a disabled controller, only feedforward values
- * are returned.
- *
- * @param enabled If the controller is enabled or not.
- */
- void SetEnabled(bool enabled);
-
- private:
- Pose2d m_poseError;
- Pose2d m_poseTolerance;
- bool m_enabled = true;
-
- frc2::PIDController m_xController;
- frc2::PIDController m_yController;
- ProfiledPIDController<units::radian> m_thetaController;
-};
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/controller/PIDController.h b/wpilibc/src/main/native/include/frc/controller/PIDController.h
deleted file mode 100644
index 5f97c1e..0000000
--- a/wpilibc/src/main/native/include/frc/controller/PIDController.h
+++ /dev/null
@@ -1,243 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <functional>
-#include <limits>
-
-#include <units/time.h>
-
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
-
-namespace frc2 {
-
-/**
- * Implements a PID control loop.
- */
-class PIDController : public frc::Sendable,
- public frc::SendableHelper<PIDController> {
- public:
- /**
- * Allocates a PIDController with the given constants for Kp, Ki, and Kd.
- *
- * @param Kp The proportional coefficient.
- * @param Ki The integral coefficient.
- * @param Kd The derivative coefficient.
- * @param period The period between controller updates in seconds. The
- * default is 20 milliseconds.
- */
- PIDController(double Kp, double Ki, double Kd,
- units::second_t period = 20_ms);
-
- ~PIDController() override = default;
-
- PIDController(const PIDController&) = default;
- PIDController& operator=(const PIDController&) = default;
- PIDController(PIDController&&) = default;
- PIDController& operator=(PIDController&&) = default;
-
- /**
- * Sets the PID Controller gain parameters.
- *
- * Sets the proportional, integral, and differential coefficients.
- *
- * @param Kp Proportional coefficient
- * @param Ki Integral coefficient
- * @param Kd Differential coefficient
- */
- void SetPID(double Kp, double Ki, double Kd);
-
- /**
- * Sets the proportional coefficient of the PID controller gain.
- *
- * @param Kp proportional coefficient
- */
- void SetP(double Kp);
-
- /**
- * Sets the integral coefficient of the PID controller gain.
- *
- * @param Ki integral coefficient
- */
- void SetI(double Ki);
-
- /**
- * Sets the differential coefficient of the PID controller gain.
- *
- * @param Kd differential coefficient
- */
- void SetD(double Kd);
-
- /**
- * Gets the proportional coefficient.
- *
- * @return proportional coefficient
- */
- double GetP() const;
-
- /**
- * Gets the integral coefficient.
- *
- * @return integral coefficient
- */
- double GetI() const;
-
- /**
- * Gets the differential coefficient.
- *
- * @return differential coefficient
- */
- double GetD() const;
-
- /**
- * Gets the period of this controller.
- *
- * @return The period of the controller.
- */
- units::second_t GetPeriod() const;
-
- /**
- * Sets the setpoint for the PIDController.
- *
- * @param setpoint The desired setpoint.
- */
- void SetSetpoint(double setpoint);
-
- /**
- * Returns the current setpoint of the PIDController.
- *
- * @return The current setpoint.
- */
- double GetSetpoint() const;
-
- /**
- * Returns true if the error is within the tolerance of the setpoint.
- *
- * This will return false until at least one input value has been computed.
- */
- bool AtSetpoint() const;
-
- /**
- * Enables continuous input.
- *
- * Rather then using the max and min input range as constraints, it considers
- * them to be the same point and automatically calculates the shortest route
- * to the setpoint.
- *
- * @param minimumInput The minimum value expected from the input.
- * @param maximumInput The maximum value expected from the input.
- */
- void EnableContinuousInput(double minimumInput, double maximumInput);
-
- /**
- * Disables continuous input.
- */
- void DisableContinuousInput();
-
- /**
- * Returns true if continuous input is enabled.
- */
- bool IsContinuousInputEnabled() const;
-
- /**
- * Sets the minimum and maximum values for the integrator.
- *
- * When the cap is reached, the integrator value is added to the controller
- * output rather than the integrator value times the integral gain.
- *
- * @param minimumIntegral The minimum value of the integrator.
- * @param maximumIntegral The maximum value of the integrator.
- */
- void SetIntegratorRange(double minimumIntegral, double maximumIntegral);
-
- /**
- * Sets the error which is considered tolerable for use with AtSetpoint().
- *
- * @param positionTolerance Position error which is tolerable.
- * @param velociytTolerance Velocity error which is tolerable.
- */
- void SetTolerance(
- double positionTolerance,
- double velocityTolerance = std::numeric_limits<double>::infinity());
-
- /**
- * Returns the difference between the setpoint and the measurement.
- */
- double GetPositionError() const;
-
- /**
- * Returns the velocity error.
- */
- double GetVelocityError() const;
-
- /**
- * Returns the next output of the PID controller.
- *
- * @param measurement The current measurement of the process variable.
- */
- double Calculate(double measurement);
-
- /**
- * Returns the next output of the PID controller.
- *
- * @param measurement The current measurement of the process variable.
- * @param setpoint The new setpoint of the controller.
- */
- double Calculate(double measurement, double setpoint);
-
- /**
- * Reset the previous error, the integral term, and disable the controller.
- */
- void Reset();
-
- void InitSendable(frc::SendableBuilder& builder) override;
-
- private:
- // Factor for "proportional" control
- double m_Kp;
-
- // Factor for "integral" control
- double m_Ki;
-
- // Factor for "derivative" control
- double m_Kd;
-
- // The period (in seconds) of the control loop running this controller
- units::second_t m_period;
-
- double m_maximumIntegral = 1.0;
-
- double m_minimumIntegral = -1.0;
-
- double m_maximumInput = 0;
-
- double m_minimumInput = 0;
-
- // Do the endpoints wrap around? eg. Absolute encoder
- bool m_continuous = false;
-
- // The error at the time of the most recent call to Calculate()
- double m_positionError = 0;
- double m_velocityError = 0;
-
- // The error at the time of the second-most-recent call to Calculate() (used
- // to compute velocity)
- double m_prevError = 0;
-
- // The sum of the errors for use in the integral calc
- double m_totalError = 0;
-
- // The error that is considered at setpoint.
- double m_positionTolerance = 0.05;
- double m_velocityTolerance = std::numeric_limits<double>::infinity();
-
- double m_setpoint = 0;
-};
-
-} // namespace frc2
diff --git a/wpilibc/src/main/native/include/frc/controller/ProfiledPIDController.h b/wpilibc/src/main/native/include/frc/controller/ProfiledPIDController.h
deleted file mode 100644
index fd246cd..0000000
--- a/wpilibc/src/main/native/include/frc/controller/ProfiledPIDController.h
+++ /dev/null
@@ -1,367 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <algorithm>
-#include <cmath>
-#include <functional>
-#include <limits>
-
-#include <units/time.h>
-
-#include "frc/controller/ControllerUtil.h"
-#include "frc/controller/PIDController.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableHelper.h"
-#include "frc/trajectory/TrapezoidProfile.h"
-
-namespace frc {
-namespace detail {
-void ReportProfiledPIDController();
-} // namespace detail
-
-/**
- * Implements a PID control loop whose setpoint is constrained by a trapezoid
- * profile.
- */
-template <class Distance>
-class ProfiledPIDController
- : public Sendable,
- public SendableHelper<ProfiledPIDController<Distance>> {
- public:
- using Distance_t = units::unit_t<Distance>;
- using Velocity =
- units::compound_unit<Distance, units::inverse<units::seconds>>;
- using Velocity_t = units::unit_t<Velocity>;
- using Acceleration =
- units::compound_unit<Velocity, units::inverse<units::seconds>>;
- using Acceleration_t = units::unit_t<Acceleration>;
- using State = typename TrapezoidProfile<Distance>::State;
- using Constraints = typename TrapezoidProfile<Distance>::Constraints;
-
- /**
- * Allocates a ProfiledPIDController with the given constants for Kp, Ki, and
- * Kd. Users should call reset() when they first start running the controller
- * to avoid unwanted behavior.
- *
- * @param Kp The proportional coefficient.
- * @param Ki The integral coefficient.
- * @param Kd The derivative coefficient.
- * @param constraints Velocity and acceleration constraints for goal.
- * @param period The period between controller updates in seconds. The
- * default is 20 milliseconds.
- */
- ProfiledPIDController(double Kp, double Ki, double Kd,
- Constraints constraints, units::second_t period = 20_ms)
- : m_controller(Kp, Ki, Kd, period), m_constraints(constraints) {
- detail::ReportProfiledPIDController();
- }
-
- ~ProfiledPIDController() override = default;
-
- ProfiledPIDController(const ProfiledPIDController&) = default;
- ProfiledPIDController& operator=(const ProfiledPIDController&) = default;
- ProfiledPIDController(ProfiledPIDController&&) = default;
- ProfiledPIDController& operator=(ProfiledPIDController&&) = default;
-
- /**
- * Sets the PID Controller gain parameters.
- *
- * Sets the proportional, integral, and differential coefficients.
- *
- * @param Kp Proportional coefficient
- * @param Ki Integral coefficient
- * @param Kd Differential coefficient
- */
- void SetPID(double Kp, double Ki, double Kd) {
- m_controller.SetPID(Kp, Ki, Kd);
- }
-
- /**
- * Sets the proportional coefficient of the PID controller gain.
- *
- * @param Kp proportional coefficient
- */
- void SetP(double Kp) { m_controller.SetP(Kp); }
-
- /**
- * Sets the integral coefficient of the PID controller gain.
- *
- * @param Ki integral coefficient
- */
- void SetI(double Ki) { m_controller.SetI(Ki); }
-
- /**
- * Sets the differential coefficient of the PID controller gain.
- *
- * @param Kd differential coefficient
- */
- void SetD(double Kd) { m_controller.SetD(Kd); }
-
- /**
- * Gets the proportional coefficient.
- *
- * @return proportional coefficient
- */
- double GetP() const { return m_controller.GetP(); }
-
- /**
- * Gets the integral coefficient.
- *
- * @return integral coefficient
- */
- double GetI() const { return m_controller.GetI(); }
-
- /**
- * Gets the differential coefficient.
- *
- * @return differential coefficient
- */
- double GetD() const { return m_controller.GetD(); }
-
- /**
- * Gets the period of this controller.
- *
- * @return The period of the controller.
- */
- units::second_t GetPeriod() const { return m_controller.GetPeriod(); }
-
- /**
- * Sets the goal for the ProfiledPIDController.
- *
- * @param goal The desired unprofiled setpoint.
- */
- void SetGoal(State goal) { m_goal = goal; }
-
- /**
- * Sets the goal for the ProfiledPIDController.
- *
- * @param goal The desired unprofiled setpoint.
- */
- void SetGoal(Distance_t goal) { m_goal = {goal, Velocity_t(0)}; }
-
- /**
- * Gets the goal for the ProfiledPIDController.
- */
- State GetGoal() const { return m_goal; }
-
- /**
- * Returns true if the error is within the tolerance of the error.
- *
- * This will return false until at least one input value has been computed.
- */
- bool AtGoal() const { return AtSetpoint() && m_goal == m_setpoint; }
-
- /**
- * Set velocity and acceleration constraints for goal.
- *
- * @param constraints Velocity and acceleration constraints for goal.
- */
- void SetConstraints(Constraints constraints) { m_constraints = constraints; }
-
- /**
- * Returns the current setpoint of the ProfiledPIDController.
- *
- * @return The current setpoint.
- */
- State GetSetpoint() const { return m_setpoint; }
-
- /**
- * Returns true if the error is within the tolerance of the error.
- *
- * Currently this just reports on target as the actual value passes through
- * the setpoint. Ideally it should be based on being within the tolerance for
- * some period of time.
- *
- * This will return false until at least one input value has been computed.
- */
- bool AtSetpoint() const { return m_controller.AtSetpoint(); }
-
- /**
- * Enables continuous input.
- *
- * Rather then using the max and min input range as constraints, it considers
- * them to be the same point and automatically calculates the shortest route
- * to the setpoint.
- *
- * @param minimumInput The minimum value expected from the input.
- * @param maximumInput The maximum value expected from the input.
- */
- void EnableContinuousInput(Distance_t minimumInput, Distance_t maximumInput) {
- m_controller.EnableContinuousInput(minimumInput.template to<double>(),
- maximumInput.template to<double>());
- m_minimumInput = minimumInput;
- m_maximumInput = maximumInput;
- }
-
- /**
- * Disables continuous input.
- */
- void DisableContinuousInput() { m_controller.DisableContinuousInput(); }
-
- /**
- * Sets the minimum and maximum values for the integrator.
- *
- * When the cap is reached, the integrator value is added to the controller
- * output rather than the integrator value times the integral gain.
- *
- * @param minimumIntegral The minimum value of the integrator.
- * @param maximumIntegral The maximum value of the integrator.
- */
- void SetIntegratorRange(double minimumIntegral, double maximumIntegral) {
- m_controller.SetIntegratorRange(minimumIntegral, maximumIntegral);
- }
-
- /**
- * Sets the error which is considered tolerable for use with
- * AtSetpoint().
- *
- * @param positionTolerance Position error which is tolerable.
- * @param velocityTolerance Velocity error which is tolerable.
- */
- void SetTolerance(
- Distance_t positionTolerance,
- Velocity_t velocityTolerance = std::numeric_limits<double>::infinity()) {
- m_controller.SetTolerance(positionTolerance.template to<double>(),
- velocityTolerance.template to<double>());
- }
-
- /**
- * Returns the difference between the setpoint and the measurement.
- *
- * @return The error.
- */
- Distance_t GetPositionError() const {
- return Distance_t(m_controller.GetPositionError());
- }
-
- /**
- * Returns the change in error per second.
- */
- Velocity_t GetVelocityError() const {
- return Velocity_t(m_controller.GetVelocityError());
- }
-
- /**
- * Returns the next output of the PID controller.
- *
- * @param measurement The current measurement of the process variable.
- */
- double Calculate(Distance_t measurement) {
- if (m_controller.IsContinuousInputEnabled()) {
- // Get error which is smallest distance between goal and measurement
- auto goalMinDistance = frc::GetModulusError<Distance_t>(
- m_goal.position, measurement, m_minimumInput, m_maximumInput);
- auto setpointMinDistance = frc::GetModulusError<Distance_t>(
- m_setpoint.position, measurement, m_minimumInput, m_maximumInput);
-
- // Recompute the profile goal with the smallest error, thus giving the
- // shortest path. The goal may be outside the input range after this
- // operation, but that's OK because the controller will still go there and
- // report an error of zero. In other words, the setpoint only needs to be
- // offset from the measurement by the input range modulus; they don't need
- // to be equal.
- m_goal.position = goalMinDistance + measurement;
- m_setpoint.position = setpointMinDistance + measurement;
- }
-
- frc::TrapezoidProfile<Distance> profile{m_constraints, m_goal, m_setpoint};
- m_setpoint = profile.Calculate(GetPeriod());
- return m_controller.Calculate(measurement.template to<double>(),
- m_setpoint.position.template to<double>());
- }
-
- /**
- * Returns the next output of the PID controller.
- *
- * @param measurement The current measurement of the process variable.
- * @param goal The new goal of the controller.
- */
- double Calculate(Distance_t measurement, State goal) {
- SetGoal(goal);
- return Calculate(measurement);
- }
- /**
- * Returns the next output of the PID controller.
- *
- * @param measurement The current measurement of the process variable.
- * @param goal The new goal of the controller.
- */
- double Calculate(Distance_t measurement, Distance_t goal) {
- SetGoal(goal);
- return Calculate(measurement);
- }
-
- /**
- * Returns the next output of the PID controller.
- *
- * @param measurement The current measurement of the process variable.
- * @param goal The new goal of the controller.
- * @param constraints Velocity and acceleration constraints for goal.
- */
- double Calculate(
- Distance_t measurement, Distance_t goal,
- typename frc::TrapezoidProfile<Distance>::Constraints constraints) {
- SetConstraints(constraints);
- return Calculate(measurement, goal);
- }
-
- /**
- * Reset the previous error and the integral term.
- *
- * @param measurement The current measured State of the system.
- */
- void Reset(const State& measurement) {
- m_controller.Reset();
- m_setpoint = measurement;
- }
-
- /**
- * Reset the previous error and the integral term.
- *
- * @param measuredPosition The current measured position of the system.
- * @param measuredVelocity The current measured velocity of the system.
- */
- void Reset(Distance_t measuredPosition, Velocity_t measuredVelocity) {
- Reset(State{measuredPosition, measuredVelocity});
- }
-
- /**
- * Reset the previous error and the integral term.
- *
- * @param measuredPosition The current measured position of the system. The
- * velocity is assumed to be zero.
- */
- void Reset(Distance_t measuredPosition) {
- Reset(measuredPosition, Velocity_t(0));
- }
-
- void InitSendable(frc::SendableBuilder& builder) override {
- builder.SetSmartDashboardType("ProfiledPIDController");
- builder.AddDoubleProperty(
- "p", [this] { return GetP(); }, [this](double value) { SetP(value); });
- builder.AddDoubleProperty(
- "i", [this] { return GetI(); }, [this](double value) { SetI(value); });
- builder.AddDoubleProperty(
- "d", [this] { return GetD(); }, [this](double value) { SetD(value); });
- builder.AddDoubleProperty(
- "goal", [this] { return GetGoal().position.template to<double>(); },
- [this](double value) { SetGoal(Distance_t{value}); });
- }
-
- private:
- frc2::PIDController m_controller;
- Distance_t m_minimumInput{0};
- Distance_t m_maximumInput{0};
- typename frc::TrapezoidProfile<Distance>::State m_goal;
- typename frc::TrapezoidProfile<Distance>::State m_setpoint;
- typename frc::TrapezoidProfile<Distance>::Constraints m_constraints;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/controller/RamseteController.h b/wpilibc/src/main/native/include/frc/controller/RamseteController.h
deleted file mode 100644
index e746bb3..0000000
--- a/wpilibc/src/main/native/include/frc/controller/RamseteController.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <units/angular_velocity.h>
-#include <units/velocity.h>
-
-#include "frc/geometry/Pose2d.h"
-#include "frc/kinematics/ChassisSpeeds.h"
-#include "frc/trajectory/Trajectory.h"
-
-namespace frc {
-
-/**
- * Ramsete is a nonlinear time-varying feedback controller for unicycle models
- * that drives the model to a desired pose along a two-dimensional trajectory.
- * Why would we need a nonlinear control law in addition to the linear ones we
- * have used so far like PID? If we use the original approach with PID
- * controllers for left and right position and velocity states, the controllers
- * only deal with the local pose. If the robot deviates from the path, there is
- * no way for the controllers to correct and the robot may not reach the desired
- * global pose. This is due to multiple endpoints existing for the robot which
- * have the same encoder path arc lengths.
- *
- * Instead of using wheel path arc lengths (which are in the robot's local
- * coordinate frame), nonlinear controllers like pure pursuit and Ramsete use
- * global pose. The controller uses this extra information to guide a linear
- * reference tracker like the PID controllers back in by adjusting the
- * references of the PID controllers.
- *
- * The paper "Control of Wheeled Mobile Robots: An Experimental Overview"
- * describes a nonlinear controller for a wheeled vehicle with unicycle-like
- * kinematics; a global pose consisting of x, y, and theta; and a desired pose
- * consisting of x_d, y_d, and theta_d. We call it Ramsete because that's the
- * acronym for the title of the book it came from in Italian ("Robotica
- * Articolata e Mobile per i SErvizi e le TEcnologie").
- *
- * See <https://file.tavsys.net/control/controls-engineering-in-frc.pdf> section
- * on Ramsete unicycle controller for a derivation and analysis.
- */
-class RamseteController {
- public:
- /**
- * Construct a Ramsete unicycle controller.
- *
- * @param b Tuning parameter (b > 0) for which larger values make
- * convergence more aggressive like a proportional term.
- * @param zeta Tuning parameter (0 < zeta < 1) for which larger values provide
- * more damping in response.
- */
- RamseteController(double b, double zeta);
-
- /**
- * Construct a Ramsete unicycle controller. The default arguments for
- * b and zeta of 2.0 and 0.7 have been well-tested to produce desirable
- * results.
- */
- RamseteController() : RamseteController(2.0, 0.7) {}
-
- /**
- * Returns true if the pose error is within tolerance of the reference.
- */
- bool AtReference() const;
-
- /**
- * Sets the pose error which is considered tolerable for use with
- * AtReference().
- *
- * @param poseTolerance Pose error which is tolerable.
- */
- void SetTolerance(const Pose2d& poseTolerance);
-
- /**
- * Returns the next output of the Ramsete controller.
- *
- * The reference pose, linear velocity, and angular velocity should come from
- * a drivetrain trajectory.
- *
- * @param currentPose The current pose.
- * @param poseRef The desired pose.
- * @param linearVelocityRef The desired linear velocity.
- * @param angularVelocityRef The desired angular velocity.
- */
- ChassisSpeeds Calculate(const Pose2d& currentPose, const Pose2d& poseRef,
- units::meters_per_second_t linearVelocityRef,
- units::radians_per_second_t angularVelocityRef);
-
- /**
- * Returns the next output of the Ramsete controller.
- *
- * The reference pose, linear velocity, and angular velocity should come from
- * a drivetrain trajectory.
- *
- * @param currentPose The current pose.
- * @param desiredState The desired pose, linear velocity, and angular velocity
- * from a trajectory.
- */
- ChassisSpeeds Calculate(const Pose2d& currentPose,
- const Trajectory::State& desiredState);
-
- /**
- * Enables and disables the controller for troubleshooting purposes.
- *
- * @param enabled If the controller is enabled or not.
- */
- void SetEnabled(bool enabled);
-
- private:
- double m_b;
- double m_zeta;
-
- Pose2d m_poseError;
- Pose2d m_poseTolerance;
- bool m_enabled = true;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h b/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h
index 86103de..50a7a3f 100644
--- a/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h
+++ b/wpilibc/src/main/native/include/frc/drive/DifferentialDrive.h
@@ -1,20 +1,29 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/raw_ostream.h>
+#include <string>
+
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/drive/RobotDriveBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
class SpeedController;
/**
@@ -22,9 +31,9 @@
* the Kit of Parts drive base, "tank drive", or West Coast Drive.
*
* These drive bases typically have drop-center / skid-steer with two or more
- * wheels per side (e.g., 6WD or 8WD). This class takes a SpeedController per
+ * wheels per side (e.g., 6WD or 8WD). This class takes a MotorController per
* side. For four and six motor drivetrains, construct and pass in
- * SpeedControllerGroup instances as follows.
+ * MotorControllerGroup instances as follows.
*
* Four motor drivetrain:
* @code{.cpp}
@@ -32,11 +41,11 @@
* public:
* frc::PWMVictorSPX m_frontLeft{1};
* frc::PWMVictorSPX m_rearLeft{2};
- * frc::SpeedControllerGroup m_left{m_frontLeft, m_rearLeft};
+ * frc::MotorControllerGroup m_left{m_frontLeft, m_rearLeft};
*
* frc::PWMVictorSPX m_frontRight{3};
* frc::PWMVictorSPX m_rearRight{4};
- * frc::SpeedControllerGroup m_right{m_frontRight, m_rearRight};
+ * frc::MotorControllerGroup m_right{m_frontRight, m_rearRight};
*
* frc::DifferentialDrive m_drive{m_left, m_right};
* };
@@ -49,12 +58,12 @@
* frc::PWMVictorSPX m_frontLeft{1};
* frc::PWMVictorSPX m_midLeft{2};
* frc::PWMVictorSPX m_rearLeft{3};
- * frc::SpeedControllerGroup m_left{m_frontLeft, m_midLeft, m_rearLeft};
+ * frc::MotorControllerGroup m_left{m_frontLeft, m_midLeft, m_rearLeft};
*
* frc::PWMVictorSPX m_frontRight{4};
* frc::PWMVictorSPX m_midRight{5};
* frc::PWMVictorSPX m_rearRight{6};
- * frc::SpeedControllerGroup m_right{m_frontRight, m_midRight, m_rearRight};
+ * frc::MotorControllerGroup m_right{m_frontRight, m_midRight, m_rearRight};
*
* frc::DifferentialDrive m_drive{m_left, m_right};
* };
@@ -87,28 +96,20 @@
* Inputs smaller then 0.02 will be set to 0, and larger values will be scaled
* so that the full range is still used. This deadband value can be changed
* with SetDeadband().
- *
- * <p>RobotDrive porting guide:
- * <br>TankDrive(double, double, bool) is equivalent to
- * RobotDrive#TankDrive(double, double, bool) if a deadband of 0 is used.
- * <br>ArcadeDrive(double, double, bool) is equivalent to
- * RobotDrive#ArcadeDrive(double, double, bool) if a deadband of 0 is used
- * and the the rotation input is inverted eg ArcadeDrive(y, -rotation, false)
- * <br>CurvatureDrive(double, double, bool) is similar in concept to
- * RobotDrive#Drive(double, double) with the addition of a quick turn
- * mode. However, it is not designed to give exactly the same response.
*/
class DifferentialDrive : public RobotDriveBase,
- public Sendable,
- public SendableHelper<DifferentialDrive> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<DifferentialDrive> {
public:
- static constexpr double kDefaultQuickStopThreshold = 0.2;
- static constexpr double kDefaultQuickStopAlpha = 0.1;
+ struct WheelSpeeds {
+ double left = 0.0;
+ double right = 0.0;
+ };
/**
* Construct a DifferentialDrive.
*
- * To pass multiple motors per side, use a SpeedControllerGroup. If a motor
+ * To pass multiple motors per side, use a MotorControllerGroup. If a motor
* needs to be inverted, do so before passing it in.
*/
DifferentialDrive(SpeedController& leftMotor, SpeedController& rightMotor);
@@ -137,17 +138,16 @@
*
* The rotation argument controls the curvature of the robot's path rather
* than its rate of heading change. This makes the robot more controllable at
- * high speeds. Also handles the robot's quick turn functionality - "quick
- * turn" overrides constant-curvature turning for turn-in-place maneuvers.
+ * high speeds.
*
- * @param xSpeed The robot's speed along the X axis [-1.0..1.0]. Forward
- * is positive.
- * @param zRotation The robot's rotation rate around the Z axis [-1.0..1.0].
- * Clockwise is positive.
- * @param isQuickTurn If set, overrides constant-curvature turning for
- * turn-in-place maneuvers.
+ * @param xSpeed The robot's speed along the X axis [-1.0..1.0].
+ * Forward is positive.
+ * @param zRotation The robot's rotation rate around the Z axis
+ * [-1.0..1.0]. Clockwise is positive.
+ * @param allowTurnInPlace If set, overrides constant-curvature turning for
+ * turn-in-place maneuvers.
*/
- void CurvatureDrive(double xSpeed, double zRotation, bool isQuickTurn);
+ void CurvatureDrive(double xSpeed, double zRotation, bool allowTurnInPlace);
/**
* Tank drive method for differential drive platform.
@@ -161,65 +161,65 @@
void TankDrive(double leftSpeed, double rightSpeed, bool squareInputs = true);
/**
- * Sets the QuickStop speed threshold in curvature drive.
+ * Arcade drive inverse kinematics for differential drive platform.
*
- * QuickStop compensates for the robot's moment of inertia when stopping after
- * a QuickTurn.
+ * Note: Some drivers may prefer inverted rotation controls. This can be done
+ * by negating the value passed for rotation.
*
- * While QuickTurn is enabled, the QuickStop accumulator takes on the rotation
- * rate value outputted by the low-pass filter when the robot's speed along
- * the X axis is below the threshold. When QuickTurn is disabled, the
- * accumulator's value is applied against the computed angular power request
- * to slow the robot's rotation.
- *
- * @param threshold X speed below which quick stop accumulator will receive
- * rotation rate values [0..1.0].
+ * @param xSpeed The speed at which the robot should drive along the X
+ * axis [-1.0..1.0]. Forward is positive.
+ * @param zRotation The rotation rate of the robot around the Z axis
+ * [-1.0..1.0]. Clockwise is positive.
+ * @param squareInputs If set, decreases the input sensitivity at low speeds.
*/
- void SetQuickStopThreshold(double threshold);
+ static WheelSpeeds ArcadeDriveIK(double xSpeed, double zRotation,
+ bool squareInputs = true);
/**
- * Sets the low-pass filter gain for QuickStop in curvature drive.
+ * Curvature drive inverse kinematics for differential drive platform.
*
- * The low-pass filter filters incoming rotation rate commands to smooth out
- * high frequency changes.
+ * The rotation argument controls the curvature of the robot's path rather
+ * than its rate of heading change. This makes the robot more controllable at
+ * high speeds.
*
- * @param alpha Low-pass filter gain [0.0..2.0]. Smaller values result in
- * slower output changes. Values between 1.0 and 2.0 result in
- * output oscillation. Values below 0.0 and above 2.0 are
- * unstable.
+ * @param xSpeed The robot's speed along the X axis [-1.0..1.0].
+ * Forward is positive.
+ * @param zRotation The robot's rotation rate around the Z axis
+ * [-1.0..1.0]. Clockwise is positive.
+ * @param allowTurnInPlace If set, overrides constant-curvature turning for
+ * turn-in-place maneuvers.
*/
- void SetQuickStopAlpha(double alpha);
+ static WheelSpeeds CurvatureDriveIK(double xSpeed, double zRotation,
+ bool allowTurnInPlace);
/**
- * Gets if the power sent to the right side of the drivetrain is multiplied by
- * -1.
+ * Tank drive inverse kinematics for differential drive platform.
*
- * @return true if the right side is inverted
+ * @param leftSpeed The robot left side's speed along the X axis
+ * [-1.0..1.0]. Forward is positive.
+ * @param rightSpeed The robot right side's speed along the X axis
+ * [-1.0..1.0]. Forward is positive.
+ * @param squareInputs If set, decreases the input sensitivity at low speeds.
*/
- bool IsRightSideInverted() const;
-
- /**
- * Sets if the power sent to the right side of the drivetrain should be
- * multiplied by -1.
- *
- * @param rightSideInverted true if right side power should be multiplied by
- * -1
- */
- void SetRightSideInverted(bool rightSideInverted);
+ static WheelSpeeds TankDriveIK(double leftSpeed, double rightSpeed,
+ bool squareInputs = true);
void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
+ std::string GetDescription() const override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
SpeedController* m_leftMotor;
SpeedController* m_rightMotor;
-
- double m_quickStopThreshold = kDefaultQuickStopThreshold;
- double m_quickStopAlpha = kDefaultQuickStopAlpha;
- double m_quickStopAccumulator = 0.0;
- double m_rightSideInvertMultiplier = -1.0;
};
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#elif defined(__clang__)
+#pragma clang diagnostic pop
+#elif defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/drive/KilloughDrive.h b/wpilibc/src/main/native/include/frc/drive/KilloughDrive.h
index 2cc1c91..1acc69f 100644
--- a/wpilibc/src/main/native/include/frc/drive/KilloughDrive.h
+++ b/wpilibc/src/main/native/include/frc/drive/KilloughDrive.h
@@ -1,23 +1,31 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string>
-#include <wpi/raw_ostream.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/drive/RobotDriveBase.h"
#include "frc/drive/Vector2d.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
class SpeedController;
/**
@@ -47,13 +55,19 @@
* clockwise rotation around the Z axis is positive.
*/
class KilloughDrive : public RobotDriveBase,
- public Sendable,
- public SendableHelper<KilloughDrive> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<KilloughDrive> {
public:
static constexpr double kDefaultLeftMotorAngle = 60.0;
static constexpr double kDefaultRightMotorAngle = 120.0;
static constexpr double kDefaultBackMotorAngle = 270.0;
+ struct WheelSpeeds {
+ double left = 0.0;
+ double right = 0.0;
+ double back = 0.0;
+ };
+
/**
* Construct a Killough drive with the given motors and default motor angles.
*
@@ -126,10 +140,28 @@
*/
void DrivePolar(double magnitude, double angle, double zRotation);
- void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
+ /**
+ * Cartesian inverse kinematics for Killough platform.
+ *
+ * Angles are measured clockwise from the positive X axis. The robot's speed
+ * is independent from its angle or rotation rate.
+ *
+ * @param ySpeed The robot's speed along the Y axis [-1.0..1.0]. Right is
+ * positive.
+ * @param xSpeed The robot's speed along the X axis [-1.0..1.0]. Forward is
+ * positive.
+ * @param zRotation The robot's rotation rate around the Z axis [-1.0..1.0].
+ * Clockwise is positive.
+ * @param gyroAngle The current angle reading from the gyro in degrees around
+ * the Z axis. Use this to implement field-oriented controls.
+ */
+ WheelSpeeds DriveCartesianIK(double ySpeed, double xSpeed, double zRotation,
+ double gyroAngle = 0.0);
- void InitSendable(SendableBuilder& builder) override;
+ void StopMotor() override;
+ std::string GetDescription() const override;
+
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
SpeedController* m_leftMotor;
@@ -143,4 +175,12 @@
bool reported = false;
};
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#elif defined(__clang__)
+#pragma clang diagnostic pop
+#elif defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h b/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h
index 8435b4d..809e7ea 100644
--- a/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h
+++ b/wpilibc/src/main/native/include/frc/drive/MecanumDrive.h
@@ -1,22 +1,30 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string>
-#include <wpi/raw_ostream.h>
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
#include "frc/drive/RobotDriveBase.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
namespace frc {
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
class SpeedController;
/**
@@ -52,22 +60,29 @@
* with SetDeadband().
*
* RobotDrive porting guide:
- * <br>In MecanumDrive, the right side speed controllers are automatically
- * inverted, while in RobotDrive, no speed controllers are automatically
+ * <br>In MecanumDrive, the right side motor controllers are automatically
+ * inverted, while in RobotDrive, no motor controllers are automatically
* inverted.
* <br>DriveCartesian(double, double, double, double) is equivalent to
- * RobotDrive#MecanumDrive_Cartesian(double, double, double, double)
+ * RobotDrive's MecanumDrive_Cartesian(double, double, double, double)
* if a deadband of 0 is used, and the ySpeed and gyroAngle values are inverted
* compared to RobotDrive (eg DriveCartesian(xSpeed, -ySpeed, zRotation,
* -gyroAngle).
* <br>DrivePolar(double, double, double) is equivalent to
- * RobotDrive#MecanumDrive_Polar(double, double, double) if a
+ * RobotDrive's MecanumDrive_Polar(double, double, double) if a
* deadband of 0 is used.
*/
class MecanumDrive : public RobotDriveBase,
- public Sendable,
- public SendableHelper<MecanumDrive> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<MecanumDrive> {
public:
+ struct WheelSpeeds {
+ double frontLeft = 0.0;
+ double frontRight = 0.0;
+ double rearLeft = 0.0;
+ double rearRight = 0.0;
+ };
+
/**
* Construct a MecanumDrive.
*
@@ -116,26 +131,27 @@
void DrivePolar(double magnitude, double angle, double zRotation);
/**
- * Gets if the power sent to the right side of the drivetrain is multiplied by
- * -1.
+ * Cartesian inverse kinematics for Mecanum platform.
*
- * @return true if the right side is inverted
- */
- bool IsRightSideInverted() const;
-
- /**
- * Sets if the power sent to the right side of the drivetrain should be
- * multiplied by -1.
+ * Angles are measured clockwise from the positive X axis. The robot's speed
+ * is independent from its angle or rotation rate.
*
- * @param rightSideInverted true if right side power should be multiplied by
- * -1
+ * @param ySpeed The robot's speed along the Y axis [-1.0..1.0]. Right is
+ * positive.
+ * @param xSpeed The robot's speed along the X axis [-1.0..1.0]. Forward is
+ * positive.
+ * @param zRotation The robot's rotation rate around the Z axis [-1.0..1.0].
+ * Clockwise is positive.
+ * @param gyroAngle The current angle reading from the gyro in degrees around
+ * the Z axis. Use this to implement field-oriented controls.
*/
- void SetRightSideInverted(bool rightSideInverted);
+ static WheelSpeeds DriveCartesianIK(double ySpeed, double xSpeed,
+ double zRotation, double gyroAngle = 0.0);
void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
+ std::string GetDescription() const override;
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
SpeedController* m_frontLeftMotor;
@@ -143,9 +159,15 @@
SpeedController* m_frontRightMotor;
SpeedController* m_rearRightMotor;
- double m_rightSideInvertMultiplier = -1.0;
-
bool reported = false;
};
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#elif defined(__clang__)
+#pragma clang diagnostic pop
+#elif defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h b/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h
index ce9cbc5..389d67b 100644
--- a/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h
+++ b/wpilibc/src/main/native/include/frc/drive/RobotDriveBase.h
@@ -1,23 +1,19 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string>
-#include <wpi/ArrayRef.h>
-#include <wpi/raw_ostream.h>
+#include <wpi/deprecated.h>
+#include <wpi/span.h>
#include "frc/MotorSafety.h"
namespace frc {
-class SpeedController;
-
/**
* Common base class for drive platforms.
*/
@@ -47,7 +43,7 @@
*
* The default value is 0.02. Inputs smaller than the deadband are set to 0.0
* while inputs larger than the deadband are scaled from 0.0 to 1.0. See
- * ApplyDeadband().
+ * frc::ApplyDeadband().
*
* @param deadband The deadband to set.
*/
@@ -71,7 +67,7 @@
void FeedWatchdog();
void StopMotor() override = 0;
- void GetDescription(wpi::raw_ostream& desc) const override = 0;
+ std::string GetDescription() const override = 0;
protected:
/**
@@ -80,14 +76,16 @@
*
* @param value value to clip
* @param deadband range around zero
+ * @deprecated Use ApplyDeadband() in frc/MathUtil.h.
*/
- double ApplyDeadband(double number, double deadband);
+ WPI_DEPRECATED("Use ApplyDeadband() in frc/MathUtil.h")
+ static double ApplyDeadband(double value, double deadband);
/**
* Normalize all wheel speeds if the magnitude of any wheel is greater than
* 1.0.
*/
- void Normalize(wpi::MutableArrayRef<double> wheelSpeeds);
+ static void Normalize(wpi::span<double> wheelSpeeds);
double m_deadband = 0.02;
double m_maxOutput = 1.0;
diff --git a/wpilibc/src/main/native/include/frc/drive/Vector2d.h b/wpilibc/src/main/native/include/frc/drive/Vector2d.h
index c9bd08a..92a3de6 100644
--- a/wpilibc/src/main/native/include/frc/drive/Vector2d.h
+++ b/wpilibc/src/main/native/include/frc/drive/Vector2d.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/filters/Filter.h b/wpilibc/src/main/native/include/frc/filters/Filter.h
deleted file mode 100644
index fb14d28..0000000
--- a/wpilibc/src/main/native/include/frc/filters/Filter.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-
-#include <wpi/deprecated.h>
-
-#include "frc/PIDSource.h"
-
-namespace frc {
-
-/**
- * Interface for filters
- *
- * @deprecated only used by the deprecated LinearDigitalFilter
- */
-class Filter : public PIDSource {
- public:
- WPI_DEPRECATED("This class is no longer used.")
- explicit Filter(PIDSource& source);
- WPI_DEPRECATED("This class is no longer used.")
- explicit Filter(std::shared_ptr<PIDSource> source);
- virtual ~Filter() = default;
-
- Filter(Filter&&) = default;
- Filter& operator=(Filter&&) = default;
-
- // PIDSource interface
- void SetPIDSourceType(PIDSourceType pidSource) override;
- PIDSourceType GetPIDSourceType() const override;
- double PIDGet() override = 0;
-
- /**
- * Returns the current filter estimate without also inserting new data as
- * PIDGet() would do.
- *
- * @return The current filter estimate
- */
- virtual double Get() const = 0;
-
- /**
- * Reset the filter state
- */
- virtual void Reset() = 0;
-
- protected:
- /**
- * Calls PIDGet() of source
- *
- * @return Current value of source
- */
- double PIDGetSource();
-
- private:
- std::shared_ptr<PIDSource> m_source;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/filters/LinearDigitalFilter.h b/wpilibc/src/main/native/include/frc/filters/LinearDigitalFilter.h
deleted file mode 100644
index c4fc3ef..0000000
--- a/wpilibc/src/main/native/include/frc/filters/LinearDigitalFilter.h
+++ /dev/null
@@ -1,226 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <initializer_list>
-#include <memory>
-#include <vector>
-
-#include <wpi/ArrayRef.h>
-#include <wpi/circular_buffer.h>
-#include <wpi/deprecated.h>
-
-#include "frc/filters/Filter.h"
-
-namespace frc {
-
-/**
- * This class implements a linear, digital filter. All types of FIR and IIR
- * filters are supported. Static factory methods are provided to create commonly
- * used types of filters.
- *
- * Filters are of the form:<br>
- * y[n] = (b0 * x[n] + b1 * x[n-1] + ... + bP * x[n-P]) -
- * (a0 * y[n-1] + a2 * y[n-2] + ... + aQ * y[n-Q])
- *
- * Where:<br>
- * y[n] is the output at time "n"<br>
- * x[n] is the input at time "n"<br>
- * y[n-1] is the output from the LAST time step ("n-1")<br>
- * x[n-1] is the input from the LAST time step ("n-1")<br>
- * b0...bP are the "feedforward" (FIR) gains<br>
- * a0...aQ are the "feedback" (IIR) gains<br>
- * IMPORTANT! Note the "-" sign in front of the feedback term! This is a common
- * convention in signal processing.
- *
- * What can linear filters do? Basically, they can filter, or diminish, the
- * effects of undesirable input frequencies. High frequencies, or rapid changes,
- * can be indicative of sensor noise or be otherwise undesirable. A "low pass"
- * filter smooths out the signal, reducing the impact of these high frequency
- * components. Likewise, a "high pass" filter gets rid of slow-moving signal
- * components, letting you detect large changes more easily.
- *
- * Example FRC applications of filters:
- * - Getting rid of noise from an analog sensor input (note: the roboRIO's FPGA
- * can do this faster in hardware)
- * - Smoothing out joystick input to prevent the wheels from slipping or the
- * robot from tipping
- * - Smoothing motor commands so that unnecessary strain isn't put on
- * electrical or mechanical components
- * - If you use clever gains, you can make a PID controller out of this class!
- *
- * For more on filters, I highly recommend the following articles:<br>
- * http://en.wikipedia.org/wiki/Linear_filter<br>
- * http://en.wikipedia.org/wiki/Iir_filter<br>
- * http://en.wikipedia.org/wiki/Fir_filter<br>
- *
- * Note 1: PIDGet() should be called by the user on a known, regular period.
- * You can set up a Notifier to do this (look at the WPILib PIDController
- * class), or do it "inline" with code in a periodic function.
- *
- * Note 2: For ALL filters, gains are necessarily a function of frequency. If
- * you make a filter that works well for you at, say, 100Hz, you will most
- * definitely need to adjust the gains if you then want to run it at 200Hz!
- * Combining this with Note 1 - the impetus is on YOU as a developer to make
- * sure PIDGet() gets called at the desired, constant frequency!
- *
- * @deprecated Use LinearFilter class instead
- */
-class LinearDigitalFilter : public Filter {
- public:
- /**
- * Create a linear FIR or IIR filter.
- *
- * @param source The PIDSource object that is used to get values
- * @param ffGains The "feed forward" or FIR gains
- * @param fbGains The "feed back" or IIR gains
- */
- WPI_DEPRECATED("Use LinearFilter class instead.")
- LinearDigitalFilter(PIDSource& source, wpi::ArrayRef<double> ffGains,
- wpi::ArrayRef<double> fbGains);
-
- /**
- * Create a linear FIR or IIR filter.
- *
- * @param source The PIDSource object that is used to get values
- * @param ffGains The "feed forward" or FIR gains
- * @param fbGains The "feed back" or IIR gains
- */
- WPI_DEPRECATED("Use LinearFilter class instead.")
- LinearDigitalFilter(PIDSource& source, std::initializer_list<double> ffGains,
- std::initializer_list<double> fbGains);
-
- /**
- * Create a linear FIR or IIR filter.
- *
- * @param source The PIDSource object that is used to get values
- * @param ffGains The "feed forward" or FIR gains
- * @param fbGains The "feed back" or IIR gains
- */
- WPI_DEPRECATED("Use LinearFilter class instead.")
- LinearDigitalFilter(std::shared_ptr<PIDSource> source,
- wpi::ArrayRef<double> ffGains,
- wpi::ArrayRef<double> fbGains);
-
- /**
- * Create a linear FIR or IIR filter.
- *
- * @param source The PIDSource object that is used to get values
- * @param ffGains The "feed forward" or FIR gains
- * @param fbGains The "feed back" or IIR gains
- */
- WPI_DEPRECATED("Use LinearFilter class instead.")
- LinearDigitalFilter(std::shared_ptr<PIDSource> source,
- std::initializer_list<double> ffGains,
- std::initializer_list<double> fbGains);
-
- LinearDigitalFilter(LinearDigitalFilter&&) = default;
- LinearDigitalFilter& operator=(LinearDigitalFilter&&) = default;
-
- // Static methods to create commonly used filters
- /**
- * Creates a one-pole IIR low-pass filter of the form:<br>
- * y[n] = (1 - gain) * x[n] + gain * y[n-1]<br>
- * where gain = e<sup>-dt / T</sup>, T is the time constant in seconds
- *
- * This filter is stable for time constants greater than zero.
- *
- * @param source The PIDSource object that is used to get values
- * @param timeConstant The discrete-time time constant in seconds
- * @param period The period in seconds between samples taken by the user
- */
- static LinearDigitalFilter SinglePoleIIR(PIDSource& source,
- double timeConstant, double period);
-
- /**
- * Creates a first-order high-pass filter of the form:<br>
- * y[n] = gain * x[n] + (-gain) * x[n-1] + gain * y[n-1]<br>
- * where gain = e<sup>-dt / T</sup>, T is the time constant in seconds
- *
- * This filter is stable for time constants greater than zero.
- *
- * @param source The PIDSource object that is used to get values
- * @param timeConstant The discrete-time time constant in seconds
- * @param period The period in seconds between samples taken by the user
- */
- static LinearDigitalFilter HighPass(PIDSource& source, double timeConstant,
- double period);
-
- /**
- * Creates a K-tap FIR moving average filter of the form:<br>
- * y[n] = 1/k * (x[k] + x[k-1] + … + x[0])
- *
- * This filter is always stable.
- *
- * @param source The PIDSource object that is used to get values
- * @param taps The number of samples to average over. Higher = smoother but
- * slower
- */
- static LinearDigitalFilter MovingAverage(PIDSource& source, int taps);
-
- /**
- * Creates a one-pole IIR low-pass filter of the form:<br>
- * y[n] = (1 - gain) * x[n] + gain * y[n-1]<br>
- * where gain = e<sup>-dt / T</sup>, T is the time constant in seconds
- *
- * This filter is stable for time constants greater than zero.
- *
- * @param source The PIDSource object that is used to get values
- * @param timeConstant The discrete-time time constant in seconds
- * @param period The period in seconds between samples taken by the user
- */
- static LinearDigitalFilter SinglePoleIIR(std::shared_ptr<PIDSource> source,
- double timeConstant, double period);
-
- /**
- * Creates a first-order high-pass filter of the form:<br>
- * y[n] = gain * x[n] + (-gain) * x[n-1] + gain * y[n-1]<br>
- * where gain = e<sup>-dt / T</sup>, T is the time constant in seconds
- *
- * This filter is stable for time constants greater than zero.
- *
- * @param source The PIDSource object that is used to get values
- * @param timeConstant The discrete-time time constant in seconds
- * @param period The period in seconds between samples taken by the user
- */
- static LinearDigitalFilter HighPass(std::shared_ptr<PIDSource> source,
- double timeConstant, double period);
-
- /**
- * Creates a K-tap FIR moving average filter of the form:<br>
- * y[n] = 1/k * (x[k] + x[k-1] + … + x[0])
- *
- * This filter is always stable.
- *
- * @param source The PIDSource object that is used to get values
- * @param taps The number of samples to average over. Higher = smoother but
- * slower
- */
- static LinearDigitalFilter MovingAverage(std::shared_ptr<PIDSource> source,
- int taps);
-
- // Filter interface
- double Get() const override;
- void Reset() override;
-
- // PIDSource interface
- /**
- * Calculates the next value of the filter
- *
- * @return The filtered value at this step
- */
- double PIDGet() override;
-
- private:
- wpi::circular_buffer<double> m_inputs;
- wpi::circular_buffer<double> m_outputs;
- std::vector<double> m_inputGains;
- std::vector<double> m_outputGains;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h b/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h
index 499ba5b..c95466a 100644
--- a/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h
+++ b/wpilibc/src/main/native/include/frc/interfaces/Accelerometer.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/interfaces/Gyro.h b/wpilibc/src/main/native/include/frc/interfaces/Gyro.h
index 8c06993..50417ea 100644
--- a/wpilibc/src/main/native/include/frc/interfaces/Gyro.h
+++ b/wpilibc/src/main/native/include/frc/interfaces/Gyro.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/interfaces/Potentiometer.h b/wpilibc/src/main/native/include/frc/interfaces/Potentiometer.h
deleted file mode 100644
index 219e6ba..0000000
--- a/wpilibc/src/main/native/include/frc/interfaces/Potentiometer.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/PIDSource.h"
-
-namespace frc {
-
-/**
- * Interface for potentiometers.
- */
-class Potentiometer : public PIDSource {
- public:
- Potentiometer() = default;
- virtual ~Potentiometer() = default;
-
- Potentiometer(Potentiometer&&) = default;
- Potentiometer& operator=(Potentiometer&&) = default;
-
- /**
- * Common interface for getting the current value of a potentiometer.
- *
- * @return The current set speed. Value is between -1.0 and 1.0.
- */
- virtual double Get() const = 0;
-
- void SetPIDSourceType(PIDSourceType pidSource) override;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h b/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h
index b755f46..6851cde 100644
--- a/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h
+++ b/wpilibc/src/main/native/include/frc/livewindow/LiveWindow.h
@@ -1,66 +1,77 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2012-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
-#include <memory>
+
+#include <wpi/deprecated.h>
+
+namespace wpi {
+class Sendable;
+} // namespace wpi
namespace frc {
-class Sendable;
-
/**
* The LiveWindow class is the public interface for putting sensors and
* actuators on the LiveWindow.
*/
class LiveWindow {
public:
- LiveWindow(const LiveWindow&) = delete;
- LiveWindow& operator=(const LiveWindow&) = delete;
-
- std::function<void()> enabled;
- std::function<void()> disabled;
-
/**
* Get an instance of the LiveWindow main class.
*
* This is a singleton to guarantee that there is only a single instance
* regardless of how many times GetInstance is called.
+ * @deprecated Use the static methods unless guaranteeing LiveWindow is
+ * instantiated
*/
+ WPI_DEPRECATED("Use static methods")
static LiveWindow* GetInstance();
/**
+ * Set function to be called when LiveWindow is enabled.
+ *
+ * @param func function (or nullptr for none)
+ */
+ static void SetEnabledCallback(std::function<void()> func);
+
+ /**
+ * Set function to be called when LiveWindow is disabled.
+ *
+ * @param func function (or nullptr for none)
+ */
+ static void SetDisabledCallback(std::function<void()> func);
+
+ /**
* Enable telemetry for a single component.
*
- * @param sendable component
+ * @param component sendable
*/
- void EnableTelemetry(Sendable* component);
+ static void EnableTelemetry(wpi::Sendable* component);
/**
* Disable telemetry for a single component.
*
- * @param sendable component
+ * @param component sendable
*/
- void DisableTelemetry(Sendable* component);
+ static void DisableTelemetry(wpi::Sendable* component);
/**
* Disable ALL telemetry.
*/
- void DisableAllTelemetry();
+ static void DisableAllTelemetry();
- bool IsEnabled() const;
+ static bool IsEnabled();
/**
* Change the enabled status of LiveWindow.
*
* If it changes to enabled, start livewindow running otherwise stop it
*/
- void SetEnabled(bool enabled);
+ static void SetEnabled(bool enabled);
/**
* Tell all the sensors to update (send) their values.
@@ -68,18 +79,15 @@
* Actuators are handled through callbacks on their value changing from the
* SmartDashboard widgets.
*/
- void UpdateValues();
+ static void UpdateValues();
private:
- LiveWindow();
-
- struct Impl;
- std::unique_ptr<Impl> m_impl;
+ LiveWindow() = default;
/**
* Updates the entries, without using a mutex or lock.
*/
- void UpdateValuesUnsafe();
+ static void UpdateValuesUnsafe();
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/DMC60.h b/wpilibc/src/main/native/include/frc/motorcontrol/DMC60.h
similarity index 62%
rename from wpilibc/src/main/native/include/frc/DMC60.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/DMC60.h
index ecf01e1..f47826a 100644
--- a/wpilibc/src/main/native/include/frc/DMC60.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/DMC60.h
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/PWMSpeedController.h"
+#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
/**
- * Digilent DMC 60 Speed Controller.
+ * Digilent DMC 60 Motor %Controller.
*
* Note that the DMC 60 uses the following bounds for PWM values. These
* values should work reasonably well for most controllers, but if users
@@ -27,7 +24,7 @@
* \li 1.480ms = the "low end" of the deadband range
* \li 0.997ms = full "reverse"
*/
-class DMC60 : public PWMSpeedController {
+class DMC60 : public PWMMotorController {
public:
/**
* Constructor for a Digilent DMC 60.
diff --git a/wpilibc/src/main/native/include/frc/Jaguar.h b/wpilibc/src/main/native/include/frc/motorcontrol/Jaguar.h
similarity index 61%
rename from wpilibc/src/main/native/include/frc/Jaguar.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/Jaguar.h
index 7a8503e..d25a457 100644
--- a/wpilibc/src/main/native/include/frc/Jaguar.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/Jaguar.h
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/PWMSpeedController.h"
+#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
/**
- * Luminary Micro / Vex Robotics Jaguar Speed Controller with PWM control.
+ * Luminary Micro / Vex Robotics Jaguar Motor %Controller with PWM control.
*
* Note that the Jaguar uses the following bounds for PWM values. These values
* should work reasonably well for most controllers, but if users experience
@@ -27,7 +24,7 @@
* \li 1.454ms = the "low end" of the deadband range
* \li 0.697ms = full "reverse"
*/
-class Jaguar : public PWMSpeedController {
+class Jaguar : public PWMMotorController {
public:
/**
* Constructor for a Jaguar connected via PWM.
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/MotorController.h b/wpilibc/src/main/native/include/frc/motorcontrol/MotorController.h
new file mode 100644
index 0000000..8ed19bc
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/MotorController.h
@@ -0,0 +1,37 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <units/voltage.h>
+
+#include "frc/SpeedController.h"
+
+namespace frc {
+
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996) // was declared deprecated
+#elif defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#elif defined(__GNUC__)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
+/**
+ * Interface for motor controlling devices.
+ */
+class MotorController : public SpeedController {};
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#elif defined(__clang__)
+#pragma clang diagnostic pop
+#elif defined(__GNUC__)
+#pragma GCC diagnostic pop
+#endif
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h
new file mode 100644
index 0000000..6f47bf9
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.h
@@ -0,0 +1,51 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <functional>
+#include <vector>
+
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/motorcontrol/MotorController.h"
+
+namespace frc {
+
+/**
+ * Allows multiple MotorController objects to be linked together.
+ */
+class MotorControllerGroup : public wpi::Sendable,
+ public MotorController,
+ public wpi::SendableHelper<MotorControllerGroup> {
+ public:
+ template <class... MotorControllers>
+ explicit MotorControllerGroup(MotorController& motorController,
+ MotorControllers&... motorControllers);
+ explicit MotorControllerGroup(
+ std::vector<std::reference_wrapper<MotorController>>&& motorControllers);
+
+ MotorControllerGroup(MotorControllerGroup&&) = default;
+ MotorControllerGroup& operator=(MotorControllerGroup&&) = default;
+
+ void Set(double speed) override;
+ double Get() const override;
+ void SetInverted(bool isInverted) override;
+ bool GetInverted() const override;
+ void Disable() override;
+ void StopMotor() override;
+
+ void InitSendable(wpi::SendableBuilder& builder) override;
+
+ private:
+ bool m_isInverted = false;
+ std::vector<std::reference_wrapper<MotorController>> m_motorControllers;
+
+ void Initialize();
+};
+
+} // namespace frc
+
+#include "frc/motorcontrol/MotorControllerGroup.inc"
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc
new file mode 100644
index 0000000..8f87635
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/MotorControllerGroup.inc
@@ -0,0 +1,22 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <functional>
+#include <vector>
+
+#include "frc/motorcontrol/MotorControllerGroup.h"
+
+namespace frc {
+
+template <class... MotorControllers>
+MotorControllerGroup::MotorControllerGroup(
+ MotorController& motorController, MotorControllers&... motorControllers)
+ : m_motorControllers(std::vector<std::reference_wrapper<MotorController>>{
+ motorController, motorControllers...}) {
+ Initialize();
+}
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/NidecBrushless.h b/wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h
similarity index 61%
rename from wpilibc/src/main/native/include/frc/NidecBrushless.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h
index fa77e28..cc95d71 100644
--- a/wpilibc/src/main/native/include/frc/NidecBrushless.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/NidecBrushless.h
@@ -1,31 +1,28 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
+#include <string>
+
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
#include "frc/DigitalOutput.h"
-#include "frc/ErrorBase.h"
#include "frc/MotorSafety.h"
#include "frc/PWM.h"
-#include "frc/SpeedController.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include "frc/motorcontrol/MotorController.h"
namespace frc {
-class SendableBuilder;
-
/**
* Nidec Brushless Motor.
*/
-class NidecBrushless : public SpeedController,
+class NidecBrushless : public MotorController,
public MotorSafety,
- public Sendable,
- public SendableHelper<NidecBrushless> {
+ public wpi::Sendable,
+ public wpi::SendableHelper<NidecBrushless> {
public:
/**
* Constructor.
@@ -42,7 +39,7 @@
NidecBrushless(NidecBrushless&&) = default;
NidecBrushless& operator=(NidecBrushless&&) = default;
- // SpeedController interface
+ // MotorController interface
/**
* Set the PWM value.
*
@@ -76,17 +73,9 @@
*/
void Enable();
- // PIDOutput interface
- /**
- * Write out the PID value as seen in the PIDOutput base object.
- *
- * @param output Write out the PWM value as was found in the PIDController
- */
- void PIDWrite(double output) override;
-
// MotorSafety interface
void StopMotor() override;
- void GetDescription(wpi::raw_ostream& desc) const override;
+ std::string GetDescription() const override;
/**
* Gets the channel number associated with the object.
@@ -96,7 +85,7 @@
int GetChannel() const;
// Sendable interface
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
bool m_isInverted = false;
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h
new file mode 100644
index 0000000..ac6ba4b
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMMotorController.h
@@ -0,0 +1,84 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <string>
+#include <string_view>
+
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/MotorSafety.h"
+#include "frc/PWM.h"
+#include "frc/motorcontrol/MotorController.h"
+
+namespace frc {
+class DMA;
+
+/**
+ * Common base class for all PWM Motor Controllers.
+ */
+class PWMMotorController : public MotorController,
+ public MotorSafety,
+ public wpi::Sendable,
+ public wpi::SendableHelper<PWMMotorController> {
+ public:
+ friend class DMA;
+
+ PWMMotorController(PWMMotorController&&) = default;
+ PWMMotorController& operator=(PWMMotorController&&) = default;
+
+ /**
+ * Set the PWM value.
+ *
+ * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
+ * the value for the FPGA.
+ *
+ * @param value The speed value between -1.0 and 1.0 to set.
+ */
+ void Set(double value) override;
+
+ /**
+ * Get the recently set value of the PWM. This value is affected by the
+ * inversion property. If you want the value that is sent directly to the
+ * MotorController, use PWM::GetSpeed() instead.
+ *
+ * @return The most recently set value for the PWM between -1.0 and 1.0.
+ */
+ double Get() const override;
+
+ void SetInverted(bool isInverted) override;
+
+ bool GetInverted() const override;
+
+ void Disable() override;
+
+ // MotorSafety interface
+ void StopMotor() override;
+ std::string GetDescription() const override;
+
+ int GetChannel() const;
+
+ protected:
+ /**
+ * Constructor for a PWM Motor %Controller connected via PWM.
+ *
+ * @param name Name to use for SendableRegistry
+ * @param channel The PWM channel that the controller is attached to. 0-9 are
+ * on-board, 10-19 are on the MXP port
+ */
+ PWMMotorController(std::string_view name, int channel);
+
+ void InitSendable(wpi::SendableBuilder& builder) override;
+
+ PWM m_pwm;
+
+ private:
+ bool m_isInverted = false;
+
+ PWM* GetPwm() { return &m_pwm; }
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PWMSparkMax.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMSparkMax.h
similarity index 62%
rename from wpilibc/src/main/native/include/frc/PWMSparkMax.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/PWMSparkMax.h
index 3ce6466..45c7bae 100644
--- a/wpilibc/src/main/native/include/frc/PWMSparkMax.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMSparkMax.h
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/PWMSpeedController.h"
+#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
/**
- * REV Robotics SPARK MAX Speed Controller.
+ * REV Robotics SPARK MAX Motor %Controller.
*
* Note that the SPARK MAX uses the following bounds for PWM values. These
* values should work reasonably well for most controllers, but if users
@@ -27,7 +24,7 @@
* \li 1.460ms = the "low end" of the deadband range
* \li 0.999ms = full "reverse"
*/
-class PWMSparkMax : public PWMSpeedController {
+class PWMSparkMax : public PWMMotorController {
public:
/**
* Constructor for a SPARK MAX.
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/PWMTalonFX.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMTalonFX.h
new file mode 100644
index 0000000..29aada6
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMTalonFX.h
@@ -0,0 +1,42 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+namespace frc {
+
+/**
+ * Cross the Road Electronics (CTRE) %Talon FX Motor %Controller with PWM
+ * control.
+ *
+ * Note that the %Talon FX uses the following bounds for PWM values. These
+ * values should work reasonably well for most controllers, but if users
+ * experience issues such as asymmetric behavior around the deadband or
+ * inability to saturate the controller in either direction, calibration is
+ * recommended. The calibration procedure can be found in the %Talon FX User
+ * Manual available from Cross The Road Electronics.
+ *
+ * \li 2.004ms = full "forward"
+ * \li 1.520ms = the "high end" of the deadband range
+ * \li 1.500ms = center of the deadband range (off)
+ * \li 1.480ms = the "low end" of the deadband range
+ * \li 0.997ms = full "reverse"
+ */
+class PWMTalonFX : public PWMMotorController {
+ public:
+ /**
+ * Construct a %Talon FX connected via PWM.
+ *
+ * @param channel The PWM channel that the %Talon FX is attached to. 0-9 are
+ * on-board, 10-19 are on the MXP port
+ */
+ explicit PWMTalonFX(int channel);
+
+ PWMTalonFX(PWMTalonFX&&) = default;
+ PWMTalonFX& operator=(PWMTalonFX&&) = default;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/PWMTalonSRX.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMTalonSRX.h
new file mode 100644
index 0000000..9f9e384
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMTalonSRX.h
@@ -0,0 +1,42 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+namespace frc {
+
+/**
+ * Cross the Road Electronics (CTRE) %Talon SRX Motor %Controller with PWM
+ * control.
+ *
+ * Note that the %Talon SRX uses the following bounds for PWM values. These
+ * values should work reasonably well for most controllers, but if users
+ * experience issues such as asymmetric behavior around the deadband or
+ * inability to saturate the controller in either direction, calibration is
+ * recommended. The calibration procedure can be found in the %Talon SRX User
+ * Manual available from Cross The Road Electronics.
+ *
+ * \li 2.004ms = full "forward"
+ * \li 1.520ms = the "high end" of the deadband range
+ * \li 1.500ms = center of the deadband range (off)
+ * \li 1.480ms = the "low end" of the deadband range
+ * \li 0.997ms = full "reverse"
+ */
+class PWMTalonSRX : public PWMMotorController {
+ public:
+ /**
+ * Construct a %Talon SRX connected via PWM.
+ *
+ * @param channel The PWM channel that the %Talon SRX is attached to. 0-9 are
+ * on-board, 10-19 are on the MXP port
+ */
+ explicit PWMTalonSRX(int channel);
+
+ PWMTalonSRX(PWMTalonSRX&&) = default;
+ PWMTalonSRX& operator=(PWMTalonSRX&&) = default;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/PWMVenom.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMVenom.h
similarity index 63%
rename from wpilibc/src/main/native/include/frc/PWMVenom.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/PWMVenom.h
index 189db43..1047e8e 100644
--- a/wpilibc/src/main/native/include/frc/PWMVenom.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMVenom.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/PWMSpeedController.h"
+#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
@@ -26,7 +23,7 @@
* \li 1.480ms = the "low end" of the deadband range
* \li 0.997ms = full "reverse"
*/
-class PWMVenom : public PWMSpeedController {
+class PWMVenom : public PWMMotorController {
public:
/**
* Construct a Venom connected via PWM.
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/PWMVictorSPX.h b/wpilibc/src/main/native/include/frc/motorcontrol/PWMVictorSPX.h
new file mode 100644
index 0000000..b6bb324
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/PWMVictorSPX.h
@@ -0,0 +1,42 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+namespace frc {
+
+/**
+ * Cross the Road Electronics (CTRE) %Victor SPX Motor %Controller with PWM
+ * control.
+ *
+ * Note that the %Victor SPX uses the following bounds for PWM values. These
+ * values should work reasonably well for most controllers, but if users
+ * experience issues such as asymmetric behavior around the deadband or
+ * inability to saturate the controller in either direction, calibration is
+ * recommended. The calibration procedure can be found in the %Victor SPX User
+ * Manual available from Cross The Road Electronics.
+ *
+ * \li 2.004ms = full "forward"
+ * \li 1.520ms = the "high end" of the deadband range
+ * \li 1.500ms = center of the deadband range (off)
+ * \li 1.480ms = the "low end" of the deadband range
+ * \li 0.997ms = full "reverse"
+ */
+class PWMVictorSPX : public PWMMotorController {
+ public:
+ /**
+ * Construct a %Victor SPX connected via PWM.
+ *
+ * @param channel The PWM channel that the %Victor SPX is attached to. 0-9
+ * are on-board, 10-19 are on the MXP port
+ */
+ explicit PWMVictorSPX(int channel);
+
+ PWMVictorSPX(PWMVictorSPX&&) = default;
+ PWMVictorSPX& operator=(PWMVictorSPX&&) = default;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/SD540.h b/wpilibc/src/main/native/include/frc/motorcontrol/SD540.h
similarity index 61%
rename from wpilibc/src/main/native/include/frc/SD540.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/SD540.h
index 07f7f18..44a0c8c 100644
--- a/wpilibc/src/main/native/include/frc/SD540.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/SD540.h
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/PWMSpeedController.h"
+#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
/**
- * Mindsensors SD540 Speed Controller.
+ * Mindsensors SD540 Motor %Controller.
*
* Note that the SD540 uses the following bounds for PWM values. These values
* should work reasonably well for most controllers, but if users experience
@@ -27,7 +24,7 @@
* \li 1.44ms = the "low end" of the deadband range
* \li 0.94ms = full "reverse"
*/
-class SD540 : public PWMSpeedController {
+class SD540 : public PWMMotorController {
public:
/**
* Constructor for a SD540.
diff --git a/wpilibc/src/main/native/include/frc/Spark.h b/wpilibc/src/main/native/include/frc/motorcontrol/Spark.h
similarity index 62%
rename from wpilibc/src/main/native/include/frc/Spark.h
rename to wpilibc/src/main/native/include/frc/motorcontrol/Spark.h
index 24ed8f5..6163234 100644
--- a/wpilibc/src/main/native/include/frc/Spark.h
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/Spark.h
@@ -1,18 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include "frc/PWMSpeedController.h"
+#include "frc/motorcontrol/PWMMotorController.h"
namespace frc {
/**
- * REV Robotics SPARK Speed Controller.
+ * REV Robotics SPARK Motor %Controller.
*
* Note that the SPARK uses the following bounds for PWM values. These values
* should work reasonably well for most controllers, but if users experience
@@ -27,7 +24,7 @@
* \li 1.460ms = the "low end" of the deadband range
* \li 0.999ms = full "reverse"
*/
-class Spark : public PWMSpeedController {
+class Spark : public PWMMotorController {
public:
/**
* Constructor for a SPARK.
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/Talon.h b/wpilibc/src/main/native/include/frc/motorcontrol/Talon.h
new file mode 100644
index 0000000..acf5c55
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/Talon.h
@@ -0,0 +1,41 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+namespace frc {
+
+/**
+ * Cross the Road Electronics (CTRE) %Talon and %Talon SR Motor %Controller.
+ *
+ * Note that the %Talon uses the following bounds for PWM values. These values
+ * should work reasonably well for most controllers, but if users experience
+ * issues such as asymmetric behavior around the deadband or inability to
+ * saturate the controller in either direction, calibration is recommended.
+ * The calibration procedure can be found in the %Talon User Manual available
+ * from CTRE.
+ *
+ * \li 2.037ms = full "forward"
+ * \li 1.539ms = the "high end" of the deadband range
+ * \li 1.513ms = center of the deadband range (off)
+ * \li 1.487ms = the "low end" of the deadband range
+ * \li 0.989ms = full "reverse"
+ */
+class Talon : public PWMMotorController {
+ public:
+ /**
+ * Constructor for a %Talon (original or %Talon SR).
+ *
+ * @param channel The PWM channel number that the %Talon is attached to. 0-9
+ * are on-board, 10-19 are on the MXP port
+ */
+ explicit Talon(int channel);
+
+ Talon(Talon&&) = default;
+ Talon& operator=(Talon&&) = default;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/Victor.h b/wpilibc/src/main/native/include/frc/motorcontrol/Victor.h
new file mode 100644
index 0000000..9627925
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/Victor.h
@@ -0,0 +1,45 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+namespace frc {
+
+/**
+ * Vex Robotics %Victor 888 Motor %Controller.
+ *
+ * The Vex Robotics %Victor 884 Motor %Controller can also be used with this
+ * class but may need to be calibrated per the Victor 884 user manual.
+ *
+ * Note that the %Victor uses the following bounds for PWM values. These
+ * values were determined empirically and optimized for the %Victor 888. These
+ * values should work reasonably well for %Victor 884 controllers as well but
+ * if users experience issues such as asymmetric behavior around the deadband
+ * or inability to saturate the controller in either direction, calibration is
+ * recommended. The calibration procedure can be found in the %Victor 884 User
+ * Manual available from Vex.
+ *
+ * \li 2.027ms = full "forward"
+ * \li 1.525ms = the "high end" of the deadband range
+ * \li 1.507ms = center of the deadband range (off)
+ * \li 1.490ms = the "low end" of the deadband range
+ * \li 1.026ms = full "reverse"
+ */
+class Victor : public PWMMotorController {
+ public:
+ /**
+ * Constructor for a %Victor.
+ *
+ * @param channel The PWM channel number that the %Victor is attached to. 0-9
+ * are on-board, 10-19 are on the MXP port
+ */
+ explicit Victor(int channel);
+
+ Victor(Victor&&) = default;
+ Victor& operator=(Victor&&) = default;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/motorcontrol/VictorSP.h b/wpilibc/src/main/native/include/frc/motorcontrol/VictorSP.h
new file mode 100644
index 0000000..f599ff4
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/motorcontrol/VictorSP.h
@@ -0,0 +1,41 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/PWMMotorController.h"
+
+namespace frc {
+
+/**
+ * Vex Robotics %Victor SP Motor %Controller.
+ *
+ * Note that the %Victor SP uses the following bounds for PWM values. These
+ * values should work reasonably well for most controllers, but if users
+ * experience issues such as asymmetric behavior around the deadband or
+ * inability to saturate the controller in either direction, calibration is
+ * recommended. The calibration procedure can be found in the %Victor SP User
+ * Manual available from Vex.
+ *
+ * \li 2.004ms = full "forward"
+ * \li 1.520ms = the "high end" of the deadband range
+ * \li 1.500ms = center of the deadband range (off)
+ * \li 1.480ms = the "low end" of the deadband range
+ * \li 0.997ms = full "reverse"
+ */
+class VictorSP : public PWMMotorController {
+ public:
+ /**
+ * Constructor for a %Victor SP.
+ *
+ * @param channel The PWM channel that the Victor SP is attached to. 0-9 are
+ * on-board, 10-19 are on the MXP port
+ */
+ explicit VictorSP(int channel);
+
+ VictorSP(VictorSP&&) = default;
+ VictorSP& operator=(VictorSP&&) = default;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInLayouts.h b/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInLayouts.h
index 1d1ea5f..ca5e29f 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInLayouts.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInLayouts.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInWidgets.h b/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInWidgets.h
index df943b2..9ac315f 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInWidgets.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/BuiltInWidgets.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -163,8 +160,8 @@
*/
kVoltageView,
/**
- * Displays a PowerDistributionPanel. <br>Supported types: <ul> <li>
- * PowerDistributionPanel</li>
+ * Displays a PowerDistribution. <br>Supported types: <ul> <li>
+ * PowerDistribution</li>
* </ul>
* <br>Custom properties:
* <table>
@@ -173,7 +170,7 @@
* <td>Whether or not to display the voltage and current draw</td></tr>
* </table>
*/
- kPowerDistributionPanel,
+ kPowerDistribution,
/**
* Displays a SendableChooser with a dropdown combo box with a list of
* options.
@@ -203,10 +200,10 @@
*/
kEncoder,
/**
- * Displays a SpeedController.
- * The speed controller will be controllable from the dashboard when test mode
+ * Displays a MotorController.
+ * The motor controller will be controllable from the dashboard when test mode
* is enabled, but will otherwise be view-only. <br>Supported types: <ul>
- * <li>PWMSpeedController</li>
+ * <li>PWMMotorController</li>
* <li>DMC60</li>
* <li>Jaguar</li>
* <li>PWMTalonSRX</li>
@@ -216,7 +213,7 @@
* <li>Talon</li>
* <li>Victor</li>
* <li>VictorSP</li>
- * <li>SpeedControllerGroup</li>
+ * <li>MotorControllerGroup</li>
* <li>Any custom subclass of {@code SpeedContorller}</li>
* </ul>
* <br>Custom properties:
@@ -226,7 +223,7 @@
* <td>One of {@code ["HORIZONTAL", "VERTICAL"]}</td></tr>
* </table>
*/
- kSpeedController,
+ kMotorController,
/**
* Displays a command with a toggle button. Pressing the button will start the
* command, and the button will automatically release when the command
@@ -283,7 +280,7 @@
* <br>Custom properties:
* <table>
* <tr><th>Name</th><th>Type</th><th>Default Value</th><th>Notes</th></tr>
- * <tr><td>Range</td><td>{@link Range}</td><td>k16G</td><td>The accelerometer
+ * <tr><td>Range</td><td>Range</td><td>k16G</td><td>The accelerometer
* range</td></tr> <tr><td>Show value</td><td>Boolean</td><td>true</td>
* <td>Show or hide the acceleration values</td></tr>
* <tr><td>Precision</td><td>Number</td><td>2</td>
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ComplexWidget.h b/wpilibc/src/main/native/include/frc/shuffleboard/ComplexWidget.h
index 218ed2f..dc49d64 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ComplexWidget.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ComplexWidget.h
@@ -1,34 +1,35 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string_view>
#include <networktables/NetworkTable.h>
-#include <wpi/Twine.h>
#include "frc/shuffleboard/ShuffleboardWidget.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableBuilderImpl.h"
+
+namespace wpi {
+class Sendable;
+class SendableBuilder;
+} // namespace wpi
namespace frc {
-class Sendable;
class ShuffleboardContainer;
/**
- * A Shuffleboard widget that handles a {@link Sendable} object such as a speed
+ * A Shuffleboard widget that handles a Sendable object such as a speed
* controller or sensor.
*/
class ComplexWidget final : public ShuffleboardWidget<ComplexWidget> {
public:
- ComplexWidget(ShuffleboardContainer& parent, const wpi::Twine& title,
- Sendable& sendable);
+ ComplexWidget(ShuffleboardContainer& parent, std::string_view title,
+ wpi::Sendable& sendable);
+
+ ~ComplexWidget() override;
void EnableIfActuator() override;
@@ -38,9 +39,8 @@
std::shared_ptr<nt::NetworkTable> metaTable) override;
private:
- Sendable& m_sendable;
- SendableBuilderImpl m_builder;
- bool m_builderInit = false;
+ wpi::Sendable& m_sendable;
+ std::unique_ptr<wpi::SendableBuilder> m_builder;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h b/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h
index 00a5e36..5fa5ca4 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/StringRef.h>
+#include <string_view>
namespace frc {
@@ -28,7 +25,7 @@
* Gets the string type of the layout as defined by that layout in
* Shuffleboard.
*/
- wpi::StringRef GetLayoutName() const;
+ std::string_view GetLayoutName() const;
private:
const char* m_layoutName;
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h b/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h
index dacbdb4..83b23a4 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h
@@ -1,24 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <string>
+#include <string_view>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableInstance.h>
#include <wpi/SmallVector.h>
-#include <wpi/StringRef.h>
#include "frc/shuffleboard/ShuffleboardEventImportance.h"
-namespace frc {
-namespace detail {
+namespace frc::detail {
class RecordingController final {
public:
@@ -27,10 +23,10 @@
void StartRecording();
void StopRecording();
- void SetRecordingFileNameFormat(wpi::StringRef format);
+ void SetRecordingFileNameFormat(std::string_view format);
void ClearRecordingFileNameFormat();
- void AddEventMarker(wpi::StringRef name, wpi::StringRef description,
+ void AddEventMarker(std::string_view name, std::string_view description,
ShuffleboardEventImportance importance);
private:
@@ -39,5 +35,4 @@
std::shared_ptr<nt::NetworkTable> m_eventsTable;
};
-} // namespace detail
-} // namespace frc
+} // namespace frc::detail
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h b/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h
index 5610cf8..e7c9a81 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/SendableCameraWrapper.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -17,12 +14,12 @@
namespace cs {
class VideoSource;
} // namespace cs
-typedef int CS_Handle;
-typedef CS_Handle CS_Source;
+using CS_Handle = int; // NOLINT
+using CS_Source = CS_Handle; // NOLINT
#endif
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/sendable/Sendable.h>
+#include <wpi/sendable/SendableHelper.h>
namespace frc {
@@ -32,14 +29,15 @@
constexpr const char* kProtocol = "camera_server://";
std::shared_ptr<SendableCameraWrapper>& GetSendableCameraWrapper(
CS_Source source);
-void AddToSendableRegistry(Sendable* sendable, std::string name);
+void AddToSendableRegistry(wpi::Sendable* sendable, std::string name);
} // namespace detail
/**
* A wrapper to make video sources sendable and usable from Shuffleboard.
*/
-class SendableCameraWrapper : public Sendable,
- public SendableHelper<SendableCameraWrapper> {
+class SendableCameraWrapper
+ : public wpi::Sendable,
+ public wpi::SendableHelper<SendableCameraWrapper> {
private:
struct private_init {};
@@ -63,7 +61,7 @@
static SendableCameraWrapper& Wrap(const cs::VideoSource& source);
static SendableCameraWrapper& Wrap(CS_Source source);
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
private:
std::string m_uri;
@@ -86,8 +84,9 @@
inline SendableCameraWrapper& SendableCameraWrapper::Wrap(CS_Source source) {
auto& wrapper = detail::GetSendableCameraWrapper(source);
- if (!wrapper)
+ if (!wrapper) {
wrapper = std::make_shared<SendableCameraWrapper>(source, private_init{});
+ }
return *wrapper;
}
#endif
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h b/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h
index e49d1c3..252d74a 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/StringRef.h>
+#include <string_view>
#include "frc/shuffleboard/RecordingController.h"
#include "frc/shuffleboard/ShuffleboardEventImportance.h"
@@ -80,7 +77,7 @@
* @param title the title of the tab
* @return the tab with the given title
*/
- static ShuffleboardTab& GetTab(wpi::StringRef title);
+ static ShuffleboardTab& GetTab(std::string_view title);
/**
* Selects the tab in the dashboard with the given index in the range
@@ -96,10 +93,10 @@
*
* @param title the title of the tab to select
*/
- static void SelectTab(wpi::StringRef title);
+ static void SelectTab(std::string_view title);
/**
- * Enables user control of widgets containing actuators: speed controllers,
+ * Enables user control of widgets containing actuators: motor controllers,
* relays, etc. This should only be used when the robot is in test mode.
* IterativeRobotBase and SampleRobot are both configured to call this method
* when entering test mode; most users should not need to use this method
@@ -144,13 +141,13 @@
*
* @param format the format for the
*/
- static void SetRecordingFileNameFormat(wpi::StringRef format);
+ static void SetRecordingFileNameFormat(std::string_view format);
/**
* Clears the custom name format for recording files. New recordings will use
* the default format.
*
- * @see #setRecordingFileNameFormat(String)
+ * @see SetRecordingFileNameFormat(std::string_view)
*/
static void ClearRecordingFileNameFormat();
@@ -166,7 +163,8 @@
* @param description a description of the event
* @param importance the importance of the event
*/
- static void AddEventMarker(wpi::StringRef name, wpi::StringRef description,
+ static void AddEventMarker(std::string_view name,
+ std::string_view description,
ShuffleboardEventImportance importance);
/**
@@ -180,7 +178,7 @@
* @param name the name of the event
* @param importance the importance of the event
*/
- static void AddEventMarker(wpi::StringRef name,
+ static void AddEventMarker(std::string_view name,
ShuffleboardEventImportance importance);
private:
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h
index d6b4bc4..24f65a3 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.h
@@ -1,19 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <string>
+#include <string_view>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableValue.h>
#include <wpi/StringMap.h>
-#include <wpi/Twine.h>
#include "frc/shuffleboard/ShuffleboardComponentBase.h"
@@ -29,10 +26,8 @@
template <typename Derived>
class ShuffleboardComponent : public ShuffleboardComponentBase {
public:
- ShuffleboardComponent(ShuffleboardContainer& parent, const wpi::Twine& title,
- const wpi::Twine& type = "");
-
- virtual ~ShuffleboardComponent() = default;
+ ShuffleboardComponent(ShuffleboardContainer& parent, std::string_view title,
+ std::string_view type = "");
/**
* Sets custom properties for this component. Property names are
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc
index f75fb0d..9750d4a 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponent.inc
@@ -1,21 +1,21 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <string>
+#include <string_view>
+
+#include "frc/shuffleboard/ShuffleboardComponent.h"
namespace frc {
template <typename Derived>
ShuffleboardComponent<Derived>::ShuffleboardComponent(
- ShuffleboardContainer& parent, const wpi::Twine& title,
- const wpi::Twine& type)
+ ShuffleboardContainer& parent, std::string_view title,
+ std::string_view type)
: ShuffleboardValue(title),
ShuffleboardComponentBase(parent, title, type) {}
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponentBase.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponentBase.h
index c63e517..d33a234 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponentBase.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardComponentBase.h
@@ -1,19 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <string>
+#include <string_view>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableValue.h>
#include <wpi/StringMap.h>
-#include <wpi/Twine.h>
#include "frc/shuffleboard/ShuffleboardValue.h"
@@ -27,12 +24,9 @@
class ShuffleboardComponentBase : public virtual ShuffleboardValue {
public:
ShuffleboardComponentBase(ShuffleboardContainer& parent,
- const wpi::Twine& title,
- const wpi::Twine& type = "");
+ std::string_view title, std::string_view type = "");
- virtual ~ShuffleboardComponentBase() = default;
-
- void SetType(const wpi::Twine& type);
+ void SetType(std::string_view type);
void BuildMetadata(std::shared_ptr<nt::NetworkTable> metaTable);
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardContainer.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardContainer.h
index 7b8b49d..db58a21 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardContainer.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardContainer.h
@@ -1,26 +1,21 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
#include <memory>
#include <string>
+#include <string_view>
#include <vector>
#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableValue.h>
-#include <wpi/ArrayRef.h>
#include <wpi/SmallSet.h>
#include <wpi/StringMap.h>
-#include <wpi/Twine.h>
+#include <wpi/span.h>
-#include "frc/ErrorBase.h"
-#include "frc/WPIErrors.h"
#include "frc/shuffleboard/BuiltInLayouts.h"
#include "frc/shuffleboard/LayoutType.h"
#include "frc/shuffleboard/ShuffleboardComponentBase.h"
@@ -31,24 +26,26 @@
class VideoSource;
} // namespace cs
+namespace wpi {
+class Sendable;
+} // namespace wpi
+
namespace frc {
class ComplexWidget;
-class Sendable;
class ShuffleboardLayout;
class SimpleWidget;
/**
* Common interface for objects that can contain shuffleboard components.
*/
-class ShuffleboardContainer : public virtual ShuffleboardValue,
- public ErrorBase {
+class ShuffleboardContainer : public virtual ShuffleboardValue {
public:
- explicit ShuffleboardContainer(const wpi::Twine& title);
+ explicit ShuffleboardContainer(std::string_view title);
ShuffleboardContainer(ShuffleboardContainer&& rhs) = default;
- virtual ~ShuffleboardContainer() = default;
+ ~ShuffleboardContainer() override = default;
/**
* Gets the components that are direct children of this container.
@@ -60,38 +57,36 @@
* Gets the layout with the given type and title, creating it if it does not
* already exist at the time this method is called.
*
- * @param title the title of the layout
- * @param layoutType the type of the layout, eg "List" or "Grid"
+ * @param title the title of the layout
+ * @param type the type of the layout, eg "List" or "Grid"
* @return the layout
*/
- ShuffleboardLayout& GetLayout(const wpi::Twine& title, BuiltInLayouts type);
+ ShuffleboardLayout& GetLayout(std::string_view title, BuiltInLayouts type);
/**
* Gets the layout with the given type and title, creating it if it does not
* already exist at the time this method is called.
*
- * @param title the title of the layout
- * @param layoutType the type of the layout, eg "List" or "Grid"
+ * @param title the title of the layout
+ * @param type the type of the layout, eg "List" or "Grid"
* @return the layout
*/
- ShuffleboardLayout& GetLayout(const wpi::Twine& title,
- const LayoutType& type);
+ ShuffleboardLayout& GetLayout(std::string_view title, const LayoutType& type);
/**
* Gets the layout with the given type and title, creating it if it does not
* already exist at the time this method is called. Note: this method should
* only be used to use a layout type that is not already built into
* Shuffleboard. To use a layout built into Shuffleboard, use
- * {@link #GetLayout(String, LayoutType)} and the layouts in {@link
- * BuiltInLayouts}.
+ * GetLayout(std::string_view, const LayoutType&) and the layouts in
+ * BuiltInLayouts.
*
* @param title the title of the layout
* @param type the type of the layout, eg "List Layout" or "Grid Layout"
* @return the layout
- * @see #GetLayout(String, LayoutType)
+ * @see GetLayout(std::string_view, const LayoutType&)
*/
- ShuffleboardLayout& GetLayout(const wpi::Twine& title,
- const wpi::Twine& type);
+ ShuffleboardLayout& GetLayout(std::string_view title, std::string_view type);
/**
* Gets the already-defined layout in this container with the given title.
@@ -108,7 +103,7 @@
* @return the layout with the given title
* @throws if no layout has yet been defined with the given title
*/
- ShuffleboardLayout& GetLayout(const wpi::Twine& title);
+ ShuffleboardLayout& GetLayout(std::string_view title);
/**
* Adds a widget to this container to display the given sendable.
@@ -119,7 +114,7 @@
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
*/
- ComplexWidget& Add(const wpi::Twine& title, Sendable& sendable);
+ ComplexWidget& Add(std::string_view title, wpi::Sendable& sendable);
/**
* Adds a widget to this container to display the given video stream.
@@ -130,7 +125,7 @@
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
*/
- ComplexWidget& Add(const wpi::Twine& title, const cs::VideoSource& video);
+ ComplexWidget& Add(std::string_view title, const cs::VideoSource& video);
/**
* Adds a widget to this container to display the given sendable.
@@ -141,7 +136,7 @@
* container with the given title, or if the sendable's name has not been
* specified
*/
- ComplexWidget& Add(Sendable& sendable);
+ ComplexWidget& Add(wpi::Sendable& sendable);
/**
* Adds a widget to this container to display the given video stream.
@@ -161,9 +156,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, std::shared_ptr<nt::Value>)
+ * Add(std::string_view title, std::shared_ptr<nt::Value> defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title,
+ SimpleWidget& Add(std::string_view title,
std::shared_ptr<nt::Value> defaultValue);
/**
@@ -174,9 +170,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, bool)
+ * Add(std::string_view title, bool defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title, bool defaultValue);
+ SimpleWidget& Add(std::string_view title, bool defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -186,9 +183,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, double)
+ * Add(std::string_view title, double defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title, double defaultValue);
+ SimpleWidget& Add(std::string_view title, double defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -198,9 +196,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, int)
+ * Add(std::string_view title, int defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title, int defaultValue);
+ SimpleWidget& Add(std::string_view title, int defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -210,9 +209,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, std::string_view)
+ * Add(std::string_view title, std::string_view defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title, const wpi::Twine& defaultValue);
+ SimpleWidget& Add(std::string_view title, std::string_view defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -222,9 +222,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, const char*)
+ * Add(std::string_view title, const char* defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title, const char* defaultValue);
+ SimpleWidget& Add(std::string_view title, const char* defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -234,9 +235,10 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, wpi::span<const bool>)
+ * Add(std::string_view title, wpi::span<const bool> defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title, wpi::ArrayRef<bool> defaultValue);
+ SimpleWidget& Add(std::string_view title, wpi::span<const bool> defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -246,10 +248,11 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, wpi::span<const double>)
+ * Add(std::string_view title, wpi::span<const double> defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title,
- wpi::ArrayRef<double> defaultValue);
+ SimpleWidget& Add(std::string_view title,
+ wpi::span<const double> defaultValue);
/**
* Adds a widget to this container to display the given data.
@@ -259,10 +262,11 @@
* @return a widget to display the sendable data
* @throws IllegalArgumentException if a widget already exists in this
* container with the given title
- * @see #addPersistent(String, Object) add(String title, Object defaultValue)
+ * @see AddPersistent(std::string_view, wpi::span<const std::string>)
+ * Add(std::string_view title, wpi::span<const std::string> defaultValue)
*/
- SimpleWidget& Add(const wpi::Twine& title,
- wpi::ArrayRef<std::string> defaultValue);
+ SimpleWidget& Add(std::string_view title,
+ wpi::span<const std::string> defaultValue);
/**
* Adds a widget to this container. The widget will display the data provided
@@ -271,11 +275,11 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
SuppliedValueWidget<std::string>& AddString(
- const wpi::Twine& title, std::function<std::string()> supplier);
+ std::string_view title, std::function<std::string()> supplier);
/**
* Adds a widget to this container. The widget will display the data provided
@@ -284,10 +288,10 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
- SuppliedValueWidget<double>& AddNumber(const wpi::Twine& title,
+ SuppliedValueWidget<double>& AddNumber(std::string_view title,
std::function<double()> supplier);
/**
@@ -297,10 +301,10 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
- SuppliedValueWidget<bool>& AddBoolean(const wpi::Twine& title,
+ SuppliedValueWidget<bool>& AddBoolean(std::string_view title,
std::function<bool()> supplier);
/**
@@ -310,11 +314,11 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
SuppliedValueWidget<std::vector<std::string>>& AddStringArray(
- const wpi::Twine& title,
+ std::string_view title,
std::function<std::vector<std::string>()> supplier);
/**
@@ -324,11 +328,11 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
SuppliedValueWidget<std::vector<double>>& AddNumberArray(
- const wpi::Twine& title, std::function<std::vector<double>()> supplier);
+ std::string_view title, std::function<std::vector<double>()> supplier);
/**
* Adds a widget to this container. The widget will display the data provided
@@ -337,11 +341,11 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
SuppliedValueWidget<std::vector<int>>& AddBooleanArray(
- const wpi::Twine& title, std::function<std::vector<int>()> supplier);
+ std::string_view title, std::function<std::vector<int>()> supplier);
/**
* Adds a widget to this container. The widget will display the data provided
@@ -350,128 +354,136 @@
* supplier.
*
* @param title the title of the widget
- * @param valueSupplier the supplier for values
+ * @param supplier the supplier for values
* @return a widget to display data
*/
- SuppliedValueWidget<wpi::StringRef>& AddRaw(
- const wpi::Twine& title, std::function<wpi::StringRef()> supplier);
+ SuppliedValueWidget<std::string_view>& AddRaw(
+ std::string_view title, std::function<std::string_view()> supplier);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
- * on the robot and will be used when the robot program next starts rather
- * than {@code defaultValue}.
+ * Unlike Add(std::string_view, std::shared_ptr<nt::Value>), the value in the
+ * widget will be saved on the robot and will be used when the robot program
+ * next starts rather than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(stdd::string_view, std::shared_ptr<nt::Value>)
+ * Add(std::string_view title, std::shared_ptr<nt::Value> defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title,
+ SimpleWidget& AddPersistent(std::string_view title,
std::shared_ptr<nt::Value> defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
+ * Unlike Add(std::string_view, bool), the value in the widget will be saved
* on the robot and will be used when the robot program next starts rather
* than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std::string_view, bool)
+ * Add(std::string_view title, bool defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title, bool defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title, bool defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
+ * Unlike Add(std::string_view, double), the value in the widget will be saved
* on the robot and will be used when the robot program next starts rather
* than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std::string_view, double)
+ * Add(std::string_view title, double defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title, double defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title, double defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
- * on the robot and will be used when the robot program next starts rather
- * than {@code defaultValue}.
+ * Unlike Add(std::string_view, int), the value in the widget will be saved on
+ * the robot and will be used when the robot program next starts rather than
+ * {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std:string_view, int)
+ * Add(std::string_view title, int defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title, int defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title, int defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
- * on the robot and will be used when the robot program next starts rather
- * than {@code defaultValue}.
+ * Unlike Add(std::string_view, std::string_view), the value in the widget
+ * will be saved on the robot and will be used when the robot program next
+ * starts rather than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std::string_view, std::string_view)
+ * Add(std::string_view title, std::string_view defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title,
- const wpi::Twine& defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title,
+ std::string_view defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
- * on the robot and will be used when the robot program next starts rather
- * than {@code defaultValue}.
+ * Unlike Add(std::string_view, wpi::span<const bool>), the value in the
+ * widget will be saved on the robot and will be used when the robot program
+ * next starts rather than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std::string_view, wpi::span<const bool>)
+ * Add(std::string_view title, wpi::span<const bool> defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title,
- wpi::ArrayRef<bool> defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title,
+ wpi::span<const bool> defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
- * on the robot and will be used when the robot program next starts rather
- * than {@code defaultValue}.
+ * Unlike Add(std::string_view, wpi::span<const double>), the value in the
+ * widget will be saved on the robot and will be used when the robot program
+ * next starts rather than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std::string_view, wpi::span<const double>)
+ * Add(std::string_view title, wpi::span<const double> defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title,
- wpi::ArrayRef<double> defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title,
+ wpi::span<const double> defaultValue);
/**
* Adds a widget to this container to display a simple piece of data.
*
- * Unlike {@link #add(String, Object)}, the value in the widget will be saved
- * on the robot and will be used when the robot program next starts rather
- * than {@code defaultValue}.
+ * Unlike Add(std::string_view, wpi::span<const std::string>), the value in
+ * the widget will be saved on the robot and will be used when the robot
+ * program next starts rather than {@code defaultValue}.
*
* @param title the title of the widget
* @param defaultValue the default value of the widget
* @return a widget to display the sendable data
- * @see #add(String, Object) add(String title, Object defaultValue)
+ * @see Add(std::string_view, wpi::span<const std::string>)
+ * Add(std::string_view title, wpi::span<const std::string> defaultValue)
*/
- SimpleWidget& AddPersistent(const wpi::Twine& title,
- wpi::ArrayRef<std::string> defaultValue);
+ SimpleWidget& AddPersistent(std::string_view title,
+ wpi::span<const std::string> defaultValue);
void EnableIfActuator() override;
@@ -490,7 +502,7 @@
*
* @return True if title isn't in use; false otherwise.
*/
- void CheckTitle(const wpi::Twine& title);
+ void CheckTitle(std::string_view title);
friend class SimpleWidget;
};
@@ -511,7 +523,7 @@
}
inline frc::ComplexWidget& frc::ShuffleboardContainer::Add(
- const wpi::Twine& title, const cs::VideoSource& video) {
+ std::string_view title, const cs::VideoSource& video) {
return Add(title, frc::SendableCameraWrapper::Wrap(video));
}
#endif
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h
index 57e4743..1fa9c91 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/StringRef.h>
+#include <string_view>
namespace frc {
@@ -17,7 +14,7 @@
enum ShuffleboardEventImportance { kTrivial, kLow, kNormal, kHigh, kCritical };
-inline wpi::StringRef ShuffleboardEventImportanceName(
+inline std::string_view ShuffleboardEventImportanceName(
ShuffleboardEventImportance importance) {
switch (importance) {
case kTrivial:
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h
index 2be9859..2885af7 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h
@@ -1,19 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string_view>
#include "frc/shuffleboard/ShuffleboardRoot.h"
#include "frc/shuffleboard/ShuffleboardTab.h"
-namespace frc {
-namespace detail {
+namespace frc::detail {
class ShuffleboardInstance final : public ShuffleboardRoot {
public:
@@ -23,7 +20,7 @@
ShuffleboardInstance(ShuffleboardInstance&&) = default;
ShuffleboardInstance& operator=(ShuffleboardInstance&&) = default;
- frc::ShuffleboardTab& GetTab(wpi::StringRef title) override;
+ frc::ShuffleboardTab& GetTab(std::string_view title) override;
void Update() override;
@@ -33,12 +30,11 @@
void SelectTab(int index) override;
- void SelectTab(wpi::StringRef) override;
+ void SelectTab(std::string_view) override;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
-} // namespace detail
-} // namespace frc
+} // namespace frc::detail
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardLayout.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardLayout.h
index effa3da..fe9e102 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardLayout.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardLayout.h
@@ -1,16 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string_view>
#include <networktables/NetworkTable.h>
-#include <wpi/Twine.h>
#include "frc/shuffleboard/ShuffleboardComponent.h"
#include "frc/shuffleboard/ShuffleboardContainer.h"
@@ -29,8 +26,8 @@
class ShuffleboardLayout : public ShuffleboardComponent<ShuffleboardLayout>,
public ShuffleboardContainer {
public:
- ShuffleboardLayout(ShuffleboardContainer& parent, const wpi::Twine& name,
- const wpi::Twine& type);
+ ShuffleboardLayout(ShuffleboardContainer& parent, std::string_view name,
+ std::string_view type);
void BuildInto(std::shared_ptr<nt::NetworkTable> parentTable,
std::shared_ptr<nt::NetworkTable> metaTable) override;
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h
index 0c50545..1e766a8 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/StringRef.h>
+#include <string_view>
namespace frc {
@@ -28,7 +25,7 @@
* @param title the title of the tab
* @return the tab with the given title
*/
- virtual ShuffleboardTab& GetTab(wpi::StringRef title) = 0;
+ virtual ShuffleboardTab& GetTab(std::string_view title) = 0;
/**
* Updates all tabs.
@@ -60,7 +57,7 @@
*
* @param title the title of the tab to select
*/
- virtual void SelectTab(wpi::StringRef title) = 0;
+ virtual void SelectTab(std::string_view title) = 0;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h
index 75896ae..8864cdb 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h
@@ -1,16 +1,13 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string_view>
#include <networktables/NetworkTable.h>
-#include <wpi/StringRef.h>
#include "frc/shuffleboard/ShuffleboardContainer.h"
@@ -20,14 +17,15 @@
/**
* Represents a tab in the Shuffleboard dashboard. Widgets can be added to the
- * tab with {@link #add(Sendable)}, {@link #add(String, Object)}, and
- * {@link #add(String, Sendable)}. Widgets can also be added to layouts with
- * {@link #getLayout(String, String)}; layouts can be nested arbitrarily deep
- * (note that too many levels may make deeper components unusable).
+ * tab with Add(Sendable), Add(std::string_view, Object), and
+ * Add(String, Sendable). Widgets can also be added to layouts with
+ * GetLayout(std::string_view, std::string_view); layouts can be nested
+ * arbitrarily deep (note that too many levels may make deeper components
+ * unusable).
*/
class ShuffleboardTab final : public ShuffleboardContainer {
public:
- ShuffleboardTab(ShuffleboardRoot& root, wpi::StringRef title);
+ ShuffleboardTab(ShuffleboardRoot& root, std::string_view title);
ShuffleboardRoot& GetRoot();
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardValue.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardValue.h
index 4a88cc1..4b7ccd4 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardValue.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardValue.h
@@ -1,34 +1,30 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <string>
+#include <string_view>
#include <networktables/NetworkTable.h>
-#include <wpi/SmallVector.h>
-#include <wpi/StringRef.h>
namespace frc {
class ShuffleboardValue {
public:
- explicit ShuffleboardValue(const wpi::Twine& title) {
- wpi::SmallVector<char, 16> storage;
- m_title = title.toStringRef(storage);
- }
+ explicit ShuffleboardValue(std::string_view title) : m_title(title) {}
virtual ~ShuffleboardValue() = default;
+ ShuffleboardValue(const ShuffleboardValue&) = delete;
+ ShuffleboardValue& operator=(const ShuffleboardValue&) = delete;
+
/**
* Gets the title of this Shuffleboard value.
*/
- wpi::StringRef GetTitle() const { return m_title; }
+ const std::string& GetTitle() const { return m_title; }
/**
* Builds the entries for this value.
@@ -51,7 +47,7 @@
*
* This method is package-private to prevent users from enabling control
* themselves. Has no effect if the sendable is not marked as an actuator with
- * {@link SendableBuilder#setActuator}.
+ * SendableBuilder::SetActuator().
*/
virtual void EnableIfActuator() {}
@@ -60,7 +56,7 @@
*
* This method is package-private to prevent users from enabling control
* themselves. Has no effect if the sendable is not marked as an actuator with
- * {@link SendableBuilder#setActuator}.
+ * SendableBuilder::SetActuator().
*/
virtual void DisableIfActuator() {}
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardWidget.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardWidget.h
index 729da40..ce01367 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardWidget.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardWidget.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/Twine.h>
+#include <string_view>
#include "frc/shuffleboard/BuiltInWidgets.h"
#include "frc/shuffleboard/ShuffleboardComponent.h"
@@ -31,7 +28,7 @@
template <typename Derived>
class ShuffleboardWidget : public ShuffleboardComponent<Derived> {
public:
- ShuffleboardWidget(ShuffleboardContainer& parent, const wpi::Twine& title)
+ ShuffleboardWidget(ShuffleboardContainer& parent, std::string_view title)
: ShuffleboardValue(title),
ShuffleboardComponent<Derived>(parent, title) {}
@@ -63,13 +60,12 @@
* widget type will be used. This method should only be used to use a widget
* that does not come built into Shuffleboard (i.e. one that comes with a
* custom or third-party plugin). To use a widget that is built into
- * Shuffleboard, use {@link #withWidget(WidgetType)} and {@link
- * BuiltInWidgets}.
+ * Shuffleboard, use WithWidget(WidgetType) and BuiltInWidgets.
*
* @param widgetType the type of the widget used to display the data
* @return this widget object
*/
- Derived& WithWidget(const wpi::Twine& widgetType) {
+ Derived& WithWidget(std::string_view widgetType) {
this->SetType(widgetType);
return *static_cast<Derived*>(this);
}
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/SimpleWidget.h b/wpilibc/src/main/native/include/frc/shuffleboard/SimpleWidget.h
index 973f8cb..746b7d6 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/SimpleWidget.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/SimpleWidget.h
@@ -1,17 +1,14 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string_view>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableEntry.h>
-#include <wpi/Twine.h>
#include "frc/shuffleboard/ShuffleboardWidget.h"
@@ -25,7 +22,7 @@
*/
class SimpleWidget final : public ShuffleboardWidget<SimpleWidget> {
public:
- SimpleWidget(ShuffleboardContainer& parent, const wpi::Twine& title);
+ SimpleWidget(ShuffleboardContainer& parent, std::string_view title);
/**
* Gets the NetworkTable entry that contains the data for this widget.
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h b/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h
index c806db4..a2b042e 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/SuppliedValueWidget.h
@@ -1,34 +1,32 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
#include <memory>
+#include <string_view>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableEntry.h>
-#include <wpi/Twine.h>
#include "frc/shuffleboard/ShuffleboardComponent.h"
#include "frc/shuffleboard/ShuffleboardComponent.inc"
#include "frc/shuffleboard/ShuffleboardComponentBase.h"
-#include "frc/shuffleboard/ShuffleboardContainer.h"
#include "frc/shuffleboard/ShuffleboardWidget.h"
namespace frc {
+class ShuffleboardContainer;
+
template <typename T>
-class SuppliedValueWidget : public ShuffleboardWidget<SuppliedValueWidget<T> > {
+class SuppliedValueWidget : public ShuffleboardWidget<SuppliedValueWidget<T>> {
public:
- SuppliedValueWidget(ShuffleboardContainer& parent, const wpi::Twine& title,
+ SuppliedValueWidget(ShuffleboardContainer& parent, std::string_view title,
std::function<T()> supplier,
std::function<void(nt::NetworkTableEntry, T)> setter)
: ShuffleboardValue(title),
- ShuffleboardWidget<SuppliedValueWidget<T> >(parent, title),
+ ShuffleboardWidget<SuppliedValueWidget<T>>(parent, title),
m_supplier(supplier),
m_setter(setter) {}
diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h b/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h
index ff92fe7..13805bb 100644
--- a/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h
+++ b/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/StringRef.h>
+#include <string_view>
namespace frc {
@@ -28,7 +25,7 @@
* Gets the string type of the widget as defined by that widget in
* Shuffleboard.
*/
- wpi::StringRef GetWidgetName() const;
+ std::string_view GetWidgetName() const;
private:
const char* m_widgetName;
diff --git a/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h b/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h
new file mode 100644
index 0000000..af96b39
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/ADXL345Sim.h
@@ -0,0 +1,63 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <hal/SimDevice.h>
+
+namespace frc {
+
+class ADXL345_SPI;
+class ADXL345_I2C;
+
+namespace sim {
+
+/**
+ * Class to control a simulated ADXRS450 gyroscope.
+ */
+class ADXL345Sim {
+ public:
+ /**
+ * Constructs from a ADXL345_I2C object.
+ *
+ * @param accel ADXL345 accel to simulate
+ */
+ explicit ADXL345Sim(const ADXL345_I2C& accel);
+
+ /**
+ * Constructs from a ADXL345_SPI object.
+ *
+ * @param accel ADXL345 accel to simulate
+ */
+ explicit ADXL345Sim(const ADXL345_SPI& accel);
+
+ /**
+ * Sets the X acceleration.
+ *
+ * @param accel The X acceleration.
+ */
+ void SetX(double accel);
+
+ /**
+ * Sets the Y acceleration.
+ *
+ * @param accel The Y acceleration.
+ */
+ void SetY(double accel);
+
+ /**
+ * Sets the Z acceleration.
+ *
+ * @param accel The Z acceleration.
+ */
+ void SetZ(double accel);
+
+ private:
+ hal::SimDouble m_simX;
+ hal::SimDouble m_simY;
+ hal::SimDouble m_simZ;
+};
+
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h b/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h
new file mode 100644
index 0000000..269732b
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/ADXL362Sim.h
@@ -0,0 +1,55 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <hal/SimDevice.h>
+
+namespace frc {
+
+class ADXL362;
+
+namespace sim {
+
+/**
+ * Class to control a simulated ADXRS450 gyroscope.
+ */
+class ADXL362Sim {
+ public:
+ /**
+ * Constructs from a ADXL362 object.
+ *
+ * @param accel ADXL362 accel to simulate
+ */
+ explicit ADXL362Sim(const ADXL362& accel);
+
+ /**
+ * Sets the X acceleration.
+ *
+ * @param accel The X acceleration.
+ */
+ void SetX(double accel);
+
+ /**
+ * Sets the Y acceleration.
+ *
+ * @param accel The Y acceleration.
+ */
+ void SetY(double accel);
+
+ /**
+ * Sets the Z acceleration.
+ *
+ * @param accel The Z acceleration.
+ */
+ void SetZ(double accel);
+
+ private:
+ hal::SimDouble m_simX;
+ hal::SimDouble m_simY;
+ hal::SimDouble m_simZ;
+};
+
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/ADXRS450_GyroSim.h b/wpilibc/src/main/native/include/frc/simulation/ADXRS450_GyroSim.h
index 1d2d2c3..4cb4737 100644
--- a/wpilibc/src/main/native/include/frc/simulation/ADXRS450_GyroSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/ADXRS450_GyroSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/simulation/AddressableLEDSim.h b/wpilibc/src/main/native/include/frc/simulation/AddressableLEDSim.h
index 0c578f4..4533086 100644
--- a/wpilibc/src/main/native/include/frc/simulation/AddressableLEDSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/AddressableLEDSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -55,39 +52,131 @@
*/
static AddressableLEDSim CreateForIndex(int index);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback on the Initialized property.
+ *
+ * @param callback the callback that will be called whenever the Initialized
+ * property is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object storing this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Change the Initialized value of the LED strip.
+ *
+ * @param initialized the new value
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterOutputPortCallback(
+ /**
+ * Register a callback on the output port.
+ *
+ * @param callback the callback that will be called whenever the output port
+ * is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterOutputPortCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the output port.
+ *
+ * @return the output port
+ */
int GetOutputPort() const;
+ /**
+ * Change the output port.
+ *
+ * @param outputPort the new output port
+ */
void SetOutputPort(int outputPort);
- std::unique_ptr<CallbackStore> RegisterLengthCallback(NotifyCallback callback,
- bool initialNotify);
-
- int GetLength() const;
-
- void SetLength(int length);
-
- std::unique_ptr<CallbackStore> RegisterRunningCallback(
+ /**
+ * Register a callback on the length.
+ *
+ * @param callback the callback that will be called whenever the length is
+ * changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterLengthCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the length of the LED strip.
+ *
+ * @return the length
+ */
+ int GetLength() const;
+
+ /**
+ * Change the length of the LED strip.
+ *
+ * @param length the new value
+ */
+ void SetLength(int length);
+
+ /**
+ * Register a callback on whether the LEDs are running.
+ *
+ * @param callback the callback that will be called whenever the LED state is
+ * changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterRunningCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check if the LEDs are running.
+ *
+ * @return true if they are
+ */
int GetRunning() const;
+ /**
+ * Change whether the LEDs are active.
+ *
+ * @param running the new value
+ */
void SetRunning(bool running);
- std::unique_ptr<CallbackStore> RegisterDataCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback on the LED data.
+ *
+ * @param callback the callback that will be called whenever the LED data is
+ * changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterDataCallback(
+ ConstBufferCallback callback, bool initialNotify);
+ /**
+ * Get the LED data.
+ *
+ * @param data output parameter to fill with LED data
+ * @return the length of the LED data
+ */
int GetData(struct HAL_AddressableLEDData* data) const;
+ /**
+ * Change the LED data.
+ *
+ * @param data the new data
+ * @param length the length of the LED data
+ */
void SetData(struct HAL_AddressableLEDData* data, int length);
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/AnalogEncoderSim.h b/wpilibc/src/main/native/include/frc/simulation/AnalogEncoderSim.h
index aef979a..6d76326 100644
--- a/wpilibc/src/main/native/include/frc/simulation/AnalogEncoderSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/AnalogEncoderSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -31,7 +28,7 @@
explicit AnalogEncoderSim(const AnalogEncoder& encoder);
/**
- * Set the position using an {@link Rotation2d}.
+ * Set the position using an Rotation2d.
*
* @param angle The angle.
*/
@@ -50,7 +47,7 @@
units::turn_t GetTurns();
/**
- * Get the position as a {@link Rotation2d}.
+ * Get the position as a Rotation2d.
*/
Rotation2d GetPosition();
diff --git a/wpilibc/src/main/native/include/frc/simulation/AnalogGyroSim.h b/wpilibc/src/main/native/include/frc/simulation/AnalogGyroSim.h
index 685e3ed..faa11d7 100644
--- a/wpilibc/src/main/native/include/frc/simulation/AnalogGyroSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/AnalogGyroSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -36,27 +33,82 @@
*/
explicit AnalogGyroSim(int channel);
- std::unique_ptr<CallbackStore> RegisterAngleCallback(NotifyCallback callback,
- bool initialNotify);
-
- double GetAngle() const;
-
- void SetAngle(double angle);
-
- std::unique_ptr<CallbackStore> RegisterRateCallback(NotifyCallback callback,
- bool initialNotify);
-
- double GetRate() const;
-
- void SetRate(double rate);
-
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback on the angle.
+ *
+ * @param callback the callback that will be called whenever the angle changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterAngleCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the current angle of the gyro.
+ *
+ * @return the angle measured by the gyro
+ */
+ double GetAngle() const;
+
+ /**
+ * Change the angle measured by the gyro.
+ *
+ * @param angle the new value
+ */
+ void SetAngle(double angle);
+
+ /**
+ * Register a callback on the rate.
+ *
+ * @param callback the callback that will be called whenever the rate changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterRateCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Get the rate of angle change on this gyro.
+ *
+ * @return the rate
+ */
+ double GetRate() const;
+
+ /**
+ * Change the rate of the gyro.
+ *
+ * @param rate the new rate
+ */
+ void SetRate(double rate);
+
+ /**
+ * Register a callback on whether the gyro is initialized.
+ *
+ * @param callback the callback that will be called whenever the gyro is
+ * initialized
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check if the gyro is initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Set whether this gyro is initialized.
+ *
+ * @param initialized the new value
+ */
void SetInitialized(bool initialized);
+ /**
+ * Reset all simulation data for this object.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/AnalogInputSim.h b/wpilibc/src/main/native/include/frc/simulation/AnalogInputSim.h
index a52cec4..03d7548 100644
--- a/wpilibc/src/main/native/include/frc/simulation/AnalogInputSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/AnalogInputSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -36,69 +33,237 @@
*/
explicit AnalogInputSim(int channel);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback on whether the analog input is initialized.
+ *
+ * @param callback the callback that will be called whenever the analog input
+ * is initialized
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if this analog input has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Change whether this analog input has been initialized.
+ *
+ * @param initialized the new value
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterAverageBitsCallback(
+ /**
+ * Register a callback on the number of average bits.
+ *
+ * @param callback the callback that will be called whenever the number of
+ * average bits is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterAverageBitsCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the number of average bits.
+ *
+ * @return the number of average bits
+ */
int GetAverageBits() const;
+ /**
+ * Change the number of average bits.
+ *
+ * @param averageBits the new value
+ */
void SetAverageBits(int averageBits);
- std::unique_ptr<CallbackStore> RegisterOversampleBitsCallback(
+ /**
+ * Register a callback on the amount of oversampling bits.
+ *
+ * @param callback the callback that will be called whenever the oversampling
+ * bits are changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterOversampleBitsCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the amount of oversampling bits.
+ *
+ * @return the amount of oversampling bits
+ */
int GetOversampleBits() const;
+ /**
+ * Change the amount of oversampling bits.
+ *
+ * @param oversampleBits the new value
+ */
void SetOversampleBits(int oversampleBits);
- std::unique_ptr<CallbackStore> RegisterVoltageCallback(
+ /**
+ * Register a callback on the voltage.
+ *
+ * @param callback the callback that will be called whenever the voltage is
+ * changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterVoltageCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the voltage.
+ *
+ * @return the voltage
+ */
double GetVoltage() const;
+ /**
+ * Change the voltage.
+ *
+ * @param voltage the new value
+ */
void SetVoltage(double voltage);
- std::unique_ptr<CallbackStore> RegisterAccumulatorInitializedCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on whether the accumulator is initialized.
+ *
+ * @param callback the callback that will be called whenever the accumulator
+ * is initialized
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterAccumulatorInitializedCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Check if the accumulator has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetAccumulatorInitialized() const;
+ /**
+ * Change whether the accumulator has been initialized.
+ *
+ * @param accumulatorInitialized the new value
+ */
void SetAccumulatorInitialized(bool accumulatorInitialized);
- std::unique_ptr<CallbackStore> RegisterAccumulatorValueCallback(
+ /**
+ * Register a callback on the accumulator value.
+ *
+ * @param callback the callback that will be called whenever the accumulator
+ * value is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterAccumulatorValueCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the accumulator value.
+ *
+ * @return the accumulator value
+ */
int64_t GetAccumulatorValue() const;
+ /**
+ * Change the accumulator value.
+ *
+ * @param accumulatorValue the new value
+ */
void SetAccumulatorValue(int64_t accumulatorValue);
- std::unique_ptr<CallbackStore> RegisterAccumulatorCountCallback(
+ /**
+ * Register a callback on the accumulator count.
+ *
+ * @param callback the callback that will be called whenever the accumulator
+ * count is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterAccumulatorCountCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the accumulator count.
+ *
+ * @return the accumulator count.
+ */
int64_t GetAccumulatorCount() const;
+ /**
+ * Change the accumulator count.
+ *
+ * @param accumulatorCount the new count.
+ */
void SetAccumulatorCount(int64_t accumulatorCount);
- std::unique_ptr<CallbackStore> RegisterAccumulatorCenterCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on the accumulator center.
+ *
+ * @param callback the callback that will be called whenever the accumulator
+ * center is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterAccumulatorCenterCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Get the accumulator center.
+ *
+ * @return the accumulator center
+ */
int GetAccumulatorCenter() const;
+ /**
+ * Change the accumulator center.
+ *
+ * @param accumulatorCenter the new center
+ */
void SetAccumulatorCenter(int accumulatorCenter);
- std::unique_ptr<CallbackStore> RegisterAccumulatorDeadbandCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on the accumulator deadband.
+ *
+ * @param callback the callback that will be called whenever the accumulator
+ * deadband is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterAccumulatorDeadbandCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Get the accumulator deadband.
+ *
+ * @return the accumulator deadband
+ */
int GetAccumulatorDeadband() const;
+ /**
+ * Change the accumulator deadband.
+ *
+ * @param accumulatorDeadband the new deadband
+ */
void SetAccumulatorDeadband(int accumulatorDeadband);
+ /**
+ * Reset all simulation data for this object.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/AnalogOutputSim.h b/wpilibc/src/main/native/include/frc/simulation/AnalogOutputSim.h
index e468fa5..ffec03a 100644
--- a/wpilibc/src/main/native/include/frc/simulation/AnalogOutputSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/AnalogOutputSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -36,20 +33,57 @@
*/
explicit AnalogOutputSim(int channel);
- std::unique_ptr<CallbackStore> RegisterVoltageCallback(
+ /**
+ * Register a callback to be run whenever the voltage changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterVoltageCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the analog output voltage.
+ *
+ * @return the voltage on this analog output
+ */
double GetVoltage() const;
+ /**
+ * Set the analog output voltage.
+ *
+ * @param voltage the new voltage on this analog output
+ */
void SetVoltage(double voltage);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback to be run when this analog output is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether this analog output has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Define whether this analog output has been initialized.
+ *
+ * @param initialized whether this object is initialized
+ */
void SetInitialized(bool initialized);
+ /**
+ * Reset all simulation data on this object.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/AnalogTriggerSim.h b/wpilibc/src/main/native/include/frc/simulation/AnalogTriggerSim.h
index 60d62e1..04e9e9b 100644
--- a/wpilibc/src/main/native/include/frc/simulation/AnalogTriggerSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/AnalogTriggerSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -48,27 +45,86 @@
*/
static AnalogTriggerSim CreateForIndex(int index);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback on whether the analog trigger is initialized.
+ *
+ * @param callback the callback that will be called whenever the analog
+ * trigger is initialized
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if this analog trigger has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Change whether this analog trigger has been initialized.
+ *
+ * @param initialized the new value
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterTriggerLowerBoundCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on the lower bound.
+ *
+ * @param callback the callback that will be called whenever the lower bound
+ * is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterTriggerLowerBoundCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Get the lower bound.
+ *
+ * @return the lower bound
+ */
double GetTriggerLowerBound() const;
+ /**
+ * Change the lower bound.
+ *
+ * @param triggerLowerBound the new lower bound
+ */
void SetTriggerLowerBound(double triggerLowerBound);
- std::unique_ptr<CallbackStore> RegisterTriggerUpperBoundCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on the upper bound.
+ *
+ * @param callback the callback that will be called whenever the upper bound
+ * is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterTriggerUpperBoundCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Get the upper bound.
+ *
+ * @return the upper bound
+ */
double GetTriggerUpperBound() const;
+ /**
+ * Change the upper bound.
+ *
+ * @param triggerUpperBound the new upper bound
+ */
void SetTriggerUpperBound(double triggerUpperBound);
+ /**
+ * Reset all simulation data for this object.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/BatterySim.h b/wpilibc/src/main/native/include/frc/simulation/BatterySim.h
index ef8fb5d..4a350cf 100644
--- a/wpilibc/src/main/native/include/frc/simulation/BatterySim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/BatterySim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -15,13 +12,16 @@
namespace frc::sim {
+/**
+ * A utility class to simulate the robot battery.
+ */
class BatterySim {
public:
/**
* Calculate the loaded battery voltage. Use this with
- * {@link RoboRioSim#setVInVoltage(double)} to set the simulated battery
- * voltage, which can then be retrieved with the {@link
- * RobotController#getBatteryVoltage()} method.
+ * RoboRioSim::SetVInVoltage(double) to set the simulated battery voltage,
+ * which can then be retrieved with the RobotController::GetBatteryVoltage()
+ * method.
*
* @param nominalVoltage The nominal battery voltage. Usually 12v.
* @param resistance The forward resistance of the battery. Most batteries
@@ -38,10 +38,10 @@
/**
* Calculate the loaded battery voltage. Use this with
- * {@link RoboRioSim#setVInVoltage(double)} to set the simulated battery
- * voltage, which can then be retrieved with the {@link
- * RobotController#getBatteryVoltage()} method. This function assumes a
- * nominal voltage of 12v and a resistance of 20 milliohms (0.020 ohms)
+ * RoboRioSimSetVInVoltage(double) to set the simulated battery voltage, which
+ * can then be retrieved with the RobotController::GetBatteryVoltage() method.
+ * This function assumes a nominal voltage of 12V and a resistance of 20
+ * milliohms (0.020 ohms).
*
* @param currents The currents drawn from the battery.
* @return The battery's voltage under load.
diff --git a/wpilibc/src/main/native/include/frc/simulation/BuiltInAccelerometerSim.h b/wpilibc/src/main/native/include/frc/simulation/BuiltInAccelerometerSim.h
index 49a581c..9ffcf5b 100644
--- a/wpilibc/src/main/native/include/frc/simulation/BuiltInAccelerometerSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/BuiltInAccelerometerSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -36,41 +33,129 @@
*/
explicit BuiltInAccelerometerSim(const BuiltInAccelerometer& accel);
- std::unique_ptr<CallbackStore> RegisterActiveCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run when this accelerometer activates.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterActiveCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether the accelerometer is active.
+ *
+ * @return true if active
+ */
bool GetActive() const;
+ /**
+ * Define whether this accelerometer is active.
+ *
+ * @param active the new state
+ */
void SetActive(bool active);
- std::unique_ptr<CallbackStore> RegisterRangeCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the range changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterRangeCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Check the range of this accelerometer.
+ *
+ * @return the accelerometer range
+ */
HAL_AccelerometerRange GetRange() const;
+ /**
+ * Change the range of this accelerometer.
+ *
+ * @param range the new accelerometer range
+ */
void SetRange(HAL_AccelerometerRange range);
- std::unique_ptr<CallbackStore> RegisterXCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the X axis value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterXCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the X axis value.
+ *
+ * @return the X axis measurement
+ */
double GetX() const;
+ /**
+ * Change the X axis value of the accelerometer.
+ *
+ * @param x the new reading of the X axis
+ */
void SetX(double x);
- std::unique_ptr<CallbackStore> RegisterYCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the Y axis value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterYCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the Y axis value.
+ *
+ * @return the Y axis measurement
+ */
double GetY() const;
+ /**
+ * Change the Y axis value of the accelerometer.
+ *
+ * @param y the new reading of the Y axis
+ */
void SetY(double y);
- std::unique_ptr<CallbackStore> RegisterZCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the Z axis value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterZCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the Z axis value.
+ *
+ * @return the Z axis measurement
+ */
double GetZ() const;
+ /**
+ * Change the Z axis value of the accelerometer.
+ *
+ * @param z the new reading of the Z axis
+ */
void SetZ(double z);
+ /**
+ * Reset all simulation data of this object.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/CTREPCMSim.h b/wpilibc/src/main/native/include/frc/simulation/CTREPCMSim.h
new file mode 100644
index 0000000..0929308
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/CTREPCMSim.h
@@ -0,0 +1,212 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include "frc/PneumaticsBase.h"
+#include "frc/simulation/CallbackStore.h"
+
+namespace frc {
+
+class Compressor;
+
+namespace sim {
+
+/**
+ * Class to control a simulated Pneumatic Control Module (PCM).
+ */
+class CTREPCMSim {
+ public:
+ /**
+ * Constructs with the default PCM module number (CAN ID).
+ */
+ CTREPCMSim();
+
+ /**
+ * Constructs from a PCM module number (CAN ID).
+ *
+ * @param module module number
+ */
+ explicit CTREPCMSim(int module);
+
+ explicit CTREPCMSim(const PneumaticsBase& pneumatics);
+
+ /**
+ * Register a callback to be run when a solenoid is initialized on a channel.
+ *
+ * @param callback the callback
+ * @param initialNotify should the callback be run with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check if a solenoid has been initialized on a specific channel.
+ *
+ * @return true if initialized
+ */
+ bool GetInitialized() const;
+
+ /**
+ * Define whether a solenoid has been initialized on a specific channel.
+ *
+ * @param solenoidInitialized is there a solenoid initialized on that channel
+ */
+ void SetInitialized(bool solenoidInitialized);
+
+ /**
+ * Register a callback to be run when the solenoid output on a channel
+ * changes.
+ *
+ * @param channel the channel to monitor
+ * @param callback the callback
+ * @param initialNotify should the callback be run with the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterSolenoidOutputCallback(
+ int channel, NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check the solenoid output on a specific channel.
+ *
+ * @param channel the channel to check
+ * @return the solenoid output
+ */
+ bool GetSolenoidOutput(int channel) const;
+
+ /**
+ * Change the solenoid output on a specific channel.
+ *
+ * @param channel the channel to check
+ * @param solenoidOutput the new solenoid output
+ */
+ void SetSolenoidOutput(int channel, bool solenoidOutput);
+
+ /**
+ * Register a callback to be run when the compressor activates.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterCompressorOnCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check if the compressor is on.
+ *
+ * @return true if the compressor is active
+ */
+ bool GetCompressorOn() const;
+
+ /**
+ * Set whether the compressor is active.
+ *
+ * @param compressorOn the new value
+ */
+ void SetCompressorOn(bool compressorOn);
+
+ /**
+ * Register a callback to be run whenever the closed loop state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterClosedLoopEnabledCallback(NotifyCallback callback,
+ bool initialNotify);
+
+ /**
+ * Check whether the closed loop compressor control is active.
+ *
+ * @return true if active
+ */
+ bool GetClosedLoopEnabled() const;
+
+ /**
+ * Turn on/off the closed loop control of the compressor.
+ *
+ * @param closedLoopEnabled whether the control loop is active
+ */
+ void SetClosedLoopEnabled(bool closedLoopEnabled);
+
+ /**
+ * Register a callback to be run whenever the pressure switch value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPressureSwitchCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check the value of the pressure switch.
+ *
+ * @return the pressure switch value
+ */
+ bool GetPressureSwitch() const;
+
+ /**
+ * Set the value of the pressure switch.
+ *
+ * @param pressureSwitch the new value
+ */
+ void SetPressureSwitch(bool pressureSwitch);
+
+ /**
+ * Register a callback to be run whenever the compressor current changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterCompressorCurrentCallback(NotifyCallback callback,
+ bool initialNotify);
+
+ /**
+ * Read the compressor current.
+ *
+ * @return the current of the compressor connected to this module
+ */
+ double GetCompressorCurrent() const;
+
+ /**
+ * Set the compressor current.
+ *
+ * @param compressorCurrent the new compressor current
+ */
+ void SetCompressorCurrent(double compressorCurrent);
+
+ /**
+ * Get the current value of all solenoid outputs.
+ *
+ * @return the solenoid outputs (1 bit per output)
+ */
+ uint8_t GetAllSolenoidOutputs() const;
+
+ /**
+ * Change all of the solenoid outputs.
+ *
+ * @param outputs the new solenoid outputs (1 bit per output)
+ */
+ void SetAllSolenoidOutputs(uint8_t outputs);
+
+ /**
+ * Reset all simulation data for this object.
+ */
+ void ResetData();
+
+ private:
+ int m_index;
+};
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h b/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h
index 379296a..61cc6b2 100644
--- a/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h
+++ b/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h
@@ -1,33 +1,32 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
+#include <string_view>
#include <hal/Value.h>
-#include <wpi/StringRef.h>
-namespace frc {
-namespace sim {
+namespace frc::sim {
-using NotifyCallback = std::function<void(wpi::StringRef, const HAL_Value*)>;
+using NotifyCallback = std::function<void(std::string_view, const HAL_Value*)>;
using ConstBufferCallback = std::function<void(
- wpi::StringRef, const unsigned char* buffer, unsigned int count)>;
-typedef void (*CancelCallbackFunc)(int32_t index, int32_t uid);
-typedef void (*CancelCallbackNoIndexFunc)(int32_t uid);
-typedef void (*CancelCallbackChannelFunc)(int32_t index, int32_t channel,
- int32_t uid);
+ std::string_view, const unsigned char* buffer, unsigned int count)>;
+using CancelCallbackFunc = void (*)(int32_t index, int32_t uid);
+using CancelCallbackNoIndexFunc = void (*)(int32_t uid);
+using CancelCallbackChannelFunc = void (*)(int32_t index, int32_t channel,
+ int32_t uid);
void CallbackStoreThunk(const char* name, void* param, const HAL_Value* value);
void ConstBufferCallbackStoreThunk(const char* name, void* param,
const unsigned char* buffer,
unsigned int count);
+/**
+ * Manages simulation callbacks; each object is associated with a callback.
+ */
class CallbackStore {
public:
CallbackStore(int32_t i, NotifyCallback cb, CancelCallbackNoIndexFunc ccf);
@@ -76,5 +75,4 @@
enum CancelType { Normal, Channel, NoIndex };
CancelType cancelType;
};
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/DIOSim.h b/wpilibc/src/main/native/include/frc/simulation/DIOSim.h
index f6edb39..9bbd3fb 100644
--- a/wpilibc/src/main/native/include/frc/simulation/DIOSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/DIOSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -44,41 +41,132 @@
*/
explicit DIOSim(int channel);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback to be run when this DIO is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether this DIO has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Define whether this DIO has been initialized.
+ *
+ * @param initialized whether this object is initialized
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterValueCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the DIO value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterValueCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the value of the DIO port.
+ *
+ * @return the DIO value
+ */
bool GetValue() const;
+ /**
+ * Change the DIO value.
+ *
+ * @param value the new value
+ */
void SetValue(bool value);
- std::unique_ptr<CallbackStore> RegisterPulseLengthCallback(
+ /**
+ * Register a callback to be run whenever the pulse length changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPulseLengthCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the pulse length.
+ *
+ * @return the pulse length of this DIO port
+ */
double GetPulseLength() const;
+ /**
+ * Change the pulse length of this DIO port.
+ *
+ * @param pulseLength the new pulse length
+ */
void SetPulseLength(double pulseLength);
- std::unique_ptr<CallbackStore> RegisterIsInputCallback(
+ /**
+ * Register a callback to be run whenever this DIO changes to be an input.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterIsInputCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether this DIO port is currently an Input.
+ *
+ * @return true if Input
+ */
bool GetIsInput() const;
+ /**
+ * Define whether this DIO port is an Input.
+ *
+ * @param isInput whether this DIO should be an Input
+ */
void SetIsInput(bool isInput);
- std::unique_ptr<CallbackStore> RegisterFilterIndexCallback(
+ /**
+ * Register a callback to be run whenever the filter index changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterFilterIndexCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the filter index.
+ *
+ * @return the filter index of this DIO port
+ */
int GetFilterIndex() const;
+ /**
+ * Change the filter index of this DIO port.
+ *
+ * @param filterIndex the new filter index
+ */
void SetFilterIndex(int filterIndex);
+ /**
+ * Reset all simulation data of this object.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h b/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h
index a75edb9..e64a652 100644
--- a/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/DifferentialDrivetrainSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -24,42 +21,66 @@
/**
* Create a SimDrivetrain.
*
- * @param drivetrainPlant The LinearSystem representing the robot's
- * drivetrain. This system can be created with
- * LinearSystemId#createDrivetrainVelocitySystem or
- * LinearSystemId#identifyDrivetrainSystem.
- * @param trackWidth The robot's track width.
- * @param driveMotor A {@link DCMotor} representing the left side of
- * the drivetrain.
- * @param gearingRatio The gearingRatio ratio of the left side, as output
- * over input. This must be the same ratio as the ratio used to identify or
- * create the drivetrainPlant.
- * @param wheelRadiusMeters The radius of the wheels on the drivetrain, in
- * meters.
+ * @param plant The LinearSystem representing the robot's drivetrain. This
+ * system can be created with
+ * LinearSystemId::DrivetrainVelocitySystem() or
+ * LinearSystemId::IdentifyDrivetrainSystem().
+ * @param trackWidth The robot's track width.
+ * @param driveMotor A DCMotor representing the left side of the drivetrain.
+ * @param gearingRatio The gearingRatio ratio of the left side, as output over
+ * input. This must be the same ratio as the ratio used to
+ * identify or create the plant.
+ * @param wheelRadius The radius of the wheels on the drivetrain, in meters.
+ * @param measurementStdDevs Standard deviations for measurements, in the form
+ * [x, y, heading, left velocity, right velocity,
+ * left distance, right distance]áµ€. Can be omitted
+ * if no noise is desired. Gyro standard deviations
+ * of 0.0001 radians, velocity standard deviations
+ * of 0.05 m/s, and position measurement standard
+ * deviations of 0.005 meters are a reasonable
+ * starting point.
*/
- DifferentialDrivetrainSim(const LinearSystem<2, 2, 2>& plant,
- units::meter_t trackWidth, DCMotor driveMotor,
- double gearingRatio, units::meter_t wheelRadius);
+ DifferentialDrivetrainSim(
+ LinearSystem<2, 2, 2> plant, units::meter_t trackWidth,
+ DCMotor driveMotor, double gearingRatio, units::meter_t wheelRadius,
+ const std::array<double, 7>& measurementStdDevs = {});
/**
* Create a SimDrivetrain.
*
- * @param driveMotor A {@link DCMotor} representing the left side of the
- * drivetrain.
+ * @param driveMotor A DCMotor representing the left side of the drivetrain.
* @param gearing The gearing on the drive between motor and wheel, as
- * output over input. This must be the same ratio as the ratio used to
- * identify or create the drivetrainPlant.
+ * output over input. This must be the same ratio as the
+ * ratio used to identify or create the plant.
* @param J The moment of inertia of the drivetrain about its
- * center.
+ * center.
* @param mass The mass of the drivebase.
* @param wheelRadius The radius of the wheels on the drivetrain.
* @param trackWidth The robot's track width, or distance between left and
- * right wheels.
+ * right wheels.
+ * @param measurementStdDevs Standard deviations for measurements, in the form
+ * [x, y, heading, left velocity, right velocity,
+ * left distance, right distance]áµ€. Can be omitted
+ * if no noise is desired. Gyro standard deviations
+ * of 0.0001 radians, velocity standard deviations
+ * of 0.05 m/s, and position measurement standard
+ * deviations of 0.005 meters are a reasonable
+ * starting point.
*/
- DifferentialDrivetrainSim(frc::DCMotor driveMotor, double gearing,
- units::kilogram_square_meter_t J,
- units::kilogram_t mass, units::meter_t wheelRadius,
- units::meter_t trackWidth);
+ DifferentialDrivetrainSim(
+ frc::DCMotor driveMotor, double gearing, units::kilogram_square_meter_t J,
+ units::kilogram_t mass, units::meter_t wheelRadius,
+ units::meter_t trackWidth,
+ const std::array<double, 7>& measurementStdDevs = {});
+
+ /**
+ * Clamp the input vector such that no element exceeds the battery voltage.
+ * If any does, the relative magnitudes of the input will be maintained.
+ *
+ * @param u The input vector.
+ * @return The normalized input.
+ */
+ Eigen::Vector<double, 2> ClampInput(const Eigen::Vector<double, 2>& u);
/**
* Sets the applied voltage to the drivetrain. Note that positive voltage must
@@ -81,30 +102,18 @@
/**
* Updates the simulation.
*
- * @param dt The time that's passed since the last {@link #update(double)}
- * call.
+ * @param dt The time that's passed since the last Update(units::second_t)
+ * call.
*/
void Update(units::second_t dt);
/**
- * Returns an element of the state vector.
- *
- * @param state The row of the state vector.
- */
- double GetState(int state) const;
-
- /**
* Returns the current gearing reduction of the drivetrain, as output over
* input.
*/
double GetGearing() const;
/**
- * Returns the current state vector x.
- */
- Eigen::Matrix<double, 7, 1> GetState() const;
-
- /**
* Returns the direction the robot is pointing.
*
* Note that this angle is counterclockwise-positive, while most gyros are
@@ -118,6 +127,48 @@
Pose2d GetPose() const;
/**
+ * Get the right encoder position in meters.
+ * @return The encoder position.
+ */
+ units::meter_t GetRightPosition() const {
+ return units::meter_t{GetOutput(State::kRightPosition)};
+ }
+
+ /**
+ * Get the right encoder velocity in meters per second.
+ * @return The encoder velocity.
+ */
+ units::meters_per_second_t GetRightVelocity() const {
+ return units::meters_per_second_t{GetOutput(State::kRightVelocity)};
+ }
+
+ /**
+ * Get the left encoder position in meters.
+ * @return The encoder position.
+ */
+ units::meter_t GetLeftPosition() const {
+ return units::meter_t{GetOutput(State::kLeftPosition)};
+ }
+
+ /**
+ * Get the left encoder velocity in meters per second.
+ * @return The encoder velocity.
+ */
+ units::meters_per_second_t GetLeftVelocity() const {
+ return units::meters_per_second_t{GetOutput(State::kLeftVelocity)};
+ }
+
+ /**
+ * Returns the currently drawn current for the right side.
+ */
+ units::ampere_t GetRightCurrentDraw() const;
+
+ /**
+ * Returns the currently drawn current for the left side.
+ */
+ units::ampere_t GetLeftCurrentDraw() const;
+
+ /**
* Returns the currently drawn current.
*/
units::ampere_t GetCurrentDraw() const;
@@ -127,7 +178,7 @@
*
* @param state The state.
*/
- void SetState(const Eigen::Matrix<double, 7, 1>& state);
+ void SetState(const Eigen::Vector<double, 7>& state);
/**
* Sets the system pose.
@@ -136,8 +187,8 @@
*/
void SetPose(const frc::Pose2d& pose);
- Eigen::Matrix<double, 7, 1> Dynamics(const Eigen::Matrix<double, 7, 1>& x,
- const Eigen::Matrix<double, 2, 1>& u);
+ Eigen::Vector<double, 7> Dynamics(const Eigen::Vector<double, 7>& x,
+ const Eigen::Vector<double, 2>& u);
class State {
public:
@@ -189,10 +240,16 @@
* @param motor The motors installed in the bot.
* @param gearing The gearing reduction used.
* @param wheelSize The wheel size.
+ * @param measurementStdDevs Standard deviations for measurements, in the form
+ * [x, y, heading, left velocity, right velocity, left distance, right
+ * distance]áµ€. Can be omitted if no noise is desired. Gyro standard
+ * deviations of 0.0001 radians, velocity standard deviations of 0.05 m/s, and
+ * position measurement standard deviations of 0.005 meters are a reasonable
+ * starting point.
*/
- static DifferentialDrivetrainSim CreateKitbotSim(frc::DCMotor motor,
- double gearing,
- units::meter_t wheelSize) {
+ static DifferentialDrivetrainSim CreateKitbotSim(
+ frc::DCMotor motor, double gearing, units::meter_t wheelSize,
+ const std::array<double, 7>& measurementStdDevs = {}) {
// MOI estimation -- note that I = m r^2 for point masses
units::kilogram_square_meter_t batteryMoi = 12.5_lb * 10_in * 10_in;
units::kilogram_square_meter_t gearboxMoi = (2.8_lb + 2.0_lb) *
@@ -200,7 +257,8 @@
* (26_in / 2) * (26_in / 2);
return DifferentialDrivetrainSim{
- motor, gearing, batteryMoi + gearboxMoi, 25_kg, wheelSize / 2.0, 26_in};
+ motor, gearing, batteryMoi + gearboxMoi, 60_lb,
+ wheelSize / 2.0, 26_in, measurementStdDevs};
}
/**
@@ -210,16 +268,48 @@
* @param gearing The gearing reduction used.
* @param wheelSize The wheel size.
* @param J The moment of inertia of the drivebase. This can be
- * calculated using frc-characterization.
+ * calculated using SysId.
+ * @param measurementStdDevs Standard deviations for measurements, in the form
+ * [x, y, heading, left velocity, right velocity, left distance, right
+ * distance]áµ€. Can be omitted if no noise is desired. Gyro standard
+ * deviations of 0.0001 radians, velocity standard deviations of 0.05 m/s, and
+ * position measurement standard deviations of 0.005 meters are a reasonable
+ * starting point.
*/
static DifferentialDrivetrainSim CreateKitbotSim(
frc::DCMotor motor, double gearing, units::meter_t wheelSize,
- units::kilogram_square_meter_t J) {
- return DifferentialDrivetrainSim{motor, gearing, J,
- 25_kg, wheelSize / 2.0, 26_in};
+ units::kilogram_square_meter_t J,
+ const std::array<double, 7>& measurementStdDevs = {}) {
+ return DifferentialDrivetrainSim{
+ motor, gearing, J, 60_lb, wheelSize / 2.0, 26_in, measurementStdDevs};
}
private:
+ /**
+ * Returns an element of the state vector.
+ *
+ * @param output The row of the output vector.
+ */
+ double GetOutput(int output) const;
+
+ /**
+ * Returns the current output vector y.
+ */
+ Eigen::Vector<double, 7> GetOutput() const;
+
+ /**
+ * Returns an element of the state vector. Note that this will not include
+ * noise!
+ *
+ * @param output The row of the output vector.
+ */
+ double GetState(int state) const;
+
+ /**
+ * Returns the current state vector x. Note that this will not include noise!
+ */
+ Eigen::Vector<double, 7> GetState() const;
+
LinearSystem<2, 2, 2> m_plant;
units::meter_t m_rb;
units::meter_t m_wheelRadius;
@@ -229,7 +319,9 @@
double m_originalGearing;
double m_currentGearing;
- Eigen::Matrix<double, 7, 1> m_x;
- Eigen::Matrix<double, 2, 1> m_u;
+ Eigen::Vector<double, 7> m_x;
+ Eigen::Vector<double, 2> m_u;
+ Eigen::Vector<double, 7> m_y;
+ std::array<double, 7> m_measurementStdDevs;
};
} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/DigitalPWMSim.h b/wpilibc/src/main/native/include/frc/simulation/DigitalPWMSim.h
index 2ff8a12..53caee7 100644
--- a/wpilibc/src/main/native/include/frc/simulation/DigitalPWMSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/DigitalPWMSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -50,27 +47,81 @@
*/
static DigitalPWMSim CreateForIndex(int index);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback to be run when this PWM output is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether this PWM output has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Define whether this PWM output has been initialized.
+ *
+ * @param initialized whether this object is initialized
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterDutyCycleCallback(
+ /**
+ * Register a callback to be run whenever the duty cycle value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterDutyCycleCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the duty cycle value.
+ *
+ * @return the duty cycle value of this PWM output
+ */
double GetDutyCycle() const;
+ /**
+ * Set the duty cycle value of this PWM output.
+ *
+ * @param dutyCycle the new value
+ */
void SetDutyCycle(double dutyCycle);
- std::unique_ptr<CallbackStore> RegisterPinCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the pin changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPinCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Check the pin number.
+ *
+ * @return the pin number
+ */
int GetPin() const;
+ /**
+ * Change the pin number.
+ *
+ * @param pin the new pin number
+ */
void SetPin(int pin);
+ /**
+ * Reset all simulation data.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/DriverStationSim.h b/wpilibc/src/main/native/include/frc/simulation/DriverStationSim.h
index 80cf942..412a921 100644
--- a/wpilibc/src/main/native/include/frc/simulation/DriverStationSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/DriverStationSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -14,68 +11,212 @@
#include "frc/DriverStation.h"
#include "frc/simulation/CallbackStore.h"
-namespace frc {
-namespace sim {
+namespace frc::sim {
/**
* Class to control a simulated driver station.
*/
class DriverStationSim {
public:
- static std::unique_ptr<CallbackStore> RegisterEnabledCallback(
+ /**
+ * Register a callback on whether the DS is enabled.
+ *
+ * @param callback the callback that will be called whenever the enabled
+ * state is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore> RegisterEnabledCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if the DS is enabled.
+ *
+ * @return true if enabled
+ */
static bool GetEnabled();
+ /**
+ * Change whether the DS is enabled.
+ *
+ * @param enabled the new value
+ */
static void SetEnabled(bool enabled);
- static std::unique_ptr<CallbackStore> RegisterAutonomousCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on whether the DS is in autonomous mode.
+ *
+ * @param callback the callback that will be called on autonomous mode
+ * entrance/exit
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterAutonomousCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if the DS is in autonomous.
+ *
+ * @return true if autonomous
+ */
static bool GetAutonomous();
+ /**
+ * Change whether the DS is in autonomous.
+ *
+ * @param autonomous the new value
+ */
static void SetAutonomous(bool autonomous);
- static std::unique_ptr<CallbackStore> RegisterTestCallback(
+ /**
+ * Register a callback on whether the DS is in test mode.
+ *
+ * @param callback the callback that will be called whenever the test mode
+ * is entered or left
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore> RegisterTestCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if the DS is in test.
+ *
+ * @return true if test
+ */
static bool GetTest();
+ /**
+ * Change whether the DS is in test.
+ *
+ * @param test the new value
+ */
static void SetTest(bool test);
- static std::unique_ptr<CallbackStore> RegisterEStopCallback(
+ /**
+ * Register a callback on the eStop state.
+ *
+ * @param callback the callback that will be called whenever the eStop state
+ * changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore> RegisterEStopCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if eStop has been activated.
+ *
+ * @return true if eStopped
+ */
static bool GetEStop();
+ /**
+ * Set whether eStop is active.
+ *
+ * @param eStop true to activate
+ */
static void SetEStop(bool eStop);
- static std::unique_ptr<CallbackStore> RegisterFmsAttachedCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on whether the FMS is connected.
+ *
+ * @param callback the callback that will be called whenever the FMS
+ * connection changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterFmsAttachedCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if the FMS is connected.
+ *
+ * @return true if FMS is connected
+ */
static bool GetFmsAttached();
+ /**
+ * Change whether the FMS is connected.
+ *
+ * @param fmsAttached the new value
+ */
static void SetFmsAttached(bool fmsAttached);
- static std::unique_ptr<CallbackStore> RegisterDsAttachedCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on whether the DS is connected.
+ *
+ * @param callback the callback that will be called whenever the DS
+ * connection changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterDsAttachedCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if the DS is attached.
+ *
+ * @return true if attached
+ */
static bool GetDsAttached();
+ /**
+ * Change whether the DS is attached.
+ *
+ * @param dsAttached the new value
+ */
static void SetDsAttached(bool dsAttached);
- static std::unique_ptr<CallbackStore> RegisterAllianceStationIdCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback on the alliance station ID.
+ *
+ * @param callback the callback that will be called whenever the alliance
+ * station changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterAllianceStationIdCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Get the alliance station ID (color + number).
+ *
+ * @return the alliance station color and number
+ */
static HAL_AllianceStationID GetAllianceStationId();
+ /**
+ * Change the alliance station.
+ *
+ * @param allianceStationId the new alliance station
+ */
static void SetAllianceStationId(HAL_AllianceStationID allianceStationId);
- static std::unique_ptr<CallbackStore> RegisterMatchTimeCallback(
+ /**
+ * Register a callback on match time.
+ *
+ * @param callback the callback that will be called whenever match time
+ * changes
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore> RegisterMatchTimeCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the current value of the match timer.
+ *
+ * @return the current match time
+ */
static double GetMatchTime();
+ /**
+ * Sets the match timer.
+ *
+ * @param matchTime the new match time
+ */
static void SetMatchTime(double matchTime);
/**
@@ -116,7 +257,7 @@
static int GetJoystickRumble(int stick, int rumbleNum);
/**
- * Sets the state of one joystick button. Button indexes begin at 1.
+ * Sets the state of one joystick button. %Button indexes begin at 1.
*
* @param stick The joystick number
* @param button The button index, beginning at 1
@@ -242,7 +383,9 @@
*/
static void SetReplayNumber(int replayNumber);
+ /**
+ * Reset all simulation data for the Driver Station.
+ */
static void ResetData();
};
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/DutyCycleEncoderSim.h b/wpilibc/src/main/native/include/frc/simulation/DutyCycleEncoderSim.h
index 5d9a039..19577bb 100644
--- a/wpilibc/src/main/native/include/frc/simulation/DutyCycleEncoderSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/DutyCycleEncoderSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -24,7 +21,7 @@
/**
* Constructs from a DutyCycleEncoder object.
*
- * @param dutyCycleEncoder DutyCycleEncoder to simulate
+ * @param encoder DutyCycleEncoder to simulate
*/
explicit DutyCycleEncoderSim(const DutyCycleEncoder& encoder);
diff --git a/wpilibc/src/main/native/include/frc/simulation/DutyCycleSim.h b/wpilibc/src/main/native/include/frc/simulation/DutyCycleSim.h
index 40dad13..ec7b48c 100644
--- a/wpilibc/src/main/native/include/frc/simulation/DutyCycleSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/DutyCycleSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -47,27 +44,81 @@
*/
static DutyCycleSim CreateForIndex(int index);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback to be run when this duty cycle input is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether this duty cycle input has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Define whether this duty cycle input has been initialized.
+ *
+ * @param initialized whether this object is initialized
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterFrequencyCallback(
+ /**
+ * Register a callback to be run whenever the frequency changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterFrequencyCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the frequency.
+ *
+ * @return the duty cycle frequency
+ */
int GetFrequency() const;
- void SetFrequency(int count);
+ /**
+ * Change the duty cycle frequency.
+ *
+ * @param frequency the new frequency
+ */
+ void SetFrequency(int frequency);
- std::unique_ptr<CallbackStore> RegisterOutputCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the output changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterOutputCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the output from this duty cycle port.
+ *
+ * @return the output value
+ */
double GetOutput() const;
- void SetOutput(double period);
+ /**
+ * Change the duty cycle output.
+ *
+ * @param output the new output value
+ */
+ void SetOutput(double output);
+ /**
+ * Reset all simulation data for the duty cycle output.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h b/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h
index 9b7069f..14b6d2d 100644
--- a/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/ElevatorSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -61,20 +58,34 @@
const std::array<double, 1>& measurementStdDevs = {0.0});
/**
+ * Returns whether the elevator would hit the lower limit.
+ *
+ * @param elevatorHeight The elevator height.
+ * @return Whether the elevator would hit the lower limit.
+ */
+ bool WouldHitLowerLimit(units::meter_t elevatorHeight) const;
+
+ /**
+ * Returns whether the elevator would hit the upper limit.
+ *
+ * @param elevatorHeight The elevator height.
+ * @return Whether the elevator would hit the upper limit.
+ */
+ bool WouldHitUpperLimit(units::meter_t elevatorHeight) const;
+
+ /**
* Returns whether the elevator has hit the lower limit.
*
- * @param x The current elevator state.
* @return Whether the elevator has hit the lower limit.
*/
- bool HasHitLowerLimit(const Eigen::Matrix<double, 2, 1>& x) const;
+ bool HasHitLowerLimit() const;
/**
* Returns whether the elevator has hit the upper limit.
*
- * @param x The current elevator state.
* @return Whether the elevator has hit the upper limit.
*/
- bool HasHitUpperLimit(const Eigen::Matrix<double, 2, 1>& x) const;
+ bool HasHitUpperLimit() const;
/**
* Returns the position of the elevator.
@@ -112,9 +123,9 @@
* @param u The system inputs (voltage).
* @param dt The time difference between controller updates.
*/
- Eigen::Matrix<double, 2, 1> UpdateX(
- const Eigen::Matrix<double, 2, 1>& currentXhat,
- const Eigen::Matrix<double, 1, 1>& u, units::second_t dt) override;
+ Eigen::Vector<double, 2> UpdateX(const Eigen::Vector<double, 2>& currentXhat,
+ const Eigen::Vector<double, 1>& u,
+ units::second_t dt) override;
private:
DCMotor m_gearbox;
diff --git a/wpilibc/src/main/native/include/frc/simulation/EncoderSim.h b/wpilibc/src/main/native/include/frc/simulation/EncoderSim.h
index 4049ab8..0d578b4 100644
--- a/wpilibc/src/main/native/include/frc/simulation/EncoderSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/EncoderSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -48,77 +45,261 @@
*/
static EncoderSim CreateForIndex(int index);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback on the Initialized property of the encoder.
+ *
+ * @param callback the callback that will be called whenever the Initialized
+ * property is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the Initialized value of the encoder.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Change the Initialized value of the encoder.
+ *
+ * @param initialized the new value
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterCountCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback on the count property of the encoder.
+ *
+ * @param callback the callback that will be called whenever the count
+ * property is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterCountCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the count of the encoder.
+ *
+ * @return the count
+ */
int GetCount() const;
+ /**
+ * Change the count of the encoder.
+ *
+ * @param count the new count
+ */
void SetCount(int count);
- std::unique_ptr<CallbackStore> RegisterPeriodCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback on the period of the encoder.
+ *
+ * @param callback the callback that will be called whenever the period is
+ * changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPeriodCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the period of the encoder.
+ *
+ * @return the encoder period
+ */
double GetPeriod() const;
+ /**
+ * Change the encoder period.
+ *
+ * @param period the new period
+ */
void SetPeriod(double period);
- std::unique_ptr<CallbackStore> RegisterResetCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be called whenever the encoder is reset.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterResetCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Check if the encoder has been reset.
+ *
+ * @return true if reset
+ */
bool GetReset() const;
+ /**
+ * Change the reset property of the encoder.
+ *
+ * @param reset the new value
+ */
void SetReset(bool reset);
- std::unique_ptr<CallbackStore> RegisterMaxPeriodCallback(
+ /**
+ * Register a callback to be run whenever the max period of the encoder is
+ * changed.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterMaxPeriodCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the max period of the encoder.
+ *
+ * @return the max period of the encoder
+ */
double GetMaxPeriod() const;
+ /**
+ * Change the max period of the encoder.
+ *
+ * @param maxPeriod the new value
+ */
void SetMaxPeriod(double maxPeriod);
- std::unique_ptr<CallbackStore> RegisterDirectionCallback(
+ /**
+ * Register a callback on the direction of the encoder.
+ *
+ * @param callback the callback that will be called whenever the direction
+ * is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterDirectionCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the direction of the encoder.
+ *
+ * @return the direction of the encoder
+ */
bool GetDirection() const;
+ /**
+ * Set the direction of the encoder.
+ *
+ * @param direction the new direction
+ */
void SetDirection(bool direction);
- std::unique_ptr<CallbackStore> RegisterReverseDirectionCallback(
+ /**
+ * Register a callback on the reverse direction.
+ *
+ * @param callback the callback that will be called whenever the reverse
+ * direction is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterReverseDirectionCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the reverse direction of the encoder.
+ *
+ * @return the reverse direction of the encoder
+ */
bool GetReverseDirection() const;
+ /**
+ * Set the reverse direction.
+ *
+ * @param reverseDirection the new value
+ */
void SetReverseDirection(bool reverseDirection);
- std::unique_ptr<CallbackStore> RegisterSamplesToAverageCallback(
+ /**
+ * Register a callback on the samples-to-average value of this encoder.
+ *
+ * @param callback the callback that will be called whenever the
+ * samples-to-average is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterSamplesToAverageCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the samples-to-average value.
+ *
+ * @return the samples-to-average value
+ */
int GetSamplesToAverage() const;
+ /**
+ * Set the samples-to-average value.
+ *
+ * @param samplesToAverage the new value
+ */
void SetSamplesToAverage(int samplesToAverage);
- std::unique_ptr<CallbackStore> RegisterDistancePerPulseCallback(
+ /**
+ * Register a callback on the distance per pulse value of this encoder.
+ *
+ * @param callback the callback that will be called whenever the
+ * distance per pulse is changed
+ * @param initialNotify if true, the callback will be run on the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterDistancePerPulseCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Read the distance per pulse of the encoder.
+ *
+ * @return the encoder distance per pulse
+ */
double GetDistancePerPulse() const;
+ /**
+ * Change the encoder distance per pulse.
+ *
+ * @param distancePerPulse the new distance per pulse
+ */
void SetDistancePerPulse(double distancePerPulse);
+ /**
+ * Resets all simulation data for this encoder.
+ */
void ResetData();
+ /**
+ * Change the encoder distance.
+ *
+ * @param distance the new distance
+ */
void SetDistance(double distance);
+ /**
+ * Read the distance of the encoder.
+ *
+ * @return the encoder distance
+ */
double GetDistance();
+ /**
+ * Change the rate of the encoder.
+ *
+ * @param rate the new rate
+ */
void SetRate(double rate);
+ /**
+ * Get the rate of the encoder.
+ *
+ * @return the rate of change
+ */
double GetRate();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/Field2d.h b/wpilibc/src/main/native/include/frc/simulation/Field2d.h
deleted file mode 100644
index de30847..0000000
--- a/wpilibc/src/main/native/include/frc/simulation/Field2d.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <hal/SimDevice.h>
-#include <units/length.h>
-
-#include "frc/geometry/Pose2d.h"
-#include "frc/geometry/Rotation2d.h"
-
-namespace frc {
-
-/**
- * 2D representation of game field (for simulation).
- *
- * In non-simulation mode this simply stores and returns the robot pose.
- *
- * The robot pose is the actual location shown on the simulation view.
- * This may or may not match the robot's internal odometry. For example, if
- * the robot is shown at a particular starting location, the pose in this
- * class would represent the actual location on the field, but the robot's
- * internal state might have a 0,0,0 pose (unless it's initialized to
- * something different).
- *
- * As the user is able to edit the pose, code performing updates should get
- * the robot pose, transform it as appropriate (e.g. based on simulated wheel
- * velocity), and set the new pose.
- */
-class Field2d {
- public:
- Field2d();
-
- /**
- * Set the robot pose from a Pose object.
- *
- * @param pose 2D pose
- */
- void SetRobotPose(const Pose2d& pose);
-
- /**
- * Set the robot pose from x, y, and rotation.
- *
- * @param x X location
- * @param y Y location
- * @param rotation rotation
- */
- void SetRobotPose(units::meter_t x, units::meter_t y, Rotation2d rotation);
-
- /**
- * Get the robot pose.
- *
- * @return 2D pose
- */
- Pose2d GetRobotPose();
-
- private:
- Pose2d m_pose;
-
- hal::SimDevice m_device;
- hal::SimDouble m_x;
- hal::SimDouble m_y;
- hal::SimDouble m_rot;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h b/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h
index 1c47c45..9f2272c 100644
--- a/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/FlywheelSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -21,7 +18,7 @@
class FlywheelSim : public LinearSystemSim<1, 1, 1> {
public:
/**
- * Creates a simulated flywhel mechanism.
+ * Creates a simulated flywheel mechanism.
*
* @param plant The linear system representing the flywheel.
* @param gearbox The type of and number of motors in the flywheel
@@ -35,7 +32,7 @@
const std::array<double, 1>& measurementStdDevs = {0.0});
/**
- * Creates a simulated flywhel mechanism.
+ * Creates a simulated flywheel mechanism.
*
* @param gearbox The type of and number of motors in the flywheel
* gearbox.
diff --git a/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h b/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h
index 1705200..399e0c1 100644
--- a/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/GenericHIDSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -41,30 +38,101 @@
*/
void NotifyNewData();
+ /**
+ * Set the value of a given button.
+ *
+ * @param button the button to set
+ * @param value the new value
+ */
void SetRawButton(int button, bool value);
+ /**
+ * Set the value of a given axis.
+ *
+ * @param axis the axis to set
+ * @param value the new value
+ */
void SetRawAxis(int axis, double value);
+ /**
+ * Set the value of a given POV.
+ *
+ * @param pov the POV to set
+ * @param value the new value
+ */
void SetPOV(int pov, int value);
+ /**
+ * Set the value of the default POV (port 0).
+ *
+ * @param value the new value
+ */
void SetPOV(int value);
+ /**
+ * Set the axis count of this device.
+ *
+ * @param count the new axis count
+ */
void SetAxisCount(int count);
+ /**
+ * Set the POV count of this device.
+ *
+ * @param count the new POV count
+ */
void SetPOVCount(int count);
+ /**
+ * Set the button count of this device.
+ *
+ * @param count the new button count
+ */
void SetButtonCount(int count);
+ /**
+ * Set the type of this device.
+ *
+ * @param type the new device type
+ */
void SetType(GenericHID::HIDType type);
+ /**
+ * Set the name of this device.
+ *
+ * @param name the new device name
+ */
void SetName(const char* name);
+ /**
+ * Set the type of an axis.
+ *
+ * @param axis the axis
+ * @param type the type
+ */
void SetAxisType(int axis, int type);
+ /**
+ * Read the output of a button.
+ *
+ * @param outputNumber the button number
+ * @return the value of the button (true = pressed)
+ */
bool GetOutput(int outputNumber);
+ /**
+ * Get the encoded 16-bit integer that passes button values.
+ *
+ * @return the button values
+ */
int64_t GetOutputs();
+ /**
+ * Get the joystick rumble.
+ *
+ * @param type the rumble to read
+ * @return the rumble value
+ */
double GetRumble(GenericHID::RumbleType type);
protected:
diff --git a/wpilibc/src/main/native/include/frc/simulation/JoystickSim.h b/wpilibc/src/main/native/include/frc/simulation/JoystickSim.h
index 5735728..db573ad 100644
--- a/wpilibc/src/main/native/include/frc/simulation/JoystickSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/JoystickSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -34,18 +31,53 @@
*/
explicit JoystickSim(int port);
+ /**
+ * Set the X value of the joystick.
+ *
+ * @param value the new X value
+ */
void SetX(double value);
+ /**
+ * Set the Y value of the joystick.
+ *
+ * @param value the new Y value
+ */
void SetY(double value);
+ /**
+ * Set the Z value of the joystick.
+ *
+ * @param value the new Z value
+ */
void SetZ(double value);
+ /**
+ * Set the twist value of the joystick.
+ *
+ * @param value the new twist value
+ */
void SetTwist(double value);
+ /**
+ * Set the throttle value of the joystick.
+ *
+ * @param value the new throttle value
+ */
void SetThrottle(double value);
+ /**
+ * Set the trigger value of the joystick.
+ *
+ * @param state the new value
+ */
void SetTrigger(bool state);
+ /**
+ * Set the top state of the joystick.
+ *
+ * @param state the new state
+ */
void SetTop(bool state);
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h b/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h
index 4f3c658..61cbd46 100644
--- a/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/LinearSystemSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -13,6 +10,7 @@
#include <units/current.h>
#include <units/time.h>
+#include "frc/RobotController.h"
#include "frc/StateSpaceUtil.h"
#include "frc/system/LinearSystem.h"
@@ -38,13 +36,13 @@
* @param system The system to simulate.
* @param measurementStdDevs The standard deviations of the measurements.
*/
- LinearSystemSim(const LinearSystem<States, Inputs, Outputs>& system,
- const std::array<double, Outputs>& measurementStdDevs =
- std::array<double, Outputs>{})
+ explicit LinearSystemSim(
+ const LinearSystem<States, Inputs, Outputs>& system,
+ const std::array<double, Outputs>& measurementStdDevs = {})
: m_plant(system), m_measurementStdDevs(measurementStdDevs) {
- m_x = Eigen::Matrix<double, States, 1>::Zero();
- m_y = Eigen::Matrix<double, Outputs, 1>::Zero();
- m_u = Eigen::Matrix<double, Inputs, 1>::Zero();
+ m_x = Eigen::Vector<double, States>::Zero();
+ m_y = Eigen::Vector<double, Outputs>::Zero();
+ m_u = Eigen::Vector<double, Inputs>::Zero();
}
/**
@@ -71,7 +69,7 @@
*
* @return The current output of the plant.
*/
- const Eigen::Matrix<double, Outputs, 1>& GetOutput() const { return m_y; }
+ const Eigen::Vector<double, Outputs>& GetOutput() const { return m_y; }
/**
* Returns an element of the current output of the plant.
@@ -86,7 +84,7 @@
*
* @param u The system inputs.
*/
- void SetInput(const Eigen::Matrix<double, Inputs, 1>& u) { m_u = u; }
+ void SetInput(const Eigen::Vector<double, Inputs>& u) { m_u = ClampInput(u); }
/*
* Sets the system inputs.
@@ -94,14 +92,17 @@
* @param row The row in the input matrix to set.
* @param value The value to set the row to.
*/
- void SetInput(int row, double value) { m_u(row, 0) = value; }
+ void SetInput(int row, double value) {
+ m_u(row, 0) = value;
+ ClampInput(m_u);
+ }
/**
* Sets the system state.
*
* @param state The new state.
*/
- void SetState(const Eigen::Matrix<double, States, 1>& state) { m_x = state; }
+ void SetState(const Eigen::Vector<double, States>& state) { m_x = state; }
/**
* Returns the current drawn by this simulated system. Override this method to
@@ -121,17 +122,29 @@
* @param u The system inputs (usually voltage).
* @param dt The time difference between controller updates.
*/
- virtual Eigen::Matrix<double, States, 1> UpdateX(
- const Eigen::Matrix<double, States, 1>& currentXhat,
- const Eigen::Matrix<double, Inputs, 1>& u, units::second_t dt) {
+ virtual Eigen::Vector<double, States> UpdateX(
+ const Eigen::Vector<double, States>& currentXhat,
+ const Eigen::Vector<double, Inputs>& u, units::second_t dt) {
return m_plant.CalculateX(currentXhat, u, dt);
}
+ /**
+ * Clamp the input vector such that no element exceeds the given voltage. If
+ * any does, the relative magnitudes of the input will be maintained.
+ *
+ * @param u The input vector.
+ * @return The normalized input.
+ */
+ Eigen::Vector<double, Inputs> ClampInput(Eigen::Vector<double, Inputs> u) {
+ return frc::NormalizeInputVector<Inputs>(
+ u, frc::RobotController::GetInputVoltage());
+ }
+
LinearSystem<States, Inputs, Outputs> m_plant;
- Eigen::Matrix<double, States, 1> m_x;
- Eigen::Matrix<double, Outputs, 1> m_y;
- Eigen::Matrix<double, Inputs, 1> m_u;
+ Eigen::Vector<double, States> m_x;
+ Eigen::Vector<double, Outputs> m_y;
+ Eigen::Vector<double, Inputs> m_u;
std::array<double, Outputs> m_measurementStdDevs;
};
} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/Mechanism2D.h b/wpilibc/src/main/native/include/frc/simulation/Mechanism2D.h
deleted file mode 100644
index 3d61cf5..0000000
--- a/wpilibc/src/main/native/include/frc/simulation/Mechanism2D.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <map>
-#include <string>
-
-#include <hal/SimDevice.h>
-#include <wpi/StringMap.h>
-
-#include "frc/geometry/Pose2d.h"
-#include "frc/geometry/Rotation2d.h"
-
-namespace frc {
-class Mechanism2D {
- public:
- Mechanism2D();
-
- /**
- * Set/Create the angle of a ligament
- *
- * @param ligamentPath json path to the ligament
- * @param angle to set the ligament
- */
- void SetLigamentAngle(const wpi::Twine& ligamentPath, float angle);
-
- /**
- * Set/Create the length of a ligament
- *
- * @param ligamentPath json path to the ligament
- * @param length to set the ligament
- */
- void SetLigamentLength(const wpi::Twine& ligamentPath, float length);
-
- private:
- wpi::StringMap<hal::SimDouble> createdItems;
- hal::SimDevice m_device;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/PCMSim.h b/wpilibc/src/main/native/include/frc/simulation/PCMSim.h
deleted file mode 100644
index 2e3ed5e..0000000
--- a/wpilibc/src/main/native/include/frc/simulation/PCMSim.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-
-#include "frc/simulation/CallbackStore.h"
-
-namespace frc {
-
-class Compressor;
-
-namespace sim {
-
-/**
- * Class to control a simulated Pneumatic Control Module (PCM).
- */
-class PCMSim {
- public:
- /**
- * Constructs with the default PCM module number (CAN ID).
- */
- PCMSim();
-
- /**
- * Constructs from a PCM module number (CAN ID).
- *
- * @param module module number
- */
- explicit PCMSim(int module);
-
- /**
- * Constructs from a Compressor object.
- *
- * @param compressor Compressor connected to PCM to simulate
- */
- explicit PCMSim(const Compressor& compressor);
-
- std::unique_ptr<CallbackStore> RegisterSolenoidInitializedCallback(
- int channel, NotifyCallback callback, bool initialNotify);
-
- bool GetSolenoidInitialized(int channel) const;
-
- void SetSolenoidInitialized(int channel, bool solenoidInitialized);
-
- std::unique_ptr<CallbackStore> RegisterSolenoidOutputCallback(
- int channel, NotifyCallback callback, bool initialNotify);
-
- bool GetSolenoidOutput(int channel) const;
-
- void SetSolenoidOutput(int channel, bool solenoidOutput);
-
- std::unique_ptr<CallbackStore> RegisterCompressorInitializedCallback(
- NotifyCallback callback, bool initialNotify);
-
- bool GetCompressorInitialized() const;
-
- void SetCompressorInitialized(bool compressorInitialized);
-
- std::unique_ptr<CallbackStore> RegisterCompressorOnCallback(
- NotifyCallback callback, bool initialNotify);
-
- bool GetCompressorOn() const;
-
- void SetCompressorOn(bool compressorOn);
-
- std::unique_ptr<CallbackStore> RegisterClosedLoopEnabledCallback(
- NotifyCallback callback, bool initialNotify);
-
- bool GetClosedLoopEnabled() const;
-
- void SetClosedLoopEnabled(bool closedLoopEnabled);
-
- std::unique_ptr<CallbackStore> RegisterPressureSwitchCallback(
- NotifyCallback callback, bool initialNotify);
-
- bool GetPressureSwitch() const;
-
- void SetPressureSwitch(bool pressureSwitch);
-
- std::unique_ptr<CallbackStore> RegisterCompressorCurrentCallback(
- NotifyCallback callback, bool initialNotify);
-
- double GetCompressorCurrent() const;
-
- void SetCompressorCurrent(double compressorCurrent);
-
- uint8_t GetAllSolenoidOutputs() const;
-
- void SetAllSolenoidOutputs(uint8_t outputs);
-
- void ResetData();
-
- private:
- int m_index;
-};
-} // namespace sim
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/PDPSim.h b/wpilibc/src/main/native/include/frc/simulation/PDPSim.h
deleted file mode 100644
index c67815f..0000000
--- a/wpilibc/src/main/native/include/frc/simulation/PDPSim.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-
-#include "frc/simulation/CallbackStore.h"
-
-namespace frc {
-
-class PowerDistributionPanel;
-
-namespace sim {
-
-/**
- * Class to control a simulated Power Distribution Panel (PDP).
- */
-class PDPSim {
- public:
- /**
- * Constructs from a PDP module number (CAN ID).
- *
- * @param module module number
- */
- explicit PDPSim(int module = 0);
-
- /**
- * Constructs from a PowerDistributionPanel object.
- *
- * @param pdp PowerDistributionPanel to simulate
- */
- explicit PDPSim(const PowerDistributionPanel& pdp);
-
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
- NotifyCallback callback, bool initialNotify);
-
- bool GetInitialized() const;
-
- void SetInitialized(bool initialized);
-
- std::unique_ptr<CallbackStore> RegisterTemperatureCallback(
- NotifyCallback callback, bool initialNotify);
-
- double GetTemperature() const;
-
- void SetTemperature(double temperature);
-
- std::unique_ptr<CallbackStore> RegisterVoltageCallback(
- NotifyCallback callback, bool initialNotify);
-
- double GetVoltage() const;
-
- void SetVoltage(double voltage);
-
- std::unique_ptr<CallbackStore> RegisterCurrentCallback(
- int channel, NotifyCallback callback, bool initialNotify);
-
- double GetCurrent(int channel) const;
-
- void SetCurrent(int channel, double current);
-
- void GetAllCurrents(double* currents) const;
-
- void SetAllCurrents(const double* currents);
-
- void ResetData();
-
- private:
- int m_index;
-};
-} // namespace sim
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/PS4ControllerSim.h b/wpilibc/src/main/native/include/frc/simulation/PS4ControllerSim.h
new file mode 100644
index 0000000..a599ad9
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/PS4ControllerSim.h
@@ -0,0 +1,176 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/simulation/GenericHIDSim.h"
+
+namespace frc {
+
+class PS4Controller;
+
+namespace sim {
+
+/**
+ * Class to control a simulated PS4 controller.
+ */
+class PS4ControllerSim : public GenericHIDSim {
+ public:
+ /**
+ * Constructs from a PS4Controller object.
+ *
+ * @param joystick controller to simulate
+ */
+ explicit PS4ControllerSim(const PS4Controller& joystick);
+
+ /**
+ * Constructs from a joystick port number.
+ *
+ * @param port port number
+ */
+ explicit PS4ControllerSim(int port);
+
+ /**
+ * Change the X axis value of the controller's left stick.
+ *
+ * @param value the new value
+ */
+ void SetLeftX(double value);
+
+ /**
+ * Change the X axis value of the controller's right stick.
+ *
+ * @param value the new value
+ */
+ void SetRightX(double value);
+
+ /**
+ * Change the Y axis value of the controller's left stick.
+ *
+ * @param value the new value
+ */
+ void SetLeftY(double value);
+
+ /**
+ * Change the Y axis value of the controller's right stick.
+ *
+ * @param value the new value
+ */
+ void SetRightY(double value);
+
+ /**
+ * Change the L2 axis axis value of the controller.
+ *
+ * @param value the new value
+ */
+ void SetL2Axis(double value);
+
+ /**
+ * Change the R2 axis value of the controller.
+ *
+ * @param value the new value
+ */
+ void SetR2Axis(double value);
+
+ /**
+ * Change the value of the Square button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetSquareButton(bool value);
+
+ /**
+ * Change the value of the Cross button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetCrossButton(bool value);
+
+ /**
+ * Change the value of the Circle button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetCircleButton(bool value);
+
+ /**
+ * Change the value of the Triangle button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetTriangleButton(bool value);
+
+ /**
+ * Change the value of the L1 button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetL1Button(bool value);
+
+ /**
+ * Change the value of the R1 button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetR1Button(bool value);
+
+ /**
+ * Change the value of the L2 button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetL2Button(bool value);
+
+ /**
+ * Change the value of the R2 button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetR2Button(bool value);
+
+ /**
+ * Change the value of the Share button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetShareButton(bool value);
+
+ /**
+ * Change the value of the Options button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetOptionsButton(bool value);
+
+ /**
+ * Change the value of the L3 (left stick) button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetL3Button(bool value);
+
+ /**
+ * Change the value of the R3 (right stick) button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetR3Button(bool value);
+
+ /**
+ * Change the value of the PS button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetPSButton(bool value);
+
+ /**
+ * Change the value of the touchpad button on the controller.
+ *
+ * @param value the new value
+ */
+ void SetTouchpad(bool value);
+};
+
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/PWMSim.h b/wpilibc/src/main/native/include/frc/simulation/PWMSim.h
index ca2dfca..97e9b1f 100644
--- a/wpilibc/src/main/native/include/frc/simulation/PWMSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/PWMSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -36,48 +33,153 @@
*/
explicit PWMSim(int channel);
- std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ /**
+ * Register a callback to be run when the PWM is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether the PWM has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitialized() const;
+ /**
+ * Define whether the PWM has been initialized.
+ *
+ * @param initialized whether this object is initialized
+ */
void SetInitialized(bool initialized);
- std::unique_ptr<CallbackStore> RegisterRawValueCallback(
+ /**
+ * Register a callback to be run when the PWM raw value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterRawValueCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the PWM raw value.
+ *
+ * @return the PWM raw value
+ */
int GetRawValue() const;
+ /**
+ * Set the PWM raw value.
+ *
+ * @param rawValue the PWM raw value
+ */
void SetRawValue(int rawValue);
- std::unique_ptr<CallbackStore> RegisterSpeedCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run when the PWM speed changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterSpeedCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the PWM speed.
+ *
+ * @return the PWM speed (-1.0 to 1.0)
+ */
double GetSpeed() const;
+ /**
+ * Set the PWM speed.
+ *
+ * @param speed the PWM speed (-1.0 to 1.0)
+ */
void SetSpeed(double speed);
- std::unique_ptr<CallbackStore> RegisterPositionCallback(
+ /**
+ * Register a callback to be run when the PWM position changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPositionCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the PWM position.
+ *
+ * @return the PWM position (0.0 to 1.0)
+ */
double GetPosition() const;
+ /**
+ * Set the PWM position.
+ *
+ * @param position the PWM position (0.0 to 1.0)
+ */
void SetPosition(double position);
- std::unique_ptr<CallbackStore> RegisterPeriodScaleCallback(
+ /**
+ * Register a callback to be run when the PWM period scale changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPeriodScaleCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the PWM period scale.
+ *
+ * @return the PWM period scale
+ */
int GetPeriodScale() const;
+ /**
+ * Set the PWM period scale.
+ *
+ * @param periodScale the PWM period scale
+ */
void SetPeriodScale(int periodScale);
- std::unique_ptr<CallbackStore> RegisterZeroLatchCallback(
+ /**
+ * Register a callback to be run when the PWM zero latch state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterZeroLatchCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether the PWM is zero latched.
+ *
+ * @return true if zero latched
+ */
bool GetZeroLatch() const;
+ /**
+ * Define whether the PWM has been zero latched.
+ *
+ * @param zeroLatch true to indicate zero latched
+ */
void SetZeroLatch(bool zeroLatch);
+ /**
+ * Reset all simulation data.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/PowerDistributionSim.h b/wpilibc/src/main/native/include/frc/simulation/PowerDistributionSim.h
new file mode 100644
index 0000000..ac54da2
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/PowerDistributionSim.h
@@ -0,0 +1,167 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include "frc/simulation/CallbackStore.h"
+
+namespace frc {
+
+class PowerDistribution;
+
+namespace sim {
+
+/**
+ * Class to control a simulated Power Distribution Panel (PowerDistribution).
+ */
+class PowerDistributionSim {
+ public:
+ /**
+ * Constructs from a PowerDistribution module number (CAN ID).
+ *
+ * @param module module number
+ */
+ explicit PowerDistributionSim(int module = 0);
+
+ /**
+ * Constructs from a PowerDistribution object.
+ *
+ * @param pdp PowerDistribution to simulate
+ */
+ explicit PowerDistributionSim(const PowerDistribution& pdp);
+
+ /**
+ * Register a callback to be run when the PowerDistribution is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check whether the PowerDistribution has been initialized.
+ *
+ * @return true if initialized
+ */
+ bool GetInitialized() const;
+
+ /**
+ * Define whether the PowerDistribution has been initialized.
+ *
+ * @param initialized whether this object is initialized
+ */
+ void SetInitialized(bool initialized);
+
+ /**
+ * Register a callback to be run whenever the PowerDistribution temperature
+ * changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterTemperatureCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check the temperature of the PowerDistribution.
+ *
+ * @return the PowerDistribution temperature
+ */
+ double GetTemperature() const;
+
+ /**
+ * Define the PowerDistribution temperature.
+ *
+ * @param temperature the new PowerDistribution temperature
+ */
+ void SetTemperature(double temperature);
+
+ /**
+ * Register a callback to be run whenever the PowerDistribution voltage
+ * changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterVoltageCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check the PowerDistribution voltage.
+ *
+ * @return the PowerDistribution voltage.
+ */
+ double GetVoltage() const;
+
+ /**
+ * Set the PowerDistribution voltage.
+ *
+ * @param voltage the new PowerDistribution voltage
+ */
+ void SetVoltage(double voltage);
+
+ /**
+ * Register a callback to be run whenever the current of a specific channel
+ * changes.
+ *
+ * @param channel the channel
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterCurrentCallback(
+ int channel, NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Read the current in one of the PowerDistribution channels.
+ *
+ * @param channel the channel to check
+ * @return the current in the given channel
+ */
+ double GetCurrent(int channel) const;
+
+ /**
+ * Change the current in the given channel.
+ *
+ * @param channel the channel to edit
+ * @param current the new current for the channel
+ */
+ void SetCurrent(int channel, double current);
+
+ /**
+ * Read the current of all of the PowerDistribution channels.
+ *
+ * @param currents output array; set to the current in each channel. The
+ * array must be big enough to hold all the PowerDistribution
+ * channels
+ * @param length length of output array
+ */
+ void GetAllCurrents(double* currents, int length) const;
+
+ /**
+ * Change the current in all of the PowerDistribution channels.
+ *
+ * @param currents array containing the current values for each channel. The
+ * array must be big enough to hold all the PowerDistribution
+ * channels
+ * @param length length of array
+ */
+ void SetAllCurrents(const double* currents, int length);
+
+ /**
+ * Reset all PowerDistribution simulation data.
+ */
+ void ResetData();
+
+ private:
+ int m_index;
+};
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/REVPHSim.h b/wpilibc/src/main/native/include/frc/simulation/REVPHSim.h
new file mode 100644
index 0000000..97e31bf
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/REVPHSim.h
@@ -0,0 +1,212 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+
+#include "frc/PneumaticsBase.h"
+#include "frc/simulation/CallbackStore.h"
+
+namespace frc {
+
+class Compressor;
+
+namespace sim {
+
+/**
+ * Class to control a simulated Pneumatic Control Module (PCM).
+ */
+class REVPHSim {
+ public:
+ /**
+ * Constructs with the default PCM module number (CAN ID).
+ */
+ REVPHSim();
+
+ /**
+ * Constructs from a PCM module number (CAN ID).
+ *
+ * @param module module number
+ */
+ explicit REVPHSim(int module);
+
+ explicit REVPHSim(const PneumaticsBase& pneumatics);
+
+ /**
+ * Register a callback to be run when a solenoid is initialized on a channel.
+ *
+ * @param callback the callback
+ * @param initialNotify should the callback be run with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterInitializedCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check if a solenoid has been initialized on a specific channel.
+ *
+ * @return true if initialized
+ */
+ bool GetInitialized() const;
+
+ /**
+ * Define whether a solenoid has been initialized on a specific channel.
+ *
+ * @param solenoidInitialized is there a solenoid initialized on that channel
+ */
+ void SetInitialized(bool solenoidInitialized);
+
+ /**
+ * Register a callback to be run when the solenoid output on a channel
+ * changes.
+ *
+ * @param channel the channel to monitor
+ * @param callback the callback
+ * @param initialNotify should the callback be run with the initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterSolenoidOutputCallback(
+ int channel, NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check the solenoid output on a specific channel.
+ *
+ * @param channel the channel to check
+ * @return the solenoid output
+ */
+ bool GetSolenoidOutput(int channel) const;
+
+ /**
+ * Change the solenoid output on a specific channel.
+ *
+ * @param channel the channel to check
+ * @param solenoidOutput the new solenoid output
+ */
+ void SetSolenoidOutput(int channel, bool solenoidOutput);
+
+ /**
+ * Register a callback to be run when the compressor activates.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterCompressorOnCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check if the compressor is on.
+ *
+ * @return true if the compressor is active
+ */
+ bool GetCompressorOn() const;
+
+ /**
+ * Set whether the compressor is active.
+ *
+ * @param compressorOn the new value
+ */
+ void SetCompressorOn(bool compressorOn);
+
+ /**
+ * Register a callback to be run whenever the closed loop state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterClosedLoopEnabledCallback(NotifyCallback callback,
+ bool initialNotify);
+
+ /**
+ * Check whether the closed loop compressor control is active.
+ *
+ * @return true if active
+ */
+ bool GetClosedLoopEnabled() const;
+
+ /**
+ * Turn on/off the closed loop control of the compressor.
+ *
+ * @param closedLoopEnabled whether the control loop is active
+ */
+ void SetClosedLoopEnabled(bool closedLoopEnabled);
+
+ /**
+ * Register a callback to be run whenever the pressure switch value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterPressureSwitchCallback(
+ NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Check the value of the pressure switch.
+ *
+ * @return the pressure switch value
+ */
+ bool GetPressureSwitch() const;
+
+ /**
+ * Set the value of the pressure switch.
+ *
+ * @param pressureSwitch the new value
+ */
+ void SetPressureSwitch(bool pressureSwitch);
+
+ /**
+ * Register a callback to be run whenever the compressor current changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterCompressorCurrentCallback(NotifyCallback callback,
+ bool initialNotify);
+
+ /**
+ * Read the compressor current.
+ *
+ * @return the current of the compressor connected to this module
+ */
+ double GetCompressorCurrent() const;
+
+ /**
+ * Set the compressor current.
+ *
+ * @param compressorCurrent the new compressor current
+ */
+ void SetCompressorCurrent(double compressorCurrent);
+
+ /**
+ * Get the current value of all solenoid outputs.
+ *
+ * @return the solenoid outputs (1 bit per output)
+ */
+ uint8_t GetAllSolenoidOutputs() const;
+
+ /**
+ * Change all of the solenoid outputs.
+ *
+ * @param outputs the new solenoid outputs (1 bit per output)
+ */
+ void SetAllSolenoidOutputs(uint8_t outputs);
+
+ /**
+ * Reset all simulation data for this object.
+ */
+ void ResetData();
+
+ private:
+ int m_index;
+};
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/RelaySim.h b/wpilibc/src/main/native/include/frc/simulation/RelaySim.h
index 99a8eef..5034885 100644
--- a/wpilibc/src/main/native/include/frc/simulation/RelaySim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/RelaySim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -36,34 +33,107 @@
*/
explicit RelaySim(int channel);
- std::unique_ptr<CallbackStore> RegisterInitializedForwardCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run when the forward direction is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterInitializedForwardCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Check whether the forward direction has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitializedForward() const;
+ /**
+ * Define whether the forward direction has been initialized.
+ *
+ * @param initializedForward whether this object is initialized
+ */
void SetInitializedForward(bool initializedForward);
- std::unique_ptr<CallbackStore> RegisterInitializedReverseCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run when the reverse direction is initialized.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore>
+ RegisterInitializedReverseCallback(NotifyCallback callback,
+ bool initialNotify);
+ /**
+ * Check whether the reverse direction has been initialized.
+ *
+ * @return true if initialized
+ */
bool GetInitializedReverse() const;
+ /**
+ * Define whether the reverse direction has been initialized.
+ *
+ * @param initializedReverse whether this object is initialized
+ */
void SetInitializedReverse(bool initializedReverse);
- std::unique_ptr<CallbackStore> RegisterForwardCallback(
+ /**
+ * Register a callback to be run when the forward direction changes state.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterForwardCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether the forward direction is active.
+ *
+ * @return true if active
+ */
bool GetForward() const;
+ /**
+ * Set whether the forward direction is active.
+ *
+ * @param forward true to make active
+ */
void SetForward(bool forward);
- std::unique_ptr<CallbackStore> RegisterReverseCallback(
+ /**
+ * Register a callback to be run when the reverse direction changes state.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterReverseCallback(
NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether the reverse direction is active.
+ *
+ * @return true if active
+ */
bool GetReverse() const;
+ /**
+ * Set whether the reverse direction is active.
+ *
+ * @param reverse true to make active
+ */
void SetReverse(bool reverse);
+ /**
+ * Reset all simulation data.
+ */
void ResetData();
private:
diff --git a/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h b/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h
index 32eb462..1095106 100644
--- a/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/RoboRioSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -14,120 +11,416 @@
#include "frc/simulation/CallbackStore.h"
-namespace frc {
-namespace sim {
+namespace frc::sim {
/**
- * Class to control a simulated RoboRIO.
+ * A utility class to control a simulated RoboRIO.
*/
class RoboRioSim {
public:
- static std::unique_ptr<CallbackStore> RegisterFPGAButtonCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run when the FPGA button state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterFPGAButtonCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Query the state of the FPGA button.
+ *
+ * @return the FPGA button state
+ */
static bool GetFPGAButton();
+ /**
+ * Define the state of the FPGA button.
+ *
+ * @param fPGAButton the new state
+ */
static void SetFPGAButton(bool fPGAButton);
- static std::unique_ptr<CallbackStore> RegisterVInVoltageCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the Vin voltage changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterVInVoltageCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the Vin voltage.
+ *
+ * @return the Vin voltage
+ */
static units::volt_t GetVInVoltage();
+ /**
+ * Define the Vin voltage.
+ *
+ * @param vInVoltage the new voltage
+ */
static void SetVInVoltage(units::volt_t vInVoltage);
- static std::unique_ptr<CallbackStore> RegisterVInCurrentCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the Vin current changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterVInCurrentCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the Vin current.
+ *
+ * @return the Vin current
+ */
static units::ampere_t GetVInCurrent();
+ /**
+ * Define the Vin current.
+ *
+ * @param vInCurrent the new current
+ */
static void SetVInCurrent(units::ampere_t vInCurrent);
- static std::unique_ptr<CallbackStore> RegisterUserVoltage6VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 6V rail voltage changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserVoltage6VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the 6V rail voltage.
+ *
+ * @return the 6V rail voltage
+ */
static units::volt_t GetUserVoltage6V();
+ /**
+ * Define the 6V rail voltage.
+ *
+ * @param userVoltage6V the new voltage
+ */
static void SetUserVoltage6V(units::volt_t userVoltage6V);
- static std::unique_ptr<CallbackStore> RegisterUserCurrent6VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 6V rail current changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserCurrent6VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the 6V rail current.
+ *
+ * @return the 6V rail current
+ */
static units::ampere_t GetUserCurrent6V();
+ /**
+ * Define the 6V rail current.
+ *
+ * @param userCurrent6V the new current
+ */
static void SetUserCurrent6V(units::ampere_t userCurrent6V);
- static std::unique_ptr<CallbackStore> RegisterUserActive6VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 6V rail active state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserActive6VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the 6V rail active state.
+ *
+ * @return true if the 6V rail is active
+ */
static bool GetUserActive6V();
+ /**
+ * Set the 6V rail active state.
+ *
+ * @param userActive6V true to make rail active
+ */
static void SetUserActive6V(bool userActive6V);
- static std::unique_ptr<CallbackStore> RegisterUserVoltage5VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 5V rail voltage changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserVoltage5VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the 5V rail voltage.
+ *
+ * @return the 5V rail voltage
+ */
static units::volt_t GetUserVoltage5V();
+ /**
+ * Define the 5V rail voltage.
+ *
+ * @param userVoltage5V the new voltage
+ */
static void SetUserVoltage5V(units::volt_t userVoltage5V);
- static std::unique_ptr<CallbackStore> RegisterUserCurrent5VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 5V rail current changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserCurrent5VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the 5V rail current.
+ *
+ * @return the 5V rail current
+ */
static units::ampere_t GetUserCurrent5V();
+ /**
+ * Define the 5V rail current.
+ *
+ * @param userCurrent5V the new current
+ */
static void SetUserCurrent5V(units::ampere_t userCurrent5V);
- static std::unique_ptr<CallbackStore> RegisterUserActive5VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 5V rail active state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserActive5VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the 5V rail active state.
+ *
+ * @return true if the 5V rail is active
+ */
static bool GetUserActive5V();
+ /**
+ * Set the 5V rail active state.
+ *
+ * @param userActive5V true to make rail active
+ */
static void SetUserActive5V(bool userActive5V);
- static std::unique_ptr<CallbackStore> RegisterUserVoltage3V3Callback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 3.3V rail voltage changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserVoltage3V3Callback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the 3.3V rail voltage.
+ *
+ * @return the 3.3V rail voltage
+ */
static units::volt_t GetUserVoltage3V3();
+ /**
+ * Define the 3.3V rail voltage.
+ *
+ * @param userVoltage3V3 the new voltage
+ */
static void SetUserVoltage3V3(units::volt_t userVoltage3V3);
- static std::unique_ptr<CallbackStore> RegisterUserCurrent3V3Callback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 3.3V rail current changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserCurrent3V3Callback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the 3.3V rail current.
+ *
+ * @return the 3.3V rail current
+ */
static units::ampere_t GetUserCurrent3V3();
+ /**
+ * Define the 3.3V rail current.
+ *
+ * @param userCurrent3V3 the new current
+ */
static void SetUserCurrent3V3(units::ampere_t userCurrent3V3);
- static std::unique_ptr<CallbackStore> RegisterUserActive3V3Callback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 3.3V rail active state changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserActive3V3Callback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the 3.3V rail active state.
+ *
+ * @return true if the 3.3V rail is active
+ */
static bool GetUserActive3V3();
+ /**
+ * Set the 3.3V rail active state.
+ *
+ * @param userActive3V3 true to make rail active
+ */
static void SetUserActive3V3(bool userActive3V3);
- static std::unique_ptr<CallbackStore> RegisterUserFaults6VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 6V rail number of faults
+ * changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserFaults6VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the 6V rail number of faults.
+ *
+ * @return number of faults
+ */
static int GetUserFaults6V();
+ /**
+ * Set the 6V rail number of faults.
+ *
+ * @param userFaults6V number of faults
+ */
static void SetUserFaults6V(int userFaults6V);
- static std::unique_ptr<CallbackStore> RegisterUserFaults5VCallback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 5V rail number of faults
+ * changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserFaults5VCallback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the 5V rail number of faults.
+ *
+ * @return number of faults
+ */
static int GetUserFaults5V();
+ /**
+ * Set the 5V rail number of faults.
+ *
+ * @param userFaults5V number of faults
+ */
static void SetUserFaults5V(int userFaults5V);
- static std::unique_ptr<CallbackStore> RegisterUserFaults3V3Callback(
- NotifyCallback callback, bool initialNotify);
+ /**
+ * Register a callback to be run whenever the 3.3V rail number of faults
+ * changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether the callback should be called with the
+ * initial value
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterUserFaults3V3Callback(NotifyCallback callback, bool initialNotify);
+ /**
+ * Get the 3.3V rail number of faults.
+ *
+ * @return number of faults
+ */
static int GetUserFaults3V3();
+ /**
+ * Set the 3.3V rail number of faults.
+ *
+ * @param userFaults3V3 number of faults
+ */
static void SetUserFaults3V3(int userFaults3V3);
+ /**
+ * Register a callback to be run whenever the brownout voltage changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] static std::unique_ptr<CallbackStore>
+ RegisterBrownoutVoltageCallback(NotifyCallback callback, bool initialNotify);
+
+ /**
+ * Measure the brownout voltage.
+ *
+ * @return the brownout voltage
+ */
+ static units::volt_t GetBrownoutVoltage();
+
+ /**
+ * Define the brownout voltage.
+ *
+ * @param brownoutVoltage the new voltage
+ */
+ static void SetBrownoutVoltage(units::volt_t brownoutVoltage);
+
+ /**
+ * Reset all simulation data.
+ */
static void ResetData();
};
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/SPIAccelerometerSim.h b/wpilibc/src/main/native/include/frc/simulation/SPIAccelerometerSim.h
index f2e3249..9d31bd0 100644
--- a/wpilibc/src/main/native/include/frc/simulation/SPIAccelerometerSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/SPIAccelerometerSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -11,51 +8,142 @@
#include "frc/simulation/CallbackStore.h"
-namespace frc {
-namespace sim {
+namespace frc::sim {
class SPIAccelerometerSim {
public:
+ /**
+ * Construct a new simulation object.
+ *
+ * @param index the HAL index of the accelerometer
+ */
explicit SPIAccelerometerSim(int index);
- std::unique_ptr<CallbackStore> RegisterActiveCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run when this accelerometer activates.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to run the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterActiveCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Check whether the accelerometer is active.
+ *
+ * @return true if active
+ */
bool GetActive() const;
+ /**
+ * Define whether this accelerometer is active.
+ *
+ * @param active the new state
+ */
void SetActive(bool active);
- std::unique_ptr<CallbackStore> RegisterRangeCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the range changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterRangeCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Check the range of this accelerometer.
+ *
+ * @return the accelerometer range
+ */
int GetRange() const;
+ /**
+ * Change the range of this accelerometer.
+ *
+ * @param range the new accelerometer range
+ */
void SetRange(int range);
- std::unique_ptr<CallbackStore> RegisterXCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the X axis value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterXCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the X axis value.
+ *
+ * @return the X axis measurement
+ */
double GetX() const;
+ /**
+ * Change the X axis value of the accelerometer.
+ *
+ * @param x the new reading of the X axis
+ */
void SetX(double x);
- std::unique_ptr<CallbackStore> RegisterYCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the Y axis value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterYCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the Y axis value.
+ *
+ * @return the Y axis measurement
+ */
double GetY() const;
+ /**
+ * Change the Y axis value of the accelerometer.
+ *
+ * @param y the new reading of the Y axis
+ */
void SetY(double y);
- std::unique_ptr<CallbackStore> RegisterZCallback(NotifyCallback callback,
- bool initialNotify);
+ /**
+ * Register a callback to be run whenever the Z axis value changes.
+ *
+ * @param callback the callback
+ * @param initialNotify whether to call the callback with the initial state
+ * @return the CallbackStore object associated with this callback
+ */
+ [[nodiscard]] std::unique_ptr<CallbackStore> RegisterZCallback(
+ NotifyCallback callback, bool initialNotify);
+ /**
+ * Measure the Z axis value.
+ *
+ * @return the Z axis measurement
+ */
double GetZ() const;
+ /**
+ * Change the Z axis value of the accelerometer.
+ *
+ * @param z the new reading of the Z axis
+ */
void SetZ(double z);
+ /**
+ * Reset all simulation data of this object.
+ */
void ResetData();
private:
int m_index;
};
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/SimDeviceSim.h b/wpilibc/src/main/native/include/frc/simulation/SimDeviceSim.h
index 640cc0e..0a4e4d8 100644
--- a/wpilibc/src/main/native/include/frc/simulation/SimDeviceSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/SimDeviceSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -14,8 +11,7 @@
#include <hal/SimDevice.h>
#include <hal/simulation/SimDeviceData.h>
-namespace frc {
-namespace sim {
+namespace frc::sim {
/**
* Class to control the simulation side of a SimDevice.
@@ -29,28 +25,109 @@
*/
explicit SimDeviceSim(const char* name);
+ /**
+ * Constructs a SimDeviceSim.
+ *
+ * @param name name of the SimDevice
+ * @param index device index number to append to name
+ */
+ SimDeviceSim(const char* name, int index);
+
+ /**
+ * Constructs a SimDeviceSim.
+ *
+ * @param name name of the SimDevice
+ * @param index device index number to append to name
+ * @param channel device channel number to append to name
+ */
+ SimDeviceSim(const char* name, int index, int channel);
+
+ /**
+ * Get the property object with the given name.
+ *
+ * @param name the property name
+ * @return the property object
+ */
hal::SimValue GetValue(const char* name) const;
+ /**
+ * Get the property object with the given name.
+ *
+ * @param name the property name
+ * @return the property object
+ */
+ hal::SimInt GetInt(const char* name) const;
+
+ /**
+ * Get the property object with the given name.
+ *
+ * @param name the property name
+ * @return the property object
+ */
+ hal::SimLong GetLong(const char* name) const;
+
+ /**
+ * Get the property object with the given name.
+ *
+ * @param name the property name
+ * @return the property object
+ */
hal::SimDouble GetDouble(const char* name) const;
+ /**
+ * Get the property object with the given name.
+ *
+ * @param name the property name
+ * @return the property object
+ */
hal::SimEnum GetEnum(const char* name) const;
+ /**
+ * Get the property object with the given name.
+ *
+ * @param name the property name
+ * @return the property object
+ */
hal::SimBoolean GetBoolean(const char* name) const;
+ /**
+ * Get all options for the given enum.
+ *
+ * @param val the enum
+ * @return names of the different values for that enum
+ */
static std::vector<std::string> GetEnumOptions(hal::SimEnum val);
+ /**
+ * Get all properties.
+ *
+ * @param callback callback called for each property (SimValue). Signature
+ * of the callback must be const char*, HAL_SimValueHandle,
+ * int, const HAL_Value*
+ */
template <typename F>
void EnumerateValues(F callback) const {
return HALSIM_EnumerateSimValues(
m_handle, &callback,
[](const char* name, void* param, HAL_SimValueHandle handle,
- HAL_Bool readonly, const struct HAL_Value* value) {
- std::invoke(*static_cast<F*>(param), name, handle, readonly, value);
+ int direction, const struct HAL_Value* value) {
+ std::invoke(*static_cast<F*>(param), name, handle, direction, value);
});
}
- operator HAL_SimDeviceHandle() const { return m_handle; }
+ /**
+ * Get the raw handle of this object.
+ *
+ * @return the handle used to refer to this object
+ */
+ operator HAL_SimDeviceHandle() const { return m_handle; } // NOLINT
+ /**
+ * Get all sim devices with the given prefix.
+ *
+ * @param prefix the prefix to filter sim devices
+ * @param callback callback function to call for each sim device
+ */
template <typename F>
static void EnumerateDevices(const char* prefix, F callback) {
return HALSIM_EnumerateSimDevices(
@@ -60,10 +137,12 @@
});
}
+ /**
+ * Reset all SimDevice data.
+ */
static void ResetData();
private:
HAL_SimDeviceHandle m_handle;
};
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/SimHooks.h b/wpilibc/src/main/native/include/frc/simulation/SimHooks.h
index 7690a4f..5d8a6b4 100644
--- a/wpilibc/src/main/native/include/frc/simulation/SimHooks.h
+++ b/wpilibc/src/main/native/include/frc/simulation/SimHooks.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -12,9 +9,13 @@
#include <hal/HALBase.h>
#include <units/time.h>
-namespace frc {
-namespace sim {
+namespace frc::sim {
+/**
+ * Override the HAL runtime type (simulated/real).
+ *
+ * @param type runtime type
+ */
void SetRuntimeType(HAL_RuntimeType type);
void WaitForProgramStart();
@@ -23,17 +24,40 @@
bool GetProgramStarted();
+/**
+ * Restart the simulator time.
+ */
void RestartTiming();
+/**
+ * Pause the simulator time.
+ */
void PauseTiming();
+/**
+ * Resume the simulator time.
+ */
void ResumeTiming();
+/**
+ * Check if the simulator time is paused.
+ *
+ * @return true if paused
+ */
bool IsTimingPaused();
+/**
+ * Advance the simulator time and wait for all notifiers to run.
+ *
+ * @param delta the amount to advance (in seconds)
+ */
void StepTiming(units::second_t delta);
+/**
+ * Advance the simulator time and return immediately.
+ *
+ * @param delta the amount to advance (in seconds)
+ */
void StepTimingAsync(units::second_t delta);
-} // namespace sim
-} // namespace frc
+} // namespace frc::sim
diff --git a/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h b/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h
index f8de822..4ff29cc 100644
--- a/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/SingleJointedArmSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -66,20 +63,34 @@
const std::array<double, 1>& measurementStdDevs = {0.0});
/**
+ * Returns whether the arm would hit the lower limit.
+ *
+ * @param armAngle The arm height.
+ * @return Whether the arm would hit the lower limit.
+ */
+ bool WouldHitLowerLimit(units::radian_t armAngle) const;
+
+ /**
+ * Returns whether the arm would hit the upper limit.
+ *
+ * @param armAngle The arm height.
+ * @return Whether the arm would hit the upper limit.
+ */
+ bool WouldHitUpperLimit(units::radian_t armAngle) const;
+
+ /**
* Returns whether the arm has hit the lower limit.
*
- * @param x The current arm state.
* @return Whether the arm has hit the lower limit.
*/
- bool HasHitLowerLimit(const Eigen::Matrix<double, 2, 1>& x) const;
+ bool HasHitLowerLimit() const;
/**
* Returns whether the arm has hit the upper limit.
*
- * @param x The current arm state.
* @return Whether the arm has hit the upper limit.
*/
- bool HasHitUpperLimit(const Eigen::Matrix<double, 2, 1>& x) const;
+ bool HasHitUpperLimit() const;
/**
* Returns the current arm angle.
@@ -103,7 +114,7 @@
units::ampere_t GetCurrentDraw() const override;
/**
- * Sets the input voltage for the elevator.
+ * Sets the input voltage for the arm.
*
* @param voltage The input voltage.
*/
@@ -131,9 +142,9 @@
* @param u The system inputs (voltage).
* @param dt The time difference between controller updates.
*/
- Eigen::Matrix<double, 2, 1> UpdateX(
- const Eigen::Matrix<double, 2, 1>& currentXhat,
- const Eigen::Matrix<double, 1, 1>& u, units::second_t dt) override;
+ Eigen::Vector<double, 2> UpdateX(const Eigen::Vector<double, 2>& currentXhat,
+ const Eigen::Vector<double, 1>& u,
+ units::second_t dt) override;
private:
units::meter_t m_r;
diff --git a/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h b/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h
new file mode 100644
index 0000000..efa9b37
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/simulation/UltrasonicSim.h
@@ -0,0 +1,48 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <hal/SimDevice.h>
+#include <units/length.h>
+
+namespace frc {
+
+class Ultrasonic;
+
+namespace sim {
+
+/**
+ * Class to control a simulated ADXRS450 gyroscope.
+ */
+class UltrasonicSim {
+ public:
+ /**
+ * Constructs from a ADXRS450_Gyro object.
+ *
+ * @param gyro ADXRS450_Gyro to simulate
+ */
+ explicit UltrasonicSim(const Ultrasonic& gyro);
+
+ /**
+ * Sets if the range measurement is valid.
+ *
+ * @param isValid True if valid
+ */
+ void SetRangeValid(bool isValid);
+
+ /**
+ * Sets the range measurement
+ *
+ * @param range The range
+ */
+ void SetRange(units::meter_t range);
+
+ private:
+ hal::SimBoolean m_simRangeValid;
+ hal::SimDouble m_simRange;
+};
+
+} // namespace sim
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/simulation/XboxControllerSim.h b/wpilibc/src/main/native/include/frc/simulation/XboxControllerSim.h
index d981111..e609ff0 100644
--- a/wpilibc/src/main/native/include/frc/simulation/XboxControllerSim.h
+++ b/wpilibc/src/main/native/include/frc/simulation/XboxControllerSim.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -34,27 +31,117 @@
*/
explicit XboxControllerSim(int port);
- void SetX(GenericHID::JoystickHand hand, double value);
+ /**
+ * Change the X axis value of the controller's left stick.
+ *
+ * @param value the new value
+ */
+ void SetLeftX(double value);
- void SetY(GenericHID::JoystickHand hand, double value);
+ /**
+ * Change the X axis value of the controller's right stick.
+ *
+ * @param value the new value
+ */
+ void SetRightX(double value);
- void SetTriggerAxis(GenericHID::JoystickHand hand, double value);
+ /**
+ * Change the Y axis value of the controller's left stick.
+ *
+ * @param value the new value
+ */
+ void SetLeftY(double value);
- void SetBumper(GenericHID::JoystickHand hand, bool state);
+ /**
+ * Change the Y axis value of the controller's right stick.
+ *
+ * @param value the new value
+ */
+ void SetRightY(double value);
- void SetStickButton(GenericHID::JoystickHand hand, bool state);
+ /**
+ * Change the left trigger axis value of the joystick.
+ *
+ * @param value the new value
+ */
+ void SetLeftTriggerAxis(double value);
- void SetAButton(bool state);
+ /**
+ * Change the right trigger axis value of the joystick.
+ *
+ * @param value the new value
+ */
+ void SetRightTriggerAxis(double value);
- void SetBButton(bool state);
+ /**
+ * Change the left bumper value of the joystick.
+ *
+ * @param value the new value
+ */
+ void SetLeftBumper(bool value);
- void SetXButton(bool state);
+ /**
+ * Change the right bumper value of the joystick.
+ *
+ * @param value the new value
+ */
+ void SetRightBumper(bool value);
- void SetYButton(bool state);
+ /**
+ * Change the left button value of the joystick.
+ *
+ * @param value the new value
+ */
+ void SetLeftStickButton(bool value);
- void SetBackButton(bool state);
+ /**
+ * Change the right button value of the joystick.
+ *
+ * @param value the new value
+ */
+ void SetRightStickButton(bool value);
- void SetStartButton(bool state);
+ /**
+ * Change the value of the A button.
+ *
+ * @param value the new value
+ */
+ void SetAButton(bool value);
+
+ /**
+ * Change the value of the B button.
+ *
+ * @param value the new value
+ */
+ void SetBButton(bool value);
+
+ /**
+ * Change the value of the X button.
+ *
+ * @param value the new value
+ */
+ void SetXButton(bool value);
+
+ /**
+ * Change the value of the Y button.
+ *
+ * @param value the new value
+ */
+ void SetYButton(bool value);
+
+ /**
+ * Change the value of the Back button.
+ *
+ * @param value the new value
+ */
+ void SetBackButton(bool value);
+
+ /**
+ * Change the value of the Start button.
+ *
+ * @param value the new value
+ */
+ void SetStartButton(bool value);
};
} // namespace sim
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/Field2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/Field2d.h
new file mode 100644
index 0000000..61d7a72
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/Field2d.h
@@ -0,0 +1,97 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+#include <string_view>
+#include <vector>
+
+#include <networktables/NTSendable.h>
+#include <networktables/NetworkTable.h>
+#include <networktables/NetworkTableEntry.h>
+#include <units/length.h>
+#include <wpi/mutex.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/geometry/Pose2d.h"
+#include "frc/geometry/Rotation2d.h"
+#include "frc/smartdashboard/FieldObject2d.h"
+
+namespace frc {
+
+/**
+ * 2D representation of game field for dashboards.
+ *
+ * An object's pose is the location shown on the dashboard view. Note that
+ * for the robot, this may or may not match the internal odometry. For example,
+ * if the robot is shown at a particular starting location, the pose in this
+ * class would represent the actual location on the field, but the robot's
+ * internal state might have a 0,0,0 pose (unless it's initialized to
+ * something different).
+ *
+ * As the user is able to edit the pose, code performing updates should get
+ * the robot pose, transform it as appropriate (e.g. based on wheel odometry),
+ * and set the new pose.
+ *
+ * This class provides methods to set the robot pose, but other objects can
+ * also be shown by using the GetObject() function. Other objects can
+ * also have multiple poses (which will show the object at multiple locations).
+ */
+class Field2d : public nt::NTSendable, public wpi::SendableHelper<Field2d> {
+ public:
+ using Entry = size_t;
+
+ Field2d();
+
+ Field2d(Field2d&& rhs);
+ Field2d& operator=(Field2d&& rhs);
+
+ /**
+ * Set the robot pose from a Pose object.
+ *
+ * @param pose 2D pose
+ */
+ void SetRobotPose(const Pose2d& pose);
+
+ /**
+ * Set the robot pose from x, y, and rotation.
+ *
+ * @param x X location
+ * @param y Y location
+ * @param rotation rotation
+ */
+ void SetRobotPose(units::meter_t x, units::meter_t y, Rotation2d rotation);
+
+ /**
+ * Get the robot pose.
+ *
+ * @return 2D pose
+ */
+ Pose2d GetRobotPose() const;
+
+ /**
+ * Get or create a field object.
+ *
+ * @return Field object
+ */
+ FieldObject2d* GetObject(std::string_view name);
+
+ /**
+ * Get the robot object.
+ *
+ * @return Field object for robot
+ */
+ FieldObject2d* GetRobotObject();
+
+ void InitSendable(nt::NTSendableBuilder& builder) override;
+
+ private:
+ std::shared_ptr<nt::NetworkTable> m_table;
+
+ mutable wpi::mutex m_mutex;
+ std::vector<std::unique_ptr<FieldObject2d>> m_objects;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h
new file mode 100644
index 0000000..2e41d84
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/FieldObject2d.h
@@ -0,0 +1,112 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <initializer_list>
+#include <string>
+#include <string_view>
+#include <utility>
+#include <vector>
+
+#include <networktables/NetworkTableEntry.h>
+#include <units/length.h>
+#include <wpi/SmallVector.h>
+#include <wpi/mutex.h>
+#include <wpi/span.h>
+
+#include "frc/geometry/Pose2d.h"
+#include "frc/geometry/Rotation2d.h"
+
+namespace frc {
+
+class Field2d;
+class Trajectory;
+
+/**
+ * Game field object on a Field2d.
+ */
+class FieldObject2d {
+ friend class Field2d;
+ struct private_init {};
+
+ public:
+ FieldObject2d(std::string_view name, const private_init&) : m_name{name} {}
+
+ FieldObject2d(FieldObject2d&& rhs);
+ FieldObject2d& operator=(FieldObject2d&& rhs);
+
+ /**
+ * Set the pose from a Pose object.
+ *
+ * @param pose 2D pose
+ */
+ void SetPose(const Pose2d& pose);
+
+ /**
+ * Set the pose from x, y, and rotation.
+ *
+ * @param x X location
+ * @param y Y location
+ * @param rotation rotation
+ */
+ void SetPose(units::meter_t x, units::meter_t y, Rotation2d rotation);
+
+ /**
+ * Get the pose.
+ *
+ * @return 2D pose, or 0,0,0 if unknown / does not exist
+ */
+ Pose2d GetPose() const;
+
+ /**
+ * Set multiple poses from an array of Pose objects.
+ * The total number of poses is limited to 85.
+ *
+ * @param poses array of 2D poses
+ */
+ void SetPoses(wpi::span<const Pose2d> poses);
+
+ /**
+ * Set multiple poses from an array of Pose objects.
+ * The total number of poses is limited to 85.
+ *
+ * @param poses array of 2D poses
+ */
+ void SetPoses(std::initializer_list<Pose2d> poses);
+
+ /**
+ * Sets poses from a trajectory.
+ *
+ * @param trajectory The trajectory from which poses should be added.
+ */
+ void SetTrajectory(const Trajectory& trajectory);
+
+ /**
+ * Get multiple poses.
+ *
+ * @param obj Object entry
+ * @return vector of 2D poses
+ */
+ std::vector<Pose2d> GetPoses() const;
+
+ /**
+ * Get multiple poses.
+ *
+ * @param out output SmallVector to hold 2D poses
+ * @return span referring to output SmallVector
+ */
+ wpi::span<const Pose2d> GetPoses(wpi::SmallVectorImpl<Pose2d>& out) const;
+
+ private:
+ void UpdateEntry(bool setDefault = false);
+ void UpdateFromEntry() const;
+
+ mutable wpi::mutex m_mutex;
+ std::string m_name;
+ nt::NetworkTableEntry m_entry;
+ mutable wpi::SmallVector<Pose2d, 1> m_poses;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/ListenerExecutor.h b/wpilibc/src/main/native/include/frc/smartdashboard/ListenerExecutor.h
index 9500278..cdfdafd 100644
--- a/wpilibc/src/main/native/include/frc/smartdashboard/ListenerExecutor.h
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/ListenerExecutor.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h
new file mode 100644
index 0000000..cbe25be
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h
@@ -0,0 +1,87 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include <networktables/NTSendable.h>
+#include <networktables/NetworkTableEntry.h>
+#include <wpi/StringMap.h>
+#include <wpi/mutex.h>
+#include <wpi/sendable/SendableHelper.h>
+
+#include "frc/smartdashboard/MechanismRoot2d.h"
+#include "frc/util/Color8Bit.h"
+
+namespace frc {
+
+/**
+ * Visual 2D representation of arms, elevators, and general mechanisms through
+ * a node-based API.
+ *
+ * A Mechanism2d object is published and contains at least one root node. A root
+ * is the anchor point of other nodes (such as ligaments). Other nodes are
+ * recursively appended based on other nodes.
+ *
+ * Except for the Mechanism2d container object, none of the objects should be
+ * passed or interacted with by value! Obtain pointers from factory methods such
+ * as Mechanism2d.GetRoot() and MechanismObject2d.Append<>(). The Mechanism2d
+ * container object owns the root nodes, and each node internally owns the nodes
+ * based on it. Beware not to let the Mechanism2d object out of scope - all
+ * nodes will be recursively destructed!
+ *
+ * @see MechanismObject2d
+ * @see MechanismLigament2d
+ * @see MechanismRoot2d
+ */
+class Mechanism2d : public nt::NTSendable,
+ public wpi::SendableHelper<Mechanism2d> {
+ public:
+ /**
+ * Create a new Mechanism2d with the given dimensions and background color.
+ *
+ * The dimensions represent the canvas that all the nodes are drawn on. The
+ * default color is dark blue.
+ *
+ * @param width the width
+ * @param height the height
+ * @param backgroundColor the background color
+ */
+ Mechanism2d(double width, double height,
+ const Color8Bit& backgroundColor = {0, 0, 32});
+
+ /**
+ * Get or create a root in this Mechanism2d with the given name and
+ * position.
+ *
+ * <p>If a root with the given name already exists, the given x and y
+ * coordinates are not used.
+ *
+ * @param name the root name
+ * @param x the root x coordinate
+ * @param y the root y coordinate
+ * @return a new root object, or the existing one with the given name.
+ */
+ MechanismRoot2d* GetRoot(std::string_view name, double x, double y);
+
+ /**
+ * Set the Mechanism2d background color.
+ *
+ * @param color the new background color
+ */
+ void SetBackgroundColor(const Color8Bit& color);
+
+ void InitSendable(nt::NTSendableBuilder& builder) override;
+
+ private:
+ double m_width;
+ double m_height;
+ char m_color[10];
+ mutable wpi::mutex m_mutex;
+ std::shared_ptr<nt::NetworkTable> m_table;
+ wpi::StringMap<std::unique_ptr<MechanismRoot2d>> m_roots;
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/MechanismLigament2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismLigament2d.h
new file mode 100644
index 0000000..70abaa6
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismLigament2d.h
@@ -0,0 +1,88 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+#include <string_view>
+
+#include <networktables/NetworkTableEntry.h>
+#include <units/angle.h>
+
+#include "frc/smartdashboard/MechanismObject2d.h"
+#include "frc/util/Color8Bit.h"
+
+namespace frc {
+
+/**
+ * Ligament node on a Mechanism2d.
+ *
+ * A ligament can have its length changed (like an elevator) or angle changed,
+ * like an arm.
+ *
+ * @see Mechanism2d
+ */
+class MechanismLigament2d : public MechanismObject2d {
+ public:
+ MechanismLigament2d(std::string_view name, double length,
+ units::degree_t angle, double lineWidth = 6,
+ const frc::Color8Bit& color = {235, 137, 52});
+
+ /**
+ * Set the ligament color.
+ *
+ * @param color the color of the line
+ */
+ void SetColor(const frc::Color8Bit& color);
+
+ /**
+ * Set the ligament's length.
+ *
+ * @param length the line length
+ */
+ void SetLength(double length);
+
+ /**
+ * Get the ligament length.
+ *
+ * @return the line length
+ */
+ double GetLength();
+
+ /**
+ * Set the ligament's angle relative to its parent.
+ *
+ * @param angle the angle
+ */
+ void SetAngle(units::degree_t angle);
+
+ /**
+ * Get the ligament's angle relative to its parent.
+ *
+ * @return the angle
+ */
+ double GetAngle();
+
+ /**
+ * Set the line thickness.
+ *
+ * @param lineWidth the line thickness
+ */
+ void SetLineWeight(double lineWidth);
+
+ protected:
+ void UpdateEntries(std::shared_ptr<nt::NetworkTable> table) override;
+
+ private:
+ void Flush();
+ double m_length;
+ nt::NetworkTableEntry m_lengthEntry;
+ double m_angle;
+ nt::NetworkTableEntry m_angleEntry;
+ double m_weight;
+ nt::NetworkTableEntry m_weightEntry;
+ char m_color[10];
+ nt::NetworkTableEntry m_colorEntry;
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h
new file mode 100644
index 0000000..c4185e7
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h
@@ -0,0 +1,91 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+#include <stdexcept>
+#include <string>
+#include <string_view>
+#include <type_traits>
+#include <utility>
+
+#include <networktables/NetworkTable.h>
+#include <wpi/StringMap.h>
+
+#include "frc/Errors.h"
+
+namespace frc {
+
+/**
+ * Common base class for all Mechanism2d node types.
+ *
+ * To append another node, call Append with the type of node and its
+ * construction parameters. None of the node types are designed to be
+ * constructed directly, and are owned by their parent node/container - obtain
+ * pointers from the Append function or similar factory methods.
+ *
+ * @see Mechanism2d.
+ */
+class MechanismObject2d {
+ friend class Mechanism2d;
+
+ protected:
+ explicit MechanismObject2d(std::string_view name);
+
+ /**
+ * Update all entries with new ones from a new table.
+ *
+ * @param table the new table.
+ */
+ virtual void UpdateEntries(std::shared_ptr<nt::NetworkTable> table) = 0;
+
+ mutable wpi::mutex m_mutex;
+
+ public:
+ virtual ~MechanismObject2d() = default;
+
+ /**
+ * Retrieve the object's name.
+ *
+ * @return the object's name relative to its parent.
+ */
+ const std::string& GetName() const;
+
+ /**
+ * Append a Mechanism object that is based on this one.
+ *
+ * @param name the name of the new object.
+ * @param args constructor arguments of the object type.
+ * @return the constructed and appended object, useful for variable
+ * assignments and call chaining.
+ * @throw if an object with the given name already exists.
+ */
+ template <typename T, typename... Args,
+ typename =
+ std::enable_if_t<std::is_convertible_v<T*, MechanismObject2d*>>>
+ T* Append(std::string_view name, Args&&... args) {
+ std::scoped_lock lock(m_mutex);
+ auto& obj = m_objects[name];
+ if (obj) {
+ throw FRC_MakeError(
+ err::Error,
+ "MechanismObject names must be unique! `{}` was inserted twice!",
+ name);
+ }
+ obj = std::make_unique<T>(name, std::forward<Args>(args)...);
+ T* ex = static_cast<T*>(obj.get());
+ if (m_table) {
+ ex->Update(m_table->GetSubTable(name));
+ }
+ return ex;
+ }
+
+ private:
+ std::string m_name;
+ wpi::StringMap<std::unique_ptr<MechanismObject2d>> m_objects;
+ std::shared_ptr<nt::NetworkTable> m_table;
+ void Update(std::shared_ptr<nt::NetworkTable> table);
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/MechanismRoot2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismRoot2d.h
new file mode 100644
index 0000000..5072547
--- /dev/null
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismRoot2d.h
@@ -0,0 +1,54 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <memory>
+#include <string_view>
+
+#include <networktables/NetworkTableEntry.h>
+
+#include "MechanismObject2d.h"
+
+namespace frc {
+
+/**
+ * Root Mechanism2d node.
+ *
+ * A root is the anchor point of other nodes (such as ligaments).
+ *
+ * Do not create objects of this class directly! Obtain pointers from the
+ * Mechanism2d.GetRoot() factory method.
+ *
+ * <p>Append other nodes by using Append().
+ */
+class MechanismRoot2d : private MechanismObject2d {
+ friend class Mechanism2d;
+ struct private_init {};
+
+ public:
+ MechanismRoot2d(std::string_view name, double x, double y,
+ const private_init&);
+
+ /**
+ * Set the root's position.
+ *
+ * @param x new x coordinate
+ * @param y new y coordinate
+ */
+ void SetPosition(double x, double y);
+
+ using MechanismObject2d::GetName;
+
+ using MechanismObject2d::Append;
+
+ private:
+ void UpdateEntries(std::shared_ptr<nt::NetworkTable> table) override;
+ inline void Flush();
+ double m_x;
+ double m_y;
+ nt::NetworkTableEntry m_xEntry;
+ nt::NetworkTableEntry m_yEntry;
+};
+} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/Sendable.h b/wpilibc/src/main/native/include/frc/smartdashboard/Sendable.h
deleted file mode 100644
index 5000855..0000000
--- a/wpilibc/src/main/native/include/frc/smartdashboard/Sendable.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-namespace frc {
-
-class SendableBuilder;
-
-/**
- * Interface for Sendable objects.
- */
-class Sendable {
- public:
- virtual ~Sendable() = default;
-
- /**
- * Initializes this Sendable object.
- *
- * @param builder sendable builder
- */
- virtual void InitSendable(SendableBuilder& builder) = 0;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBase.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBase.h
deleted file mode 100644
index 98419b9..0000000
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBase.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <wpi/deprecated.h>
-
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
-
-namespace frc {
-
-class SendableBase : public Sendable, public SendableHelper<SendableBase> {
- public:
- /**
- * Creates an instance of the sensor base
- *
- * @deprecated use Sendable and SendableHelper
- *
- * @param addLiveWindow if true, add this Sendable to LiveWindow
- */
- WPI_DEPRECATED("use Sendable and SendableHelper")
- explicit SendableBase(bool addLiveWindow = true);
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h
deleted file mode 100644
index 3f5f892..0000000
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <functional>
-#include <memory>
-#include <string>
-#include <vector>
-
-#include <networktables/NetworkTableEntry.h>
-#include <networktables/NetworkTableValue.h>
-#include <wpi/ArrayRef.h>
-#include <wpi/SmallVector.h>
-#include <wpi/Twine.h>
-
-namespace frc {
-
-class SendableBuilder {
- public:
- virtual ~SendableBuilder() = default;
-
- /**
- * Set the string representation of the named data type that will be used
- * by the smart dashboard for this sendable.
- *
- * @param type data type
- */
- virtual void SetSmartDashboardType(const wpi::Twine& type) = 0;
-
- /**
- * Set a flag indicating if this sendable should be treated as an actuator.
- * By default this flag is false.
- *
- * @param value true if actuator, false if not
- */
- virtual void SetActuator(bool value) = 0;
-
- /**
- * Set the function that should be called to set the Sendable into a safe
- * state. This is called when entering and exiting Live Window mode.
- *
- * @param func function
- */
- virtual void SetSafeState(std::function<void()> func) = 0;
-
- /**
- * Set the function that should be called to update the network table
- * for things other than properties. Note this function is not passed
- * the network table object; instead it should use the entry handles
- * returned by GetEntry().
- *
- * @param func function
- */
- virtual void SetUpdateTable(std::function<void()> func) = 0;
-
- /**
- * Add a property without getters or setters. This can be used to get
- * entry handles for the function called by SetUpdateTable().
- *
- * @param key property name
- * @return Network table entry
- */
- virtual nt::NetworkTableEntry GetEntry(const wpi::Twine& key) = 0;
-
- /**
- * Add a boolean property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddBooleanProperty(const wpi::Twine& key,
- std::function<bool()> getter,
- std::function<void(bool)> setter) = 0;
-
- /**
- * Add a double property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddDoubleProperty(const wpi::Twine& key,
- std::function<double()> getter,
- std::function<void(double)> setter) = 0;
-
- /**
- * Add a string property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddStringProperty(
- const wpi::Twine& key, std::function<std::string()> getter,
- std::function<void(wpi::StringRef)> setter) = 0;
-
- /**
- * Add a boolean array property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddBooleanArrayProperty(
- const wpi::Twine& key, std::function<std::vector<int>()> getter,
- std::function<void(wpi::ArrayRef<int>)> setter) = 0;
-
- /**
- * Add a double array property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddDoubleArrayProperty(
- const wpi::Twine& key, std::function<std::vector<double>()> getter,
- std::function<void(wpi::ArrayRef<double>)> setter) = 0;
-
- /**
- * Add a string array property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddStringArrayProperty(
- const wpi::Twine& key, std::function<std::vector<std::string>()> getter,
- std::function<void(wpi::ArrayRef<std::string>)> setter) = 0;
-
- /**
- * Add a raw property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddRawProperty(const wpi::Twine& key,
- std::function<std::string()> getter,
- std::function<void(wpi::StringRef)> setter) = 0;
-
- /**
- * Add a NetworkTableValue property.
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddValueProperty(
- const wpi::Twine& key, std::function<std::shared_ptr<nt::Value>()> getter,
- std::function<void(std::shared_ptr<nt::Value>)> setter) = 0;
-
- /**
- * Add a string property (SmallString form).
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddSmallStringProperty(
- const wpi::Twine& key,
- std::function<wpi::StringRef(wpi::SmallVectorImpl<char>& buf)> getter,
- std::function<void(wpi::StringRef)> setter) = 0;
-
- /**
- * Add a boolean array property (SmallVector form).
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddSmallBooleanArrayProperty(
- const wpi::Twine& key,
- std::function<wpi::ArrayRef<int>(wpi::SmallVectorImpl<int>& buf)> getter,
- std::function<void(wpi::ArrayRef<int>)> setter) = 0;
-
- /**
- * Add a double array property (SmallVector form).
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddSmallDoubleArrayProperty(
- const wpi::Twine& key,
- std::function<wpi::ArrayRef<double>(wpi::SmallVectorImpl<double>& buf)>
- getter,
- std::function<void(wpi::ArrayRef<double>)> setter) = 0;
-
- /**
- * Add a string array property (SmallVector form).
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddSmallStringArrayProperty(
- const wpi::Twine& key,
- std::function<
- wpi::ArrayRef<std::string>(wpi::SmallVectorImpl<std::string>& buf)>
- getter,
- std::function<void(wpi::ArrayRef<std::string>)> setter) = 0;
-
- /**
- * Add a raw property (SmallVector form).
- *
- * @param key property name
- * @param getter getter function (returns current value)
- * @param setter setter function (sets new value)
- */
- virtual void AddSmallRawProperty(
- const wpi::Twine& key,
- std::function<wpi::StringRef(wpi::SmallVectorImpl<char>& buf)> getter,
- std::function<void(wpi::StringRef)> setter) = 0;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h
index e5dea44..36830f6 100644
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h
@@ -1,30 +1,26 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <functional>
#include <memory>
#include <string>
+#include <string_view>
#include <utility>
#include <vector>
+#include <networktables/NTSendableBuilder.h>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableValue.h>
-#include <wpi/ArrayRef.h>
#include <wpi/SmallVector.h>
-#include <wpi/Twine.h>
-
-#include "frc/smartdashboard/SendableBuilder.h"
+#include <wpi/span.h>
namespace frc {
-class SendableBuilderImpl : public SendableBuilder {
+class SendableBuilderImpl : public nt::NTSendableBuilder {
public:
SendableBuilderImpl() = default;
~SendableBuilderImpl() override = default;
@@ -43,13 +39,13 @@
* Get the network table.
* @return The network table
*/
- std::shared_ptr<nt::NetworkTable> GetTable();
+ std::shared_ptr<nt::NetworkTable> GetTable() override;
/**
* Return whether this sendable has an associated table.
* @return True if it has a table, false if not.
*/
- bool HasTable() const;
+ bool IsPublished() const override;
/**
* Return whether this sendable should be treated as an actuator.
@@ -60,7 +56,7 @@
/**
* Update the network table values by calling the getters for all properties.
*/
- void UpdateTable();
+ void Update() override;
/**
* Hook setters for all properties.
@@ -87,75 +83,75 @@
/**
* Clear properties.
*/
- void ClearProperties();
+ void ClearProperties() override;
- void SetSmartDashboardType(const wpi::Twine& type) override;
+ void SetSmartDashboardType(std::string_view type) override;
void SetActuator(bool value) override;
void SetSafeState(std::function<void()> func) override;
void SetUpdateTable(std::function<void()> func) override;
- nt::NetworkTableEntry GetEntry(const wpi::Twine& key) override;
+ nt::NetworkTableEntry GetEntry(std::string_view key) override;
- void AddBooleanProperty(const wpi::Twine& key, std::function<bool()> getter,
+ void AddBooleanProperty(std::string_view key, std::function<bool()> getter,
std::function<void(bool)> setter) override;
- void AddDoubleProperty(const wpi::Twine& key, std::function<double()> getter,
+ void AddDoubleProperty(std::string_view key, std::function<double()> getter,
std::function<void(double)> setter) override;
- void AddStringProperty(const wpi::Twine& key,
+ void AddStringProperty(std::string_view key,
std::function<std::string()> getter,
- std::function<void(wpi::StringRef)> setter) override;
+ std::function<void(std::string_view)> setter) override;
void AddBooleanArrayProperty(
- const wpi::Twine& key, std::function<std::vector<int>()> getter,
- std::function<void(wpi::ArrayRef<int>)> setter) override;
+ std::string_view key, std::function<std::vector<int>()> getter,
+ std::function<void(wpi::span<const int>)> setter) override;
void AddDoubleArrayProperty(
- const wpi::Twine& key, std::function<std::vector<double>()> getter,
- std::function<void(wpi::ArrayRef<double>)> setter) override;
+ std::string_view key, std::function<std::vector<double>()> getter,
+ std::function<void(wpi::span<const double>)> setter) override;
void AddStringArrayProperty(
- const wpi::Twine& key, std::function<std::vector<std::string>()> getter,
- std::function<void(wpi::ArrayRef<std::string>)> setter) override;
+ std::string_view key, std::function<std::vector<std::string>()> getter,
+ std::function<void(wpi::span<const std::string>)> setter) override;
- void AddRawProperty(const wpi::Twine& key,
- std::function<std::string()> getter,
- std::function<void(wpi::StringRef)> setter) override;
+ void AddRawProperty(std::string_view key, std::function<std::string()> getter,
+ std::function<void(std::string_view)> setter) override;
void AddValueProperty(
- const wpi::Twine& key, std::function<std::shared_ptr<nt::Value>()> getter,
+ std::string_view key, std::function<std::shared_ptr<nt::Value>()> getter,
std::function<void(std::shared_ptr<nt::Value>)> setter) override;
void AddSmallStringProperty(
- const wpi::Twine& key,
- std::function<wpi::StringRef(wpi::SmallVectorImpl<char>& buf)> getter,
- std::function<void(wpi::StringRef)> setter) override;
+ std::string_view key,
+ std::function<std::string_view(wpi::SmallVectorImpl<char>& buf)> getter,
+ std::function<void(std::string_view)> setter) override;
void AddSmallBooleanArrayProperty(
- const wpi::Twine& key,
- std::function<wpi::ArrayRef<int>(wpi::SmallVectorImpl<int>& buf)> getter,
- std::function<void(wpi::ArrayRef<int>)> setter) override;
+ std::string_view key,
+ std::function<wpi::span<const int>(wpi::SmallVectorImpl<int>& buf)>
+ getter,
+ std::function<void(wpi::span<const int>)> setter) override;
void AddSmallDoubleArrayProperty(
- const wpi::Twine& key,
- std::function<wpi::ArrayRef<double>(wpi::SmallVectorImpl<double>& buf)>
+ std::string_view key,
+ std::function<wpi::span<const double>(wpi::SmallVectorImpl<double>& buf)>
getter,
- std::function<void(wpi::ArrayRef<double>)> setter) override;
+ std::function<void(wpi::span<const double>)> setter) override;
void AddSmallStringArrayProperty(
- const wpi::Twine& key,
+ std::string_view key,
std::function<
- wpi::ArrayRef<std::string>(wpi::SmallVectorImpl<std::string>& buf)>
+ wpi::span<const std::string>(wpi::SmallVectorImpl<std::string>& buf)>
getter,
- std::function<void(wpi::ArrayRef<std::string>)> setter) override;
+ std::function<void(wpi::span<const std::string>)> setter) override;
void AddSmallRawProperty(
- const wpi::Twine& key,
- std::function<wpi::StringRef(wpi::SmallVectorImpl<char>& buf)> getter,
- std::function<void(wpi::StringRef)> setter) override;
+ std::string_view key,
+ std::function<std::string_view(wpi::SmallVectorImpl<char>& buf)> getter,
+ std::function<void(std::string_view)> setter) override;
private:
struct Property {
- Property(nt::NetworkTable& table, const wpi::Twine& key)
+ Property(nt::NetworkTable& table, std::string_view key)
: entry(table.GetEntry(key)) {}
Property(const Property&) = delete;
@@ -183,8 +179,9 @@
~Property() { StopListener(); }
void StartListener() {
- if (entry && listener == 0 && createListener)
+ if (entry && listener == 0 && createListener) {
listener = createListener(entry);
+ }
}
void StopListener() {
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h
index b370fc0..b693762 100644
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h
@@ -1,19 +1,15 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
+#include <string_view>
#include <wpi/StringMap.h>
-#include <wpi/StringRef.h>
#include <wpi/deprecated.h>
-#include "frc/smartdashboard/SendableBuilder.h"
#include "frc/smartdashboard/SendableChooserBase.h"
namespace frc {
@@ -45,27 +41,21 @@
static std::weak_ptr<U> _unwrap_smart_ptr(const std::shared_ptr<U>& value);
public:
- ~SendableChooser() override = default;
SendableChooser() = default;
+ ~SendableChooser() override = default;
SendableChooser(SendableChooser&& rhs) = default;
SendableChooser& operator=(SendableChooser&& rhs) = default;
- void AddOption(wpi::StringRef name, T object);
- void SetDefaultOption(wpi::StringRef name, T object);
-
/**
* Adds the given object to the list of options.
*
* On the SmartDashboard on the desktop, the object will appear as the given
* name.
*
- * @deprecated use AddOption(wpi::StringRef name, T object) instead.
- *
* @param name the name of the option
* @param object the option
*/
- WPI_DEPRECATED("use AddOption() instead")
- void AddObject(wpi::StringRef name, T object) { AddOption(name, object); }
+ void AddOption(std::string_view name, T object);
/**
* Add the given object to the list of options and marks it as the default.
@@ -73,19 +63,55 @@
* Functionally, this is very close to AddOption() except that it will use
* this as the default option if none other is explicitly selected.
*
- * @deprecated use SetDefaultOption(wpi::StringRef name, T object) instead.
+ * @param name the name of the option
+ * @param object the option
+ */
+ void SetDefaultOption(std::string_view name, T object);
+
+ /**
+ * Adds the given object to the list of options.
+ *
+ * On the SmartDashboard on the desktop, the object will appear as the given
+ * name.
+ *
+ * @deprecated use AddOption(std::string_view name, T object) instead.
+ *
+ * @param name the name of the option
+ * @param object the option
+ */
+ WPI_DEPRECATED("use AddOption() instead")
+ void AddObject(std::string_view name, T object) { AddOption(name, object); }
+
+ /**
+ * Add the given object to the list of options and marks it as the default.
+ *
+ * Functionally, this is very close to AddOption() except that it will use
+ * this as the default option if none other is explicitly selected.
+ *
+ * @deprecated use SetDefaultOption(std::string_view name, T object) instead.
*
* @param name the name of the option
* @param object the option
*/
WPI_DEPRECATED("use SetDefaultOption() instead")
- void AddDefault(wpi::StringRef name, T object) {
+ void AddDefault(std::string_view name, T object) {
SetDefaultOption(name, object);
}
+ /**
+ * Returns a copy of the selected option (a raw pointer U* if T =
+ * std::unique_ptr<U> or a std::weak_ptr<U> if T = std::shared_ptr<U>).
+ *
+ * If there is none selected, it will return the default. If there is none
+ * selected and no default, then it will return a value-initialized instance.
+ * For integer types, this is 0. For container types like std::string, this is
+ * an empty string.
+ *
+ * @return The option selected
+ */
auto GetSelected() -> decltype(_unwrap_smart_ptr(m_choices[""]));
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(nt::NTSendableBuilder& builder) override;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc
index 57e2828..25e2551 100644
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc
@@ -1,69 +1,42 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <algorithm>
#include <memory>
#include <string>
+#include <string_view>
#include <utility>
#include <vector>
-#include <wpi/StringRef.h>
+#include <networktables/NTSendableBuilder.h>
+
+#include "frc/smartdashboard/SendableChooser.h"
namespace frc {
-/**
- * Adds the given object to the list of options.
- *
- * On the SmartDashboard on the desktop, the object will appear as the given
- * name.
- *
- * @param name the name of the option
- * @param object the option
- */
template <class T>
-void SendableChooser<T>::AddOption(wpi::StringRef name, T object) {
+void SendableChooser<T>::AddOption(std::string_view name, T object) {
m_choices[name] = std::move(object);
}
-/**
- * Add the given object to the list of options and marks it as the default.
- *
- * Functionally, this is very close to AddOption() except that it will use this
- * as the default option if none other is explicitly selected.
- *
- * @param name the name of the option
- * @param object the option
- */
template <class T>
-void SendableChooser<T>::SetDefaultOption(wpi::StringRef name, T object) {
+void SendableChooser<T>::SetDefaultOption(std::string_view name, T object) {
m_defaultChoice = name;
AddOption(name, std::move(object));
}
-/**
- * Returns a copy of the selected option (a raw pointer U* if T =
- * std::unique_ptr<U> or a std::weak_ptr<U> if T = std::shared_ptr<U>).
- *
- * If there is none selected, it will return the default. If there is none
- * selected and no default, then it will return a value-initialized instance.
- * For integer types, this is 0. For container types like std::string, this is
- * an empty string.
- *
- * @return The option selected
- */
template <class T>
auto SendableChooser<T>::GetSelected()
-> decltype(_unwrap_smart_ptr(m_choices[""])) {
std::string selected = m_defaultChoice;
{
std::scoped_lock lock(m_mutex);
- if (m_haveSelected) selected = m_selected;
+ if (m_haveSelected) {
+ selected = m_selected;
+ }
}
if (selected.empty()) {
return decltype(_unwrap_smart_ptr(m_choices[""])){};
@@ -73,15 +46,15 @@
}
template <class T>
-void SendableChooser<T>::InitSendable(SendableBuilder& builder) {
+void SendableChooser<T>::InitSendable(nt::NTSendableBuilder& builder) {
builder.SetSmartDashboardType("String Chooser");
builder.GetEntry(kInstance).SetDouble(m_instance);
builder.AddStringArrayProperty(
kOptions,
- [=]() {
+ [=] {
std::vector<std::string> keys;
for (const auto& choice : m_choices) {
- keys.push_back(choice.first());
+ keys.emplace_back(choice.first());
}
// Unlike std::map, wpi::StringMap elements
@@ -93,17 +66,17 @@
nullptr);
builder.AddSmallStringProperty(
kDefault,
- [=](wpi::SmallVectorImpl<char>&) -> wpi::StringRef {
+ [=](wpi::SmallVectorImpl<char>&) -> std::string_view {
return m_defaultChoice;
},
nullptr);
builder.AddSmallStringProperty(
kActive,
- [=](wpi::SmallVectorImpl<char>& buf) -> wpi::StringRef {
+ [=](wpi::SmallVectorImpl<char>& buf) -> std::string_view {
std::scoped_lock lock(m_mutex);
if (m_haveSelected) {
buf.assign(m_selected.begin(), m_selected.end());
- return wpi::StringRef(buf.data(), buf.size());
+ return {buf.data(), buf.size()};
} else {
return m_defaultChoice;
}
@@ -113,11 +86,13 @@
std::scoped_lock lock(m_mutex);
m_activeEntries.emplace_back(builder.GetEntry(kActive));
}
- builder.AddStringProperty(kSelected, nullptr, [=](wpi::StringRef val) {
+ builder.AddStringProperty(kSelected, nullptr, [=](std::string_view val) {
std::scoped_lock lock(m_mutex);
m_haveSelected = true;
m_selected = val;
- for (auto& entry : m_activeEntries) entry.SetString(val);
+ for (auto& entry : m_activeEntries) {
+ entry.SetString(val);
+ }
});
}
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h
index 2a5f5ab..78f891a 100644
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooserBase.h
@@ -1,21 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <atomic>
#include <string>
+#include <networktables/NTSendable.h>
#include <networktables/NetworkTableEntry.h>
#include <wpi/SmallVector.h>
#include <wpi/mutex.h>
-
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+#include <wpi/sendable/SendableHelper.h>
namespace frc {
@@ -25,8 +21,8 @@
* It contains static, non-templated variables to avoid their duplication in the
* template class.
*/
-class SendableChooserBase : public Sendable,
- public SendableHelper<SendableChooserBase> {
+class SendableChooserBase : public nt::NTSendable,
+ public wpi::SendableHelper<SendableChooserBase> {
public:
SendableChooserBase();
~SendableChooserBase() override = default;
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableHelper.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableHelper.h
deleted file mode 100644
index 1f39216..0000000
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableHelper.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-#include <string>
-
-#include <wpi/Twine.h>
-#include <wpi/deprecated.h>
-
-#include "frc/smartdashboard/SendableRegistry.h"
-
-namespace frc {
-
-/**
- * A helper class for use with objects that add themselves to SendableRegistry.
- * It takes care of properly calling Move() and Remove() on move and
- * destruction. No action is taken if the object is copied.
- * Use public inheritance with CRTP when using this class.
- * @tparam CRTP derived class
- */
-template <typename Derived>
-class SendableHelper {
- public:
- SendableHelper(const SendableHelper& rhs) = default;
- SendableHelper& operator=(const SendableHelper& rhs) = default;
-
- SendableHelper(SendableHelper&& rhs) {
- // it is safe to call Move() multiple times with the same rhs
- SendableRegistry::GetInstance().Move(static_cast<Derived*>(this),
- static_cast<Derived*>(&rhs));
- }
-
- SendableHelper& operator=(SendableHelper&& rhs) {
- // it is safe to call Move() multiple times with the same rhs
- SendableRegistry::GetInstance().Move(static_cast<Derived*>(this),
- static_cast<Derived*>(&rhs));
- return *this;
- }
-
- /**
- * Gets the name of this Sendable object.
- *
- * @deprecated use SendableRegistry::GetName()
- *
- * @return Name
- */
- WPI_DEPRECATED("use SendableRegistry::GetName()")
- std::string GetName() const {
- return SendableRegistry::GetInstance().GetName(
- static_cast<const Derived*>(this));
- }
-
- /**
- * Sets the name of this Sendable object.
- *
- * @deprecated use SendableRegistry::SetName()
- *
- * @param name name
- */
- WPI_DEPRECATED("use SendableRegistry::SetName()")
- void SetName(const wpi::Twine& name) {
- SendableRegistry::GetInstance().SetName(static_cast<Derived*>(this), name);
- }
-
- /**
- * Sets both the subsystem name and device name of this Sendable object.
- *
- * @deprecated use SendableRegistry::SetName()
- *
- * @param subsystem subsystem name
- * @param name device name
- */
- WPI_DEPRECATED("use SendableRegistry::SetName()")
- void SetName(const wpi::Twine& subsystem, const wpi::Twine& name) {
- SendableRegistry::GetInstance().SetName(static_cast<Derived*>(this),
- subsystem, name);
- }
-
- /**
- * Gets the subsystem name of this Sendable object.
- *
- * @deprecated use SendableRegistry::GetSubsystem().
- *
- * @return Subsystem name
- */
- WPI_DEPRECATED("use SendableRegistry::GetSubsystem()")
- std::string GetSubsystem() const {
- return SendableRegistry::GetInstance().GetSubsystem(
- static_cast<const Derived*>(this));
- }
-
- /**
- * Sets the subsystem name of this Sendable object.
- *
- * @deprecated use SendableRegistry::SetSubsystem()
- *
- * @param subsystem subsystem name
- */
- WPI_DEPRECATED("use SendableRegistry::SetSubsystem()")
- void SetSubsystem(const wpi::Twine& subsystem) {
- SendableRegistry::GetInstance().SetSubsystem(static_cast<Derived*>(this),
- subsystem);
- }
-
- protected:
- /**
- * Add a child component.
- *
- * @deprecated use SendableRegistry::AddChild()
- *
- * @param child child component
- */
- WPI_DEPRECATED("use SendableRegistry::AddChild()")
- void AddChild(std::shared_ptr<Sendable> child) {
- SendableRegistry::GetInstance().AddChild(static_cast<Derived*>(this),
- child.get());
- }
-
- /**
- * Add a child component.
- *
- * @deprecated use SendableRegistry::AddChild()
- *
- * @param child child component
- */
- WPI_DEPRECATED("use SendableRegistry::AddChild()")
- void AddChild(void* child) {
- SendableRegistry::GetInstance().AddChild(static_cast<Derived*>(this),
- child);
- }
-
- /**
- * Sets the name of the sensor with a channel number.
- *
- * @deprecated use SendableRegistry::SetName()
- *
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param channel The channel number the device is plugged into
- */
- WPI_DEPRECATED("use SendableRegistry::SetName()")
- void SetName(const wpi::Twine& moduleType, int channel) {
- SendableRegistry::GetInstance().SetName(static_cast<Derived*>(this),
- moduleType, channel);
- }
-
- /**
- * Sets the name of the sensor with a module and channel number.
- *
- * @deprecated use SendableRegistry::SetName()
- *
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param moduleNumber The number of the particular module type
- * @param channel The channel number the device is plugged into (usually
- * PWM)
- */
- WPI_DEPRECATED("use SendableRegistry::SetName()")
- void SetName(const wpi::Twine& moduleType, int moduleNumber, int channel) {
- SendableRegistry::GetInstance().SetName(static_cast<Derived*>(this),
- moduleType, moduleNumber, channel);
- }
-
- protected:
- SendableHelper() = default;
-
- ~SendableHelper() {
- // it is safe to call Remove() multiple times with the same object
- SendableRegistry::GetInstance().Remove(static_cast<Derived*>(this));
- }
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h
deleted file mode 100644
index 78dabc6..0000000
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h
+++ /dev/null
@@ -1,341 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <memory>
-#include <string>
-
-#include <networktables/NetworkTable.h>
-#include <wpi/STLExtras.h>
-#include <wpi/Twine.h>
-
-namespace frc {
-
-class Sendable;
-class SendableBuilderImpl;
-
-/**
- * The SendableRegistry class is the public interface for registering sensors
- * and actuators for use on dashboards and LiveWindow.
- */
-class SendableRegistry {
- public:
- SendableRegistry(const SendableRegistry&) = delete;
- SendableRegistry& operator=(const SendableRegistry&) = delete;
-
- using UID = size_t;
-
- /**
- * Gets an instance of the SendableRegistry class.
- *
- * This is a singleton to guarantee that there is only a single instance
- * regardless of how many times GetInstance is called.
- */
- static SendableRegistry& GetInstance();
-
- /**
- * Adds an object to the registry.
- *
- * @param sendable object to add
- * @param name component name
- */
- void Add(Sendable* sendable, const wpi::Twine& name);
-
- /**
- * Adds an object to the registry.
- *
- * @param sendable object to add
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param channel The channel number the device is plugged into
- */
- void Add(Sendable* sendable, const wpi::Twine& moduleType, int channel);
-
- /**
- * Adds an object to the registry.
- *
- * @param sendable object to add
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param moduleNumber The number of the particular module type
- * @param channel The channel number the device is plugged into
- */
- void Add(Sendable* sendable, const wpi::Twine& moduleType, int moduleNumber,
- int channel);
-
- /**
- * Adds an object to the registry.
- *
- * @param sendable object to add
- * @param subsystem subsystem name
- * @param name component name
- */
- void Add(Sendable* sendable, const wpi::Twine& subsystem,
- const wpi::Twine& name);
-
- /**
- * Adds an object to the registry and LiveWindow.
- *
- * @param sendable object to add
- * @param name component name
- */
- void AddLW(Sendable* sendable, const wpi::Twine& name);
-
- /**
- * Adds an object to the registry and LiveWindow.
- *
- * @param sendable object to add
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param channel The channel number the device is plugged into
- */
- void AddLW(Sendable* sendable, const wpi::Twine& moduleType, int channel);
-
- /**
- * Adds an object to the registry and LiveWindow.
- *
- * @param sendable object to add
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param moduleNumber The number of the particular module type
- * @param channel The channel number the device is plugged into
- */
- void AddLW(Sendable* sendable, const wpi::Twine& moduleType, int moduleNumber,
- int channel);
-
- /**
- * Adds an object to the registry and LiveWindow.
- *
- * @param sendable object to add
- * @param subsystem subsystem name
- * @param name component name
- */
- void AddLW(Sendable* sendable, const wpi::Twine& subsystem,
- const wpi::Twine& name);
-
- /**
- * Adds a child object to an object. Adds the child object to the registry
- * if it's not already present.
- *
- * @param parent parent object
- * @param child child object
- */
- void AddChild(Sendable* parent, Sendable* child);
-
- /**
- * Adds a child object to an object. Adds the child object to the registry
- * if it's not already present.
- *
- * @param parent parent object
- * @param child child object
- */
- void AddChild(Sendable* parent, void* child);
-
- /**
- * Removes an object from the registry.
- *
- * @param sendable object to remove
- * @return true if the object was removed; false if it was not present
- */
- bool Remove(Sendable* sendable);
-
- /**
- * Moves an object in the registry (for use in move constructors/assignments).
- *
- * @param to new object
- * @param from old object
- */
- void Move(Sendable* to, Sendable* from);
-
- /**
- * Determines if an object is in the registry.
- *
- * @param sendable object to check
- * @return True if in registry, false if not.
- */
- bool Contains(const Sendable* sendable) const;
-
- /**
- * Gets the name of an object.
- *
- * @param sendable object
- * @return Name (empty if object is not in registry)
- */
- std::string GetName(const Sendable* sendable) const;
-
- /**
- * Sets the name of an object.
- *
- * @param sendable object
- * @param name name
- */
- void SetName(Sendable* sendable, const wpi::Twine& name);
-
- /**
- * Sets the name of an object with a channel number.
- *
- * @param sendable object
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param channel The channel number the device is plugged into
- */
- void SetName(Sendable* sendable, const wpi::Twine& moduleType, int channel);
-
- /**
- * Sets the name of an object with a module and channel number.
- *
- * @param sendable object
- * @param moduleType A string that defines the module name in the label for
- * the value
- * @param moduleNumber The number of the particular module type
- * @param channel The channel number the device is plugged into
- */
- void SetName(Sendable* sendable, const wpi::Twine& moduleType,
- int moduleNumber, int channel);
-
- /**
- * Sets both the subsystem name and device name of an object.
- *
- * @param sendable object
- * @param subsystem subsystem name
- * @param name device name
- */
- void SetName(Sendable* sendable, const wpi::Twine& subsystem,
- const wpi::Twine& name);
-
- /**
- * Gets the subsystem name of an object.
- *
- * @param sendable object
- * @return Subsystem name (empty if object is not in registry)
- */
- std::string GetSubsystem(const Sendable* sendable) const;
-
- /**
- * Sets the subsystem name of an object.
- *
- * @param sendable object
- * @param subsystem subsystem name
- */
- void SetSubsystem(Sendable* sendable, const wpi::Twine& subsystem);
-
- /**
- * Gets a unique handle for setting/getting data with SetData() and GetData().
- *
- * @return Handle
- */
- int GetDataHandle();
-
- /**
- * Associates arbitrary data with an object in the registry.
- *
- * @param sendable object
- * @param handle data handle returned by GetDataHandle()
- * @param data data to set
- * @return Previous data (may be null)
- */
- std::shared_ptr<void> SetData(Sendable* sendable, int handle,
- std::shared_ptr<void> data);
-
- /**
- * Gets arbitrary data associated with an object in the registry.
- *
- * @param sendable object
- * @param handle data handle returned by GetDataHandle()
- * @return data (may be null if none associated)
- */
- std::shared_ptr<void> GetData(Sendable* sendable, int handle);
-
- /**
- * Enables LiveWindow for an object.
- *
- * @param sendable object
- */
- void EnableLiveWindow(Sendable* sendable);
-
- /**
- * Disables LiveWindow for an object.
- *
- * @param sendable object
- */
- void DisableLiveWindow(Sendable* sendable);
-
- /**
- * Get unique id for an object. Since objects can move, use this instead
- * of storing Sendable* directly if ownership is in question.
- *
- * @param sendable object
- * @return unique id
- */
- UID GetUniqueId(Sendable* sendable);
-
- /**
- * Get sendable object for a given unique id.
- *
- * @param uid unique id
- * @return sendable object (may be null)
- */
- Sendable* GetSendable(UID uid);
-
- /**
- * Publishes an object in the registry to a network table.
- *
- * @param sendableUid sendable unique id
- * @param table network table
- */
- void Publish(UID sendableUid, std::shared_ptr<NetworkTable> table);
-
- /**
- * Updates network table information from an object.
- *
- * @param sendableUid sendable unique id
- */
- void Update(UID sendableUid);
-
- /**
- * Data passed to ForeachLiveWindow() callback function
- */
- struct CallbackData {
- CallbackData(Sendable* sendable_, wpi::StringRef name_,
- wpi::StringRef subsystem_, Sendable* parent_,
- std::shared_ptr<void>& data_, SendableBuilderImpl& builder_)
- : sendable(sendable_),
- name(name_),
- subsystem(subsystem_),
- parent(parent_),
- data(data_),
- builder(builder_) {}
-
- Sendable* sendable;
- wpi::StringRef name;
- wpi::StringRef subsystem;
- Sendable* parent;
- std::shared_ptr<void>& data;
- SendableBuilderImpl& builder;
- };
-
- /**
- * Iterates over LiveWindow-enabled objects in the registry.
- * It is *not* safe to call other SendableRegistry functions from the
- * callback (this will likely deadlock).
- *
- * @param dataHandle data handle to get data pointer passed to callback
- * @param callback function to call for each object
- */
- void ForeachLiveWindow(
- int dataHandle,
- wpi::function_ref<void(CallbackData& cbdata)> callback) const;
-
- private:
- SendableRegistry();
-
- struct Impl;
- std::unique_ptr<Impl> m_impl;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h b/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h
index 9fdc049..47c4a28 100644
--- a/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h
+++ b/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h
@@ -1,30 +1,28 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2011-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <memory>
#include <string>
+#include <string_view>
#include <vector>
#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableValue.h>
+#include <wpi/span.h>
-#include "frc/ErrorBase.h"
-#include "frc/smartdashboard/ListenerExecutor.h"
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableHelper.h"
+namespace wpi {
+class Sendable;
+} // namespace wpi
namespace frc {
-class SmartDashboard : public ErrorBase,
- public Sendable,
- public SendableHelper<SmartDashboard> {
+class SmartDashboard {
public:
+ SmartDashboard() = delete;
+
static void init();
/**
@@ -33,7 +31,7 @@
* @param key the key to search for
* @return true if the table as a value assigned to the given key
*/
- static bool ContainsKey(wpi::StringRef key);
+ static bool ContainsKey(std::string_view key);
/**
* @param types bitmask of types; 0 is treated as a "don't care".
@@ -46,7 +44,7 @@
*
* @param key the key to make persistent
*/
- static void SetPersistent(wpi::StringRef key);
+ static void SetPersistent(std::string_view key);
/**
* Stop making a key's value persistent through program restarts.
@@ -54,7 +52,7 @@
*
* @param key the key name
*/
- static void ClearPersistent(wpi::StringRef key);
+ static void ClearPersistent(std::string_view key);
/**
* Returns whether the value is persistent through program restarts.
@@ -62,7 +60,7 @@
*
* @param key the key name
*/
- static bool IsPersistent(wpi::StringRef key);
+ static bool IsPersistent(std::string_view key);
/**
* Sets flags on the specified key in this table. The key can
@@ -71,7 +69,7 @@
* @param key the key name
* @param flags the flags to set (bitmask)
*/
- static void SetFlags(wpi::StringRef key, unsigned int flags);
+ static void SetFlags(std::string_view key, unsigned int flags);
/**
* Clears flags on the specified key in this table. The key can
@@ -80,7 +78,7 @@
* @param key the key name
* @param flags the flags to clear (bitmask)
*/
- static void ClearFlags(wpi::StringRef key, unsigned int flags);
+ static void ClearFlags(std::string_view key, unsigned int flags);
/**
* Returns the flags for the specified key.
@@ -88,14 +86,14 @@
* @param key the key name
* @return the flags, or 0 if the key is not defined
*/
- static unsigned int GetFlags(wpi::StringRef key);
+ static unsigned int GetFlags(std::string_view key);
/**
* Deletes the specified key in this table.
*
* @param key the key name
*/
- static void Delete(wpi::StringRef key);
+ static void Delete(std::string_view key);
/**
* Returns an NT Entry mapping to the specified key
@@ -105,7 +103,7 @@
* @param key the key
* @return the entry for the key
*/
- static nt::NetworkTableEntry GetEntry(wpi::StringRef key);
+ static nt::NetworkTableEntry GetEntry(std::string_view key);
/**
* Maps the specified key to the specified value in this table.
@@ -116,10 +114,10 @@
* In order for the value to appear in the dashboard, it must be registered
* with SendableRegistry. WPILib components do this automatically.
*
- * @param keyName the key
- * @param value the value
+ * @param key the key
+ * @param data the value
*/
- static void PutData(wpi::StringRef key, Sendable* data);
+ static void PutData(std::string_view key, wpi::Sendable* data);
/**
* Maps the specified key (where the key is the name of the Sendable)
@@ -133,7 +131,7 @@
*
* @param value the value
*/
- static void PutData(Sendable* value);
+ static void PutData(wpi::Sendable* value);
/**
* Returns the value at the specified key.
@@ -141,7 +139,7 @@
* @param keyName the key
* @return the value
*/
- static Sendable* GetData(wpi::StringRef keyName);
+ static wpi::Sendable* GetData(std::string_view keyName);
/**
* Maps the specified key to the specified value in this table.
@@ -153,7 +151,7 @@
* @param value the value
* @return False if the table key already exists with a different type
*/
- static bool PutBoolean(wpi::StringRef keyName, bool value);
+ static bool PutBoolean(std::string_view keyName, bool value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -161,7 +159,7 @@
* @param defaultValue the default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultBoolean(wpi::StringRef key, bool defaultValue);
+ static bool SetDefaultBoolean(std::string_view key, bool defaultValue);
/**
* Returns the value at the specified key.
@@ -169,9 +167,10 @@
* If the key is not found, returns the default value.
*
* @param keyName the key
+ * @param defaultValue the default value to set if key doesn't exist
* @return the value
*/
- static bool GetBoolean(wpi::StringRef keyName, bool defaultValue);
+ static bool GetBoolean(std::string_view keyName, bool defaultValue);
/**
* Maps the specified key to the specified value in this table.
@@ -183,7 +182,7 @@
* @param value the value
* @return False if the table key already exists with a different type
*/
- static bool PutNumber(wpi::StringRef keyName, double value);
+ static bool PutNumber(std::string_view keyName, double value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -192,7 +191,7 @@
* @param defaultValue The default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultNumber(wpi::StringRef key, double defaultValue);
+ static bool SetDefaultNumber(std::string_view key, double defaultValue);
/**
* Returns the value at the specified key.
@@ -200,9 +199,10 @@
* If the key is not found, returns the default value.
*
* @param keyName the key
+ * @param defaultValue the default value to set if the key doesn't exist
* @return the value
*/
- static double GetNumber(wpi::StringRef keyName, double defaultValue);
+ static double GetNumber(std::string_view keyName, double defaultValue);
/**
* Maps the specified key to the specified value in this table.
@@ -214,7 +214,7 @@
* @param value the value
* @return False if the table key already exists with a different type
*/
- static bool PutString(wpi::StringRef keyName, wpi::StringRef value);
+ static bool PutString(std::string_view keyName, std::string_view value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -223,7 +223,8 @@
* @param defaultValue the default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultString(wpi::StringRef key, wpi::StringRef defaultValue);
+ static bool SetDefaultString(std::string_view key,
+ std::string_view defaultValue);
/**
* Returns the value at the specified key.
@@ -231,10 +232,11 @@
* If the key is not found, returns the default value.
*
* @param keyName the key
+ * @param defaultValue the default value to set if the key doesn't exist
* @return the value
*/
- static std::string GetString(wpi::StringRef keyName,
- wpi::StringRef defaultValue);
+ static std::string GetString(std::string_view keyName,
+ std::string_view defaultValue);
/**
* Put a boolean array in the table.
@@ -247,7 +249,7 @@
* std::vector<bool> is special-cased in C++. 0 is false, any
* non-zero value is true.
*/
- static bool PutBooleanArray(wpi::StringRef key, wpi::ArrayRef<int> value);
+ static bool PutBooleanArray(std::string_view key, wpi::span<const int> value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -256,8 +258,8 @@
* @param defaultValue the default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultBooleanArray(wpi::StringRef key,
- wpi::ArrayRef<int> defaultValue);
+ static bool SetDefaultBooleanArray(std::string_view key,
+ wpi::span<const int> defaultValue);
/**
* Returns the boolean array the key maps to.
@@ -277,8 +279,8 @@
* because std::vector<bool> is special-cased in C++. 0 is false, any
* non-zero value is true.
*/
- static std::vector<int> GetBooleanArray(wpi::StringRef key,
- wpi::ArrayRef<int> defaultValue);
+ static std::vector<int> GetBooleanArray(std::string_view key,
+ wpi::span<const int> defaultValue);
/**
* Put a number array in the table.
@@ -287,7 +289,8 @@
* @param value The value that will be assigned.
* @return False if the table key already exists with a different type
*/
- static bool PutNumberArray(wpi::StringRef key, wpi::ArrayRef<double> value);
+ static bool PutNumberArray(std::string_view key,
+ wpi::span<const double> value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -296,8 +299,8 @@
* @param defaultValue The default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultNumberArray(wpi::StringRef key,
- wpi::ArrayRef<double> defaultValue);
+ static bool SetDefaultNumberArray(std::string_view key,
+ wpi::span<const double> defaultValue);
/**
* Returns the number array the key maps to.
@@ -313,8 +316,8 @@
* @note This makes a copy of the array. If the overhead of this is a concern,
* use GetValue() instead.
*/
- static std::vector<double> GetNumberArray(wpi::StringRef key,
- wpi::ArrayRef<double> defaultValue);
+ static std::vector<double> GetNumberArray(
+ std::string_view key, wpi::span<const double> defaultValue);
/**
* Put a string array in the table.
@@ -323,8 +326,8 @@
* @param value The value that will be assigned.
* @return False if the table key already exists with a different type
*/
- static bool PutStringArray(wpi::StringRef key,
- wpi::ArrayRef<std::string> value);
+ static bool PutStringArray(std::string_view key,
+ wpi::span<const std::string> value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -333,8 +336,8 @@
* @param defaultValue The default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultStringArray(wpi::StringRef key,
- wpi::ArrayRef<std::string> defaultValue);
+ static bool SetDefaultStringArray(std::string_view key,
+ wpi::span<const std::string> defaultValue);
/**
* Returns the string array the key maps to.
@@ -351,7 +354,7 @@
* use GetValue() instead.
*/
static std::vector<std::string> GetStringArray(
- wpi::StringRef key, wpi::ArrayRef<std::string> defaultValue);
+ std::string_view key, wpi::span<const std::string> defaultValue);
/**
* Put a raw value (byte array) in the table.
@@ -360,7 +363,7 @@
* @param value The value that will be assigned.
* @return False if the table key already exists with a different type
*/
- static bool PutRaw(wpi::StringRef key, wpi::StringRef value);
+ static bool PutRaw(std::string_view key, std::string_view value);
/**
* Gets the current value in the table, setting it if it does not exist.
@@ -369,7 +372,8 @@
* @param defaultValue The default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultRaw(wpi::StringRef key, wpi::StringRef defaultValue);
+ static bool SetDefaultRaw(std::string_view key,
+ std::string_view defaultValue);
/**
* Returns the raw value (byte array) the key maps to.
@@ -385,7 +389,8 @@
* @note This makes a copy of the raw contents. If the overhead of this is a
* concern, use GetValue() instead.
*/
- static std::string GetRaw(wpi::StringRef key, wpi::StringRef defaultValue);
+ static std::string GetRaw(std::string_view key,
+ std::string_view defaultValue);
/**
* Maps the specified key to the specified complex value (such as an array) in
@@ -398,7 +403,7 @@
* @param value the value
* @return False if the table key already exists with a different type
*/
- static bool PutValue(wpi::StringRef keyName,
+ static bool PutValue(std::string_view keyName,
std::shared_ptr<nt::Value> value);
/**
@@ -408,7 +413,7 @@
* @param defaultValue The default value to set if key doesn't exist.
* @returns False if the table key exists with a different type
*/
- static bool SetDefaultValue(wpi::StringRef key,
+ static bool SetDefaultValue(std::string_view key,
std::shared_ptr<nt::Value> defaultValue);
/**
@@ -416,14 +421,12 @@
* complex data object.
*
* @param keyName the key
- * @param value the object to retrieve the value into
*/
- static std::shared_ptr<nt::Value> GetValue(wpi::StringRef keyName);
+ static std::shared_ptr<nt::Value> GetValue(std::string_view keyName);
/**
* Posts a task from a listener to the ListenerExecutor, so that it can be run
- * synchronously from the main loop on the next call to {@link
- * SmartDashboard#updateValues()}.
+ * synchronously from the main loop on the next call to updateValues().
*
* @param task The task to run synchronously from the main thread.
*/
@@ -433,11 +436,6 @@
* Puts all sendable data to the dashboard.
*/
static void UpdateValues();
-
- private:
- virtual ~SmartDashboard() = default;
-
- static detail::ListenerExecutor listenerExecutor;
};
} // namespace frc
diff --git a/wpilibc/src/main/native/include/frc/util/Color.h b/wpilibc/src/main/native/include/frc/util/Color.h
index 1321380..00bc4af 100644
--- a/wpilibc/src/main/native/include/frc/util/Color.h
+++ b/wpilibc/src/main/native/include/frc/util/Color.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -23,17 +20,17 @@
*/
/**
- * #1560BD.
+ * 0x1560BD.
*/
static const Color kDenim;
/**
- * #0066B3.
+ * 0x0066B3.
*/
static const Color kFirstBlue;
/**
- * #ED1C24.
+ * 0xED1C24.
*/
static const Color kFirstRed;
@@ -42,702 +39,702 @@
*/
/**
- * #F0F8FF.
+ * 0xF0F8FF.
*/
static const Color kAliceBlue;
/**
- * #FAEBD7.
+ * 0xFAEBD7.
*/
static const Color kAntiqueWhite;
/**
- * #00FFFF.
+ * 0x00FFFF.
*/
static const Color kAqua;
/**
- * #7FFFD4.
+ * 0x7FFFD4.
*/
static const Color kAquamarine;
/**
- * #F0FFFF.
+ * 0xF0FFFF.
*/
static const Color kAzure;
/**
- * #F5F5DC.
+ * 0xF5F5DC.
*/
static const Color kBeige;
/**
- * #FFE4C4.
+ * 0xFFE4C4.
*/
static const Color kBisque;
/**
- * #000000.
+ * 0x000000.
*/
static const Color kBlack;
/**
- * #FFEBCD.
+ * 0xFFEBCD.
*/
static const Color kBlanchedAlmond;
/**
- * #0000FF.
+ * 0x0000FF.
*/
static const Color kBlue;
/**
- * #8A2BE2.
+ * 0x8A2BE2.
*/
static const Color kBlueViolet;
/**
- * #A52A2A.
+ * 0xA52A2A.
*/
static const Color kBrown;
/**
- * #DEB887.
+ * 0xDEB887.
*/
static const Color kBurlywood;
/**
- * #5F9EA0.
+ * 0x5F9EA0.
*/
static const Color kCadetBlue;
/**
- * #7FFF00.
+ * 0x7FFF00.
*/
static const Color kChartreuse;
/**
- * #D2691E.
+ * 0xD2691E.
*/
static const Color kChocolate;
/**
- * #FF7F50.
+ * 0xFF7F50.
*/
static const Color kCoral;
/**
- * #6495ED.
+ * 0x6495ED.
*/
static const Color kCornflowerBlue;
/**
- * #FFF8DC.
+ * 0xFFF8DC.
*/
static const Color kCornsilk;
/**
- * #DC143C.
+ * 0xDC143C.
*/
static const Color kCrimson;
/**
- * #00FFFF.
+ * 0x00FFFF.
*/
static const Color kCyan;
/**
- * #00008B.
+ * 0x00008B.
*/
static const Color kDarkBlue;
/**
- * #008B8B.
+ * 0x008B8B.
*/
static const Color kDarkCyan;
/**
- * #B8860B.
+ * 0xB8860B.
*/
static const Color kDarkGoldenrod;
/**
- * #A9A9A9.
+ * 0xA9A9A9.
*/
static const Color kDarkGray;
/**
- * #006400.
+ * 0x006400.
*/
static const Color kDarkGreen;
/**
- * #BDB76B.
+ * 0xBDB76B.
*/
static const Color kDarkKhaki;
/**
- * #8B008B.
+ * 0x8B008B.
*/
static const Color kDarkMagenta;
/**
- * #556B2F.
+ * 0x556B2F.
*/
static const Color kDarkOliveGreen;
/**
- * #FF8C00.
+ * 0xFF8C00.
*/
static const Color kDarkOrange;
/**
- * #9932CC.
+ * 0x9932CC.
*/
static const Color kDarkOrchid;
/**
- * #8B0000.
+ * 0x8B0000.
*/
static const Color kDarkRed;
/**
- * #E9967A.
+ * 0xE9967A.
*/
static const Color kDarkSalmon;
/**
- * #8FBC8F.
+ * 0x8FBC8F.
*/
static const Color kDarkSeaGreen;
/**
- * #483D8B.
+ * 0x483D8B.
*/
static const Color kDarkSlateBlue;
/**
- * #2F4F4F.
+ * 0x2F4F4F.
*/
static const Color kDarkSlateGray;
/**
- * #00CED1.
+ * 0x00CED1.
*/
static const Color kDarkTurquoise;
/**
- * #9400D3.
+ * 0x9400D3.
*/
static const Color kDarkViolet;
/**
- * #FF1493.
+ * 0xFF1493.
*/
static const Color kDeepPink;
/**
- * #00BFFF.
+ * 0x00BFFF.
*/
static const Color kDeepSkyBlue;
/**
- * #696969.
+ * 0x696969.
*/
static const Color kDimGray;
/**
- * #1E90FF.
+ * 0x1E90FF.
*/
static const Color kDodgerBlue;
/**
- * #B22222.
+ * 0xB22222.
*/
static const Color kFirebrick;
/**
- * #FFFAF0.
+ * 0xFFFAF0.
*/
static const Color kFloralWhite;
/**
- * #228B22.
+ * 0x228B22.
*/
static const Color kForestGreen;
/**
- * #FF00FF.
+ * 0xFF00FF.
*/
static const Color kFuchsia;
/**
- * #DCDCDC.
+ * 0xDCDCDC.
*/
static const Color kGainsboro;
/**
- * #F8F8FF.
+ * 0xF8F8FF.
*/
static const Color kGhostWhite;
/**
- * #FFD700.
+ * 0xFFD700.
*/
static const Color kGold;
/**
- * #DAA520.
+ * 0xDAA520.
*/
static const Color kGoldenrod;
/**
- * #808080.
+ * 0x808080.
*/
static const Color kGray;
/**
- * #008000.
+ * 0x008000.
*/
static const Color kGreen;
/**
- * #ADFF2F.
+ * 0xADFF2F.
*/
static const Color kGreenYellow;
/**
- * #F0FFF0.
+ * 0xF0FFF0.
*/
static const Color kHoneydew;
/**
- * #FF69B4.
+ * 0xFF69B4.
*/
static const Color kHotPink;
/**
- * #CD5C5C.
+ * 0xCD5C5C.
*/
static const Color kIndianRed;
/**
- * #4B0082.
+ * 0x4B0082.
*/
static const Color kIndigo;
/**
- * #FFFFF0.
+ * 0xFFFFF0.
*/
static const Color kIvory;
/**
- * #F0E68C.
+ * 0xF0E68C.
*/
static const Color kKhaki;
/**
- * #E6E6FA.
+ * 0xE6E6FA.
*/
static const Color kLavender;
/**
- * #FFF0F5.
+ * 0xFFF0F5.
*/
static const Color kLavenderBlush;
/**
- * #7CFC00.
+ * 0x7CFC00.
*/
static const Color kLawnGreen;
/**
- * #FFFACD.
+ * 0xFFFACD.
*/
static const Color kLemonChiffon;
/**
- * #ADD8E6.
+ * 0xADD8E6.
*/
static const Color kLightBlue;
/**
- * #F08080.
+ * 0xF08080.
*/
static const Color kLightCoral;
/**
- * #E0FFFF.
+ * 0xE0FFFF.
*/
static const Color kLightCyan;
/**
- * #FAFAD2.
+ * 0xFAFAD2.
*/
static const Color kLightGoldenrodYellow;
/**
- * #D3D3D3.
+ * 0xD3D3D3.
*/
static const Color kLightGray;
/**
- * #90EE90.
+ * 0x90EE90.
*/
static const Color kLightGreen;
/**
- * #FFB6C1.
+ * 0xFFB6C1.
*/
static const Color kLightPink;
/**
- * #FFA07A.
+ * 0xFFA07A.
*/
static const Color kLightSalmon;
/**
- * #20B2AA.
+ * 0x20B2AA.
*/
static const Color kLightSeaGreen;
/**
- * #87CEFA.
+ * 0x87CEFA.
*/
static const Color kLightSkyBlue;
/**
- * #778899.
+ * 0x778899.
*/
static const Color kLightSlateGray;
/**
- * #B0C4DE.
+ * 0xB0C4DE.
*/
static const Color kLightSteelBlue;
/**
- * #FFFFE0.
+ * 0xFFFFE0.
*/
static const Color kLightYellow;
/**
- * #00FF00.
+ * 0x00FF00.
*/
static const Color kLime;
/**
- * #32CD32.
+ * 0x32CD32.
*/
static const Color kLimeGreen;
/**
- * #FAF0E6.
+ * 0xFAF0E6.
*/
static const Color kLinen;
/**
- * #FF00FF.
+ * 0xFF00FF.
*/
static const Color kMagenta;
/**
- * #800000.
+ * 0x800000.
*/
static const Color kMaroon;
/**
- * #66CDAA.
+ * 0x66CDAA.
*/
static const Color kMediumAquamarine;
/**
- * #0000CD.
+ * 0x0000CD.
*/
static const Color kMediumBlue;
/**
- * #BA55D3.
+ * 0xBA55D3.
*/
static const Color kMediumOrchid;
/**
- * #9370DB.
+ * 0x9370DB.
*/
static const Color kMediumPurple;
/**
- * #3CB371.
+ * 0x3CB371.
*/
static const Color kMediumSeaGreen;
/**
- * #7B68EE.
+ * 0x7B68EE.
*/
static const Color kMediumSlateBlue;
/**
- * #00FA9A.
+ * 0x00FA9A.
*/
static const Color kMediumSpringGreen;
/**
- * #48D1CC.
+ * 0x48D1CC.
*/
static const Color kMediumTurquoise;
/**
- * #C71585.
+ * 0xC71585.
*/
static const Color kMediumVioletRed;
/**
- * #191970.
+ * 0x191970.
*/
static const Color kMidnightBlue;
/**
- * #F5FFFA.
+ * 0xF5FFFA.
*/
static const Color kMintcream;
/**
- * #FFE4E1.
+ * 0xFFE4E1.
*/
static const Color kMistyRose;
/**
- * #FFE4B5.
+ * 0xFFE4B5.
*/
static const Color kMoccasin;
/**
- * #FFDEAD.
+ * 0xFFDEAD.
*/
static const Color kNavajoWhite;
/**
- * #000080.
+ * 0x000080.
*/
static const Color kNavy;
/**
- * #FDF5E6.
+ * 0xFDF5E6.
*/
static const Color kOldLace;
/**
- * #808000.
+ * 0x808000.
*/
static const Color kOlive;
/**
- * #6B8E23.
+ * 0x6B8E23.
*/
static const Color kOliveDrab;
/**
- * #FFA500.
+ * 0xFFA500.
*/
static const Color kOrange;
/**
- * #FF4500.
+ * 0xFF4500.
*/
static const Color kOrangeRed;
/**
- * #DA70D6.
+ * 0xDA70D6.
*/
static const Color kOrchid;
/**
- * #EEE8AA.
+ * 0xEEE8AA.
*/
static const Color kPaleGoldenrod;
/**
- * #98FB98.
+ * 0x98FB98.
*/
static const Color kPaleGreen;
/**
- * #AFEEEE.
+ * 0xAFEEEE.
*/
static const Color kPaleTurquoise;
/**
- * #DB7093.
+ * 0xDB7093.
*/
static const Color kPaleVioletRed;
/**
- * #FFEFD5.
+ * 0xFFEFD5.
*/
static const Color kPapayaWhip;
/**
- * #FFDAB9.
+ * 0xFFDAB9.
*/
static const Color kPeachPuff;
/**
- * #CD853F.
+ * 0xCD853F.
*/
static const Color kPeru;
/**
- * #FFC0CB.
+ * 0xFFC0CB.
*/
static const Color kPink;
/**
- * #DDA0DD.
+ * 0xDDA0DD.
*/
static const Color kPlum;
/**
- * #B0E0E6.
+ * 0xB0E0E6.
*/
static const Color kPowderBlue;
/**
- * #800080.
+ * 0x800080.
*/
static const Color kPurple;
/**
- * #FF0000.
+ * 0xFF0000.
*/
static const Color kRed;
/**
- * #BC8F8F.
+ * 0xBC8F8F.
*/
static const Color kRosyBrown;
/**
- * #4169E1.
+ * 0x4169E1.
*/
static const Color kRoyalBlue;
/**
- * #8B4513.
+ * 0x8B4513.
*/
static const Color kSaddleBrown;
/**
- * #FA8072.
+ * 0xFA8072.
*/
static const Color kSalmon;
/**
- * #F4A460.
+ * 0xF4A460.
*/
static const Color kSandyBrown;
/**
- * #2E8B57.
+ * 0x2E8B57.
*/
static const Color kSeaGreen;
/**
- * #FFF5EE.
+ * 0xFFF5EE.
*/
static const Color kSeashell;
/**
- * #A0522D.
+ * 0xA0522D.
*/
static const Color kSienna;
/**
- * #C0C0C0.
+ * 0xC0C0C0.
*/
static const Color kSilver;
/**
- * #87CEEB.
+ * 0x87CEEB.
*/
static const Color kSkyBlue;
/**
- * #6A5ACD.
+ * 0x6A5ACD.
*/
static const Color kSlateBlue;
/**
- * #708090.
+ * 0x708090.
*/
static const Color kSlateGray;
/**
- * #FFFAFA.
+ * 0xFFFAFA.
*/
static const Color kSnow;
/**
- * #00FF7F.
+ * 0x00FF7F.
*/
static const Color kSpringGreen;
/**
- * #4682B4.
+ * 0x4682B4.
*/
static const Color kSteelBlue;
/**
- * #D2B48C.
+ * 0xD2B48C.
*/
static const Color kTan;
/**
- * #008080.
+ * 0x008080.
*/
static const Color kTeal;
/**
- * #D8BFD8.
+ * 0xD8BFD8.
*/
static const Color kThistle;
/**
- * #FF6347.
+ * 0xFF6347.
*/
static const Color kTomato;
/**
- * #40E0D0.
+ * 0x40E0D0.
*/
static const Color kTurquoise;
/**
- * #EE82EE.
+ * 0xEE82EE.
*/
static const Color kViolet;
/**
- * #F5DEB3.
+ * 0xF5DEB3.
*/
static const Color kWheat;
/**
- * #FFFFFF.
+ * 0xFFFFFF.
*/
static const Color kWhite;
/**
- * #F5F5F5.
+ * 0xF5F5F5.
*/
static const Color kWhiteSmoke;
/**
- * #FFFF00.
+ * 0xFFFF00.
*/
static const Color kYellow;
/**
- * #9ACD32.
+ * 0x9ACD32.
*/
static const Color kYellowGreen;
@@ -746,9 +743,9 @@
/**
* Constructs a Color.
*
- * @param red Red value (0-1)
- * @param green Green value (0-1)
- * @param blue Blue value (0-1)
+ * @param r Red value (0-1)
+ * @param g Green value (0-1)
+ * @param b Blue value (0-1)
*/
constexpr Color(double r, double g, double b)
: red(roundAndClamp(r)),
@@ -809,6 +806,10 @@
return c1.red == c2.red && c1.green == c2.green && c1.blue == c2.blue;
}
+inline bool operator!=(const Color& c1, const Color& c2) {
+ return !(c1 == c2);
+}
+
/*
* FIRST Colors
*/
diff --git a/wpilibc/src/main/native/include/frc/util/Color8Bit.h b/wpilibc/src/main/native/include/frc/util/Color8Bit.h
index d5dba07..62cbde9 100644
--- a/wpilibc/src/main/native/include/frc/util/Color8Bit.h
+++ b/wpilibc/src/main/native/include/frc/util/Color8Bit.h
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
@@ -23,9 +20,9 @@
/**
* Constructs a Color8Bit.
*
- * @param red Red value (0-255)
- * @param green Green value (0-255)
- * @param blue Blue value (0-255)
+ * @param r Red value (0-255)
+ * @param g Green value (0-255)
+ * @param b Blue value (0-255)
*/
constexpr Color8Bit(int r, int g, int b)
: red(std::clamp(r, 0, 255)),
@@ -37,12 +34,12 @@
*
* @param color The color
*/
- constexpr Color8Bit(const Color& color)
+ constexpr Color8Bit(const Color& color) // NOLINT
: red(color.red * 255),
green(color.green * 255),
blue(color.blue * 255) {}
- constexpr operator Color() const {
+ constexpr operator Color() const { // NOLINT
return Color(red / 255.0, green / 255.0, blue / 255.0);
}
diff --git a/wpilibc/src/main/native/include/frc2/Timer.h b/wpilibc/src/main/native/include/frc2/Timer.h
deleted file mode 100644
index 8f943a6..0000000
--- a/wpilibc/src/main/native/include/frc2/Timer.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include <units/time.h>
-#include <wpi/mutex.h>
-
-namespace frc2 {
-
-/**
- * Pause the task for a specified time.
- *
- * Pause the execution of the program for a specified period of time given in
- * seconds. Motors will continue to run at their last assigned values, and
- * sensors will continue to update. Only the task containing the wait will pause
- * until the wait time is expired.
- *
- * @param seconds Length of time to pause, in seconds.
- */
-void Wait(units::second_t seconds);
-
-/**
- * @brief Gives real-time clock system time with nanosecond resolution
- * @return The time, just in case you want the robot to start autonomous at 8pm
- * on Saturday.
- */
-units::second_t GetTime();
-
-/**
- * A wrapper for the frc::Timer class that returns unit-typed values.
- */
-class Timer {
- public:
- /**
- * Create a new timer object.
- *
- * Create a new timer object and reset the time to zero. The timer is
- * initially not running and must be started.
- */
- Timer();
-
- virtual ~Timer() = default;
-
- Timer(const Timer& rhs);
- Timer& operator=(const Timer& rhs);
- Timer(Timer&& rhs);
- Timer& operator=(Timer&& rhs);
-
- /**
- * Get the current time from the timer. If the clock is running it is derived
- * from the current system clock the start time stored in the timer class. If
- * the clock is not running, then return the time when it was last stopped.
- *
- * @return Current time value for this timer in seconds
- */
- units::second_t Get() const;
-
- /**
- * Reset the timer by setting the time to 0.
- *
- * Make the timer startTime the current time so new requests will be relative
- * to now.
- */
- void Reset();
-
- /**
- * Start the timer running.
- *
- * Just set the running flag to true indicating that all time requests should
- * be relative to the system clock. Note that this method is a no-op if the
- * timer is already running.
- */
- void Start();
-
- /**
- * Stop the timer.
- *
- * This computes the time as of now and clears the running flag, causing all
- * subsequent time requests to be read from the accumulated time rather than
- * looking at the system clock.
- */
- void Stop();
-
- /**
- * Check if the period specified has passed.
- *
- * @param seconds The period to check.
- * @return True if the period has passed.
- */
- bool HasElapsed(units::second_t period) const;
-
- /**
- * Check if the period specified has passed and if it has, advance the start
- * time by that period. This is useful to decide if it's time to do periodic
- * work without drifting later by the time it took to get around to checking.
- *
- * @param period The period to check for.
- * @return True if the period has passed.
- */
- bool HasPeriodPassed(units::second_t period);
-
- /**
- * Check if the period specified has passed and if it has, advance the start
- * time by that period. This is useful to decide if it's time to do periodic
- * work without drifting later by the time it took to get around to checking.
- *
- * @param period The period to check for.
- * @return True if the period has passed.
- */
- bool AdvanceIfElapsed(units::second_t period);
-
- /**
- * Return the FPGA system clock time in seconds.
- *
- * Return the time from the FPGA hardware clock in seconds since the FPGA
- * started. Rolls over after 71 minutes.
- *
- * @returns Robot running time in seconds.
- */
- static units::second_t GetFPGATimestamp();
-
- /**
- * Return the approximate match time.
- *
- * The FMS does not send an official match time to the robots, but does send
- * an approximate match time. The value will count down the time remaining in
- * the current period (auto or teleop).
- *
- * Warning: This is not an official time (so it cannot be used to dispute ref
- * calls or guarantee that a function will trigger before the match ends).
- *
- * The Practice Match function of the DS approximates the behavior seen on the
- * field.
- *
- * @return Time remaining in current match period (auto or teleop)
- */
- static units::second_t GetMatchTime();
-
- private:
- units::second_t m_startTime = 0_s;
- units::second_t m_accumulatedTime = 0_s;
- bool m_running = false;
- mutable wpi::mutex m_mutex;
-};
-
-} // namespace frc2
diff --git a/wpilibc/src/test/native/c/test.c b/wpilibc/src/test/native/c/test.c
index 105e289..36d4f56 100644
--- a/wpilibc/src/test/native/c/test.c
+++ b/wpilibc/src/test/native/c/test.c
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <cscore.h>
#include <hal/HAL.h>
diff --git a/wpilibc/src/test/native/cpp/AnalogPotentiometerTest.cpp b/wpilibc/src/test/native/cpp/AnalogPotentiometerTest.cpp
new file mode 100644
index 0000000..de69894
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/AnalogPotentiometerTest.cpp
@@ -0,0 +1,92 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <hal/HAL.h>
+
+#include "frc/AnalogPotentiometer.h"
+#include "frc/simulation/AnalogInputSim.h"
+#include "frc/simulation/RoboRioSim.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+using namespace frc::sim;
+TEST(AnalogPotentiometerTest, InitializeWithAnalogInput) {
+ HAL_Initialize(500, 0);
+
+ AnalogInput ai{0};
+ AnalogPotentiometer pot{&ai};
+ AnalogInputSim sim{ai};
+
+ RoboRioSim::ResetData();
+ sim.SetVoltage(4.0);
+ EXPECT_EQ(0.8, pot.Get());
+}
+
+TEST(AnalogPotentiometerTest, InitializeWithAnalogInputAndScale) {
+ HAL_Initialize(500, 0);
+
+ AnalogInput ai{0};
+ AnalogPotentiometer pot{&ai, 270.0};
+ RoboRioSim::ResetData();
+ AnalogInputSim sim{ai};
+
+ sim.SetVoltage(5.0);
+ EXPECT_EQ(270.0, pot.Get());
+
+ sim.SetVoltage(2.5);
+ EXPECT_EQ(135, pot.Get());
+
+ sim.SetVoltage(0.0);
+ EXPECT_EQ(0.0, pot.Get());
+}
+
+TEST(AnalogPotentiometerTest, InitializeWithChannel) {
+ HAL_Initialize(500, 0);
+
+ AnalogPotentiometer pot{1};
+ AnalogInputSim sim{1};
+
+ sim.SetVoltage(5.0);
+ EXPECT_EQ(1.0, pot.Get());
+}
+
+TEST(AnalogPotentiometerTest, InitializeWithChannelAndScale) {
+ HAL_Initialize(500, 0);
+
+ AnalogPotentiometer pot{1, 180.0};
+ RoboRioSim::ResetData();
+ AnalogInputSim sim{1};
+
+ sim.SetVoltage(5.0);
+ EXPECT_EQ(180.0, pot.Get());
+
+ sim.SetVoltage(0.0);
+ EXPECT_EQ(0.0, pot.Get());
+}
+
+TEST(AnalogPotentiometerTest, WithModifiedBatteryVoltage) {
+ AnalogPotentiometer pot{1, 180.0, 90.0};
+ RoboRioSim::ResetData();
+ AnalogInputSim sim{1};
+
+ // Test at 5v
+ sim.SetVoltage(5.0);
+ EXPECT_EQ(270, pot.Get());
+
+ sim.SetVoltage(0.0);
+ EXPECT_EQ(90, pot.Get());
+
+ // Simulate a lower battery voltage
+ RoboRioSim::SetUserVoltage5V(units::volt_t{2.5});
+
+ sim.SetVoltage(2.5);
+ EXPECT_EQ(270, pot.Get());
+
+ sim.SetVoltage(2.0);
+ EXPECT_EQ(234, pot.Get());
+
+ sim.SetVoltage(0.0);
+ EXPECT_EQ(90, pot.Get());
+}
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/DebouncerTest.cpp b/wpilibc/src/test/native/cpp/DebouncerTest.cpp
new file mode 100644
index 0000000..379a6d5
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/DebouncerTest.cpp
@@ -0,0 +1,48 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/Debouncer.h" // NOLINT(build/include_order)
+
+#include "frc/simulation/SimHooks.h"
+#include "gtest/gtest.h"
+
+using namespace frc;
+
+TEST(DebouncerTest, DebounceRising) {
+ Debouncer debouncer{20_ms};
+
+ debouncer.Calculate(false);
+ EXPECT_FALSE(debouncer.Calculate(true));
+
+ frc::sim::StepTiming(100_ms);
+
+ EXPECT_TRUE(debouncer.Calculate(true));
+}
+
+TEST(DebouncerTest, DebounceFalling) {
+ Debouncer debouncer{20_ms, Debouncer::DebounceType::kFalling};
+
+ debouncer.Calculate(true);
+ EXPECT_TRUE(debouncer.Calculate(false));
+
+ frc::sim::StepTiming(100_ms);
+
+ EXPECT_FALSE(debouncer.Calculate(false));
+}
+
+TEST(DebouncerTest, DebounceBoth) {
+ Debouncer debouncer{20_ms, Debouncer::DebounceType::kBoth};
+
+ debouncer.Calculate(false);
+ EXPECT_FALSE(debouncer.Calculate(true));
+
+ frc::sim::StepTiming(100_ms);
+
+ EXPECT_TRUE(debouncer.Calculate(true));
+ EXPECT_TRUE(debouncer.Calculate(false));
+
+ frc::sim::StepTiming(100_ms);
+
+ EXPECT_FALSE(debouncer.Calculate(false));
+}
diff --git a/wpilibc/src/test/native/cpp/DoubleSolenoidTestCTRE.cpp b/wpilibc/src/test/native/cpp/DoubleSolenoidTestCTRE.cpp
new file mode 100644
index 0000000..2678395
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/DoubleSolenoidTestCTRE.cpp
@@ -0,0 +1,75 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <hal/HAL.h>
+
+#include "frc/DoubleSolenoid.h"
+#include "frc/PneumaticsControlModule.h"
+#include "frc/Solenoid.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+
+TEST(DoubleSolenoidCTRETest, ValidInitialization) {
+ DoubleSolenoid solenoid{3, frc::PneumaticsModuleType::CTREPCM, 2, 3};
+ solenoid.Set(DoubleSolenoid::kReverse);
+ EXPECT_EQ(DoubleSolenoid::kReverse, solenoid.Get());
+
+ solenoid.Set(DoubleSolenoid::kForward);
+ EXPECT_EQ(DoubleSolenoid::kForward, solenoid.Get());
+
+ solenoid.Set(DoubleSolenoid::kOff);
+ EXPECT_EQ(DoubleSolenoid::kOff, solenoid.Get());
+}
+
+TEST(DoubleSolenoidCTRETest, ThrowForwardPortAlreadyInitialized) {
+ // Single solenoid that is reused for forward port
+ Solenoid solenoid{5, frc::PneumaticsModuleType::CTREPCM, 2};
+ EXPECT_THROW(DoubleSolenoid(5, frc::PneumaticsModuleType::CTREPCM, 2, 3),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidCTRETest, ThrowReversePortAlreadyInitialized) {
+ // Single solenoid that is reused for forward port
+ Solenoid solenoid{6, frc::PneumaticsModuleType::CTREPCM, 3};
+ EXPECT_THROW(DoubleSolenoid(6, frc::PneumaticsModuleType::CTREPCM, 2, 3),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidCTRETest, ThrowBothPortsAlreadyInitialized) {
+ PneumaticsControlModule pcm{6};
+ // Single solenoid that is reused for forward port
+ Solenoid solenoid0(6, frc::PneumaticsModuleType::CTREPCM, 2);
+ Solenoid solenoid1(6, frc::PneumaticsModuleType::CTREPCM, 3);
+ EXPECT_THROW(DoubleSolenoid(6, frc::PneumaticsModuleType::CTREPCM, 2, 3),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidCTRETest, Toggle) {
+ DoubleSolenoid solenoid{4, frc::PneumaticsModuleType::CTREPCM, 2, 3};
+ // Bootstrap it into reverse
+ solenoid.Set(DoubleSolenoid::kReverse);
+
+ solenoid.Toggle();
+ EXPECT_EQ(DoubleSolenoid::kForward, solenoid.Get());
+
+ solenoid.Toggle();
+ EXPECT_EQ(DoubleSolenoid::kReverse, solenoid.Get());
+
+ // Of shouldn't do anything on toggle
+ solenoid.Set(DoubleSolenoid::kOff);
+ solenoid.Toggle();
+ EXPECT_EQ(DoubleSolenoid::kOff, solenoid.Get());
+}
+
+TEST(DoubleSolenoidCTRETest, InvalidForwardPort) {
+ EXPECT_THROW(DoubleSolenoid(0, frc::PneumaticsModuleType::CTREPCM, 100, 1),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidCTRETest, InvalidReversePort) {
+ EXPECT_THROW(DoubleSolenoid(0, frc::PneumaticsModuleType::CTREPCM, 0, 100),
+ std::runtime_error);
+}
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/DoubleSolenoidTestREV.cpp b/wpilibc/src/test/native/cpp/DoubleSolenoidTestREV.cpp
new file mode 100644
index 0000000..23893c4
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/DoubleSolenoidTestREV.cpp
@@ -0,0 +1,75 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <hal/HAL.h>
+
+#include "frc/DoubleSolenoid.h"
+#include "frc/PneumaticsControlModule.h"
+#include "frc/Solenoid.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+
+TEST(DoubleSolenoidREVTest, ValidInitialization) {
+ DoubleSolenoid solenoid{3, frc::PneumaticsModuleType::CTREPCM, 2, 3};
+ solenoid.Set(DoubleSolenoid::kReverse);
+ EXPECT_EQ(DoubleSolenoid::kReverse, solenoid.Get());
+
+ solenoid.Set(DoubleSolenoid::kForward);
+ EXPECT_EQ(DoubleSolenoid::kForward, solenoid.Get());
+
+ solenoid.Set(DoubleSolenoid::kOff);
+ EXPECT_EQ(DoubleSolenoid::kOff, solenoid.Get());
+}
+
+TEST(DoubleSolenoidREVTest, ThrowForwardPortAlreadyInitialized) {
+ // Single solenoid that is reused for forward port
+ Solenoid solenoid{5, frc::PneumaticsModuleType::CTREPCM, 2};
+ EXPECT_THROW(DoubleSolenoid(5, frc::PneumaticsModuleType::CTREPCM, 2, 3),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidREVTest, ThrowReversePortAlreadyInitialized) {
+ // Single solenoid that is reused for forward port
+ Solenoid solenoid{6, frc::PneumaticsModuleType::CTREPCM, 3};
+ EXPECT_THROW(DoubleSolenoid(6, frc::PneumaticsModuleType::CTREPCM, 2, 3),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidREVTest, ThrowBothPortsAlreadyInitialized) {
+ PneumaticsControlModule pcm{6};
+ // Single solenoid that is reused for forward port
+ Solenoid solenoid0(6, frc::PneumaticsModuleType::CTREPCM, 2);
+ Solenoid solenoid1(6, frc::PneumaticsModuleType::CTREPCM, 3);
+ EXPECT_THROW(DoubleSolenoid(6, frc::PneumaticsModuleType::CTREPCM, 2, 3),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidREVTest, Toggle) {
+ DoubleSolenoid solenoid{4, frc::PneumaticsModuleType::CTREPCM, 2, 3};
+ // Bootstrap it into reverse
+ solenoid.Set(DoubleSolenoid::kReverse);
+
+ solenoid.Toggle();
+ EXPECT_EQ(DoubleSolenoid::kForward, solenoid.Get());
+
+ solenoid.Toggle();
+ EXPECT_EQ(DoubleSolenoid::kReverse, solenoid.Get());
+
+ // Of shouldn't do anything on toggle
+ solenoid.Set(DoubleSolenoid::kOff);
+ solenoid.Toggle();
+ EXPECT_EQ(DoubleSolenoid::kOff, solenoid.Get());
+}
+
+TEST(DoubleSolenoidREVTest, InvalidForwardPort) {
+ EXPECT_THROW(DoubleSolenoid(0, frc::PneumaticsModuleType::CTREPCM, 100, 1),
+ std::runtime_error);
+}
+
+TEST(DoubleSolenoidREVTest, InvalidReversePort) {
+ EXPECT_THROW(DoubleSolenoid(0, frc::PneumaticsModuleType::CTREPCM, 0, 100),
+ std::runtime_error);
+}
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/DriverStationTest.cpp b/wpilibc/src/test/native/cpp/DriverStationTest.cpp
index 3b8272f..c191e2b 100644
--- a/wpilibc/src/test/native/cpp/DriverStationTest.cpp
+++ b/wpilibc/src/test/native/cpp/DriverStationTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <string>
#include <tuple>
@@ -14,10 +11,10 @@
#include "frc/simulation/SimHooks.h"
#include "gtest/gtest.h"
-class IsJoystickConnectedParametersTests
+class IsJoystickConnectedParametersTest
: public ::testing::TestWithParam<std::tuple<int, int, int, bool>> {};
-TEST_P(IsJoystickConnectedParametersTests, IsJoystickConnected) {
+TEST_P(IsJoystickConnectedParametersTest, IsJoystickConnected) {
frc::sim::DriverStationSim::SetJoystickAxisCount(1, std::get<0>(GetParam()));
frc::sim::DriverStationSim::SetJoystickButtonCount(1,
std::get<1>(GetParam()));
@@ -25,50 +22,54 @@
frc::sim::DriverStationSim::NotifyNewData();
ASSERT_EQ(std::get<3>(GetParam()),
- frc::DriverStation::GetInstance().IsJoystickConnected(1));
+ frc::DriverStation::IsJoystickConnected(1));
}
-INSTANTIATE_TEST_SUITE_P(IsConnectedTests, IsJoystickConnectedParametersTests,
+INSTANTIATE_TEST_SUITE_P(IsConnectedTests, IsJoystickConnectedParametersTest,
::testing::Values(std::make_tuple(0, 0, 0, false),
std::make_tuple(1, 0, 0, true),
std::make_tuple(0, 1, 0, true),
std::make_tuple(0, 0, 1, true),
std::make_tuple(1, 1, 1, true),
std::make_tuple(4, 10, 1, true)));
-class JoystickConnectionWarningTests
+class JoystickConnectionWarningTest
: public ::testing::TestWithParam<
std::tuple<bool, bool, bool, std::string>> {};
-TEST_P(JoystickConnectionWarningTests, JoystickConnectionWarnings) {
+TEST_P(JoystickConnectionWarningTest, JoystickConnectionWarnings) {
// Capture all output to stderr.
::testing::internal::CaptureStderr();
// Set FMS and Silence settings
frc::sim::DriverStationSim::SetFmsAttached(std::get<0>(GetParam()));
frc::sim::DriverStationSim::NotifyNewData();
- frc::DriverStation::GetInstance().SilenceJoystickConnectionWarning(
- std::get<1>(GetParam()));
+ frc::DriverStation::SilenceJoystickConnectionWarning(std::get<1>(GetParam()));
// Create joystick and attempt to retrieve button.
frc::Joystick joystick(0);
joystick.GetRawButton(1);
frc::sim::StepTiming(1_s);
- EXPECT_EQ(
- frc::DriverStation::GetInstance().IsJoystickConnectionWarningSilenced(),
- std::get<2>(GetParam()));
- EXPECT_EQ(::testing::internal::GetCapturedStderr(), std::get<3>(GetParam()));
+ EXPECT_EQ(frc::DriverStation::IsJoystickConnectionWarningSilenced(),
+ std::get<2>(GetParam()));
+ EXPECT_EQ(::testing::internal::GetCapturedStderr().substr(
+ 0, std::get<3>(GetParam()).size()),
+ std::get<3>(GetParam()));
}
INSTANTIATE_TEST_SUITE_P(
- DriverStation, JoystickConnectionWarningTests,
- ::testing::Values(std::make_tuple(false, true, true, ""),
- std::make_tuple(false, false, false,
- "Joystick Button missing, check if all "
- "controllers are plugged in\n"),
- std::make_tuple(true, true, false,
- "Joystick Button missing, check if all "
- "controllers are plugged in\n"),
- std::make_tuple(true, false, false,
- "Joystick Button missing, check if all "
- "controllers are plugged in\n")));
+ DriverStationTests, JoystickConnectionWarningTest,
+ ::testing::Values(
+ std::make_tuple(false, true, true, ""),
+ std::make_tuple(
+ false, false, false,
+ "Warning: Joystick Button 1 missing (max 0), check if all "
+ "controllers are plugged in\n"),
+ std::make_tuple(
+ true, true, false,
+ "Warning: Joystick Button 1 missing (max 0), check if all "
+ "controllers are plugged in\n"),
+ std::make_tuple(
+ true, false, false,
+ "Warning: Joystick Button 1 missing (max 0), check if all "
+ "controllers are plugged in\n")));
diff --git a/wpilibc/src/test/native/cpp/InterruptTest.cpp b/wpilibc/src/test/native/cpp/InterruptTest.cpp
new file mode 100644
index 0000000..1bf0aa2
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/InterruptTest.cpp
@@ -0,0 +1,45 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <atomic>
+
+#include <hal/HAL.h>
+
+#include "frc/AsynchronousInterrupt.h"
+#include "frc/DigitalInput.h"
+#include "frc/Timer.h"
+#include "frc/simulation/DIOSim.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+using namespace frc::sim;
+TEST(InterruptTest, AsynchronousInterrupt) {
+ HAL_Initialize(500, 0);
+
+ std::atomic_int counter{0};
+ std::atomic_bool hasFired{false};
+
+ DigitalInput di{0};
+ AsynchronousInterrupt interrupt{di, [&](bool rising, bool falling) {
+ counter++;
+ hasFired = true;
+ }};
+
+ interrupt.Enable();
+ frc::Wait(0.5_s);
+ DIOSim digitalSim{di};
+ digitalSim.SetValue(false);
+ frc::Wait(20_ms);
+ digitalSim.SetValue(true);
+ frc::Wait(10_ms);
+
+ int count = 0;
+ while (!hasFired) {
+ frc::Wait(5_ms);
+ count++;
+ ASSERT_TRUE(count < 1000);
+ }
+ ASSERT_EQ(1, counter.load());
+}
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/JoystickTest.cpp b/wpilibc/src/test/native/cpp/JoystickTest.cpp
index 0480b76..5697879 100644
--- a/wpilibc/src/test/native/cpp/JoystickTest.cpp
+++ b/wpilibc/src/test/native/cpp/JoystickTest.cpp
@@ -1,39 +1,20 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Joystick.h" // NOLINT(build/include_order)
+#include "JoystickTestMacros.h"
#include "frc/simulation/JoystickSim.h"
#include "gtest/gtest.h"
using namespace frc;
-TEST(JoystickTests, GetX) {
- Joystick joy{1};
- sim::JoystickSim joysim{joy};
+AXIS_TEST(Joystick, X)
+AXIS_TEST(Joystick, Y)
+AXIS_TEST(Joystick, Z)
+AXIS_TEST(Joystick, Throttle)
+AXIS_TEST(Joystick, Twist)
- joysim.SetX(0.25);
- joysim.NotifyNewData();
- ASSERT_NEAR(joy.GetX(), 0.25, 0.001);
-
- joysim.SetX(0);
- joysim.NotifyNewData();
- ASSERT_NEAR(joy.GetX(), 0, 0.001);
-}
-
-TEST(JoystickTests, GetY) {
- Joystick joy{1};
- sim::JoystickSim joysim{joy};
-
- joysim.SetY(0.25);
- joysim.NotifyNewData();
- ASSERT_NEAR(joy.GetY(), 0.25, 0.001);
-
- joysim.SetY(0);
- joysim.NotifyNewData();
- ASSERT_NEAR(joy.GetY(), 0, 0.001);
-}
+BUTTON_TEST(Joystick, Trigger)
+BUTTON_TEST(Joystick, Top)
diff --git a/wpilibc/src/test/native/cpp/JoystickTestMacros.h b/wpilibc/src/test/native/cpp/JoystickTestMacros.h
new file mode 100644
index 0000000..81ccedc
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/JoystickTestMacros.h
@@ -0,0 +1,39 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#define AXIS_TEST(JoystickType, AxisName) \
+ TEST(JoystickType##Test, Get##AxisName) { \
+ JoystickType joy{2}; \
+ sim::JoystickType##Sim joysim{joy}; \
+ joysim.Set##AxisName(0.35); \
+ joysim.NotifyNewData(); \
+ ASSERT_NEAR(joy.Get##AxisName(), 0.35, 0.001); \
+ }
+
+#define BUTTON_TEST(JoystickType, ButtonName) \
+ TEST(JoystickType##Test, Get##ButtonName) { \
+ JoystickType joy{1}; \
+ sim::JoystickType##Sim joysim{joy}; \
+ \
+ joysim.Set##ButtonName(false); \
+ joysim.NotifyNewData(); \
+ ASSERT_FALSE(joy.Get##ButtonName()); \
+ /* need to call pressed and released to clear flags */ \
+ joy.Get##ButtonName##Pressed(); \
+ joy.Get##ButtonName##Released(); \
+ \
+ joysim.Set##ButtonName(true); \
+ joysim.NotifyNewData(); \
+ ASSERT_TRUE(joy.Get##ButtonName()); \
+ ASSERT_TRUE(joy.Get##ButtonName##Pressed()); \
+ ASSERT_FALSE(joy.Get##ButtonName##Released()); \
+ \
+ joysim.Set##ButtonName(false); \
+ joysim.NotifyNewData(); \
+ ASSERT_FALSE(joy.Get##ButtonName()); \
+ ASSERT_FALSE(joy.Get##ButtonName##Pressed()); \
+ ASSERT_TRUE(joy.Get##ButtonName##Released()); \
+ }
diff --git a/wpilibc/src/test/native/cpp/MockMotorController.cpp b/wpilibc/src/test/native/cpp/MockMotorController.cpp
new file mode 100644
index 0000000..62fd54a
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/MockMotorController.cpp
@@ -0,0 +1,31 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "MockMotorController.h"
+
+using namespace frc;
+
+void MockMotorController::Set(double speed) {
+ m_speed = m_isInverted ? -speed : speed;
+}
+
+double MockMotorController::Get() const {
+ return m_speed;
+}
+
+void MockMotorController::SetInverted(bool isInverted) {
+ m_isInverted = isInverted;
+}
+
+bool MockMotorController::GetInverted() const {
+ return m_isInverted;
+}
+
+void MockMotorController::Disable() {
+ m_speed = 0;
+}
+
+void MockMotorController::StopMotor() {
+ Disable();
+}
diff --git a/wpilibc/src/test/native/cpp/MockSpeedController.cpp b/wpilibc/src/test/native/cpp/MockSpeedController.cpp
deleted file mode 100644
index 875fec1..0000000
--- a/wpilibc/src/test/native/cpp/MockSpeedController.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "MockSpeedController.h"
-
-using namespace frc;
-
-void MockSpeedController::Set(double speed) {
- m_speed = m_isInverted ? -speed : speed;
-}
-
-double MockSpeedController::Get() const { return m_speed; }
-
-void MockSpeedController::SetInverted(bool isInverted) {
- m_isInverted = isInverted;
-}
-
-bool MockSpeedController::GetInverted() const { return m_isInverted; }
-
-void MockSpeedController::Disable() { m_speed = 0; }
-
-void MockSpeedController::StopMotor() { Disable(); }
-
-void MockSpeedController::PIDWrite(double output) { Set(output); }
diff --git a/wpilibc/src/test/native/cpp/PS4ControllerTest.cpp b/wpilibc/src/test/native/cpp/PS4ControllerTest.cpp
new file mode 100644
index 0000000..329a165
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/PS4ControllerTest.cpp
@@ -0,0 +1,37 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/PS4Controller.h" // NOLINT(build/include_order)
+
+#include "JoystickTestMacros.h"
+#include "frc/simulation/PS4ControllerSim.h"
+#include "gtest/gtest.h"
+
+using namespace frc;
+
+BUTTON_TEST(PS4Controller, SquareButton)
+BUTTON_TEST(PS4Controller, CrossButton)
+BUTTON_TEST(PS4Controller, CircleButton)
+BUTTON_TEST(PS4Controller, TriangleButton)
+
+BUTTON_TEST(PS4Controller, L1Button)
+BUTTON_TEST(PS4Controller, R1Button)
+BUTTON_TEST(PS4Controller, L2Button)
+BUTTON_TEST(PS4Controller, R2Button)
+
+BUTTON_TEST(PS4Controller, ShareButton)
+BUTTON_TEST(PS4Controller, OptionsButton)
+
+BUTTON_TEST(PS4Controller, L3Button)
+BUTTON_TEST(PS4Controller, R3Button)
+
+BUTTON_TEST(PS4Controller, PSButton)
+BUTTON_TEST(PS4Controller, Touchpad)
+
+AXIS_TEST(PS4Controller, LeftX)
+AXIS_TEST(PS4Controller, RightX)
+AXIS_TEST(PS4Controller, LeftY)
+AXIS_TEST(PS4Controller, RightY)
+AXIS_TEST(PS4Controller, L2Axis)
+AXIS_TEST(PS4Controller, R2Axis)
diff --git a/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp b/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp
index da222de..c4ef317 100644
--- a/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp
+++ b/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp
@@ -1,33 +1,28 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
-#include <string>
-#include <thread>
+#include <string_view>
#include <wpi/SmallString.h>
-#include <wpi/StringRef.h>
+#include <wpi/StringExtras.h>
#include <wpi/raw_ostream.h>
#include "frc/ScopedTracer.h"
+#include "frc/simulation/SimHooks.h"
#include "gtest/gtest.h"
-wpi::SmallString<128> buf;
-wpi::raw_svector_ostream os(buf);
-
-#ifdef __APPLE__
-TEST(ScopedTracerTest, DISABLED_Timing) {
-#else
TEST(ScopedTracerTest, Timing) {
-#endif
+ wpi::SmallString<128> buf;
+ wpi::raw_svector_ostream os(buf);
+
+ frc::sim::PauseTiming();
{
frc::ScopedTracer tracer("timing_test", os);
- std::this_thread::sleep_for(std::chrono::milliseconds(1500));
+ frc::sim::StepTiming(1.5_s);
}
+ frc::sim::ResumeTiming();
- wpi::StringRef out = os.str();
- EXPECT_TRUE(out.startswith(" timing_test: 1.5"));
+ std::string_view out = os.str();
+ EXPECT_TRUE(wpi::starts_with(out, " timing_test: 1.5"));
}
diff --git a/wpilibc/src/test/native/cpp/SlewRateLimiterTest.cpp b/wpilibc/src/test/native/cpp/SlewRateLimiterTest.cpp
deleted file mode 100644
index dea56bb..0000000
--- a/wpilibc/src/test/native/cpp/SlewRateLimiterTest.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include <thread>
-
-#include <units/length.h>
-#include <units/time.h>
-#include <units/velocity.h>
-
-#include "frc/SlewRateLimiter.h"
-#include "frc/simulation/SimHooks.h"
-#include "gtest/gtest.h"
-
-TEST(SlewRateLimiterTest, SlewRateLimitTest) {
- frc::SlewRateLimiter<units::meters> limiter(1_mps);
-
- frc::sim::StepTiming(1.0_s);
-
- EXPECT_TRUE(limiter.Calculate(2_m) < 2_m);
-}
-
-TEST(SlewRateLimiterTest, SlewRateNoLimitTest) {
- frc::SlewRateLimiter<units::meters> limiter(1_mps);
-
- frc::sim::StepTiming(1.0_s);
-
- EXPECT_EQ(limiter.Calculate(0.5_m), 0.5_m);
-}
diff --git a/wpilibc/src/test/native/cpp/SolenoidTestCTRE.cpp b/wpilibc/src/test/native/cpp/SolenoidTestCTRE.cpp
new file mode 100644
index 0000000..61e3fb6
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/SolenoidTestCTRE.cpp
@@ -0,0 +1,52 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <hal/HAL.h>
+
+#include "frc/DoubleSolenoid.h"
+#include "frc/PneumaticsControlModule.h"
+#include "frc/Solenoid.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+TEST(SolenoidCTRETest, ValidInitialization) {
+ Solenoid solenoid{3, frc::PneumaticsModuleType::CTREPCM, 2};
+ EXPECT_EQ(2, solenoid.GetChannel());
+
+ solenoid.Set(true);
+ EXPECT_TRUE(solenoid.Get());
+
+ solenoid.Set(false);
+ EXPECT_FALSE(solenoid.Get());
+}
+
+TEST(SolenoidCTRETest, DoubleInitialization) {
+ Solenoid solenoid{3, frc::PneumaticsModuleType::CTREPCM, 2};
+ EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::CTREPCM, 2),
+ std::runtime_error);
+}
+
+TEST(SolenoidCTRETest, DoubleInitializationFromDoubleSolenoid) {
+ DoubleSolenoid solenoid{3, frc::PneumaticsModuleType::CTREPCM, 2, 3};
+ EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::CTREPCM, 2),
+ std::runtime_error);
+}
+
+TEST(SolenoidCTRETest, InvalidChannel) {
+ EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::CTREPCM, 100),
+ std::runtime_error);
+}
+
+TEST(SolenoidCTRETest, Toggle) {
+ Solenoid solenoid{3, frc::PneumaticsModuleType::CTREPCM, 2};
+ solenoid.Set(true);
+ EXPECT_TRUE(solenoid.Get());
+
+ solenoid.Toggle();
+ EXPECT_FALSE(solenoid.Get());
+
+ solenoid.Toggle();
+ EXPECT_TRUE(solenoid.Get());
+}
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/SolenoidTestREV.cpp b/wpilibc/src/test/native/cpp/SolenoidTestREV.cpp
new file mode 100644
index 0000000..75ea261
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/SolenoidTestREV.cpp
@@ -0,0 +1,52 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <hal/HAL.h>
+
+#include "frc/DoubleSolenoid.h"
+#include "frc/PneumaticsControlModule.h"
+#include "frc/Solenoid.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+TEST(SolenoidREVTest, ValidInitialization) {
+ Solenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2};
+ EXPECT_EQ(2, solenoid.GetChannel());
+
+ solenoid.Set(true);
+ EXPECT_TRUE(solenoid.Get());
+
+ solenoid.Set(false);
+ EXPECT_FALSE(solenoid.Get());
+}
+
+TEST(SolenoidREVTest, DoubleInitialization) {
+ Solenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2};
+ EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::REVPH, 2),
+ std::runtime_error);
+}
+
+TEST(SolenoidREVTest, DoubleInitializationFromDoubleSolenoid) {
+ DoubleSolenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2, 3};
+ EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::REVPH, 2),
+ std::runtime_error);
+}
+
+TEST(SolenoidREVTest, InvalidChannel) {
+ EXPECT_THROW(Solenoid(3, frc::PneumaticsModuleType::REVPH, 100),
+ std::runtime_error);
+}
+
+TEST(SolenoidREVTest, Toggle) {
+ Solenoid solenoid{3, frc::PneumaticsModuleType::REVPH, 2};
+ solenoid.Set(true);
+ EXPECT_TRUE(solenoid.Get());
+
+ solenoid.Toggle();
+ EXPECT_FALSE(solenoid.Get());
+
+ solenoid.Toggle();
+ EXPECT_TRUE(solenoid.Get());
+}
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/SpeedControllerGroupTest.cpp b/wpilibc/src/test/native/cpp/SpeedControllerGroupTest.cpp
index cb81fc9..38e1592 100644
--- a/wpilibc/src/test/native/cpp/SpeedControllerGroupTest.cpp
+++ b/wpilibc/src/test/native/cpp/SpeedControllerGroupTest.cpp
@@ -1,33 +1,30 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
-#include "frc/SpeedControllerGroup.h" // NOLINT(build/include_order)
+#include "frc/motorcontrol/MotorControllerGroup.h" // NOLINT(build/include_order)
#include <memory>
#include <vector>
-#include "MockSpeedController.h"
+#include "MockMotorController.h"
#include "gtest/gtest.h"
using namespace frc;
-enum SpeedControllerGroupTestType { TEST_ONE, TEST_TWO, TEST_THREE };
+enum MotorControllerGroupTestType { TEST_ONE, TEST_TWO, TEST_THREE };
std::ostream& operator<<(std::ostream& os,
- const SpeedControllerGroupTestType& type) {
+ const MotorControllerGroupTestType& type) {
switch (type) {
case TEST_ONE:
- os << "SpeedControllerGroup with one speed controller";
+ os << "MotorControllerGroup with one speed controller";
break;
case TEST_TWO:
- os << "SpeedControllerGroup with two speed controllers";
+ os << "MotorControllerGroup with two speed controllers";
break;
case TEST_THREE:
- os << "SpeedControllerGroup with three speed controllers";
+ os << "MotorControllerGroup with three speed controllers";
break;
}
@@ -35,26 +32,26 @@
}
/**
- * A fixture used for SpeedControllerGroup testing.
+ * A fixture used for MotorControllerGroup testing.
*/
-class SpeedControllerGroupTest
- : public testing::TestWithParam<SpeedControllerGroupTestType> {
+class MotorControllerGroupTest
+ : public testing::TestWithParam<MotorControllerGroupTestType> {
protected:
- std::vector<MockSpeedController> m_speedControllers;
- std::unique_ptr<SpeedControllerGroup> m_group;
+ std::vector<MockMotorController> m_speedControllers;
+ std::unique_ptr<MotorControllerGroup> m_group;
void SetUp() override {
switch (GetParam()) {
case TEST_ONE: {
m_speedControllers.emplace_back();
- m_group = std::make_unique<SpeedControllerGroup>(m_speedControllers[0]);
+ m_group = std::make_unique<MotorControllerGroup>(m_speedControllers[0]);
break;
}
case TEST_TWO: {
m_speedControllers.emplace_back();
m_speedControllers.emplace_back();
- m_group = std::make_unique<SpeedControllerGroup>(m_speedControllers[0],
+ m_group = std::make_unique<MotorControllerGroup>(m_speedControllers[0],
m_speedControllers[1]);
break;
}
@@ -63,7 +60,7 @@
m_speedControllers.emplace_back();
m_speedControllers.emplace_back();
m_speedControllers.emplace_back();
- m_group = std::make_unique<SpeedControllerGroup>(m_speedControllers[0],
+ m_group = std::make_unique<MotorControllerGroup>(m_speedControllers[0],
m_speedControllers[1],
m_speedControllers[2]);
break;
@@ -72,7 +69,7 @@
}
};
-TEST_P(SpeedControllerGroupTest, Set) {
+TEST_P(MotorControllerGroupTest, Set) {
m_group->Set(1.0);
for (auto& speedController : m_speedControllers) {
@@ -80,13 +77,13 @@
}
}
-TEST_P(SpeedControllerGroupTest, GetInverted) {
+TEST_P(MotorControllerGroupTest, GetInverted) {
m_group->SetInverted(true);
EXPECT_TRUE(m_group->GetInverted());
}
-TEST_P(SpeedControllerGroupTest, SetInvertedDoesNotModifySpeedControllers) {
+TEST_P(MotorControllerGroupTest, SetInvertedDoesNotModifyMotorControllers) {
for (auto& speedController : m_speedControllers) {
speedController.SetInverted(false);
}
@@ -97,7 +94,7 @@
}
}
-TEST_P(SpeedControllerGroupTest, SetInvertedDoesInvert) {
+TEST_P(MotorControllerGroupTest, SetInvertedDoesInvert) {
m_group->SetInverted(true);
m_group->Set(1.0);
@@ -106,7 +103,7 @@
}
}
-TEST_P(SpeedControllerGroupTest, Disable) {
+TEST_P(MotorControllerGroupTest, Disable) {
m_group->Set(1.0);
m_group->Disable();
@@ -115,7 +112,7 @@
}
}
-TEST_P(SpeedControllerGroupTest, StopMotor) {
+TEST_P(MotorControllerGroupTest, StopMotor) {
m_group->Set(1.0);
m_group->StopMotor();
@@ -124,13 +121,5 @@
}
}
-TEST_P(SpeedControllerGroupTest, PIDWrite) {
- m_group->PIDWrite(1.0);
-
- for (auto& speedController : m_speedControllers) {
- EXPECT_FLOAT_EQ(speedController.Get(), 1.0);
- }
-}
-
-INSTANTIATE_TEST_SUITE_P(Test, SpeedControllerGroupTest,
+INSTANTIATE_TEST_SUITE_P(Tests, MotorControllerGroupTest,
testing::Values(TEST_ONE, TEST_TWO, TEST_THREE));
diff --git a/wpilibc/src/test/native/cpp/TestCallbackHelpers.cpp b/wpilibc/src/test/native/cpp/TestCallbackHelpers.cpp
new file mode 100644
index 0000000..d98f539
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/TestCallbackHelpers.cpp
@@ -0,0 +1,82 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "callback_helpers/TestCallbackHelpers.h"
+
+#include <iostream>
+
+#include <fmt/format.h>
+
+namespace frc::sim {
+
+void BooleanCallback::HandleCallback(std::string_view name,
+ const HAL_Value* value) {
+ if (!value) {
+ throw std::invalid_argument("Null value");
+ }
+ if (value->type != HAL_BOOLEAN) {
+ throw std::invalid_argument(
+ fmt::format("Wrong type '{}' for boolean", value->type).c_str());
+ }
+ m_wasTriggered = true;
+ m_lastValue = value->data.v_boolean;
+}
+
+void EnumCallback::HandleCallback(std::string_view name,
+ const HAL_Value* value) {
+ if (!value) {
+ throw std::invalid_argument("Null value");
+ }
+ if (value->type != HAL_ENUM) {
+ throw std::invalid_argument(
+ fmt::format("Wrong type '{}' for enum", value->type).c_str());
+ }
+
+ m_wasTriggered = true;
+ m_lastValue = value->data.v_enum;
+}
+
+void IntCallback::HandleCallback(std::string_view name,
+ const HAL_Value* value) {
+ if (!value) {
+ throw std::invalid_argument("Null value");
+ }
+ if (value->type != HAL_INT) {
+ throw std::invalid_argument(
+ fmt::format("Wrong type '{}' for integer", value->type).c_str());
+ }
+
+ m_wasTriggered = true;
+ m_lastValue = value->data.v_int;
+}
+
+void LongCallback::HandleCallback(std::string_view name,
+ const HAL_Value* value) {
+ if (!value) {
+ throw std::invalid_argument("Null value");
+ }
+ if (value->type != HAL_LONG) {
+ throw std::invalid_argument(
+ fmt::format("Wrong type '{}' for long", value->type).c_str());
+ }
+
+ m_wasTriggered = true;
+ m_lastValue = value->data.v_long;
+}
+
+void DoubleCallback::HandleCallback(std::string_view name,
+ const HAL_Value* value) {
+ if (!value) {
+ throw std::invalid_argument("Null value");
+ }
+ if (value->type != HAL_DOUBLE) {
+ throw std::invalid_argument(
+ fmt::format("Wrong type '{}' for double", value->type).c_str());
+ }
+
+ m_wasTriggered = true;
+ m_lastValue = value->data.v_double;
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/TimedRobotTest.cpp b/wpilibc/src/test/native/cpp/TimedRobotTest.cpp
index f91efb8..ea9656b 100644
--- a/wpilibc/src/test/native/cpp/TimedRobotTest.cpp
+++ b/wpilibc/src/test/native/cpp/TimedRobotTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/TimedRobot.h" // NOLINT(build/include_order)
@@ -35,6 +32,11 @@
std::atomic<uint32_t> m_teleopInitCount{0};
std::atomic<uint32_t> m_testInitCount{0};
+ std::atomic<uint32_t> m_disabledExitCount{0};
+ std::atomic<uint32_t> m_autonomousExitCount{0};
+ std::atomic<uint32_t> m_teleopExitCount{0};
+ std::atomic<uint32_t> m_testExitCount{0};
+
std::atomic<uint32_t> m_robotPeriodicCount{0};
std::atomic<uint32_t> m_simulationPeriodicCount{0};
std::atomic<uint32_t> m_disabledPeriodicCount{0};
@@ -65,10 +67,18 @@
void TeleopPeriodic() override { m_teleopPeriodicCount++; }
void TestPeriodic() override { m_testPeriodicCount++; }
+
+ void DisabledExit() override { m_disabledExitCount++; }
+
+ void AutonomousExit() override { m_autonomousExitCount++; }
+
+ void TeleopExit() override { m_teleopExitCount++; }
+
+ void TestExit() override { m_testExitCount++; }
};
} // namespace
-TEST_F(TimedRobotTest, Disabled) {
+TEST_F(TimedRobotTest, DisabledMode) {
MockRobot robot;
std::thread robotThread{[&] { robot.StartCompetition(); }};
@@ -91,6 +101,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -107,6 +122,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -123,11 +143,16 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
robot.EndCompetition();
robotThread.join();
}
-TEST_F(TimedRobotTest, Autonomous) {
+TEST_F(TimedRobotTest, AutonomousMode) {
MockRobot robot;
std::thread robotThread{[&] { robot.StartCompetition(); }};
@@ -152,6 +177,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -168,6 +198,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -184,11 +219,16 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
robot.EndCompetition();
robotThread.join();
}
-TEST_F(TimedRobotTest, Teleop) {
+TEST_F(TimedRobotTest, TeleopMode) {
MockRobot robot;
std::thread robotThread{[&] { robot.StartCompetition(); }};
@@ -213,6 +253,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -229,6 +274,11 @@
EXPECT_EQ(1u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -245,11 +295,16 @@
EXPECT_EQ(2u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
robot.EndCompetition();
robotThread.join();
}
-TEST_F(TimedRobotTest, Test) {
+TEST_F(TimedRobotTest, TestMode) {
MockRobot robot;
std::thread robotThread{[&] { robot.StartCompetition(); }};
@@ -274,6 +329,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(0u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -290,6 +350,11 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(1u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
frc::sim::StepTiming(20_ms);
EXPECT_EQ(1u, robot.m_robotInitCount);
@@ -306,6 +371,117 @@
EXPECT_EQ(0u, robot.m_teleopPeriodicCount);
EXPECT_EQ(2u, robot.m_testPeriodicCount);
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
+ robot.EndCompetition();
+ robotThread.join();
+}
+
+TEST_F(TimedRobotTest, ModeChange) {
+ MockRobot robot;
+
+ std::thread robotThread{[&] { robot.StartCompetition(); }};
+
+ // Start in disabled
+ frc::sim::DriverStationSim::SetEnabled(false);
+ frc::sim::DriverStationSim::SetAutonomous(false);
+ frc::sim::DriverStationSim::SetTest(false);
+ frc::sim::DriverStationSim::NotifyNewData();
+ frc::sim::StepTiming(0_ms); // Wait for Notifiers
+
+ EXPECT_EQ(0u, robot.m_disabledInitCount);
+ EXPECT_EQ(0u, robot.m_autonomousInitCount);
+ EXPECT_EQ(0u, robot.m_teleopInitCount);
+ EXPECT_EQ(0u, robot.m_testInitCount);
+
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
+ frc::sim::StepTiming(20_ms);
+
+ EXPECT_EQ(1u, robot.m_disabledInitCount);
+ EXPECT_EQ(0u, robot.m_autonomousInitCount);
+ EXPECT_EQ(0u, robot.m_teleopInitCount);
+ EXPECT_EQ(0u, robot.m_testInitCount);
+
+ EXPECT_EQ(0u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
+ // Transition to autonomous
+ frc::sim::DriverStationSim::SetEnabled(true);
+ frc::sim::DriverStationSim::SetAutonomous(true);
+ frc::sim::DriverStationSim::SetTest(false);
+
+ frc::sim::StepTiming(20_ms);
+
+ EXPECT_EQ(1u, robot.m_disabledInitCount);
+ EXPECT_EQ(1u, robot.m_autonomousInitCount);
+ EXPECT_EQ(0u, robot.m_teleopInitCount);
+ EXPECT_EQ(0u, robot.m_testInitCount);
+
+ EXPECT_EQ(1u, robot.m_disabledExitCount);
+ EXPECT_EQ(0u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
+ // Transition to teleop
+ frc::sim::DriverStationSim::SetEnabled(true);
+ frc::sim::DriverStationSim::SetAutonomous(false);
+ frc::sim::DriverStationSim::SetTest(false);
+
+ frc::sim::StepTiming(20_ms);
+
+ EXPECT_EQ(1u, robot.m_disabledInitCount);
+ EXPECT_EQ(1u, robot.m_autonomousInitCount);
+ EXPECT_EQ(1u, robot.m_teleopInitCount);
+ EXPECT_EQ(0u, robot.m_testInitCount);
+
+ EXPECT_EQ(1u, robot.m_disabledExitCount);
+ EXPECT_EQ(1u, robot.m_autonomousExitCount);
+ EXPECT_EQ(0u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
+ // Transition to test
+ frc::sim::DriverStationSim::SetEnabled(true);
+ frc::sim::DriverStationSim::SetAutonomous(false);
+ frc::sim::DriverStationSim::SetTest(true);
+
+ frc::sim::StepTiming(20_ms);
+
+ EXPECT_EQ(1u, robot.m_disabledInitCount);
+ EXPECT_EQ(1u, robot.m_autonomousInitCount);
+ EXPECT_EQ(1u, robot.m_teleopInitCount);
+ EXPECT_EQ(1u, robot.m_testInitCount);
+
+ EXPECT_EQ(1u, robot.m_disabledExitCount);
+ EXPECT_EQ(1u, robot.m_autonomousExitCount);
+ EXPECT_EQ(1u, robot.m_teleopExitCount);
+ EXPECT_EQ(0u, robot.m_testExitCount);
+
+ // Transition to disabled
+ frc::sim::DriverStationSim::SetEnabled(false);
+ frc::sim::DriverStationSim::SetAutonomous(false);
+ frc::sim::DriverStationSim::SetTest(false);
+
+ frc::sim::StepTiming(20_ms);
+
+ EXPECT_EQ(2u, robot.m_disabledInitCount);
+ EXPECT_EQ(1u, robot.m_autonomousInitCount);
+ EXPECT_EQ(1u, robot.m_teleopInitCount);
+ EXPECT_EQ(1u, robot.m_testInitCount);
+
+ EXPECT_EQ(1u, robot.m_disabledExitCount);
+ EXPECT_EQ(1u, robot.m_autonomousExitCount);
+ EXPECT_EQ(1u, robot.m_teleopExitCount);
+ EXPECT_EQ(1u, robot.m_testExitCount);
+
robot.EndCompetition();
robotThread.join();
}
diff --git a/wpilibc/src/test/native/cpp/TimerTest.cpp b/wpilibc/src/test/native/cpp/TimerTest.cpp
new file mode 100644
index 0000000..a7adc45
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/TimerTest.cpp
@@ -0,0 +1,115 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/Timer.h" // NOLINT(build/include_order)
+
+#include "frc/simulation/SimHooks.h"
+#include "gtest/gtest.h"
+
+using namespace frc;
+
+namespace {
+class TimerTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ frc::sim::PauseTiming();
+ frc::sim::RestartTiming();
+ }
+
+ void TearDown() override { frc::sim::ResumeTiming(); }
+};
+
+} // namespace
+
+TEST_F(TimerTest, StartStop) {
+ Timer timer;
+
+ // Verify timer is initialized as stopped
+ EXPECT_EQ(timer.Get(), 0_s);
+ frc::sim::StepTiming(500_ms);
+ EXPECT_EQ(timer.Get(), 0_s);
+
+ // Verify timer increments after it's started
+ timer.Start();
+ frc::sim::StepTiming(500_ms);
+ EXPECT_EQ(timer.Get(), 500_ms);
+
+ // Verify timer stops incrementing after it's stopped
+ timer.Stop();
+ frc::sim::StepTiming(500_ms);
+ EXPECT_EQ(timer.Get(), 500_ms);
+}
+
+TEST_F(TimerTest, Reset) {
+ Timer timer;
+ timer.Start();
+
+ // Advance timer to 500 ms
+ EXPECT_EQ(timer.Get(), 0_s);
+ frc::sim::StepTiming(500_ms);
+ EXPECT_EQ(timer.Get(), 500_ms);
+
+ // Verify timer reports 0 ms after reset
+ timer.Reset();
+ EXPECT_EQ(timer.Get(), 0_s);
+
+ // Verify timer continues incrementing
+ frc::sim::StepTiming(500_ms);
+ EXPECT_EQ(timer.Get(), 500_ms);
+
+ // Verify timer doesn't start incrementing after reset if it was stopped
+ timer.Stop();
+ timer.Reset();
+ frc::sim::StepTiming(500_ms);
+ EXPECT_EQ(timer.Get(), 0_ms);
+}
+
+TEST_F(TimerTest, HasElapsed) {
+ Timer timer;
+
+ // Verify 0 ms has elapsed since timer hasn't started
+ EXPECT_TRUE(timer.HasElapsed(0_s));
+
+ // Verify timer doesn't report elapsed time when stopped
+ frc::sim::StepTiming(500_ms);
+ EXPECT_FALSE(timer.HasElapsed(400_ms));
+
+ timer.Start();
+
+ // Verify timer reports >= 400 ms has elapsed after multiple calls
+ frc::sim::StepTiming(500_ms);
+ EXPECT_TRUE(timer.HasElapsed(400_ms));
+ EXPECT_TRUE(timer.HasElapsed(400_ms));
+}
+
+TEST_F(TimerTest, AdvanceIfElapsed) {
+ Timer timer;
+
+ // Verify 0 ms has elapsed since timer hasn't started
+ EXPECT_TRUE(timer.AdvanceIfElapsed(0_s));
+
+ // Verify timer doesn't report elapsed time when stopped
+ frc::sim::StepTiming(500_ms);
+ EXPECT_FALSE(timer.AdvanceIfElapsed(400_ms));
+
+ timer.Start();
+
+ // Verify timer reports >= 400 ms has elapsed for only first call
+ frc::sim::StepTiming(500_ms);
+ EXPECT_TRUE(timer.AdvanceIfElapsed(400_ms));
+ EXPECT_FALSE(timer.AdvanceIfElapsed(400_ms));
+
+ // Verify timer reports >= 400 ms has elapsed for two calls
+ frc::sim::StepTiming(1_s);
+ EXPECT_TRUE(timer.AdvanceIfElapsed(400_ms));
+ EXPECT_TRUE(timer.AdvanceIfElapsed(400_ms));
+ EXPECT_FALSE(timer.AdvanceIfElapsed(400_ms));
+}
+
+TEST_F(TimerTest, GetFPGATimestamp) {
+ auto start = frc::Timer::GetFPGATimestamp();
+ frc::sim::StepTiming(500_ms);
+ auto end = frc::Timer::GetFPGATimestamp();
+ EXPECT_EQ(start + 500_ms, end);
+}
diff --git a/wpilibc/src/test/native/cpp/TimesliceRobotTest.cpp b/wpilibc/src/test/native/cpp/TimesliceRobotTest.cpp
new file mode 100644
index 0000000..a2e4e13
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/TimesliceRobotTest.cpp
@@ -0,0 +1,100 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/TimesliceRobot.h" // NOLINT(build/include_order)
+
+#include <stdint.h>
+
+#include <atomic>
+#include <thread>
+
+#include "frc/simulation/DriverStationSim.h"
+#include "frc/simulation/SimHooks.h"
+#include "gtest/gtest.h"
+
+using namespace frc;
+
+namespace {
+class TimesliceRobotTest : public ::testing::Test {
+ protected:
+ void SetUp() override { frc::sim::PauseTiming(); }
+
+ void TearDown() override { frc::sim::ResumeTiming(); }
+};
+
+class MockRobot : public TimesliceRobot {
+ public:
+ std::atomic<uint32_t> m_robotPeriodicCount{0};
+
+ MockRobot() : TimesliceRobot{2_ms, 5_ms} {}
+
+ void RobotPeriodic() override { m_robotPeriodicCount++; }
+};
+} // namespace
+
+TEST_F(TimesliceRobotTest, Schedule) {
+ MockRobot robot;
+
+ std::atomic<uint32_t> callbackCount1{0};
+ std::atomic<uint32_t> callbackCount2{0};
+
+ // Timeslice allocation table
+ //
+ // | Name | Offset (ms) | Allocation (ms)|
+ // |-----------------|-------------|----------------|
+ // | RobotPeriodic() | 0 | 2 |
+ // | Callback 1 | 2 | 0.5 |
+ // | Callback 2 | 2.5 | 1 |
+ robot.Schedule([&] { callbackCount1++; }, 0.5_ms);
+ robot.Schedule([&] { callbackCount2++; }, 1_ms);
+
+ std::thread robotThread{[&] { robot.StartCompetition(); }};
+
+ frc::sim::DriverStationSim::SetEnabled(false);
+ frc::sim::DriverStationSim::NotifyNewData();
+ frc::sim::StepTiming(0_ms); // Wait for Notifiers
+
+ // Functions scheduled with addPeriodic() are delayed by one period before
+ // their first run (5 ms for this test's callbacks here and 20 ms for
+ // robotPeriodic()).
+ frc::sim::StepTiming(5_ms);
+
+ EXPECT_EQ(0u, robot.m_robotPeriodicCount);
+ EXPECT_EQ(0u, callbackCount1);
+ EXPECT_EQ(0u, callbackCount2);
+
+ // Step to 1.5 ms
+ frc::sim::StepTiming(1.5_ms);
+ EXPECT_EQ(0u, robot.m_robotPeriodicCount);
+ EXPECT_EQ(0u, callbackCount1);
+ EXPECT_EQ(0u, callbackCount2);
+
+ // Step to 2.25 ms
+ frc::sim::StepTiming(0.75_ms);
+ EXPECT_EQ(0u, robot.m_robotPeriodicCount);
+ EXPECT_EQ(1u, callbackCount1);
+ EXPECT_EQ(0u, callbackCount2);
+
+ // Step to 2.75 ms
+ frc::sim::StepTiming(0.5_ms);
+ EXPECT_EQ(0u, robot.m_robotPeriodicCount);
+ EXPECT_EQ(1u, callbackCount1);
+ EXPECT_EQ(1u, callbackCount2);
+
+ robot.EndCompetition();
+ robotThread.join();
+}
+
+TEST_F(TimesliceRobotTest, ScheduleOverrun) {
+ MockRobot robot;
+
+ robot.Schedule([] {}, 0.5_ms);
+ robot.Schedule([] {}, 1_ms);
+
+ // offset = 2 ms + 0.5 ms + 1 ms = 3.5 ms
+ // 3.5 ms + 3 ms allocation = 6.5 ms > max of 5 ms
+ EXPECT_THROW(robot.Schedule([] {}, 3_ms), std::runtime_error);
+
+ robot.EndCompetition();
+}
diff --git a/wpilibc/src/test/native/cpp/UltrasonicTest.cpp b/wpilibc/src/test/native/cpp/UltrasonicTest.cpp
new file mode 100644
index 0000000..72d72d2
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/UltrasonicTest.cpp
@@ -0,0 +1,26 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/Ultrasonic.h"
+#include "frc/simulation/UltrasonicSim.h"
+#include "gtest/gtest.h"
+
+namespace frc {
+
+TEST(UltrasonicTest, SimDevices) {
+ Ultrasonic ultrasonic{0, 1};
+ sim::UltrasonicSim sim{ultrasonic};
+
+ EXPECT_EQ(0, ultrasonic.GetRange().value());
+ EXPECT_TRUE(ultrasonic.IsRangeValid());
+
+ sim.SetRange(units::meter_t{35.04});
+ EXPECT_EQ(35.04, ultrasonic.GetRange().value());
+
+ sim.SetRangeValid(false);
+ EXPECT_FALSE(ultrasonic.IsRangeValid());
+ EXPECT_EQ(0, ultrasonic.GetRange().value());
+}
+
+} // namespace frc
diff --git a/wpilibc/src/test/native/cpp/WatchdogTest.cpp b/wpilibc/src/test/native/cpp/WatchdogTest.cpp
index 0e33511..5f55c2f 100644
--- a/wpilibc/src/test/native/cpp/WatchdogTest.cpp
+++ b/wpilibc/src/test/native/cpp/WatchdogTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/Watchdog.h" // NOLINT(build/include_order)
@@ -78,7 +75,7 @@
frc::sim::StepTiming(0.2_s);
watchdog.SetTimeout(0.2_s);
- EXPECT_EQ(0.2, watchdog.GetTimeout());
+ EXPECT_EQ(0.2_s, watchdog.GetTimeout());
EXPECT_EQ(0u, watchdogCounter) << "Watchdog triggered early";
frc::sim::StepTiming(0.3_s);
diff --git a/wpilibc/src/test/native/cpp/XboxControllerTest.cpp b/wpilibc/src/test/native/cpp/XboxControllerTest.cpp
index 66ccfcd..0a8316b 100644
--- a/wpilibc/src/test/native/cpp/XboxControllerTest.cpp
+++ b/wpilibc/src/test/native/cpp/XboxControllerTest.cpp
@@ -1,74 +1,32 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/XboxController.h" // NOLINT(build/include_order)
+#include "JoystickTestMacros.h"
#include "frc/simulation/XboxControllerSim.h"
#include "gtest/gtest.h"
using namespace frc;
-TEST(XboxControllerTests, GetX) {
- XboxController joy{2};
- sim::XboxControllerSim joysim{joy};
+BUTTON_TEST(XboxController, LeftBumper)
+BUTTON_TEST(XboxController, RightBumper)
- joysim.SetX(XboxController::kLeftHand, 0.35);
- joysim.SetX(XboxController::kRightHand, 0.45);
- joysim.NotifyNewData();
- ASSERT_NEAR(joy.GetX(XboxController::kLeftHand), 0.35, 0.001);
- ASSERT_NEAR(joy.GetX(XboxController::kRightHand), 0.45, 0.001);
-}
+BUTTON_TEST(XboxController, LeftStickButton)
+BUTTON_TEST(XboxController, RightStickButton)
-TEST(XboxControllerTests, GetBumper) {
- XboxController joy{1};
- sim::XboxControllerSim joysim{joy};
+BUTTON_TEST(XboxController, AButton)
+BUTTON_TEST(XboxController, BButton)
+BUTTON_TEST(XboxController, XButton)
+BUTTON_TEST(XboxController, YButton)
+BUTTON_TEST(XboxController, BackButton)
+BUTTON_TEST(XboxController, StartButton)
- joysim.SetBumper(XboxController::kLeftHand, false);
- joysim.SetBumper(XboxController::kRightHand, true);
- joysim.NotifyNewData();
- ASSERT_FALSE(joy.GetBumper(XboxController::kLeftHand));
- ASSERT_TRUE(joy.GetBumper(XboxController::kRightHand));
- // need to call pressed and released to clear flags
- joy.GetBumperPressed(XboxController::kLeftHand);
- joy.GetBumperReleased(XboxController::kLeftHand);
- joy.GetBumperPressed(XboxController::kRightHand);
- joy.GetBumperReleased(XboxController::kRightHand);
+AXIS_TEST(XboxController, LeftX)
+AXIS_TEST(XboxController, RightX)
+AXIS_TEST(XboxController, LeftY)
+AXIS_TEST(XboxController, RightY)
- joysim.SetBumper(XboxController::kLeftHand, true);
- joysim.SetBumper(XboxController::kRightHand, false);
- joysim.NotifyNewData();
- ASSERT_TRUE(joy.GetBumper(XboxController::kLeftHand));
- ASSERT_TRUE(joy.GetBumperPressed(XboxController::kLeftHand));
- ASSERT_FALSE(joy.GetBumperReleased(XboxController::kLeftHand));
- ASSERT_FALSE(joy.GetBumper(XboxController::kRightHand));
- ASSERT_FALSE(joy.GetBumperPressed(XboxController::kRightHand));
- ASSERT_TRUE(joy.GetBumperReleased(XboxController::kRightHand));
-}
-
-TEST(XboxControllerTests, GetAButton) {
- XboxController joy{1};
- sim::XboxControllerSim joysim{joy};
-
- joysim.SetAButton(false);
- joysim.NotifyNewData();
- ASSERT_FALSE(joy.GetAButton());
- // need to call pressed and released to clear flags
- joy.GetAButtonPressed();
- joy.GetAButtonReleased();
-
- joysim.SetAButton(true);
- joysim.NotifyNewData();
- ASSERT_TRUE(joy.GetAButton());
- ASSERT_TRUE(joy.GetAButtonPressed());
- ASSERT_FALSE(joy.GetAButtonReleased());
-
- joysim.SetAButton(false);
- joysim.NotifyNewData();
- ASSERT_FALSE(joy.GetAButton());
- ASSERT_FALSE(joy.GetAButtonPressed());
- ASSERT_TRUE(joy.GetAButtonReleased());
-}
+AXIS_TEST(XboxController, LeftTriggerAxis)
+AXIS_TEST(XboxController, RightTriggerAxis)
diff --git a/wpilibc/src/test/native/cpp/controller/ControllerUtilTest.cpp b/wpilibc/src/test/native/cpp/controller/ControllerUtilTest.cpp
deleted file mode 100644
index 00259d1..0000000
--- a/wpilibc/src/test/native/cpp/controller/ControllerUtilTest.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include <units/angle.h>
-
-#include "frc/controller/ControllerUtil.h"
-#include "gtest/gtest.h"
-
-TEST(ControllerUtilTest, GetModulusError) {
- // Test symmetric range
- EXPECT_FLOAT_EQ(-20.0, frc::GetModulusError(170.0, -170.0, -180.0, 180.0));
- EXPECT_FLOAT_EQ(-20.0,
- frc::GetModulusError(170.0 + 360.0, -170.0, -180.0, 180.0));
- EXPECT_FLOAT_EQ(-20.0,
- frc::GetModulusError(170.0, -170.0 + 360.0, -180.0, 180.0));
- EXPECT_FLOAT_EQ(20.0, frc::GetModulusError(-170.0, 170.0, -180.0, 180.0));
- EXPECT_FLOAT_EQ(20.0,
- frc::GetModulusError(-170.0 + 360.0, 170.0, -180.0, 180.0));
- EXPECT_FLOAT_EQ(20.0,
- frc::GetModulusError(-170.0, 170.0 + 360.0, -180.0, 180.0));
-
- // Test range starting at zero
- EXPECT_FLOAT_EQ(-20.0, frc::GetModulusError(170.0, 190.0, 0.0, 360.0));
- EXPECT_FLOAT_EQ(-20.0,
- frc::GetModulusError(170.0 + 360.0, 190.0, 0.0, 360.0));
- EXPECT_FLOAT_EQ(-20.0,
- frc::GetModulusError(170.0, 190.0 + 360.0, 0.0, 360.0));
-
- // Test asymmetric range that doesn't start at zero
- EXPECT_FLOAT_EQ(-20.0, frc::GetModulusError(170.0, -170.0, -170.0, 190.0));
-
- // Test all supported types
- EXPECT_FLOAT_EQ(-20.0,
- frc::GetModulusError<double>(170.0, -170.0, -170.0, 190.0));
- EXPECT_EQ(-20, frc::GetModulusError<int>(170, -170, -170, 190));
- EXPECT_EQ(-20_deg, frc::GetModulusError<units::degree_t>(170_deg, -170_deg,
- -170_deg, 190_deg));
-}
diff --git a/wpilibc/src/test/native/cpp/controller/HolonomicDriveControllerTest.cpp b/wpilibc/src/test/native/cpp/controller/HolonomicDriveControllerTest.cpp
deleted file mode 100644
index fb72a4a..0000000
--- a/wpilibc/src/test/native/cpp/controller/HolonomicDriveControllerTest.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include <units/math.h>
-#include <units/time.h>
-#include <wpi/math>
-
-#include "frc/controller/HolonomicDriveController.h"
-#include "frc/trajectory/TrajectoryGenerator.h"
-#include "gtest/gtest.h"
-
-#define EXPECT_NEAR_UNITS(val1, val2, eps) \
- EXPECT_LE(units::math::abs(val1 - val2), eps)
-
-static constexpr units::meter_t kTolerance{1 / 12.0};
-static constexpr units::radian_t kAngularTolerance{2.0 * wpi::math::pi / 180.0};
-
-TEST(HolonomicDriveControllerTest, ReachesReference) {
- frc::HolonomicDriveController controller{
- frc2::PIDController{1.0, 0.0, 0.0}, frc2::PIDController{1.0, 0.0, 0.0},
- frc::ProfiledPIDController<units::radian>{
- 1.0, 0.0, 0.0,
- frc::TrapezoidProfile<units::radian>::Constraints{
- 6.28_rad_per_s, 3.14_rad_per_s / 1_s}}};
-
- frc::Pose2d robotPose{2.7_m, 23_m, frc::Rotation2d{0_deg}};
-
- auto waypoints = std::vector{frc::Pose2d{2.75_m, 22.521_m, 0_rad},
- frc::Pose2d{24.73_m, 19.68_m, 5.846_rad}};
- auto trajectory = frc::TrajectoryGenerator::GenerateTrajectory(
- waypoints, {8.0_mps, 4.0_mps_sq});
-
- constexpr auto kDt = 0.02_s;
- auto totalTime = trajectory.TotalTime();
- for (size_t i = 0; i < (totalTime / kDt).to<double>(); ++i) {
- auto state = trajectory.Sample(kDt * i);
- auto [vx, vy, omega] = controller.Calculate(robotPose, state, 0_rad);
-
- robotPose = robotPose.Exp(frc::Twist2d{vx * kDt, vy * kDt, omega * kDt});
- }
-
- auto& endPose = trajectory.States().back().pose;
- EXPECT_NEAR_UNITS(endPose.X(), robotPose.X(), kTolerance);
- EXPECT_NEAR_UNITS(endPose.Y(), robotPose.Y(), kTolerance);
- EXPECT_NEAR_UNITS(units::math::NormalizeAngle(robotPose.Rotation().Radians()),
- 0_rad, kAngularTolerance);
-}
diff --git a/wpilibc/src/test/native/cpp/controller/PIDInputOutputTest.cpp b/wpilibc/src/test/native/cpp/controller/PIDInputOutputTest.cpp
deleted file mode 100644
index 3580308..0000000
--- a/wpilibc/src/test/native/cpp/controller/PIDInputOutputTest.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/controller/PIDController.h"
-#include "gtest/gtest.h"
-
-class PIDInputOutputTest : public testing::Test {
- protected:
- frc2::PIDController* controller;
-
- void SetUp() override { controller = new frc2::PIDController(0, 0, 0); }
-
- void TearDown() override { delete controller; }
-};
-
-TEST_F(PIDInputOutputTest, ContinuousInputTest) {
- controller->SetP(1);
- controller->EnableContinuousInput(-180, 180);
-
- EXPECT_LT(controller->Calculate(-179, 179), 0);
-}
-
-TEST_F(PIDInputOutputTest, ProportionalGainOutputTest) {
- controller->SetP(4);
-
- EXPECT_DOUBLE_EQ(-0.1, controller->Calculate(0.025, 0));
-}
-
-TEST_F(PIDInputOutputTest, IntegralGainOutputTest) {
- controller->SetI(4);
-
- double out = 0;
-
- for (int i = 0; i < 5; i++) {
- out = controller->Calculate(0.025, 0);
- }
-
- EXPECT_DOUBLE_EQ(-0.5 * controller->GetPeriod().to<double>(), out);
-}
-
-TEST_F(PIDInputOutputTest, DerivativeGainOutputTest) {
- controller->SetD(4);
-
- controller->Calculate(0, 0);
-
- EXPECT_DOUBLE_EQ(-10_ms / controller->GetPeriod(),
- controller->Calculate(0.0025, 0));
-}
diff --git a/wpilibc/src/test/native/cpp/controller/PIDToleranceTest.cpp b/wpilibc/src/test/native/cpp/controller/PIDToleranceTest.cpp
deleted file mode 100644
index 3251098..0000000
--- a/wpilibc/src/test/native/cpp/controller/PIDToleranceTest.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "frc/controller/PIDController.h"
-#include "gtest/gtest.h"
-
-static constexpr double kSetpoint = 50.0;
-static constexpr double kRange = 200;
-static constexpr double kTolerance = 10.0;
-
-TEST(PIDToleranceTest, InitialTolerance) {
- frc2::PIDController controller{0.5, 0.0, 0.0};
- controller.EnableContinuousInput(-kRange / 2, kRange / 2);
-
- EXPECT_TRUE(controller.AtSetpoint());
-}
-
-TEST(PIDToleranceTest, AbsoluteTolerance) {
- frc2::PIDController controller{0.5, 0.0, 0.0};
- controller.EnableContinuousInput(-kRange / 2, kRange / 2);
-
- controller.SetTolerance(kTolerance);
- controller.SetSetpoint(kSetpoint);
-
- controller.Calculate(0.0);
-
- EXPECT_FALSE(controller.AtSetpoint())
- << "Error was in tolerance when it should not have been. Error was "
- << controller.GetPositionError();
-
- controller.Calculate(kSetpoint + kTolerance / 2);
-
- EXPECT_TRUE(controller.AtSetpoint())
- << "Error was not in tolerance when it should have been. Error was "
- << controller.GetPositionError();
-
- controller.Calculate(kSetpoint + 10 * kTolerance);
-
- EXPECT_FALSE(controller.AtSetpoint())
- << "Error was in tolerance when it should not have been. Error was "
- << controller.GetPositionError();
-}
diff --git a/wpilibc/src/test/native/cpp/controller/ProfiledPIDInputOutputTest.cpp b/wpilibc/src/test/native/cpp/controller/ProfiledPIDInputOutputTest.cpp
deleted file mode 100644
index 6f9c36d..0000000
--- a/wpilibc/src/test/native/cpp/controller/ProfiledPIDInputOutputTest.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include <units/angle.h>
-#include <units/angular_acceleration.h>
-#include <units/angular_velocity.h>
-#include <wpi/math>
-
-#include "frc/controller/ProfiledPIDController.h"
-#include "gtest/gtest.h"
-
-class ProfiledPIDInputOutputTest : public testing::Test {
- protected:
- frc::ProfiledPIDController<units::degrees>* controller;
-
- void SetUp() override {
- controller = new frc::ProfiledPIDController<units::degrees>(
- 0, 0, 0, {360_deg_per_s, 180_deg_per_s_sq});
- }
-
- void TearDown() override { delete controller; }
-};
-
-TEST_F(ProfiledPIDInputOutputTest, ContinuousInputTest) {
- controller->SetP(1);
- controller->EnableContinuousInput(-180_deg, 180_deg);
-
- controller->Reset(-179_deg);
- EXPECT_LT(controller->Calculate(-179_deg, 179_deg), 0);
-}
-
-TEST_F(ProfiledPIDInputOutputTest, ContinuousInputTest1) {
- controller->SetP(1);
- controller->EnableContinuousInput(-180_deg, 180_deg);
-
- static constexpr units::degree_t kSetpoint{-179.0};
- static constexpr units::degree_t kMeasurement{-179.0};
- static constexpr units::degree_t kGoal{179.0};
-
- controller->Reset(kSetpoint);
- EXPECT_LT(controller->Calculate(kMeasurement, kGoal), 0.0);
-
- // Error must be less than half the input range at all times
- EXPECT_LT(units::math::abs(controller->GetSetpoint().position - kMeasurement),
- 180_deg);
-}
-
-TEST_F(ProfiledPIDInputOutputTest, ContinuousInputTest2) {
- controller->SetP(1);
- controller->EnableContinuousInput(-units::radian_t{wpi::math::pi},
- units::radian_t{wpi::math::pi});
-
- static constexpr units::radian_t kSetpoint{-3.4826633343199735};
- static constexpr units::radian_t kMeasurement{-3.1352207333939606};
- static constexpr units::radian_t kGoal{-3.534162788601621};
-
- controller->Reset(kSetpoint);
- EXPECT_LT(controller->Calculate(kMeasurement, kGoal), 0.0);
-
- // Error must be less than half the input range at all times
- EXPECT_LT(units::math::abs(controller->GetSetpoint().position - kMeasurement),
- units::radian_t{wpi::math::pi});
-}
-
-TEST_F(ProfiledPIDInputOutputTest, ContinuousInputTest3) {
- controller->SetP(1);
- controller->EnableContinuousInput(-units::radian_t{wpi::math::pi},
- units::radian_t{wpi::math::pi});
-
- static constexpr units::radian_t kSetpoint{-3.5176604690006377};
- static constexpr units::radian_t kMeasurement{3.1191729343822456};
- static constexpr units::radian_t kGoal{2.709680418117445};
-
- controller->Reset(kSetpoint);
- EXPECT_LT(controller->Calculate(kMeasurement, kGoal), 0.0);
-
- // Error must be less than half the input range at all times
- EXPECT_LT(units::math::abs(controller->GetSetpoint().position - kMeasurement),
- units::radian_t{wpi::math::pi});
-}
-
-TEST_F(ProfiledPIDInputOutputTest, ProportionalGainOutputTest) {
- controller->SetP(4);
-
- EXPECT_DOUBLE_EQ(-0.1, controller->Calculate(0.025_deg, 0_deg));
-}
-
-TEST_F(ProfiledPIDInputOutputTest, IntegralGainOutputTest) {
- controller->SetI(4);
-
- double out = 0;
-
- for (int i = 0; i < 5; i++) {
- out = controller->Calculate(0.025_deg, 0_deg);
- }
-
- EXPECT_DOUBLE_EQ(-0.5 * controller->GetPeriod().to<double>(), out);
-}
-
-TEST_F(ProfiledPIDInputOutputTest, DerivativeGainOutputTest) {
- controller->SetD(4);
-
- controller->Calculate(0_deg, 0_deg);
-
- EXPECT_DOUBLE_EQ(-10_ms / controller->GetPeriod(),
- controller->Calculate(0.0025_deg, 0_deg));
-}
diff --git a/wpilibc/src/test/native/cpp/controller/RamseteControllerTest.cpp b/wpilibc/src/test/native/cpp/controller/RamseteControllerTest.cpp
deleted file mode 100644
index fb34385..0000000
--- a/wpilibc/src/test/native/cpp/controller/RamseteControllerTest.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include <units/math.h>
-
-#include "frc/controller/RamseteController.h"
-#include "frc/trajectory/TrajectoryGenerator.h"
-#include "gtest/gtest.h"
-
-#define EXPECT_NEAR_UNITS(val1, val2, eps) \
- EXPECT_LE(units::math::abs(val1 - val2), eps)
-
-static constexpr units::meter_t kTolerance{1 / 12.0};
-static constexpr units::radian_t kAngularTolerance{2.0 * wpi::math::pi / 180.0};
-
-TEST(RamseteControllerTest, ReachesReference) {
- frc::RamseteController controller{2.0, 0.7};
- frc::Pose2d robotPose{2.7_m, 23_m, frc::Rotation2d{0_deg}};
-
- auto waypoints = std::vector{frc::Pose2d{2.75_m, 22.521_m, 0_rad},
- frc::Pose2d{24.73_m, 19.68_m, 5.846_rad}};
- auto trajectory = frc::TrajectoryGenerator::GenerateTrajectory(
- waypoints, {8.8_mps, 0.1_mps_sq});
-
- constexpr auto kDt = 0.02_s;
- auto totalTime = trajectory.TotalTime();
- for (size_t i = 0; i < (totalTime / kDt).to<double>(); ++i) {
- auto state = trajectory.Sample(kDt * i);
- auto [vx, vy, omega] = controller.Calculate(robotPose, state);
- static_cast<void>(vy);
-
- robotPose = robotPose.Exp(frc::Twist2d{vx * kDt, 0_m, omega * kDt});
- }
-
- auto& endPose = trajectory.States().back().pose;
- EXPECT_NEAR_UNITS(endPose.X(), robotPose.X(), kTolerance);
- EXPECT_NEAR_UNITS(endPose.Y(), robotPose.Y(), kTolerance);
- EXPECT_NEAR_UNITS(units::math::NormalizeAngle(endPose.Rotation().Radians() -
- robotPose.Rotation().Radians()),
- 0_rad, kAngularTolerance);
-}
diff --git a/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp b/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp
new file mode 100644
index 0000000..1d13a77
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/drive/DifferentialDriveTest.cpp
@@ -0,0 +1,229 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "MockMotorController.h"
+#include "frc/drive/DifferentialDrive.h"
+#include "gtest/gtest.h"
+
+TEST(DifferentialDriveTest, ArcadeDrive) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::DifferentialDrive drive{left, right};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.ArcadeDrive(1.0, 0.0, false);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward left turn
+ drive.ArcadeDrive(0.5, -0.5, false);
+ EXPECT_DOUBLE_EQ(0.0, left.Get());
+ EXPECT_DOUBLE_EQ(0.5, right.Get());
+
+ // Forward right turn
+ drive.ArcadeDrive(0.5, 0.5, false);
+ EXPECT_DOUBLE_EQ(0.5, left.Get());
+ EXPECT_DOUBLE_EQ(0.0, right.Get());
+
+ // Backward
+ drive.ArcadeDrive(-1.0, 0.0, false);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward left turn
+ drive.ArcadeDrive(-0.5, -0.5, false);
+ EXPECT_DOUBLE_EQ(-0.5, left.Get());
+ EXPECT_DOUBLE_EQ(0.0, right.Get());
+
+ // Backward right turn
+ drive.ArcadeDrive(-0.5, 0.5, false);
+ EXPECT_DOUBLE_EQ(0.0, left.Get());
+ EXPECT_DOUBLE_EQ(-0.5, right.Get());
+}
+
+TEST(DifferentialDriveTest, ArcadeDriveSquared) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::DifferentialDrive drive{left, right};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.ArcadeDrive(1.0, 0.0, true);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward left turn
+ drive.ArcadeDrive(0.5, -0.5, true);
+ EXPECT_DOUBLE_EQ(0.0, left.Get());
+ EXPECT_DOUBLE_EQ(0.25, right.Get());
+
+ // Forward right turn
+ drive.ArcadeDrive(0.5, 0.5, true);
+ EXPECT_DOUBLE_EQ(0.25, left.Get());
+ EXPECT_DOUBLE_EQ(0.0, right.Get());
+
+ // Backward
+ drive.ArcadeDrive(-1.0, 0.0, true);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward left turn
+ drive.ArcadeDrive(-0.5, -0.5, true);
+ EXPECT_DOUBLE_EQ(-0.25, left.Get());
+ EXPECT_DOUBLE_EQ(0.0, right.Get());
+
+ // Backward right turn
+ drive.ArcadeDrive(-0.5, 0.5, true);
+ EXPECT_DOUBLE_EQ(0.0, left.Get());
+ EXPECT_DOUBLE_EQ(-0.25, right.Get());
+}
+
+TEST(DifferentialDriveTest, CurvatureDrive) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::DifferentialDrive drive{left, right};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.CurvatureDrive(1.0, 0.0, false);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward left turn
+ drive.CurvatureDrive(0.5, -0.5, false);
+ EXPECT_DOUBLE_EQ(0.25, left.Get());
+ EXPECT_DOUBLE_EQ(0.75, right.Get());
+
+ // Forward right turn
+ drive.CurvatureDrive(0.5, 0.5, false);
+ EXPECT_DOUBLE_EQ(0.75, left.Get());
+ EXPECT_DOUBLE_EQ(0.25, right.Get());
+
+ // Backward
+ drive.CurvatureDrive(-1.0, 0.0, false);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward left turn
+ drive.CurvatureDrive(-0.5, -0.5, false);
+ EXPECT_DOUBLE_EQ(-0.75, left.Get());
+ EXPECT_DOUBLE_EQ(-0.25, right.Get());
+
+ // Backward right turn
+ drive.CurvatureDrive(-0.5, 0.5, false);
+ EXPECT_DOUBLE_EQ(-0.25, left.Get());
+ EXPECT_DOUBLE_EQ(-0.75, right.Get());
+}
+
+TEST(DifferentialDriveTest, CurvatureDriveTurnInPlace) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::DifferentialDrive drive{left, right};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.CurvatureDrive(1.0, 0.0, true);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward left turn
+ drive.CurvatureDrive(0.5, -0.5, true);
+ EXPECT_DOUBLE_EQ(0.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward right turn
+ drive.CurvatureDrive(0.5, 0.5, true);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(0.0, right.Get());
+
+ // Backward
+ drive.CurvatureDrive(-1.0, 0.0, true);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward left turn
+ drive.CurvatureDrive(-0.5, -0.5, true);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(0.0, right.Get());
+
+ // Backward right turn
+ drive.CurvatureDrive(-0.5, 0.5, true);
+ EXPECT_DOUBLE_EQ(0.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+}
+
+TEST(DifferentialDriveTest, TankDrive) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::DifferentialDrive drive{left, right};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.TankDrive(1.0, 1.0, false);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward left turn
+ drive.TankDrive(0.5, 1.0, false);
+ EXPECT_DOUBLE_EQ(0.5, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward right turn
+ drive.TankDrive(1.0, 0.5, false);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(0.5, right.Get());
+
+ // Backward
+ drive.TankDrive(-1.0, -1.0, false);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward left turn
+ drive.TankDrive(-0.5, -1.0, false);
+ EXPECT_DOUBLE_EQ(-0.5, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward right turn
+ drive.TankDrive(-0.5, 1.0, false);
+ EXPECT_DOUBLE_EQ(-0.5, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+}
+
+TEST(DifferentialDriveTest, TankDriveSquared) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::DifferentialDrive drive{left, right};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.TankDrive(1.0, 1.0, true);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward left turn
+ drive.TankDrive(0.5, 1.0, true);
+ EXPECT_DOUBLE_EQ(0.25, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+
+ // Forward right turn
+ drive.TankDrive(1.0, 0.5, true);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(0.25, right.Get());
+
+ // Backward
+ drive.TankDrive(-1.0, -1.0, true);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward left turn
+ drive.TankDrive(-0.5, -1.0, true);
+ EXPECT_DOUBLE_EQ(-0.25, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+
+ // Backward right turn
+ drive.TankDrive(-1.0, -0.5, true);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-0.25, right.Get());
+}
diff --git a/wpilibc/src/test/native/cpp/drive/DriveTest.cpp b/wpilibc/src/test/native/cpp/drive/DriveTest.cpp
deleted file mode 100644
index 1ebb6b3..0000000
--- a/wpilibc/src/test/native/cpp/drive/DriveTest.cpp
+++ /dev/null
@@ -1,190 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2014-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#include "MockSpeedController.h"
-#include "frc/RobotDrive.h"
-#include "frc/drive/DifferentialDrive.h"
-#include "frc/drive/MecanumDrive.h"
-#include "gtest/gtest.h"
-
-using namespace frc;
-
-class DriveTest : public testing::Test {
- protected:
- MockSpeedController m_rdFrontLeft;
- MockSpeedController m_rdRearLeft;
- MockSpeedController m_rdFrontRight;
- MockSpeedController m_rdRearRight;
- MockSpeedController m_frontLeft;
- MockSpeedController m_rearLeft;
- MockSpeedController m_frontRight;
- MockSpeedController m_rearRight;
- frc::RobotDrive m_robotDrive{m_rdFrontLeft, m_rdRearLeft, m_rdFrontRight,
- m_rdRearRight};
- frc::DifferentialDrive m_differentialDrive{m_frontLeft, m_frontRight};
- frc::MecanumDrive m_mecanumDrive{m_frontLeft, m_rearLeft, m_frontRight,
- m_rearRight};
-
- double m_testJoystickValues[9] = {-1.0, -0.9, -0.5, -0.01, 0.0,
- 0.01, 0.5, 0.9, 1.0};
- double m_testGyroValues[19] = {0, 45, 90, 135, 180, 225, 270,
- 305, 360, 540, -45, -90, -135, -180,
- -225, -270, -305, -360, -540};
-};
-
-TEST_F(DriveTest, TankDrive) {
- int joystickSize = sizeof(m_testJoystickValues) / sizeof(double);
- double leftJoystick, rightJoystick;
- m_differentialDrive.SetDeadband(0.0);
- m_differentialDrive.SetSafetyEnabled(false);
- m_mecanumDrive.SetSafetyEnabled(false);
- m_robotDrive.SetSafetyEnabled(false);
- for (int i = 0; i < joystickSize; i++) {
- for (int j = 0; j < joystickSize; j++) {
- leftJoystick = m_testJoystickValues[i];
- rightJoystick = m_testJoystickValues[j];
- m_robotDrive.TankDrive(leftJoystick, rightJoystick, false);
- m_differentialDrive.TankDrive(leftJoystick, rightJoystick, false);
- ASSERT_NEAR(m_rdFrontLeft.Get(), m_frontLeft.Get(), 0.01);
- ASSERT_NEAR(m_rdFrontRight.Get(), m_frontRight.Get(), 0.01);
- }
- }
-}
-
-TEST_F(DriveTest, TankDriveSquared) {
- int joystickSize = sizeof(m_testJoystickValues) / sizeof(double);
- double leftJoystick, rightJoystick;
- m_differentialDrive.SetDeadband(0.0);
- m_differentialDrive.SetSafetyEnabled(false);
- m_mecanumDrive.SetSafetyEnabled(false);
- m_robotDrive.SetSafetyEnabled(false);
- for (int i = 0; i < joystickSize; i++) {
- for (int j = 0; j < joystickSize; j++) {
- leftJoystick = m_testJoystickValues[i];
- rightJoystick = m_testJoystickValues[j];
- m_robotDrive.TankDrive(leftJoystick, rightJoystick, true);
- m_differentialDrive.TankDrive(leftJoystick, rightJoystick, true);
- ASSERT_NEAR(m_rdFrontLeft.Get(), m_frontLeft.Get(), 0.01);
- ASSERT_NEAR(m_rdFrontRight.Get(), m_frontRight.Get(), 0.01);
- }
- }
-}
-
-TEST_F(DriveTest, ArcadeDriveSquared) {
- int joystickSize = sizeof(m_testJoystickValues) / sizeof(double);
- double moveJoystick, rotateJoystick;
- m_differentialDrive.SetDeadband(0.0);
- m_differentialDrive.SetSafetyEnabled(false);
- m_mecanumDrive.SetSafetyEnabled(false);
- m_robotDrive.SetSafetyEnabled(false);
- for (int i = 0; i < joystickSize; i++) {
- for (int j = 0; j < joystickSize; j++) {
- moveJoystick = m_testJoystickValues[i];
- rotateJoystick = m_testJoystickValues[j];
- m_robotDrive.ArcadeDrive(moveJoystick, rotateJoystick, true);
- m_differentialDrive.ArcadeDrive(moveJoystick, -rotateJoystick, true);
- ASSERT_NEAR(m_rdFrontLeft.Get(), m_frontLeft.Get(), 0.01);
- ASSERT_NEAR(m_rdFrontRight.Get(), m_frontRight.Get(), 0.01);
- }
- }
-}
-
-TEST_F(DriveTest, ArcadeDrive) {
- int joystickSize = sizeof(m_testJoystickValues) / sizeof(double);
- double moveJoystick, rotateJoystick;
- m_differentialDrive.SetDeadband(0.0);
- m_differentialDrive.SetSafetyEnabled(false);
- m_mecanumDrive.SetSafetyEnabled(false);
- m_robotDrive.SetSafetyEnabled(false);
- for (int i = 0; i < joystickSize; i++) {
- for (int j = 0; j < joystickSize; j++) {
- moveJoystick = m_testJoystickValues[i];
- rotateJoystick = m_testJoystickValues[j];
- m_robotDrive.ArcadeDrive(moveJoystick, rotateJoystick, false);
- m_differentialDrive.ArcadeDrive(moveJoystick, -rotateJoystick, false);
- ASSERT_NEAR(m_rdFrontLeft.Get(), m_frontLeft.Get(), 0.01);
- ASSERT_NEAR(m_rdFrontRight.Get(), m_frontRight.Get(), 0.01);
- }
- }
-}
-
-TEST_F(DriveTest, MecanumCartesian) {
- int joystickSize = sizeof(m_testJoystickValues) / sizeof(double);
- int gyroSize = sizeof(m_testGyroValues) / sizeof(double);
- double xJoystick, yJoystick, rotateJoystick, gyroValue;
- m_mecanumDrive.SetDeadband(0.0);
- m_mecanumDrive.SetSafetyEnabled(false);
- m_differentialDrive.SetSafetyEnabled(false);
- m_robotDrive.SetSafetyEnabled(false);
- for (int i = 0; i < joystickSize; i++) {
- for (int j = 0; j < joystickSize; j++) {
- for (int k = 0; k < joystickSize; k++) {
- for (int l = 0; l < gyroSize; l++) {
- xJoystick = m_testJoystickValues[i];
- yJoystick = m_testJoystickValues[j];
- rotateJoystick = m_testJoystickValues[k];
- gyroValue = m_testGyroValues[l];
- m_robotDrive.MecanumDrive_Cartesian(xJoystick, yJoystick,
- rotateJoystick, gyroValue);
- m_mecanumDrive.DriveCartesian(xJoystick, -yJoystick, rotateJoystick,
- -gyroValue);
- ASSERT_NEAR(m_rdFrontLeft.Get(), m_frontLeft.Get(), 0.01)
- << "X: " << xJoystick << " Y: " << yJoystick
- << " Rotate: " << rotateJoystick << " Gyro: " << gyroValue;
- ASSERT_NEAR(m_rdFrontRight.Get(), -m_frontRight.Get(), 0.01)
- << "X: " << xJoystick << " Y: " << yJoystick
- << " Rotate: " << rotateJoystick << " Gyro: " << gyroValue;
- ASSERT_NEAR(m_rdRearLeft.Get(), m_rearLeft.Get(), 0.01)
- << "X: " << xJoystick << " Y: " << yJoystick
- << " Rotate: " << rotateJoystick << " Gyro: " << gyroValue;
- ASSERT_NEAR(m_rdRearRight.Get(), -m_rearRight.Get(), 0.01)
- << "X: " << xJoystick << " Y: " << yJoystick
- << " Rotate: " << rotateJoystick << " Gyro: " << gyroValue;
- }
- }
- }
- }
-}
-
-TEST_F(DriveTest, MecanumPolar) {
- int joystickSize = sizeof(m_testJoystickValues) / sizeof(double);
- int gyroSize = sizeof(m_testGyroValues) / sizeof(double);
- double magnitudeJoystick, directionJoystick, rotateJoystick;
- m_mecanumDrive.SetDeadband(0.0);
- m_mecanumDrive.SetSafetyEnabled(false);
- m_differentialDrive.SetSafetyEnabled(false);
- m_robotDrive.SetSafetyEnabled(false);
- for (int i = 0; i < joystickSize; i++) {
- for (int j = 0; j < gyroSize; j++) {
- for (int k = 0; k < joystickSize; k++) {
- magnitudeJoystick = m_testJoystickValues[i];
- directionJoystick = m_testGyroValues[j];
- rotateJoystick = m_testJoystickValues[k];
- m_robotDrive.MecanumDrive_Polar(magnitudeJoystick, directionJoystick,
- rotateJoystick);
- m_mecanumDrive.DrivePolar(magnitudeJoystick, directionJoystick,
- rotateJoystick);
- ASSERT_NEAR(m_rdFrontLeft.Get(), m_frontLeft.Get(), 0.01)
- << "Magnitude: " << magnitudeJoystick
- << " Direction: " << directionJoystick
- << " Rotate: " << rotateJoystick;
- ASSERT_NEAR(m_rdFrontRight.Get(), -m_frontRight.Get(), 0.01)
- << "Magnitude: " << magnitudeJoystick
- << " Direction: " << directionJoystick
- << " Rotate: " << rotateJoystick;
- ASSERT_NEAR(m_rdRearLeft.Get(), m_rearLeft.Get(), 0.01)
- << "Magnitude: " << magnitudeJoystick
- << " Direction: " << directionJoystick
- << " Rotate: " << rotateJoystick;
- ASSERT_NEAR(m_rdRearRight.Get(), -m_rearRight.Get(), 0.01)
- << "Magnitude: " << magnitudeJoystick
- << " Direction: " << directionJoystick
- << " Rotate: " << rotateJoystick;
- }
- }
- }
-}
diff --git a/wpilibc/src/test/native/cpp/drive/KilloughDriveTest.cpp b/wpilibc/src/test/native/cpp/drive/KilloughDriveTest.cpp
new file mode 100644
index 0000000..510b377
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/drive/KilloughDriveTest.cpp
@@ -0,0 +1,123 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <cmath>
+
+#include "MockMotorController.h"
+#include "frc/drive/KilloughDrive.h"
+#include "gtest/gtest.h"
+
+TEST(KilloughDriveTest, Cartesian) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::MockMotorController back;
+ frc::KilloughDrive drive{left, right, back};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.DriveCartesian(1.0, 0.0, 0.0);
+ EXPECT_DOUBLE_EQ(0.5, left.Get());
+ EXPECT_DOUBLE_EQ(-0.5, right.Get());
+ EXPECT_NEAR(0.0, back.Get(), 1e-9);
+
+ // Left
+ drive.DriveCartesian(0.0, -1.0, 0.0);
+ EXPECT_DOUBLE_EQ(-std::sqrt(3) / 2, left.Get());
+ EXPECT_DOUBLE_EQ(-std::sqrt(3) / 2, right.Get());
+ EXPECT_DOUBLE_EQ(1.0, back.Get());
+
+ // Right
+ drive.DriveCartesian(0.0, 1.0, 0.0);
+ EXPECT_DOUBLE_EQ(std::sqrt(3) / 2, left.Get());
+ EXPECT_DOUBLE_EQ(std::sqrt(3) / 2, right.Get());
+ EXPECT_DOUBLE_EQ(-1.0, back.Get());
+
+ // Rotate CCW
+ drive.DriveCartesian(0.0, 0.0, -1.0);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+ EXPECT_DOUBLE_EQ(-1.0, back.Get());
+
+ // Rotate CW
+ drive.DriveCartesian(0.0, 0.0, 1.0);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+ EXPECT_DOUBLE_EQ(1.0, back.Get());
+}
+
+TEST(KilloughDriveTest, CartesianGyro90CW) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::MockMotorController back;
+ frc::KilloughDrive drive{left, right, back};
+ drive.SetDeadband(0.0);
+
+ // Forward in global frame; left in robot frame
+ drive.DriveCartesian(1.0, 0.0, 0.0, 90.0);
+ EXPECT_DOUBLE_EQ(-std::sqrt(3) / 2, left.Get());
+ EXPECT_DOUBLE_EQ(-std::sqrt(3) / 2, right.Get());
+ EXPECT_DOUBLE_EQ(1.0, back.Get());
+
+ // Left in global frame; backward in robot frame
+ drive.DriveCartesian(0.0, -1.0, 0.0, 90.0);
+ EXPECT_DOUBLE_EQ(-0.5, left.Get());
+ EXPECT_NEAR(0.5, right.Get(), 1e-9);
+ EXPECT_NEAR(0.0, back.Get(), 1e-9);
+
+ // Right in global frame; forward in robot frame
+ drive.DriveCartesian(0.0, 1.0, 0.0, 90.0);
+ EXPECT_DOUBLE_EQ(0.5, left.Get());
+ EXPECT_NEAR(-0.5, right.Get(), 1e-9);
+ EXPECT_NEAR(0.0, back.Get(), 1e-9);
+
+ // Rotate CCW
+ drive.DriveCartesian(0.0, 0.0, -1.0, 90.0);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+ EXPECT_DOUBLE_EQ(-1.0, back.Get());
+
+ // Rotate CW
+ drive.DriveCartesian(0.0, 0.0, 1.0, 90.0);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+ EXPECT_DOUBLE_EQ(1.0, back.Get());
+}
+
+TEST(KilloughDriveTest, Polar) {
+ frc::MockMotorController left;
+ frc::MockMotorController right;
+ frc::MockMotorController back;
+ frc::KilloughDrive drive{left, right, back};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.DrivePolar(1.0, 0.0, 0.0);
+ EXPECT_DOUBLE_EQ(std::sqrt(3) / 2, left.Get());
+ EXPECT_DOUBLE_EQ(std::sqrt(3) / 2, right.Get());
+ EXPECT_DOUBLE_EQ(-1.0, back.Get());
+
+ // Left
+ drive.DrivePolar(1.0, -90.0, 0.0);
+ EXPECT_DOUBLE_EQ(-0.5, left.Get());
+ EXPECT_DOUBLE_EQ(0.5, right.Get());
+ EXPECT_NEAR(0.0, back.Get(), 1e-9);
+
+ // Right
+ drive.DrivePolar(1.0, 90.0, 0.0);
+ EXPECT_DOUBLE_EQ(0.5, left.Get());
+ EXPECT_NEAR(-0.5, right.Get(), 1e-9);
+ EXPECT_NEAR(0.0, back.Get(), 1e-9);
+
+ // Rotate CCW
+ drive.DrivePolar(0.0, 0.0, -1.0);
+ EXPECT_DOUBLE_EQ(-1.0, left.Get());
+ EXPECT_DOUBLE_EQ(-1.0, right.Get());
+ EXPECT_DOUBLE_EQ(-1.0, back.Get());
+
+ // Rotate CW
+ drive.DrivePolar(0.0, 0.0, 1.0);
+ EXPECT_DOUBLE_EQ(1.0, left.Get());
+ EXPECT_DOUBLE_EQ(1.0, right.Get());
+ EXPECT_DOUBLE_EQ(1.0, back.Get());
+}
diff --git a/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp b/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp
new file mode 100644
index 0000000..fe0a73b
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/drive/MecanumDriveTest.cpp
@@ -0,0 +1,139 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "MockMotorController.h"
+#include "frc/drive/MecanumDrive.h"
+#include "gtest/gtest.h"
+
+TEST(MecanumDriveTest, Cartesian) {
+ frc::MockMotorController fl;
+ frc::MockMotorController fr;
+ frc::MockMotorController rl;
+ frc::MockMotorController rr;
+ frc::MecanumDrive drive{fl, fr, rl, rr};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.DriveCartesian(1.0, 0.0, 0.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Left
+ drive.DriveCartesian(0.0, -1.0, 0.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+
+ // Right
+ drive.DriveCartesian(0.0, 1.0, 0.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Rotate CCW
+ drive.DriveCartesian(0.0, 0.0, -1.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Rotate CW
+ drive.DriveCartesian(0.0, 0.0, 1.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+}
+
+TEST(MecanumDriveTest, CartesianGyro90CW) {
+ frc::MockMotorController fl;
+ frc::MockMotorController fr;
+ frc::MockMotorController rl;
+ frc::MockMotorController rr;
+ frc::MecanumDrive drive{fl, fr, rl, rr};
+ drive.SetDeadband(0.0);
+
+ // Forward in global frame; left in robot frame
+ drive.DriveCartesian(1.0, 0.0, 0.0, 90.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+
+ // Left in global frame; backward in robot frame
+ drive.DriveCartesian(0.0, -1.0, 0.0, 90.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+
+ // Right in global frame; forward in robot frame
+ drive.DriveCartesian(0.0, 1.0, 0.0, 90.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Rotate CCW
+ drive.DriveCartesian(0.0, 0.0, -1.0, 90.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Rotate CW
+ drive.DriveCartesian(0.0, 0.0, 1.0, 90.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+}
+
+TEST(MecanumDriveTest, Polar) {
+ frc::MockMotorController fl;
+ frc::MockMotorController fr;
+ frc::MockMotorController rl;
+ frc::MockMotorController rr;
+ frc::MecanumDrive drive{fl, fr, rl, rr};
+ drive.SetDeadband(0.0);
+
+ // Forward
+ drive.DrivePolar(1.0, 0.0, 0.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Left
+ drive.DrivePolar(1.0, -90.0, 0.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+
+ // Right
+ drive.DrivePolar(1.0, 90.0, 0.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Rotate CCW
+ drive.DrivePolar(0.0, 0.0, -1.0);
+ EXPECT_DOUBLE_EQ(-1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(1.0, rr.Get());
+
+ // Rotate CW
+ drive.DrivePolar(0.0, 0.0, 1.0);
+ EXPECT_DOUBLE_EQ(1.0, fl.Get());
+ EXPECT_DOUBLE_EQ(1.0, fr.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rl.Get());
+ EXPECT_DOUBLE_EQ(-1.0, rr.Get());
+}
diff --git a/wpilibc/src/test/native/cpp/main.cpp b/wpilibc/src/test/native/cpp/main.cpp
index c6b6c58..6aea19a 100644
--- a/wpilibc/src/test/native/cpp/main.cpp
+++ b/wpilibc/src/test/native/cpp/main.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <hal/HALBase.h>
diff --git a/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp b/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp
index 172d7c6..5a9f993 100644
--- a/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp
+++ b/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp
@@ -1,20 +1,16 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "shuffleboard/MockActuatorSendable.h"
-#include "frc/smartdashboard/SendableRegistry.h"
+#include <wpi/sendable/SendableBuilder.h>
+#include <wpi/sendable/SendableRegistry.h>
-using namespace frc;
-
-MockActuatorSendable::MockActuatorSendable(wpi::StringRef name) {
- SendableRegistry::GetInstance().Add(this, name);
+MockActuatorSendable::MockActuatorSendable(std::string_view name) {
+ wpi::SendableRegistry::Add(this, name);
}
-void MockActuatorSendable::InitSendable(SendableBuilder& builder) {
+void MockActuatorSendable::InitSendable(wpi::SendableBuilder& builder) {
builder.SetActuator(true);
}
diff --git a/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardInstanceTest.cpp b/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardInstanceTest.cpp
index ae21526..d370a2d 100644
--- a/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardInstanceTest.cpp
+++ b/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardInstanceTest.cpp
@@ -1,50 +1,46 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/ShuffleboardInstance.h" // NOLINT(build/include_order)
-#include <memory>
-#include <string>
+#include <string_view>
-#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableInstance.h>
#include "frc/shuffleboard/ShuffleboardInstance.h"
#include "gtest/gtest.h"
#include "shuffleboard/MockActuatorSendable.h"
-using namespace frc;
+class NTWrapper {
+ public:
+ NTWrapper() { inst = nt::NetworkTableInstance::Create(); }
-class ShuffleboardInstanceTest : public testing::Test {
- void SetUp() override {
- m_ntInstance = nt::NetworkTableInstance::Create();
- m_shuffleboardInstance =
- std::make_unique<detail::ShuffleboardInstance>(m_ntInstance);
- }
+ ~NTWrapper() { nt::NetworkTableInstance::Destroy(inst); }
- protected:
- nt::NetworkTableInstance m_ntInstance;
- std::unique_ptr<detail::ShuffleboardInstance> m_shuffleboardInstance;
+ nt::NetworkTableInstance inst;
};
-TEST_F(ShuffleboardInstanceTest, PathFluent) {
- auto entry = m_shuffleboardInstance->GetTab("Tab Title")
- .GetLayout("List Layout", "List")
+TEST(ShuffleboardInstanceTest, PathFluent) {
+ NTWrapper ntInst;
+ frc::detail::ShuffleboardInstance shuffleboardInst{ntInst.inst};
+
+ auto entry = shuffleboardInst.GetTab("Tab Title")
+ .GetLayout("List", "List Layout")
.Add("Data", "string")
.WithWidget("Text View")
.GetEntry();
EXPECT_EQ("string", entry.GetString("")) << "Wrong entry value";
- EXPECT_EQ("/Shuffleboard/Tab Title/List Layout/Data", entry.GetName())
+ EXPECT_EQ("/Shuffleboard/Tab Title/List/Data", entry.GetName())
<< "Entry path generated incorrectly";
}
-TEST_F(ShuffleboardInstanceTest, NestedLayoutsFluent) {
- auto entry = m_shuffleboardInstance->GetTab("Tab")
+TEST(ShuffleboardInstanceTest, NestedLayoutsFluent) {
+ NTWrapper ntInst;
+ frc::detail::ShuffleboardInstance shuffleboardInst{ntInst.inst};
+
+ auto entry = shuffleboardInst.GetTab("Tab")
.GetLayout("First", "List")
.GetLayout("Second", "List")
.GetLayout("Third", "List")
@@ -58,13 +54,16 @@
<< "Entry path generated incorrectly";
}
-TEST_F(ShuffleboardInstanceTest, NestedLayoutsOop) {
- ShuffleboardTab& tab = m_shuffleboardInstance->GetTab("Tab");
- ShuffleboardLayout& first = tab.GetLayout("First", "List");
- ShuffleboardLayout& second = first.GetLayout("Second", "List");
- ShuffleboardLayout& third = second.GetLayout("Third", "List");
- ShuffleboardLayout& fourth = third.GetLayout("Fourth", "List");
- SimpleWidget& widget = fourth.Add("Value", "string");
+TEST(ShuffleboardInstanceTest, NestedLayoutsOop) {
+ NTWrapper ntInst;
+ frc::detail::ShuffleboardInstance shuffleboardInst{ntInst.inst};
+
+ frc::ShuffleboardTab& tab = shuffleboardInst.GetTab("Tab");
+ frc::ShuffleboardLayout& first = tab.GetLayout("First", "List");
+ frc::ShuffleboardLayout& second = first.GetLayout("Second", "List");
+ frc::ShuffleboardLayout& third = second.GetLayout("Third", "List");
+ frc::ShuffleboardLayout& fourth = third.GetLayout("Fourth", "List");
+ frc::SimpleWidget& widget = fourth.Add("Value", "string");
auto entry = widget.GetEntry();
EXPECT_EQ("string", entry.GetString("")) << "Wrong entry value";
@@ -73,23 +72,27 @@
<< "Entry path generated incorrectly";
}
-TEST_F(ShuffleboardInstanceTest, LayoutTypeIsSet) {
- std::string layoutType = "Type";
- m_shuffleboardInstance->GetTab("Tab").GetLayout("Title", layoutType);
- m_shuffleboardInstance->Update();
- nt::NetworkTableEntry entry = m_ntInstance.GetEntry(
+TEST(ShuffleboardInstanceTest, LayoutTypeIsSet) {
+ NTWrapper ntInst;
+ frc::detail::ShuffleboardInstance shuffleboardInst{ntInst.inst};
+
+ std::string_view layoutType = "Type";
+ shuffleboardInst.GetTab("Tab").GetLayout("Title", layoutType);
+ shuffleboardInst.Update();
+ auto entry = ntInst.inst.GetEntry(
"/Shuffleboard/.metadata/Tab/Title/PreferredComponent");
EXPECT_EQ(layoutType, entry.GetString("Not Set")) << "Layout type not set";
}
-TEST_F(ShuffleboardInstanceTest, NestedActuatorWidgetsAreDisabled) {
+TEST(ShuffleboardInstanceTest, NestedActuatorWidgetsAreDisabled) {
+ NTWrapper ntInst;
+ frc::detail::ShuffleboardInstance shuffleboardInst{ntInst.inst};
+
MockActuatorSendable sendable("Actuator");
- m_shuffleboardInstance->GetTab("Tab")
- .GetLayout("Title", "Type")
- .Add(sendable);
+ shuffleboardInst.GetTab("Tab").GetLayout("Title", "Layout").Add(sendable);
auto controllableEntry =
- m_ntInstance.GetEntry("/Shuffleboard/Tab/Title/Actuator/.controllable");
- m_shuffleboardInstance->Update();
+ ntInst.inst.GetEntry("/Shuffleboard/Tab/Title/Actuator/.controllable");
+ shuffleboardInst.Update();
// Note: we use the unsafe `GetBoolean()` method because if the value is NOT
// a boolean, or if it is not present, then something has clearly gone very,
@@ -98,7 +101,7 @@
// Sanity check
EXPECT_TRUE(controllable)
<< "The nested actuator widget should be enabled by default";
- m_shuffleboardInstance->DisableActuatorWidgets();
+ shuffleboardInst.DisableActuatorWidgets();
controllable = controllableEntry.GetValue()->GetBoolean();
EXPECT_FALSE(controllable)
<< "The nested actuator widget should have been disabled";
diff --git a/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardTest.cpp b/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardTest.cpp
index d39d59d..693aac4 100644
--- a/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardTest.cpp
+++ b/wpilibc/src/test/native/cpp/shuffleboard/ShuffleboardTest.cpp
@@ -1,20 +1,12 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/shuffleboard/Shuffleboard.h"
-#include "frc/shuffleboard/ShuffleboardTab.h"
#include "gtest/gtest.h"
-using namespace frc;
-
-class ShuffleboardTest : public testing::Test {};
-
-TEST_F(ShuffleboardTest, TabObjectsCached) {
- ShuffleboardTab& tab1 = Shuffleboard::GetTab("testTabObjectsCached");
- ShuffleboardTab& tab2 = Shuffleboard::GetTab("testTabObjectsCached");
+TEST(ShuffleboardTest, TabObjectsCached) {
+ auto& tab1 = frc::Shuffleboard::GetTab("testTabObjectsCached");
+ auto& tab2 = frc::Shuffleboard::GetTab("testTabObjectsCached");
EXPECT_EQ(&tab1, &tab2) << "Tab objects were not cached";
}
diff --git a/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp b/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp
index 8e39915..c8449e5 100644
--- a/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp
+++ b/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <networktables/NetworkTableEntry.h>
#include <networktables/NetworkTableInstance.h>
@@ -14,52 +11,55 @@
using namespace frc;
-class SuppliedValueWidgetTest : public testing::Test {
- void SetUp() override {
- m_ntInstance = nt::NetworkTableInstance::Create();
- m_instance = std::make_unique<detail::ShuffleboardInstance>(m_ntInstance);
- m_tab = &(m_instance->GetTab("Tab"));
- }
+class NTWrapper {
+ public:
+ NTWrapper() { inst = nt::NetworkTableInstance::Create(); }
+ ~NTWrapper() { nt::NetworkTableInstance::Destroy(inst); }
+
+ nt::NetworkTableInstance inst;
+};
+
+class SuppliedValueWidgetTest : public testing::Test {
protected:
- nt::NetworkTableInstance m_ntInstance;
- ShuffleboardTab* m_tab;
- std::unique_ptr<detail::ShuffleboardInstance> m_instance;
+ NTWrapper m_ntInst;
+ frc::detail::ShuffleboardInstance m_shuffleboardInst{m_ntInst.inst};
+ frc::ShuffleboardTab* m_tab = &(m_shuffleboardInst.GetTab("Tab"));
};
TEST_F(SuppliedValueWidgetTest, AddString) {
std::string str = "foo";
m_tab->AddString("String", [&str]() { return str; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/String");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/String");
- m_instance->Update();
+ m_shuffleboardInst.Update();
EXPECT_EQ("foo", entry.GetValue()->GetString());
}
TEST_F(SuppliedValueWidgetTest, AddNumber) {
int num = 0;
m_tab->AddNumber("Num", [&num]() { return ++num; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/Num");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Num");
- m_instance->Update();
+ m_shuffleboardInst.Update();
EXPECT_FLOAT_EQ(1.0, entry.GetValue()->GetDouble());
}
TEST_F(SuppliedValueWidgetTest, AddBoolean) {
bool value = true;
m_tab->AddBoolean("Bool", [&value]() { return value; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/Bool");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Bool");
- m_instance->Update();
+ m_shuffleboardInst.Update();
EXPECT_EQ(true, entry.GetValue()->GetBoolean());
}
TEST_F(SuppliedValueWidgetTest, AddStringArray) {
std::vector<std::string> strings = {"foo", "bar"};
m_tab->AddStringArray("Strings", [&strings]() { return strings; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/Strings");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Strings");
- m_instance->Update();
+ m_shuffleboardInst.Update();
auto actual = entry.GetValue()->GetStringArray();
EXPECT_EQ(strings.size(), actual.size());
@@ -71,9 +71,9 @@
TEST_F(SuppliedValueWidgetTest, AddNumberArray) {
std::vector<double> nums = {0, 1, 2, 3};
m_tab->AddNumberArray("Numbers", [&nums]() { return nums; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/Numbers");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Numbers");
- m_instance->Update();
+ m_shuffleboardInst.Update();
auto actual = entry.GetValue()->GetDoubleArray();
EXPECT_EQ(nums.size(), actual.size());
@@ -85,9 +85,9 @@
TEST_F(SuppliedValueWidgetTest, AddBooleanArray) {
std::vector<int> bools = {true, false};
m_tab->AddBooleanArray("Booleans", [&bools]() { return bools; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/Booleans");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Booleans");
- m_instance->Update();
+ m_shuffleboardInst.Update();
auto actual = entry.GetValue()->GetBooleanArray();
EXPECT_EQ(bools.size(), actual.size());
@@ -97,11 +97,11 @@
}
TEST_F(SuppliedValueWidgetTest, AddRaw) {
- wpi::StringRef bytes = "\1\2\3";
+ std::string_view bytes = "\1\2\3";
m_tab->AddRaw("Raw", [&bytes]() { return bytes; });
- auto entry = m_ntInstance.GetEntry("/Shuffleboard/Tab/Raw");
+ auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Raw");
- m_instance->Update();
+ m_shuffleboardInst.Update();
auto actual = entry.GetValue()->GetRaw();
EXPECT_EQ(bytes, actual);
}
diff --git a/wpilibc/src/test/native/cpp/simulation/ADXL345SimTest.cpp b/wpilibc/src/test/native/cpp/simulation/ADXL345SimTest.cpp
new file mode 100644
index 0000000..2bec0ed
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/ADXL345SimTest.cpp
@@ -0,0 +1,63 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/ADXL345Sim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "frc/ADXL345_I2C.h"
+#include "frc/ADXL345_SPI.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(ADXL345SimTest, SetSpiAttributes) {
+ HAL_Initialize(500, 0);
+
+ ADXL345_SPI accel(SPI::kMXP, Accelerometer::kRange_2G);
+ ADXL345Sim sim(accel);
+
+ EXPECT_EQ(0, accel.GetX());
+ EXPECT_EQ(0, accel.GetY());
+ EXPECT_EQ(0, accel.GetZ());
+
+ sim.SetX(1.91);
+ sim.SetY(-3.405);
+ sim.SetZ(2.29);
+
+ EXPECT_EQ(1.91, accel.GetX());
+ EXPECT_EQ(-3.405, accel.GetY());
+ EXPECT_EQ(2.29, accel.GetZ());
+
+ ADXL345_SPI::AllAxes allAccel = accel.GetAccelerations();
+ EXPECT_EQ(1.91, allAccel.XAxis);
+ EXPECT_EQ(-3.405, allAccel.YAxis);
+ EXPECT_EQ(2.29, allAccel.ZAxis);
+}
+
+TEST(ADXL345SimTest, SetI2CAttribute) {
+ HAL_Initialize(500, 0);
+
+ ADXL345_I2C accel(I2C::kMXP);
+ ADXL345Sim sim(accel);
+
+ EXPECT_EQ(0, accel.GetX());
+ EXPECT_EQ(0, accel.GetY());
+ EXPECT_EQ(0, accel.GetZ());
+
+ sim.SetX(1.91);
+ sim.SetY(-3.405);
+ sim.SetZ(2.29);
+
+ EXPECT_EQ(1.91, accel.GetX());
+ EXPECT_EQ(-3.405, accel.GetY());
+ EXPECT_EQ(2.29, accel.GetZ());
+
+ ADXL345_I2C::AllAxes allAccel = accel.GetAccelerations();
+ EXPECT_EQ(1.91, allAccel.XAxis);
+ EXPECT_EQ(-3.405, allAccel.YAxis);
+ EXPECT_EQ(2.29, allAccel.ZAxis);
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/ADXL362SimTest.cpp b/wpilibc/src/test/native/cpp/simulation/ADXL362SimTest.cpp
new file mode 100644
index 0000000..13f6c00
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/ADXL362SimTest.cpp
@@ -0,0 +1,38 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/ADXL362Sim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "frc/ADXL362.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(ADXL362SimTest, SetAttributes) {
+ HAL_Initialize(500, 0);
+
+ ADXL362 accel(SPI::kMXP, Accelerometer::kRange_2G);
+ ADXL362Sim sim(accel);
+
+ EXPECT_EQ(0, accel.GetX());
+ EXPECT_EQ(0, accel.GetY());
+ EXPECT_EQ(0, accel.GetZ());
+
+ sim.SetX(1.91);
+ sim.SetY(-3.405);
+ sim.SetZ(2.29);
+
+ EXPECT_EQ(1.91, accel.GetX());
+ EXPECT_EQ(-3.405, accel.GetY());
+ EXPECT_EQ(2.29, accel.GetZ());
+
+ ADXL362::AllAxes allAccel = accel.GetAccelerations();
+ EXPECT_EQ(1.91, allAccel.XAxis);
+ EXPECT_EQ(-3.405, allAccel.YAxis);
+ EXPECT_EQ(2.29, allAccel.ZAxis);
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/ADXRS450_GyroSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/ADXRS450_GyroSimTest.cpp
new file mode 100644
index 0000000..57c4fbe
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/ADXRS450_GyroSimTest.cpp
@@ -0,0 +1,35 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/ADXRS450_GyroSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "frc/ADXRS450_Gyro.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(ADXRS450GyroSimTest, SetAttributes) {
+ HAL_Initialize(500, 0);
+
+ ADXRS450_Gyro gyro;
+ ADXRS450_GyroSim sim{gyro};
+
+ EXPECT_EQ(0, gyro.GetAngle());
+ EXPECT_EQ(0, gyro.GetRate());
+
+ constexpr units::degree_t TEST_ANGLE{123.456};
+ constexpr units::degrees_per_second_t TEST_RATE{229.3504};
+ sim.SetAngle(TEST_ANGLE);
+ sim.SetRate(TEST_RATE);
+
+ EXPECT_EQ(TEST_ANGLE.value(), gyro.GetAngle());
+ EXPECT_EQ(TEST_RATE.value(), gyro.GetRate());
+
+ gyro.Reset();
+ EXPECT_EQ(0, gyro.GetAngle());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp
index d2c7ea8..3dc8582 100644
--- a/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp
@@ -1,20 +1,19 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include "frc/simulation/BuiltInAccelerometerSim.h" // NOLINT(build/include_order)
#include <hal/Accelerometer.h>
#include <hal/HAL.h>
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/BuiltInAccelerometer.h"
#include "gtest/gtest.h"
-using namespace frc::sim;
+namespace frc::sim {
-TEST(AcclerometerSimTests, TestActiveCallback) {
+TEST(AcclerometerSimTest, ActiveCallback) {
HAL_Initialize(500, 0);
BuiltInAccelerometerSim sim;
@@ -25,7 +24,7 @@
bool lastValue = false;
auto cb = sim.RegisterActiveCallback(
- [&](wpi::StringRef name, const HAL_Value* value) {
+ [&](std::string_view name, const HAL_Value* value) {
wasTriggered = true;
lastValue = value->data.v_boolean;
},
@@ -37,4 +36,103 @@
EXPECT_TRUE(wasTriggered);
EXPECT_TRUE(lastValue);
+ EXPECT_TRUE(sim.GetActive());
}
+
+TEST(AcclerometerSimTest, SetX) {
+ HAL_Initialize(500, 0);
+ BuiltInAccelerometerSim sim;
+ sim.ResetData();
+
+ DoubleCallback callback;
+ constexpr double kTestValue = 1.91;
+
+ BuiltInAccelerometer accel;
+ auto cb = sim.RegisterXCallback(callback.GetCallback(), false);
+ sim.SetX(kTestValue);
+ EXPECT_EQ(kTestValue, accel.GetX());
+ EXPECT_EQ(kTestValue, sim.GetX());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestValue, callback.GetLastValue());
+}
+
+TEST(AcclerometerSimTest, SetY) {
+ HAL_Initialize(500, 0);
+ BuiltInAccelerometerSim sim;
+ sim.ResetData();
+
+ DoubleCallback callback;
+ constexpr double kTestValue = 2.29;
+
+ BuiltInAccelerometer accel;
+ auto cb = sim.RegisterYCallback(callback.GetCallback(), false);
+ sim.SetY(kTestValue);
+ EXPECT_EQ(kTestValue, accel.GetY());
+ EXPECT_EQ(kTestValue, sim.GetY());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestValue, callback.GetLastValue());
+}
+
+TEST(AcclerometerSimTest, SetZ) {
+ HAL_Initialize(500, 0);
+
+ BuiltInAccelerometer accel;
+ BuiltInAccelerometerSim sim(accel);
+ sim.ResetData();
+
+ DoubleCallback callback;
+ constexpr double kTestValue = 3.405;
+
+ auto cb = sim.RegisterZCallback(callback.GetCallback(), false);
+ sim.SetZ(kTestValue);
+ EXPECT_EQ(kTestValue, accel.GetZ());
+ EXPECT_EQ(kTestValue, sim.GetZ());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestValue, callback.GetLastValue());
+}
+
+TEST(AcclerometerSimTest, SetRange) {
+ HAL_Initialize(500, 0);
+
+ BuiltInAccelerometerSim sim;
+ sim.ResetData();
+
+ EnumCallback callback;
+
+ Accelerometer::Range range = Accelerometer::kRange_4G;
+ auto cb = sim.RegisterRangeCallback(callback.GetCallback(), false);
+ BuiltInAccelerometer accel(range);
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(static_cast<int>(range), sim.GetRange());
+ EXPECT_EQ(static_cast<int>(range), callback.GetLastValue());
+
+ // 2G
+ callback.Reset();
+ range = Accelerometer::kRange_2G;
+ accel.SetRange(range);
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(static_cast<int>(range), sim.GetRange());
+ EXPECT_EQ(static_cast<int>(range), callback.GetLastValue());
+
+ // 4G
+ callback.Reset();
+ range = Accelerometer::kRange_4G;
+ accel.SetRange(range);
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(static_cast<int>(range), sim.GetRange());
+ EXPECT_EQ(static_cast<int>(range), callback.GetLastValue());
+
+ // 8G
+ callback.Reset();
+ range = Accelerometer::kRange_8G;
+ accel.SetRange(range);
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(static_cast<int>(range), sim.GetRange());
+ EXPECT_EQ(static_cast<int>(range), callback.GetLastValue());
+
+ // 16G - Not supported
+ callback.Reset();
+ EXPECT_THROW(accel.SetRange(Accelerometer::kRange_16G), std::runtime_error);
+ EXPECT_FALSE(callback.WasTriggered());
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/AddressableLEDSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AddressableLEDSimTest.cpp
new file mode 100644
index 0000000..ad4452e
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/AddressableLEDSimTest.cpp
@@ -0,0 +1,129 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/AddressableLEDSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/AddressableLED.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(AddressableLEDSimTest, InitializationCallback) {
+ HAL_Initialize(500, 0);
+
+ BooleanCallback callback;
+ AddressableLEDSim sim;
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+
+ EXPECT_FALSE(callback.WasTriggered());
+ AddressableLED led{0};
+
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(AddressableLEDSimTest, SetLength) {
+ HAL_Initialize(500, 0);
+
+ AddressableLED led{0};
+ AddressableLEDSim sim{led};
+ IntCallback callback;
+
+ auto cb = sim.RegisterLengthCallback(callback.GetCallback(), false);
+
+ EXPECT_EQ(1, sim.GetLength()); // Defaults to 1 led
+
+ std::array<AddressableLED::LEDData, 50> ledData;
+ led.SetLength(ledData.max_size());
+ led.SetData(ledData);
+
+ EXPECT_EQ(50, sim.GetLength());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(50, callback.GetLastValue());
+}
+
+TEST(AddressableLEDSimTest, SetRunning) {
+ HAL_Initialize(500, 0);
+
+ AddressableLEDSim sim = AddressableLEDSim::CreateForIndex(0);
+ BooleanCallback callback;
+ auto cb = sim.RegisterRunningCallback(callback.GetCallback(), false);
+ AddressableLED led{0};
+
+ EXPECT_FALSE(sim.GetRunning());
+
+ led.Start();
+ EXPECT_TRUE(sim.GetRunning());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ callback.Reset();
+ led.Stop();
+ EXPECT_FALSE(sim.GetRunning());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(AddressableLEDSimTest, SetData) {
+ AddressableLED led{0};
+ AddressableLEDSim sim = AddressableLEDSim::CreateForChannel(0);
+
+ bool callbackHit = false;
+ std::array<AddressableLED::LEDData, 3> setData;
+ auto cb = sim.RegisterDataCallback(
+ [&](std::string_view, const unsigned char* buffer, unsigned int count) {
+ ASSERT_EQ(count, 12u);
+ EXPECT_EQ(0, buffer[0]);
+ EXPECT_EQ(0, buffer[1]);
+ EXPECT_EQ(255u, buffer[2]);
+ EXPECT_EQ(0, buffer[3]);
+
+ EXPECT_EQ(0, buffer[4]);
+ EXPECT_EQ(255u, buffer[5]);
+ EXPECT_EQ(0, buffer[6]);
+ EXPECT_EQ(0, buffer[7]);
+
+ EXPECT_EQ(255u, buffer[8]);
+ EXPECT_EQ(0, buffer[9]);
+ EXPECT_EQ(0, buffer[10]);
+ EXPECT_EQ(0, buffer[11]);
+
+ callbackHit = true;
+ },
+ false);
+
+ std::array<AddressableLED::LEDData, 3> ledData;
+ led.SetLength(ledData.max_size());
+
+ ledData[0].SetRGB(255, 0, 0);
+ ledData[1].SetRGB(0, 255, 0);
+ ledData[2].SetRGB(0, 0, 255);
+ led.SetData(ledData);
+
+ EXPECT_TRUE(callbackHit);
+
+ std::array<HAL_AddressableLEDData, 3> simData;
+ sim.GetData(simData.data());
+
+ EXPECT_EQ(0xFF, simData[0].r);
+ EXPECT_EQ(0x00, simData[0].g);
+ EXPECT_EQ(0x00, simData[0].b);
+ EXPECT_EQ(0x00, simData[0].padding);
+
+ EXPECT_EQ(0x00, simData[1].r);
+ EXPECT_EQ(0xFF, simData[1].g);
+ EXPECT_EQ(0x00, simData[1].b);
+ EXPECT_EQ(0x00, simData[1].padding);
+
+ EXPECT_EQ(0x00, simData[2].r);
+ EXPECT_EQ(0x00, simData[2].g);
+ EXPECT_EQ(0xFF, simData[2].b);
+ EXPECT_EQ(0x00, simData[2].padding);
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/AnalogEncoderSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AnalogEncoderSimTest.cpp
index f32be7e..375e21a 100644
--- a/wpilibc/src/test/native/cpp/simulation/AnalogEncoderSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/AnalogEncoderSimTest.cpp
@@ -1,13 +1,10 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <hal/HAL.h>
#include <units/math.h>
-#include <wpi/math>
+#include <wpi/numbers>
#include "frc/AnalogEncoder.h"
#include "frc/AnalogInput.h"
@@ -17,14 +14,14 @@
#define EXPECT_NEAR_UNITS(val1, val2, eps) \
EXPECT_LE(units::math::abs(val1 - val2), eps)
-TEST(AnalogEncoderSimTest, TestBasic) {
+TEST(AnalogEncoderSimTest, Basic) {
frc::AnalogInput ai(0);
frc::AnalogEncoder encoder{ai};
frc::sim::AnalogEncoderSim encoderSim{encoder};
encoderSim.SetPosition(180_deg);
- EXPECT_NEAR(encoder.Get().to<double>(), 0.5, 1E-8);
- EXPECT_NEAR(encoderSim.GetTurns().to<double>(), 0.5, 1E-8);
- EXPECT_NEAR(encoderSim.GetPosition().Radians().to<double>(), wpi::math::pi,
+ EXPECT_NEAR(encoder.Get().value(), 0.5, 1E-8);
+ EXPECT_NEAR(encoderSim.GetTurns().value(), 0.5, 1E-8);
+ EXPECT_NEAR(encoderSim.GetPosition().Radians().value(), wpi::numbers::pi,
1E-8);
}
diff --git a/wpilibc/src/test/native/cpp/simulation/AnalogGyroSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AnalogGyroSimTest.cpp
new file mode 100644
index 0000000..f1baaca
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/AnalogGyroSimTest.cpp
@@ -0,0 +1,86 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/AnalogGyroSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/AnalogGyro.h"
+#include "frc/AnalogInput.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(AnalogGyroSimTest, InitializeGyro) {
+ HAL_Initialize(500, 0);
+ AnalogGyroSim sim{0};
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback initializedCallback;
+
+ auto cb =
+ sim.RegisterInitializedCallback(initializedCallback.GetCallback(), false);
+ AnalogGyro gyro(0);
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(initializedCallback.WasTriggered());
+ EXPECT_TRUE(initializedCallback.GetLastValue());
+}
+
+TEST(AnalogGyroSimTest, SetAngle) {
+ HAL_Initialize(500, 0);
+
+ AnalogGyroSim sim{0};
+ DoubleCallback callback;
+
+ AnalogInput ai(0);
+ AnalogGyro gyro(&ai);
+ auto cb = sim.RegisterAngleCallback(callback.GetCallback(), false);
+ EXPECT_EQ(0, gyro.GetAngle());
+
+ constexpr double kTestAngle = 35.04;
+ sim.SetAngle(kTestAngle);
+ EXPECT_EQ(kTestAngle, sim.GetAngle());
+ EXPECT_EQ(kTestAngle, gyro.GetAngle());
+ EXPECT_EQ(-kTestAngle, gyro.GetRotation2d().Degrees().value());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestAngle, callback.GetLastValue());
+}
+
+TEST(AnalogGyroSimTest, SetRate) {
+ HAL_Initialize(500, 0);
+
+ AnalogGyroSim sim{0};
+ DoubleCallback callback;
+
+ std::shared_ptr<AnalogInput> ai(new AnalogInput(0));
+ AnalogGyro gyro(ai);
+ auto cb = sim.RegisterRateCallback(callback.GetCallback(), false);
+ EXPECT_EQ(0, gyro.GetRate());
+
+ constexpr double kTestRate = -19.1;
+ sim.SetRate(kTestRate);
+ EXPECT_EQ(kTestRate, sim.GetRate());
+ EXPECT_EQ(kTestRate, gyro.GetRate());
+
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestRate, callback.GetLastValue());
+}
+
+TEST(AnalogGyroSimTest, Reset) {
+ HAL_Initialize(500, 0);
+
+ AnalogInput ai{0};
+ AnalogGyro gyro(&ai);
+ AnalogGyroSim sim(gyro);
+ sim.SetAngle(12.34);
+ sim.SetRate(43.21);
+
+ sim.ResetData();
+ EXPECT_EQ(0, sim.GetAngle());
+ EXPECT_EQ(0, sim.GetRate());
+ EXPECT_EQ(0, gyro.GetAngle());
+ EXPECT_EQ(0, gyro.GetRate());
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/AnalogInputSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AnalogInputSimTest.cpp
new file mode 100644
index 0000000..8b4569e
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/AnalogInputSimTest.cpp
@@ -0,0 +1,188 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/AnalogInputSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/AnalogInput.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(AnalogInputSimTest, SetInitialized) {
+ HAL_Initialize(500, 0);
+
+ AnalogInputSim sim{5};
+ BooleanCallback callback;
+
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+ AnalogInput input{5};
+
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, SetVoltage) {
+ HAL_Initialize(500, 0);
+
+ AnalogInputSim sim{5};
+ DoubleCallback callback;
+
+ auto cb = sim.RegisterVoltageCallback(callback.GetCallback(), false);
+ AnalogInput input{5};
+
+ for (int i = 0; i < 50; ++i) {
+ double voltage = i * .1;
+
+ callback.Reset();
+
+ sim.SetVoltage(0);
+ EXPECT_NEAR(sim.GetVoltage(), 0, 0.001) << " on " << i;
+ EXPECT_NEAR(input.GetVoltage(), 0, 0.001) << " on " << i;
+ // 0 -> 0 isn't a change, so callback not called
+ if (i > 2) {
+ EXPECT_TRUE(callback.WasTriggered()) << " on " << i;
+ EXPECT_EQ(0, callback.GetLastValue()) << " on " << i;
+ }
+
+ callback.Reset();
+ sim.SetVoltage(voltage);
+ EXPECT_NEAR(sim.GetVoltage(), voltage, 0.001) << " on " << i;
+ EXPECT_NEAR(input.GetVoltage(), voltage, 0.001) << " on " << i;
+
+ // 0 -> 0 isn't a change, so callback not called
+ if (i != 0) {
+ EXPECT_TRUE(callback.WasTriggered()) << " on " << i;
+ EXPECT_EQ(voltage, callback.GetLastValue()) << " on " << i;
+ }
+ }
+}
+
+TEST(AnalogInputSimTest, SetOverSampleBits) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{5};
+ AnalogInputSim sim(input);
+
+ IntCallback callback;
+ auto cb = sim.RegisterOversampleBitsCallback(callback.GetCallback(), false);
+
+ input.SetOversampleBits(3504);
+ EXPECT_EQ(3504, sim.GetOversampleBits());
+ EXPECT_EQ(3504, input.GetOversampleBits());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504, callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, SetAverageBits) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{5};
+ AnalogInputSim sim(input);
+
+ IntCallback callback;
+ auto cb = sim.RegisterAverageBitsCallback(callback.GetCallback(), false);
+
+ input.SetAverageBits(3504);
+ EXPECT_EQ(3504, sim.GetAverageBits());
+ EXPECT_EQ(3504, input.GetAverageBits());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504, callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, InitAccumulator) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{0};
+ AnalogInputSim sim(input);
+
+ BooleanCallback callback;
+ auto cb =
+ sim.RegisterAccumulatorInitializedCallback(callback.GetCallback(), false);
+
+ input.InitAccumulator();
+ input.ResetAccumulator();
+ EXPECT_TRUE(sim.GetAccumulatorInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, InitAccumulatorOnInvalidPort) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{5};
+ AnalogInputSim sim(input);
+
+ BooleanCallback callback;
+ auto cb =
+ sim.RegisterAccumulatorInitializedCallback(callback.GetCallback(), false);
+
+ EXPECT_THROW(input.InitAccumulator(), std::runtime_error);
+ EXPECT_FALSE(callback.WasTriggered());
+}
+
+TEST(AnalogInputSimTest, SetAccumulatorValue) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{0};
+ AnalogInputSim sim(input);
+
+ LongCallback callback;
+ auto cb = sim.RegisterAccumulatorValueCallback(callback.GetCallback(), false);
+
+ input.InitAccumulator();
+ sim.SetAccumulatorValue(3504191229);
+ EXPECT_EQ(3504191229, sim.GetAccumulatorValue());
+ EXPECT_EQ(3504191229, input.GetAccumulatorValue());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504191229, callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, SetAccumulatorCount) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{0};
+ AnalogInputSim sim(input);
+
+ LongCallback callback;
+ auto cb = sim.RegisterAccumulatorCountCallback(callback.GetCallback(), false);
+
+ input.InitAccumulator();
+ sim.SetAccumulatorCount(3504191229);
+ EXPECT_EQ(3504191229, sim.GetAccumulatorCount());
+ EXPECT_EQ(3504191229, input.GetAccumulatorCount());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504191229, callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, SetAccumulatorDeadband) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{0};
+ AnalogInputSim sim(input);
+
+ IntCallback callback;
+ auto cb =
+ sim.RegisterAccumulatorDeadbandCallback(callback.GetCallback(), false);
+
+ input.InitAccumulator();
+ input.SetAccumulatorDeadband(3504);
+ EXPECT_EQ(3504, sim.GetAccumulatorDeadband());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504, callback.GetLastValue());
+}
+
+TEST(AnalogInputSimTest, SetAccumulatorCenter) {
+ HAL_Initialize(500, 0);
+ AnalogInput input{0};
+ AnalogInputSim sim(input);
+
+ IntCallback callback;
+ auto cb =
+ sim.RegisterAccumulatorCenterCallback(callback.GetCallback(), false);
+
+ input.InitAccumulator();
+ input.SetAccumulatorCenter(3504);
+ EXPECT_EQ(3504, sim.GetAccumulatorCenter());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504, callback.GetLastValue());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/AnalogOutputSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AnalogOutputSimTest.cpp
new file mode 100644
index 0000000..630f2c9
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/AnalogOutputSimTest.cpp
@@ -0,0 +1,89 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/AnalogOutputSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/AnalogOutput.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(AnalogOutputSimTest, Initialize) {
+ HAL_Initialize(500, 0);
+
+ AnalogOutputSim outputSim{0};
+ EXPECT_FALSE(outputSim.GetInitialized());
+
+ BooleanCallback callback;
+
+ auto cb =
+ outputSim.RegisterInitializedCallback(callback.GetCallback(), false);
+ AnalogOutput output(0);
+ EXPECT_TRUE(outputSim.GetInitialized());
+
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(AnalogOutputSimTest, SetCallback) {
+ HAL_Initialize(500, 0);
+
+ AnalogOutput output{0};
+ output.SetVoltage(0.5);
+
+ AnalogOutputSim outputSim(output);
+
+ DoubleCallback voltageCallback;
+
+ auto cb =
+ outputSim.RegisterVoltageCallback(voltageCallback.GetCallback(), false);
+
+ EXPECT_FALSE(voltageCallback.WasTriggered());
+
+ for (int i = 0; i < 50; ++i) {
+ double voltage = i * .1;
+ voltageCallback.Reset();
+
+ output.SetVoltage(0);
+
+ EXPECT_EQ(0, output.GetVoltage());
+ EXPECT_EQ(0, outputSim.GetVoltage());
+
+ // 0 -> 0 isn't a change, so callback not called
+ if (i > 2) {
+ EXPECT_TRUE(voltageCallback.WasTriggered()) << " on " << i;
+ EXPECT_NEAR(voltageCallback.GetLastValue(), 0, 0.001) << " on " << i;
+ }
+
+ voltageCallback.Reset();
+
+ output.SetVoltage(voltage);
+
+ EXPECT_EQ(voltage, output.GetVoltage());
+ EXPECT_EQ(voltage, outputSim.GetVoltage());
+
+ // 0 -> 0 isn't a change, so callback not called
+ if (i != 0) {
+ EXPECT_TRUE(voltageCallback.WasTriggered());
+ EXPECT_NEAR(voltageCallback.GetLastValue(), voltage, 0.001);
+ }
+ }
+}
+
+TEST(AnalogOutputSimTest, Reset) {
+ HAL_Initialize(500, 0);
+
+ AnalogOutputSim outputSim{0};
+
+ AnalogOutput output{0};
+ output.SetVoltage(1.2);
+
+ outputSim.ResetData();
+ EXPECT_EQ(0, output.GetVoltage());
+ EXPECT_EQ(0, outputSim.GetVoltage());
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/AnalogTriggerSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AnalogTriggerSimTest.cpp
new file mode 100644
index 0000000..5e9e28e
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/AnalogTriggerSimTest.cpp
@@ -0,0 +1,55 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/AnalogTriggerSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/AnalogTrigger.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(AnalogTriggerSimTest, Initialization) {
+ HAL_Initialize(500, 0);
+
+ AnalogTriggerSim sim = AnalogTriggerSim::CreateForIndex(0);
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+
+ AnalogTrigger trigger{0};
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(AnalogTriggerSimTest, TriggerLowerBound) {
+ HAL_Initialize(500, 0);
+
+ AnalogTrigger trigger{0};
+ AnalogTriggerSim sim(trigger);
+
+ DoubleCallback lowerCallback;
+ DoubleCallback upperCallback;
+ auto lowerCb =
+ sim.RegisterTriggerLowerBoundCallback(lowerCallback.GetCallback(), false);
+ auto upperCb =
+ sim.RegisterTriggerUpperBoundCallback(upperCallback.GetCallback(), false);
+
+ trigger.SetLimitsVoltage(0.299, 1.91);
+
+ EXPECT_EQ(0.299, sim.GetTriggerLowerBound());
+ EXPECT_EQ(1.91, sim.GetTriggerUpperBound());
+
+ EXPECT_TRUE(lowerCallback.WasTriggered());
+ EXPECT_EQ(0.299, lowerCallback.GetLastValue());
+
+ EXPECT_TRUE(upperCallback.WasTriggered());
+ EXPECT_EQ(1.91, upperCallback.GetLastValue());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/CTREPCMSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/CTREPCMSimTest.cpp
new file mode 100644
index 0000000..a8f95da
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/CTREPCMSimTest.cpp
@@ -0,0 +1,150 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/CTREPCMSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DoubleSolenoid.h"
+#include "frc/PneumaticsControlModule.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(CTREPCMSimTest, InitializedCallback) {
+ CTREPCMSim sim;
+
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+
+ PneumaticsControlModule pcm;
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(CTREPCMSimTest, SolenoidOutput) {
+ PneumaticsControlModule pcm;
+ CTREPCMSim sim(pcm);
+ sim.ResetData();
+
+ DoubleSolenoid doubleSolenoid{0, frc::PneumaticsModuleType::CTREPCM, 3, 4};
+
+ BooleanCallback callback3;
+ BooleanCallback callback4;
+ auto cb3 =
+ sim.RegisterSolenoidOutputCallback(3, callback3.GetCallback(), false);
+ auto cb4 =
+ sim.RegisterSolenoidOutputCallback(4, callback4.GetCallback(), false);
+
+ callback3.Reset();
+ callback4.Reset();
+ doubleSolenoid.Set(DoubleSolenoid::kReverse);
+ EXPECT_FALSE(callback3.WasTriggered());
+ EXPECT_FALSE(callback3.GetLastValue());
+ EXPECT_TRUE(callback4.WasTriggered());
+ EXPECT_TRUE(callback4.GetLastValue());
+ EXPECT_FALSE(sim.GetSolenoidOutput(3));
+ EXPECT_TRUE(sim.GetSolenoidOutput(4));
+ EXPECT_EQ(0b00010000, pcm.GetSolenoids());
+ EXPECT_EQ(0b00010000, sim.GetAllSolenoidOutputs());
+
+ callback3.Reset();
+ callback4.Reset();
+ doubleSolenoid.Set(DoubleSolenoid::kForward);
+ EXPECT_TRUE(callback3.WasTriggered());
+ EXPECT_TRUE(callback3.GetLastValue());
+ EXPECT_TRUE(callback4.WasTriggered());
+ EXPECT_FALSE(callback4.GetLastValue());
+ EXPECT_TRUE(sim.GetSolenoidOutput(3));
+ EXPECT_FALSE(sim.GetSolenoidOutput(4));
+ EXPECT_EQ(0b00001000, pcm.GetSolenoids());
+ EXPECT_EQ(0b00001000, sim.GetAllSolenoidOutputs());
+
+ callback3.Reset();
+ callback4.Reset();
+ doubleSolenoid.Set(DoubleSolenoid::kOff);
+ EXPECT_TRUE(callback3.WasTriggered());
+ EXPECT_FALSE(callback3.GetLastValue());
+ EXPECT_FALSE(callback4.WasTriggered());
+ EXPECT_FALSE(callback4.GetLastValue());
+ EXPECT_FALSE(sim.GetSolenoidOutput(3));
+ EXPECT_FALSE(sim.GetSolenoidOutput(4));
+ EXPECT_EQ(0b00000000, pcm.GetSolenoids());
+ EXPECT_EQ(0b00000000, sim.GetAllSolenoidOutputs());
+}
+
+TEST(CTREPCMSimTest, SetCompressorOn) {
+ PneumaticsControlModule pcm;
+ CTREPCMSim sim(pcm);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterCompressorOnCallback(callback.GetCallback(), false);
+
+ EXPECT_FALSE(pcm.GetCompressor());
+ EXPECT_FALSE(pcm.GetCompressor());
+ sim.SetCompressorOn(true);
+ EXPECT_TRUE(sim.GetCompressorOn());
+ EXPECT_TRUE(pcm.GetCompressor());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(CTREPCMSimTest, SetClosedLoopEnabled) {
+ PneumaticsControlModule pcm;
+ CTREPCMSim sim(pcm);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb =
+ sim.RegisterClosedLoopEnabledCallback(callback.GetCallback(), false);
+
+ pcm.SetClosedLoopControl(false);
+ EXPECT_FALSE(pcm.GetClosedLoopControl());
+
+ pcm.SetClosedLoopControl(true);
+ EXPECT_TRUE(sim.GetClosedLoopEnabled());
+ EXPECT_TRUE(pcm.GetClosedLoopControl());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(CTREPCMSimTest, SetPressureSwitchEnabled) {
+ PneumaticsControlModule pcm;
+ CTREPCMSim sim(pcm);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterPressureSwitchCallback(callback.GetCallback(), false);
+
+ EXPECT_FALSE(pcm.GetPressureSwitch());
+
+ sim.SetPressureSwitch(true);
+ EXPECT_TRUE(sim.GetPressureSwitch());
+ EXPECT_TRUE(pcm.GetPressureSwitch());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(CTREPCMSimTest, SetCompressorCurrent) {
+ PneumaticsControlModule pcm;
+ CTREPCMSim sim(pcm);
+ sim.ResetData();
+
+ DoubleCallback callback;
+ auto cb =
+ sim.RegisterCompressorCurrentCallback(callback.GetCallback(), false);
+
+ sim.SetCompressorCurrent(35.04);
+ EXPECT_EQ(35.04, sim.GetCompressorCurrent());
+ EXPECT_EQ(35.04, pcm.GetCompressorCurrent());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(35.04, callback.GetLastValue());
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/DIOSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DIOSimTest.cpp
new file mode 100644
index 0000000..338d24e
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/DIOSimTest.cpp
@@ -0,0 +1,80 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/DIOSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DigitalInput.h"
+#include "frc/DigitalOutput.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(DIOSimTest, Initialization) {
+ HAL_Initialize(500, 0);
+ DIOSim sim{2};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback initializeCallback;
+ BooleanCallback isInputCallback;
+
+ auto initializeCb =
+ sim.RegisterInitializedCallback(initializeCallback.GetCallback(), false);
+ auto inputCb =
+ sim.RegisterIsInputCallback(isInputCallback.GetCallback(), false);
+
+ DigitalOutput output(2);
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(initializeCallback.WasTriggered());
+ EXPECT_TRUE(initializeCallback.GetLastValue());
+ EXPECT_FALSE(sim.GetIsInput());
+ EXPECT_TRUE(isInputCallback.WasTriggered());
+ EXPECT_FALSE(isInputCallback.GetLastValue());
+
+ initializeCallback.Reset();
+ sim.SetInitialized(false);
+ EXPECT_TRUE(initializeCallback.WasTriggered());
+ EXPECT_FALSE(initializeCallback.GetLastValue());
+}
+
+TEST(DIOSimTest, Input) {
+ HAL_Initialize(500, 0);
+
+ DigitalInput input{0};
+ DIOSim sim(input);
+ EXPECT_TRUE(sim.GetIsInput());
+
+ BooleanCallback valueCallback;
+
+ auto cb = sim.RegisterValueCallback(valueCallback.GetCallback(), false);
+ EXPECT_TRUE(input.Get());
+ EXPECT_TRUE(sim.GetValue());
+
+ EXPECT_FALSE(valueCallback.WasTriggered());
+ sim.SetValue(false);
+ EXPECT_TRUE(valueCallback.WasTriggered());
+ EXPECT_FALSE(valueCallback.GetLastValue());
+}
+
+TEST(DIOSimTest, Output) {
+ HAL_Initialize(500, 0);
+ DigitalOutput output{0};
+ DIOSim sim(output);
+ EXPECT_FALSE(sim.GetIsInput());
+
+ BooleanCallback valueCallback;
+
+ auto cb = sim.RegisterValueCallback(valueCallback.GetCallback(), false);
+ EXPECT_FALSE(output.Get());
+ EXPECT_FALSE(sim.GetValue());
+
+ EXPECT_FALSE(valueCallback.WasTriggered());
+ output.Set(true);
+ EXPECT_TRUE(valueCallback.WasTriggered());
+ EXPECT_TRUE(valueCallback.GetLastValue());
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/DifferentialDriveSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DifferentialDriveSimTest.cpp
index f09344e..eabbecb 100644
--- a/wpilibc/src/test/native/cpp/simulation/DifferentialDriveSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/DifferentialDriveSimTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <units/current.h>
#include <units/math.h>
@@ -13,29 +10,30 @@
#include "frc/controller/RamseteController.h"
#include "frc/kinematics/DifferentialDriveKinematics.h"
#include "frc/simulation/DifferentialDrivetrainSim.h"
-#include "frc/system/RungeKutta.h"
+#include "frc/system/NumericalIntegration.h"
#include "frc/system/plant/DCMotor.h"
#include "frc/system/plant/LinearSystemId.h"
#include "frc/trajectory/TrajectoryGenerator.h"
#include "frc/trajectory/constraint/DifferentialDriveKinematicsConstraint.h"
#include "gtest/gtest.h"
-TEST(DifferentialDriveSim, Convergence) {
+TEST(DifferentialDriveSimTest, Convergence) {
auto motor = frc::DCMotor::NEO(2);
auto plant = frc::LinearSystemId::DrivetrainVelocitySystem(
motor, 50_kg, 2_in, 12_in, 0.5_kg_sq_m, 1.0);
frc::DifferentialDriveKinematics kinematics{24_in};
- frc::sim::DifferentialDrivetrainSim sim{plant, 24_in, motor, 1.0, 2_in};
+ frc::sim::DifferentialDrivetrainSim sim{
+ plant, 24_in, motor,
+ 1.0, 2_in, {0.001, 0.001, 0.0001, 0.1, 0.1, 0.005, 0.005}};
frc::LinearPlantInversionFeedforward feedforward{plant, 20_ms};
frc::RamseteController ramsete;
- feedforward.Reset(frc::MakeMatrix<2, 1>(0.0, 0.0));
+ feedforward.Reset(Eigen::Vector<double, 2>{0.0, 0.0});
// Ground truth.
- Eigen::Matrix<double, 7, 1> groundTruthX =
- Eigen::Matrix<double, 7, 1>::Zero();
+ Eigen::Vector<double, 7> groundTruthX = Eigen::Vector<double, 7>::Zero();
frc::TrajectoryConfig config{1_mps, 1_mps_sq};
config.AddConstraint(
@@ -44,32 +42,35 @@
auto trajectory = frc::TrajectoryGenerator::GenerateTrajectory(
frc::Pose2d(), {}, frc::Pose2d(2_m, 2_m, 0_rad), config);
- for (double t = 0; t < trajectory.TotalTime().to<double>(); t += 0.02) {
+ // NOLINTNEXTLINE
+ for (double t = 0; t < trajectory.TotalTime().value(); t += 0.02) {
auto state = trajectory.Sample(20_ms);
auto ramseteOut = ramsete.Calculate(sim.GetPose(), state);
auto [l, r] = kinematics.ToWheelSpeeds(ramseteOut);
- auto voltages = feedforward.Calculate(
- frc::MakeMatrix<2, 1>(l.to<double>(), r.to<double>()));
+ auto voltages =
+ feedforward.Calculate(Eigen::Vector<double, 2>{l.value(), r.value()});
// Sim periodic code.
sim.SetInputs(units::volt_t(voltages(0, 0)), units::volt_t(voltages(1, 0)));
sim.Update(20_ms);
// Update ground truth.
- groundTruthX = frc::RungeKutta(
- [&sim](const auto& x, const auto& u) -> Eigen::Matrix<double, 7, 1> {
+ groundTruthX = frc::RK4(
+ [&sim](const auto& x, const auto& u) -> Eigen::Vector<double, 7> {
return sim.Dynamics(x, u);
},
groundTruthX, voltages, 20_ms);
}
- EXPECT_NEAR(groundTruthX(0, 0), sim.GetState(0), 1E-6);
- EXPECT_NEAR(groundTruthX(1, 0), sim.GetState(1), 1E-6);
- EXPECT_NEAR(groundTruthX(2, 0), sim.GetState(2), 1E-6);
+ // 2 inch tolerance is OK since our ground truth is an approximation of the
+ // ODE solution using RK4 anyway
+ EXPECT_NEAR(groundTruthX(0, 0), sim.GetPose().X().value(), 0.05);
+ EXPECT_NEAR(groundTruthX(1, 0), sim.GetPose().Y().value(), 0.05);
+ EXPECT_NEAR(groundTruthX(2, 0), sim.GetHeading().Radians().value(), 0.01);
}
-TEST(DifferentialDriveSim, Current) {
+TEST(DifferentialDriveSimTest, Current) {
auto motor = frc::DCMotor::NEO(2);
auto plant = frc::LinearSystemId::DrivetrainVelocitySystem(
motor, 50_kg, 2_in, 12_in, 0.5_kg_sq_m, 1.0);
@@ -96,7 +97,7 @@
EXPECT_TRUE(sim.GetCurrentDraw() > 0_A);
}
-TEST(DifferentialDriveSim, ModelStability) {
+TEST(DifferentialDriveSimTest, ModelStability) {
auto motor = frc::DCMotor::NEO(2);
auto plant = frc::LinearSystemId::DrivetrainVelocitySystem(
motor, 50_kg, 2_in, 12_in, 2_kg_sq_m, 5.0);
diff --git a/wpilibc/src/test/native/cpp/simulation/DigitalPWMSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DigitalPWMSimTest.cpp
new file mode 100644
index 0000000..fd62edc
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/DigitalPWMSimTest.cpp
@@ -0,0 +1,57 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/DigitalPWMSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DigitalOutput.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(DigitalPWMSimTest, Initialize) {
+ HAL_Initialize(500, 0);
+
+ DigitalOutput output{0};
+ DigitalPWMSim sim(output);
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback initializeCallback;
+ auto initCb =
+ sim.RegisterInitializedCallback(initializeCallback.GetCallback(), false);
+
+ DoubleCallback dutyCycleCallback;
+ auto dutyCycleCB =
+ sim.RegisterDutyCycleCallback(dutyCycleCallback.GetCallback(), false);
+
+ constexpr double kTestDutyCycle = 0.191;
+ output.EnablePWM(kTestDutyCycle);
+
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(initializeCallback.WasTriggered());
+ EXPECT_TRUE(initializeCallback.GetLastValue());
+
+ EXPECT_EQ(kTestDutyCycle, sim.GetDutyCycle());
+ EXPECT_TRUE(dutyCycleCallback.WasTriggered());
+ EXPECT_EQ(kTestDutyCycle, dutyCycleCallback.GetLastValue());
+}
+
+TEST(DigitalPWMSimTest, SetPin) {
+ HAL_Initialize(500, 0);
+
+ DigitalOutput output{2};
+ DigitalPWMSim sim(output);
+
+ IntCallback callback;
+ auto cb = sim.RegisterPinCallback(callback.GetCallback(), false);
+
+ sim.SetPin(191);
+ EXPECT_EQ(191, sim.GetPin());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(191, callback.GetLastValue());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp
new file mode 100644
index 0000000..d01ca27
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/DriverStationSimTest.cpp
@@ -0,0 +1,238 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <string>
+#include <tuple>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DriverStation.h"
+#include "frc/Joystick.h"
+#include "frc/RobotState.h"
+#include "frc/simulation/DriverStationSim.h"
+#include "frc/simulation/SimHooks.h"
+#include "gtest/gtest.h"
+
+using namespace frc;
+using namespace frc::sim;
+
+TEST(DriverStationTest, Enabled) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ EXPECT_FALSE(DriverStation::IsEnabled());
+ BooleanCallback callback;
+ auto cb =
+ DriverStationSim::RegisterEnabledCallback(callback.GetCallback(), false);
+ DriverStationSim::SetEnabled(true);
+ DriverStationSim::NotifyNewData();
+ EXPECT_TRUE(DriverStationSim::GetEnabled());
+ EXPECT_TRUE(DriverStation::IsEnabled());
+ EXPECT_TRUE(RobotState::IsEnabled());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(DriverStationTest, AutonomousMode) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ EXPECT_FALSE(DriverStation::IsAutonomous());
+ BooleanCallback callback;
+ auto cb = DriverStationSim::RegisterAutonomousCallback(callback.GetCallback(),
+ false);
+ DriverStationSim::SetAutonomous(true);
+ DriverStationSim::NotifyNewData();
+ EXPECT_TRUE(DriverStationSim::GetAutonomous());
+ EXPECT_TRUE(DriverStation::IsAutonomous());
+ EXPECT_TRUE(RobotState::IsAutonomous());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(DriverStationTest, Mode) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ EXPECT_FALSE(DriverStation::IsTest());
+ BooleanCallback callback;
+ auto cb =
+ DriverStationSim::RegisterTestCallback(callback.GetCallback(), false);
+ DriverStationSim::SetTest(true);
+ DriverStationSim::NotifyNewData();
+ EXPECT_TRUE(DriverStationSim::GetTest());
+ EXPECT_TRUE(DriverStation::IsTest());
+ EXPECT_TRUE(RobotState::IsTest());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(DriverStationTest, Estop) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ EXPECT_FALSE(DriverStation::IsEStopped());
+ BooleanCallback callback;
+ auto cb =
+ DriverStationSim::RegisterEStopCallback(callback.GetCallback(), false);
+ DriverStationSim::SetEStop(true);
+ DriverStationSim::NotifyNewData();
+ EXPECT_TRUE(DriverStationSim::GetEStop());
+ EXPECT_TRUE(DriverStation::IsEStopped());
+ EXPECT_TRUE(RobotState::IsEStopped());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(DriverStationTest, FmsAttached) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ EXPECT_FALSE(DriverStation::IsFMSAttached());
+ BooleanCallback callback;
+ auto cb = DriverStationSim::RegisterFmsAttachedCallback(
+ callback.GetCallback(), false);
+ DriverStationSim::SetFmsAttached(true);
+ DriverStationSim::NotifyNewData();
+ EXPECT_TRUE(DriverStationSim::GetFmsAttached());
+ EXPECT_TRUE(DriverStation::IsFMSAttached());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(DriverStationTest, DsAttached) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ DriverStationSim::NotifyNewData();
+ EXPECT_TRUE(DriverStation::IsDSAttached());
+
+ BooleanCallback callback;
+ auto cb = DriverStationSim::RegisterDsAttachedCallback(callback.GetCallback(),
+ false);
+ DriverStationSim::SetDsAttached(false);
+ DriverStationSim::NotifyNewData();
+ EXPECT_FALSE(DriverStationSim::GetDsAttached());
+ EXPECT_FALSE(DriverStation::IsDSAttached());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(DriverStationTest, AllianceStationId) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ EnumCallback callback;
+
+ HAL_AllianceStationID allianceStation = HAL_AllianceStationID_kBlue2;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+
+ auto cb = DriverStationSim::RegisterAllianceStationIdCallback(
+ callback.GetCallback(), false);
+ // B1
+ allianceStation = HAL_AllianceStationID_kBlue1;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+ EXPECT_EQ(allianceStation, DriverStationSim::GetAllianceStationId());
+ EXPECT_EQ(DriverStation::kBlue, DriverStation::GetAlliance());
+ EXPECT_EQ(1, DriverStation::GetLocation());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(allianceStation, callback.GetLastValue());
+
+ // B2
+ allianceStation = HAL_AllianceStationID_kBlue2;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+ EXPECT_EQ(allianceStation, DriverStationSim::GetAllianceStationId());
+ EXPECT_EQ(DriverStation::kBlue, DriverStation::GetAlliance());
+ EXPECT_EQ(2, DriverStation::GetLocation());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(allianceStation, callback.GetLastValue());
+
+ // B3
+ allianceStation = HAL_AllianceStationID_kBlue3;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+ EXPECT_EQ(allianceStation, DriverStationSim::GetAllianceStationId());
+ EXPECT_EQ(DriverStation::kBlue, DriverStation::GetAlliance());
+ EXPECT_EQ(3, DriverStation::GetLocation());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(allianceStation, callback.GetLastValue());
+
+ // R1
+ allianceStation = HAL_AllianceStationID_kRed1;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+ EXPECT_EQ(allianceStation, DriverStationSim::GetAllianceStationId());
+ EXPECT_EQ(DriverStation::kRed, DriverStation::GetAlliance());
+ EXPECT_EQ(1, DriverStation::GetLocation());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(allianceStation, callback.GetLastValue());
+
+ // R2
+ allianceStation = HAL_AllianceStationID_kRed2;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+ EXPECT_EQ(allianceStation, DriverStationSim::GetAllianceStationId());
+ EXPECT_EQ(DriverStation::kRed, DriverStation::GetAlliance());
+ EXPECT_EQ(2, DriverStation::GetLocation());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(allianceStation, callback.GetLastValue());
+
+ // R3
+ allianceStation = HAL_AllianceStationID_kRed3;
+ DriverStationSim::SetAllianceStationId(allianceStation);
+ EXPECT_EQ(allianceStation, DriverStationSim::GetAllianceStationId());
+ EXPECT_EQ(DriverStation::kRed, DriverStation::GetAlliance());
+ EXPECT_EQ(3, DriverStation::GetLocation());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(allianceStation, callback.GetLastValue());
+}
+
+TEST(DriverStationTest, ReplayNumber) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ DriverStationSim::SetReplayNumber(4);
+ DriverStationSim::NotifyNewData();
+ EXPECT_EQ(4, DriverStation::GetReplayNumber());
+}
+
+TEST(DriverStationTest, MatchNumber) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ DriverStationSim::SetMatchNumber(3);
+ DriverStationSim::NotifyNewData();
+ EXPECT_EQ(3, DriverStation::GetMatchNumber());
+}
+
+TEST(DriverStationTest, MatchTime) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ DoubleCallback callback;
+ auto cb = DriverStationSim::RegisterMatchTimeCallback(callback.GetCallback(),
+ false);
+ constexpr double kTestTime = 19.174;
+ DriverStationSim::SetMatchTime(kTestTime);
+ EXPECT_EQ(kTestTime, DriverStationSim::GetMatchTime());
+ EXPECT_EQ(kTestTime, DriverStation::GetMatchTime());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestTime, callback.GetLastValue());
+}
+
+TEST(DriverStationTest, SetGameSpecificMessage) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ constexpr auto message = "Hello World!";
+ DriverStationSim::SetGameSpecificMessage(message);
+ DriverStationSim::NotifyNewData();
+ EXPECT_EQ(message, DriverStation::GetGameSpecificMessage());
+}
+
+TEST(DriverStationTest, SetEventName) {
+ HAL_Initialize(500, 0);
+ DriverStationSim::ResetData();
+
+ constexpr auto message = "The Best Event";
+ DriverStationSim::SetEventName(message);
+ DriverStationSim::NotifyNewData();
+ EXPECT_EQ(message, DriverStation::GetEventName());
+}
diff --git a/wpilibc/src/test/native/cpp/simulation/DutyCycleEncoderSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DutyCycleEncoderSimTest.cpp
new file mode 100644
index 0000000..8249499
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/DutyCycleEncoderSimTest.cpp
@@ -0,0 +1,35 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/DutyCycleEncoderSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DutyCycleEncoder.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(DutyCycleEncoderSimTest, Set) {
+ HAL_Initialize(500, 0);
+
+ DutyCycleEncoder enc{0};
+ DutyCycleEncoderSim sim(enc);
+
+ constexpr units::turn_t kTestValue{5.67};
+ sim.Set(kTestValue);
+ EXPECT_EQ(kTestValue, enc.Get());
+}
+
+TEST(DutyCycleEncoderSimTest, SetDistance) {
+ HAL_Initialize(500, 0);
+
+ DutyCycleEncoder enc{0};
+ DutyCycleEncoderSim sim(enc);
+ sim.SetDistance(19.1);
+ EXPECT_EQ(19.1, enc.GetDistance());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/DutyCycleSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/DutyCycleSimTest.cpp
new file mode 100644
index 0000000..56e0592
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/DutyCycleSimTest.cpp
@@ -0,0 +1,70 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/DutyCycleSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DigitalInput.h"
+#include "frc/DutyCycle.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(DutyCycleSimTest, Initialization) {
+ HAL_Initialize(500, 0);
+ DutyCycleSim sim = DutyCycleSim::CreateForIndex(0);
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+
+ DigitalInput di{2};
+ DutyCycle dc{&di};
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ callback.Reset();
+ sim.SetInitialized(false);
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(DutyCycleSimTest, SetFrequency) {
+ HAL_Initialize(500, 0);
+
+ DigitalInput di{2};
+ DutyCycle dc{di};
+ DutyCycleSim sim(dc);
+
+ IntCallback callback;
+ auto cb = sim.RegisterFrequencyCallback(callback.GetCallback(), false);
+
+ sim.SetFrequency(191);
+ EXPECT_EQ(191, sim.GetFrequency());
+ EXPECT_EQ(191, dc.GetFrequency());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(191, callback.GetLastValue());
+}
+
+TEST(DutyCycleSimTest, SetOutput) {
+ HAL_Initialize(500, 0);
+
+ DigitalInput di{2};
+ DutyCycle dc{di};
+ DutyCycleSim sim(dc);
+
+ DoubleCallback callback;
+ auto cb = sim.RegisterOutputCallback(callback.GetCallback(), false);
+
+ sim.SetOutput(229.174);
+ EXPECT_EQ(229.174, sim.GetOutput());
+ EXPECT_EQ(229.174, dc.GetOutput());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(229.174, callback.GetLastValue());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp
index 05b0dc9..bfc50e1 100644
--- a/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/ElevatorSimTest.cpp
@@ -1,26 +1,23 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <iostream>
#include <units/time.h>
#include "frc/Encoder.h"
-#include "frc/PWMVictorSPX.h"
#include "frc/RobotController.h"
-#include "frc/StateSpaceUtil.h"
#include "frc/controller/PIDController.h"
+#include "frc/motorcontrol/PWMVictorSPX.h"
#include "frc/simulation/ElevatorSim.h"
#include "frc/simulation/EncoderSim.h"
+#include "frc/system/NumericalIntegration.h"
#include "frc/system/plant/DCMotor.h"
#include "frc/system/plant/LinearSystemId.h"
#include "gtest/gtest.h"
-TEST(ElevatorSim, StateSpaceSim) {
+TEST(ElevatorSimTest, StateSpaceSim) {
frc::sim::ElevatorSim sim(frc::DCMotor::Vex775Pro(4), 14.67, 8_kg,
units::meter_t(0.75 * 25.4 / 1000.0), 0_m, 3_m,
{0.01});
@@ -35,8 +32,8 @@
auto nextVoltage = controller.Calculate(encoderSim.GetDistance());
motor.Set(nextVoltage / frc::RobotController::GetInputVoltage());
- auto u = frc::MakeMatrix<1, 1>(motor.Get() *
- frc::RobotController::GetInputVoltage());
+ Eigen::Vector<double, 1> u{motor.Get() *
+ frc::RobotController::GetInputVoltage()};
sim.SetInput(u);
sim.Update(20_ms);
@@ -44,15 +41,15 @@
encoderSim.SetDistance(y(0));
}
- EXPECT_NEAR(controller.GetSetpoint(), sim.GetPosition().to<double>(), 0.2);
+ EXPECT_NEAR(controller.GetSetpoint(), sim.GetPosition().value(), 0.2);
}
-TEST(ElevatorSim, MinMax) {
+TEST(ElevatorSimTest, MinMax) {
frc::sim::ElevatorSim sim(frc::DCMotor::Vex775Pro(4), 14.67, 8_kg,
units::meter_t(0.75 * 25.4 / 1000.0), 0_m, 1_m,
{0.01});
for (size_t i = 0; i < 100; ++i) {
- sim.SetInput(frc::MakeMatrix<1, 1>(0.0));
+ sim.SetInput(Eigen::Vector<double, 1>{0.0});
sim.Update(20_ms);
auto height = sim.GetPosition();
@@ -60,10 +57,35 @@
}
for (size_t i = 0; i < 100; ++i) {
- sim.SetInput(frc::MakeMatrix<1, 1>(12.0));
+ sim.SetInput(Eigen::Vector<double, 1>{12.0});
sim.Update(20_ms);
auto height = sim.GetPosition();
EXPECT_TRUE(height < 1.05_m);
}
}
+
+TEST(ElevatorSimTest, Stability) {
+ static constexpr double kElevatorGearing = 100.0;
+ static constexpr units::meter_t kElevatorDrumRadius = 0.5_in;
+ static constexpr units::kilogram_t kCarriageMass = 4.0_kg;
+ frc::DCMotor m_elevatorGearbox = frc::DCMotor::Vex775Pro(4);
+
+ frc::LinearSystem<2, 1, 1> system = frc::LinearSystemId::ElevatorSystem(
+ m_elevatorGearbox, kCarriageMass, kElevatorDrumRadius, kElevatorGearing);
+
+ Eigen::Vector<double, 2> x0{0.0, 0.0};
+ Eigen::Vector<double, 1> u0{12.0};
+
+ Eigen::Vector<double, 2> x1{0.0, 0.0};
+ for (size_t i = 0; i < 50; i++) {
+ x1 = frc::RKDP(
+ [&](const Eigen::Vector<double, 2>& x,
+ const Eigen::Vector<double, 1>& u) -> Eigen::Vector<double, 2> {
+ return system.A() * x + system.B() * u;
+ },
+ x1, u0, 0.020_s);
+ }
+
+ EXPECT_NEAR(x1(0), system.CalculateX(x0, u0, 1_s)(0), 0.1);
+}
diff --git a/wpilibc/src/test/native/cpp/simulation/EncoderSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/EncoderSimTest.cpp
new file mode 100644
index 0000000..be13ca5
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/EncoderSimTest.cpp
@@ -0,0 +1,230 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/EncoderSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/Encoder.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+namespace {
+constexpr double kDefaultDistancePerPulse = .0005;
+} // namespace
+
+TEST(EncoderSimTest, Initialize) {
+ HAL_Initialize(500, 0);
+
+ EncoderSim sim = EncoderSim::CreateForIndex(0);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+
+ Encoder encoder(0, 1);
+
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, Rate) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ sim.SetRate(1.91);
+ EXPECT_EQ(1.91, sim.GetRate());
+}
+
+TEST(EncoderSimTest, Count) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ IntCallback callback;
+ auto cb = sim.RegisterCountCallback(callback.GetCallback(), false);
+ sim.SetCount(3504);
+ EXPECT_EQ(3504, sim.GetCount());
+
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504, encoder.Get());
+ EXPECT_EQ(3504, callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, Distance) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ sim.SetDistance(229.174);
+ EXPECT_EQ(229.174, sim.GetDistance());
+ EXPECT_EQ(229.174, encoder.GetDistance());
+}
+
+TEST(EncoderSimTest, Period) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ DoubleCallback callback;
+ auto cb = sim.RegisterPeriodCallback(callback.GetCallback(), false);
+ sim.SetPeriod(123.456);
+ EXPECT_EQ(123.456, sim.GetPeriod());
+ EXPECT_EQ(123.456, encoder.GetPeriod().value());
+ EXPECT_EQ(kDefaultDistancePerPulse / 123.456, encoder.GetRate());
+
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(123.456, callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, SetMaxPeriod) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ DoubleCallback callback;
+ auto cb = sim.RegisterMaxPeriodCallback(callback.GetCallback(), false);
+
+ encoder.SetMaxPeriod(units::second_t{123.456});
+ EXPECT_EQ(123.456, sim.GetMaxPeriod());
+
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(123.456, callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, SetDirection) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterDirectionCallback(callback.GetCallback(), false);
+
+ sim.SetDirection(true);
+ EXPECT_TRUE(sim.GetDirection());
+ EXPECT_TRUE(encoder.GetDirection());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ sim.SetDirection(false);
+ EXPECT_FALSE(sim.GetDirection());
+ EXPECT_FALSE(encoder.GetDirection());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, SetReverseDirection) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterReverseDirectionCallback(callback.GetCallback(), false);
+
+ encoder.SetReverseDirection(true);
+ EXPECT_TRUE(sim.GetReverseDirection());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ encoder.SetReverseDirection(false);
+ EXPECT_FALSE(sim.GetReverseDirection());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, SetSamplesToAverage) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ IntCallback callback;
+ auto cb = sim.RegisterSamplesToAverageCallback(callback.GetCallback(), false);
+
+ encoder.SetSamplesToAverage(57);
+ EXPECT_EQ(57, sim.GetSamplesToAverage());
+ EXPECT_EQ(57, encoder.GetSamplesToAverage());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(57, callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, SetDistancePerPulse) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ DoubleCallback callback;
+ auto cb = sim.RegisterDistancePerPulseCallback(callback.GetCallback(), false);
+
+ encoder.SetDistancePerPulse(.03405);
+ EXPECT_EQ(.03405, sim.GetDistancePerPulse());
+ EXPECT_EQ(.03405, encoder.GetDistancePerPulse());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(.03405, callback.GetLastValue());
+}
+
+TEST(EncoderSimTest, Reset) {
+ HAL_Initialize(500, 0);
+
+ Encoder encoder(0, 1);
+ EncoderSim sim(encoder);
+ sim.ResetData();
+
+ encoder.SetDistancePerPulse(kDefaultDistancePerPulse);
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterResetCallback(callback.GetCallback(), false);
+
+ sim.SetCount(3504);
+ sim.SetDistance(229.191);
+
+ encoder.Reset();
+ EXPECT_TRUE(sim.GetReset());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ EXPECT_EQ(0, sim.GetCount());
+ EXPECT_EQ(0, encoder.Get());
+ EXPECT_EQ(0, sim.GetDistance());
+ EXPECT_EQ(0, encoder.GetDistance());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/PDPSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/PDPSimTest.cpp
new file mode 100644
index 0000000..78711b1
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/PDPSimTest.cpp
@@ -0,0 +1,82 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/PowerDistributionSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/PowerDistribution.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(PowerDistributionSimTest, Initialize) {
+ HAL_Initialize(500, 0);
+ PowerDistributionSim sim{2};
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+ PowerDistribution pdp(2, frc::PowerDistribution::ModuleType::kCTRE);
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ callback.Reset();
+ sim.SetInitialized(false);
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(PowerDistributionSimTest, SetTemperature) {
+ HAL_Initialize(500, 0);
+ PowerDistribution pdp{2, frc::PowerDistribution::ModuleType::kCTRE};
+ PowerDistributionSim sim(pdp);
+
+ DoubleCallback callback;
+ auto cb = sim.RegisterTemperatureCallback(callback.GetCallback(), false);
+
+ sim.SetTemperature(35.04);
+ EXPECT_EQ(35.04, sim.GetTemperature());
+ EXPECT_EQ(35.04, pdp.GetTemperature());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(PowerDistributionSimTest, SetVoltage) {
+ HAL_Initialize(500, 0);
+ PowerDistribution pdp{2, frc::PowerDistribution::ModuleType::kCTRE};
+ PowerDistributionSim sim(pdp);
+
+ DoubleCallback callback;
+ auto cb = sim.RegisterVoltageCallback(callback.GetCallback(), false);
+
+ sim.SetVoltage(35.04);
+ EXPECT_EQ(35.04, sim.GetVoltage());
+ EXPECT_EQ(35.04, pdp.GetVoltage());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(PowerDistributionSimTest, SetCurrent) {
+ HAL_Initialize(500, 0);
+ PowerDistribution pdp{2, frc::PowerDistribution::ModuleType::kCTRE};
+ PowerDistributionSim sim(pdp);
+
+ for (int channel = 0; channel < HAL_GetNumCTREPDPChannels(); ++channel) {
+ DoubleCallback callback;
+ auto cb =
+ sim.RegisterCurrentCallback(channel, callback.GetCallback(), false);
+
+ const double kTestCurrent = 35.04 + channel;
+ sim.SetCurrent(channel, kTestCurrent);
+ EXPECT_EQ(kTestCurrent, sim.GetCurrent(channel));
+ EXPECT_EQ(kTestCurrent, pdp.GetCurrent(channel));
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+ }
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/PWMSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/PWMSimTest.cpp
new file mode 100644
index 0000000..0df3590
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/PWMSimTest.cpp
@@ -0,0 +1,120 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/PWMSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/PWM.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(PWMSimTest, Initialize) {
+ HAL_Initialize(500, 0);
+
+ PWMSim sim{0};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+ PWM pwm{0};
+ EXPECT_TRUE(sim.GetInitialized());
+}
+
+TEST(PWMSimTest, SetRawValue) {
+ HAL_Initialize(500, 0);
+
+ PWMSim sim{0};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ IntCallback callback;
+
+ auto cb = sim.RegisterRawValueCallback(callback.GetCallback(), false);
+ PWM pwm{0};
+ sim.SetRawValue(229);
+ EXPECT_EQ(229, sim.GetRawValue());
+ EXPECT_EQ(229, pwm.GetRaw());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(229, callback.GetLastValue());
+}
+
+TEST(PWMSimTest, SetSpeed) {
+ HAL_Initialize(500, 0);
+
+ PWMSim sim{0};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ DoubleCallback callback;
+
+ auto cb = sim.RegisterSpeedCallback(callback.GetCallback(), false);
+ PWM pwm{0};
+ constexpr double kTestValue = 0.3504;
+ pwm.SetSpeed(kTestValue);
+
+ EXPECT_EQ(kTestValue, sim.GetSpeed());
+ EXPECT_EQ(kTestValue, pwm.GetSpeed());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestValue, callback.GetLastValue());
+}
+
+TEST(PWMSimTest, SetPosition) {
+ HAL_Initialize(500, 0);
+
+ PWMSim sim{0};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ DoubleCallback callback;
+
+ auto cb = sim.RegisterPositionCallback(callback.GetCallback(), false);
+ PWM pwm{0};
+ constexpr double kTestValue = 0.3504;
+ pwm.SetPosition(kTestValue);
+
+ EXPECT_EQ(kTestValue, sim.GetPosition());
+ EXPECT_EQ(kTestValue, pwm.GetPosition());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(kTestValue, callback.GetLastValue());
+}
+
+TEST(PWMSimTest, SetPeriodScale) {
+ HAL_Initialize(500, 0);
+
+ PWMSim sim{0};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ IntCallback callback;
+
+ auto cb = sim.RegisterPeriodScaleCallback(callback.GetCallback(), false);
+ PWM pwm{0};
+ sim.SetPeriodScale(3504);
+ EXPECT_EQ(3504, sim.GetPeriodScale());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(3504, callback.GetLastValue());
+}
+
+TEST(PWMSimTest, SetZeroLatch) {
+ HAL_Initialize(500, 0);
+
+ PWMSim sim{0};
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+
+ auto cb = sim.RegisterZeroLatchCallback(callback.GetCallback(), false);
+ PWM pwm{0};
+ pwm.SetZeroLatch();
+
+ EXPECT_TRUE(callback.WasTriggered());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/REVPHSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/REVPHSimTest.cpp
new file mode 100644
index 0000000..7786b29
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/REVPHSimTest.cpp
@@ -0,0 +1,150 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/REVPHSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/DoubleSolenoid.h"
+#include "frc/PneumaticHub.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(REVPHSimTest, InitializedCallback) {
+ REVPHSim sim;
+
+ sim.ResetData();
+ EXPECT_FALSE(sim.GetInitialized());
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterInitializedCallback(callback.GetCallback(), false);
+
+ PneumaticHub ph;
+ EXPECT_TRUE(sim.GetInitialized());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(REVPHSimTest, SolenoidOutput) {
+ PneumaticHub ph;
+ REVPHSim sim(ph);
+ sim.ResetData();
+
+ DoubleSolenoid doubleSolenoid{1, frc::PneumaticsModuleType::REVPH, 3, 4};
+
+ BooleanCallback callback3;
+ BooleanCallback callback4;
+ auto cb3 =
+ sim.RegisterSolenoidOutputCallback(3, callback3.GetCallback(), false);
+ auto cb4 =
+ sim.RegisterSolenoidOutputCallback(4, callback4.GetCallback(), false);
+
+ callback3.Reset();
+ callback4.Reset();
+ doubleSolenoid.Set(DoubleSolenoid::kReverse);
+ EXPECT_FALSE(callback3.WasTriggered());
+ EXPECT_FALSE(callback3.GetLastValue());
+ EXPECT_TRUE(callback4.WasTriggered());
+ EXPECT_TRUE(callback4.GetLastValue());
+ EXPECT_FALSE(sim.GetSolenoidOutput(3));
+ EXPECT_TRUE(sim.GetSolenoidOutput(4));
+ EXPECT_EQ(0b00010000, ph.GetSolenoids());
+ EXPECT_EQ(0b00010000, sim.GetAllSolenoidOutputs());
+
+ callback3.Reset();
+ callback4.Reset();
+ doubleSolenoid.Set(DoubleSolenoid::kForward);
+ EXPECT_TRUE(callback3.WasTriggered());
+ EXPECT_TRUE(callback3.GetLastValue());
+ EXPECT_TRUE(callback4.WasTriggered());
+ EXPECT_FALSE(callback4.GetLastValue());
+ EXPECT_TRUE(sim.GetSolenoidOutput(3));
+ EXPECT_FALSE(sim.GetSolenoidOutput(4));
+ EXPECT_EQ(0b00001000, ph.GetSolenoids());
+ EXPECT_EQ(0b00001000, sim.GetAllSolenoidOutputs());
+
+ callback3.Reset();
+ callback4.Reset();
+ doubleSolenoid.Set(DoubleSolenoid::kOff);
+ EXPECT_TRUE(callback3.WasTriggered());
+ EXPECT_FALSE(callback3.GetLastValue());
+ EXPECT_FALSE(callback4.WasTriggered());
+ EXPECT_FALSE(callback4.GetLastValue());
+ EXPECT_FALSE(sim.GetSolenoidOutput(3));
+ EXPECT_FALSE(sim.GetSolenoidOutput(4));
+ EXPECT_EQ(0b00000000, ph.GetSolenoids());
+ EXPECT_EQ(0b00000000, sim.GetAllSolenoidOutputs());
+}
+
+TEST(REVPHSimTest, SetCompressorOn) {
+ PneumaticHub ph;
+ REVPHSim sim(ph);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterCompressorOnCallback(callback.GetCallback(), false);
+
+ EXPECT_FALSE(ph.GetCompressor());
+ EXPECT_FALSE(ph.GetCompressor());
+ sim.SetCompressorOn(true);
+ EXPECT_TRUE(sim.GetCompressorOn());
+ EXPECT_TRUE(ph.GetCompressor());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(REVPHSimTest, SetClosedLoopEnabled) {
+ PneumaticHub ph;
+ REVPHSim sim(ph);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb =
+ sim.RegisterClosedLoopEnabledCallback(callback.GetCallback(), false);
+
+ ph.SetClosedLoopControl(false);
+ EXPECT_FALSE(ph.GetClosedLoopControl());
+
+ ph.SetClosedLoopControl(true);
+ EXPECT_TRUE(sim.GetClosedLoopEnabled());
+ EXPECT_TRUE(ph.GetClosedLoopControl());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(REVPHSimTest, SetPressureSwitchEnabled) {
+ PneumaticHub ph;
+ REVPHSim sim(ph);
+ sim.ResetData();
+
+ BooleanCallback callback;
+ auto cb = sim.RegisterPressureSwitchCallback(callback.GetCallback(), false);
+
+ EXPECT_FALSE(ph.GetPressureSwitch());
+
+ sim.SetPressureSwitch(true);
+ EXPECT_TRUE(sim.GetPressureSwitch());
+ EXPECT_TRUE(ph.GetPressureSwitch());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+}
+
+TEST(REVPHSimTest, SetCompressorCurrent) {
+ PneumaticHub ph;
+ REVPHSim sim(ph);
+ sim.ResetData();
+
+ DoubleCallback callback;
+ auto cb =
+ sim.RegisterCompressorCurrentCallback(callback.GetCallback(), false);
+
+ sim.SetCompressorCurrent(35.04);
+ EXPECT_EQ(35.04, sim.GetCompressorCurrent());
+ EXPECT_EQ(35.04, ph.GetCompressorCurrent());
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_EQ(35.04, callback.GetLastValue());
+}
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/RelaySimTest.cpp b/wpilibc/src/test/native/cpp/simulation/RelaySimTest.cpp
new file mode 100644
index 0000000..292d629
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/RelaySimTest.cpp
@@ -0,0 +1,204 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/RelaySim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/Relay.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(RelaySimTest, InitializationBidrectional) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim(0);
+ sim.ResetData();
+
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ EXPECT_FALSE(sim.GetInitializedForward());
+ EXPECT_FALSE(sim.GetInitializedReverse());
+
+ auto fwdCb = sim.RegisterInitializedForwardCallback(
+ forwardCallback.GetCallback(), false);
+ auto revCb = sim.RegisterInitializedReverseCallback(
+ reverseCallback.GetCallback(), false);
+ Relay relay{0};
+
+ EXPECT_TRUE(sim.GetInitializedForward());
+ EXPECT_TRUE(sim.GetInitializedReverse());
+
+ EXPECT_TRUE(forwardCallback.WasTriggered());
+ EXPECT_TRUE(forwardCallback.GetLastValue());
+ EXPECT_TRUE(reverseCallback.WasTriggered());
+ EXPECT_TRUE(reverseCallback.GetLastValue());
+}
+
+TEST(RelaySimTest, InitializationForwardOnly) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim{0};
+ sim.ResetData();
+
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ EXPECT_FALSE(sim.GetInitializedForward());
+ EXPECT_FALSE(sim.GetInitializedReverse());
+
+ auto fwdCb = sim.RegisterInitializedForwardCallback(
+ forwardCallback.GetCallback(), false);
+ auto revCb = sim.RegisterInitializedReverseCallback(
+ reverseCallback.GetCallback(), false);
+ Relay relay(0, Relay::kForwardOnly);
+
+ EXPECT_TRUE(sim.GetInitializedForward());
+ EXPECT_FALSE(sim.GetInitializedReverse());
+
+ EXPECT_TRUE(forwardCallback.WasTriggered());
+ EXPECT_TRUE(forwardCallback.GetLastValue());
+ EXPECT_FALSE(reverseCallback.WasTriggered());
+}
+
+TEST(RelaySimTest, InitializationReverseOnly) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim{0};
+ sim.ResetData();
+
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ EXPECT_FALSE(sim.GetInitializedForward());
+ EXPECT_FALSE(sim.GetInitializedReverse());
+
+ auto fwdCb = sim.RegisterInitializedForwardCallback(
+ forwardCallback.GetCallback(), false);
+ auto revCb = sim.RegisterInitializedReverseCallback(
+ reverseCallback.GetCallback(), false);
+ Relay relay(0, Relay::kReverseOnly);
+
+ EXPECT_FALSE(sim.GetInitializedForward());
+ EXPECT_TRUE(sim.GetInitializedReverse());
+
+ EXPECT_FALSE(forwardCallback.WasTriggered());
+ EXPECT_TRUE(reverseCallback.WasTriggered());
+ EXPECT_TRUE(reverseCallback.GetLastValue());
+}
+
+TEST(RelaySimTest, BidirectionalSetForward) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim{0};
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ Relay relay{0};
+ auto fwdCb =
+ sim.RegisterForwardCallback(forwardCallback.GetCallback(), false);
+ auto revCb =
+ sim.RegisterReverseCallback(reverseCallback.GetCallback(), false);
+
+ relay.Set(Relay::kForward);
+ EXPECT_EQ(Relay::kForward, relay.Get());
+ EXPECT_TRUE(sim.GetForward());
+ EXPECT_FALSE(sim.GetReverse());
+
+ EXPECT_TRUE(forwardCallback.WasTriggered());
+ EXPECT_TRUE(forwardCallback.GetLastValue());
+ EXPECT_FALSE(reverseCallback.WasTriggered());
+}
+
+TEST(RelaySimTest, BidirectionalSetReverse) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim{0};
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ Relay relay{0};
+ auto fwdCb =
+ sim.RegisterForwardCallback(forwardCallback.GetCallback(), false);
+ auto revCb =
+ sim.RegisterReverseCallback(reverseCallback.GetCallback(), false);
+
+ relay.Set(Relay::kReverse);
+ EXPECT_EQ(Relay::kReverse, relay.Get());
+ EXPECT_FALSE(sim.GetForward());
+ EXPECT_TRUE(sim.GetReverse());
+
+ EXPECT_FALSE(forwardCallback.WasTriggered());
+ EXPECT_TRUE(reverseCallback.WasTriggered());
+ EXPECT_TRUE(reverseCallback.GetLastValue());
+}
+
+TEST(RelaySimTest, BidirectionalSetOn) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim{0};
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ Relay relay{0};
+ auto fwdCb =
+ sim.RegisterForwardCallback(forwardCallback.GetCallback(), false);
+ auto revCb =
+ sim.RegisterReverseCallback(reverseCallback.GetCallback(), false);
+
+ relay.Set(Relay::kOn);
+ EXPECT_EQ(Relay::kOn, relay.Get());
+ EXPECT_TRUE(sim.GetForward());
+ EXPECT_TRUE(sim.GetReverse());
+
+ EXPECT_TRUE(forwardCallback.WasTriggered());
+ EXPECT_TRUE(forwardCallback.GetLastValue());
+ EXPECT_TRUE(reverseCallback.WasTriggered());
+ EXPECT_TRUE(reverseCallback.GetLastValue());
+}
+
+TEST(RelaySimTest, BidirectionalSetOff) {
+ HAL_Initialize(500, 0);
+
+ RelaySim sim{0};
+ BooleanCallback forwardCallback;
+ BooleanCallback reverseCallback;
+
+ Relay relay{0};
+ auto fwdCb =
+ sim.RegisterForwardCallback(forwardCallback.GetCallback(), false);
+ auto revCb =
+ sim.RegisterReverseCallback(reverseCallback.GetCallback(), false);
+
+ // Bootstrap into a non-off state to verify the callbacks
+ relay.Set(Relay::kOn);
+ forwardCallback.Reset();
+ reverseCallback.Reset();
+
+ relay.Set(Relay::kOff);
+ EXPECT_EQ(Relay::kOff, relay.Get());
+ EXPECT_FALSE(sim.GetForward());
+ EXPECT_FALSE(sim.GetReverse());
+
+ EXPECT_TRUE(forwardCallback.WasTriggered());
+ EXPECT_FALSE(forwardCallback.GetLastValue());
+ EXPECT_TRUE(reverseCallback.WasTriggered());
+ EXPECT_FALSE(reverseCallback.GetLastValue());
+}
+
+TEST(RelaySimTest, StopMotor) {
+ Relay relay{0};
+ RelaySim sim(relay);
+
+ // Bootstrap into non-off state
+ relay.Set(Relay::kOn);
+
+ relay.StopMotor();
+ EXPECT_EQ(Relay::kOff, relay.Get());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp
new file mode 100644
index 0000000..c6e93d4
--- /dev/null
+++ b/wpilibc/src/test/native/cpp/simulation/RoboRioSimTest.cpp
@@ -0,0 +1,210 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include "frc/simulation/RoboRioSim.h" // NOLINT(build/include_order)
+
+#include <hal/HAL.h>
+#include <hal/HALBase.h>
+
+#include "callback_helpers/TestCallbackHelpers.h"
+#include "frc/RobotController.h"
+#include "gtest/gtest.h"
+
+namespace frc::sim {
+
+TEST(RoboRioSimTest, FPGAButton) {
+ RoboRioSim::ResetData();
+
+ int dummyStatus = 0;
+
+ BooleanCallback callback;
+ auto cb =
+ RoboRioSim::RegisterFPGAButtonCallback(callback.GetCallback(), false);
+ RoboRioSim::SetFPGAButton(true);
+ EXPECT_TRUE(RoboRioSim::GetFPGAButton());
+ EXPECT_TRUE(HAL_GetFPGAButton(&dummyStatus));
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_TRUE(callback.GetLastValue());
+
+ callback.Reset();
+ RoboRioSim::SetFPGAButton(false);
+ EXPECT_FALSE(RoboRioSim::GetFPGAButton());
+ EXPECT_FALSE(HAL_GetFPGAButton(&dummyStatus));
+ EXPECT_TRUE(callback.WasTriggered());
+ EXPECT_FALSE(callback.GetLastValue());
+}
+
+TEST(RoboRioSimTest, SetVin) {
+ RoboRioSim::ResetData();
+
+ DoubleCallback voltageCallback;
+ DoubleCallback currentCallback;
+ auto voltageCb = RoboRioSim::RegisterVInVoltageCallback(
+ voltageCallback.GetCallback(), false);
+ auto currentCb = RoboRioSim::RegisterVInCurrentCallback(
+ currentCallback.GetCallback(), false);
+ constexpr double kTestVoltage = 1.91;
+ constexpr double kTestCurrent = 35.04;
+
+ RoboRioSim::SetVInVoltage(units::volt_t{kTestVoltage});
+ EXPECT_TRUE(voltageCallback.WasTriggered());
+ EXPECT_EQ(kTestVoltage, voltageCallback.GetLastValue());
+ EXPECT_EQ(kTestVoltage, RoboRioSim::GetVInVoltage().value());
+ EXPECT_EQ(kTestVoltage, RobotController::GetInputVoltage());
+
+ RoboRioSim::SetVInCurrent(units::ampere_t{kTestCurrent});
+ EXPECT_TRUE(currentCallback.WasTriggered());
+ EXPECT_EQ(kTestCurrent, currentCallback.GetLastValue());
+ EXPECT_EQ(kTestCurrent, RoboRioSim::GetVInCurrent().value());
+ EXPECT_EQ(kTestCurrent, RobotController::GetInputCurrent());
+}
+
+TEST(RoboRioSimTest, SetBrownout) {
+ RoboRioSim::ResetData();
+
+ DoubleCallback voltageCallback;
+ auto voltageCb = RoboRioSim::RegisterBrownoutVoltageCallback(
+ voltageCallback.GetCallback(), false);
+ constexpr double kTestVoltage = 1.91;
+
+ RoboRioSim::SetBrownoutVoltage(units::volt_t{kTestVoltage});
+ EXPECT_TRUE(voltageCallback.WasTriggered());
+ EXPECT_EQ(kTestVoltage, voltageCallback.GetLastValue());
+ EXPECT_EQ(kTestVoltage, RoboRioSim::GetBrownoutVoltage().value());
+ EXPECT_EQ(kTestVoltage, RobotController::GetBrownoutVoltage().value());
+}
+
+TEST(RoboRioSimTest, Set6V) {
+ RoboRioSim::ResetData();
+
+ DoubleCallback voltageCallback;
+ DoubleCallback currentCallback;
+ BooleanCallback activeCallback;
+ IntCallback faultCallback;
+ auto voltageCb = RoboRioSim::RegisterUserVoltage6VCallback(
+ voltageCallback.GetCallback(), false);
+ auto currentCb = RoboRioSim::RegisterUserCurrent6VCallback(
+ currentCallback.GetCallback(), false);
+ auto activeCb = RoboRioSim::RegisterUserActive6VCallback(
+ activeCallback.GetCallback(), false);
+ auto faultsCb = RoboRioSim::RegisterUserFaults6VCallback(
+ faultCallback.GetCallback(), false);
+ constexpr double kTestVoltage = 22.9;
+ constexpr double kTestCurrent = 174;
+ constexpr int kTestFaults = 229;
+
+ RoboRioSim::SetUserVoltage6V(units::volt_t{kTestVoltage});
+ EXPECT_TRUE(voltageCallback.WasTriggered());
+ EXPECT_EQ(kTestVoltage, voltageCallback.GetLastValue());
+ EXPECT_EQ(kTestVoltage, RoboRioSim::GetUserVoltage6V().value());
+ EXPECT_EQ(kTestVoltage, RobotController::GetVoltage6V());
+
+ RoboRioSim::SetUserCurrent6V(units::ampere_t{kTestCurrent});
+ EXPECT_TRUE(currentCallback.WasTriggered());
+ EXPECT_EQ(kTestCurrent, currentCallback.GetLastValue());
+ EXPECT_EQ(kTestCurrent, RoboRioSim::GetUserCurrent6V().value());
+ EXPECT_EQ(kTestCurrent, RobotController::GetCurrent6V());
+
+ RoboRioSim::SetUserActive6V(false);
+ EXPECT_TRUE(activeCallback.WasTriggered());
+ EXPECT_FALSE(activeCallback.GetLastValue());
+ EXPECT_FALSE(RoboRioSim::GetUserActive6V());
+ EXPECT_FALSE(RobotController::GetEnabled6V());
+
+ RoboRioSim::SetUserFaults6V(kTestFaults);
+ EXPECT_TRUE(faultCallback.WasTriggered());
+ EXPECT_EQ(kTestFaults, faultCallback.GetLastValue());
+ EXPECT_EQ(kTestFaults, RoboRioSim::GetUserFaults6V());
+ EXPECT_EQ(kTestFaults, RobotController::GetFaultCount6V());
+}
+
+TEST(RoboRioSimTest, Set5V) {
+ RoboRioSim::ResetData();
+
+ DoubleCallback voltageCallback;
+ DoubleCallback currentCallback;
+ BooleanCallback activeCallback;
+ IntCallback faultCallback;
+ auto voltageCb = RoboRioSim::RegisterUserVoltage5VCallback(
+ voltageCallback.GetCallback(), false);
+ auto currentCb = RoboRioSim::RegisterUserCurrent5VCallback(
+ currentCallback.GetCallback(), false);
+ auto activeCb = RoboRioSim::RegisterUserActive5VCallback(
+ activeCallback.GetCallback(), false);
+ auto faultsCb = RoboRioSim::RegisterUserFaults5VCallback(
+ faultCallback.GetCallback(), false);
+ constexpr double kTestVoltage = 22.9;
+ constexpr double kTestCurrent = 174;
+ constexpr int kTestFaults = 229;
+
+ RoboRioSim::SetUserVoltage5V(units::volt_t{kTestVoltage});
+ EXPECT_TRUE(voltageCallback.WasTriggered());
+ EXPECT_EQ(kTestVoltage, voltageCallback.GetLastValue());
+ EXPECT_EQ(kTestVoltage, RoboRioSim::GetUserVoltage5V().value());
+ EXPECT_EQ(kTestVoltage, RobotController::GetVoltage5V());
+
+ RoboRioSim::SetUserCurrent5V(units::ampere_t{kTestCurrent});
+ EXPECT_TRUE(currentCallback.WasTriggered());
+ EXPECT_EQ(kTestCurrent, currentCallback.GetLastValue());
+ EXPECT_EQ(kTestCurrent, RoboRioSim::GetUserCurrent5V().value());
+ EXPECT_EQ(kTestCurrent, RobotController::GetCurrent5V());
+
+ RoboRioSim::SetUserActive5V(false);
+ EXPECT_TRUE(activeCallback.WasTriggered());
+ EXPECT_FALSE(activeCallback.GetLastValue());
+ EXPECT_FALSE(RoboRioSim::GetUserActive5V());
+ EXPECT_FALSE(RobotController::GetEnabled5V());
+
+ RoboRioSim::SetUserFaults5V(kTestFaults);
+ EXPECT_TRUE(faultCallback.WasTriggered());
+ EXPECT_EQ(kTestFaults, faultCallback.GetLastValue());
+ EXPECT_EQ(kTestFaults, RoboRioSim::GetUserFaults5V());
+ EXPECT_EQ(kTestFaults, RobotController::GetFaultCount5V());
+}
+
+TEST(RoboRioSimTest, Set3V3) {
+ RoboRioSim::ResetData();
+
+ DoubleCallback voltageCallback;
+ DoubleCallback currentCallback;
+ BooleanCallback activeCallback;
+ IntCallback faultCallback;
+ auto voltageCb = RoboRioSim::RegisterUserVoltage3V3Callback(
+ voltageCallback.GetCallback(), false);
+ auto currentCb = RoboRioSim::RegisterUserCurrent3V3Callback(
+ currentCallback.GetCallback(), false);
+ auto activeCb = RoboRioSim::RegisterUserActive3V3Callback(
+ activeCallback.GetCallback(), false);
+ auto faultsCb = RoboRioSim::RegisterUserFaults3V3Callback(
+ faultCallback.GetCallback(), false);
+ constexpr double kTestVoltage = 22.9;
+ constexpr double kTestCurrent = 174;
+ constexpr int kTestFaults = 229;
+
+ RoboRioSim::SetUserVoltage3V3(units::volt_t{kTestVoltage});
+ EXPECT_TRUE(voltageCallback.WasTriggered());
+ EXPECT_EQ(kTestVoltage, voltageCallback.GetLastValue());
+ EXPECT_EQ(kTestVoltage, RoboRioSim::GetUserVoltage3V3().value());
+ EXPECT_EQ(kTestVoltage, RobotController::GetVoltage3V3());
+
+ RoboRioSim::SetUserCurrent3V3(units::ampere_t{kTestCurrent});
+ EXPECT_TRUE(currentCallback.WasTriggered());
+ EXPECT_EQ(kTestCurrent, currentCallback.GetLastValue());
+ EXPECT_EQ(kTestCurrent, RoboRioSim::GetUserCurrent3V3().value());
+ EXPECT_EQ(kTestCurrent, RobotController::GetCurrent3V3());
+
+ RoboRioSim::SetUserActive3V3(false);
+ EXPECT_TRUE(activeCallback.WasTriggered());
+ EXPECT_FALSE(activeCallback.GetLastValue());
+ EXPECT_FALSE(RoboRioSim::GetUserActive3V3());
+ EXPECT_FALSE(RobotController::GetEnabled3V3());
+
+ RoboRioSim::SetUserFaults3V3(kTestFaults);
+ EXPECT_TRUE(faultCallback.WasTriggered());
+ EXPECT_EQ(kTestFaults, faultCallback.GetLastValue());
+ EXPECT_EQ(kTestFaults, RoboRioSim::GetUserFaults3V3());
+ EXPECT_EQ(kTestFaults, RobotController::GetFaultCount3V3());
+}
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp
index ea7b809..5ef2675 100644
--- a/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp
@@ -1,19 +1,17 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#include <string_view>
#include <hal/SimDevice.h>
-#include <wpi/StringRef.h>
#include "frc/simulation/SimDeviceSim.h"
#include "gtest/gtest.h"
using namespace frc::sim;
-TEST(SimDeviceSimTests, TestBasic) {
+TEST(SimDeviceSimTest, Basic) {
hal::SimDevice dev{"test"};
hal::SimBoolean devBool = dev.CreateBoolean("bool", false, false);
@@ -24,13 +22,15 @@
EXPECT_TRUE(devBool.Get());
}
-TEST(SimDeviceSimTests, TestEnumerateDevices) {
+TEST(SimDeviceSimTest, EnumerateDevices) {
hal::SimDevice dev{"test"};
bool foundit = false;
SimDeviceSim::EnumerateDevices(
"te", [&](const char* name, HAL_SimDeviceHandle handle) {
- if (wpi::StringRef(name) == "test") foundit = true;
+ if (std::string_view(name) == "test") {
+ foundit = true;
+ }
});
EXPECT_TRUE(foundit);
}
diff --git a/wpilibc/src/test/native/cpp/simulation/SimInitializationTest.cpp b/wpilibc/src/test/native/cpp/simulation/SimInitializationTest.cpp
index 1b86e05..e703912 100644
--- a/wpilibc/src/test/native/cpp/simulation/SimInitializationTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/SimInitializationTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <exception>
@@ -15,14 +12,14 @@
#include "frc/simulation/AnalogOutputSim.h"
#include "frc/simulation/AnalogTriggerSim.h"
#include "frc/simulation/BuiltInAccelerometerSim.h"
+#include "frc/simulation/CTREPCMSim.h"
#include "frc/simulation/DIOSim.h"
#include "frc/simulation/DigitalPWMSim.h"
#include "frc/simulation/DriverStationSim.h"
#include "frc/simulation/DutyCycleSim.h"
#include "frc/simulation/EncoderSim.h"
-#include "frc/simulation/PCMSim.h"
-#include "frc/simulation/PDPSim.h"
#include "frc/simulation/PWMSim.h"
+#include "frc/simulation/PowerDistributionSim.h"
#include "frc/simulation/RelaySim.h"
#include "frc/simulation/RoboRioSim.h"
#include "frc/simulation/SPIAccelerometerSim.h"
@@ -30,7 +27,7 @@
using namespace frc::sim;
-TEST(SimInitializationTests, TestAllInitialize) {
+TEST(SimInitializationTest, AllInitialize) {
HAL_Initialize(500, 0);
BuiltInAccelerometerSim biacsim;
AnalogGyroSim agsim{0};
@@ -43,8 +40,8 @@
(void)dssim;
EncoderSim esim = EncoderSim::CreateForIndex(0);
(void)esim;
- PCMSim pcmsim{0};
- PDPSim pdpsim{0};
+ CTREPCMSim pcmsim{0};
+ PowerDistributionSim pdpsim{0};
PWMSim pwmsim{0};
RelaySim rsim{0};
RoboRioSim rrsim;
diff --git a/wpilibc/src/test/native/cpp/simulation/SingleJointedArmSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/SingleJointedArmSimTest.cpp
index a553985..03df12b 100644
--- a/wpilibc/src/test/native/cpp/simulation/SingleJointedArmSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/SingleJointedArmSimTest.cpp
@@ -1,11 +1,8 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
-#include <wpi/math>
+#include <wpi/numbers>
#include "frc/simulation/SingleJointedArmSim.h"
#include "gtest/gtest.h"
@@ -13,13 +10,13 @@
TEST(SingleJointedArmTest, Disabled) {
frc::sim::SingleJointedArmSim sim(frc::DCMotor::Vex775Pro(2), 100, 3_kg_sq_m,
9.5_in, -180_deg, 0_deg, 10_lb, true);
- sim.SetState(frc::MakeMatrix<2, 1>(0.0, 0.0));
+ sim.SetState(Eigen::Vector<double, 2>{0.0, 0.0});
for (size_t i = 0; i < 12 / 0.02; ++i) {
- sim.SetInput(frc::MakeMatrix<1, 1>(0.0));
+ sim.SetInput(Eigen::Vector<double, 1>{0.0});
sim.Update(20_ms);
}
// The arm should swing down.
- EXPECT_NEAR(sim.GetAngle().to<double>(), -wpi::math::pi / 2, 0.01);
+ EXPECT_NEAR(sim.GetAngle().value(), -wpi::numbers::pi / 2, 0.01);
}
diff --git a/wpilibc/src/test/native/cpp/simulation/StateSpaceSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/StateSpaceSimTest.cpp
index 5766751..e7e0405 100644
--- a/wpilibc/src/test/native/cpp/simulation/StateSpaceSimTest.cpp
+++ b/wpilibc/src/test/native/cpp/simulation/StateSpaceSimTest.cpp
@@ -1,9 +1,6 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2020 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#include <iostream>
@@ -11,10 +8,10 @@
#include <units/angular_velocity.h>
#include "frc/Encoder.h"
-#include "frc/PWMVictorSPX.h"
#include "frc/RobotController.h"
#include "frc/controller/PIDController.h"
#include "frc/controller/SimpleMotorFeedforward.h"
+#include "frc/motorcontrol/PWMVictorSPX.h"
#include "frc/simulation/BatterySim.h"
#include "frc/simulation/DifferentialDrivetrainSim.h"
#include "frc/simulation/ElevatorSim.h"
@@ -27,7 +24,7 @@
#include "frc/system/plant/LinearSystemId.h"
#include "gtest/gtest.h"
-TEST(StateSpaceSimTest, TestFlywheelSim) {
+TEST(StateSpaceSimTest, FlywheelSim) {
const frc::LinearSystem<1, 1, 1> plant =
frc::LinearSystemId::IdentifyVelocitySystem<units::radian>(
0.02_V / 1_rad_per_s, 0.01_V / 1_rad_per_s_sq);
@@ -39,6 +36,9 @@
frc::sim::EncoderSim encoderSim{encoder};
frc::PWMVictorSPX motor{0};
+ frc::sim::RoboRioSim::ResetData();
+ encoderSim.ResetData();
+
for (int i = 0; i < 100; i++) {
// RobotPeriodic runs first
auto voltageOut = controller.Calculate(encoder.GetRate(), 200.0);
@@ -48,10 +48,10 @@
// Then, SimulationPeriodic runs
frc::sim::RoboRioSim::SetVInVoltage(
frc::sim::BatterySim::Calculate({sim.GetCurrentDraw()}));
- sim.SetInput(frc::MakeMatrix<1, 1>(
- motor.Get() * frc::RobotController::GetInputVoltage()));
+ sim.SetInput(Eigen::Vector<double, 1>{
+ motor.Get() * frc::RobotController::GetInputVoltage()});
sim.Update(20_ms);
- encoderSim.SetRate(sim.GetAngularVelocity().to<double>());
+ encoderSim.SetRate(sim.GetAngularVelocity().value());
}
ASSERT_TRUE(std::abs(200 - encoder.GetRate()) < 0.1);
diff --git a/wpilibc/src/test/native/include/MockMotorController.h b/wpilibc/src/test/native/include/MockMotorController.h
new file mode 100644
index 0000000..e17931f
--- /dev/null
+++ b/wpilibc/src/test/native/include/MockMotorController.h
@@ -0,0 +1,25 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include "frc/motorcontrol/MotorController.h"
+
+namespace frc {
+
+class MockMotorController : public MotorController {
+ public:
+ void Set(double speed) override;
+ double Get() const override;
+ void SetInverted(bool isInverted) override;
+ bool GetInverted() const override;
+ void Disable() override;
+ void StopMotor() override;
+
+ private:
+ double m_speed = 0.0;
+ bool m_isInverted = false;
+};
+
+} // namespace frc
diff --git a/wpilibc/src/test/native/include/MockSpeedController.h b/wpilibc/src/test/native/include/MockSpeedController.h
deleted file mode 100644
index e0c788f..0000000
--- a/wpilibc/src/test/native/include/MockSpeedController.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
-
-#pragma once
-
-#include "frc/SpeedController.h"
-
-namespace frc {
-
-class MockSpeedController : public SpeedController {
- public:
- void Set(double speed) override;
- double Get() const override;
- void SetInverted(bool isInverted) override;
- bool GetInverted() const override;
- void Disable() override;
- void StopMotor() override;
-
- void PIDWrite(double output) override;
-
- private:
- double m_speed = 0.0;
- bool m_isInverted = false;
-};
-
-} // namespace frc
diff --git a/wpilibc/src/test/native/include/callback_helpers/TestCallbackHelpers.h b/wpilibc/src/test/native/include/callback_helpers/TestCallbackHelpers.h
new file mode 100644
index 0000000..646bcdd
--- /dev/null
+++ b/wpilibc/src/test/native/include/callback_helpers/TestCallbackHelpers.h
@@ -0,0 +1,64 @@
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
+
+#pragma once
+
+#include <functional>
+#include <string_view>
+
+#include <hal/Value.h>
+
+namespace frc::sim {
+
+template <typename ValueType>
+class BaseCallbackHelper {
+ public:
+ bool WasTriggered() const { return m_wasTriggered; }
+ ValueType GetLastValue() const { return m_lastValue; }
+
+ void Reset() {
+ m_wasTriggered = false;
+ m_lastValue = 0;
+ }
+
+ virtual void HandleCallback(std::string_view name,
+ const HAL_Value* value) = 0;
+
+ std::function<void(std::string_view, const HAL_Value*)> GetCallback() {
+ return [&](std::string_view name, const HAL_Value* value) {
+ HandleCallback(name, value);
+ };
+ }
+
+ protected:
+ bool m_wasTriggered{false};
+ ValueType m_lastValue{0};
+};
+
+class BooleanCallback : public BaseCallbackHelper<bool> {
+ public:
+ void HandleCallback(std::string_view name, const HAL_Value* value) override;
+};
+
+class EnumCallback : public BaseCallbackHelper<int32_t> {
+ public:
+ void HandleCallback(std::string_view name, const HAL_Value* value) override;
+};
+
+class IntCallback : public BaseCallbackHelper<int32_t> {
+ public:
+ void HandleCallback(std::string_view name, const HAL_Value* value) override;
+};
+
+class LongCallback : public BaseCallbackHelper<int64_t> {
+ public:
+ void HandleCallback(std::string_view name, const HAL_Value* value) override;
+};
+
+class DoubleCallback : public BaseCallbackHelper<double> {
+ public:
+ void HandleCallback(std::string_view name, const HAL_Value* value) override;
+};
+
+} // namespace frc::sim
diff --git a/wpilibc/src/test/native/include/shuffleboard/MockActuatorSendable.h b/wpilibc/src/test/native/include/shuffleboard/MockActuatorSendable.h
index 1cba8e3..8baf2a2 100644
--- a/wpilibc/src/test/native/include/shuffleboard/MockActuatorSendable.h
+++ b/wpilibc/src/test/native/include/shuffleboard/MockActuatorSendable.h
@@ -1,29 +1,19 @@
-/*----------------------------------------------------------------------------*/
-/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
-/* Open Source Software - may be modified and shared by FRC teams. The code */
-/* must be accompanied by the FIRST BSD license file in the root directory of */
-/* the project. */
-/*----------------------------------------------------------------------------*/
+// Copyright (c) FIRST and other WPILib contributors.
+// Open Source Software; you can modify and/or share it under the terms of
+// the WPILib BSD license file in the root directory of this project.
#pragma once
-#include <wpi/StringRef.h>
+#include <string_view>
-#include "frc/smartdashboard/Sendable.h"
-#include "frc/smartdashboard/SendableBuilder.h"
-#include "frc/smartdashboard/SendableHelper.h"
-
-namespace frc {
+#include <wpi/sendable/Sendable.h>
/**
* A mock sendable that marks itself as an actuator.
*/
-class MockActuatorSendable : public Sendable,
- public SendableHelper<MockActuatorSendable> {
+class MockActuatorSendable : public wpi::Sendable {
public:
- explicit MockActuatorSendable(wpi::StringRef name);
+ explicit MockActuatorSendable(std::string_view name);
- void InitSendable(SendableBuilder& builder) override;
+ void InitSendable(wpi::SendableBuilder& builder) override;
};
-
-} // namespace frc