Compare commits

...

1926 Commits

Author SHA1 Message Date
Tyler Veness
35eb90c135 Fix "'dimensionless' ambiguous symbol" error (#2382)
A typedef for units::dimensionless::dimensionless is defined, which
conflicted with the namespace when we added "using namespace
dimensionless". This patch reverts the "using namespace" directive.
"using" directives were added to pull three of the four relevant
typedefs but avoid the "dimensionless" type conflict.

This issue was first introduced in #2301.
2020-02-21 00:41:50 -08:00
Dustin Spicuzza
761f79385a Add SimulationInit and SimulationPeriodic functions (#2377)
Fixes #2375
2020-02-18 23:05:16 -08:00
Thad House
554bda3332 HAL: Expose NetComm SendConsoleLine (#2337)
This can be use to synchronize writes between threads, assuming writes all go through this and not stdout.
2020-02-18 20:44:40 -08:00
Thad House
2a968df779 Add method for releasing a waiting interrupt (#2347)
Useful for a new high level interrupt implementation.
2020-02-18 20:41:42 -08:00
sciencewhiz
30ccd13b69 Add methods for getting color of an LED (#2366)
Also fix rounding in Color.
2020-02-18 20:40:03 -08:00
Thad House
60c09ea51f Fix notifier race happening with very fast notifiers (#2370)
What would happen is the Stop() call would happen between the notifier loop being triggered and calling UpdateAlarm(). This would cause the Update to overwrite the stop.
2020-02-18 20:38:05 -08:00
Oblarg
65eab93527 Fix DifferentialDriveVoltageConstraint for tight turns w/ zero velocity (#2341) 2020-02-15 12:36:16 -08:00
sciencewhiz
a226ad8509 Set a default option for Sendable Chooser in examples (#2361) 2020-02-15 09:54:12 -08:00
Peter Johnson
31f4fd70ce Sim GUI: Fix crash when field/robot image load is canceled (#2362) 2020-02-15 09:53:21 -08:00
Dustin Spicuzza
7275ab9837 Add headerpad_max_install_names to Mac builds (#2333)
This allows dylib paths to be rewritten to a larger size by downstream tools.
2020-02-10 21:52:58 -08:00
Dustin Spicuzza
5b3facc63b TrapezoidProfile: Make units public (#2342) 2020-02-10 21:44:21 -08:00
CircuitCraft42
0f313fb9ab cmake: Improved portability of OpenCV Java binding search (#2348)
The CMake option OPENCV_JAVA_INSTALL_DIR can be set to the location
to search for the jar file. Note that the file name cannot be
changed, as, after checking several Linux package repositories,
that seems to be constant across all of them.

Fixes #2346.
2020-02-10 17:30:54 -08:00
Oblarg
05b7593e66 C++ circular_buffer: support types not implicitly convertible from int (#2350)
Also fixes two cases of returning a reference to a constant.
2020-02-08 13:35:21 -08:00
sciencewhiz
1b85066d26 Fix C++ ParallelRaceGroup multiple calls behavior (#2339)
The Java version was correct, but the C++ version would only run once.
2020-02-08 10:26:06 -08:00
sciencewhiz
e93b64f58d Add note that only a single instance of ADXRS450 is supported (#2349) 2020-02-08 10:24:18 -08:00
Oblarg
f0a18f31e7 Timer: add hasElapsed, advanceIfElapsed (#2322)
The current hasPeriodPassed() function is confusing.  In preparation for deprecating it,
add new advanceIfElapsed() function with same functionality and hasElapsed() function
which only checks that the time period has elapsed and does not advance the timer.

Also fix a couple of incorrect usages of hasPeriodPassed().
2020-02-08 10:23:29 -08:00
Vasista Vovveti
29c82527a5 Fix typo in ADXL sim double creation (#2332)
Sets m_simY to the virtual Y acceleration.
2020-02-04 20:15:25 -08:00
Peter Johnson
c165dc5e50 Simulation GUI: Add 2D field view (#2261)
The field image and robot image can be loaded or just a wireframe used.
The robot can be moved and rotated with a mouse click + drag.
The robot position is settable in robot code via the Field2d class.
2020-02-01 21:30:23 -08:00
sciencewhiz
42da07396c Add missing references to f in PIDSubsystem javadoc (#2318) 2020-01-31 19:18:17 -08:00
Jonathan Noyola
20e6c04059 Fix cmake install of hal generated files (#2320) 2020-01-31 19:18:00 -08:00
Declan Freeman-Gleason
ff5d3e5b36 RamseteController: Add setEnabled method (#2313) 2020-01-27 21:53:00 -08:00
sciencewhiz
6cc68ab503 Update MavenArtifacts.md (#2289) 2020-01-27 19:45:53 -08:00
Thad House
068465146b Fix null check order in SendableRegistry (#2314) 2020-01-27 19:43:31 -08:00
Thad House
3bcf8057d4 Add more detail to RuntimeLoader failure message (#2309)
Now specifies the C++ runtime is needed, along with more detail to make it easier to troubleshoot and not lose exception information.
2020-01-27 14:10:46 -08:00
David Vo
8039a6c525 Add missing include to ShuffleboardEventImportance (#2310) 2020-01-26 21:03:15 -08:00
Prateek Machiraju
558c020cca Fix duplicated state when using quintic splines (#2307)
Generating a trajectory using quintic splines caused a duplicated state at all knot points.
2020-01-24 23:10:28 -08:00
Prateek Machiraju
7797da78f5 Add missing methods to Timed and TimedSkeleton templates (#2306) 2020-01-24 20:01:23 -08:00
Oblarg
0ab81d768f Add feed-forward and slew rate limiting to advanced drive examples (#2301) 2020-01-23 18:07:38 -08:00
Oblarg
1cee5ccb93 Feed RobotDrive watchdog in RamseteCommand example (#2298) 2020-01-23 17:41:45 -08:00
Dan Katzuv
3ce01b5ac2 Fix DriveSubsystem.getHeading Java documentation (#2282) 2020-01-23 16:46:53 -08:00
sciencewhiz
e6aa8f3ff4 Update toolchain link in readme (#2304) 2020-01-23 16:43:06 -08:00
Peter Johnson
9d7b087972 Simulation GUI: Add support for custom names (#2292)
This allows users to right click on just about any name in the GUI (e.g. "PWM[0]") and rename it (e.g. "Left Motor [0]"). The index portion is not editable. The name is saved into imgui.ini so it's persistent.
2020-01-20 22:47:36 -08:00
Peter Johnson
bb184ed481 Simulation GUI: Refactor ini saving (#2291) 2020-01-20 21:49:03 -08:00
Peter Johnson
b9b31069cc Fix C++ POVButton (#2294)
Also add unit test.
2020-01-20 21:35:19 -08:00
Peter Johnson
d0cf4e8882 Change sim Filesystem.getDeployDirectory() to src/main/deploy (#2293) 2020-01-19 16:34:45 -08:00
sciencewhiz
02fb850761 Add new speed controllers to shuffleboard docs (#2288)
Also fix java links in C++ docs and a few typos.
2020-01-19 14:26:44 -08:00
sciencewhiz
ac8177e10d Fix GearsBot log methods not being called periodically (#2280)
Add logging for C++ Wrist and Claw
2020-01-17 20:18:15 -08:00
Tyler Veness
2eb5c54476 TrapezoidProfile: Fix aliasing of m_initial to result in calculate() (#2284)
Fixes #2283.
2020-01-17 20:17:21 -08:00
Peter Johnson
0e206e69cf Remove Set Camera Server Shared message (#2285) 2020-01-17 20:16:24 -08:00
Peter Johnson
b1357cace7 Fix LiveWindow SetEnabled C++ std::bad_function_call (#2281)
It was missing a null check.
2020-01-16 00:34:51 -08:00
Thad House
37202b6f28 Add missing SensorUtil::kAnalogOutputs (#2276) 2020-01-15 21:34:28 -08:00
Thad House
2ac0d52960 Remove AnalogTrigger::SetDutyCycle (#2275) 2020-01-15 21:33:58 -08:00
Thad House
dbe1e6f466 Fix missing SetDutyCycleSimDevice on Rio (#2274) 2020-01-15 21:33:35 -08:00
Chris Russell
a61fcbd68d Make Button class concrete (#2244) 2020-01-15 18:59:51 -08:00
Thad House
fe597eeba1 Fix SPI DIO count for sim (#2272)
Only 26 DIO were detectable, not 31.
2020-01-15 18:58:14 -08:00
Jonathan Leitschuh
e213a47efd Official Gradle Wrapper Validation GitHub Action (#2273)
See: https://github.com/gradle/wrapper-validation-action
2020-01-15 14:21:50 -08:00
Peter Johnson
dcb96cb50c TrajectoryGenerator: Allow replacement of error reporting function (C++) (#2267)
C++ version of #2234.
2020-01-13 20:36:16 -08:00
Austin Shalit
60d48fec57 Fix Java static colors having zero values (#2269)
Also add test for this.
2020-01-13 12:21:44 -08:00
Austin Shalit
ee8475d21f Run wpiformat (#2270) 2020-01-13 12:19:08 -08:00
Peter Johnson
f47e318131 C++ units: Interoperate with Windows headers min/max (#2268) 2020-01-12 22:52:36 -08:00
Thad House
cb66bcca3c Add callback handlers for LiveWindow (#2053)
Fixes #2223
2020-01-12 22:37:24 -08:00
Simon Abrelat
73302f6162 Fix color name typos (#2265) 2020-01-12 22:15:19 -08:00
Oblarg
cba21a768f Fix C++ JoystickButton and POVButton (#2259)
C++ JoystickButton and POVButton were both nonfunctional due to slicing when trigger passes itself by value to the button scheduler it creates.

Fix is to remove the virtual Get() method entirely and use only the m_isActive functor; since the subclass now passes the button condition back as a functor to the base class, in which it's stored as a member, it will now still work after being sliced.
2020-01-12 14:57:28 -08:00
Peter Johnson
822e75ec45 Simulator GUI: Handle save file having window size=0 (#2260)
This should never happen, but if it does, it's not recoverable without
either deleting imgui.ini or editing it manually.
2020-01-12 01:37:53 -08:00
Peter Johnson
108ddfa1b4 Fix Pi Camera auto exposure property name (#2258) 2020-01-11 15:04:29 -08:00
Prateek Machiraju
d4c8ee5915 Add Axis enum in XboxController (#2253) 2020-01-10 23:43:19 -08:00
Peter Johnson
ab9647ff5b CommandScheduler: Don't store NetworkTableEntry 2020-01-10 23:42:18 -08:00
Peter Johnson
6666d3be42 SendableBuilder: Allow multiple updateTable functions
This fixes cases like CommandScheduler not working when added to both
LiveWindow and SmartDashboard.
2020-01-10 23:42:18 -08:00
Peter Johnson
795086b4cf Fix Demangle when used standalone (#2256) 2020-01-10 23:41:40 -08:00
Peter Johnson
56765cf49a C++ CommandBase: Don't add to LiveWindow (#2255) 2020-01-10 20:37:49 -08:00
Peter Johnson
bf7012fa2d Fix new CommandScheduler.cancelAll() (#2251)
When called outside the run loop, it would result in a CME in Java.
2020-01-10 16:10:16 -08:00
Peter Johnson
10e8fdb724 Make C++ IterativeRobotBase and RobotBase constructor and destructor public (#2242) 2020-01-08 23:17:12 -08:00
Peter Johnson
790dc552ca Add quirks support for Pi camera (#2241)
- Valid video modes (native modes plus some low-res modes)
- Exposure setting
2020-01-07 20:21:28 -08:00
Peter Johnson
0ec8ed6c05 Make C++ controller using declarations public (#2240) 2020-01-06 23:30:47 -08:00
Tyler Veness
832693617f Add missing definition for PIDController::SetPID() (#2239)
Fixes #2238.
2020-01-06 21:17:16 -08:00
sciencewhiz
772ef8f961 Update Maven location to artifactory (#2235) 2020-01-06 20:13:42 -08:00
Peter Johnson
95b6cd2dd9 TrajectoryGenerator: Allow replacement of error reporting function (#2234)
This is needed to avoid use of DriverStation if used from desktop applications
such as PathWeaver.
2020-01-05 16:01:31 -08:00
sciencewhiz
ce1ac17dfb Remove experimental from new command example descriptions (#2226) 2020-01-04 19:57:31 -08:00
Thad House
b2f7a6b651 Add clarification to LED about length and # of drivers (#2231) 2020-01-04 19:57:10 -08:00
Peter Johnson
bedbef7999 Revert "Remove -no-module-directories flag from javadoc build (#2201)" (#2229)
This reverts commit f9a11cce5e.
2020-01-04 19:52:43 -08:00
Thad House
bc159a92a7 Default sim voltage to 12v, make user rails active (#2224) 2020-01-04 15:07:47 -08:00
Austin Shalit
f50d710a5e Make color ctor public (#2222) 2020-01-04 08:28:18 -08:00
Peter Johnson
bc8f68bec7 Add sim HAL_WaitForCachedControlData (#2221) 2020-01-03 22:38:45 -08:00
Peter Johnson
32c62449be Add ArrayRef overloads to new command classes (#2216)
Also default requirements to {} in all cases for consistency.
2020-01-01 20:09:17 -08:00
Tyler Veness
6190fcb237 Run wpiformat (#2218) 2020-01-01 20:04:56 -08:00
Declan Freeman-Gleason
012d93b2bd Use an explicit stack instead of recursion when parameterizing splines (#2197)
This PR changes the spline parameterizer to use an explicit stack instead of recursion. This is motivated by the fact that splines with adjacent waypoints with approximately opposite headings will never parameterize. In this case the parameterizer subdivides these malformed splines fine for a while, and then gets stuck parameterizing infinitely on some interval. In the recursive approach, this would lead to a stack overflow. We could implement a recursion depth counter (this is what my team did on our similar trajectory code last season), but it's hard to choose a good number for max depth because the initial amount of stack used varies based on how the user calls Parameterize.

A good solution for this is converting the recursion to an "explicit stack," which basically simulates recursion, but allows us to have a much larger maximum stack size. Because we avoid the stack overflow, we can instead throws a more informative MalformedSplineException. If the user is using the TrajectoryGenerator instead of the SplineParameterizer directly then the TrajectoryGenerator will go ahead and catch the exception, return a harmless empty trajectory, and report and error to the driver station.
2020-01-01 18:23:08 -08:00
Matt
222669dc2c Fix trapezoidal profile PID controller setpoint bug (#2210)
Co-Authored-By: Austin Shalit <austinshalit@gmail.com>
2020-01-01 15:23:25 -08:00
Peter Johnson
abe25b795b TrajectoryUtil.toPathweaverJson: Create parent directories (#2214) 2020-01-01 13:35:04 -08:00
sciencewhiz
354185189c Update ProjectYear to 2020 (#2212) 2020-01-01 11:14:31 -08:00
sciencewhiz
f14fe434a1 Add (Old) qualifier to old subsystem (#2211) 2019-12-31 23:00:35 -06:00
Prateek Machiraju
e874ba9313 Add Color classes for use with AddressableLED (#2127)
Both floating point and 8-bit integer classes are included, as well as a wide selection of color constants.

Co-authored-by: Austin Shalit <austinshalit@gmail.com>
2019-12-30 00:01:20 -06:00
Peter Johnson
96348e835a Fix C++ SendableRegistry::AddChild() (#2207)
Add a Sendable* overload so pointers to sendable objects work appropriately.
Otherwise an AddLW(this) in a child (which is a Sendable*) could be a
different pointer than a void* to the same object.

For example:
  AnalogInput constructor calls AddLW(this)
  AnalogPotentiometer constructor calls AddChild(analog input pointer)

Also add handling for the child object moving (if it's Sendable).
2019-12-29 23:37:14 -06:00
Oblarg
d91796f8d2 fix clang-format version number (#2206) 2019-12-29 21:31:26 -06:00
Peter Johnson
9abce8eb06 Fix subsystem LiveWindow usage (#2202) 2019-12-29 21:28:38 -06:00
Peter Johnson
8b4508ad53 Use default path for networktables.ini in simulation (#2205) 2019-12-29 18:55:02 -06:00
Oblarg
5b7dd186d2 Add templates for new commands for vscode plugin (#2016) 2019-12-29 15:02:49 -06:00
Peter Johnson
6ea13ea8f3 ntcore: Add support for local-only operation (#2204)
StartLocal() causes future calls to StartServer() or StartClient() to have
no effect. StopLocal() re-enables these calls.
2019-12-29 14:56:41 -06:00
Oblarg
44bcf7fb4d Java examples: use non-static imports for constants (#2191) 2019-12-29 14:55:49 -06:00
Oblarg
c7a1dfc0bc Add SlewRateLimiter class (#2192)
This is extremely useful for implementing various "ramping" functions
(such as voltage ramps, setpoint ramps, etc). Usage is straightforward;
it behaves like all of our other filter classes. C++ version is unit-safe.
2019-12-29 13:36:28 -06:00
Peter Johnson
a12bb447e4 Fail cmake build if python3 generate_numbers.py fails (#2203) 2019-12-29 13:12:00 -06:00
Declan Freeman-Gleason
c4bd54ef44 Add JNI binding to suppress driver station error/warning messages (#2200)
This is to allow suppressing an ugly stack trace/error message in a unit test in #2197. It doesn't support the full HALSIM_SetSendError callback stuff (i.e. you can only suppress, not intercept, stack traces with this).
2019-12-27 21:11:26 -06:00
Austin Shalit
f9a11cce5e Remove -no-module-directories flag from javadoc build (#2201) 2019-12-27 10:19:49 -06:00
Peter Johnson
6008671c30 Report WPILib version as part of usage reporting (#2199) 2019-12-26 22:34:10 -06:00
Peter Johnson
7b952d599d Add usage reporting for many new things (#2184)
- new CommandScheduler
- kinematics and odometry classes
- new PIDController
- ProfiledPIDController
- TrapezoidProfile (reported in Constraints class)

Also update instances.txt to match latest NI version.

One side effect is that a couple of classes are no longer constexpr.
2019-12-25 00:42:14 -06:00
Peter Johnson
93cdf68694 Add Constants.cpp for MecanumControllerCommand example (#2196) 2019-12-24 16:19:02 -06:00
Peter Johnson
0c6f24562f Fix bug in ULEB128 decoding (#2195) 2019-12-24 14:12:42 -06:00
Thad House
bdc1cab013 Add support for configuring SPI Auto Stall Config (#2193) 2019-12-24 12:52:58 -06:00
Prateek Machiraju
3259cffc63 Add transform methods to Trajectory (#2187) 2019-12-23 13:16:30 -06:00
Oblarg
67b59f2b31 Minor improvements/fixes to new command framework (#2186) 2019-12-23 01:09:25 -06:00
sciencewhiz
1ce24a7a2f Add 2020 speed controllers (#2188)
Add CTRE TalonFX (PWMTalonFX)
Add Playing with Fusion Venom (PWMVenom)
2019-12-22 13:51:43 -06:00
Prateek Machiraju
635882a9f7 Add getter for initial pose in Trajectory (#2180) 2019-12-21 06:57:39 -08:00
Thad House
71a22861eb Use ManagedStatic for CameraServer (#2174) 2019-12-20 14:20:38 -08:00
Thad House
9cb69c5b46 Add a way to pass in a preconstructed value to ManagedStatic (#2175)
A lot of our cases don't need the lazy construction, but do need manual destruction.
2019-12-20 14:06:22 -08:00
Thad House
5e08bb28f8 Add docs and lifecycle tasks for faster dev builds (#2182) 2019-12-20 13:48:26 -08:00
Oblarg
ea4d1a39e1 Update characterization values to match real robot (#2183)
This is in preparation for an end-to-end trajectory tutorial example.

Co-Authored-By: Dalton Smith <gamefollower26@gmail.com>
2019-12-20 13:46:13 -08:00
Prateek Machiraju
31b588d961 Fix ArmFeedforward Javadocs (#2176) 2019-12-15 14:34:18 -08:00
Thad House
0b80d566ad Use ChipObject HMB function for LED (#2173)
It's fixed in v9 and up.
2019-12-14 21:15:32 -08:00
Peter Johnson
f8294e689b Sim GUI: Add a bit of spacing to the analog inputs (#2170)
This helps make it clear they are separate controls.
2019-12-14 10:49:01 -08:00
Peter Johnson
b78f115fcf Work around VS2019 16.4.0 bugs (#2171)
Work around frontend bug in scoped_lock and code generation bug in reverse_iterator in gtest.

See https://github.com/google/googletest/pull/2635
2019-12-14 10:48:19 -08:00
sciencewhiz
b468c51251 Change AddressableLED example to use consistent PWM port (#2168) 2019-12-11 15:39:36 -08:00
Prateek Machiraju
023c088290 Add toString() to relevant kinematics classes (#2160) 2019-12-09 21:35:43 -08:00
Thad House
8a11d13a39 Fix C++ DutyCycleEncoder int constructor (#2166) 2019-12-09 21:35:00 -08:00
Claudius Tewari
daa81c64a7 Minor javadoc fix in SwerveDriveKinematicsConstraint (#2167) 2019-12-09 21:34:32 -08:00
Peter Johnson
e20d96ea4e Use __has_include for WPILib.h (#2164)
Now that commands and cameraserver libraries are no longer direct dependencies,
it's necessary to check for their presence.
2019-12-07 21:39:58 -08:00
Thad House
a76d006a07 Update native-utils to 2020.7.2 (#2161)
Fixes a bug where source directories were being added to the header search path
2019-12-07 17:18:50 -08:00
Thad House
24c031d692 Increase SPI auto byte count to allow 32 bytes to be sent (#2163)
The FPGA now supports 32 bytes.
2019-12-07 17:18:25 -08:00
Thad House
6b4eecf5fe Add hidden functions to get the SPI system and SPI DMA (#2162)
With the addition of stall configuration, its not very clear how it works, and seems like it would be different
per use. So adding ways to manually get them, so the functionality can be figured out how to be used.
2019-12-07 17:16:14 -08:00
Oblarg
ccdd0fbdb2 Add TrapezoidProfile external PID examples (#2131) 2019-12-07 13:37:54 -08:00
Tyler Veness
5c6b8a0f45 Replace std::is_pod_v with std::is_standard_layout_v (#2159)
The former is deprecated in C++20.
2019-12-07 13:34:52 -08:00
Thad House
67d2fed685 Add DutyCycleEncoder channel constructor (#2158)
Avoids extra boilerplate at user level.
2019-12-06 20:58:04 -08:00
Thad House
d8f11eb149 Hardcode channels for LSB weight (#2153)
Avoids a mutex and a lookup.
2019-12-06 20:56:40 -08:00
Thad House
b2ae75acd8 Add way to disable "no extensions found" message (#2134)
We want it enabled by default, but there have been requests for a way to disable it.
2019-12-06 20:55:36 -08:00
Austin Shalit
4f951789fe Build testbench tests online inorder to improve speed (#2144)
* Attempt to build testbench tests online inorder to improve speed

* Fix contianer reference

* Start to remove jenkins shell script

* Change job names

* Remove sshpass

* Remove teststand code

* Copy test results back

* Fix build by using athena container

* Fail if any command fails

* Remove jenkins test script

* Remove name argument

* Fix param count

* Add build display name

* Fix scp to copy into dir

* Update display names

* Update stage name

* Fix test results scp

* Create local test report dir

* Remove commented out old code

* Remove force pseudo-terminal allocation

* Remove extra variables

* Update readme

* Remove old test runs

* Update license header
2019-12-06 17:46:29 -05:00
Austin Shalit
005c4c5beb Try catch around task dependencies to fix loading in editor (#2156) 2019-12-06 11:46:21 -08:00
Tyler Veness
34f6b3f4c0 Fix C++ RamseteCommand param doxygen (#2157) 2019-12-05 23:54:32 -08:00
Oblarg
f7a93713fa Fix up templated TrapezoidProfile classes (#2151)
* Fix two-phase name lookup bug

* Fix param in ProfiledPIDCommand constructor overload

* Fix ProfiledPIDCommand/Controller
2019-12-04 20:40:37 -08:00
Tyler Veness
8c2ff94d70 Rename MathUtils to MathUtil for consistency with other util classes (#2155) 2019-12-04 20:39:12 -08:00
Thad House
d003ec2dc9 Update to 2020v9 image (#2154)
- Fix VISA include and FPGA header
- Fix missing VISA lib from executables
2019-12-04 20:38:43 -08:00
Peter Johnson
8e7cc3fe78 Add user-friendly SimDeviceSim wrappers (#2150)
This makes unit testing with SimDevice devices much easier.
2019-12-02 23:27:33 -08:00
Matt
6c8f6cf479 Fix bug in cubic and quintic hermetic spline generation (#2139)
Add documentation for spline derivatives and explicitly zero matrices.
2019-12-01 21:29:52 -08:00
Peter Johnson
e37ecd33ae Sim GUI: Add support for LED displays (#2138)
LED displays connect the LEDs in various ways (column major vs row major,
different starting locations, serpentine connection order), so add
configuration parameters for these options.
2019-12-01 21:28:02 -08:00
Prateek Machiraju
57c5523d67 Fix documentation in RamseteCommand (#2149) 2019-12-01 21:27:02 -08:00
Matt
7b9c6ebc2f Fix wpiutilJNIShared linkage typo in wpilibj (#2143) 2019-12-01 13:25:46 -08:00
Oblarg
9a515c80f8 Template C++ LinearFilter to work with unit types (#2142) 2019-11-30 23:12:02 -08:00
Prateek Machiraju
5b73c17f25 Remove encoder velocities methods in DifferentialDriveOdometry (#2147)
It doesn't make sense to continue to provide a less accurate method of performing odometry
when a more accurate method using distances exists.

This also removes the need to pass DifferentialDriveKinematics to the constructor.
2019-11-30 23:10:29 -08:00
Banks T
b8c1024261 Fix PS3Eye VID and PID (#2146) 2019-11-30 12:35:47 -08:00
Prateek Machiraju
2622c6c291 Add default values for b and zeta in RamseteController (#2145)
Values b=2.0 and zeta=0.7 have been well-tested to produce desirable results.
2019-11-29 21:16:01 -08:00
Austin Shalit
f66ae59992 Add HSV helpers to AddressableLED (#2135)
Also change the setLED() method to setRGB() for consistency and clarity.

Add rainbow example to demonstrate HSV usage.
2019-11-29 15:16:57 -08:00
Oblarg
5e97c81d80 Add MedianFilter class for moving-window median (#2136)
This kind of filter is extremely useful for signals that are susceptible to sudden
outliers - ultrasonics, 1-D LIDAR, and results from vision processing are all
good use-cases.

This also modifies the existing ultrasonic examples accordingly.
2019-11-29 15:13:40 -08:00
Tyler Veness
f79b7a058a Remove unnecessary constructor arg for LinearFilter's circular buffers (#2140)
They are initialized in LinearFilter's constructor, so the default is
never used.
2019-11-28 23:27:20 -08:00
Austin Shalit
e49494830f Replace Jenkins with Azure agent (#1914) 2019-11-25 22:00:35 -08:00
sciencewhiz
b67d049ac2 Check status of PDP CAN reads (#2126)
Fixes #2124
2019-11-25 21:47:35 -08:00
Peter Johnson
70102a60b7 SendableRegistry.foreachLiveWindow: Prevent concurrent modification (#2129)
Copy the internal map values into an array before iterating.

In C++, change to recursive mutex as well.
2019-11-25 21:47:06 -08:00
Oblarg
6dcd2b0e2c Improve various subsystem APIs (#2130)
Improves the APIs for various prebuilt subsystems (PIDSubsystem, TrapezoidProfileSubsystem, ProfiledPIDSubsystem). Addresses #2128, and also changes the rather cumbersome getSetpoint API to a more intuitive setSetpoint one. Updates examples to match.
2019-11-25 21:46:47 -08:00
Thad House
ce3973435e HAL_CAN_ReceiveMessage: return MessageNotFound if no callbacks registered (#2133) 2019-11-25 21:45:44 -08:00
Thad House
3fcfc8ea72 Fix double disable segfaulting interrupts (#2132)
Also fixes DigitalOutput not closing correctly.
2019-11-25 21:43:58 -08:00
sciencewhiz
6ceafe3cd0 Fix class reference for logger (#2123) 2019-11-23 07:47:02 -08:00
Peter Johnson
b058dcf64e Catch exceptions generated by OpenCV in cscore JNI (#2118) 2019-11-22 08:12:17 -08:00
Tyler Veness
0b9307fdf3 Remove unused parts of .styleguide files (#2119) 2019-11-22 06:34:58 -08:00
Peter Johnson
39be812b2e Fix C++ ArmFeedforward (#2120) 2019-11-22 06:31:32 -08:00
Oblarg
21e957ee42 Add DifferentialDrive voltage constraint (#2075) 2019-11-21 21:43:02 -08:00
Oblarg
e0bc97f66b Add ProfiledPIDSubsystem example (#2076) 2019-11-21 20:55:16 -08:00
Modelmat
3df44c874d Remove Rotation2d.h wpi/math include (#2117) 2019-11-21 19:54:29 -08:00
CTT
a58dbec8aa Add holonomic follower examples (#2052) 2019-11-21 19:52:56 -08:00
Tyler Veness
9a8067465c Fix incomplete .styleguide (#2113)
Also clean up other .styleguides.

Fixes #2111.
2019-11-20 22:44:18 -08:00
Tyler Veness
ffa4b907c0 Fix C++ floating point literal formatting (#2114)
Found formatting errors with this regex
"([^a-z0-9\.]\.[0-9]|[^a-z0-9\.][0-9]\.[^a-z0-9\.])" and ignored false
positives.

Fixes #2112.
2019-11-20 21:48:15 -08:00
Oblarg
3d1ca856b2 Fix missing typename and return type (#2115) 2019-11-20 21:46:33 -08:00
Austin Shalit
5f85457a97 Add usage reporting for AddressableLED (#2108) 2019-11-20 20:13:39 -08:00
Austin Shalit
4ebae17123 Enforce leading/trailing zeros in Java numeric constants (#2105)
Enforce that integer literals must not have leading zeros and that floating point literals must have leading or trailing zeros in Java.
2019-11-20 20:13:15 -08:00
Oblarg
fa85fbfc1c Template C++ TrapezoidProfile and ProfiledPIDController on units (#2109) 2019-11-20 20:11:46 -08:00
Thad House
f62e23f1af Add Doxygen for new HAL interfaces (#2110) 2019-11-20 16:21:07 -08:00
Thad House
5443fdabc1 Directly construct PWM port from HAL, avoid wpilib PWM object (#2106) 2019-11-20 14:48:14 -08:00
Austin Shalit
c0e36df9d8 Standardize on PWMVictorSPX in examples (#2104) 2019-11-19 21:48:22 -08:00
Oblarg
8c4d9f5415 Add TrapezoidProfileSubsystem (#2077)
Adds a subsystem that continually runs a TrapezoidProfile, for composition with offboard PID controllers.
2019-11-19 12:38:42 -08:00
Prateek Machiraju
45201d15fc Add encoder distance overload to DifferentialDriveOdometry (#2096)
Also force encoders to be reset to zero on pose reset.
2019-11-19 09:56:34 -08:00
Tyler Veness
845aba33fe Make feedforward classes constexpr (#2103)
ArmFeedforward::Calculate() can't be made constexpr because std::cos()
and thus units::math::cos() is not constexpr.

Fixes #2101.
2019-11-19 06:47:59 -08:00
Thad House
500c43fb84 Add examples for DMA, DutyCycle, DutyCycleEncoder and AddressableLED (#2100) 2019-11-18 22:12:17 -08:00
Prateek Machiraju
5891628112 Use DifferentialDriveWheelSpeeds in RamseteCommand ctor (#2091) 2019-11-18 22:11:05 -08:00
Thad House
b37b68daaf Add JRE deployment to MyRobot Deploy (#2099) 2019-11-18 19:52:56 -08:00
Oblarg
0e83c65d27 Fix small logic error in ParallelDeadlineGroup (#2095) 2019-11-18 15:33:45 -08:00
Thad House
6f6c6da9f5 Updates to addressable LED (#2098)
Only PWM Headers are supported, so enforce that.

Also fixes some init checks and init order checks.
2019-11-18 15:25:04 -08:00
Thad House
1894219ef6 Fix devmain package in commands (#2097) 2019-11-18 15:24:04 -08:00
Peter Johnson
77a9949bbf Add AddressableLED simulation GUI support 2019-11-18 00:51:59 -08:00
Peter Johnson
a4c9e4ec28 Add AddressableLED simulation support 2019-11-18 00:51:59 -08:00
Thad House
8ed2059074 Add AddressableLED (#2092) 2019-11-17 16:39:38 -08:00
Thad House
59507b12dc Bump to 2020 v7 image (#2086) 2019-11-15 21:51:31 -08:00
Peter Johnson
5d39bf8065 Make halsimgui::DrawLEDs() values parameter const (#2088) 2019-11-15 20:29:51 -08:00
Prateek Machiraju
841ef91c0f Use gyro angle instead of robot angle for odometry (#2081)
The odometry classes previously took in the robot angle as an argument, meaning that users had to take care of offsetting the gyro themselves to accurately report the robot angle. This change will make it so that users will not have to worry about resetting gyros and adding offsets themselves, as this will be handled by the odometry classes.
2019-11-15 17:34:10 -08:00
Tyler Veness
1b66ead49d Use standard constant for pi instead of 3.14 (#2084) 2019-11-15 17:33:18 -08:00
Thad House
db2c3dddd7 Use DMA Global Number for DMA Index (#2085) 2019-11-15 17:32:29 -08:00
Thad House
82b2170feb Add DMA support to HAL and WPILibC (#2080) 2019-11-14 22:52:34 -08:00
Thad House
8280b7e3af Add DutyCycleEncoder and AnalogEncoder (#2040) 2019-11-14 22:51:33 -08:00
Thad House
5510960068 Use kNumSystems for DutyCycle count in Ports (#2083) 2019-11-14 12:15:47 -08:00
Thad House
df10652183 Remove release configs of deploy in MyRobot (#2082)
Bug in lower level library causes having both be broken. So for now just removed release.

Issue created in low level library to fix
2019-11-14 12:15:36 -08:00
Thad House
bf5388393e Add deploy options to myRobot (#2079)
Will only deploy to USB by default, and will not deploy the JRE, but will deploy a Java app.
2019-11-13 22:45:19 -08:00
Thad House
b7bc1ea745 Update to 2020v6 image (#2078) 2019-11-13 21:35:52 -08:00
Thad House
708009cd20 Update to gradle 6.0 (#2074) 2019-11-12 17:14:04 -08:00
Thad House
3cce61b89f Add SmartDashboard::GetEntry function in C++ (#2064)
Existed in Java already.
2019-11-12 17:11:32 -08:00
CTT
565e1f3e79 Fix spelling in MecanumDriveOdometry docs (#2072) 2019-11-11 23:25:09 -08:00
Peter Johnson
1853f7b6b7 Add timing window to simulation GUI
This shows the FPGA time and notifier timing, and has buttons to
start/pause/step the simulation.

The GUI also pauses DS new data notifications when paused.  This could be
done globally instead by blocking NotifyNewData at the HAL level?
2019-11-11 22:03:29 -08:00
Peter Johnson
c5a0497124 Add simulation pause/resume/step support
Calling HALSIM_PauseTiming pauses the FPGA clock and notifiers.
Calling HALSIM_ResumeTiming resumes the FPGA clock and notifiers.
Calling HALSIM_StepTiming steps the FPGA clock and runs applicable notifiers.

This will effectively pause TimedRobot and any other notifier-based events,
but of course will not pause user threads that do not use the notifier (e.g.
image processing).
2019-11-11 22:03:29 -08:00
Peter Johnson
f5446c7409 Add Notifier HALSIM access 2019-11-11 22:03:29 -08:00
Peter Johnson
3e049e02f0 Add name to HAL Notifier 2019-11-11 22:03:29 -08:00
David Vo
2da64d15f6 Make usage reporting enums type match (#2069)
This changes the C++ HALUsageReporting enums to have an
explicit type which matches the HAL_Report parameter
types.  In practice this shouldn't change much except
for tooling that might be parsing this header.
2019-11-11 21:38:49 -08:00
David Vo
f04d95e50f Make FRCUsageReporting.h C-compatible (#2070)
Now that HAL_Report has been moved into FRCUsageReporting.h,
this should also be C-compatible.

This also removes the C++ ifdef guard in HAL.h.
2019-11-11 21:38:24 -08:00
sciencewhiz
d748c67a54 Generate docs for command libraries and fix doclint enable (#2071) 2019-11-11 21:38:04 -08:00
Prateek Machiraju
55a7f2b4ad Add template for old command-based style (#2031) 2019-11-10 23:20:33 -08:00
CTT
486fa9c696 Add XboxController examples for arcade and tank drive (#2058) 2019-11-10 22:53:17 -08:00
Oblarg
e3dd1c5d77 Fix small bug in SplineHelper (#2061)
Also add comments for clamped cubic solution.
2019-11-10 22:52:24 -08:00
Oblarg
7dc7c71b58 Add feedforward components (#2045)
Add helper classes for computing feedforwards with parameters supplied by the characterization tool.
2019-11-09 20:16:42 -08:00
Oblarg
5f33d6af12 Fix ProfiledPIDSubsystem parameter name (#2017)
Change from goal to setpoint (these are two different things).
2019-11-09 09:16:50 -08:00
sciencewhiz
94843adb8f Standardize documentation of Speed Controllers bounds (#2043)
Some were in constructor docs, some in init function docs, and some
inline in code. Move them all to class docs.
2019-11-09 09:14:53 -08:00
Thad House
9bcff37b93 Add HAL specific version of wpi_setError (#2055)
Cleans up error writing, and allows fewer headers to be included in many of the wpilibc cpp files.

This removes all usages of the hal/HAL.h header.
2019-11-08 22:53:20 -08:00
Thad House
326aecc9a0 Add error message for CAN Write Overrun (#2062) 2019-11-08 22:51:11 -08:00
Oblarg
00228678d4 Add requirements param to more Command APIs (#2059)
Assorted improvements to the ergonomics of declaring requirements in the new
command framework. C++ requirements list parameters have been defaulted
to an empty list, some missing C++ requirements list parameters have been
added, and both C++ and Java have been given requirements list params in
various InstantCommand wrapper methods (#2049), whose value is
forwarded to the command.
2019-11-08 18:30:30 -08:00
Thad House
ff39a96cee Make DigitalOutput a DigitalSource (#2054)
It's perfectly safe to use as a DigitalSource, and can enable some cool tricks.
2019-11-07 20:03:43 -08:00
Thad House
5ccad2e8a4 Fix frc2::Timer returning incorrect timestamp values (#2057) 2019-11-07 20:02:27 -08:00
Thad House
629e95776a Add VendorDeps JSON files for command libraries (#2048)
Add commandversion flag to the examples and templates json files.
2019-11-07 17:38:07 -08:00
Thad House
6858a57f72 Make notifier command tests a lot more lenient (#2056)
They don't need to be testing timing, just that the command starts and stops.
2019-11-07 17:26:29 -08:00
Thad House
0ebe32823a Fix MyRobotStatic accidentally linking to shared command libs (#2046) 2019-11-06 14:06:04 -08:00
Thad House
384d00f9e6 Fix various duty cycle bugs (#2047) 2019-11-06 14:05:25 -08:00
Thad House
1f6850adf2 Add CAN Manufacturer for Studica (#2050) 2019-11-06 14:04:27 -08:00
Peter Johnson
7508aada93 Add ability to end startCompetition() main loop (#2032)
This is useful for both cleanly exiting from simulation and for unit testing
at a framework level.

This change required removing move constructor/assignment from IterativeRobot.
2019-11-05 21:33:09 -08:00
Peter Johnson
f5b4be16db Old C++ Command: Make GetName et al public (#2042)
These used to be effectively public due to SendableBase, and are public
in the Java version.
2019-11-05 20:53:40 -08:00
Peter Johnson
e6f5c93ab1 Clean up new C++ commands (#2027)
- Remove use of std::set. The only place std::set was actually used was in ParallelRaceGroup,
but this was of minimal utility as ParallelRaceGroup checked for duplicate subsystem
requirements, so it would be very unusual to end up with duplicate commands
in any case; replaced it with a vector.
- Remove use of std::unordered_map except for SelectCommand. Replaced with vector.
- Use pImpl idiom for CommandScheduler
- Minimize include files (remove unnecessary ones)
- Reformat include file order for consistency
2019-11-05 20:52:49 -08:00
Thad House
39f46ceab6 Don't allow rising and falling values to be read from AnalogTrigger (#2039)
They can't be caught from user code
2019-11-05 20:42:01 -08:00
Thad House
d93aa2b6b2 Add missing lock in FRCDriverStation (#2034)
Switch newDataCounter to atomic
2019-11-05 20:41:16 -08:00
Austin Shalit
114ddaf81f Fix duplicate encoders in examples (#2033) 2019-11-03 09:08:05 -08:00
Peter Johnson
f22d0961e3 Sim GUI: Add duty cycle support 2019-11-02 21:43:57 -07:00
Peter Johnson
3262c2badb Sim GUI: Use new multi-channel PDP getter function 2019-11-02 21:43:57 -07:00
Peter Johnson
96d40192ae Revert accidental change to MyRobot.cpp (#2029) 2019-11-02 21:06:22 -07:00
carbotaniuman
ed30d5d40e Add JSON support for Trajectories (#2025) 2019-11-02 11:35:03 -07:00
Peter Johnson
2b6811eddb Fix null pointer dereference in C++ CommandScheduler (#2023)
Java has a null check that was missing in C++ when adding default commands.
2019-11-01 23:42:01 -07:00
Thad House
1d695a1660 Add FPGA Duty Cycle support (#1987) 2019-11-01 23:41:30 -07:00
Thad House
509819d83f Split the two command implementations into separate libraries (#2012)
This will allow us at the user code side to determine to include old commands, new commands or both.
2019-11-01 21:58:54 -07:00
Thad House
2ad15cae19 Add multi PDP getter and sim PCM/PDP multi arg functions (#2014) 2019-11-01 21:55:35 -07:00
Thad House
931b8ceefd Add new usage reporting types from 2020v5 (#2026) 2019-11-01 21:54:17 -07:00
Tyler Veness
0b3821eba3 Change files with CRLF line endings to LF (#2022) 2019-11-01 20:26:05 -07:00
Thad House
6f159d1426 Add way to atomically check for new data, and wait otherwise (#2015) 2019-11-01 17:09:28 -07:00
Austin Shalit
a769f1f227 Fix bug in RamseteCommand (using degrees instead of radians) (#2020) 2019-11-01 13:21:02 -07:00
Oblarg
c5186d8159 Clean up PIDCommand (#2010)
PIDCommand uses a function based (callback) model, so functions designed for use in derived classes are of limited utility.
2019-11-01 13:11:55 -07:00
Oblarg
9ebd23d61e Add setVoltage method to SpeedController (#1997)
Add a voltage-compensated setVoltage method to SpeedController, which is sorely needed to help teams use feedforward-based controls effectively. Also uses correct units on the cpp side.

Also update relevant examples.
2019-11-01 09:32:40 -07:00
Prateek Machiraju
f6e311ef86 Fix SplineHelper bug (#2018)
Add unit test to check interior waypoints
2019-11-01 09:28:11 -07:00
Oblarg
f33bd9f050 Fix NPE in RamseteCommand (#2019) 2019-11-01 09:26:48 -07:00
Thad House
1c1e0c9a6a Add HAL_SetAllSolenoids to sim (#2004) 2019-10-30 21:29:35 -07:00
Thad House
ea9bb651a3 Remove accidental OpenCV link from wpilibc shared library (#2013) 2019-10-30 21:28:45 -07:00
Oblarg
cc07425182 Change command decorators to return implementation (#2007)
Changes Command decorators to return actual implementation classes rather than Commands. Previously, decorated commands were not Sendable, which was a problem. Also, there's no real reason not to expose the implementation details here, as we're extremely unlikely to change the implementations in the future.
2019-10-30 21:28:08 -07:00
Thad House
16b34cce20 Remove IterativeRobot templates (#2011)
With the class being deprecated, new projects shouldn't be created with it
2019-10-30 21:26:30 -07:00
Thad House
669127e49c Update intellisense to work with Beta 2020 code (#2008)
Needed to fix case when both rio and raspbian compilers installed, along with C++17 intellisense.
2019-10-29 21:36:13 -07:00
Thad House
9dc30797e4 Fix usage reporting indices (#2009)
According to NI, 0 is unspecified, and all the indices need to be
index + 1, so the first index becomes 1.
2019-10-29 21:34:10 -07:00
Thad House
f6b844ea30 Move HAL Interrupt struct to anonymous namespace (#2003) 2019-10-28 22:32:28 -07:00
Thad House
a72f809911 Add extern C to DigitalGlitchFilterJNI (#2002) 2019-10-28 22:30:04 -07:00
Thad House
916596cb01 Fix invalid examples json, add validator (#2001) 2019-10-28 20:10:05 -07:00
Peter Johnson
5509a8e968 Use constexpr for all example constants
Also make DifferentialDriveKinematics constructor constexpr.
2019-10-28 09:19:41 -07:00
Peter Johnson
0be6b64756 Use constexpr for DifferentialDriveKinematics 2019-10-28 09:19:41 -07:00
Thad House
936627bd94 wpilibc: Remove direct CameraServer dependency (#1989)
This makes linking easier, particularly for third party vendors and other language wrappers.
2019-10-27 08:37:30 -07:00
Prateek Machiraju
8e333c0aad Use FPGA Time instead of wall clock time for odometry (#1996) 2019-10-27 07:57:35 -07:00
sciencewhiz
d4430b765e Gearsbot example: Use standard argument order (#1995)
The convention is to put the subsystem last.
2019-10-27 06:28:29 -07:00
Oblarg
75438ab2ce Add RamseteCommand (#1951) 2019-10-26 21:33:41 -07:00
Thad House
989df1b461 Bump Native Utils and OpenCV dependencies (#1993)
OpenCV doesn't change anything other then the hash file. NativeUtils is needed to get the newest compiler.
2019-10-26 16:21:29 -07:00
Oblarg
dbc33b61e1 Fix Timer usage in TrapezoidProfileCommand (#1992) 2019-10-26 12:50:30 -07:00
Oblarg
79f8c5644a Add TrapezoidProfileCommand (#1962) 2019-10-26 09:58:13 -07:00
Prateek Machiraju
9440edf2b5 Refactor TrajectoryGenerator (#1972) 2019-10-26 09:39:47 -07:00
Oblarg
73a30182c3 Add frc2::Timer (#1968)
This is a unit-safe version of frc::Timer.
Undo previous (#1815) deprecation of parts of frc::Timer.
2019-10-26 08:21:40 -07:00
Banks T
36ea865edc Add toString for geometry and trajectory classes (#1991) 2019-10-26 08:18:56 -07:00
Oblarg
cbe05e7e8a Update ProfiledPIDController API (#1967) 2019-10-24 20:37:55 -07:00
Tyler Veness
d04eb35465 Deprecate old PID classes (#1964)
PIDBase was only used by the old PIDController, which is deprecated.
PIDInterface is only used by PIDBase, and that's deprecated by this
commit.
2019-10-24 20:32:31 -07:00
Thad House
02264db69c Add JNI dependencies to myRobotCpp (#1980)
That way it's a bit easier to test the Java builds.
2019-10-24 20:31:07 -07:00
Banks T
2a76c996eb Use VID/PID detection for PS3Eye (#1977) 2019-10-24 20:28:21 -07:00
Thad House
a3820bbdfa Remove HAL_BaseInitialize (#1981) 2019-10-24 20:26:11 -07:00
Thad House
a83fb47933 Update to 2020v5 image (#1983)
* Update to 2020v5 image
2019-10-24 12:14:22 -07:00
CTT
4b0ed910ee Make SwerveDriveKinematics.toChassisSpeeds() public (#1976) 2019-10-24 09:13:04 -07:00
Thad House
103c1b121c Remove DS caching from the HAL level (#1971)
With updates to netcomm, this is no longer required.
2019-10-23 20:25:07 -07:00
Peter Johnson
6635ea75ee Fix NPE in SendableRegistry.foreachLiveWindow() (#1974) 2019-10-22 21:12:07 -07:00
sciencewhiz
cfe23c5cd0 Fix grammar error in comment for configureButtonBindings (#1969) 2019-10-22 19:59:15 -07:00
Thad House
4bde2654e2 Fix mac azure build (#1973)
Build was broken due to an azure image change.
2019-10-22 19:58:48 -07:00
Prateek Machiraju
4f034e6c14 generateTrajectory: default reversed param to false (#1953) 2019-10-21 16:21:46 -07:00
Peter Johnson
acf960f729 Sim GUI: Add option to disable outputs on DS disable 2019-10-21 16:16:17 -07:00
Peter Johnson
2d3dac99f0 Sim GUI: Handle low resolutions and scale default window positions
Low resolutions result in a maximized window and forced user scaling down
(by default, can still be changed by the user).
2019-10-21 16:16:17 -07:00
Peter Johnson
07c86e0cd5 Sim GUI: Support High DPI monitors
Add user setting for scaling on top of DPI scaling.
Add user setting for visual style (light/dark/normal).
Save window position, size, maximized state, scale, and style to ini file.
2019-10-21 16:16:17 -07:00
Peter Johnson
46ad95512e SimDeviceData: Add missing null check 2019-10-21 16:16:17 -07:00
Peter Johnson
5bce489b98 Add ProggyDotted font to imgui (both cmake and gradle) 2019-10-21 16:16:17 -07:00
Peter Johnson
55af553acc Simulation GUI: Map gamepad the same way as DS 2019-10-21 16:16:17 -07:00
Peter Johnson
c59f9cea5f CameraServer: Add VID/PID support for Linux USB devices (#1960) 2019-10-20 14:12:00 -07:00
carbotaniuman
3fc89c84d6 Make splinePointsFromSplines public (#1963) 2019-10-20 14:11:17 -07:00
Peter Johnson
2c50937975 Fix implicitly deleted move constructors (#1954)
These were incorrect and exhibited as warnings on more recent versions of
clang (notably on Mac).

- Use pointers instead of references internally in GenericHID and *Drive
- Leave PIDBase, PIDController, and Resource non-moveable
- Remove the atomic from m_disabled in NidecBrushless
- Make Timer and Trigger copyable as well as moveable
- Implement custom move constructor/assignment for SendableChooserBase

Also comment out some unused variables that caused clang warnings.
2019-10-19 11:36:44 -07:00
Peter Johnson
f3ad927f45 Update Java SmartDashboard and LiveWindow to match C++ 2019-10-19 11:36:24 -07:00
Peter Johnson
05c25deb7b Fix move handling of C++ Sendable in SmartDashboard and LiveWindow 2019-10-19 11:36:24 -07:00
Peter Johnson
d726591ce4 Fix Gazebo sim plugin build (#1959) 2019-10-19 11:35:56 -07:00
Peter Johnson
2ff694fa49 Unbreak gradle build when other compilers installed (#1958)
There was dependency breakage in halsim_gui, which is only available on desktop.
2019-10-19 09:50:49 -07:00
Oblarg
53816155ba Improve command decorator names (#1945) 2019-10-19 08:13:33 -07:00
Peter Johnson
a38f183a98 Fix GenResources.cmake so it's usable in a submodule (#1956)
This is only important for projects that reference this repo as a submodule.
2019-10-18 17:24:47 -07:00
Peter Johnson
b3398dca39 Set gradlebase correctly for all examples (#1950) 2019-10-18 11:39:31 -07:00
Banks T
2c311013d4 Add Aarch64Bionic platform detection (#1922) 2019-10-18 08:03:48 -07:00
Prateek Machiraju
c10f2003c5 Add generateTrajectory overload (#1944)
Add an overload for the generateTrajectory method that accepts a DifferentialDriveKinematics instance instead of a list of constraints. This instance is used to automatically create a DifferentialDriveKinematicsConstraint behind the scenes, saving the user some verbosity.
2019-10-18 08:02:42 -07:00
Prateek Machiraju
63cfa64fb3 Add getters for pose in odometry classes (#1943) 2019-10-18 07:58:22 -07:00
Oblarg
2402c2bad7 Fix C++ command group recursive constructor bug (#1941)
Passing command groups as lvalue-references to other command groups should be illegal, as their copy constructors have been deleted. However, copy constructors are const-qualified. This led to a very obscure bug where passing a command group by lvalue to another command group would result in a valid template expansion 'looking like' a copy constructor, and being preferred to the deleted copy constructor. This would result in constructor recursion (the expanded constructor would, in an attempt to call the copy constructor, call itself), and an eventual segfault when the stack inevitably overflowed.

This fixes the problem by explicitly deleting the problematic constructor signature - attempting to do this now (correctly) generates a compilation error.
2019-10-18 07:57:43 -07:00
Oblarg
f4eedf597f Fix ConcurrentModificationException in CommandScheduler (#1938) 2019-10-18 07:56:12 -07:00
Matt
bb0b207d2f Fix array out of bounds exception caused by parallel race group (#1935)
The current index would be set to -1 by the execute method of ParallelRaceGroup,
and then an index out of bounds exception would be thrown by the end() method of
SequentialCommandGroup. This change bound checks the current command index as well
as only calls end at the end of parallel race group rather than during execute.
2019-10-18 07:55:14 -07:00
sciencewhiz
7bd69e591c Fix typo in temperature (#1940) 2019-10-14 16:16:30 -07:00
Thad House
ec9738245d Bump to 2020 v4 image (#1931) 2019-10-10 10:11:59 -07:00
Thad House
46303a8221 Add messaging to extension loading in the HAL (#1926) 2019-10-09 22:25:02 -07:00
sciencewhiz
d169d6be9e Set extract_static for Doxygen config so that static members show up (#1930)
Update Doxygen to 1.8.16
2019-10-09 22:24:45 -07:00
Thad House
4e183eb104 Bump to 2020 v3 image (#1929) 2019-10-09 22:24:17 -07:00
Peter Johnson
84c185803d LiveWindow: catch errors in callback/builder functions (#1921)
This prevents LiveWindow bugs from crashing the entire robot program.
Instead, an error is printed and the object is removed from LiveWindow.
2019-10-09 22:22:30 -07:00
Thad House
0e3b0f3da7 Remove deprecated free() calls (#1925)
Replaced with the standard close()
2019-10-08 21:30:33 -07:00
Thad House
7f839b87ce Remove timeouts from azure builds (#1924)
Windows builds are occasionally crossing 1 hour and failing
2019-10-07 20:47:01 -07:00
Thad House
45b766a5dc Fix main thread ID being potentially incorrect for simulation (#1923) 2019-10-07 20:45:33 -07:00
Banks T
56d782b16c Add secondary camera name for PS3Eye (#1920) 2019-10-06 22:18:49 -07:00
Peter Johnson
2b4894038e Add simulation GUI plugin
This uses Dear Imgui to provide a cross-platform integrated GUI for robot
simulation. The GUI provides fully integrated DS and joystick support so it's
not necessary to run the official DS.
2019-10-06 17:28:39 -07:00
Peter Johnson
f97d16073a Add imgui build to cmake 2019-10-06 17:28:39 -07:00
Peter Johnson
55a844a3e1 HAL sim: Add encoder channel B access 2019-10-06 17:28:39 -07:00
Peter Johnson
10deba8546 Remove sendables from SendableRegistry when close() is called (#1917)
This only affected Java (C++ RAII doesn't have the same problem).

Needed to add close/AutoCloseable to several classes to add this behavior.
2019-10-05 23:42:53 -07:00
Peter Johnson
a9f0e46680 Implement sim devices for ADXL345, ADXL362, ADXRS450, Ultrasonic
This makes the halsim_adx_gyro_accelerometer simulation plugin and
the accelerometer part of lowfi_simulation obsolete.
2019-10-05 22:39:00 -07:00
Peter Johnson
aa90645865 Add ability to associate other devices with a SimDevice
Implemented only for AnalogInput, DIO, and Encoder.
2019-10-05 22:39:00 -07:00
Peter Johnson
81c2c8a7de Add simulation generic device/value support
This allows high-level library classes to implement enhanced simulation
support even if no low-level corresponding simulation library exists, and
avoids the need for bit-banging complex interfaces like SPI or CAN.
2019-10-05 22:39:00 -07:00
Peter Johnson
e8d6f8a2c1 Move mockdata/HAL_Value.h to hal/Value.h
Also prefix the MakeBoolean et al functions with HAL_ to avoid namespace
pollution.
2019-10-05 22:39:00 -07:00
Peter Johnson
1b266717a8 Add simulation module support to cmake build (#1906) 2019-10-04 19:08:57 -07:00
Thad House
fb8f3bd06b Add testbench yaml file (#1915) 2019-10-04 15:09:35 -07:00
Thad House
846d8def00 Update to 2020 v2 image (#1913)
* Update to 2020 v2 image
2019-10-02 13:14:30 -07:00
Thad House
d6ac6e512b Fix PortForwarder package declaration (#1912) 2019-09-30 15:13:09 -07:00
Banks T
2271570860 Fix PS3Eye exposure setting (#1911) 2019-09-30 15:09:39 -07:00
Peter Johnson
885744d7e1 Add myRobot C++ version to cmake build (#1907) 2019-09-29 20:36:28 -07:00
sciencewhiz
366091fa87 Document that ConditionalCommand requires all subsystems (#1909)
Fixes #1683
Fixes typo
2019-09-29 20:35:41 -07:00
sciencewhiz
c58b072c89 Fix Drive usage reporting order (#1908)
Fixes #1893
2019-09-29 20:35:04 -07:00
sciencewhiz
762c88adb8 Update compiler versions in readme (#1905) 2019-09-29 16:56:11 -07:00
Tyler Veness
af8ce568d1 Add Ramsete unicycle controller (#1790) 2019-09-29 16:48:12 -07:00
Tyler Veness
b2c2934d05 Fix javadoc warnings about invalid usage of ">" (#1904)
The trajectory gen docs use "->". ">" has been replaced with "&gt;".
2019-09-29 16:38:48 -07:00
Tyler Veness
cce26ec78e Replace CRLF line endings with LF (#1902) 2019-09-28 19:55:50 -07:00
Thad House
cb54602d49 Add support for writing RTR CAN Frames to the CAN API (#1900) 2019-09-28 16:49:34 -07:00
Thad House
9f740e5905 Use OS for serial port instead of NI VISA (#1875) 2019-09-28 16:49:11 -07:00
Peter Johnson
b23baf611a Add ability to run robot main loop in a separate thread (#1895)
Default behavior is still to run the robot main loop in the main thread.

The ability to run the robot main loop in a separate thread and add a hook
for running a different function in the main thread is needed for simulation
GUI support on some platforms.
2019-09-28 15:43:24 -07:00
Prateek Machiraju
457f94ba26 Add trajectory generation using hermite splines (#1843) 2019-09-28 15:40:56 -07:00
Thad House
fd612052f3 Update native utils to use new frchome directory (#1884) 2019-09-28 15:40:02 -07:00
Thad House
8858ec55c7 Remove periodic can read call (#1868)
It is not necessary anymore, and is a complicated and confusing API to keep around.
2019-09-28 15:38:58 -07:00
CodingWithFusion
41efb8015d Update CANAPITypes.h (#1860)
Add Playing With Fusion to CAN manufacturer list.
2019-09-28 15:33:18 -07:00
Thad House
c93be1b2d5 Remove LabVIEW HAL support (#1901) 2019-09-28 15:31:43 -07:00
Thad House
680f8919ed Remove eigen, units and libuv from doxygen generation (#1898) 2019-09-28 08:28:31 -07:00
Thad House
c5812524f8 Bump GradleJNI plugin version (#1899)
Fixes an issue where the symbol check task doesn't always run.
2019-09-28 08:28:02 -07:00
Peter Johnson
971303da8c Add PortForwarder class (#1890)
This class provides an easy way to forward local ports to another host/port.
This is primarily useful to provide a way to access Ethernet-connected devices
from a computer tethered to the RoboRIO USB port.

The most natural spot to put the shared implementation of this class was into
wpiutil, so a wpiutilJNI library has been added.
2019-09-26 22:53:21 -07:00
hjelstromboli
50db77bf25 Fix wpiutil cmake eigen install source directory (#1891) 2019-09-16 12:54:13 -05:00
Oblarg
85d42c1993 C++ PIDCommand: Add GetMeasurement() and UseOutput() (#1892)
These are in the Java version but were missed in C++.
2019-09-16 12:53:03 -05:00
Prateek Machiraju
2dfbb855d7 wpilibj: Fix SwerveDriveKinematics ctor parameter name (#1889) 2019-09-15 14:53:21 -05:00
Peter Johnson
471f375a38 Simplify Sendable interface (#1864)
This removes the name and subsystem from individual objects, and instead
puts this data into a new singleton class, SendableRegistry.  Much of
LiveWindow has been refactored into SendableRegistry.

In C++, a new CRTP helper class, SendableHelper, has been added to provide
move and destruction functionality.

Shims for GetName, SetName, GetSubsystem, and SetSubsystem have been added
to Command and Subsystem (both old and new), and also to SendableHelper to
prevent code breakage.

This deprecates SendableBase in preparation for future removal.
2019-09-14 15:22:54 -05:00
Tyler Veness
1d8c4d016f Replace ::value and ::type with _v and _t suffixes (#1885) 2019-09-13 22:14:37 -05:00
Rishab Rao
a5650b9439 Add Units Utility class for Java (#1829)
Units conversion class to convert between commonly used units.

Co-Authored-By: Austin Shalit <austinshalit@gmail.com>
2019-09-12 13:38:25 -05:00
Tyler Veness
904479ad43 Deprecate GearTooth class for removal (#1878)
It only works with a specific sensor that isn't available anymore, the
class is a trivial wrapper around a Counter, and no one uses this class
according to FMS usage reporting.
2019-09-08 13:21:36 -05:00
Prateek Machiraju
86b666bba9 Add equality comparator to geometry classes (#1882) 2019-09-08 13:20:26 -05:00
Tyler Veness
62f07c182c Make one-arg Rotation2d constructor implicit (#1883)
Since a value in radians is always a rotation, it makes sense to provide
an implicit constructor for this for convenience with Pose2d's
constructor.
2019-09-08 13:15:07 -05:00
Prateek Machiraju
f405582f86 Add kinematics suite (#1787)
Co-authored-by: Tyler Veness <calcmogul@gmail.com>
Co-authored-by: Matt <matthew.morley.ca@gmail.com>
2019-09-07 23:11:49 -05:00
Tyler Veness
561cbbd144 Deprecate Filter class for removal (#1876) 2019-09-07 23:02:44 -05:00
Tyler Veness
84e2973aaa Remove unused include from Filesystem.h (#1877) 2019-09-07 23:01:57 -05:00
Thad House
f49859ebfd Remove NI VISA headers, as they are now included in NI Libraries (#1879) 2019-09-07 23:01:27 -05:00
Thad House
bc59db5e6f Rename DEBUG macro to DEBUG0 (#1871)
This avoids conflicts with the platform DEBUG macro on some platforms.
2019-09-06 20:45:52 -05:00
Thad House
dd928b4cbf Remove JNI logging (#1872) 2019-09-06 20:42:40 -05:00
Peter Johnson
3e0f7d0995 Use units for new NotifierCommand (#1869) 2019-09-04 22:54:49 -05:00
Thad House
5ffe15d5ff Remove ability to build all combined artifacts (#1867) 2019-09-04 13:06:46 -07:00
Thad House
516cbef2c4 Remove RoboRIO ifdef from simulation headers (#1859) 2019-09-03 19:55:17 -07:00
Tyler Veness
9b6ffc201c Replace SetOutputRange() with SetIntegratorRange()
If users are attempting to use the output range to limit the controller
action, they should use ProfiledPIDController instead. If they actually
intended to clamp the output, they should use std::clamp().
2019-09-03 19:46:59 -07:00
Tyler Veness
ff8b8f0a8a Remove percent tolerance from PID controller
It breaks the unit system badly; the tolerance member variable has
different units depending on percent vs absolute. Absolute tolerance is
a lot more natural than percent tolerance anyway.
2019-09-03 19:46:59 -07:00
Peter Johnson
0ca8d667d2 Clean up AutoCloseable and other Java warnings (#1866) 2019-09-03 19:44:24 -07:00
Tyler Veness
7112add67f Watchdog: use units::second_t instead of double (#1863)
Fixes #1827.
2019-09-03 15:58:31 -07:00
Peter Johnson
761bc3ef85 Change C++ WaitCommand to use units (#1865)
Also remove unique_ptr usage.
2019-09-02 23:39:51 -07:00
Tyler Veness
1fb3011235 Add MathUtils.clamp() for Java (#1861)
Also use std::clamp() and MathUtils.clamp() in as many places as
possible in place of custom clamp functions or if statements.
2019-08-28 23:24:30 -07:00
Peter Johnson
eb3e0c9c95 Fix cmake Eigen include directory (#1862)
This currently only breaks when cmake is configured with WITH_TESTS but
ultimately this would have affected wpilibc builds too.
2019-08-28 23:24:08 -07:00
Tyler Veness
2250b7fbe3 Rename GearsBotNew example to GearsBot 2019-08-28 22:08:59 -07:00
Tyler Veness
c9f9feff1f Replace deprecated API usage in C++ examples
Since there is a new version of GearsBot using the new command-based
API, the old GearsBot is just removed.

PR #1842 is being included to verify this PR is correct.
2019-08-28 22:08:59 -07:00
Dalton Smith
d6b9c7e148 CONTRIBUTING.md: Point to frc-docs instead of screensteps (#1858) 2019-08-28 22:08:17 -07:00
Thad House
d10a1a7977 Fix eigen build in vcpkg (#1856) 2019-08-27 14:38:23 -07:00
Tyler Veness
2bdb443255 Add frc2 includes to list of "other lib" regexes (#1855) 2019-08-26 23:11:07 -07:00
Sam Carlberg
4b2b21d247 Replace outdated Java collections (#508) 2019-08-26 22:47:18 -07:00
Thad House
8993ce5bf1 Move Eigen headers out of main include folder (#1854)
This allows using Eigen as a separate cmake package, e.g. for vcpkg.
2019-08-26 21:22:41 -07:00
LilTiger
0f532a1174 Add PWMSparkMax (#1751) 2019-08-26 20:29:20 -07:00
Thad House
f7ad363d86 Add jni cross compile options for aarch64 (#1853) 2019-08-26 11:56:35 -07:00
Thad House
9afea33403 Add support for aarch64 jetson bionic builds (#1844) 2019-08-26 09:49:58 -07:00
Peter Johnson
d787b5d609 Add more items to .gitignore (#1850)
- compile_commands.json
- .clang
- .clangd/
2019-08-25 23:30:04 -07:00
Peter Johnson
5dd0d1b7db Use units in SPI 2019-08-25 22:52:48 -07:00
Peter Johnson
07ac711b31 Fix units deprecated warning in IterativeRobot 2019-08-25 22:52:48 -07:00
Peter Johnson
decfd858b8 Correctly report -1 for POV on disconnected joystick (#1852) 2019-08-25 22:51:54 -07:00
Oblarg
076ed7770c Add new C++ Command framework (#1785)
This is the C++ version of #1682.

The old command framework is still available, but will be deprecated.

Due to name conflicts, the new framework is in the frc2 namespace.
Eventually (after the old command framework is removed in a future year)
it will be moved into the main frc namespace.
2019-08-25 20:55:59 -07:00
Peter Johnson
a0be07c370 Refactor HAL handle move construction/assignment (#1845)
A templated hal::Handle class is used to wrap handles to make them move-only.
This eliminates a lot of boilerplate move constructor/assignment code
in the main WPILib classes.  HAL_SPIPort and HAL_I2CPort are also wrapped.

The wrapper class does not implement destruction.  This would require the
wrapper class to be handle-specific (rather than generic) and would result
in more code added than it removed, plus would add header dependencies on
more HAL headers.  In addition, some HAL handle release functions are more
complex (e.g. have return values) and can't be easily mapped to a destructor.
2019-08-25 18:42:00 -07:00
Oblarg
558c383088 Add new Java Command framework (#1682)
The old command framework is still available, but will be deprecated.

Due to name conflicts, the new framework is in the wpilibj2 package.
Eventually (after the old command framework is removed in a future year)
it will be moved into the main wpilibj package.
2019-08-25 14:47:07 -07:00
Peter Johnson
1379735aff Delete RobotState and SensorUtil constructors (#1847) 2019-08-24 22:28:39 -07:00
Tyler Veness
e3d86fee46 Move circular buffer class from wpilib to wpiutil (#1840) 2019-08-24 21:35:19 -07:00
Peter Johnson
4cd8a56672 TimedRobot.cpp: Fix deprecation warning (#1846)
For both TimedRobot and IterativeRobotBase, use delegating constructors
to reduce code duplication.
2019-08-24 21:13:29 -07:00
Thad House
b2861f8948 Use 2020 artifacts and artifactory server (#1838)
Uses 2020 artifacts and artifactory server, and new versioning and repository plugins.
2019-08-22 21:48:43 -07:00
Thad House
98cc32703c Update to use artifactory to publish artifacts (#1833)
* Update to use artifactory to publish artifacts
2019-08-21 07:28:24 -07:00
Tyler Veness
fa06403000 Move drive integration tests into wpilibj/src/test (#1836)
Also move drive and controller tests into subfolders.
2019-08-20 21:05:38 -07:00
Thad House
e716c36b89 Fix Nat.java generation to be incremental (#1831)
Also generate the imports.
2019-08-20 21:03:44 -07:00
Thad House
9fd2b5e3fa Fix MSVC builds on cmake windows in vcpkg (#1835) 2019-08-19 20:28:48 -07:00
Redrield
7e95010a29 Add compile-time EJML matrix wrapper to wpiutil (#1804)
This adds a wrapper over EJML's SimpleMatrix that uses generated classes representing numbers to encode the dimensions of each matrix at compile time, and to check operations between matrices for validity at compile time, rather than failing with an exception at runtime. This is required for the Java implementation of state-space control.

Additions to the wpiutil gradle script, and a python script at the wpiutil root are used to generate numeric types from a template at build time for both gradle and cmake. Users will be able to access types through functions on the Nat class.
2019-08-18 15:00:40 -07:00
Tyler Veness
3ebc5a6d3a Add ProfiledPIDController 2019-08-16 23:47:02 -07:00
Tyler Veness
fc98a79dbb Clean up PIDController interface in preparation for ProfiledPIDController 2019-08-16 23:47:02 -07:00
Tyler Veness
fdc098267e Fix compilation error in elevator trapezoid profile example (#1826)
Merging #1815 broke it, then #1814 was merged before fixing the failure.
2019-08-16 23:04:12 -07:00
Oblarg
a3dd84e854 Make XBoxController Button enum public (#1823)
This allows using the raw button number in places where that is useful.
2019-08-16 22:21:49 -07:00
Tyler Veness
a216b9e9ee Add TrapezoidProfile example (#1814) 2019-08-16 22:03:44 -07:00
Prateek Machiraju
8f386f6bb3 wpilibc: Add unit-safety to C++ geometry classes (#1811) 2019-08-16 22:00:32 -07:00
Prateek Machiraju
c07ac23532 wpilibc: Add overloads for units (#1815)
Add unit-taking overloads to the following classes:
- IterativeRobotBase
- LinearFilter
- Notifier
- TimedRobot
- Timer (HasPeriodPassed only)
- frc2::PIDController

The corresponding non-units-taking functions have been deprecated.

The return value of TimedRobot::GetPeriod() was updated.
This is a breaking change, users should use to<double> to get the value in seconds.

Other return values, e.g. Timer::Get(), have NOT been updated due to much wider use.
2019-08-16 21:56:48 -07:00
Peter Johnson
f1d71da8a9 Move GetStackTrace and Demangle to wpiutil, add Windows support (#1819)
For Windows, import the StackWalker source (https://github.com/JochenKalmbach/StackWalker)
plus PR 35 in that repo, with a few simplifications to StackWalker.h.
2019-08-12 23:45:45 -07:00
Tyler Veness
ef037457e5 Make LinearFilter copyable and moveable (#1789) 2019-08-09 22:29:23 -07:00
Thad House
76930250c0 Remove objective-cpp support (#1816)
Was only there for mac usb cam support, but we likely won't get to it this summer anyway,
and its causing a breakage in the backing libraries with cross builds
2019-08-09 16:28:53 -07:00
Tyler Veness
1c246418f8 Move TrapezoidProfileTest to trajectory folder (#1812)
The newer controls stuff is using subfolders, so it makes sense for
consistency and reduced clutter.
2019-08-09 16:27:41 -07:00
Matt
95a54a0f29 Add java arcade drive example (#1810) 2019-08-09 16:19:33 -07:00
Thad House
a4530243e1 HAL sim: Fix incorrectly setting dio port to initialized on cleanup (#1813) 2019-08-09 16:14:46 -07:00
Austin Shalit
09d00a6227 Update Java examples to use new PIDController (#1809)
This also allows us to re-enable Werror.
2019-08-04 20:35:33 -07:00
Abiel Fernandez
ba9b517427 Add missing Java examples (#841) 2019-08-04 20:34:02 -07:00
Thad House
6411bd79c6 InterruptableSensorBase: Fix callback function deletion (#1807)
Save the callback function into a unique_ptr member instead.
2019-08-04 20:25:25 -07:00
Austin Shalit
810e58ea85 I2C: Add tip about writeBulk() to transaction() (#1806) 2019-08-04 01:16:38 -07:00
Peter Johnson
607d6c148a Fix wpilibj integration tests jar name (#1808) 2019-08-04 00:06:07 -07:00
Oblarg
c9873e81b2 Remove PIDControllerRunner and mutex from new PIDController (#1795)
Teams that wish to use it asynchronously may still do so - they simply need to handle the thread safety themselves (it is not that difficult, and can be done more cleanly in the calling code anyway).
2019-08-04 00:01:11 -07:00
Tyler Veness
98d0706de8 Fix cscore build with OpenCV 4 (#1803)
The main change in OpenCV 4 was removing its C APIs from OpenCV 1. If
the user has OpenCV 4, they have no way of obtaining the correct
arguments for cscore functions that require the C API. Therefore, we can
fix the build by just not compiling in functions reliant on the C API if
OpenCV 4 is being used.

OpenCV 3 builds should continue to work with this change.
2019-08-03 16:10:39 -07:00
Oblarg
fbe67c90c8 Make Sendable setters synchronous (#1799)
Instead of being called asynchronously by NetworkTables, they are now called by updateValues() synchronously with the main loop, just like the getters.
2019-08-03 15:08:06 -07:00
Oblarg
c67a488a09 Format SendableBuilderImpl javadocs (#1802) 2019-08-03 15:00:43 -07:00
Tyler Veness
8e93ce8929 Fix PIDControllerRunner member destruction order (#1801)
The mutexes in PIDControllerRunner are declared after the Notifier, and
when the PIDControllerRunner object is destructed, the member object
destructors are called in the reverse order in which they are declared.
The mutexes are destructed first, then the Notifier destructor is called
which stops the Notifier.

There's a window between those destructor calls during which the
Notifier can run the callable and attempt to lock a mutex that no longer
exists.

Declaring the Notifier after all the variables its callable uses fixes
this issue, as it ensures the Notifier is destructed first.
2019-08-03 14:58:10 -07:00
Redrield
c98ca7310f Add EJML dependency to wpiutil (#1769)
Add EJML as the Java library for linear algebra for use in wpilib. This is equivalent to Eigen for C++.

The EJML dependency is downloaded in cmake and pulled in via maven in the gradle build.
2019-08-03 14:24:14 -07:00
Oblarg
3b12276bc3 SendableBase: remove unnecessary synchronization (#1797)
Also fixes the move constructor to update LiveWindow to follow the move.
2019-08-02 23:47:17 -07:00
Oblarg
e6d348f382 Fix missing default name in Java PIDController (#1792) 2019-08-02 23:38:35 -07:00
Austin Shalit
df12fc2a86 Java cleanups (#1776)
* Remove extra ';'s
* Remove unnecessary conversions to String
* Use StandardCharsets object
* Replace infinite while with check for interrupted thread
* Remove redundant local vars
* Remove redundant throws clause
* Remove redundant primitive wrapping
* Fix malformed Nested class test
* Remove unnecessary unboxing
* Remove unnecessary explicit type argument
* Replace lambdas with method references
* Replace statement lambdas with expression lambdas
* Replace null check with method call
* Replace number comparison with method call
* Fix broken javadoc comments
* Replace Arrays.asList with singletonLists
* Remove excessive lambda usage
* Remove redundant string operation
* Remove redundant type casts
* Remove unnecessary returns
* Remove redundant suppressions
* Fix unresolved file reference
* static analysis fixes
2019-07-31 22:19:48 -07:00
Thad House
39561751fc Update GradleVSCode version (#1786)
Fixes compile_commands
2019-07-31 22:15:48 -07:00
Tyler Veness
37d316aa09 Add C++20 std::math constants shim (#1788)
Based on http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0631r7.pdf
2019-07-31 22:15:22 -07:00
Tyler Veness
dd43109596 Deprecate frc/WPILib.h (#1779)
It drastically increases compile times and is bad style. C++ users
should be including what they use. We don't necessarily have to remove
WPILib.h, but it should at least be deprecated.
2019-07-30 00:41:14 -07:00
Thad House
823174f30a Update native utils to 2020.0.4 (#1783)
Adds -latomic by default to all linux builds
2019-07-30 00:40:23 -07:00
Tyler Veness
37c6952663 Squelch -Wdeprecated-copy for Eigen with GCC >= 9 2019-07-30 00:39:47 -07:00
Tyler Veness
04c9b000ff Revert "Fix build of Eigen 3.3.7 with GCC 9"
-Wextra adds -Wdeprecated-copy, which Eigen emits. We're going to
squelch the warning instead to minimize changes to Eigen's upstream
sources.
2019-07-30 00:39:47 -07:00
Peter Johnson
ca3e71e214 wpiutil: Fix Process::Spawn() (#1778)
Was broken due to removal of ArrayRef initializer_list constructor.
2019-07-26 11:22:23 -07:00
Prateek Machiraju
d946d5a2bb Fix Eigen compilation errors and add tests (#1777) 2019-07-24 20:51:33 -07:00
Tyler Veness
8b1b9ac75a Fix build of Eigen 3.3.7 with GCC 9 2019-07-24 00:03:18 -07:00
Tyler Veness
2f680ba990 Add Eigen linear algebra library
This imports Eigen 3.3.7, which will be used by the wpilibc implementation of
state-space control and mecanum/swerve forward kinematics (the forward
kinematics requires least-squares solutions via a matrix pseudoinverse).

While Eigen has parts licensed under BSD, MINPACK, and MPL2, the files we need
are only MPL2.
2019-07-24 00:03:18 -07:00
Prateek Machiraju
a885db7d48 Make MotorEncoderTest use LinearFilter (#1775)
Closes #1774
This also eliminates the call to the deprecated setPIDSourceType method.
2019-07-23 23:59:06 -07:00
Prateek Machiraju
ee24101696 Add geometry classes (#1766)
These classes introduce ways to represent poses and provide easy ways to transform, rotate, and translate poses across 2d space. This classes will be especially useful for a planned odometry and kinematics suite.

Furthermore, these classes can also be used to simply represent waypoints on a field, do superstructure motion planning, etc.
2019-07-23 23:57:39 -07:00
Thad House
48fe54271a Add HALSIM_SetSendError implementation (#1773) 2019-07-23 23:55:51 -07:00
Peter Johnson
dff58c87f4 Fix unused warning in release build (#1771) 2019-07-21 22:17:42 -07:00
Tyler Veness
dde61aad32 Remove TimerEventHandler typedef from Notifier class (#1767)
Using std::function<void()> directly makes it much clearer to the user
what kind of function Notifier expects. The Doxygen comments already say
what the function is used for, so the typedef just discards useful
information.
2019-07-20 22:57:16 -07:00
Loki
0f6ef80ab2 Add RobotState#IsEStopped and DriverStation#IsEStopped (#952) 2019-07-16 09:18:23 -05:00
Austin Shalit
e488861877 Move unit tests from integration test suite (#1170) 2019-07-16 00:02:52 -05:00
Oblarg
dffa1a5cba Make null checks more descriptive (#1688) 2019-07-15 20:22:36 -05:00
Oblarg
fe59d854d5 Notifier: add null check (#1684) 2019-07-15 20:20:11 -05:00
Peter Johnson
10731f3d6b Update uv Udp wrapper for latest features 2019-07-15 20:15:37 -05:00
Peter Johnson
89f7b72b6e Update libuv to 1.30.1 release 2019-07-15 20:15:37 -05:00
Peter Johnson
85f2f87400 wpiutil: Add unique_function (#1761)
This is a move-only variant of std::function to support move-only captures.

Imported from LLVM with some small tweaks (changed to 4 pointer internal storage, warnings fixes).
2019-07-15 20:13:57 -05:00
Tyler Veness
73ec940786 Remove SampleRobot (#1658)
SampleRobot provides no benefits over RobotBase to advanced teams and
TimedRobot is recommended for everyone else.

A skeleton template for RobotBase was added.
2019-07-15 20:09:47 -05:00
Tyler Veness
62be0392b6 Replace std::lock_guard and std::lock with std::scoped_lock (#1758)
std::scoped_lock was introduced in C++17 and is strictly better than
std::lock_guard as it supports locking any number of mutexes safely.
It's also easier to use than std::lock for locking multiple mutexes at
once.
2019-07-08 22:58:39 -07:00
Tyler Veness
24d31df55a Make sure move constructor is generated for TrapezoidProfile (#1757)
This wasn't necessarily the case before because defining a nondefault
constructor results in no default move constructor.
2019-07-08 22:19:13 -07:00
Tyler Veness
841ef5d739 Remove template types from lock RAII wrapper usages (#1756)
C++17 has template type autodeduction. These wrappers include
std::lock_guard and std::unique_lock.
2019-07-07 19:17:14 -07:00
Tyler Veness
e582518bae Fix some move constructors (#1754)
Timer didn't have working move semantics because mutexes aren't
moveable, meaning the default implementations were ill-formed.
MotorSafety wasn't locking its mutex.
2019-07-07 19:15:59 -07:00
Peter Johnson
8757bc471b Remove pre-C++17 shims (#1752)
Now that all compilers support C++17, remove some old C++14/C++17 shims.
2019-07-07 15:44:43 -07:00
Tyler Veness
ea9512977c Add replacement PIDController class (#1300)
Originally, PIDController used PIDSource with its "PIDSourceType" to
determine whether a class should return position or velocity to the
controller. However, the supported languages have changed a lot over 10
years and now support lambdas. Instead of using PIDSource and PIDOutput,
users can pass in doubles to the Calculate() function synchronously.
This makes the controller much more flexible for team's needs as they no
longer have to make a separate PIDSource-inheriting class just to
provide a custom input.

The built-in feedforward was removed. Since PIDController is synchronous
now, they can add their own feedforward on top of what Calculate()
returns.

To facilitate running the controller asynchronously, there is a
PIDControllerRunner class that handles that. By separating the loop from
the control law, PIDController can now be composed with others and be
used to control a drivetrain (a multiple input, multiple output system
that requires summing the results from two controllers) much easier.
Also, motion profiling can be used to set the reference over time.

All the classes related to the old PIDController are now deprecated. The
new classes are in an experimental namespace to avoid name conflicts.

While this is a large change, I think it is a necessary one for growth.
The old PIDController design was created in a time when languages only
supported OOP, and we have more tools at our disposal now to solve
problems. This more versatile implementation can be used in more places
like as a replacement for Pathfinder's "EncoderFollower" class.

There has been hesitation to add lambda support to WPILib for a while
now out of concerns for requiring teams to learn more features of C++ or
Java. In my opinion, this change makes PIDController easier to use, not
harder. The concept of a function is a building block of OOP and should
be learned before classes. The ability to store functions as first-class
objects and invoke them just like variables is rather natural.

Note that PID constants for the new controller will be different from
the old one. The original controller didn't take the discretization
period into account. To fix this, teams should just have to divide their
Ki gain by 0.05 and multiply their Kd gain by 0.05 where 0.05 is the
original default period.
2019-07-07 15:37:13 -07:00
Tyler Veness
9b798d228f Add TrapezoidProfile class (#1673) 2019-06-30 23:25:11 -07:00
Thad House
804926fb5b Unconditionally skip athena builds for sim (#1748)
They'll pretty much never work
2019-06-30 19:45:33 -07:00
Tyler Veness
118e9d29d5 Add C++14 units library (#1749) 2019-06-30 19:44:51 -07:00
Tyler Veness
c705953d77 Add usage reporting to LinearFilter (#1750) 2019-06-30 19:44:15 -07:00
Thad House
852d1b9cad Don't cross-build gazebo for raspbian (#1747) 2019-06-30 12:42:32 -07:00
Peter Johnson
eedb3a1adc Fix GCC 9 warnings (#1730) 2019-06-30 00:28:32 -07:00
Peter Johnson
60dce66a4f Remove wpi::ArrayRef std::initializer_list constructor (#1745)
This can be dangerous as it refers to a temporary, and GCC 9.0 warns about
its use.  Instead add std::initializer_list overloads to common places it
was used in an initializer_list sense.
2019-06-29 23:54:02 -07:00
Thad House
9e19b29c31 Use base azure image for primary wpilib build (#1744)
This will ensure everything works with no flags, even without a rio or raspbian compiler
2019-06-29 21:37:34 -07:00
Thad House
2994250714 Update jni library, fix cross builds of the jni symbol check (#1742) 2019-06-29 21:31:55 -07:00
Thad House
a6b0e9b856 Only disable execution of cross compile google tests (#1741)
Still build them and link them, just don't execute them.

Google test is still disabled completely for the HAL and wpilibc.
2019-06-29 21:31:27 -07:00
Peter Johnson
3c2093119e Use docker container to run wpiformat (#1740)
Also update raspbian image to use new unified name.
2019-06-29 21:11:17 -07:00
Thad House
5fe2eebceb Revert "Don't build halsim_gazebo on raspbian (#1737)" (#1743)
This reverts commit d9cb57a429.
2019-06-29 21:05:44 -07:00
Peter Johnson
4b1b92bb74 Replace wpi::optional with C++17 std::optional (#1732)
Keep wpi/optional.h as a shim with deprecated warnings.
2019-06-29 11:20:22 -07:00
Peter Johnson
0fbb0d989e Update to 2020 compilers (#1733)
Also link to libatomic in cmake and for Raspbian only in gradle.
2019-06-29 09:28:28 -07:00
Thad House
2dc94e6052 Disable google tests on cross compilers (#1738)
Removes checks for onlyathena and onlyraspbian, and just disables gtest for cross compilers.
2019-06-29 09:27:11 -07:00
Peter Johnson
d9cb57a429 Don't build halsim_gazebo on raspbian (#1737)
Reference shared/config.gradle instead of shared/plugins/setupBuild.gradle.
2019-06-28 22:30:17 -07:00
Austin Shalit
f7cfdd7cee Replace crlf line endings with lf (#1731) 2019-06-28 20:55:14 -07:00
Austin Shalit
b6d5d90d9d Add JaCoCo Support (#1734) 2019-06-28 20:01:02 -07:00
Thad House
c7ab2baa6e Add way to disable the jni check tasks from a property (#1736) 2019-06-28 20:00:35 -07:00
Thad House
0c45c5b7ea Fix skip athena and skip raspbian flags (#1735) 2019-06-28 20:00:09 -07:00
Thad House
3dfb01d45b Update to new Native Utils (#1696)
Also update to azure 2019 windows image
2019-06-28 14:09:10 -07:00
Tyler Veness
30e936837c Clean up LinearDigitalFilter class (#782)
* Renamed LinearDigitalFilter to LinearFilter
* Filter base class removed since it wasn't useful
* C++: std::shared_ptr<> replaced with double parameter
2019-06-28 13:35:57 -07:00
Tyler Veness
311e2de4c1 Remove deprecated Joystick constants (#1715) 2019-06-26 14:17:11 -07:00
Benjamin Ward
c08fd6682f Update CAN manufacturer list (#1706) 2019-06-26 14:16:12 -07:00
Peter Johnson
258bba0c2d ErrorBase and WPIError improvements (#1727)
* ErrorBase: Use magic static singleton for globals
* ErrorBase: Add testability features for global errors
* Make WPIError definitions inline functions
(This works around cross-DLL variable issues on Windows)

Fixes #1726.
2019-06-23 20:36:52 -07:00
Peter Johnson
372ca4f456 cmake: Enable googletest unit tests (#1720)
Also don't inherit compile warnings from wpiutil

There's not a good way to disable inherited compiler flags.
2019-06-23 12:44:28 -07:00
Peter Johnson
223d47af0e HALSIM: support mocking of HAL_SendError() (#1728) 2019-06-23 11:48:04 -07:00
Peter Johnson
55cb683db4 Change compiler flags to C++17 (#1723)
The current versions of the RoboRIO and Raspbian compilers support the flag but have
minimal actual C++17 support.  Changing the flag is the first step.
2019-06-20 22:32:50 -07:00
Peter Johnson
ee8a33c568 wpiutil: SafeThread: Add thread id, support getting shared_ptr (#1722)
Rename base class function from GetThread to GetThreadSharedPtr.
2019-06-20 19:51:09 -07:00
Peter Johnson
61426d08de wpiutil: Signal: make operator() const (#1721)
This enables const-ness in uv::Handle ReportError() and Invoke() as well.
2019-06-20 17:51:32 -07:00
Tyler Veness
b630b63ef0 Remove functions in LiveWindow deprecated since 2018 (#1716)
The Java versions were already accidentally removed in #1059.
2019-06-14 18:52:10 -07:00
Peter Johnson
1d0c05d4f8 Styleguide fixes for #1718 (#1719) 2019-06-14 18:51:49 -07:00
Peter Johnson
f07569df19 Fix newer GCC/clang compiler warnings (#1718) 2019-06-14 18:32:27 -07:00
David Vo
0120f31247 C++ SPI: Fix SetClockRate to take int (#1717)
The Java version takes an int, and HAL_SetSPISpeed takes an int as well.
2019-06-12 06:04:52 -07:00
Thad House
c2829ed98e Configure gradle to ignore unresolved headers (#1711)
Work around Gradle's handling of libraries like eigen and opencv
which use macro includes.  Also completely disable incremental includes.
2019-06-11 21:48:32 -07:00
Thad House
221e66f46d Allow disabling static init of JNI libraries (#1672) 2019-06-10 22:29:32 -07:00
Thad House
738852e119 cmake: Add cross toolchain files for Rio and Pi (#1710) 2019-06-10 22:05:20 -07:00
Tyler Veness
27b697b084 Remove frc directory include shims (#1714) 2019-06-10 22:03:52 -07:00
Tyler Veness
9e45373a74 Remove functions and classes deprecated for 2018 season (#1059) 2019-06-10 22:03:15 -07:00
David Vo
eeb1025ac7 SPI: Report port as instance for usage reporting (#1704) 2019-06-10 20:57:36 -07:00
Thad House
bc6f1e2469 Windows compiler options improvements (#1709)
- Use generators to set options only during build
- Add ZcThrowingNew
- Disable 4996

Fixes #1699
2019-06-10 20:09:39 -07:00
Thad House
bb48ae391e cmake: Move example programs into folders (#1654)
This looks cleaner in VS.
2019-06-10 20:04:34 -07:00
Thad House
221011494d Update for C++17 and fix MSVC warnings (#1694)
* Update MSVC arguments
* Fix json allocator
* Fix simulation diamond
* Bump gtest
* Remove empty varargs in unit tests
* Replace test case with test suite
* Remove deprecation warning in optional
* Remove need for NOMIXMAX to be defined in wpilib headers
2019-05-31 15:43:32 -05:00
Thad House
fb1239a2ad Add raw sources and sinks to cscore (#1670)
In some cases, we don't want the cv requirement to get an image, for instance interop with other versions of opencv

This enables getting a raw image, and handling conversions from the user side.
2019-05-30 21:12:05 -05:00
Thad House
7de9477347 Add lambda overloads for interrupts (#1636) 2019-05-30 19:59:35 -05:00
Thad House
90957aeea4 Move libuv to its own subfolder in build (#1661)
Allows using system libuv

* Fix Gradle Build and include dirs

* Update cmake find to support vcpkg libuv
2019-05-30 15:59:26 -07:00
Thad House
47aae502a7 Styleguide fixes (#1702) 2019-05-30 12:36:36 -07:00
pgfisico
0bff98b5ec Correct DifferentialDrive::ArcadeDrive param docs (#1698) 2019-05-30 11:05:42 -07:00
Sam Carlberg
b52e40b80c Allow widgets to be added by passing value suppliers (#1690) 2019-05-30 09:45:23 -07:00
Sam Carlberg
4a00cd77bb Add usage reporting for the Shuffleboard API (#1685) 2019-05-30 09:36:49 -07:00
Thad House
e25e515f2e Publish artifacts on azure (#1678) 2019-05-25 06:18:49 -07:00
Thad House
322ef9b967 Force Java 11, fix javadoc generation (#1695) 2019-05-19 16:59:44 -07:00
Tyler Veness
d42ef5df02 Fix Watchdog print formatting (#1693) 2019-05-19 12:24:40 -07:00
Tyler Veness
f432f65bef Update copyright year in license to 2019 (#1524)
Also update clang-format to 6.0.
2019-05-17 17:35:09 -07:00
Thad House
1726b77ac5 wpiutil: uv: Remove copy from SimpleBufferPool (#1680) 2019-05-07 20:55:58 -07:00
Thad House
620bec9cae wpiutil: uv: Add LoopClosing status to Handle (#1647)
Useful for EventLoopRunner to know if a stop is requested, or close is happening for another reason.
2019-05-05 17:38:56 -07:00
Thad House
7cd6e2e7fa UsbCamera: Solve race in windows initialization (#1638)
Create message pump during UsbCameraImpl creation.
2019-05-05 16:29:47 -07:00
Thad House
7732836bd5 Completely disable watchdog tests on mac (#1679)
They’re just not reliable.
2019-05-05 15:51:14 -07:00
Thad House
698edfda9d Remove framework load, disable mac timeout test (#1676)
* Remove system includes from all mac builds

* Disable java watchdog on mac
2019-05-05 13:16:47 -07:00
sciencewhiz
1c454b000f Add Shuffleboard calls to IterativeRobotBase in C++ (#1607)
Additionally, add epochs for Shuffleboard, LiveWindow, and
Smartdashboard updates.
2019-04-27 22:23:21 -07:00
David Vo
f42905b32e Include missing headers in HAL.h (#1660)
* Include CANAPI.h and Encoder.h in HAL.h

* Include Threads.h in HAL.h

* Make Threads.h C compatible

Also changes the #define to a typedef.
2019-04-27 21:52:54 -07:00
Thad House
bdc822fad8 Only generate passthrough URLs for RoboRIO (#1624)
Otherwise accidentally, a race could occur between coprocessors and rio.

Java was done in both old and new locations as it's a race.
2019-04-27 20:35:23 -07:00
Tyler Veness
d3affb16bc Make failure of HAL_GetFPGATime() more descriptive (#1633) 2019-04-27 20:34:14 -07:00
Peter Johnson
2de3bf7f58 Update LLVM from stable upstream (#1653)
Replace CheckedMalloc with upstream safe_malloc.
2019-04-27 20:33:08 -07:00
Austin Shalit
3cf4f38f5d Fix build on macos10.14.4 (#1648) 2019-04-27 20:25:27 -07:00
Thad House
4e0c10f488 Fix CAN Clean using wrong ID (#1668) 2019-04-27 20:24:40 -07:00
Thad House
3b06313243 Fix Gray to BGR conversion in CameraServer (#1665) 2019-04-27 20:17:17 -07:00
Thad House
6cd1c73efe Fix GUID comparison creating weird symbol (#1659) 2019-04-27 20:16:52 -07:00
Austin Shalit
063bbab6f5 MavenArtifacts.md: update links to HTTPS (#1674) 2019-04-27 20:16:04 -07:00
sciencewhiz
aab4c494d6 Fix type in build.gradle (#1604) 2019-03-10 18:40:16 -07:00
Peter Johnson
bf46af2600 Disable extraneous data warnings in libjpeg (#1630)
These are common with USB cameras.
2019-03-10 18:39:07 -07:00
Thad House
655763a9a7 Limit length of message sent to DS SendError call (#1618)
If total length is over 65536, the packet will get thrown out.
This can be a problem in stack overflow cases (e.g. infinite recursion).
2019-03-03 15:43:04 -08:00
Tyler Veness
a095ec2d8f Fix linker errors with free functions in Threads.h (#1625)
The functions in Threads.h are in the frc namespace. `using namespace frc;` in
Threads.cpp doesn't put their implementations in the frc namespace, so linker
errors occur when attempting to use them in robot programs.

To fix this, one can either wrap them in a namespace block or prepend
`frc::` to the implementation's signature. Based on past discussion, I
opted for the namespace block.
2019-03-03 15:39:59 -08:00
Thad House
12ab035aad Fix receive side of LabVIEW USB streams (#1621)
LabView only accepts %20 instead of + for parameters, only sends '\n' at the boundaries,
and includes the -- when sending the initial boundary.  This solves those parts.

This is not fully enough to fix shuffleboard and others, as the NT format for paths is not the correct path.
2019-03-03 11:20:43 -08:00
Thad House
99e4f7dd2c Fix SPI CS1 not working correctly (#1614)
It was failing the check when remapping digital sources
2019-02-25 18:48:22 -08:00
Peter Johnson
60c2f59051 C++ CameraServer: initialize default Usb camera device number (#1601)
Otherwise just plain StartAutomaticCapture() starts with random number.
2019-02-14 22:39:40 -08:00
Peter Johnson
d55ca191b8 CameraServer: Add switched camera support (#1600)
This adds a new function "addSwitchedCamera" that creates and publishes a
virtual camera where the published stream information is consistent even if
the mjpeg server source is switched to a different camera.

Previously, changing the source of the mjpeg server resulted in updating the
stream information published for that source.
2019-02-14 22:05:40 -08:00
Sam Carlberg
e8b24717c7 C++ Shuffleboard fixes (#1595)
* Fix C++ ShuffleboardComponent template type

* Fix `WithWidget(WidgetType&)`not being properly capitalized

* Fix data members across dll boundaries by using enum for built in types
2019-02-14 20:44:30 -08:00
Tyler Veness
182758c05b Fix Ultrasonic sensor runner thread (#1598)
When there is more than one ultrasonic sensor, only the last sensor
instantiated would work due to incorrect array index management. This
replaces the previous approach with range-based for loops like the C++
implementation.

Supersedes #1589.
2019-02-14 20:25:56 -08:00
Peter Johnson
74f7ba04b0 Java PIDBase: Make setPIDSourceType and getPIDSourceType public (#1599)
Fixes #1596.
2019-02-13 23:41:05 -08:00
Thad House
997d4fdf47 Update HAL GetStackTrace to properly report user errors (#1594)
With the move of the HAL, the old value no longer worked, as the JNI call is in a different namespace
2019-02-11 20:17:31 -08:00
Thad House
76d9e26633 uv: Add reuse to pipe (#1577)
Needed for a reconnection API
2019-02-09 00:09:22 -08:00
Thad House
a230c814cb Add support for WPILib vscode extension for allwpilib C++ intellisense (#1590) 2019-02-09 00:07:48 -08:00
Thad House
12cb77cd7c Fix DS Comm button tests (#1591)
Mac requires the double braces
2019-02-09 00:07:24 -08:00
Thad House
8a9822a96b Allow multiple instances of the same PDP (#1582)
Previously multiple instances would overrun with each other. This make all instances get the same HAL handle.
2019-02-06 22:51:34 -08:00
Thad House
a9371a7586 Fix missing exposure property on windows USB cameras (#1571) 2019-02-06 22:49:55 -08:00
Peter Johnson
6992f5421f cscore: Avoid crash if invalid (null) source set in MjpegServer (#1585)
Fixes robotpy/robotpy-cscore#60
2019-02-03 00:22:07 -08:00
Tyler Veness
43696956d2 Fix Watchdog incorrectly resetting expiration flag upon disable (#1580)
Resetting the flag should only occur in Enable() and Reset().
IterativeRobotBase needs the flag to remain set to print epochs after
disabling the Watchdog.
2019-02-02 00:22:07 -08:00
Thad House
ae3fd5adac Fix docs search having unspecified module directory (#1568)
Also add Doxygen comment for C++ filesystem API.
2019-02-02 00:20:57 -08:00
Jaci Brunning
404666b298 Fix Halsim DS Button Format (#1583) 2019-02-01 23:23:04 -08:00
sciencewhiz
1eb4c99d15 Update README for 2019 changes (#1569)
Fixes #1562
2019-02-01 23:05:41 -08:00
Thad House
910b9f3af7 Add support for camera descriptions on windows (#1572)
For now, has to force enumerate all cameras to find the matching one
2019-02-01 23:04:12 -08:00
Thad House
09d90b02fb Remove prints and unecessary items from windows GetNetworkInterfaces (#1573) 2019-02-01 23:02:12 -08:00
Peter Johnson
0e1f9c2ed2 ntcore: Read ini escaped quotes correctly (#1579) 2019-02-01 23:01:00 -08:00
Thad House
f156a00117 wpiutil uv: Pass IPC value of listening pipe to accepted pipe (#1576)
Otherwise, the acception fails.
2019-01-30 20:37:28 -08:00
Thad House
4a6087ed56 Disable watchdog test on mac (#1578)
It can't be held property on the asure test system
2019-01-30 20:35:16 -08:00
Peter Johnson
88a09dd13a cscore: Handle USB camera integer menus (#1561)
The Pi Camera is one of these.  Previously, integers were just being
cast to a string instead of formatted as a string.
2019-01-24 22:46:29 -08:00
Christopher Cantrell
7d19596367 Changed terminology from "Overload" to "Override" (#1563) 2019-01-24 22:45:05 -08:00
Jaci Brunning
bd05dfa1c7 Fix ds_socket matchinfo (#1555) 2019-01-16 21:32:34 -08:00
Peter Johnson
05d6660a6b cscore: Add config json to VideoSink (#1543)
Same format as VideoSource.

Refactor properties json handling into PropertyContainer.
2019-01-11 20:33:05 -08:00
Peter Johnson
1349dd4bd8 Make MjpegServer functions public (#1545) 2019-01-11 17:53:44 -08:00
Peter Johnson
fdf298b172 CameraServer: Return MjpegServer from StartAutomaticCapture(VideoSource) (#1544) 2019-01-11 16:44:49 -08:00
Peter Johnson
453a9047e4 Fix cmake hal sim build (#1539)
A source directory was named incorrectly in CamelCase.
2019-01-11 02:38:35 -08:00
Peter Johnson
e97e7a7611 Add DriverStationSim.notifyNewData (#1537) 2019-01-09 23:47:42 -08:00
Thad House
308bdbe298 cscore: Windows UsbCamera: Use custom windows message for initial connection (#1534)
WM_CREATE is being called at a time where the message pump cannot be called back into.
2019-01-09 22:52:24 -08:00
Peter Johnson
f889b45d59 cscore: MjpegServer: Fix FPS limiting (#1536)
This uses a 1-second window average to try to hit the desired FPS.
2019-01-09 22:50:34 -08:00
Peter Johnson
444b899a9f Java: Fix Timer.get() handling of accumulated time (#1531)
Fixes #1530.
2019-01-08 19:43:49 -08:00
Tyler Veness
f121ccff0d Avoid Watchdog thread clobbering m_isExpired flag after callback (#1527) 2019-01-08 19:37:59 -08:00
Peter Johnson
bc2c932f92 Fix MotorSafety deadlock (#1526)
Some instances of StopMotor (most notably DifferentialDrive) call Feed(),
which deadlocks due to Check() holding the same lock.

Fixes #1525.
2019-01-02 20:58:39 -08:00
Thad House
6bdd7ce506 Update docs for disabled init to match all the other modes (#1523)
Closes #1522
2018-12-31 19:11:35 -08:00
Thad House
c12d7729e3 Update examples to use VictorSPX's rather then Sparks (#1521) 2018-12-31 13:45:09 -08:00
Dustin Spicuzza
3635116049 cscore: set charset of displayed pages (#1520)
All of our strings are UTF-8, but the default charset for HTML<5 was ISO-8859-1
2018-12-30 23:49:24 -08:00
Peter Johnson
6105873cbe Provide alternate device paths info for USB cameras (#1519)
This is primarily for use on Linux to get by-id or by-path device names.

This information is now part of UsbCameraInfo.

A new entry point was added to UsbCamera to get that camera's UsbCameraInfo.

The alternate paths are also returned in EnumerateUsbCameras.
2018-12-30 11:48:18 -08:00
Sam Carlberg
80f87ff8ad Allow video sources to be added to Shuffleboard (#1453)
Add a Sendable wrapper for VideoSource objects.

Add convenience methods for adding video sources directly to containers
so users won't have to manually wrap video sources.
2018-12-30 11:45:41 -08:00
Peter Johnson
a2368a6199 Watchdog: add timeout message suppression feature
Was part of reverted #1486
2018-12-30 00:16:50 -08:00
Peter Johnson
ae3cb6c83b Watchdog.java: add comment fixes from reverted #1442 2018-12-30 00:16:50 -08:00
Peter Johnson
f0f196e5b3 Revert "MotorSafety: Use Watchdog instead of DS class polling (#1442)"
This reverts commit 26e8e587f9.
2018-12-30 00:16:50 -08:00
Peter Johnson
7c35355d29 Revert "Suppress Watchdog's generic timeout message in MotorSafety (#1486)"
This reverts commit 41596608cc.
2018-12-30 00:16:50 -08:00
Peter Johnson
75cc09a9e4 Revert "Suppress timeout message in C++ MotorSafety class (#1512)"
This reverts commit 300eeb330d.
2018-12-30 00:16:50 -08:00
Peter Johnson
0e2e180635 PowerDistributionPanelTest.cpp: Include thread 2018-12-30 00:16:50 -08:00
Sam Carlberg
01d1322066 Add constants for built-in Shuffleboard widgets and layouts (#1468)
Prevents users from having to remember (and correctly type) the names of Shuffleboard widgets.
2018-12-29 17:22:47 -08:00
Peter Johnson
ceed1d74dc ntcore: Strip whitespace from IP addresses (#1516) 2018-12-29 14:47:25 -08:00
Peter Johnson
e1bf623997 cscore: handle HTTP stream hangs (#1513)
Automatically disconnect the HTTP stream if no frames have been received
for 1 second.
2018-12-29 14:08:45 -08:00
Thad House
d46ce13ffe Fix CAN API timing out incorrectly (#1497)
HAL_GetFPGATime returns 0 if it starts with a non zero status.

Always use monotonic clock for CAN times, rather then trying to sync FPGA.

Change timeout from 50 ms to 100 ms.
2018-12-29 13:57:23 -08:00
Tyler Veness
300eeb330d Suppress timeout message in C++ MotorSafety class (#1512)
wpilibj's default constructor is already correct.
2018-12-27 14:01:02 -06:00
Andrew Dassonville
d817001259 Only write version information on real robot (#1510)
Writing to the versions file throws an exception on Windows, and might
write weird files on Linux.
2018-12-27 00:59:49 -06:00
Austin Shalit
8ac4b113a5 Fix build on macOS 10.14.2 (#1509) 2018-12-25 22:58:04 -06:00
Tyler Veness
f3864e9abb Move deprecated message in C++ from class level to constructor (#1505)
This prevents deprecation messages when including a header but not
instantiating the class. SampleRobot was addressed by #1503.
2018-12-25 01:14:24 -06:00
Thad House
799c3ea8a6 Disable gyro sim test on mac (#1506)
It fails with a mutex error very often, and we have not been able to figure out the issue.

It breaks CI.
2018-12-25 01:13:59 -06:00
David Vo
8d95c38e39 Watchdog: Fix potential IllegalFormatException (#1508)
If an epoch name contains a % symbol, this could've lead to an exception
at runtime where the number of arguments mismatches the format string.
2018-12-25 01:12:44 -06:00
Thad House
a7f4e29b73 Update versioning and vscode plugin (#1498)
versioning fixes multi tag issue
2018-12-24 15:46:41 -06:00
Thad House
b88369f5e8 Move deprecation warning for SampleRobot to constructor (#1503)
This way, the warning doesn't occur when including wpilib.h

Closes #1501
2018-12-24 15:46:12 -06:00
Thad House
ce6f1d0588 Change deperecation year for serial port direct constructor (#1504) 2018-12-24 15:17:19 -06:00
Thad House
f163216a4c Add support for raspbian extraction (#1494)
This is how I did it in C#, and it was the most reliable way I could find.
2018-12-24 15:15:15 -06:00
Thad House
c449ef1064 Unconditionally await in awaitUntil (#1499)
Negative numbers are properly handled, which will reduce chances of deadlocks.
2018-12-24 15:07:47 -06:00
Thad House
6593f4346e Default to DS attached to true in sim (#1500)
Otherwise, it is required to be set manually, which isn't obvious.

This is because the HighLevel DS classes check that the ds is attached before enabling
2018-12-24 02:06:53 -06:00
Thad House
ce1367a115 Make JNI library not found message clearer (#1495)
Closes #1472
2018-12-21 00:26:53 -08:00
Thad House
0d7d880261 Renable full Java 8 Compatibility (#1493) 2018-12-21 00:25:23 -08:00
Thad House
ca2acec88c Update to NI Libraries 2019v12 (#1492) 2018-12-21 00:24:44 -08:00
Thad House
3721463eb3 Don't use symbolic path searching for USB detection (#1491)
The USB directories we care about are not symbolic links, so we can ignore them.

There was a recursive symbolic link, which was causing failure.
2018-12-19 14:40:01 -08:00
Thad House
6e8f8be370 Make C++ examples able to run GradleRIO unit tests (#1490)
Closes #1484
2018-12-17 09:26:20 -08:00
Thad House
d84240d8e9 Bump opencv version to 3.4.4-4 (#1489) 2018-12-14 20:17:51 -08:00
Thad House
1823cb2b68 Fix periodic can packets not being received properly (#1488)
Constant calls would result in timeout, because a valid packet wasn't being returned early.

Also fix data copies (was copying in wrong direction).
2018-12-14 17:43:48 -08:00
Tyler Veness
41596608cc Suppress Watchdog's generic timeout message in MotorSafety (#1486) 2018-12-14 10:53:33 -08:00
Thad House
0c3b488e18 Make ntcore instances not smart pointers (#1485)
During static shutdown, the instances hang on windows 7, so let them leak instead.
2018-12-13 21:33:58 -08:00
Thad House
7d7af287f6 Add empty classes to command/classes creation (#1479)
Closes #1478
2018-12-09 21:25:37 -08:00
Thad House
4119622994 Fix characters in license file (#1480)
Causes wpiformat errors on windows.
2018-12-09 21:23:19 -08:00
Peter Johnson
d528a77963 wpiutil: Fix resources build (#1476) 2018-12-09 11:45:11 -08:00
Peter Johnson
dab7e1b7a2 Add multiCameraServer to cmake build (#1477) 2018-12-09 11:44:45 -08:00
Peter Johnson
ab49345460 Add missing param javadoc comment and fix argument order inconsistency (#1475) 2018-12-09 08:37:09 -08:00
Peter Johnson
608d82423d wpiutil: Use scoped connections to ensure cleanup (#1474) 2018-12-09 01:36:36 -08:00
Peter Johnson
e0e15eafeb wpiutil: Add shared resources for http servers
Files are named only with major.minor versions.  Full versions are:
* bootstrap 4.1.3
* coreui 2.1.8
* feather 4.8.0
* jquery 3.3.1
* popper 1.14.4
2018-12-09 00:58:04 -08:00
Peter Johnson
0fb24538a7 wpiutil: HttpServerConnection: add SendStaticResponse
This function is intended for use when the content is a static const variable.
It allows gzipped static data, but doesn't provide the functionality to ungzip
it if the client doesn't support gzip.  This is because it would add a
dependency on zlib and basically all clients support gzip.

Change extraHeader on all Send functions to include the final newline,
this makes it easier to build up extra headers incrementally.

Expose sig::Connection for messageComplete and headerConn to allow them to
be disconnected by users of the class.  This is commonly needed for things
like WebSocket upgrades.
2018-12-09 00:58:04 -08:00
Thad House
d65547ea74 Bump OpenCV version (#1471) 2018-12-08 23:12:39 -08:00
Peter Johnson
bfe15245a6 Add multiCameraServer executable (#1422)
This standalone CameraServer reads its configuration from a json file.
2018-12-07 23:57:37 -08:00
Nicolas Machado
ff58c5156a Change SmartDashboard type of PIDBase.cpp to match PIDBase.java (#1470) 2018-12-07 19:40:31 -08:00
Tyler Veness
6d4326a560 Rate-limit Watchdog timeout prints to 1Hz (#1459) 2018-12-07 19:39:02 -08:00
Sam Carlberg
97ba195b88 Fix LiveWindow attempting to start listeners on uninitialized sendables (#1463)
Additionally adds a defensive check in SendableBuilderImpl to avoid the NPE.
2018-12-07 19:38:22 -08:00
Thad House
3d546428ab Add missing SubTableListener methods to C++ NetworkTable (#1465) 2018-12-06 23:27:49 -08:00
Dustin Spicuzza
b64dfacff3 DriverStation: fix error checking for GetXXXAxis and GetXXXPov (#1469)
Fixes #1436
2018-12-06 22:31:14 -08:00
Peter Johnson
dcbf02a1ec Update auto SPI for timestamp changes (#1457)
The 2019 FPGA image switched the output of auto SPI from plain bytes to a
sequence of 32-bit words (timestamp, then words with the byte values in the
least significant byte of each word).

In addition to changing the HAL and simulators to reflect this, add piecewise
integration support to wpilibc/wpilibj SPI to take advantage of the timestamps
and use it in the ADXRS450 gyro.
2018-12-06 22:29:20 -08:00
Thad House
7e1ec28839 NI image 2019v9 (#1467) 2018-12-06 21:59:13 -08:00
Thad House
ef16317f8f Update NativeUtils and Doxygen (#1462)
Adds debug stripping to executables.
Copies .debug and .pdb files to install directories to ease debugging.

Update to v0.5 of doxygen, which fixes the download location.
2018-12-05 00:27:18 -08:00
Tyler Veness
26e8e587f9 MotorSafety: Use Watchdog instead of DS class polling (#1442) 2018-12-01 01:34:52 -08:00
Dustin Spicuzza
0d0492bfcc HAL: Add additional error messages to HAL_GetErrorMessage (#965) 2018-12-01 00:06:30 -08:00
Tyler Veness
3b33abfc7b Make Watchdog use single thread dispatch (#1347)
Notifier has one thread per instance because the callbacks must be
asynchronous. Watchdog callbacks can be synchronous, so this overhead
can be done away with via a scheduler thread akin to what the HAL
Notifier does.
2018-12-01 00:05:33 -08:00
Peter Johnson
99033481e0 Add netconsoleTee
This is similar to netconsoleServer, but is designed to operate as a tee
in a pipeline (it reads console data from stdin).
2018-11-30 23:06:31 -08:00
Peter Johnson
b4901985b7 Add netconsoleServer
This is a updated version of netconsole-host that can serve either as a
new-style TCP riolog or output UDP to either localhost or broadcast.
2018-11-30 23:06:31 -08:00
Peter Johnson
97edb6c68f wpiutil: uv::Buffer: Add Dup() function 2018-11-30 23:06:31 -08:00
Peter Johnson
73de3364b7 AxisCamera constructor: add StringRef overload (#1458)
This avoids a conversion ambiguity when StringRef is passed.
2018-11-30 22:35:56 -08:00
Thad House
5551981b3f Upgrade to Gradle 5.0 (#1444)
Also skip raspbian for gazebo.
2018-11-29 23:17:06 -08:00
Jaci Brunning
90572a3cc5 Add wpilibc and wpilibj skeleton templates (#1441)
See also vscode-wpilib#132.
2018-11-29 22:15:17 -08:00
Thad House
c405188052 Fix directory iterators not working correctly (#1454)
The size of the directory_entry was different between translation units.
This was caused by the FILE_OFFSET_BITS macro when building wpiutil.
Removing that fixes the issue.
Should fix NavX USB issues.
2018-11-29 00:24:10 -08:00
Thad House
bea0565ac9 Update to OpenCV 3.4.4 (#1452) 2018-11-28 12:26:56 -08:00
Peter Johnson
0b03454366 wpiutil: Replace LLVM Optional with C++17-compatible optional
Imported from https://github.com/akrzemi1/Optional with minor changes:
- Compiler conditional simplifications (we only use recent versions)
- Move from std::experimental to wpi namespace
- Change tests to integrate with Google Test

Update LLVM use cases.
2018-11-28 12:23:56 -08:00
Peter Johnson
489701cacc wpiutil: Rename Optional.h to LLVMOptional.h 2018-11-28 12:23:56 -08:00
Tyler
a769d56ec1 Create C++ ShuffleBoard example (#1438) 2018-11-28 12:13:38 -08:00
Sam Carlberg
6f0c185a05 Add methods to change the selected tab in the Shuffleboard app (#1448) 2018-11-27 22:12:50 -08:00
Sam Carlberg
a60f312d19 Add eager null checks in drive base classes (#1447)
All null motors will be specified in the error messages.
2018-11-27 18:11:56 -08:00
Tyler Veness
acb786a791 Remove MotorSafetyHelper, create MotorSafety base class instead (#562)
Most of the MotorSafety implementation was moved into the MotorSafety base
class. SafePWM's inheritance of MotorSafety was moved into PWM to
eliminate Java needing a helper class.

In Java, a helper class for Sendable (SendableImpl) was added due to
lack of multiple inheritance.
2018-11-22 21:15:26 -08:00
Peter Johnson
df347e3d80 wpiutil: uv::Process: Revamp args/options approach (#1434) 2018-11-19 19:54:54 -08:00
Peter Johnson
e4aa45f34b wpiutil: WebSocket: Fix Sec-Websocket-Accept computation
It needs to use the raw SHA1 bytes, not the hex-decoded text.
2018-11-19 19:24:28 -08:00
Peter Johnson
75cc3cda28 wpiutil: SHA1: Add method to get raw bytes instead of hex 2018-11-19 19:24:28 -08:00
Sam Carlberg
45f4472d42 Add mechanism to control Shuffleboard recordings and add event markers (#1414) 2018-11-18 23:15:30 -08:00
Thad House
69cb53b51b Add support for USB Webcams on Windows (#1390) 2018-11-17 23:16:35 -08:00
Tyler Veness
70a66fc943 Make Gradle show stdout for wpilibj tests (#1431) 2018-11-17 20:29:27 -08:00
Austin Schuh
9207d788ab Convert ReadInterrupt* to return int64_t time (#1417)
HAL_ReadInterruptRisingTimestamp and HAL_ReadInterruptFallingTimestamp
return time as a double.  Instead, keep the raw integer count and move the
double conversion into the C++ and Java code.  This enables comparison of the
time with other timers.
2018-11-15 21:22:03 -08:00
Thad House
ef3a31aa20 Add an example of using the HAL directly (#1374)
This is useful for advanced users, and shows a few things like error messages, and DS things that are needed.
2018-11-15 19:33:50 -08:00
Tyler Veness
63775362fe Remove SynchronousPID class (#1429)
PR #1300 supersedes it, but won't be merged until the 2020 season. Since
SynchronousPID hasn't been used during a season, it would be best to
just remove it to avoid breakage when we deprecate and remove it again.
2018-11-15 19:25:31 -08:00
Tyler Veness
55493b0c18 Fix polymorphic exception types being caught by value (#1426)
Catching these by value breaks the build with GCC 8.2.1.
2018-11-12 19:39:49 -08:00
Tyler Veness
1696557c46 Fix deprecation warning in wpilibj shuffleboard example (#1427)
TimedRobot should be used instead of IterativeRobot.
2018-11-12 19:38:50 -08:00
Thad House
ecd376be4c Export C functions from JNI statically linked library (#1425)
The JNI libraries are useful from other tools, so they should contain the C functions.
2018-11-12 19:38:35 -08:00
Peter Johnson
f54c0f70f6 Update opencv to 3.4.3-19 (#1424) 2018-11-11 19:27:20 -08:00
Peter Johnson
9bc998f4b0 cscore: Add JSON for source settings (#1423)
This allows save and restore of camera settings.  The restore is a bit
smarter than the save.

* Fix mime types in mjpeg server

* wpiutil: WPI_LOG: Make sure level is an unsigned int
2018-11-10 20:30:02 -08:00
Peter Johnson
43d188a429 RobotBase: Call cscore Shutdown() from destructor 2018-11-09 23:33:55 -08:00
Peter Johnson
563d5334c9 Update OpenCV to 3.4.3-17 2018-11-09 23:33:55 -08:00
Peter Johnson
193b0a222c cscore: Add Shutdown() function
This allows ordered shutdown / destruction of sources and sinks prior to
global singleton destruction.
2018-11-09 23:33:55 -08:00
Peter Johnson
76f5d153fa wpiutil: Add Stop() to EventLoopRunner
This allows stopping the event loop without having to destroy the object.

Also fix ExecSync() to actually wait for the call to complete.
2018-11-09 23:33:55 -08:00
Peter Johnson
19caeca990 cscore: Use more standard naming for Instance public variables 2018-11-09 23:33:55 -08:00
Peter Johnson
0abae17653 cscore: Refactor sink and source creation
Also make sources and sinks members of Instance private, with appropriate
accessor functions.
2018-11-09 23:33:55 -08:00
Peter Johnson
81d10bc656 cscore: Build examples on Windows (#1421) 2018-11-09 22:42:04 -08:00
Austin Shalit
b51b86525d Stop webserver on test run (#1420) 2018-11-09 20:36:35 -08:00
Peter Johnson
ace37c517e CameraServer: enable usb cameras on non-Linux platforms (#1411) 2018-11-09 20:27:23 -08:00
Austin Schuh
ac751d3224 Fix unused variable warnings in ntcore (#1416)
This avoids -Wextra warnings.
2018-11-09 20:02:58 -08:00
Thad House
7c9a3c4d77 Update NI Library to 2019.7.1 and OpenCV to 3.4.3-16 (#1418)
Add def for each to eliminate duplication of version number.
2018-11-09 19:59:06 -08:00
Sam Carlberg
8be693f55d Fix list layout in shuffleboard example (#1413) 2018-11-09 01:14:15 -08:00
Peter Johnson
622ae29dff CameraServer: Change opencv sources to publish "cv:" type (#1412)
The LabVIEW dashboard has been fixed to understand this prefix.
2018-11-09 01:13:39 -08:00
Peter Johnson
e7c98feca2 libuv: Use WPI (FPGA) clock on roboRio (#1409)
This is set to the FPGA clock by HAL_Initialize.  Note this change means
that libuv loops should not be started until after HAL_Initialize is called (on the Rio).
Non-Rio functionality is unchanged.
2018-11-07 00:06:18 -08:00
Jaci Brunning
28087424ec Add deploy directory detection (#1400)
Add Filesystem class for java and namespace methods for C++ for detecting deploy location.
2018-11-02 13:16:44 -07:00
Peter Johnson
b6830638df NetworkListener: use Pimpl idiom (#1405)
This enables different platforms to use very different implementations.
2018-11-02 13:14:06 -07:00
Liam Kinne
fb557f49ea Add missing driver station documentation (#1388) 2018-11-01 23:34:48 -07:00
Peter Johnson
746f950a0b Remove ifdefs from linux NetworkListener (#1404) 2018-11-01 23:27:22 -07:00
Peter Johnson
9a38a3e188 Don't use static for raw_ostream outs/errs (#1401)
Static destruction order is not well defined, so it was possible for outs()
or errs() return value to be destroyed even while other code was running,
resulting in a crash.  Instead dynamically allocate the static so the
destructor never runs.  While this technically leaks, valgrind generally
supresses such leaks as the data is still "reachable" from the static pointer.
2018-11-01 10:48:50 -07:00
Thad House
2e3e3a47b9 Use a kill -9 after attemting a safe kill (#1397)
Should fix some deploy deadlocks.
2018-11-01 01:55:26 -07:00
Peter Johnson
e27d6d7bb8 cscore: Change impl to only one singleton (#1398)
This avoids a number of shutdown use-after-free races by controlling the
destruction order.  It also is a prerequisite to making the internal
interfaces mockable for unit testing.
2018-10-31 20:22:58 -07:00
Thad House
1dec0393a1 Fix static deletion race condition in DS thread (#1396)
The static condition variable was getting destroyed before the DS thread exited,
resulting in a deadlock on program exit when the DS thread tried to notify it.
This change moves the condition variable into the DS thread to avoid the race.
2018-10-30 11:51:17 -07:00
Peter Johnson
d03b020326 wpiutil: Add WorkerThread (#1302)
This provides a worker thread that can execute a work function with the result
going into either a future or a uv::Loop functor.
2018-10-29 20:54:42 -07:00
Austin Shalit
71e29b1d91 Remove unused import from rumble example (#1395)
This fixes a nit in #1394.
2018-10-29 20:54:15 -07:00
Thad House
f0b0965f9b Remove large HAL headers from wpilibc headers (#1386)
Now only includes the types in the wpilib headers.
Should immensely clean up intellisense.

Closes #1383
2018-10-29 12:49:17 -07:00
Austin Shalit
f774e47c80 Add an example showing how to use a hid rumbler (#1394) 2018-10-29 12:37:30 -07:00
Nicolas Machado
761933a164 Refactor Java Ultrasonic to use a List container (#1389) 2018-10-29 01:15:32 -07:00
Tyler Veness
99e0f08a6f Move applicable integration tests to native build as unit tests (#1364) 2018-10-29 00:12:38 -07:00
Tyler Veness
e89d5eb692 Fix stringop truncation warning from GCC 8.2 (#1393)
The next line adds a null terminator, but it's cleaner to just do a
std::memcpy() since the code already assumes a null terminator exists in
the source string.
2018-10-29 00:09:53 -07:00
Austin Shalit
2501e11886 Enable HTML5 javadocs (#1267)
This suppresses a build warning about HTML 4.01 being used.
2018-10-29 00:08:21 -07:00
Thad House
9174f23f36 Remove some usages of windows.h (#1370)
For HAL and wpilib, we don't need them, especially where they were being used.
2018-10-28 22:33:55 -07:00
Redrield
9f6544fa87 Allow binding commands to POV (#1378) 2018-10-28 21:54:06 -07:00
Peter Johnson
9a1af132bf Unify GetHostname() and use libuv implementation (#1391) 2018-10-28 19:01:48 -07:00
Thad House
a8aacd3657 Update build setup for raspbian and debug binaries (#1384)
- Build both debug and release binaries
- Append "d" to debug libraries in the style of opencv
- Split shared and static classifiers
- Add raspbian support
2018-10-27 00:19:38 -07:00
Peter Johnson
8ff81f5a2a cscore: Separate platform-specific sources (#1387) 2018-10-23 22:59:47 -07:00
Liam Kinne
349e273ecc AnalogGyro: add "calibrating for n seconds" message (#1380) 2018-10-23 00:29:23 -07:00
Tyler Veness
0a2ab4f0d7 Revert change in behavior in HeldButtonScheduler (#1381)
Originally, the command was restarted every time the scheduler was
executed if the button was pressed. #1340 changed this behavior in a
breaking manner.
2018-10-20 21:25:37 -07:00
Peter Johnson
7c1a7332e1 uv::Async, uv::AsyncFunction: allow calling from within loop 2018-10-16 09:40:59 -07:00
Peter Johnson
172e438cd6 wpiutil: uv::Async: Keep weak reference to loop
Other handles can only be used within the loop itself, but Async is intended
to be used from another thread.  This introduces the possibility of a race
condition between the loop being destroyed and the Async being destroyed.
Change Async to keep a weak reference to a loop and check it before performing
libuv operations.
2018-10-16 09:40:59 -07:00
Peter Johnson
1a7a0db1ff wpiutil: Change uv::AsyncFunction to use promise/future.
This allows the called function to pass along the promise to another
asynchronous callback.

To avoid memory allocations, add a home-rolled, simplified, non-allocating
version of std::promise and std::future as wpi::promise and wpi::future.
2018-10-16 09:40:59 -07:00
Thad House
11e5faf469 Use Array Constructor rather then new array to toArray (#1368)
A bit cleaner to use, and more standard for the current java. Still java 8 compatible.
2018-10-16 01:30:42 -07:00
Peter Johnson
c7118f8ade wpiutil: Signal: Don't use std::forward when calling (#1371)
This causes a std::move of objects that are both moveable and copyable.
2018-10-16 00:39:16 -07:00
Peter Johnson
7933d2cbe5 wpiutil: uv: Don't close uninitialized handles (#1372) 2018-10-16 00:38:48 -07:00
Dan Katzuv
ce8c71b1f3 Fix link for license (#1367)
The previous license link referred to `license.txt', but the correct file is `LICENSE.txt`.
2018-10-14 09:58:54 -07:00
Liam Kinne
da9a575526 Rename squaredInputs to squareInputs in DifferentialDrive (#1361)
Fixes #1360.
2018-10-13 23:10:16 -07:00
Thad House
7068551a3e Bump OpenCV and GTest to 2019 dependencies (#1366) 2018-10-13 20:46:14 -07:00
Tyler Veness
bd9484a2f4 Make MyRobot compilation test use TimedRobot (#1363)
IterativeRobot is deprecated.
2018-10-12 23:41:05 -07:00
Thad House
b9fa3a4398 Update to 2019 RoboRIO and 2019 v4 image (#1352)
Also make updates for Java 11:
* Disable errorprone plugin (currently broken on Java 11)
* Update checkstyle to 8.12
* Update pmd to 6.7.0
2018-10-07 18:11:57 -07:00
Thad House
88b93c220e Update NativeUtils to not copy NI libraries to jenkins RoboRIO (#1359)
Allows for compile only shared libraries
2018-10-06 20:51:00 -07:00
Peter Johnson
0a937bb5b9 wpiutil: SafeThread: Ensure thread is released in destructor (#1358)
The thread must be released with either a detach or a join, otherwise
std::terminate is called.
2018-10-06 18:07:56 -07:00
Peter Johnson
613d5eda0d wpiutil: SafeThread: join on thread exit (#1357)
This can be conditionally disabled (for cases like JNI callbacks where the JVM
may block callbacks into it during shutdown).
2018-10-06 15:17:13 -07:00
Peter Johnson
18c8cce6a7 SafeThread: Avoid use-after-free risk in thread shutdown (#1355)
Use shared_ptr to keep data alive until the thread has terminated.
2018-10-05 16:32:43 -07:00
Peter Johnson
36000ddb36 wpiutil: uv::Loop: Store the thread ID of the loop 2018-10-05 13:32:51 -07:00
Peter Johnson
de6d6c9a5c wpiutil: EventLoopRunner: Allow getting the loop shared_ptr. 2018-10-05 13:32:51 -07:00
Peter Johnson
6d99c0ac6c wpiutil: EventLoopRunner: Remove extraneous wpi namespace qualifier 2018-10-05 13:32:51 -07:00
Peter Johnson
164e9a2c7d wpiutil: uv::Work: Don't connect work and afterWork if they're null 2018-10-05 13:32:51 -07:00
Peter Johnson
f3fb95af70 wpiutil: uv::Tcp: Simplify reuse function 2018-10-05 13:32:51 -07:00
Peter Johnson
40a9fc44ff wpiutil: uv::Poll: add reuse functionality 2018-10-05 13:32:51 -07:00
Thad House
f0ac048645 Remove pmd and checkstyle publishing from azure (#1353)
Bug in azure makes out of branch PRs fail
2018-10-05 10:20:20 -07:00
Tyler Veness
81498e6af9 Deprecate IterativeRobot in favor of TimedRobot (#1341)
Since https://github.com/wpilibsuite/allwpilib/issues/786 has been
closed as not a legitimate concern, there is now no reason to use
IterativeRobot over TimedRobot. It's a drop-in replacement that's
strictly an improvement in terms of execution jitter.

To migrate, one simply has to replace the IterativeRobot subclass in
their robot code with TimedRobot.
2018-10-04 01:02:07 -07:00
Thad House
f1056efa01 Updates version plugin to 2.2 (#1349)
Fixes describe bug, and removes timestamp from published version number
2018-10-04 01:01:00 -07:00
ariovistus
54fbec27df Fix typo (#1348) 2018-10-04 00:59:47 -07:00
Thad House
fd82153456 Fix shuffleboard C++ tests, and run them on desktop (#1351) 2018-10-02 20:55:03 -07:00
Thad House
7b471d8c62 Fix windows image on azure pipelines (#1350) 2018-10-02 10:42:18 -07:00
Sam Carlberg
175c6c1f01 Add fluent builders for more flexibly adding data to Shuffleboard (#1022) 2018-09-28 01:18:18 -07:00
Thad House
ac7dfa5042 Switch to using containers for Linux builds on Azure (#1335) 2018-09-27 22:38:33 -07:00
Tyler Veness
a732854866 Clean up edge detection logic in ButtonScheduler subclasses (#1340)
This also changes the behavior of whileActive to call start once on the starting edge
instead of every loop iteration.
2018-09-26 22:55:34 -07:00
Tyler Veness
6171856020 Document Watchdog epochs better (#1345) 2018-09-26 22:53:34 -07:00
Thad House
d5d744a390 Fix publishing of templates on jenkins (#1343) 2018-09-26 21:10:26 -07:00
Tyler Veness
8b1274d744 Replace typedefs in C++ with using declarations (#1339)
These are more readable than typedefs. C headers were left alone.
2018-09-26 00:09:25 -07:00
Tyler Veness
26c33a9a56 Remove priority_condition_variable (#1337)
Make wpi::condition_variable typedef to std::condition_variable_any if
wpi::mutex typedefs to priority_mutex.

priority_condition_variable was originally intended as a copy of
std::condition_variable_any that also returned the internal handle like
std::condition_variable. This was needed because NetComm required a
pthread_cond_t. We no longer use it anywhere.

Its args were specialized for priority_mutex, but
std::condition_variable_any supports this and more through
templatization.
2018-09-25 21:38:52 -07:00
Thad House
5fad2b1056 Remove travis and appveyor configuration files (#1338)
Also update build badge to point to Azure instead.
2018-09-25 21:37:04 -07:00
Thad House
32ec07ee01 Throw correct exception in HAL_getJoystickAxes/POVs JNI (#1336)
Was incorrectly not returning immediately after throwing the exception.

Also add more detail to exception.
2018-09-24 22:17:17 -07:00
Thad House
15c5a820bf Publish tests to azure ci (#1334)
Makes reviews easier.
2018-09-24 16:36:50 -07:00
Thad House
e15fabd2e1 Add cmake azure build (#1332) 2018-09-24 16:36:24 -07:00
Tyler Veness
1aa8446725 Add move constructors and assignment operators to wpilibc (#1314)
Fixes #898.
2018-09-24 00:08:25 -07:00
Thad House
b1965f74a8 Add styleguide check to azure pipelines build (#1331) 2018-09-23 23:38:04 -07:00
Thad House
0c58a0a705 Repackage CameraServer classes (#1321)
This is necessary for modularization.
Move the wpilibj CameraServer classes to the cameraserver package.
Move the edu.wpi.first.wpilibj.vision package to edu.wpi.first.vision.
To avoid code breakage, add deprecated copies of the wpilibj classes to the wpilibj jar.
2018-09-23 21:20:12 -07:00
Tyler Veness
467c9fd686 Add kInvalid value to HAL_I2CPort and HAL_SPIPort (#1329)
This allows HAL_CloseI2C() and HAL_CloseSPI() to be noops, which makes
enabling move semantics in the I2C and SPI wpilibc classes easier and
cleaner.

Fixes #1328.
2018-09-23 21:14:04 -07:00
Tyler Veness
b505bbefd1 Rename variable in SPI class not compliant with style guide (#1330)
Also rename some wpilibj SPI class variables to match wpilibc and
better communicate their intent.
2018-09-23 18:26:02 -07:00
Thad House
5c6b78ea2b Set up CI with Azure Pipelines (#1306) 2018-09-23 17:43:23 -07:00
Thad House
f89274fb13 Fix hal header zip task dependencies (#1327)
Sometimes wouldn't include generated header file
2018-09-21 12:04:11 -07:00
Thad House
1137582a7a Revert "Move deprecated ntcore classes to wpilibj jar (#1322)" (#1326)
This reverts commit 12c92a822d.
2018-09-21 11:32:11 -07:00
Thad House
e26e3b6aa8 Fix HAL Headers Zip (#1325)
Was generating file into wrong directory
2018-09-21 10:51:17 -07:00
Thad House
456d3e16a6 Update NI Libraries to layout without C++ (#1324)
An explicit classifier is not required because we now generate usage reporting
2018-09-21 10:36:40 -07:00
Thad House
e210073044 Move HAL classes to their own base package (#1317)
Needed for modularization.
2018-09-20 21:59:46 -07:00
Thad House
0068b6aea3 Remove wpilibj tests from wpilibjIntegrationTests (#1323)
Since the integration tests are still on junit 4, the wpilibj junit 5 tests fail.
2018-09-20 21:57:59 -07:00
Thad House
12c92a822d Move deprecated ntcore classes to wpilibj jar (#1322)
Will allow for modularization
2018-09-20 21:50:30 -07:00
Thad House
d2a5aaafdd Use external dependencies for NI and NetComm libraries (#1304)
This removes a number of large binary files from the repo and enables vendors
to depend on these libraries separately.
2018-09-19 21:57:58 -07:00
Tyler Veness
bedef476fd Replace IterativeRobot in examples with TimedRobot (#1310)
Fixes #1309.
2018-09-19 21:41:08 -07:00
Thad House
59386635e7 Add CAN API constructor that takes explicit manufacturer and device type (#1311)
Useful for vendors wanting to use the API and make their own device parameters
2018-09-19 21:40:47 -07:00
Thad House
a846ed062f Add virtual destructor to CameraServerShared (#1313)
Fixes mac builds after update
2018-09-19 21:39:57 -07:00
Matt Soucy
8b5dc53cc7 Add Lambda support to InstantCommand (#1262) 2018-09-11 23:44:22 -07:00
Kay Kasemir
59700882f1 PIDController: Mention unit for 'period' (#1305) 2018-09-11 21:38:19 -07:00
Peter Johnson
025af24523 Make NetworkTableEntry.callRpc and createRpc public (#1303) 2018-09-08 21:19:14 -07:00
Peter Johnson
c0ff6198b3 Change hal sim to use spinlocks (#1291)
This makes callback registration completely thread safe.

This patch also uses templates and macros to dramatically reduce the amount of
manual boilerplate.
2018-09-03 16:08:07 -07:00
Peter Johnson
67b1c85315 Notifier: properly reset HAL alarm in non-periodic case (#1296)
The loop spins otherwise.
2018-09-03 16:07:23 -07:00
Tyler Veness
0b113ad9ce Fix some PIDCommand constructors not forwarding subsystems (#1299)
Also added missing constructor to wpilibc's InstantCommand and renamed
argument from requirement to subsystem as per
https://github.com/wpilibsuite/allwpilib/pull/1275#issuecomment-416071940.
2018-09-02 14:18:12 -07:00
Peter Johnson
c8482cd6d2 wpiutil: Add WebSocket implementation (#1186)
This is a RFC 6455 compliant implementation with both client and server support.
2018-08-24 20:54:23 -07:00
Peter Johnson
d6d5321828 wpiutil UidVector: Implement clear() and forward iterator (#1293)
The forward iterator only iterates over "live" elements.

Also add a couple of unit tests for UidVector.
2018-08-24 20:39:57 -07:00
Peter Johnson
8d91343bf5 wpiutil spinlock.h: Include STL mutex for convenience (#1292)
The STL mutex header defines classes like lock_guard and unique_lock.
2018-08-24 20:39:20 -07:00
PJ Reiniger
488ba79379 Add more checkstyle checks to simulator code (#1289) 2018-08-23 23:15:29 -07:00
PJ Reiniger
de212a9dd0 Add names to simulator components (#1268)
Makes configuration easier when you can associate the items with a name
instead of just a port number. Important if there is a GUI added at some
point.
2018-08-23 17:59:09 -07:00
Peter Johnson
8d8f120cc3 EventLoopRunner: Use AsyncFunction 2018-08-20 22:21:53 -07:00
Peter Johnson
57490e0002 Add uv::AsyncFunction to do a roundtrip function call to a uv::Async
This optionally blocks to wait for a return value.
2018-08-20 22:21:53 -07:00
Peter Johnson
1de1900dbb Change uv::Async to accept data parameters
This is a breaking change as it makes Async a template (e.g. Async<> must
be used instead of just Async).  When data parameters are provided, an
internal mutex and vector is used to hold the parameter packs until the loop
runs.
2018-08-20 22:21:53 -07:00
Peter Johnson
4a3e43d4a7 Add HttpMultipartScanner (#1197)
This is a non-blocking version of FindMultipartBoundary.
2018-08-20 22:00:54 -07:00
Peter Johnson
9e37ee13de Add wpi::HttpServerConnection and an example of its use (#1281) 2018-08-20 13:11:39 -07:00
Peter Johnson
7b95c5341a ntcore: Change params in Java RpcAnswer from String to byte[] (#1280)
The underlying protocol uses raw bytes, so they should not be required to be
a valid string.
2018-08-20 13:07:13 -07:00
Peter Johnson
5283726cce ntcore: Describe RPC version 0 in spec (#1279) 2018-08-20 13:06:43 -07:00
Peter Johnson
0b8f4b5e6c Add libdl to wpiutil cmake build (#1288)
This is required for dlopen, which is required by libuv.
2018-08-20 00:56:16 -07:00
Peter Johnson
a5f7342fce Run cmake build in travis (#1287) 2018-08-20 00:55:54 -07:00
Peter Johnson
6df7425440 cmake: Compile cscore and wpiutil examples (#1286) 2018-08-19 23:22:52 -07:00
Peter Johnson
d7b68f3f95 Unbreak cmake build (#1285) 2018-08-19 23:21:51 -07:00
Matt Soucy
e28295fc7b Add dependency injection of Subsystem to Command (#1275) 2018-08-19 19:43:21 -07:00
Peter Johnson
6df500e726 Add missing library dependencies in simulation dev executables (#1284) 2018-08-19 19:12:43 -07:00
Peter Johnson
83cfb8b19f UrlParser: fix Has() functions (#1283) 2018-08-19 17:25:42 -07:00
Peter Johnson
82b25d0ec9 spinlock_bench.cpp: Fix wpiformat warning (#1282) 2018-08-19 17:25:20 -07:00
Peter Johnson
b44f27ddfa SendableChooser: Rename addDefault and addObject for clarity (#1239)
Rename addDefault to setDefaultOption and addObject to addOption.

The old names are still available but are marked as deprecated.
2018-08-19 01:51:17 -07:00
Peter Johnson
fa78f30e30 ntcore: Make protocol revision more visible in docs (#1278)
Also add author line to correct document formatting.
2018-08-19 01:38:23 -07:00
Peter Johnson
46ae19d082 wpiutil: Add a mutex-compatible spinlock implementation (#1272)
Note this is only faster than mutex if compiler optimization is enabled.
2018-08-19 01:01:10 -07:00
Peter Johnson
77124a229e Twine: disable part of isValid() that causes spurious warnings (#1271) 2018-08-16 19:35:40 -07:00
PJ Reiniger
1462a5bd46 Fix spacing and const correctness in sim (#1269) 2018-08-15 22:17:59 -07:00
Austin Shalit
44099d9a21 Update errorprone config for Java 10 (#1265) 2018-08-10 20:02:41 -07:00
PJ Reiniger
c2ceebfb9c Add gyro and accelerometer simulator wrappers (#1183) 2018-08-01 21:39:20 -07:00
Peter Johnson
0a0d9245e2 cscore: Add connection strategy to sources (#1252)
By default, sources automatically manage their connection based on whether
any sinks are connected.  This change allows the user to keep a connection
open or force it closed regardless of the number of connected sinks.
2018-07-29 21:18:45 -07:00
Jamie Sinn
7bd3f9f0bd Change ButtonScheduler scope start method to public (#1254)
Fixes #765.
2018-07-29 19:26:48 -07:00
Tyler Veness
4801ae2499 Replace ellipsis characters munged by wpiformat with three periods (#1256)
The Java LinearDigitalFilter class has already been changed.
2018-07-29 19:25:26 -07:00
Peter Johnson
0e9172f9a7 Fix many errorprone warnings (#1247)
This fixes two real bugs:
- TimedRobot had a m_period that was hiding the IterativeRobotBase m_period
  and was not getting initialized.
- PDPSim was swapping two parameters to getCurrent()
2018-07-29 16:47:22 -07:00
Peter Johnson
6db5f80430 docs: Set use_mathjax to true (#1251)
This avoids depending on latex for HTML formula output.
2018-07-29 15:36:28 -07:00
Peter Johnson
898076f698 docs/build.gradle: Use unix EOL (#1250) 2018-07-29 15:14:37 -07:00
Peter Johnson
195e101816 cscore: Use Twine instead of StringRef in API (#1244) 2018-07-29 12:53:41 -07:00
Peter Johnson
97a8f8f47b HAL: Add Doxygen module documentation (#1246)
This helps organize the functions in the generated docs.
2018-07-29 12:49:46 -07:00
Peter Johnson
9408fd5176 Add Doxygen comments for namespaces (#1245) 2018-07-29 12:49:28 -07:00
Thad House
00c2cd7dab Improve JNI loading efficiency (#1224)
A hash is stored for each native library with the name libraryName.hash.
If the library is not found on the system search path, it is extracted to a cache directory.
Extracted libraries are named with the hash appended, so the library will not be
re-extracted if one with the same hash already exists.

Hashing without the hash file requires double traversing if the file is not in the cache,
but it is still faster than creating a new file in most cases.  This won't be needed
after opencv is updated to provide a hash as well.
2018-07-29 10:20:41 -07:00
Austin Shalit
cbb62fb98f Fix errorprone so it is version locked and reports warnings (#1242) 2018-07-29 09:32:22 -07:00
Austin Shalit
a11fcb605d Add UseConcurrentHashMap exception to PMD and clean NOPMDs (#1243) 2018-07-29 09:29:32 -07:00
Austin Shalit
139b1720b2 Fix JavaDoc generation (#1241)
JavaDoc cannot handle redirects so HTTP link does not work anymore.
It also looks like javadoc.options was the wrong thing to set.
Options properly connects external docs to ours.
Re-enabled warnings so these things will pop out if they turn up again.
2018-07-29 09:28:41 -07:00
Austin Shalit
011f0ff536 UsbCamera: Make setConnectVerbose public and add test (#1240) 2018-07-29 00:48:00 -07:00
Thad House
75a67202e5 Add documentation building to repo (#1238)
Running build will now build docs. If you just want to build docs, run :documentation:build
2018-07-28 17:54:41 -07:00
Peter Johnson
186e1dc54b ntcore: Documentation cleanups (#1237) 2018-07-28 17:41:57 -07:00
Peter Johnson
f2393feeef cscore: Documentation cleanups (#1236)
Reformat the C++ documentation to use the normal comment style and
add doxygen grouping.
2018-07-28 17:35:33 -07:00
Peter Johnson
66e35128c9 Use Pimpl idiom for CameraServer
This dramatically reduces header dependencies.
2018-07-28 17:34:42 -07:00
Peter Johnson
6933fefe55 Use Pimpl idiom for Scheduler
Particularly since Scheduler is a singleton, it makes a lot of sense to
use the pointer-to-implementation idiom to reduce header depedencies.
2018-07-28 17:34:42 -07:00
Peter Johnson
fedf828120 Command: Use SmallPtrSet for requirements instead of std::set 2018-07-28 17:34:42 -07:00
Peter Johnson
eb64ea9fc7 MotorSafetyHelper: Use SmallPtrSet instead of std::set 2018-07-28 17:34:42 -07:00
Peter Johnson
826ed7fe3c SmallPtrSet: Fix makeIterator 2018-07-28 17:34:42 -07:00
Peter Johnson
a2d314b0d9 ConditionalCommand.cpp: Remove iostream include 2018-07-28 17:34:42 -07:00
Peter Johnson
6b37ca9f9a UsbCamera: Allow silencing of Connecting message (#1231) 2018-07-28 14:57:41 -07:00
Peter Johnson
0614913f1a Add a way to indicate a Sendable is an actuator (#1226)
SendableBuilder.setActuator() sets the .actuator key in the network table
so dashboards can change behavior on the client side if desired, and also
sets a local flag (retrievable via isActuator()).

Both make drive bases actuators and call setSafeState on them.
2018-07-28 14:04:46 -07:00
Peter Johnson
5fafaf6272 Add confirmation to SendableChooser (#1217)
This echos back the "selected" value to the "active" key to enable dashboards
to display positive feedback to the user that the value is actually set on
the robot side.

Also fixes SendableChooser so it can be safely added to multiple tables.
Changes to "selected" in any table will result in all "active" values being
updated.

Now that adding SendableChooser to multiple tables is supported, an ".instance"
key enables dashboards to treat the same SendableChooser as a common instance
if desired.
2018-07-28 10:43:47 -07:00
Peter Johnson
397a296e25 Add a .controllable key as a standard part of Sendable (#1225)
This indicates whether or not the Sendable listeners are installed.
It is set to true when SendableBuilder.startListeners() starts the listeners,
and set to false when SendableBuilder.stopListeners() stops the listeners.

This allows dashboards to choose to change their widget display based on
whether or not the value is actually controllable.
2018-07-28 10:42:31 -07:00
Thad House
1d9ed8f458 Fix SensorUtil issues (#1194)
C++ PDP was missing module check, and channel check called module.
Java docs said 1 based instead of 0 based.
2018-07-28 09:51:49 -07:00
Austin Shalit
bbb622aaa6 Revert "Use ASAN when on Clang (#1187)" (#1234)
This reverts commit 340b26bada.

Closes #1232

We are reverting this because it broke Mac builds. The root cause of
this is a requirement that the entire application must be built with ASAN
to link properly. For more information about why this is see the below link.

https://github.com/google/sanitizers/wiki/AddressSanitizerContainerOverflow#false-positives
2018-07-28 09:50:25 -07:00
Peter Johnson
8cbe7a6257 cscore: Move CvSourceImpl placeholders into SourceImpl (#1230)
This makes it easier to implement new non-camera Sources.
2018-07-27 23:15:35 -07:00
Peter Johnson
932308b497 MjpegServer: Add ability to set compression, etc in code (#1229)
This allows code to set the stream compression, resolution, and FPS used if
not specified in HTTP parameters by the client.
2018-07-27 23:00:15 -07:00
Peter Johnson
9398278250 cscore: Add properties support to VideoSink (#1228)
Refactor the Property internals into PropertyContainer.
2018-07-27 22:12:30 -07:00
Peter Johnson
c9a75a119a cscore: Support multiple levels of JPEG compression (#1223)
This allows two streams with different compression levels, and also allows
a stream to receive a different compression level than provided by a JPEG
camera (decompress and recompress).
2018-07-27 21:51:40 -07:00
Peter Johnson
04ee8dbe79 UsbCamera: In JPEG mode, get size from image instead of mode (#1222)
Some cameras will accept a different resolution as the mode but then provide
JPEG images of a different size.  Trust the JPEG image size if available.

This also validates the JPEG image is actually JPEG.
2018-07-27 21:50:28 -07:00
Peter Johnson
7fd7192b16 Disable UvGetAddrInfo Concurrent test on Windows (#1227)
This test likes to intermittently hang for some unknown reason, so disable it.
2018-07-27 21:41:04 -07:00
Thad House
63c1f80d60 halsim_ds_socket: Update tag parsing, and add rumble support (#1214)
Outputs are now sent. Ensure only the proper number of outputs are actually sent though.

Also adds match time, and proper enable tags.
2018-07-26 01:30:29 -07:00
Tyler Veness
d54c2665dc Update UsageReporting enums and their uses for 2019 (#1218) 2018-07-25 19:58:05 -07:00
Peter Johnson
8aac46542d Add a SimpleBufferPool for uv::Buffer (#1215)
Buffers are reused on a regular basis in many use cases.
2018-07-25 00:58:54 -07:00
Thad House
c78e1499d7 Remove appveyor artifacts, and only build 64 bit (#1212)
There is a limit on artifacts, and doing both builds gains little and doubles build time.
2018-07-22 23:05:25 -07:00
Thad House
a34df5589e Switch DS Sim Sockets to use UV loops (#1211)
Also adds the simulation packet to force switch the DS to local.
2018-07-22 23:03:55 -07:00
PJ Reiniger
eb2c6e19f8 Add sim hooks to set match data (#1191) 2018-07-22 19:43:24 -07:00
Peter Johnson
c25d48fd0c HttpParser: Add Reset() function (#1210)
This allows reuse of the HttpParser object for multiple requests.
2018-07-22 19:41:23 -07:00
Tyler Veness
794403dcea Add shim headers for headers moved to cameraserver and frc folders
Shim headers were placed in the original location to warn users that they
are deprecated and that they should use the headers in the folders
instead.
2018-07-22 19:40:57 -07:00
Tyler Veness
d89b7dd412 Move CameraServer and WPILib headers into their own folder
The old headers were moved into folders because doing so avoids polluting
the system include directories.

Folder names were also normalized to lowercase.
2018-07-22 19:40:57 -07:00
Peter Johnson
31ced30c1e HttpParser: Change Execute() to return StringRef (#1209)
This is more user-friendly than returning the number of parsed bytes.
2018-07-22 15:07:22 -07:00
Jeremy White
74a306d47a Add halsim_ds_socket to allow a simulated robot to talk to the real DS (#1180)
This implements enough of the UDP and TCP protocol used by the FRC
driver station to allow us to talk to either QDriverStation or to the
real Driver Station.

This was inspired by a similar function in Toast by Jaci, and also
uses a lot of the research found in the QDriverStation project.
2018-07-22 15:00:06 -07:00
Peter Johnson
5bf5821138 Cleanup docs in uv::Stream and uv::Tcp (#1207) 2018-07-22 13:01:14 -07:00
Peter Johnson
eed28a5852 Add sockaddr_in overloads for uv::Tcp and uv::Udp (#1206)
These help avoid the need for reinterpret_casts in common use cases.
2018-07-22 13:01:00 -07:00
Peter Johnson
435e026c08 uv::Loop: Add user-defined data (#1205) 2018-07-22 13:00:47 -07:00
Peter Johnson
739267d36d Add Reuse function to uv::Tcp (#1208)
This allows reusing the Tcp object in cases when the connection errors out.
2018-07-22 12:31:50 -07:00
Jeremy White
85118a023d Minor fixes required to enable the simulated robots to run (#1181)
* Fix bugs in PacGoat Java example that prevent it from working.

We have conflicting ports in use, each of which causes a crash
at startup.  These changes fix those issues.

* Change to avoid a crash in Visual C++ when running simulated code.

Without this change, we would get a crash in SendableRobotBase when
constructing a Twine from the 'kOptions' constant string;
we'd get an unable to access memory exception.
2018-07-22 00:58:42 -07:00
Tyler Veness
ae72c0b296 Clean up style issues in wpilibj_frcnetcomm.py (#1199) 2018-07-21 23:50:40 -07:00
Thad House
b72885b4f8 Remove wildcard dep version from gazebo msg (#1203)
We don't want any wildcards in allwpilib.
Also uses plugin repo for protobuf rather then mavenCentral.
2018-07-21 23:50:01 -07:00
Peter Johnson
70b0d7cb03 UDPClient: Add receive functionality (#1204) 2018-07-21 23:49:16 -07:00
Thad House
053ca47d4e Update gradle dependencies (#1202)
ErrorProne fixes some Java 9 issues, vscode cpp fixes a bug and updates for lazy tasks, jni updates for lazy tasks
2018-07-20 16:56:22 -07:00
Jeremy White
74efe5aafe Get halsim_gazebo building again (#1201) 2018-07-20 16:24:48 -07:00
Thad House
fe5d7dd6ba Move DS caching from user level to the HAL (#1143)
Also switch eventName and gameSpecificData to fixed 64-byte arrays to avoid mallocs and
extra NetComm calls.  This behavior matches 2018 LabView.

The DS caching is kept in Java to avoid JNI and/or massive amounts of allocations.
This does not increase latency because Java still only hits NetComm once.

Moving the DS caching benefits all languages other than Java, because it avoids the need
for individual implementations.  If caching is ever added to NetComm, it will then only be
necessary to remove it from the HAL and Java rather than all languages.
2018-07-18 22:22:41 -07:00
Thad House
0b5df467e1 Update Native Utils to fix static allocations (#1196)
Should fix lag after 15 or so builds that was being seen with daemon.
2018-07-18 22:14:24 -07:00
Thad House
80134164a4 Move Java main function from library to user code (#1148)
It is much more reliable than the old approach, as it no longer depends on a magic string
in a manifest file, and if the user changes their main class, or makes it not import from
something RobotBase, it will fail to compile instead of failing at runtime.

With requiring an importer, we should be able to automate this in the importer.
2018-07-18 22:01:19 -07:00
Thad House
76b26c2df5 HAL_InitializePWMPort: Check for MXP port (#1195)
Previously all channels were incorrectly handled as MXP channels.

Closes #1182
2018-07-18 20:39:05 -07:00
Thad House
f8635e8abf Update to gradle 4.9 (#1193)
4.9 will be needed for some things being added to a few of our plugins. It adds the new lazy configuration tasks which help a good amount in some cases.
2018-07-18 20:36:10 -07:00
Peter Johnson
4029b5d84d Update gazebo plugins to Gazebo 9 (#1189)
Note: This breaks Gazebo 7 support.
2018-07-18 20:16:43 -07:00
Thad House
4c527b9b08 Add vscode intellisense settings (#1173) 2018-07-18 12:26:29 -07:00
Peter Johnson
caa03d23a3 Make JxArrayRef less error-prone for jxArray (#1190)
Add a length-taking overload so that if a length happens to be provided for
a jarray, the direct byte buffer overload is not used.
2018-07-17 20:19:49 -07:00
Peter Johnson
297863b17a Add HttpParser and UrlParser C++ wrappers for http_parser. 2018-07-17 02:24:56 -07:00
Peter Johnson
1992b67ee3 Import nodejs/http-parser.
Upstream version: 5b76466c6b9063e2c5982423962a16f7319c81f8
2018-07-17 02:24:56 -07:00
Peter Johnson
e2314f3528 wpiutil: Add C++ libuv wrappers (#1166)
- Provide an EventLoopRunner to run uv::Loop on a separate thread.

- Add raw_ostream wrapper for uv::Buffer.
2018-07-17 01:06:24 -07:00
Jaci Brunning
340b26bada Use ASAN when on Clang (#1187)
This currently only affects MacOS builds, as that's the only platform where clang is used.
2018-07-16 22:48:02 -07:00
Thad House
7f000fecc4 Force a DS mutex release on shutdown on desktop (#1188)
This fixes some issues with freezing tests.
2018-07-16 22:42:04 -07:00
PJ Reiniger
76c901ce78 Add simple motor simulation classes (#1117) 2018-07-12 20:11:26 -07:00
Thad House
57fc614074 Compile C headers in C mode, and fix cscore C (#1179) 2018-07-08 15:42:59 -07:00
Thad House
89d15f061b Fix main function initialization (#1176)
I don't have a good way to ensure this always works, so this is going to be a documentation issue.
But initializeHardwareConfiguration is now reentrant, so we can just have all tests call it.
2018-07-08 15:41:31 -07:00
Austin Shalit
f5b1028b5a Fix race conditions in command tests by increasing the delay time (#1178) 2018-07-08 12:39:15 -07:00
David Vo
ad3e2d7d3b Make HAL headers C-compatible (#1177)
Also fix the return type of HAL_IsNewControlData() and HAL_MatchType's type.

Since UsageReporting is intended to be namespaced, it is hidden when this is being used in C.

Fixes: #476
Closes: #535
Ref: #1122
2018-07-07 22:18:03 -07:00
Thad House
3818a8b3b6 Update to gradle 4.8.1 (#1174) 2018-07-04 09:41:18 -07:00
Thad House
59e8b60267 Add HAL Documentation (#1132) 2018-07-04 00:18:18 -07:00
Peter Johnson
de5d7d3c17 Only use priority_mutex on RoboRIO by default. (#1172)
On all Linux platforms it can be specifically requested by defining
WPI_USE_PRIORITY_MUTEX.
2018-07-03 20:35:07 -07:00
Jeremy White
ebd41fe0bb Bring back the gazebo plugins (#1063)
The models and meshes are not included. We will need
to find an alternate way to reintegrate these and use them.

* Add simulation/gz_msgs back, and build with Gradle.

* Add back in the frc simulation plugins for gazebo.

* Add a new shared library, halsim_gazebo.

This library will become the interface between the
HAL sim layer and gazebo.

* Preserve the first channel number used in created Encoders in the Sim MockData.

This allows us to use the DIO channel number to connect with simulated encoders.

* Have the HAL Simulator set the reverse direction on creation.

This enables a simulator to be aware of the direction.

* Add a drive_motor plugin.

This is a bit of a 'magic' motor, which allows us to build robot
models that drive in a more realistic fashion.  It does this
by apply forces directly to the chassis, rather than relying on
the complex motion dynamics of a driven wheel.

This in turn allows the model to reduce wheel friction,
reducing scrub, and allowing for a more natural driving experience.
2018-06-30 00:45:21 -07:00
Peter Johnson
70960b0251 Signal: rename Signal to Signal_mt and Signal_st to Signal.
The single-threaded version is fine for most of the use cases we're planning
on, and is half the size on most platforms.
2018-06-30 00:21:09 -07:00
Peter Johnson
c8afe9bc2f Signal: Optimize to use plain std::function.
This optimizes the common case of a single simple callback (e.g. std::function
or lambda) so no additional allocation is required.  As a Connection return
value is not possible in this case, provide a separate connect_connection()
function to provide that.
2018-06-30 00:21:09 -07:00
Peter Johnson
1ecaaafa6c Discuss and include licenses for third party software. (#1101) 2018-06-29 11:06:43 -07:00
Thad House
33a01b3146 Add maven documentation (#1140) 2018-06-28 20:07:31 -07:00
Austin Shalit
1d8456e2bf Move FRCNetComm.java into generated directory (#1168) 2018-06-28 13:37:14 -07:00
Peter Johnson
b5bacc09a7 libuv: Silence cast-function-type warning on GCC 8. (#1169)
GCC 8 treats void(*)(void) specially to silence the warning.
2018-06-28 00:33:24 -07:00
Peter Johnson
876c650471 wpiutil: Add a signal-slot implementation. (#1163)
Imported from https://github.com/palacaze/sigslot

Classes were renamed from lowercase_me to UppercaseMe style, primarily
to avoid conflicting with the C standard library "signal" function.  They
were also moved to the "wpi::sig" namespace.
2018-06-27 23:01:17 -07:00
Austin Shalit
3eae079db4 Add PDP usage reporting (#1167) 2018-06-24 23:48:22 -07:00
Peter Johnson
122fdf48b2 libuv: Hook up to build. 2018-06-24 10:31:55 -07:00
Peter Johnson
d94f49b3ba libuv: Silence clang compiler warning in uv-common.c 2018-06-24 10:31:55 -07:00
Peter Johnson
39670fc9c0 libuv: Add pragmas for win32 libraries. 2018-06-24 10:31:55 -07:00
Peter Johnson
6f0d50b9cb libuv: Avoid conditional-true compiler warning.
Instead use a preprocessor macro to comment out the code as necessary.
2018-06-24 10:31:55 -07:00
Peter Johnson
873b2ed13c libuv: Add missing casts. 2018-06-24 10:31:55 -07:00
Peter Johnson
321c144d21 libuv: Remove extern "C" from uv.h.
This results in name-mangling of the uv symbols and thereby avoids potential
symbol conflicts with system libuv installations.
2018-06-24 10:31:55 -07:00
Peter Johnson
13e1af259c libuv: Remove MSVC 2008 stdint from uv.h and uv-win.h. 2018-06-24 10:31:55 -07:00
Peter Johnson
9d7792ead0 libuv: Remove aix, os390, and sunos from uv-unix.h. 2018-06-24 10:31:55 -07:00
Peter Johnson
6d93d3c250 libuv: Rename source files from .c to .cpp.
This ensures they will actually get compiled as C++.
2018-06-24 10:31:55 -07:00
Peter Johnson
156822dbc8 Import libuv 1.21.0. 2018-06-24 10:31:55 -07:00
Peter Johnson
208f82d6f2 Revert "Add libuv dependency (#1109)"
This reverts commit 859b457c3d.
2018-06-24 10:31:55 -07:00
Tyler Veness
a818c7fd47 Add loop timing to IterativeRobot and TimedRobot (#781) 2018-06-24 00:29:21 -07:00
Austin Shalit
50b13d2f36 Convert UnitTestUtility to a JUnit 5 MockHardwareExtension (#1153)
Only initialize the HAL once.
2018-06-24 00:19:45 -07:00
Tyler Veness
b7807bf9d2 Clean up Command container iteration code (#73) 2018-06-23 17:41:45 -07:00
Peter Johnson
ea7d11b1db Twine: Make isNull() public. (#1162)
This makes it possible to pass "null" Twines and detect it in the callee.
2018-06-23 16:13:50 -07:00
Tyler Veness
212f378d08 Replace globalError in ErrorBase with a global set of all errors (#615) 2018-06-18 00:13:28 -07:00
Thad House
2faba39b58 Change wpilibc artifact name to match standard (#1158) 2018-06-17 20:28:43 -07:00
Thad House
064989f2e4 Fix projects having different version numbers (#1113) 2018-06-17 19:59:49 -07:00
Thad House
6b1b4796c2 Remove Link Script (#1159)
This is no longer required due to the move to GradleRIO (it was only used for Eclipse).
2018-06-17 19:52:18 -07:00
Thad House
1ebb83e0f2 Remove explicit close() from Gyro interface (#1152)
It's not needed, as extending AutoClosable is enough.
2018-06-11 15:02:50 -07:00
Austin Shalit
9108a93598 Switch non-integration tests to JUnit 5 (#1120) 2018-06-11 15:01:49 -07:00
Thad House
c7e97f45f5 Add RobotPeriodic functions to default templates. (#1149) 2018-06-10 20:16:54 -07:00
Thad House
5af85dd1bb Explicitly states the gyro direction contract for the Gyro interface (#1151) 2018-06-10 20:13:36 -07:00
Thad House
b20158015c Update java robot class docs (#1150) 2018-06-10 20:12:41 -07:00
PJ Reiniger
b1bb63f9a4 Add ADX Simulator tests (#1142) 2018-06-08 13:25:39 -07:00
Thad House
056e68f2ae Use new CAN API for PDP (#1081) 2018-06-07 22:31:26 -07:00
Thad House
f6e4df6a18 Remove OS Serial Port (#1141)
It was done as a shim fix around some VISA issues that don't seem to exist anymore. Was never really tested, and I don't think ever actually worked.
2018-06-07 20:51:26 -07:00
Thad House
0cde67143a Upgrade to gradle 4.8 (#1136) 2018-06-07 20:49:25 -07:00
Thad House
1f9645afe9 Fix CAN API reads (#1139) 2018-06-07 20:49:03 -07:00
Thad House
86285b427f Removes MSVC 2013 Shims (#1130)
We have done things recently that have broken any builds before VS 2015
2018-06-03 17:16:51 -07:00
Austin Shalit
e548a5f705 Update and enable PMD 6.3.0 (#1107) 2018-06-03 10:00:53 -07:00
Thad House
8eafe7f325 Solve some safety issues with RPCs (#1127)
Java would never properly dispose, and C++'s were easy to respond after disposing.
We now return a bool if the call was successful or not.
2018-06-03 08:43:48 -07:00
Peter Johnson
6aebba5452 Import MapVector from LLVM. (#1128) 2018-06-03 08:39:14 -07:00
Peter Johnson
664a3c2463 ntcore: Fix C API polling array returns. (#1126)
The implementation of ConvertToC for arrays was broken.  Also change it
to be templated on the returned array type, rather than passing the array.
This makes the uses a bit more clean.
2018-06-01 13:45:33 -07:00
Tyler Veness
321dfaf0a2 Remove non-existent directory from .styleguide (#1124) 2018-06-01 09:36:12 -07:00
Tyler Veness
8373e0361b Made Controller interface public (#1123) 2018-06-01 01:00:24 -07:00
Tyler Veness
8c680a26f8 Moved C++ comments from source files to headers (#1111)
Also sorted functions in C++ sources to match order in related headers.
2018-05-31 20:47:15 -07:00
Thad House
d9971a705a Throw UncleanStatusException rather then RuntimeException (#1114) 2018-05-30 23:36:40 -07:00
Thad House
85fe722f4c Fixes JNI files not getting cleaned on rebuild (#1121)
If a JNI file was added then removed without a clean (like a branch change)
The symbol check would fail because extra headers wouldnt get removed.
2018-05-30 23:24:00 -07:00
Thad House
c04f463b78 Makes FRCNetComm interfaces static final classes. (#1118)
Closes #1104
2018-05-29 15:55:38 -07:00
Thad House
307da3ad2d Simplify allocation of JNI global classes and exceptions (#1110)
Helps ensure they get freed properly (We have had a few cases before where this wasn't the case).
2018-05-29 15:44:16 -07:00
Austin Shalit
39f80730de Disable broken ntcore tests using JUnit 5 (#1116) 2018-05-28 23:07:28 -07:00
Tyler Veness
35cfe0d92c Add comment to FRCNetComm.java noting that it is autogenerated (#1115) 2018-05-28 18:29:42 -07:00
Thad House
8d218dbca4 Add support for unit testing from GradleRIO for C++ projects (#1094)
In order for this to properly work, we need to remove the main code.
Then the test component will actually have the main in it.  Example tests will be added later.
2018-05-28 02:07:03 -04:00
Thad House
938f835142 Update things deprecated in gradle 4.8; remove unused function (#1093) 2018-05-28 02:00:03 -04:00
Thad House
1dc55c03dc Add Windows PDBs to release zips, and skip strip on mac (#1092)
Mac shared libraries drop about 10% in size, but the symbol library is about 5x the size of the original library.
2018-05-28 01:58:46 -04:00
Thad House
859b457c3d Add libuv dependency (#1109) 2018-05-28 01:56:58 -04:00
Tyler Veness
8958c4eabd Fixed wpilibj_frcnetcomm.py and added invocation to Travis (#1106)
Making Travis run wpilibj_frcnetcomm.py will help avoid bitrot in
FRCNetComm.java in the future. Formatting was also enabled on Python
source files and FRCNetComm.java was added back to the generated files
list.
2018-05-28 00:53:39 -04:00
Austin Shalit
7c9517ce5b Fix gain encapsulation in LinearDigitalFilter (#1105) 2018-05-28 00:52:59 -04:00
Thad House
5bf9720ccf Use externally built Google Test (#1108) 2018-05-28 00:44:12 -04:00
Peter Johnson
d1587ed2c1 LICENSE.txt: Update copyright date to 2018. (#1100) 2018-05-26 10:57:33 -04:00
Thad House
5fcb67aaf5 Fix Checkstyle (#1095)
Broken by merge of earlier change.
2018-05-24 22:56:36 -04:00
Austin Shalit
2e5fece594 Add utility class tests (#871)
Checks for classes that only have static methods.
2018-05-24 20:39:15 -04:00
Thad House
863cfde394 Adds tests to ensure all examples have matching item in json file (#1079)
Also checks that all items in the json file have a matching example
One was missing from C++, that example was added (The one in eclipse was completely wrong)
2018-05-24 20:08:37 -04:00
Thad House
c4728d291e Makes CAN API initializer setup HAL (#1084) 2018-05-24 20:07:03 -04:00
Thad House
fb45a5b314 Allows passing in the main robot class from the command line (#1091) 2018-05-24 20:05:58 -04:00
Thad House
86c1f8ae50 Fixes initialization when not using the provided main (#1085)
Helpful for simulation, which might not use our main.
2018-05-24 20:03:19 -04:00
Thad House
381c25c573 Fixes interrupts not getting closed properly. (#1088)
The threads being created were never getting cleaned up.
2018-05-24 20:02:13 -04:00
Thad House
62d5301b1f Changes notifier to be closable. (#1090)
Fixes #1089
2018-05-24 19:56:29 -04:00
Austin Shalit
40cc743cc7 Enable checkstyle on cscore, ntcore, wpiutil (#1032)
Also update to version 8.10.
2018-05-24 00:31:04 -04:00
Tyler Veness
ecfe95383c Made SensorBase a utility class and renamed it to SensorUtil (#813) 2018-05-23 23:22:30 -04:00
Austin Shalit
ba93f79d8b Fix mac builds (#1087) 2018-05-23 21:36:43 -04:00
Peter Johnson
dcc2764844 Default to requiring frc namespace for wpilibc. (#972)
Instead of defining NAMESPACED_WPILIB to remove the "using namespace frc"
shim in Base.h, instead require NO_NAMESPACED_WPILIB be defined to add it.

Fix up various examples to use correct namespacing.
2018-05-22 23:33:50 -07:00
Thad House
cbaff52850 Implements AutoCloseable for types, replacing free() (#1048) 2018-05-22 23:33:17 -07:00
Peter Johnson
a2ecb1027a Update LLVM to latest upstream. (#1080)
Also change header guards to WPI header guards.
Remove StringRef::c_str() customization, replacing the handful of uses with Twine or SmallString.
TCPStream: Include errno.h and make Windows includes lowercase for consistency.

Upstream LLVM version: eb4186cca7924fb1706357545311a2fa3de40c59
2018-05-22 23:31:08 -07:00
Thad House
680aabbe7c Add new CAN API (#1036) 2018-05-21 16:09:38 -07:00
Thad House
55b0fe0082 Fixes JNI symbol check on VS 2015 (#1078) 2018-05-19 20:06:05 -07:00
Thad House
8b8c3d5462 Updates NativeUtils dependency (#1077)
New version handles dependency extraction better, and easier for IDEs
2018-05-19 18:49:29 -07:00
Thad House
38a7786f22 Remove spotless (#1074)
Enforcing Line endings isn't a good idea for cross system development,
and wpiformat handles everything else
2018-05-19 18:48:38 -07:00
Tyler Veness
df182f382e PIDController now supports composition (#976)
For example, an outer position feedback controller can now drive the
reference of an inner velocity feedback controller.
2018-05-19 01:32:43 -07:00
Thad House
5cc7573574 Updates JNI to support embedded jni libraries for easier setup (#1075) 2018-05-19 01:31:24 -07:00
Austin Shalit
17401e10f0 Add setting to invert the right side of the drive (#1045) 2018-05-19 01:22:20 -07:00
David Vo
73439d8213 DriverStation: Fix getStickButtonPressed/Released (#856)
This fixes DriverStation in WPILibJ to check the existence of buttons and hold the data mutex in getStickButtonPressed() and getStickButtonReleased(), as the corresponding methods in WPILibC do.
2018-05-16 20:00:48 -07:00
Tyler Veness
72a79aac53 Fixed the names of the arguments to some C++ drive classes (#1070)
The docs already have the correct name, but some headers and sources
weren't updated. Java doesn't have this mistake.
2018-05-16 19:55:27 -07:00
Tyler Veness
c89678971c Replaced the START_ROBOT_CLASS() macro with a template function (#1050)
The START_ROBOT_CLASS() macro's main() now calls this function through a
deprecated proxy function to encourage users to switch.
2018-05-16 19:54:39 -07:00
Tyler Veness
64b03704f8 Rename Joystick default channel constants (#904)
The new naming makes it more clear that the constants are intended to be used
with the channel setters.
2018-05-16 19:53:16 -07:00
Tyler Veness
630fc55bde Implemented synchronous PID controller (#993)
SynchronousPID provides a Calculate() function for teams to call themselves
instead of running the controller with a Notifier.
2018-05-16 19:51:37 -07:00
Austin Shalit
f90e429bf9 Add removeAll to preferences (#987)
This removes all keys except for .type.
2018-05-16 19:50:35 -07:00
Austin Shalit
2e0709f05b Add spotless to check line endings (#1055) 2018-05-16 19:47:35 -07:00
Thad House
11d46713d1 Fixes pessimistic std::move (#1069)
Also adds test to ensure all the sim headers get compiled

Closes #1068
2018-05-16 19:45:46 -07:00
Tyler Veness
ef442d775d Refactored DriverStation.java unplugged message handling to match C++ (#808)
Also fixed error handling in C++ for out-of-bounds arguments.
2018-05-16 00:13:52 -07:00
Tyler Veness
3e6c3c3e98 Replaces Timer in PIDController.java with Notifier (#878)
Fixes #877.
2018-05-16 00:02:21 -07:00
Tyler Veness
8d57b73b41 Fixed naming convention of static variable in TimedRobot.java (#876) 2018-05-15 23:59:38 -07:00
Tyler Veness
d8c8643b52 Format HTML and XML files (#944)
Generated by wpilibsuite/styleguide#52.
2018-05-15 23:58:20 -07:00
Tyler Veness
adb6098353 Removed extra newlines after open curly braces (#935)
Generated by wpilibsuite/styleguide#115.
2018-05-15 23:57:24 -07:00
Thad House
938d5379e6 Adds command examples to built examples (#1062) 2018-05-15 23:56:03 -07:00
Peter Johnson
7cd15aa049 Re-enable JsonIteratorObjectTest.KeyValue. 2018-05-15 22:31:35 -07:00
Peter Johnson
f8ed48af98 Update json from upstream version 3.1.2.
This adds support for ubjson and makes a number of bugfixes.

Binary input and output have switched from strings to uint8_t arrays.
2018-05-15 22:31:35 -07:00
Peter Johnson
c274d1790f StringRef: Add comparison operators against const char*. 2018-05-15 22:31:35 -07:00
Peter Johnson
6699f86361 Make most StringRef functions noexcept. 2018-05-15 22:31:35 -07:00
Peter Johnson
c2b1ed3edd ArrayRef: Add value_type typedef like std containers. 2018-05-15 22:31:35 -07:00
Peter Johnson
2c27ad073a raw_istream enhancements. 2018-05-15 22:31:35 -07:00
Peter Johnson
31bb55c319 Add std::vector and unsigned variants of raw_ostream. 2018-05-15 22:31:35 -07:00
Peter Johnson
dd4230d743 StringMap: Add decrement operations to iterator. 2018-05-15 22:31:35 -07:00
Thad House
cff475c1fc Moves C++ templates and examples to match gradle setup (#1065) 2018-05-15 21:25:24 -07:00
Thad House
d564e19ef3 Only prints the debug binary message once per build (#1066) 2018-05-15 21:24:44 -07:00
Thad House
1d6eb629ad Adds Objective C++ Build capabilities to cscore mac (#1029) 2018-05-14 19:34:26 -07:00
Thad House
406e18663d Switches NotifyListenerVector to SmallVector (#1004) 2018-05-14 18:17:34 -07:00
Thad House
ab70220ecf Makes SPI edge changes more obvious (#1056)
Rising and Falling mean the opposite when active is set high vs low. Leading and trailing makes much more sense.

Closes #925
2018-05-14 18:16:36 -07:00
Thad House
560123ab7d Fixes command folder name in templates.json (#1061) 2018-05-14 00:19:47 -07:00
Thad House
4e1964156e Removes 32 bit configs for linux and mac. (#1060)
For mac, 32 bit will never be supported. Apple has dropped all support.

For 32 bit linux, vscode explicitly does not support it, and it is difficult to find anybody using a 32 bit os.
2018-05-13 23:27:44 -07:00
Tyler Veness
5ff3d837b6 Fix compilation with GCC 8 (#1051)
The anonymous namespace was renamed due to -Wsubobject-linkage complaining
about a field created in a GTest template class (CborRoundtripTestParam)
being defined in an anonymous namespace. See
https://stackoverflow.com/a/37723265.
2018-05-13 23:11:13 -07:00
Thad House
74d7107ac6 Add AppVeyor Build Support (#1013) 2018-05-13 22:23:35 -07:00
Thad House
e21a246a4d Make the HAL self initialize when ever any initialization function is called (#1012) 2018-05-13 22:02:47 -07:00
Thad House
59a8e9da57 Fixes gradle wpilibj classpath for editors (#1047) 2018-05-13 22:00:56 -07:00
Thad House
795c60da01 Adds a testCpp task to all projects (#1014) 2018-05-13 22:00:36 -07:00
Thad House
f3db329115 Enables MyRobot project (#1028) 2018-05-13 22:00:15 -07:00
Thad House
f07799c67b Disables unstable and failing unit tests (#1057) 2018-05-13 21:59:45 -07:00
Thad House
eec4f53a65 Forces CRLF files to LF (#1054) 2018-05-13 19:37:20 -07:00
Tyler Veness
01d8d0c795 Moved C++ header includes out of extern "C" and added missing C header includes (#1053) 2018-05-13 19:05:39 -07:00
Tyler Veness
6729a7d6b1 Run wpiformat on merged repo (#1021) 2018-05-13 17:09:56 -07:00
Thad House
0babbf317c Adds CMake Readme (#1042) 2018-05-13 14:12:12 -07:00
Thad House
337e89cf6e Adds JNI Simulator interface and updated Sim API (#1002)
The simulator was generated by https://github.com/ThadHouse/SimulatorGenerator
2018-05-11 12:38:23 -07:00
Thad House
1046371349 Fixes some JNI issues with method calling and class storage (#1043) 2018-05-10 22:38:21 -07:00
Austin Shalit
665a6e356a Allow users to feed the watchdog contained in drive objects (#1044) 2018-05-09 20:18:55 -07:00
Dustin Spicuzza
b7ea481bf9 Notifier: reset updatedAlarm before waiting (#946)
- If this isn't done, then the wait will always be performed at least twice
2018-05-04 18:29:42 -07:00
Peter Johnson
7a34f5d17d Check for nullptr return from malloc, calloc, and realloc. (#1023)
These are used in ntcore and cscore.  Add inline null-checking versions
to wpi/memory.h and use them throughout.
2018-05-04 17:55:46 -07:00
Thad House
e8d5759d95 Actually have the cscore examples build, and makes them build only on linux (#1030) 2018-05-04 17:54:56 -07:00
Thad House
eeae84c715 Adds cscore examples to builds (#1027) 2018-05-04 16:51:50 -07:00
Thad House
dab6f40b46 Moves examples.xml to json, and adds template json (#1026) 2018-05-04 16:51:37 -07:00
Peter Johnson
5c2c5ccd07 Remove atomic static shim. (#1020)
This was only useful for pre-VS2015 and was only being used in one place.
2018-05-04 02:07:27 -07:00
Peter Johnson
8cbfe35bd4 ntcore: Remove MSVC 2013 shim. (#1018) 2018-05-04 02:06:45 -07:00
Thad House
954f8c40f5 Adds CMake Builds (#1015) 2018-05-02 21:15:30 -07:00
Peter Johnson
6a49173cea Update cscore examples for llvm to wpi rename. (#1016) 2018-05-02 20:56:55 -07:00
Peter Johnson
1043aef7f7 ntcore: Make header actually a C header (#1007) 2018-05-01 22:51:28 -07:00
Thad House
f7bcf53059 HAL: wait for all objects to release handle before freeing (#1011)
This avoids a race on free.
2018-05-01 19:26:25 -07:00
Tyler Veness
6a159c5bd2 Miscellaneous cleanups (#1008) 2018-04-30 10:30:16 -07:00
Thad House
a098814ea0 Removes the make_unique shim for c++11 (#1010)
All of our compilers support c++14 now.
2018-04-30 10:28:34 -07:00
Peter Johnson
a28832e52f Add backwards compatibility shims for old wpiutil headers.
These generate a warning when included, then include the old header.

Note for GCC, #warning is used; this requires -std=gnu++14 instead of
-std=c++14 (otherwise the warning is treated as an error because #warning is
a GNU extension).  On MSVC, #pragma message is used, which is a bit
unsatisfactory as the message doesn't say where it was included from.

The llvm shim headers also include a llvm namespace shim.
2018-04-30 10:22:54 -07:00
Peter Johnson
f84018af5f Move entirety of llvm namespace to wpi namespace.
During shared library loading, a different libLLVM can be pulled in, causing
llvm symbols from dependent libraries to resolve to that library instead of
this one. This has been seen in the wild with the Mesa OpenGL implementation
in JavaFX applications (see wpilibsuite/shuffleboard#361).

This is clearly a very breaking change. For some level of backwards
compatibility, a namespace alias from llvm to wpi is performed in the "llvm"
headers.  Unfortunately, forward declarations of llvm classes will still break,
but compilers seem to generate clear error messages in those cases
("namespace alias 'llvm' not allowed here, assuming 'wpi'").

This change also moves all the wpiutil headers to a single "wpi" subdirectory
from the previously split "llvm", "support", "tcpsockets", and "udpsockets".
Shim headers will be added for backwards compatibility in a later commit.
2018-04-30 10:22:54 -07:00
Tyler Veness
93859eb84f TimedRobot now uses the Notifier HAL API (#942)
Fixes #941.
2018-04-30 00:00:09 -07:00
Tyler Veness
e7cf6bf7c5 Fixed wpilibj GenericHID.getType() (#969)
It was using array indexing to map the return value of
DriverStation.getJoystickType() to HIDType when the enum should instead be
constructed from the int value. C++ already does this.

Fixes #968.
2018-04-29 23:56:00 -07:00
Peter Johnson
a8fd88840d Revert "Uses ComputeDigitalMask function across HAL DIO (#837)" (#1005)
This reverts commit c84bd744c8.
2018-04-29 21:48:53 -07:00
Thad House
c84bd744c8 Uses ComputeDigitalMask function across HAL DIO (#837)
less risk for errors in the future.
2018-04-29 21:12:15 -07:00
Thad House
11b99a016a Removes old version files from git ignore (#1003) 2018-04-29 20:28:45 -07:00
Brennon Brimhall
dfa46cbddd Fix typos, keep formatting consistent. (#974) 2018-04-29 20:15:50 -07:00
Austin Shalit
91151e33bb Add out to gitignore (#988) 2018-04-29 20:14:53 -07:00
Tyler Veness
2ed9ae1652 Removed unused ROBOT_TASK_PRIORITY constant from RobotBase.java (#991) 2018-04-29 20:14:06 -07:00
Austin Shalit
fdfea35161 Fix JavaDoc tag (#995)
The isParented method had an incorrect javadoc tag for the return value.
2018-04-29 20:13:18 -07:00
Austin Shalit
47783842e9 Fix JavaDoc tag in Differential Drive (#996)
The `{@link SpeedControllerGroup}` was broken because SpeedControllerGroup was not imported.
2018-04-29 20:12:35 -07:00
Thad House
7f88cf768d New 2018 and later build setup (#1001) 2018-04-29 13:29:07 -07:00
Thad House
cb2c9eb6d5 Remove gmock and builds from utility libraries (#999) 2018-04-27 22:14:26 -07:00
Peter Johnson
4a1e520758 Merge cscore into allwpilib. 2018-04-27 20:02:15 -07:00
Peter Johnson
b3aa659f93 Merge ntcore into allwpilib. 2018-04-27 20:02:05 -07:00
Peter Johnson
4870d83ad1 Merge wpiutil into allwpilib. 2018-04-27 20:01:38 -07:00
Peter Johnson
7210a8fd28 Prepare ntcore for merge into allwpilib. 2018-04-27 19:57:35 -07:00
Peter Johnson
0f947613a9 Prepare wpiutil for merge into allwpilib. 2018-04-27 19:56:51 -07:00
Peter Johnson
ea73c10cd8 Prepare cscore for merge into allwpilib. 2018-04-27 19:43:49 -07:00
Peter Johnson
6d3d52f923 Fix GetJpegSize() and JpegNeedsDHT() to handle SOF as first tag. (#127)
Previously these functions ignored SOF if they came immediately after
the SOI (e.g. bytes 2 and 3 of the file).  A handful of cameras generate
images like this.
2018-03-08 19:51:40 -08:00
Tyler Veness
dbd1f1781e Ran wpiformat (#126) 2018-03-07 01:14:21 -08:00
Tyler Veness
96e9a6989c Improved Command-based examples (#906)
Robot.cpp has been split into header-source pairs and the Command-based
examples now define an example subsystem in the Robot class.
2018-03-05 22:06:40 -08:00
Thad House
14228d82f3 Adds Direct port name Serial API (#956) 2018-03-05 19:41:09 -08:00
Peter Johnson
040731447f Add FPS and byte count telemetry measurement for sources. (#125)
* Add FPS and byte count telemetry measurement for sources.

* Add new error code for telemetry not enabled.
2018-03-04 21:01:55 -08:00
Peter Johnson
5175829bab PWM: Use getRaw and setRaw for Sendable "Value" property. (#963)
Also change type to "PWM".  Move old PWM Sendable behavior for both value
and type to PWMSpeedController.
2018-03-03 21:36:25 -08:00
Peter Johnson
9d7293734a SendableChooser: Do not automatically add to LiveWindow. (#964)
SendableChooser::InitSendable() is written such that it saves the table
being used in an instance variable.  This doesn't work if the chooser is
added to both LiveWindow and SmartDashboard.  Normally it is not added to
LiveWindow because the name is empty, but if setName() is called this could
still happen.  Note adding the same SendableChooser to SmartDashboard with
two different names is also not currently supported, for the same reason.

The correct solution will be to remove the instance variable, but this is
too high risk to implement mid-season, so instead just remove from LiveWindow.
2018-03-03 21:34:42 -08:00
Peter Johnson
1e5ec362f7 CameraServer: catch VideoExceptions in video listener. (#949)
We don't want failures here to stop other video properties from updating.

Reported here: https://www.chiefdelphi.com/forums/showthread.php?t=162860
2018-03-03 01:58:28 -08:00
Tyler Veness
7bb3e4efc3 Made documentation for RobotDriveBase::SetDeadband() clearer (#953)
It now mentions that the deadband is applied to the drive inputs.
2018-03-03 01:57:59 -08:00
PJ Reiniger
67de595c85 ADXRS450_Gyro: Add null check around reset (#948)
Reset() is the only function without a null check around it. We call the function on startup, which means if it is unplugged the robot crashes.

Also added an accessor for checking if it is connected, as some teams (us) would like to handle the case where it was not connected on startup.
2018-03-03 01:57:45 -08:00
Thad House
82152e90fe Adds defaults to PWM config (#961) 2018-03-03 01:56:49 -08:00
Dustin Spicuzza
1e7d439899 HAL Notifier: Don't disable the notifier manager when the last handle is cleaned up (#960)
- Addresses #959, but not a good long term solution
2018-03-03 01:56:24 -08:00
Peter Johnson
71d06a1a20 HttpRequest: Don't reorder parameters. (#73)
Also now allows duplicate parameters (which is needed for some use cases).
2018-03-01 20:01:11 -08:00
Peter Johnson
698feff2ff MjpegServer: Support limiting FPS. (#123) 2018-03-01 20:00:25 -08:00
Peter Johnson
3ef9ffaf34 HttpCamera: Force reconnect when SetUrls() is called. (#122)
The URL often contains other information like the camera resolution,
not to mention actually changing cameras!
2018-02-28 23:28:49 -08:00
Peter Johnson
3025a182cc Fix two bugs in client synchronization. (#270)
Both could occur if a client and server write to the same key and the server
disconnects/reconnects (or restarts).

Bug 1: the client did not properly update the sequence number in this case,
so later server updates could be ignored until the sequence number wrapped.

Bug 2: the client did not properly set the id and sequence number for the
update message back to the server, so the server would ignore the message.
2018-02-28 22:58:34 -08:00
Tyler Veness
febc41c85d Fix Travis CI wpiformat install (#72) 2018-02-20 23:03:29 -08:00
Tyler Veness
627ca6db75 Fix Travis CI wpiformat install (#121) 2018-02-20 23:02:55 -08:00
Tyler Veness
c80b0de2c4 Fix Travis CI wpiformat install (#269) 2018-02-20 23:02:36 -08:00
Tyler Veness
979984fa6b Fix Travis CI wpiformat install (#947) 2018-02-20 23:01:57 -08:00
Thad House
57e9fb33d2 Fixes C++ SendableChooser using invalid temp variable (#945) 2018-02-15 23:00:46 -08:00
Thad House
f5a292dadd Adds TriState JNI entry point (#938)
Also adds missing sim TriState DIO HAL call, and a ToDo for later
2018-02-12 16:05:10 -08:00
Peter Johnson
4e9e7ec8f5 ParseHttpHeaders: Make case-insensitive per HTTP spec. 2018-02-09 11:31:03 -08:00
Sam Carlberg
77d6c11743 Invert right side motors in MecanumDrive sendable (#933)
This aligns with the current behavior of DifferentialDrive
Fixes shuffleboard#404
2018-02-09 08:30:12 -08:00
Peter Johnson
c69b8f00d0 ReadJpeg: Don't read past the end of the image. (#119)
This was causing HTTP cameras that didn't send content-length to skip
frames.
2018-02-08 20:16:30 -08:00
Peter Johnson
0542b50f76 Work around fallthrough warnings on GCC 7+. 2018-02-07 22:10:21 -08:00
Thad House
1077ef9fb7 Adds compile task (#118) 2018-02-04 22:41:28 -08:00
Tyler Veness
67f9c9a5b3 Fixed TimedRobot.java hanging if an exception was thrown (#926) 2018-02-04 22:38:19 -08:00
Thad House
f720cbb121 Switches CtreCanNode to use locking and std::chrono for time (#909) 2018-02-01 21:39:06 -08:00
Tyler Veness
64a7e57fe0 Added output normalization to DifferentialDrive::CurvatureDrive() (#924)
This normalizes within -1..1 to avoid clipping and maintain the ratio between
wheel speeds, since that ratio determines the center of rotation.

Fixes #923.
2018-02-01 21:17:04 -08:00
Tyler Veness
5ca00dddbe Added TimedRobot::GetPeriod() (#915)
Fixes #914.
2018-01-27 01:01:15 -08:00
Tyler Veness
120ceb3427 Fix channel reassignments for C++ Joystick twist and throttle axes (#903) 2018-01-26 17:26:10 -08:00
Thad House
5cbafc1382 Updates to image 17 (#913)
These should be binary compatible, so safe to use with image 16.
2018-01-26 17:21:13 -08:00
Thad House
39d1650d51 Fixes double to int to double cast in encoderJNI (#918)
Fixes #916
2018-01-26 17:20:20 -08:00
Tyler Veness
4376c94dc1 Updated copyright year 2018-01-02 16:07:38 -06:00
Tyler Veness
19f7a5f108 Set up wpiformat 2018-01-02 16:07:38 -06:00
Tyler Veness
4514ff8071 Removed extra newlines from beginning of Java classes (#264) 2018-01-02 14:47:27 -06:00
Tyler Veness
b66d72f5c2 Updated copyright year 2018-01-02 14:30:19 -06:00
Tyler Veness
c6f6b352fb Set up wpiformat 2018-01-02 14:30:19 -06:00
Tyler Veness
882399c65e Update copyright year to 2018 (#116) 2018-01-02 11:16:20 -06:00
Thad House
2287281066 Fixes linux and mac builds to -Og, and strips binaries (#261)
Also fixes errors from new optimization level.
2017-12-29 22:17:47 -06:00
Thad House
cd4b7b6cc7 Switches to -Og instead of -O2, and strip binaries on linux and mac (#63) 2017-12-29 22:16:35 -06:00
Thad House
da5458a2d2 Updates to newest build setup, fixing -Og and strip binaries (#115) 2017-12-29 22:15:38 -06:00
Omar Zrien
4e0ed79864 Fix no return warning in jni_util.h (#62) 2017-12-02 00:28:56 -08:00
Thad House
6767afd400 Adds a UDPClient (#60)
Send only currently. Will eventually implement receive, but not
necessary for now.
2017-11-28 00:53:10 -08:00
Peter Johnson
aa2de65bad Use Twine instead of StringRef where appropriate. (#259)
Deprecated interfaces were not updated.
2017-11-24 20:13:00 -08:00
Peter Johnson
877c7f51c1 raw_istream: Don't forward declare Twine et al. (#59)
It breaks existing users who use StringRef.
2017-11-22 23:49:57 -08:00
Peter Johnson
912b74151f Use llvm::Twine instead of llvm::StringRef in several places. (#58) 2017-11-22 21:47:56 -08:00
Peter Johnson
f73db4a49b Twine::isSingleStringRef(): Support CharKind. (#57) 2017-11-22 21:38:25 -08:00
Tyler Veness
cf828ca858 Upgraded clang-format to 5.0 (#103) 2017-11-19 15:15:41 -08:00
Peter Johnson
7847c69231 Update for wpi::Now() change to microseconds. (#113)
Also be explicit in docs about what timebase and step are used.
2017-11-19 14:35:50 -08:00
Peter Johnson
0e4a1c5dae NetworkTable: Add key utility functions. (#256)
- BasenameKey
- NormalizeKey
- GetHierarchy
2017-11-19 11:52:10 -08:00
Peter Johnson
551504e773 Update documentation for Now() for 1 us steps. (#258)
This is to match wpilibsuite/wpiutil#56.
2017-11-19 11:47:37 -08:00
Peter Johnson
85e83f1bba WPI_Now(): return microseconds, and make backend replaceable. (#56)
- Add function documentation.
- Use uint64_t instead of unsigned long long
2017-11-19 11:47:06 -08:00
Peter Johnson
7eac3fcbda Java NetworkTableEntry.setValue() and kin: Handle common Java types. (#257)
This restores the behavior of the old NetworkTable.putValue() function.
2017-11-19 11:44:54 -08:00
Peter Johnson
e9b0b9d8f6 MjpegServer: Use sink name in title. (#112)
Fixes #83.
2017-11-17 09:34:30 -08:00
Peter Johnson
cad1b9413c Add exposure quirk for LifeCam Cinema. (#111)
This is the same quirk as the LifeCam HD-3000.

Fixes #110.
2017-11-17 09:30:56 -08:00
Peter Johnson
3324bcc5ce Use magic statics instead of ATOMIC_STATIC. (#109) 2017-11-17 09:29:20 -08:00
Peter Johnson
20c8d29ae9 Fix wpi::mutex usage in SetVideoMode(). 2017-11-17 02:04:24 -08:00
Thad House
110726c5bf Adds support to test library for JNI testing (#54) 2017-11-17 01:53:25 -08:00
Peter Johnson
7db60f8e7c CvSource: Implement SetVideoMode(). (#104) 2017-11-14 22:09:30 -08:00
Tyler Veness
b3f1e74317 Ran formatter based on styleguide#95 (#108) 2017-11-14 22:07:56 -08:00
Peter Johnson
e301adb22b Use wpi::mutex instead of std::mutex. (#105)
This uses a priority-aware mutex on Linux platforms.
2017-11-13 09:51:26 -08:00
Peter Johnson
3438a17341 Use wpi::mutex instead of std::mutex. (#254)
This uses a priority-aware mutex on Linux platforms.
2017-11-13 09:51:05 -08:00
Peter Johnson
e4deda5ccb Fix SafeThread bad merge. (#53) 2017-11-12 23:00:50 -08:00
Peter Johnson
80618a2e64 Use wpi mutex and condition_variable. (#52) 2017-11-12 22:12:03 -08:00
Peter Johnson
e45b6e0f65 Fix typo in priority_condition_variable. (#51) 2017-11-12 22:11:08 -08:00
Peter Johnson
86d4899a54 Make NetworkTable constructor private/package-private. (#253)
Users should be using either NetworkTableInstance.getTable() or
NetworkTable.getSubTable().
2017-11-12 21:57:28 -08:00
Peter Johnson
9d8a508cd5 Add priority_mutex and priority_condition_variable. (#50)
Also provide wpi::mutex and wpi::condition_variable as wrappers for these
on Linux (where they're available), and for std::mutex and
std::condition_variable on other platforms.
2017-11-12 20:56:29 -08:00
Peter Johnson
c9ead29f44 SafeThread: Simplify m_lock assignment. (#49)
Instead of construct-and-swap, just use the move operator=.
2017-11-12 20:10:55 -08:00
Peter Johnson
f77fd1eca9 Set SO_EXCLUSIVEADDRUSE for server sockets on Windows. (#44)
On Windows, the shutdown() call relies on exclusively owning the server
socket.
2017-11-11 16:27:33 -08:00
Peter Johnson
5a5e753921 LLVM path: Don't follow symlinks. (#48)
This causes issues in recursive_directory_iterator.
2017-11-11 16:27:07 -08:00
Thad House
3e4e5261fe Remove no warnings on winsock and scl issues (#47)
Not needed anymore. The winsock one we removed and the scl one is
dangerous anyway.
2017-11-09 18:56:27 -08:00
Thad House
cf4afb6feb Adds get header task (#46) 2017-11-09 18:55:27 -08:00
Thad House
55fa1e5e76 Adds header task (#101) 2017-11-09 18:43:21 -08:00
Thad House
c101655419 Adds warning prints by updating native plugin (#100) 2017-11-09 11:24:22 -08:00
Thad House
51165ba0aa Updates native plugin to add warning prints (#251) 2017-11-09 11:23:52 -08:00
Thad House
f03b31f433 Adds warning printouts to gradle by updating native plugin (#45) 2017-11-09 09:25:22 -08:00
Peter Johnson
8e797a1a1d Import filesystem directory iterators from llvm. (#43)
Note: these are similar to the C++17 ones, but don't have quite the same API.
2017-11-03 11:40:42 -07:00
Dustin Spicuzza
fd32350dc6 Assign received sequence number on receiving an unknown entry (#250) 2017-10-28 01:07:17 -07:00
Tyler Veness
b9c8ebeffa Ran formatter (#99) 2017-10-27 23:46:50 -07:00
Tyler Veness
ec12b0ffe2 Add wpiformat to Travis CI (#98) 2017-10-18 00:49:19 -07:00
Tyler Veness
7fd5947486 Fix include guards (#97)
Enforced by styleguide#79.
2017-10-18 00:48:44 -07:00
Tyler Veness
b68e1c5570 Added brace comments (#96)
Enforced by wpilibsuite/styleguide#80.
2017-10-15 10:01:17 -07:00
Thad House
ded1beb949 Removes specific raspbian, armv7 and armv8 cross builds (#249)
Matches wpilibsuite/wpiutil#41
2017-10-14 21:58:32 -07:00
Thad House
a6c7789b5e Removes specific raspbian, armv7 and armv8 cross builds (#41)
Will make the cross platform build case easier. A bit more difficult to
consume, but will be easier in the long run.
2017-10-14 21:57:53 -07:00
Peter Johnson
73f8412b42 Correctly handle negative waitForXQueue timeouts in Java. 2017-10-05 23:29:00 -07:00
Peter Johnson
529d7f5fe3 Initialize logger min level from logger_impl. 2017-10-05 23:29:00 -07:00
Peter Johnson
a6c1e18aef NetworkTable.containsKey(): Always return false on empty key. 2017-10-05 23:29:00 -07:00
Peter Johnson
8a37b81f4e LoadEntries: Don't emit NOTIFY_FLAGS. (#247)
Fixes #246.
2017-10-04 11:28:35 -07:00
Peter Johnson
f81b6fbcd6 Fix handling of deleted values in several places. (#241)
Now that the m_entries entry is kept, other places can't assume that
a value exists simply because the entry exists.
2017-10-02 13:06:39 -07:00
Peter Johnson
223e61df2a Depend on wpiutil 3.+ rather than just +. (#95)
Also update to wpilib-version-plugin 2.0.
2017-10-01 10:56:21 -07:00
Peter Johnson
303df626a2 Depend on wpiutil 3.+ rather than just +. (#235)
Also update to wpilib-version-plugin 2.0.
2017-10-01 10:55:43 -07:00
Peter Johnson
9e8ad778dd Update wpilib-version-plugin to 2.0. (#39) 2017-10-01 10:55:17 -07:00
Peter Johnson
1f18cc5416 Add SaveEntries() and LoadEntries(). (#233)
These allow saving and loading non-persistent entries in the persistent
file format.
2017-10-01 09:13:43 -07:00
Peter Johnson
e68a71022c Move immediate connection notification logic into Dispatcher.
This prevents a race condition that could result in out of order
notifications.
2017-10-01 09:01:00 -07:00
Peter Johnson
e4a8bff70e Move immediate entry notification logic into Storage.
This prevents a race condition that could result in out of order
notifications.
2017-10-01 09:01:00 -07:00
Peter Johnson
10982e0275 Don't actually remove deleted entries from m_entries. (#239)
Doing so invalidates entry instance handles.

Fixes #238.
2017-09-30 22:55:30 -07:00
Peter Johnson
8edc02b06d Update README for new build system. (#232) 2017-09-22 22:32:01 -07:00
Tyler Veness
4b2aaee9ea Made package local methods in NetworkTableInstance public (#234) 2017-09-22 22:31:19 -07:00
Thad House
9fdb33b6af Switches native linux arm build to be nativearm arch (#38)
Fixes gradle bug
2017-09-22 09:30:58 -07:00
Peter Johnson
3faecdb353 Add SHA1 algorithm implementation. (#32)
Largely based on https://github.com/vog/sha1 with some customizations and
optimizations.
2017-09-10 17:21:19 -07:00
Peter Johnson
db96f41ad7 Log.cpp: Use raw_ostream and llvm path functions. (#93) 2017-09-07 00:16:26 -07:00
Tyler Veness
10fbf17d42 .styleguide now uses generalized config file format (#94)
Requires styleguide#66.
2017-09-06 22:59:23 -07:00
Peter Johnson
ef85809690 Fix bug in raw_fd_istream::read_impl(). (#30)
It would not set error if read() returned 0 (indicating EOF).
2017-09-06 22:06:21 -07:00
Peter Johnson
95bce5d656 Add more storage incoming unit tests. 2017-09-06 20:59:09 -07:00
Peter Johnson
cedbafeb28 Add INetworkConnection interface for unit testing. 2017-09-06 20:59:09 -07:00
Peter Johnson
7c1d2f4bc4 Improve client connection synchronization behavior.
The original synchronization behavior was troublesome for two reasons:
- It had unpredictable behavior for updated values
- It brought back to life deleted values

Instead of relying on the server to inform the client regarding reconnections,
the client keeps track of what values have been modified by user code on the
client.  When the client connects to the server, the following occurs.

For entries that have been modified by user code on the client:
- If the entry is not persistent, the server value is overwritten with the
  client value
- If the entry does not exist on the server, the client sends an assignment
  to the server to recreate it on the server

For entries that have not been modified by user code on the client:
- The client value is overwritten with the server value
- If the entry does not exist on the server, the client deletes the entry

Fixes #8.
2017-09-06 20:48:48 -07:00
Peter Johnson
8099d6dbd7 Refactor Storage ProcessIncoming(). 2017-09-06 20:41:53 -07:00
Peter Johnson
8e01b68cf6 Switch Storage save/load to use raw_ostream/raw_istream. 2017-09-06 20:41:53 -07:00
Peter Johnson
d707a07f84 Refactor Storage load and save functionality.
Fixes #191.
2017-09-06 20:41:53 -07:00
Peter Johnson
5ab20bb27c Implement independent instances.
Previously, most of the classes were implemented as singletons so only one
instance was possible.

This change adds an instance handle-based API.  In Java, this API is located
in a different package than the old API (edu.wpi.first.networktables).

Backwards compatibility with ITable and the old NetworkTable API is largely
maintained, but a handful of classes have moved to the new package in Java
(ConnectionInfo and PersistentException), and the old JNI has been completed
replaced.

Also:
- Move SetTeam implementation to Dispatcher.
- Consistently pass time through Java and C++ Value API.
- Rename nt_Value.h to NetworkTableValue.h for consistency with Java.
- Improve documentation
- Make C++ and Java APIs more consistent
- Document RPC functions and support RPC in Java.
- Add polling features for entry and connection listeners and use them to
  move callback threads to Java level.
- Remove thread start and stop hooks (as polling is available).
- Make Notifiers, RpcServer, Dispatcher, and Storage mockable.
- Set NOTIFY_NEW on immediate entry notifications.
- Make GetTable("/") and GetTable("") equivalent.
- Generate local notification for flags update when loading persistent file.

And many unit test updates/changes:
- Use InitGoogleMock instead of InitGoogleTest in test main.
- Move test printers to TestPrinter.h/cpp.
- Provide printers for StringRef, EntryNotifier, and Handle.
- StorageTest: Check notifications.
- Add entry notifier unit tests.
- Storage: Add test for incoming entry assignment.
- Update connection listener tests.
- Add entry listener unit tests.

Fixes #11, #140, #189, #190, #192, #193, #221
2017-09-06 20:28:35 -07:00
Peter Johnson
8125a179fb Only include .cpp files in testsuite build. 2017-09-06 20:28:35 -07:00
Peter Johnson
041563f8ea Change UidVector to be LRU with a reuse threshold. (#29)
This keeps indexes from being instantly reused and reduces the risk of
accidentally using an old index.

Also change erase and emplace_back to return 0-based instead of 1-based
indexes.

This is a breaking change, but a noisy one due to the template parameter
change.
2017-09-06 19:54:58 -07:00
Thad House
c3f7c85f8a Adds wpi GetHostname function (#25) 2017-08-27 21:35:34 -07:00
Peter Johnson
12b2efa489 Log.cpp: Use raw_ostream and llvm path functions. (#223) 2017-08-27 12:01:31 -07:00
Thad House
5d403a7b49 Makes an empty stringref have a valid Data pointer (#28)
Now acts similar to std::string, where an empty construction string is valid.
2017-08-26 10:04:11 -07:00
Peter Johnson
3c88f94b43 HttpUtil has moved to wpiutil; use it. (#92) 2017-08-25 18:10:47 -07:00
Tyler Veness
06636a0e1c Set up wpiformat (#86) 2017-08-25 17:48:06 -07:00
Thad House
8416b4e42c Add default parameter to StringRef to allow null termination on lengthed strings. (#27) 2017-08-23 21:02:11 -05:00
Thad House
1a0ed61f78 Force the java dev library to be built during build (#24) 2017-08-23 01:27:56 -05:00
Peter Johnson
68501759fa tcpsockets: Don't pull in platform-specific headers in headers. (#26)
This pollutes the namespace for all users of these headers.
This is particularly an issue on Windows.
2017-08-23 01:27:19 -05:00
Peter Johnson
dd85b1e519 Update googletest and googlemock to 1.8.0. (#90) 2017-08-18 20:47:04 -07:00
Thad House
2d3cf1bdb1 Updates plugin to 1.2.12 (#91)
Fixes .debug issue
2017-08-18 20:22:21 -07:00
Thad House
baa8021c79 Force dev java to be built during build task (#227) 2017-08-18 19:51:14 -07:00
Thad House
133540f577 Switches to the new build system (#87)
* Removes old build system

* Removes old gmock

* Adds new gmock

* Moves source files to new locations

* Adds new build system
2017-08-18 17:52:08 -07:00
Peter Johnson
43c103c0ac Update googletest and googlemock to 1.8.0. (#23) 2017-08-15 23:53:20 -07:00
Peter Johnson
162ac787b7 Update googletest and googlemock to 1.8.0. (#226) 2017-08-15 23:47:25 -07:00
Peter Johnson
fa7d5bc023 Add UidVector (used in both ntcore and cscore Notifier). (#22) 2017-08-14 22:58:11 -07:00
Peter Johnson
9d45088127 Fix destruction order issue in SourceImpl. (#89)
The Frame destructor calls back into SourceImpl, locking m_poolMutex, so
it's necessary to destroy m_frame before m_poolMutex.  Reverse destruction
order to member definition order is guaranteed by the C++ standard.
2017-08-14 22:27:28 -07:00
Thad House
7ef56de3f2 Fix mac builds. (#88)
Warnings for unused functions, and the same skips as Windows.
2017-08-14 22:27:07 -07:00
Tyler Veness
0d76b3f308 Added gradlew.bat to .gitattributes (#225)
The gradle-wrapper.properties file also got committed with CRLF line endings,
which this commit rectifies.
2017-08-14 00:02:38 -07:00
Thad House
92c4c49b01 Removes the custom platform include flag (#224)
Was replaced by #222
2017-08-13 15:41:59 -07:00
Peter Johnson
855df5d679 raw_mem_istream: Add StringRef constructor. 2017-08-13 12:18:19 -07:00
Peter Johnson
c8d9cc7e5b Add filename constructor to raw_fd_istream. 2017-08-13 12:18:19 -07:00
Peter Johnson
1c1fbf14cf Import LLVM openFileForRead and openFileForWrite. 2017-08-13 12:18:19 -07:00
Peter Johnson
9e4dc235d7 Connect to server in parallel rather than doing round-robin. (#205)
This substantially speeds up client connection times.
2017-08-13 12:05:29 -07:00
Peter Johnson
4bd8cf6f5c Native tests depend on native sources, so include in exportedHeaders. (#222) 2017-08-13 10:27:06 -07:00
Thad House
d9c754c30f Add a java version of the dev app. (#218) 2017-08-13 08:02:29 -07:00
Thad House
ea028a3822 Add a cpp dev run task. (#219) 2017-08-13 08:01:39 -07:00
Peter Johnson
7d9e6b7e22 Move ReadLine into raw_istream class as getline. (#20) 2017-08-13 00:56:35 -07:00
Peter Johnson
17b5cace5b Base64: Add raw_ostream and SmallString interfaces. (#19) 2017-08-13 00:55:56 -07:00
Thad House
2fa41b23b9 Add a java version of the dev app. (#16) 2017-08-12 23:52:08 -07:00
Thad House
9f5f6111d4 Add a cpp dev run task. (#17) 2017-08-12 23:51:25 -07:00
Thad House
0782164120 Gradle 4.1 (#220) 2017-08-11 01:10:18 -07:00
Thad House
5439fe7b16 Gradle 4.1 (#18) 2017-08-09 20:20:10 -07:00
Thad House
55111ac35f Fix CORS issue with all requests (#85)
Closes #84.
2017-08-07 17:46:33 -07:00
Thad House
f0cc5d9ca8 Adds an all artifact to the published libraries (#15)
Better then the old desktop zips because it will include all artifacts
built, not just specifically the desktop ones. Also, the individual
artifacts are published as well so users can decide which artifacts they
specifically want, and can help decrease download sizes. The cpp plugin
will continue using the individual artifacts.
2017-08-07 17:44:07 -07:00
Thad House
ccfeab5ac9 Adds an all artifact to the published libraries (#217)
Better then the old desktop zips because it will include all artifacts
built, not just specifically the desktop ones. Also, the individual
artifacts are published as well so users can decide which artifacts they
specifically want, and can help decrease download sizes. The cpp plugin
will continue using the individual artifacts.
2017-08-07 17:42:58 -07:00
Peter Johnson
7e011bda6f Add HTTP utilities. (#7)
Imported from cscore.
2017-08-06 23:28:21 -07:00
Peter Johnson
8418c39120 Add Path and Twine components from LLVM. (#10) 2017-08-06 23:26:42 -07:00
Peter Johnson
4b8ef57a99 Remove networktables2.type Java custom container types. (#214) 2017-08-04 20:24:36 -05:00
Peter Johnson
d910b0b2a2 Remove deprecated throwing get functions. (#213) 2017-08-04 14:02:28 -05:00
Thad House
80c8de7d69 Add dependency to jni task to fix 32 bit builds (#216)
Fixes #212
Also forces appveyor to test both 32 and 64 bit correctly.
assemble was removed because it would inadvertently cause a 3rd build.
2017-08-04 13:46:58 -05:00
Peter Johnson
7f776deae2 Fix ntcoreExe build model. (#215) 2017-08-04 13:35:23 -05:00
Peter Johnson
8209ba8a00 Move NetworkTable into nt namespace, with a shim. (#211)
Defining NAMESPACED_NT will disable the shim.
2017-08-04 10:32:33 -05:00
Peter Johnson
25c8e873d0 TCPConnector: Add method to connect to server in parallel. (#6)
This substantially speeds up connection times compared to sequentially
trying to connect to each server in round-robin fashion.
2017-08-03 16:45:42 -05:00
Thad House
e24db75f08 Build updates to newest version of plugins and gradle, along with config file (#13) 2017-08-03 16:24:02 -05:00
Thad House
5df7463663 Remove wpiutil and update to the new build system (#210) 2017-08-03 16:14:40 -05:00
Thad House
eb7331f2ab Actually makes the right classifier 2017-08-02 19:47:32 -07:00
Thad House
03bd0820cc Adds a java classifier whenever jenkins is building (#12)
Makes the jar much easier to find when attempting to combine.
2017-08-02 19:33:26 -07:00
Thad House
63768166ea Updates to plugin 1.2 (#9)
1.1 was a bad publish
2017-08-02 13:17:34 -07:00
Thad House
bd899a7a7c Fixes mac RuntimeDetector (#11) 2017-08-02 13:17:26 -07:00
Peter Johnson
301442ee43 Add json support to wpiutil.
This is a modified version of https://github.com/nlohmann/json.

It's been moved into the wpi namespace as many of the changes are not
compatible.  The amount of template code has been significantly reduced,
enabling many functions to be moved out-of-line, and for the result to
build on older compiler versions (in particular GCC 4.8).
2017-07-28 21:55:03 -07:00
Peter Johnson
de9dd1180b Include src/main/native/cpp when building test. 2017-07-28 21:55:03 -07:00
Peter Johnson
436ed4d1e3 Implement comparison operators for llvm::StringMap. 2017-07-28 21:55:03 -07:00
Peter Johnson
88aa273e55 license.txt: Add LLVM license. 2017-07-28 18:09:14 -07:00
Peter Johnson
d11d8409a8 license.txt: Remove leading asterisks 2017-07-28 18:09:14 -07:00
Peter Johnson
9385d1b6d8 GetJavaStackTrace: Provide llvm::StringRef excludeFuncPrefix. (#3)
This is a bit cleaner to use than the templated version (many compilers
have issues with templating on static strings, for example).
2017-07-28 18:08:54 -07:00
Peter Johnson
b90653f3e3 Logger: Add def_func and min_level constructors. (#2) 2017-07-28 18:08:31 -07:00
Thad House
1243cf04ea Adds new build system to repo (#1) 2017-07-28 07:29:49 -07:00
Thad House
4f5b5b1377 Adds gmock files 2017-07-27 00:04:00 -07:00
Sam Carlberg
f43675e2bd Add functionality for getting the current network mode (#202)
Use bit flags to indicate a combination of network mode and status.
2017-06-02 17:25:20 -07:00
Sam Carlberg
417cf33f90 Expose ITable paths (#200)
Closes #196
2017-05-26 21:02:45 -07:00
Thad House
067b1f3ee0 Adds a way to get the native handle from SafeThread (#198)
Useful to wpilib to enable easier changing of RT priorities.
2017-05-09 22:04:57 -07:00
Thad House
3d2f41d081 Adds a way to get the native handle from SafeThread (#198)
Useful to wpilib to enable easier changing of RT priorities.
2017-05-09 22:04:57 -07:00
Dustin Spicuzza
49de28d3d0 Add overloads for property types except enum (#73)
- Fixes #70
2017-05-01 20:44:09 -07:00
Dustin Spicuzza
c34cf11769 MjpegServer: style fixes for root page (#72)
- Moves stream to the right of any settings
- When the page is too small, then the stream will move to the top of the settings
2017-04-30 08:49:21 -07:00
Austin Shalit
42facbb07e Make Java "struct" constructors public for testing/simulating (#195) 2017-04-30 08:48:02 -07:00
Joseph Jackson
9f97cd61bf Correct platform path for 32-bit Linux (#179)
Gradle needs to produce a platform path of "Linux/i386" when targeting a Linux 32-bit Intel platform. Otherwise, it doesn't match Java's os.name/os.arch when loading the ntcore library in NetworkTablesJNI.java. Windows uses "x86" but Linux uses "i386". (http://lopica.sourceforge.net/os.html)
2017-04-30 08:47:02 -07:00
Peter Johnson
59133a7d93 Use Javadoc formatting for Java comments. (#66) 2017-03-11 21:56:14 -08:00
Thad House
b484cbba7c Adds SinkFrameTimeoutCpp to def file (#61) 2017-02-17 20:41:32 -08:00
Peter Johnson
61e34621cc Add GetNextFrame timeout to CvSink and MjpegServer.
MjpegServer uses the timeout to generate keep-alives to any clients
(which helps detect disconnects and avoid stale client threads).

CvSink GrabFrame now defaults to a timeout, but the timeout can be
changed by the user, or the old no-timeout version is now available
as GrabFrameNoTimeout.
2017-02-17 02:06:46 -08:00
Peter Johnson
5e9575de66 Add missing CS_SetDefaultLogger in cscore-jni.def. 2017-02-17 02:06:46 -08:00
Dustin Spicuzza
c02d34dbf3 Allow resetting the logger back to default (#55) 2017-02-16 22:12:16 -08:00
Peter Johnson
8f97637b71 Fix handling of HTTP cameras that do not provide a Content-Length. (#59)
ReadJpeg was not correctly parsing the SOS segment.
2017-02-16 22:11:54 -08:00
Peter Johnson
878d3a6f4f Publish video modes to webserver. (#58)
This puts a table of modes onto the main webpage and also adds them to
the JSON output.

Fixes #50.
2017-02-16 01:06:38 -08:00
Peter Johnson
ef25bbde75 Fix SetExposureAuto. (#57)
This is an enum value; setting 3 seems to be correct for USB cameras.

Fixes #56.
2017-02-15 16:25:43 -08:00
Dustin Spicuzza
8c3efa5926 Increment reference count when creating VideoSource object (#53) 2017-02-09 00:55:40 -08:00
Thad House
e6656326a8 Adds field IP to round robin list (#187)
With how many more coprocessors are being added, this is probably needed
to make the field crew sane.
2017-02-09 00:55:01 -08:00
Thad House
cf8cab850b Fixes missing VideoProperty constructor. (#49) 2017-01-20 00:49:58 -07:00
Thad House
db5dfa1746 Adds sliders for all settable properties to the default webpage (#48)
When the page is loaded, if properties can be found they will
automatically be created on screen. They are currently not auto
updating. Raw values are currently disabled because of this.
2017-01-19 01:02:37 -07:00
Peter Johnson
13457d1bf4 Update setUpdateRate() documentation to match implementation.
Update rates as fast as 10 ms are now allowed.

Fixes #184.
2017-01-18 21:32:15 -08:00
Peter Johnson
8f8c4d3d95 HttpUtil: Allow "http" scheme to be mixed case. 2017-01-10 00:15:39 -08:00
Thad House
d47bd1ecbc Fixes embedded library name used for extraction in Java (#45) 2017-01-09 20:49:02 -08:00
Thad House
e9fcb5381a Fixes Java artifact clasifiers when using custom suffix (#44) 2017-01-05 14:14:42 -08:00
Thad House
3e2631f49b Fixes Java artifact clasifiers when using custom suffix (#183) 2017-01-05 14:13:57 -08:00
Peter Johnson
3c3236c5d5 Fix video mode notifications. 2017-01-05 01:42:19 -08:00
Thad House
23462ec7df Adds way to force publishing version from command line (#43)
In case we need to do a recreation of an artifact for some reason, this
makes it possible.
2017-01-04 22:16:17 -08:00
Thad House
ac56b0a33e Adds way to force publishing version from command line (#182)
In case we need to do a recreation of an artifact for some reason, this
makes it possible.
2017-01-04 22:15:23 -08:00
Thad House
b55c604c0a Updates Gradle to 3.3, and removes the Visual Studio 2015 workaround (#41) 2017-01-04 19:40:44 -08:00
Thad House
a72f8f3bcd Add new ARM Toolchain, add toolchainpath to README (#42)
Matches ntcore #165
2017-01-04 19:40:28 -08:00
Thad House
27c0405fc9 Reruns gradle wrapper to fully generate 3.3 files (#181) 2017-01-04 19:08:33 -08:00
Thad House
b9e80ecfdc Updates to gradle 3.3, and removes Visual Studio 2015 workaround (#180) 2017-01-04 17:37:02 -08:00
Thad House
a3adb38bef Adds support for specifying output suffix of arm packages. (#34)
Currently if using a separate compiler prefix, it would get published to
the arm classifier. This modifies so the output suffix can now be
specified (e.g. "hf" for armhf).
2017-01-04 01:38:37 -08:00
Peter Johnson
593ba37c43 Java VideoEvent: Make propertyHandle public. 2017-01-04 01:16:10 -08:00
Peter Johnson
4ed78a84ef Java VideoMode: Provide PixelFormat-taking constructor. 2017-01-04 01:16:10 -08:00
Thad House
e893662c0a Adds new functions to def file (#40) 2017-01-03 19:52:26 -08:00
Thad House
5df78c520c Adds support for building separate armhf artifacts (#177)
Currently if using a separate compiler prefix, it would still get published
to the arm classifier. This modifies so a classifier suffix can be used to
disambiguate arm from armhf.
2017-01-03 19:12:47 -08:00
Thad House
f13f886886 Fixes arm example builds on windows (#39) 2017-01-03 19:10:21 -08:00
Thad House
5dd8e4dc7f Adds defs for the C windows functions, and shims the 5 missing ones (#38) 2017-01-03 19:09:11 -08:00
Peter Johnson
883fd5b062 For property events, provide property name rather than source name.
This is much more useful.
2017-01-02 23:17:00 -08:00
Peter Johnson
7ddbf20108 Create VideoCamera base class and move camera settings functions to it.
This makes them available for both UsbCamera and HttpCamera / AxisCamera.

To avoid virtual functions in the public-facing interface, move the
implementation of the camera settings functions to the core library.
2017-01-02 23:17:00 -08:00
Peter Johnson
23135d7a5a Allow Sink.SetSource() to be given an empty source.
In Java, allow source to be null (pointers are not used in C++, so
this isn't necessary).
2017-01-02 23:17:00 -08:00
Thad House
b91ab0b44f Gets builds working on Windows (VS 2015) (#37)
Def files will be updated after the latest PR with new definitions gets
added.
2017-01-02 23:16:35 -08:00
Thad House
9a2ec13ba4 Fixes SetIntArrayRegion template for windows builds (#178) 2017-01-02 22:29:56 -08:00
Thad House
78995f5cca Fixes SetIntArrayRegion template for windows builds (#178) 2017-01-02 22:29:56 -08:00
Thad House
f225c4773a Fixes gradle publish with no flags. (#35) 2017-01-02 17:23:11 -08:00
Fred Silberberg
bac4b3d5cb Fixed gradle publish with no flags. (#176) 2017-01-01 00:13:00 -08:00
Peter Johnson
e3f99a4a22 JStringRef: ensure string is null terminated so c_str() works correctly. 2016-12-26 14:13:15 -08:00
Peter Johnson
df7d3261c9 JStringRef: ensure string is null terminated so c_str() works correctly. 2016-12-26 14:13:15 -08:00
Peter Johnson
95ad4783f1 Revert "Fixes TCPAcceptor able to use an empty string (#172)"
This doesn't actually do anything since the outer if statement checks
for empty m_address already.

This reverts commit 6ad9f45d9a.
2016-12-26 13:55:21 -08:00
Peter Johnson
b5b0899226 Revert "Fixes TCPAcceptor able to use an empty string (#172)"
This doesn't actually do anything since the outer if statement checks
for empty m_address already.

This reverts commit 6ad9f45d9a.
2016-12-26 13:55:21 -08:00
Thad House
9a0a1baa6b Fixes TCPAcceptor able to use an empty string (#172) 2016-12-26 12:27:08 -08:00
Thad House
6ad9f45d9a Fixes TCPAcceptor able to use an empty string (#172) 2016-12-26 12:27:08 -08:00
Fred Silberberg
7ec223d445 Update WPILib Version Plugin (#33) 2016-12-25 22:13:00 -08:00
Fred Silberberg
ed9e837229 Updates the wpilib version plugin (#171) 2016-12-25 22:11:54 -08:00
Fred Silberberg
b9a08e8260 Fixed entry comment (#169) 2016-12-25 22:11:14 -08:00
Peter Johnson
58931e1d30 Be even more permissive on valid JPEG formats. 2016-12-25 01:45:35 -08:00
Peter Johnson
976ca80056 Use InetNtop on Win32 rather than WSAAddressToString. (#170)
Similarly, use InetPton rather than WSAStringToAddress.

The WSAAddressToString function is intended to provide a user-readable
string and thus includes the port number.  This breaks some use cases
on Windows which expect to get just the IP address.

Note: The InetPton and InetNtop functions are available only in Vista or above.
2016-12-25 01:30:12 -08:00
Peter Johnson
95e5295666 Use InetNtop on Win32 rather than WSAAddressToString. (#170)
Similarly, use InetPton rather than WSAStringToAddress.

The WSAAddressToString function is intended to provide a user-readable
string and thus includes the port number.  This breaks some use cases
on Windows which expect to get just the IP address.

Note: The InetPton and InetNtop functions are available only in Vista or above.
2016-12-25 01:30:12 -08:00
Peter Johnson
4b16999fbc Fix tests that are only built on cmake. (#168)
Fixes #167.
2016-12-24 01:58:12 -06:00
Peter Johnson
318d23ba1c Add AxisCamera wrapper class.
This takes hosts (IP or DNS name) rather than URLs, making it easier
to use.

Also add more overloads to resolve ambiguities encountered when using
std::string and const char*, and also add overloads for
std::initializer_list<T> so braced initializer lists can be used.
2016-12-23 22:26:27 -08:00
Peter Johnson
9c4c7c08bf Java HttpCamera: Make accessor functions public. 2016-12-23 22:26:27 -08:00
Peter Johnson
9016a9e8b8 Start implementing HttpCamera.
This is a work in progress that does not yet support camera settings.
2016-12-23 22:26:27 -08:00
Peter Johnson
4c8c41fdc0 CvSink: Support grayscale images.
Also support 4-channel BGRx images and provide better error reporting
on bad images passed to PutFrame.
2016-12-23 22:25:11 -08:00
Peter Johnson
205d3b1d04 Some cameras don't provide the JFIF header, so don't require it.
This fixes DHT not being inserted on some images.
2016-12-23 22:21:11 -08:00
Peter Johnson
1575fff07a MjpegServer: Limit the number of simultaneous clients to 10.
This prevents client issues from swamping the network.
2016-12-23 22:01:35 -08:00
Peter Johnson
8c7338f2ba TCPAcceptor: Include port number in error messages. (#166) 2016-12-23 20:36:45 -06:00
Peter Johnson
459cc65b3f TCPAcceptor: Include port number in error messages. (#166) 2016-12-23 20:36:45 -06:00
Peter Johnson
3d28275675 UsbCamera: Simplify the message passing implementation. 2016-12-23 10:58:11 -08:00
Peter Johnson
6f41b3cde7 UsbCamera: Implement LifeCam HD-3000 exposure quirk.
On Linux, the V4L exposure setting is logarithmic and only accepts
certain exact values.
2016-12-22 23:44:40 -08:00
Peter Johnson
9ffc09a11b Fix settings example if there's no "--" in arg list. 2016-12-22 22:50:07 -08:00
Peter Johnson
ced2608afd Move ExtCtrlIoctl to UsbCameraProperty::DeviceQuery. 2016-12-22 22:44:46 -08:00
Peter Johnson
adbca532c0 Break up UsbCameraImpl::DeviceProcessCommands(). 2016-12-22 22:36:07 -08:00
Peter Johnson
5e38d8f28a Refactor UsbCameraProperty. 2016-12-22 22:11:54 -08:00
Peter Johnson
d6ef2c04a5 Start refactoring source property implementations. 2016-12-22 21:19:50 -08:00
Peter Johnson
ce69783871 UsbCamera: Scale some properties to make them constently percentages.
The "raw" version of these properties are still available, just prefixed
with "raw_".
2016-12-22 20:51:04 -08:00
Peter Johnson
10b13da3da Refactor USB vendor/product to product string to UsbUtil.h.
Also implement reading of /var/lib/usbutils/usb.ids for systems that
have it (e.g. desktop Linux).
2016-12-21 10:56:40 -08:00
Peter Johnson
88afefe464 Avoid crash in SourceImpl constructor.
The Frame constructor calls back into SourceImpl (the passed this reference),
and when in-place constructed in the SourceImpl constructor, SourceImpl
is only partially constructed.
2016-12-21 10:56:40 -08:00
Peter Johnson
80abf6bf24 Support per-stream resolution settings.
The code now automatically resizes as required.

This change also disconnects camera resolution settings from MJPEG
stream connections; setting the camera resolution can now only be done
via code.
2016-12-20 20:48:31 -08:00
Jaci R
94359709a1 Add new ARM Toolchain, add toolchainpath to README (#165) 2016-12-19 23:16:39 -06:00
Peter Johnson
8501b7c9e2 CvSourceImpl::CreateProperty(): Use lock_guard instead of unique_lock. 2016-12-18 09:13:52 -08:00
Peter Johnson
0ce0855a6f Java: check for null and use new jni_util features. 2016-12-18 09:13:51 -08:00
Peter Johnson
e1dabbc2d5 cscore_cpp.cpp: Fix include order. 2016-12-18 09:13:01 -08:00
Peter Johnson
c08a489e27 Improve error message for VIDIOC_STREAMON "no space left on device". 2016-12-18 09:13:01 -08:00
Peter Johnson
28a2ba4bf8 Add external logger interface. 2016-12-18 09:13:01 -08:00
Peter Johnson
2b8b8e7403 Improve logging consistency by using source/sink name throughout. 2016-12-18 09:12:59 -08:00
Peter Johnson
bdaf60b2d6 Replace tabs with spaces in gradle files. 2016-12-18 09:05:03 -08:00
Peter Johnson
7c2f994a66 Refactor source IsConnected() and connected notification. 2016-12-18 09:05:03 -08:00
Peter Johnson
bb9f5b7491 jni_util: Add JException wrapper class.
This allows more natural C++ Throw semantics (for a variety of string
data types) for any java exception that just takes a String argument.
2016-12-15 21:54:36 -08:00
Peter Johnson
c091d74de4 jni_util: Add JException wrapper class.
This allows more natural C++ Throw semantics (for a variety of string
data types) for any java exception that just takes a String argument.
2016-12-15 21:54:36 -08:00
Peter Johnson
19be09c361 Add null checks on all JNI object parameters. 2016-12-15 00:27:32 -08:00
Peter Johnson
57d053a8fb jni_util: Make JStringRef and JArrayRef null-safe.
They return empty string and empty array (to avoid crashes) but also
report an error with backtrace to stderr when called in that manner.
2016-12-14 23:59:06 -08:00
Peter Johnson
8c2a148ed1 jni_util: Make JStringRef and JArrayRef null-safe.
They return empty string and empty array (to avoid crashes) but also
report an error with backtrace to stderr when called in that manner.
2016-12-14 23:59:06 -08:00
Peter Johnson
0e43765c53 jni_util: Add GetJavaStackTrace. 2016-12-14 23:59:02 -08:00
Peter Johnson
6fbaf57b99 jni_util: Add GetJavaStackTrace. 2016-12-14 23:59:02 -08:00
Peter Johnson
12aee3e022 Make JLocal and JArrayRef movable but non-copyable. 2016-12-14 23:29:23 -08:00
Peter Johnson
2df00647d5 Make JLocal and JArrayRef movable but non-copyable. 2016-12-14 23:29:23 -08:00
Peter Johnson
498a8e2b7d Fix JArrayRef DirectBuffer destructor.
Previously it would try to release array elements even if the DirectBuffer
constructor was used.
2016-12-14 23:29:23 -08:00
Peter Johnson
99395273c7 Fix JArrayRef DirectBuffer destructor.
Previously it would try to release array elements even if the DirectBuffer
constructor was used.
2016-12-14 23:29:23 -08:00
Peter Johnson
4568156bdf Make JClass more useful and use it in ntcore JNI. 2016-12-14 23:29:18 -08:00
Peter Johnson
ce7611562f Make JClass more useful and use it in ntcore JNI. 2016-12-14 23:29:18 -08:00
Peter Johnson
81fd0eefac usbcvstream example: Print error from GrabFrame. 2016-12-04 21:45:37 -08:00
Peter Johnson
b5fd15e052 CvSink::GrabFrame(): Add delays like MjpegServer to avoid consuming CPU. 2016-12-04 21:45:37 -08:00
Peter Johnson
ecfc684174 MjpegServer: Increase bad frame wait from 10 to 20 ms. 2016-12-04 21:45:37 -08:00
Peter Johnson
4600ea135c Frame: Make Data struct public. 2016-12-04 21:45:37 -08:00
Peter Johnson
3b82ba8945 Refactor JPEG functions to JpegUtil. 2016-12-04 21:45:37 -08:00
Peter Johnson
c32fc57ce1 Refactor HTTP utilities. 2016-12-04 21:45:37 -08:00
Peter Johnson
9a8f66e3e5 SourceImpl: Add no-copy PutFrame. 2016-12-04 21:45:37 -08:00
Peter Johnson
ef39713219 Revert "Don't output \r\n before boundary. This throws off some clients."
This reverts commit ae8c8ec230.
2016-12-04 21:45:37 -08:00
Thad House
da68fea081 Fixes shared wpiutil switch on athena (#24) 2016-12-04 21:44:06 -08:00
Peter Johnson
1f93a4ab4f Change acronym class names to use MixedCase (UsbCamera, MjpegServer). (#22) 2016-12-04 00:08:47 -08:00
Thad House
7a587390ba Fixes OpenCV on windows when we get to it. (#23) 2016-12-04 00:08:26 -08:00
Thad House
378a145cf7 Fixes Missed Symbol from Def file (#162) 2016-12-01 13:45:39 -08:00
Thad House
3625f11e08 Adds C methods that take a cv::Mat* (#21)
Some implementations of OpenCV use cv::Mat as their native pointer
rather then CvMat, so we need to support both in the C interface
2016-11-30 22:00:44 -08:00
Thad House
1332ba3ad2 Adds JNI symbol check to ensure we don't miss any definitions (#19) 2016-11-27 23:17:26 -08:00
Peter Johnson
558b2ffa41 NetworkStream: Add setBlocking() and getNativeHandle(). (#161)
Also add checking for "would block" errors in send() and receive().

Check for set nonblocking failures in TCPConnector as well (generate warnings rather than errors)
2016-11-27 19:59:52 -08:00
Peter Johnson
1315a3967d NetworkStream: Add setBlocking() and getNativeHandle(). (#161)
Also add checking for "would block" errors in send() and receive().

Check for set nonblocking failures in TCPConnector as well (generate warnings rather than errors)
2016-11-27 19:59:52 -08:00
Austin Schuh
00b76d42e0 Fixed unused variable warning from gcc. (#159)
This makes it so that ntcore builds with -Wextra -Werror
2016-11-26 16:28:50 -08:00
Austin Schuh
e7c4150c02 Fixed unused variable warning from gcc. (#159)
This makes it so that ntcore builds with -Wextra -Werror
2016-11-26 16:28:50 -08:00
Thad House
bc06c843c7 Adds JNI symbol check to ensure we don't miss any definitions (#160) 2016-11-25 17:07:58 -08:00
Peter Johnson
b8e9439d32 Message: Fix typo in error message. (#158) 2016-11-24 23:50:02 -08:00
Fred Silberberg
046d385a78 Actually fix lack of - (#157) 2016-11-20 21:42:17 -08:00
Fred Silberberg
5caf75237b Fixed version generation when no - is present (#156) 2016-11-20 21:32:32 -08:00
Thad House
a19b1b9341 Adds data accessor functions to JNI (#18) 2016-11-19 19:02:20 -08:00
Peter Johnson
0b1e876dcf Bump wpiutil version to 1.0.2. 2016-11-18 22:25:38 -08:00
Peter Johnson
ae8c8ec230 Don't output \r\n before boundary. This throws off some clients. 2016-11-18 19:52:22 -08:00
Peter Johnson
ec8c0eb3c2 Fix FPS setting and crash in reapplying settings. 2016-11-18 19:23:35 -08:00
Peter Johnson
3d898dd8f7 MJPEGServer: Fix URI %xx-decoding. 2016-11-18 19:03:35 -08:00
Peter Johnson
df18e178ee MJPEGServer: Provide a bare-bones HTML root page. 2016-11-18 18:58:03 -08:00
Peter Johnson
71a6e08988 MJPEGServer: Make a couple of tweaks for Axis camera compatibility. 2016-11-18 18:33:49 -08:00
Peter Johnson
a05636d9a6 Add data accessors for USBCamera and MJPEGServer.
USBCamera: getPath()

MJPEGServer: getListenAddress() and getPort()
2016-11-18 17:21:03 -08:00
Peter Johnson
5eecbfd9bf Implement immediate notify on network interfaces event. 2016-11-18 16:27:26 -08:00
Peter Johnson
65514b3028 USBCamera: Update description on reconnect. 2016-11-18 16:16:04 -08:00
Peter Johnson
881d55f858 VideoListener: Add move assignment operator. 2016-11-18 15:10:37 -08:00
Peter Johnson
cc20d9d0fe Add no-parameter constructors for specific sources/sinks. 2016-11-18 14:33:47 -08:00
Peter Johnson
35aa544415 VideoEvent: Make sourceHandle and sinkHandle public. 2016-11-18 13:20:50 -08:00
Peter Johnson
bad4ca4666 Add event for network interfaces change. 2016-11-18 12:41:08 -08:00
Peter Johnson
5fecc57e8a Add methods to get the hostname and network interfaces. 2016-11-18 12:41:08 -08:00
Peter Johnson
e1f4e3d2d7 Fix mapping into Java enums.
The values are bitmask not contiguous, so we need to use a switch instead
of an array.
2016-11-18 12:41:08 -08:00
Peter Johnson
5ace9e4189 Renumber event kind values. 2016-11-18 12:41:08 -08:00
Peter Johnson
9945459a41 Notify sink enable and disable events. 2016-11-18 12:41:08 -08:00
Peter Johnson
22c11fad36 Notify source property events. 2016-11-18 12:41:08 -08:00
Peter Johnson
c6b527d452 Notify source connect, disconnect, and video mode changes. 2016-11-18 12:41:08 -08:00
Peter Johnson
8e9911d330 Notify on sink source change. 2016-11-18 12:41:08 -08:00
Peter Johnson
b245725941 Notify on source and sink create and destroy. 2016-11-18 12:41:08 -08:00
Peter Johnson
154ae5dcbf Notifier: Take Impl rather than handle in notification functions.
Also take CS_EventKind rather than RawEvent::Kind.

Still provide the handle methods for the basic events (this is particularly
useful for create and destroy events).

This makes these functions easier to use from within the implementation.
2016-11-18 12:41:08 -08:00
Peter Johnson
bae2037086 Handle: Add methods to get Data struct from Impl pointer.
Also make a number of methods in UnlimitedHandleResource inline.
2016-11-18 12:41:08 -08:00
Peter Johnson
c0bc8d7028 Change examples to start at port 8081 rather than 8080.
Port 8080 is too commonly used for other purposes.
2016-11-18 12:41:08 -08:00
Peter Johnson
736b5ff424 Java: throw VideoException on error. 2016-11-18 12:41:08 -08:00
Peter Johnson
29cd2b11be enum_usb example: output the property type. 2016-11-18 12:41:08 -08:00
Peter Johnson
dcf773c3ef Add USBCamera setting functions similar to the old WPILib nivision ones. 2016-11-18 12:41:08 -08:00
Peter Johnson
791cabbc26 Rename Type to Kind. 2016-11-18 12:41:08 -08:00
Peter Johnson
3c7d8063f6 VideoProperty: rename type() to getType(). 2016-11-18 12:41:08 -08:00
Peter Johnson
3381340eb5 Add method to get source/sink type.
Also provide convenience method to enumerate all sinks connected to a source.
2016-11-18 12:41:08 -08:00
Peter Johnson
6446b9ef10 Add sink source changed event. 2016-11-18 12:41:08 -08:00
Peter Johnson
6c19eb59b2 VideoSource, VideoSink: Provide equality operation.
* Provide hashCode implementation for Java.

* Provide getHandle for both C++ and Java.
2016-11-18 12:41:08 -08:00
Peter Johnson
797d049f31 Use java.util.function.Consumer for event listener. 2016-11-18 12:41:08 -08:00
Peter Johnson
0bcafedebf MJPEGServerImpl: Refactor NeedsDHT. 2016-11-18 12:40:31 -08:00
Peter Johnson
7e0e8286eb SourceImpl: Refactor frame allocation into AllocFrame. 2016-11-18 12:40:31 -08:00
Peter Johnson
5ae1162378 Move MJPEG DHT insertion from SourceImpl to MJPEGServerImpl.
OpenCV imdecode supports images with no DHT, so it's not necessary to
add it on the source side.
2016-11-18 12:40:31 -08:00
Peter Johnson
c80c4ae55c MJPEGServer: Use worker thread model.
Also make the worker thread a class for future per-client configuration use.

Depends on wpiutil #153.
2016-11-18 12:40:31 -08:00
Peter Johnson
254b88bdbe Start adding support for non-MJPEG frame types.
Not yet supported by MJPEGServer.
2016-11-18 12:40:31 -08:00
Thad House
2657d89178 Adds a c_str method to StringRef (#155)
The StringRef class does not ensure the string is null terminated. As there is
no defined way to actually check for a null terminator, we determine
if it is null terminated based on the constructor type. Then if on c_str
it is not known to be null terminated, we use a passed in buffer to copy
the string and ensure null termination.
2016-11-14 22:51:52 -08:00
Thad House
38ec59f03a Adds a c_str method to StringRef (#155)
The StringRef class does not ensure the string is null terminated. As there is
no defined way to actually check for a null terminator, we determine
if it is null terminated based on the constructor type. Then if on c_str
it is not known to be null terminated, we use a passed in buffer to copy
the string and ensure null termination.
2016-11-14 22:51:52 -08:00
Peter Johnson
259cf1ff3a Mark NetworkTablesJNI callback interfaces as FunctionalInterface. (#154)
This allows them to be used in Java 8 lambdas.
2016-11-13 23:33:12 -08:00
Peter Johnson
b12658afc2 Make SafeThreadOwner moveable. (#153)
This allows it to be used in data structures such as std::vector.

Also make GetThread() const.
2016-11-11 22:18:52 -08:00
Peter Johnson
c23880f829 Make SafeThreadOwner moveable. (#153)
This allows it to be used in data structures such as std::vector.

Also make GetThread() const.
2016-11-11 22:18:52 -08:00
Thad House
41dd9e4f06 Loads OpenCV JNI Library in Java (#15) 2016-11-11 21:55:13 -08:00
Thad House
3d1f69075a Adds a size parameter to JStringRef (#152)
Want to use that for some allwpilib JNI cleanups and potential bug fixes
2016-11-07 19:35:48 -08:00
Thad House
dc94a3fac9 Adds a size parameter to JStringRef (#152)
Want to use that for some allwpilib JNI cleanups and potential bug fixes
2016-11-07 19:35:48 -08:00
Thad House
468cac543f Fixes JNI 2016-11-06 19:28:14 -08:00
Thad House
d4b48216e8 Renames uberzip to athena-uberzip, and doesn't include static library in it 2016-11-06 17:42:34 -08:00
Peter Johnson
f83ff41e47 Rename from cameraserver to cscore.
This is primarily to avoid header naming conflicts with wpilib.
2016-11-05 22:11:55 -07:00
Thad House
891ce06312 Adds opencv headers to uberzip (#11) 2016-11-05 21:37:47 -07:00
Thad House
0658ba6f77 Adds javadocs and sources to published windows builds (#10) 2016-11-05 21:37:24 -07:00
Peter Johnson
29d8d1d74c Implement listener interfaces. 2016-11-05 13:19:02 -07:00
Peter Johnson
8d2efb2838 Improve listener interface.
Now a structure is passed back, enabling combining the existing source
and sink listeners and adding property listeners as well.
2016-11-05 13:19:02 -07:00
Thad House
e07a40a16d Adds an UberZip that preincludes the opencv libraries
Helps eclipse a lot
2016-11-05 12:01:16 -07:00
Thad House
38a3eda6a7 Switches CameraServer on Arm to use non-included native library 2016-11-05 11:37:12 -07:00
Thad House
6d1ab7606b Enables temporary publishing on windows 2016-11-05 11:36:30 -07:00
Peter Johnson
77edf1e103 Add FRC Driver Station connection support.
The 2017 FRC Driver Station supports getting the robot IP via a TCP
connection that returns JSON.  Use this to support overriding the
server IP address used for client connections.

Default to using this approach for client connections in the NetworkTable
interfaces.

Add support for setting the server address without stopping and
restarting the client.

SetTeam now also round-robins by default.
2016-11-04 23:42:41 -07:00
Peter Johnson
28c8678ea2 SafeThread: Use atomic for m_active. 2016-11-04 23:39:09 -07:00
Peter Johnson
34acd9d47c SafeThread: Use atomic for m_active. 2016-11-04 23:39:09 -07:00
Thad House
05ca76ea99 Runs clang-format on ntcore (#150)
Also updates .clang-format to match allwpilib

WPIUtil was skipped
2016-11-03 21:03:45 -07:00
Thad House
d1065f0bd1 Moves deprecation definition to wpiutil (#149) 2016-11-03 20:08:47 -07:00
Thad House
cf0ec7b9a9 Moves deprecation definition to wpiutil (#149) 2016-11-03 20:08:47 -07:00
Peter Johnson
46085824ae Add DHT data to MJPEG source images if not present. 2016-11-02 21:32:13 -07:00
Thad House
7067179b28 Ignores the vscode directory. (#6) 2016-11-01 00:37:10 -07:00
Peter Johnson
4828a69867 Update versioning plugin. 2016-10-31 20:15:42 -07:00
Peter Johnson
3fcc808e99 Use zlib built into OpenCV. 2016-10-31 20:00:14 -07:00
Peter Johnson
15cdd661a4 Simplify OpenCV dependencies.
Depends on https://github.com/wpilibsuite/opencv/pull/6
2016-10-30 23:58:33 -07:00
Fred Silberberg
60d9f3de68 Update version plugin (#148) 2016-10-30 01:14:57 -07:00
Thad House
f87baaa4fc Moves dependencies to their own gradle file, and adds capabilities to link to ntcore and wpilib (#4) 2016-10-29 22:36:04 -07:00
Fred Silberberg
fecd8a448f Fix wpiutil version (#147) 2016-10-28 21:04:47 -04:00
Fredric Silberberg
fe4ef75cf6 Updated wpiutil version 2016-10-28 20:09:54 -04:00
Peter Johnson
87c7a9db54 Add USB and OpenCV processed dual stream example. 2016-10-28 00:54:28 -07:00
Peter Johnson
fa2ce40084 Add OpenCV library links to example executables. 2016-10-28 00:53:44 -07:00
Peter Johnson
4eac3fe9a0 Disable x86 platform for now until we get OpenCV working with it. 2016-10-28 00:52:41 -07:00
Peter Johnson
d7efd62511 build.gradle: Fix OpenCV library order.
Also include OpenCV-built liblibjpeg.a and liblibpng.a.
2016-10-28 00:51:28 -07:00
Peter Johnson
e10b399f51 CvSource: Implement NotifyError. 2016-10-28 00:47:18 -07:00
Peter Johnson
39a8195386 CvSourceImpl: Add stub for CreateProperty(callback). 2016-10-28 00:46:43 -07:00
Peter Johnson
43331419f6 MJPEGServer: Output boundary at start of image instead of end.
This avoids hiccups/timeouts causing the next image being seen as a
completely new file rather than a continuation of a multi-part.
2016-10-26 23:58:22 -07:00
Peter Johnson
c66a55d81a Implement CvSink.
* Make CvSink constructor explicit.

* Add SetDescription function.
2016-10-26 23:37:00 -07:00
Peter Johnson
9a44a38141 Fix source and sink refcounting. 2016-10-26 23:34:44 -07:00
Peter Johnson
5f69cb2a5b SinkImpl: Refactor GetDescription, add GetError, SetEnabled. 2016-10-26 23:31:48 -07:00
Peter Johnson
a5f63c3ae3 SourceImpl::GetNextFrame(): Avoid spurious wakeups. 2016-10-26 23:31:18 -07:00
Peter Johnson
0053962182 SourceImpl: add PutError().
The error message is stored as a normal frame with unknown pixel format.
2016-10-26 23:30:13 -07:00
Peter Johnson
c462d0b249 CvSourceImpl.h: Remove unnecessary include. 2016-10-26 23:26:15 -07:00
Peter Johnson
778edaeb28 Reverse the JNI load order to look for system library first. (#145) 2016-10-25 22:27:33 -07:00
Peter Johnson
273a395a2f Client: when reconnecting, default to NT3. (#143)
Previously once the client fell back once to NT2, it would never try
connecting as NT3 even if the server was replaced with a NT3-capable
one.

Fixes #142.
2016-10-25 21:44:47 -07:00
Thad House
aa49ebd47f Links wpiutil on roboRIO dynamically (#141) 2016-10-25 20:42:42 -07:00
Thad House
c45384b91a Removes the native library from the RoboRIO Jar (#139)
Includes the native zip in the maven artifact as well.
2016-10-25 20:42:06 -07:00
Fred Silberberg
88fdbc6d3e Readds wpiutilZip dependency to the build. (#144) 2016-10-25 07:04:49 -07:00
Peter Johnson
7ca6c5ef34 Remove RemoveSourceProperty. 2016-10-24 22:29:58 -07:00
Peter Johnson
511d551546 Implement most CvSource functionality. 2016-10-24 20:27:00 -07:00
Peter Johnson
7ea13f7e03 Refactor properties from USBCameraImpl to SourceImpl. 2016-10-23 18:20:56 -07:00
Peter Johnson
6754703ad1 Updated the wpilib version plugin to 1.2.
Fixes issues with submodules.
2016-10-23 14:17:16 -07:00
Fred Silberberg
89b8e5435f Updated the wpilib version plugin to 1.2. Fixes issues with submodules. (#138) 2016-10-23 14:15:28 -07:00
Peter Johnson
b0ab351f7f Don't check for existence in distributing .debug files. (#137)
This check is unnecessary and is run during task creation, so prevents
the .debug file from being included the first time gradle is run.
2016-10-23 13:18:01 -07:00
Peter Johnson
9b6f4ecd0d Don't check for existence in distributing .debug files.
This check is unnecessary and is run during task creation, so prevents
the .debug file from being included the first time gradle is run.
2016-10-23 10:42:51 -07:00
Peter Johnson
9142cbb820 CvSource: Update interface functions.
- Add SetDescription
- Supply minimum, maximum, step, defaultValue, and value to CreateProperty
- Add SetEnumPropertyChoices
2016-10-23 08:43:06 -07:00
Peter Johnson
1f6b386325 Implement frame timestamps and use wpi::Now() for generation. 2016-10-22 22:09:47 -07:00
Peter Johnson
aad1266a94 Distribute shared library .debug files. 2016-10-22 09:57:38 -07:00
Peter Johnson
06a40680aa Change debug strip to be part of link task (as doLast).
This avoids spurious re-linking.
2016-10-22 09:57:38 -07:00
Peter Johnson
cc2cbf810d Exclude opencv MANIFEST.MF files to prevent repeat unzips.
As natives and jni extract to the same location, their MANIFEST.MF files
were overwriting each other.
2016-10-22 09:57:38 -07:00
Peter Johnson
cf9aa90321 Don't overwrite platform-dependent opencv zip files.
This was causing native downloads to overwrite each other.

Also create a single def for openCvNativesFolder.
2016-10-22 09:57:38 -07:00
Peter Johnson
d51f6c45e5 JNI: initialize status to 0. 2016-10-22 09:57:38 -07:00
Peter Johnson
017ec83ce3 Add support for OpenCV to Java wrappers. 2016-10-22 09:57:38 -07:00
Peter Johnson
6641612de5 Update to use wpi version plugin. 2016-10-22 09:57:38 -07:00
Peter Johnson
218718a063 Add OpenCV dependency and update OpenCV interfaces.
This requires the wpilibsuite/opencv packages with PRs 1-3 applied.
2016-10-22 09:57:33 -07:00
Peter Johnson
353041535c Distribute shared library .debug files. (#136) 2016-10-22 09:35:36 -07:00
Peter Johnson
e4234f5198 raw_istream: Add std::istream style in_avail(). (#135) 2016-10-21 22:50:38 -07:00
Peter Johnson
d81840d6c6 raw_istream: Add std::istream style in_avail(). (#135) 2016-10-21 22:50:38 -07:00
Peter Johnson
1d336996be Dispatcher: Minimize amount of time m_flush_mutex is held. (#132) 2016-10-21 20:01:41 -07:00
Peter Johnson
86c43df8d1 Fix connection notification races. (#130)
Use a mutex on the connection state and one-shot all change notifications.

Fixes #127.
2016-10-21 19:40:56 -07:00
Peter Johnson
5c1b7ecd17 Change debug strip to be part of link task (as doLast). (#134)
This avoids spurious re-linking.
2016-10-21 19:18:32 -07:00
Peter Johnson
011ac1fa22 Java: Allow any Number type (not just Double) to be passed to putValue(). (#129)
Also improve exception message.

Fixes #72.
2016-10-21 19:17:50 -07:00
Fred Silberberg
b8e5258cf3 Creates the build dir if it doesn't exist, and deletes the version files during clean' (#131) 2016-10-20 22:41:40 -07:00
Fred Silberberg
56179088bb Updated the gradle build to get the version from the WPILibVersioning plugin (#123)
* Updated the gradle build to get the version from the WPILibVersioning plugin

* Added version output for downstream projects

* Fixed non-arm build.
2016-10-20 21:34:14 -07:00
Thad House
780e9580b7 Ignores KeepAlive messages during initial handshakes (#128)
Shouldn't happen normally, but could happen if handshakes take a longer
then normal period of time.
Closes #126
2016-10-19 22:47:33 -07:00
Thad House
b775b01e0a Optimizes NetworkTables string concatenation (#125)
During testing, I was seeing a lot of unnecessary code (and allocations
in Java/C#) when appending the path separator to the base path. That
technically is a constant, so this computes this constant during class
construction.
2016-10-17 22:33:59 -07:00
Peter Johnson
0a8e0e9746 MJPEGServer: Pass resolution and FPS requests to source. 2016-10-17 20:16:49 -07:00
Dustin Spicuzza
89805a44c1 Fix NetworkTable::setFlag typo (#124) 2016-10-16 17:28:35 -07:00
Peter Johnson
9caa0af4d9 USBCamera, HTTPCamera: Name functions consistent with classes. 2016-10-15 23:07:28 -07:00
Peter Johnson
70531762b9 usbstream: Wait for enter rather than infinite loop/sleep. 2016-10-15 22:45:56 -07:00
Peter Johnson
30f4ecd171 Rename HTTPSink to MJPEGServer. 2016-10-15 22:44:26 -07:00
Peter Johnson
d56c3f9adf USBCamera: Default to MJPEG and lowest resolution. 2016-10-15 21:27:03 -07:00
Peter Johnson
73a97c1774 USBCamera: Finish implementing mode support. 2016-10-15 17:24:47 -07:00
Peter Johnson
8ec2b1d96f README: Fix artifact names. 2016-10-13 00:38:13 -07:00
Peter Johnson
c858e0391d README: Remove reference to cmake. 2016-10-13 00:36:41 -07:00
Peter Johnson
63c9af4578 Add license. 2016-10-13 00:35:08 -07:00
Peter Johnson
473a87a76b USBCameraImpl.cpp: Clean up formatting a bit. 2016-10-13 00:32:06 -07:00
Peter Johnson
4c6f6536b8 tests.gradle: Link to wpiutil. 2016-10-13 00:31:45 -07:00
Peter Johnson
cb4d8a6555 Add examples.
Disable google tests for now.
2016-10-13 00:18:16 -07:00
Peter Johnson
417545d521 Finish most of USBCameraImpl.
The main thing not yet fully implemented is video mode setting.

Also fix a handful of bugs in HTTPSinkImpl.
2016-10-13 00:16:24 -07:00
Peter Johnson
7f88bd15d1 SinkImpl: Keep enabled count rather than just boolean.
This allows e.g. multiple HTTP streams to individually call Enable() and
Disable().
2016-10-13 00:13:18 -07:00
Peter Johnson
7b3f6eeae2 Add raw_fd_istream. (#121) 2016-10-08 16:03:33 -07:00
Peter Johnson
f6df7cad9b Add raw_fd_istream. (#121) 2016-10-08 16:03:33 -07:00
Peter Johnson
15cb505163 TCPStream: Avoid SIGPIPE signals.
On Mac, this is done by setting SO_NOSIGPIPE on the socket.
On Linux, this is done with MSG_NOSIGNAL on the send call.
2016-10-08 16:02:55 -07:00
Peter Johnson
cc1b94afd2 TCPStream: Avoid SIGPIPE signals.
On Mac, this is done by setting SO_NOSIGPIPE on the socket.
On Linux, this is done with MSG_NOSIGNAL on the send call.
2016-10-08 16:02:55 -07:00
Thad House
a7eca7d4bd Adds ConnectionInfo to Rpc callback (#116) 2016-10-03 10:04:30 -07:00
Thad House
9047c98e68 Fixes possible indefinite timeout on multiple RPC calls (#120)
Calculates timeout before the RPC call checks ever loop.
2016-09-30 12:41:52 -07:00
Peter Johnson
53d0789660 Storage: Escape equal sign in strings. (#119)
This helps interoperability with standard config parser libraries
(such as Python's RawConfigParser).
2016-09-29 20:16:32 -07:00
Peter Johnson
ee24a6f4fc Disable support for non-MJPEG formats. 2016-09-29 00:06:31 -07:00
Peter Johnson
70616c48e3 Add support for enumerating and changing USB camera video mode. 2016-09-29 00:04:16 -07:00
Peter Johnson
d4bbd5cc6f Make raw_socket_istream constructor explicit. 2016-09-25 19:48:49 -07:00
Peter Johnson
1affae956b Make raw_socket_istream constructor explicit. 2016-09-25 19:48:49 -07:00
Peter Johnson
7463e02080 Logger: Use raw_ostream and SmallString. 2016-09-25 19:48:49 -07:00
Peter Johnson
d3ed26f7cc Logger: Use raw_ostream and SmallString. 2016-09-25 19:48:49 -07:00
Peter Johnson
f711ced4ca Add raw_socket_ostream.
This wraps NetworkStream in a llvm::raw_ostream.
2016-09-25 19:48:49 -07:00
Peter Johnson
1ec89fc4f3 Add raw_socket_ostream.
This wraps NetworkStream in a llvm::raw_ostream.
2016-09-25 19:48:49 -07:00
Peter Johnson
a92b7298f9 Add 1-character read to raw_istream. 2016-09-25 19:48:49 -07:00
Peter Johnson
de07b01a75 Add 1-character read to raw_istream. 2016-09-25 19:48:49 -07:00
Peter Johnson
4c6c096c50 Change API of raw_istream to be more similar to raw_ostream. 2016-09-25 19:48:49 -07:00
Peter Johnson
c2ae897b02 Change API of raw_istream to be more similar to raw_ostream. 2016-09-25 19:48:49 -07:00
Peter Johnson
b2e1291973 Refactor JNI helpers into wpiutil (support/jni_util.h). (#105) 2016-09-25 19:29:17 -07:00
Peter Johnson
94c2b65798 Refactor JNI helpers into wpiutil (support/jni_util.h). (#105) 2016-09-25 19:29:17 -07:00
Peter Johnson
760d6a26d3 Make SafeThread header-only. (#117) 2016-09-25 18:21:29 -07:00
Peter Johnson
3a419768ca Make SafeThread header-only. (#117) 2016-09-25 18:21:29 -07:00
Peter Johnson
d8ee44349c Update to latest LLVM code (#88)
* Update to latest LLVM code.

* Add LLVM's raw_ostream.

* MathExtras.h: Include cmath for log2.
2016-09-25 17:49:01 -07:00
Peter Johnson
ee42448504 Update to latest LLVM code (#88)
* Update to latest LLVM code.

* Add LLVM's raw_ostream.

* MathExtras.h: Include cmath for log2.
2016-09-25 17:49:01 -07:00
Peter Johnson
d90cf843e8 Move common utility classes to wpiutil library. (#79)
This is a breaking change to dependencies that use the static ntcore
library.  Unless the wpiutil library is also linked, linker errors will
result.  This does not affect the shared ntcore library.
2016-09-25 17:23:39 -07:00
Peter Johnson
f6b700ea97 Move common utility classes to wpiutil library. (#79)
This is a breaking change to dependencies that use the static ntcore
library.  Unless the wpiutil library is also linked, linker errors will
result.  This does not affect the shared ntcore library.
2016-09-25 17:23:39 -07:00
Peter Johnson
a5fe605aae HTTPSink: Add basic property setting support. 2016-09-20 23:27:21 -07:00
Peter Johnson
7818c3bda3 USBCamera: Normalize property names. 2016-09-20 22:28:48 -07:00
Peter Johnson
d5e5755ff4 Collapse boolean/double/enum properties into just integer. 2016-09-20 22:17:12 -07:00
Peter Johnson
8fbc23b1fa HTTPSinkImpl fixes. 2016-09-20 20:40:58 -07:00
Peter Johnson
d05f0820b2 HTTPSinkImpl: Report property step and default. 2016-09-20 00:01:09 -07:00
Peter Johnson
dad44cc928 Add status parameter to property functions. 2016-09-19 23:50:47 -07:00
Peter Johnson
2c80587d11 Start implementing USBCamera. 2016-09-19 22:11:37 -07:00
Peter Johnson
80eb056432 Fix property handles (and allocate more bits to the property index). 2016-09-19 22:04:45 -07:00
Thad House
80e546b79f Adds a way to externally test C structures (#115)
For language interop, its nice to be able to create the structs from the
C side to make sure everything works properly.
2016-09-18 21:48:17 -07:00
Peter Johnson
6eba04ed8e Use copy-and-swap idiom for reference-counted classes. 2016-09-18 17:25:48 -07:00
Peter Johnson
c606671d27 Consistently name property max/min functions and add step/default. 2016-09-18 17:25:21 -07:00
Peter Johnson
9bb37d5df0 Remove support for multiple channels. 2016-09-18 17:15:27 -07:00
Thad House
e952236e1a Reverts the last 2 Rpc changes (#114)
* Revert "Fully asigns the ConnectionInfo struct (#113)"

This reverts commit 9a3100b221.

* Revert "Passes the ConnectionInfo of the Rpc client on server callback (#112)"

This reverts commit 7e9754acff.
2016-09-16 22:23:58 -07:00
Thad House
9a3100b221 Fully asigns the ConnectionInfo struct (#113)
For some reason, it was putting garbage in for the things that shouldn't
have been, which doesn't make much sense.
2016-09-16 21:56:57 -07:00
Thad House
7e9754acff Passes the ConnectionInfo of the Rpc client on server callback (#112) 2016-09-16 20:20:55 -07:00
Peter Johnson
b78592d622 Log.h: Remove unnecessary includes. 2016-09-10 21:54:16 -07:00
Peter Johnson
052f746c68 Use StringRef and ArrayRef return values when buf passed.
For functions where a SmallVector is passed to be used as a stack buffer for
the return value, have the return value be the appropriate StringRef or
ArrayRef type.  This allows for both more natural usage and enables directly
returning (rather than copying) a permanently stored or constant string.
2016-09-10 21:30:39 -07:00
Peter Johnson
c4ceec145a Enable unit tests. 2016-09-10 13:01:16 -07:00
Peter Johnson
775386d8b3 HTTPSinkImpl: Implement GetDescription. 2016-09-10 12:46:43 -07:00
Peter Johnson
451c08ef7b Add wpiutil library dependency to builds. 2016-09-10 12:06:18 -07:00
Peter Johnson
52c8743b36 Finish rename of EnumerateSinks to EnumerateSinkHandles.
And similarly for EnumerateSources to EnumerateSourceHandles.
2016-09-09 23:28:57 -07:00
Peter Johnson
5c59b9aeb3 Make HTTPCamera constructor public. 2016-09-09 23:06:50 -07:00
Peter Johnson
3e00dabd16 Import gmock. 2016-09-09 22:55:15 -07:00
Thad House
c5c069743b Switches AppVeyor to use same build for 32 and 64 bit java tests (#107) 2016-09-09 12:09:53 -07:00
Peter Johnson
ba241cd7f9 Source: Keep track of how many sinks are connected and enabled. 2016-09-08 23:52:23 -07:00
Peter Johnson
ddb97bfafb Fix SendStream error handling. 2016-09-08 21:00:23 -07:00
Peter Johnson
e415ca66b6 Initial HTTPSink implementation. Untested. 2016-09-08 00:07:20 -07:00
Peter Johnson
85be299da1 Start implementation. 2016-09-08 00:07:20 -07:00
Peter Johnson
9dd5bea7a5 Create a common CS_Handle. Add initial status values. 2016-09-08 00:07:20 -07:00
Peter Johnson
e71abedefb Add logging implementation. 2016-09-08 00:07:20 -07:00
Thad House
3888d7726a Adds connection listeners that can be called statically (#111)
This way you can have a connection listener before initializing NetworkTables.
2016-09-06 21:30:59 -07:00
Thad House
fc48944b47 Fixes Rpc Cancel. Check was only in timeout case instead of global (#110) 2016-09-02 19:28:59 -07:00
Thad House
2150f5879b Adds AppVeyor support for VS 2013 and 2015 (#106) 2016-08-30 22:04:19 -07:00
Thad House
85156d15ca Fixes the final issue with VS 2013 builds (#109) 2016-08-30 21:27:48 -07:00
Peter Johnson
6943d14f93 Java: Use wpiutil jni-util.h helpers. 2016-08-28 21:20:40 -07:00
Thad House
ade4e87d6f Fixes support for MSVC 2013 (#104) 2016-08-28 19:17:31 -07:00
Peter Johnson
8007a7b153 Correctly handle UTF8 Java translation for StringArray. (#103) 2016-08-26 21:55:11 -07:00
Peter Johnson
e8643600f2 Implement all current JNI native functions. 2016-08-26 10:46:10 -07:00
Peter Johnson
cb7f1f6e3e Initial .def file real content. 2016-08-26 09:31:58 -07:00
Peter Johnson
af7132be82 Initial CameraServerJNI.cpp commit. 2016-08-26 09:31:42 -07:00
Peter Johnson
ec080118f4 Clean up odd special case of GetSourceProperty(). 2016-08-26 09:24:18 -07:00
Peter Johnson
6bcc0e2d82 Correctly prefix CS_EnumerateSourceProperties. 2016-08-26 09:12:55 -07:00
Peter Johnson
2fd81a7e33 Add copyright notices to Java files. 2016-08-26 09:01:54 -07:00
Peter Johnson
2f99f81aa6 Java: Add VideoProperty implementation. 2016-08-26 08:51:28 -07:00
Peter Johnson
97f1f1c9c4 CameraServerJNI: Fix case of a few functions. 2016-08-26 08:51:28 -07:00
Peter Johnson
0fbb2e8a14 Add methods to get property name and enumerate properties.
Also add method to remove property by handle.
2016-08-26 08:51:23 -07:00
Peter Johnson
0158fd35f0 Continue implementing C wrappers.
Implement non-OO C++ EnumerateUSBCameras().
2016-08-26 07:04:33 -07:00
Peter Johnson
80b15b7fe5 Add a bit of description about how handles work in the C API. 2016-08-26 01:00:38 -07:00
Peter Johnson
2acca6eeb1 cameraserver_cpp.h: Move stdint.h above the C++ includes. 2016-08-26 00:43:03 -07:00
Peter Johnson
151c89fb5d Rename FrameGrab to GrabFrame. 2016-08-26 00:30:45 -07:00
Peter Johnson
4f22ac4100 Move all non-trivial inline functions to cameraserver_oo.inl. 2016-08-26 00:29:28 -07:00
Peter Johnson
7c1da2dfcd Split classes in cameraserver_cpp.h out to cameraserver_oo.h. 2016-08-26 00:08:02 -07:00
Peter Johnson
b5d32ec844 VideoSource, VideoSink: Move the status flag too. 2016-08-25 23:17:46 -07:00
Peter Johnson
aec16a934f Revamp API again and start implementing C and Java wrapper shells. 2016-08-25 23:13:48 -07:00
Fred Silberberg
075155b431 More gradle 3.0 additions (#102) 2016-08-22 20:59:50 -07:00
Peter Johnson
c25c62e0af Update gradle to 3.0. 2016-08-22 20:40:19 -07:00
Fred Silberberg
e653a228fa Updates gradle to 3.0. Now that the check bug is fixed, removes the empty check tasks. (#101) 2016-08-21 11:16:33 -04:00
Peter Johnson
b2831347bc Revamp API. 2016-08-19 23:05:28 -07:00
Thad House
7845caa100 Fixes GetRpcResult not removing calluid from call list on non blocking call (#100) 2016-08-19 21:48:30 -07:00
Thad House
66d214c8a8 Finishes blocking call canceling (#99) 2016-08-18 00:05:06 -07:00
Thad House
277cf2a08f Removes new line from mdns name (#98)
Closes #97
2016-08-17 21:21:55 -07:00
Thad House
7bf44e951c Fixes server side polled rpcs (#96) 2016-08-16 23:32:13 -07:00
Thad House
c0ce4270f0 Adds a way to cancel a blocking rpc call (#94) 2016-08-16 23:31:45 -07:00
Thad House
d6e8de21ef Fixes rpc timeouts and blocking call list error (#95) 2016-08-16 23:31:01 -07:00
Peter Johnson
1635cba827 Reduced minimum update rate from 100 ms to 10 ms. (#89) 2016-08-16 12:07:17 -07:00
Thad House
a786470623 Only allows 1 blocking call per Rpc Call Id (#93) 2016-08-15 22:46:49 -07:00
Thad House
4164e670d2 Adds Visual Studio Code files to gitignore (#92) 2016-08-15 22:44:36 -07:00
Peter Johnson
062470ef68 Add llvm::SmallSet. (#90) 2016-08-15 22:05:47 -07:00
Thad House
0b80bd2b09 Adds timeout capabilities to blocking Rpc Calls (#86) 2016-08-15 20:24:07 -07:00
Peter Johnson
e1515299c2 Initial commit. 2016-08-14 12:38:13 -07:00
Thad House
bc99d341fb Changes remote_name to remote_ip (#87)
Was confusing, as remote_name seemed like a name but wasn't.
Also changes remote_ip in the C api to use an NT_String
2016-08-07 16:38:20 -05:00
Fredric Silberberg
0f9f7309e3 Sets the duplicate strategy to exclude in all zip tasks (#85) 2016-07-30 23:07:21 -05:00
Peter Johnson
e6244289ff Create dummy wpiutil library. (#84)
This will allow dependencies such as wpilibc to update to use wpiutil
without breaking "normal" ntcore static library use in the meantime.

This commit also restructures the gradle files by creating a new
(placeholder) wpiutil project, and moving the ntcore project into
a separate gradle file.  Added toolchains/native.gradle (refactored from
ntcore).

Also fixes ntcore skipJava on Windows by providing an alternate .def file
for this case.
2016-07-27 22:18:56 -05:00
Peter Johnson
30fbfe46e6 Create dummy wpiutil library. (#84)
This will allow dependencies such as wpilibc to update to use wpiutil
without breaking "normal" ntcore static library use in the meantime.

This commit also restructures the gradle files by creating a new
(placeholder) wpiutil project, and moving the ntcore project into
a separate gradle file.  Added toolchains/native.gradle (refactored from
ntcore).

Also fixes ntcore skipJava on Windows by providing an alternate .def file
for this case.
2016-07-27 22:18:56 -05:00
Peter Johnson
a73166a665 Make many more utility classes/headers public. (#76)
Moving these headers from src to include enables other libraries to use the
functionality provided.

* tcpsockets
* atomic_static
* raw_istream
* timestamp
* SafeThread
* Base64
* LEB128
* ConcurrentQueue

The classes have been moved into the wpi namespace as they're generic.
2016-07-27 00:39:38 -07:00
Fredric Silberberg
d66f65e376 Updates gradle to 2.14.1 (#83) 2016-07-25 21:21:08 -07:00
Thad House
b979fc2a67 Adds SetDefault Java definitions to Def file (#82) 2016-07-13 01:53:26 -07:00
Thad House
58092c5190 Adds SetDefault methods to NetworkTables (#54)
There was no way to atomically check for a key in the table,
and then setting if it if non existant. Back before persistent
this was not a problem, however now it is, as its possible for
values to be added before team's robot programs start. This makes
the old method of calling Put*** methods in RobotInit invalid.
This adds SetDefault methods, which do this atomically.
2016-07-13 00:31:03 -07:00
Fredric Silberberg
6615a34e99 Added contributing and license files (#63) 2016-07-12 23:20:51 -07:00
Peter Johnson
50a2612839 Notifier: maintain freelist to reuse uids. (#81)
This avoids endless growth of the vector.

Fixes #80.
2016-07-12 23:19:46 -07:00
Peter Johnson
eb4350033b Update Travis OS X build to use newest image. (#75)
Fixes #74.
2016-07-01 00:08:43 -07:00
Fredric Silberberg
384ad57d21 Updates Gradle to 2.14 (#78) 2016-06-30 19:57:29 -07:00
Peter Johnson
4b516de183 Don't delete persistent entries in DeleteAllEntries. (#71)
This is a behavior change but without it DeleteAllEntries is dangerous and
not very useful, so I consider the current behavior to be a bug.
2016-06-17 22:33:02 -07:00
Peter Johnson
c7d9ecbab3 Fix mac build by not defining false and true. (#73) 2016-06-17 22:32:18 -07:00
Tyler Veness
b2795af2b8 Added note that multilib GCC is required when building the native version on 64 bit Linux (#66)
Without a GCC installation that can build both 32 and 64 bit executables, the native build will fail on 64 bit Linux machines with an error about unsigned __int128 being undefined. GCC does not support __int128 on 32 bit targets, and GCC was using it via a standard library implementation header intended for 64 bit machines.

Instances of "arm" were replaced with "ARM" where the acronym was intended.
2016-06-11 02:55:46 -04:00
Thad House
6c6c087e30 Fixes .gitignore ignoring needed files (#68)
ntcore.def and build.gradle were being ignored, which could cause issues
if those files ever got deleted.
2016-06-11 02:52:24 -04:00
Peter Johnson
3c77faaf61 Fix UTF8 conversion in Java. (#70)
Java doesn't use standard UTF8, so surrogate pairs were being converted
incorrectly and incompatibly with C++.

Fixes #69 (artf3973).
2016-06-10 22:24:42 -04:00
Jonathan Leitschuh
6272244a73 Adds error-prone to check java code 2016-05-13 21:17:20 -07:00
Jonathan Leitschuh
a532518056 Adds all relevent tools to gitignore 2016-05-13 21:10:41 -07:00
Peter Johnson
320db8df18 Add .clang-format. 2016-05-13 21:05:56 -07:00
Jonathan Leitschuh
d1fb8cc209 Merge pull request #60 from wpilibsuite/build/appveyor
Adds appveyor build config
2016-05-12 11:57:35 -04:00
Jonathan Leitschuh
7d33059c20 Add appveyor badge to readme 2016-05-11 18:47:39 -04:00
Jonathan Leitschuh
ed0f197d1b Adds appveyor build config 2016-05-11 14:17:55 -04:00
Jonathan Leitschuh
25ad7a6230 Merge pull request #59 from wpilibsuite/build/osxTravisBuild
Adds OSX Build to travis
2016-05-11 14:12:28 -04:00
Jonathan Leitschuh
5fb31baea6 Adds OSX Build to travis 2016-05-11 13:45:53 -04:00
Jonathan Leitschuh
ffb384ebfc Add Travis Badge to ReadMe 2016-05-11 11:54:15 -04:00
Jonathan Leitschuh
95098c5496 Add required apt packages to travis 2016-05-11 11:43:03 -04:00
Jonathan Leitschuh
3862668420 Add Travis config file 2016-05-11 11:32:02 -04:00
Peter Johnson
5ac68f74d4 Support client round robin to multiple server addresses.
Change-Id: If87dc64a485b1c8a340c5f6fa39ca09d40133e30
2016-04-08 22:02:52 -07:00
Peter Johnson
b8ad1de33c Make members of ConnectionInfo and EntryInfo public. 2016-04-08 13:08:07 -07:00
Peter Johnson
f80312b86b Merge pull request #52 from robotdotnet/master
Fixes Connection Listeners
2016-02-08 23:55:10 -08:00
Thad House
836dc7a880 Fixes Connection Listeners
AddConnectionListener was returning the uid of entry listeners, which
would make connection listeners not work.
2016-02-08 15:40:34 -08:00
Peter Johnson
7283293887 Merge pull request #51 from robotdotnet/RemoteChanges
Adds extended Remote Connection Listener
2016-02-08 01:19:02 -08:00
Thad House
710bd586d5 Adds extended Remote Connection Listener
Since we now get ConnectionInfo when setting a connection listener,
there is some good information in there that teams could use.
Implemented using default interface methods, so teams should see no
change if they don't implement the Ex methods.

I noticed that the connection listener methods don't exist at all in
C++, so they did not get added there.
2016-02-06 23:28:19 -08:00
Peter Johnson (294)
cb4cc63221 Merge "Added -pthread" 2016-01-22 13:44:47 -08:00
Fredric Silberberg
838d8abf63 Added -pthread
Change-Id: Iea1553c9632fb270d56140a046cffa5258ce6d2d
2016-01-22 14:18:52 -05:00
Peter Johnson
94bd629b80 Merge pull request #48 from ThadHouse/master
Load ntcore from path if extracted load fails
2016-01-21 21:53:04 -08:00
Thad House
73d6e98bf2 Loads ntcore from path if extracted load fails
There's a lot of buzz going around the internet about people trying to
get ntcore working on other devices. One of the things that makes it
harder is having to have a separate jar for each platform. What this
change does is if the loading of the extracted library fails, it will
attempt to load ntcore from the path. This means that a program like
GRIP can just provide the libntcore.so and not have to worry about
compiling different versions for different platforms.
2016-01-18 22:39:27 -08:00
Peter Johnson
c90a8c586f getTable(): Don't prepend slash if key already starts with it.
This makes getTable("/foo") and getTable("foo") equivalent.
2016-01-14 21:38:04 -08:00
Peter Johnson
9092b74f4e TCPAcceptor: Check for socket creation failure. 2016-01-04 18:13:39 -08:00
Peter Johnson
b3d28c7e3a Merge pull request #46 from 333fred/master
Adds a compilerPrefix argument for using a compiler with a different toolchain.
2016-01-04 18:03:49 -08:00
Peter Johnson
ed92385469 Merge pull request #44 from ThadHouse/master
Fixes Android Build issues
2016-01-04 18:02:08 -08:00
Thad House
1247976a34 Fixes Android Build issues
Trying to build with the android standalone compiler, and these 2 things
were causing errors. I don't know what an equivalent to basename would
be, because I don't really know what it does.
2016-01-04 17:35:51 -08:00
Fredric Silberberg
880bc7db9f Adds a compilerPrefix argument for using a compiler with a different
toolchain.
Resolves github #45.

Change-Id: I6f16dcc41278f12fbbc1f742d6aaf3ad19ac61bc
2016-01-04 19:53:56 -05:00
Peter Johnson
20f23e0e31 TCPConnector: Don't leak socket descriptors.
Also check to see if socket() returns error (less than 0) and error out.
2016-01-04 13:08:00 -08:00
Peter Johnson
d9efcbc7a9 C++ NetworkTable: Add array and raw getters and setters.
For consistency with Java NetworkTable; also makes these data types easier
to use (although they are less efficient as they require a memory allocation
and data copy).
2016-01-04 09:37:29 -08:00
Peter Johnson
5e2a07d58a Fix client connection to 2.0 server.
Fixes #42.
2016-01-03 17:54:08 -08:00
Peter Johnson
620836e1cb Update .gitignore. 2016-01-02 09:39:14 -08:00
Peter Johnson
af2f54720d Java: Don't detach thread when releasing globals.
JavaGlobal was unconditionally attaching to (okay) and detaching from (bad)
the current thread during destruction.  We don't want to do this if the
destructor gets called from an attached thread.  Instead, use GetEnv to
first try to get the environment, and only attach and detach if it returns
an error saying the thread is detached.

Also, make sure notifier callbacks appropriately free Java locals to avoid
running out of local variable space.
2016-01-01 19:05:00 -08:00
Peter Johnson
236ef199aa Merge pull request #41 from 333fred/master
Added skipArm flag to disable the arm build entirely
2015-12-29 13:37:29 -06:00
Fredric Silberberg
1ea5b21dcf Added skipArm flag to disable the arm build entirely
Change-Id: I49c6cb3bfb3b1eda60d5b99b634b1e82fb2afcc8
2015-12-29 12:08:51 -05:00
Peter Johnson
e6054f543a ntcore_c.h: Whitespace fixes. 2015-12-29 08:57:10 -08:00
Peter Johnson
2aaaed34f9 Unbreak build on VS2012. 2015-12-28 19:27:05 -08:00
Peter Johnson
fef8f933d9 Add SafeThread to fix thread JNI shutdown races.
During JVM shutdown, some JNI calls may not return, so it's not possible to
reliably perform a join() during static variable destruction (which occurs
as the JVM unloads the JNI module).

Also, due to static variable destruction, it's not safe to use any members
of a static class instance from a separate thread of execution.

SafeThread is a templated thread class and a related owner class that's
designed for safe operation and shutdown of threads in the presence of
callbacks that may not return.  It also passes ownership of variables from
the static instance to the thread, so the thread can safely operate until
it exits (the last operation of the thread being to destroy its instance).

Notifiers, RpcServer, and Logger now use SafeThread to ensure race-free
destruction in both C++ and Java.

All Java callback threads are now marked as Java daemon threads so they
don't keep the JVM running after main() terminates.

All Java callback threads are now named so their purpose is more easily
identified in a debugger.

Add SetRpcServerOnStart and SetRpcServerOnExit (similar to Listener).
2015-12-28 17:51:56 -08:00
Fredric Silberberg
d8de5e4f19 Added ntcore sources zip to the main build
Change-Id: I7760ebb86c5493d5d9bc3ef9b9def02bcfb7216c
2015-12-24 14:42:36 -05:00
Peter Johnson (294)
554543c5d0 Merge "Fixes the sources zip to actually include all sources." 2015-12-23 18:07:57 -08:00
Peter Johnson
44821c3e3c Change how Dispatcher is shut down.
The previous use of a timeout resulting in thread detach instead of thread
join resulted in a race condition on Mac between destruction and thread
closeout.  This commit removes the detach functionality and uses dup2() to
on Linux/Mac and connecting to itself on Windows to try to ensure accept()
exits.
2015-12-23 08:08:53 -08:00
Fredric Silberberg
8cc066ecc4 Fixes the sources zip to actually include all sources.
Change-Id: I54658aacd715c9c06e1625dbebb2933d09921df1
2015-12-22 13:01:57 -05:00
Peter Johnson
2540f102b0 Include sys/select.h on Unix platforms. 2015-12-21 12:24:59 -08:00
Peter Johnson
8b3f4aa68c Remove unused member variable. 2015-12-21 09:03:30 -08:00
Peter Johnson
0537f9d0d7 Fix mac.gradle. 2015-12-20 23:49:47 -08:00
Fredric Silberberg
4b0980fb86 Fixed jar task dependencies. The stripped version of the binary is now added to the jar, not the full debug version of the binary
Change-Id: I8057dffd9e4ca28cca1fe8f0e95fa5fc536f2c9e
2015-12-21 00:33:36 -05:00
Peter Johnson
65e4eeeb7c Fix Windows linkage.
Windows needs ATOMIC_STATIC_INIT.
2015-12-20 21:06:17 -08:00
Peter Johnson
298dc54910 Fix Windows build. 2015-12-20 20:55:36 -08:00
Peter Johnson (294)
fb486e381f Merge "Added a withoutTests gradle flag for CMAKE feature parity" 2015-12-20 20:45:51 -08:00
Peter Johnson
32001427d4 Java: call JNI AttachCurrentThread less frequently.
Each call to AttachCurrentThread results in a new Java thread object being
created.  This is inefficient and also causes debugging issues with Eclipse
due to constant creation and removal of threads.  Now AttachCurrentThread is
only called once for (all) listeners and once for logging (if used).
2015-12-20 20:42:09 -08:00
Fredric Silberberg
2a43813d14 Added a withoutTests gradle flag for CMAKE feature parity
Change-Id: I7b76c3a616e66cb8e3372b01a61049a7f1406503
2015-12-20 18:05:06 -05:00
Peter Johnson
b4c0583896 ContainsKey: Compare to nullptr.
This is a style change, not a functional change.
2015-12-19 22:36:32 -08:00
Peter Johnson
88b985be5d Allow building of tests to be disabled in cmake.
Defining WITHOUT_TESTS will result in tests not being built.

Fixes #38.
2015-12-19 20:34:18 -08:00
Peter Johnson
7528b6b8bf Fix NetworkTable::ContainsKey.
Previously this would always return false due to how explicit bool is
evaluated in a return context.

Also add a test for this function.

Reported by: jcreigh
2015-12-19 08:47:52 -08:00
Peter Johnson
e25d9fc96a Use correct condition variable in DispatchThreadMain(). 2015-12-11 21:13:41 -08:00
Fredric Silberberg
b1a3ded2fa Added desktop classifier publishing for c++ as well
Change-Id: I7174aa3fce10fee2988e16b5a95c392b430cefb6
2015-12-10 18:31:59 -05:00
Peter Johnson
bc6da8effa Add noexcept shim for MSVC. 2015-12-09 01:22:21 -08:00
Peter Johnson
5d26b13553 NetworkTable: Add override declarations for all functions.
clang generates errors for using override on only some functions.
2015-12-09 01:18:14 -08:00
Peter Johnson
0d7106450b Make TableKeyNotDefinedException::what() const noexcept. 2015-12-09 01:18:00 -08:00
Peter Johnson
60647a2f8c Turn off Nagle algorithm to decrease latency.
This is safe because of the way writes are performed: for each transmission,
all outgoing messages are concatenated in memory and only a single write()
syscall is made.
2015-12-09 00:58:06 -08:00
Peter Johnson
76ee093e92 Add exception-generating C++ functions, but mark as deprecated.
These are good to have for backwards compatibility, but discouraged for new
development (default-taking functions should be used instead).  The reason
is that the exceptions must be explicitly handled and may initially work but
then fail at an inopportune moment.

Mark the similar Java functions as deprecated as well for the same reason.

Update all the docs for consistency.

Mark overridden functions as such in both C++ and Java.

Make IsPersistent and GetFlags const in C++.
2015-12-06 22:39:38 -08:00
Fredric Silberberg
9e6635ec13 Fixed log compilation on Mac
Change-Id: Ic231c56bdfd74c23d6086fb8ec485a0cec17d248
2015-12-06 16:14:26 -05:00
Fredric Silberberg
db91e20ec7 Updated ntcore build to build both arm and native versions
Change-Id: I515f051bbb816a1a82667462ad4e140cdb0fabdc
2015-12-06 14:43:30 -05:00
Peter Johnson
3cd20d3ff2 Java: Fix getValue(). 2015-12-06 08:22:34 -08:00
Peter Johnson
c2642f39ed Avoid null pointer deref on disconnect. 2015-11-30 20:02:40 -08:00
Peter Johnson
7182b9a6b5 Upgrade TCPConnector messages from DEBUG to ERROR / INFO.
This makes the client a lot more "chatty" but also a lot more informative
as to what's actually going on connection-wise.
2015-11-30 20:01:54 -08:00
Peter Johnson
ac9e42af36 TCPConnector: Select only IPv4 addresses. 2015-11-30 20:01:15 -08:00
Peter Johnson
790862db4b Provide default stderr logger for INFO/WARN/ERR levels. 2015-11-30 19:43:47 -08:00
Austin Schuh
bb9988365f Fixed const correctness in casts and unused parameters.
GCC was throwing warnings about const correctness issues and unused
parameters.  This patch gets rid of those warnings by using the
correct casts.
2015-11-28 13:12:30 -08:00
Fredric Silberberg
f10f8558eb Added README for building
Change-Id: I1bd91831b85adb90bd373c2bed44d2e4acf5dcae
2015-11-27 14:58:30 -05:00
Fredric Silberberg
26c27756af Updated the definitions file to add overloaded functions, added
no-unused-private-field for Mac builds. Gradle also now works
with the classifier-based dependency system, rather than having
separate repos for every level.

Change-Id: I2eb87391181e91b5675e3e982e4d915be83e14ea
2015-11-23 18:36:43 -05:00
Peter Johnson
c76e60324b Add Java support for raw values.
Either ByteBuffer or byte[] can be used for putRaw().
getRaw() returns byte[].
2015-11-20 01:22:26 -08:00
Peter Johnson
d98ceb60c3 Merge pull request #36 from ThadHouse/master
Makes SetTeam use Mdns
2015-11-19 23:15:06 -08:00
Thad House
2e050b0540 Makes SetTeam use Mdns 2015-11-19 23:02:39 -08:00
Peter Johnson
44ba8823d7 Merge pull request #34 from JLLeitschuh/feat/functionalTableListener
Makes ITableListener a lambda function
2015-11-17 22:44:20 -08:00
Jonathan Leitschuh
4c42712b24 Makes ITableListener a lambda function 2015-11-18 01:39:53 -05:00
Fredric Silberberg
6a0485a72c Fixed mac lib path
Change-Id: Ib6f38b7f42df9c9908c7e60eca12dd48c9c4114a
2015-11-17 18:51:16 -05:00
Peter Johnson
967400f181 Merge pull request #32 from ThadHouse/master
Adds StopNotifier and StopRpcServer functions
2015-11-11 20:57:55 -08:00
Thad House
a142cc48d3 Adds StopNotifier and StopRpcServer functions
Workaround for #30.  Allows libraries to shut down the secondary
threads.
2015-11-11 20:50:30 -08:00
Peter Johnson
3469f6733c GetRpcResult: Check m_terminating after wait() returns. 2015-11-10 23:21:50 -08:00
Peter Johnson
2b6c6f280c Merge pull request #31 from ThadHouse/master
Fixes SetEntryRaw to actually set raw.
2015-11-10 23:09:05 -08:00
Thad House
aefeee39aa Fixes SetEntryRaw to actually set raw. 2015-11-10 23:03:00 -08:00
Peter Johnson
27101979fa Add extern "C" to ntcore_c implementation.
This will catch any future parameter type mismatches to the header file.
2015-11-10 00:39:46 -08:00
Peter Johnson
033520d426 Merge pull request #29 from ThadHouse/master
Fixes parameter type differences for c interface.
2015-11-10 00:38:31 -08:00
Thad House
16e68c3480 Fixes parameter type differences for c interface. 2015-11-10 00:25:37 -08:00
Peter Johnson
94b6073f34 Merge pull request #28 from ThadHouse/master
Makes Value::MakeStringArray properly set size
2015-11-09 22:08:27 -08:00
Thad House
8fc2eee2b4 Makes Value::MakeStringArray properly set size
The Value::MakeStringArray methods were not setting the size of the
arr_string. This was causing the  NT_Value struct called from the C
entry listener callback to not have the array size, which would then
cause the GetValueStringArray method to fail the malloc.
2015-11-09 22:05:38 -08:00
Fredric Silberberg
969af7b610 Added publishing of an ntcore sources zip
Change-Id: Ibcdbff6b165f7b35ac6163e39c61f315db15f323
2015-11-03 21:12:23 -08:00
Fredric Silberberg
da66118331 Add JNI headers to the exported headers when compiled with JNI
Change-Id: I3b2dcad2f15445a9aea27ab0905d397d1cf9f9b5
2015-11-03 21:10:44 -08:00
Peter Johnson
424efca1bf NetworkConnection: bump debug levels a bit.
DEBUG4 is getting pretty verbose.
2015-11-02 22:12:20 -08:00
Peter Johnson
4d7ea37d56 Fix update message type data.
The type was being read and written as the raw enum value rather than as
the actual type definition.
2015-11-02 22:08:35 -08:00
Peter Johnson
32a1beb772 WireDecoder: Add commented-out read stream dumping. 2015-11-02 22:06:55 -08:00
Peter Johnson
d850b2fd76 Gradle build: rebuild on changes to header files in src. 2015-11-02 22:04:23 -08:00
Peter Johnson
9f5fe63aaa Reuse dead connection slots.
This fixes a memory leak on multiple disconnect/reconnect of the same client.
2015-11-01 22:48:11 -08:00
Peter Johnson
03ee425e5f Add additional debug messages. 2015-11-01 22:48:11 -08:00
Peter Johnson
9200b7c78c Add extern "C" to JNI definitions to catch mismatches. 2015-11-01 07:44:43 -08:00
Fredric Silberberg
b793810e4a Fixes for mac builds
Change-Id: I66dafd5e6d5ff10e7fb98cf718bb6f9343d03184
2015-10-31 18:49:11 -04:00
Fredric Silberberg
9df5f5e27a When running on jenkins, the base name of produced archives becomes the project name. This fixes that to be the correct name.
Change-Id: Ie5a25bf9eabdb8fb1a1ee14d56e2e7badc634afc
2015-10-31 14:28:54 -04:00
Peter Johnson
7fbd0e34d3 Merge pull request #27 from 333fred/master
Gradle Update
2015-10-31 10:46:43 -07:00
Fredric Silberberg
77cf3adf64 This commit updates the gradle files to be cleaner. It also builds for the
current platform by default, and only builds tests when building for the
current platform. Mac builds and VS2015 builds are fixed.

The other big change in this update is the introduction of Debug and
Release builds. Debug builds are built with -O0 and -g. Release builds are
built with -O2 and -g. For GCC-based builds, the resulting shared object
is copied, stripped of debug information, and a debug link is set up to
the copied shared object. This allows the release build to clock in at
around 600 KB. On Windows, the debug info is already stored in a separate
PDB file, so this copy and strip is not necessary.

ntcore is being separated out from the rest of allwpilib. All other
builds will consume a published maven dependency from this project.
There are 4 possible publishing targets now: release, stable, beta, and
development. These are specified on the command line via -Prepo=<repo
name>.

Change-Id: Ie8cb21f910953e09b80a5192317033eb0866cb70
2015-10-31 13:31:01 -04:00
Peter Johnson
dd0e3e4abb Implement join with timeout (and detach).
Under certain situations (notably JNI shutdown), it's possible to get
deadlock when using thread join().  To avoid this, implement a timeout.
Normally we try to simply join the thread, but if it times out, we
detach the thread instead.
2015-10-09 23:50:01 -07:00
Peter Johnson
d77b3d788e Dispatcher: Remove unused member variable. 2015-10-09 22:52:26 -07:00
Peter Johnson
dff6e89b4b Notify local listeners on preferences load.
Also notify local listeners even when disconnected.
2015-10-08 00:04:38 -07:00
Peter Johnson
57b00d3b38 Fix StorageTest unit test on MSVC 2015.
Per https://msdn.microsoft.com/en-us/library/bb531344.aspx, "Exponent
formatting", MSVC 2015 fixed the %g format to match the C standard's
requirement of printing a 2-digit exponent if only 2 digits are
required.
2015-10-05 20:22:36 -07:00
Peter Johnson
898952a2df Merge pull request #26 from Beachbot330/master
fix javadoc warnings/errors
2015-10-04 08:41:08 -07:00
Joe Ross
202cb8bb1f fix javadoc warnings/errors 2015-10-03 19:20:26 -07:00
Peter Johnson
4592c90e34 Add protocol specification documentation.
These have been converted to asciidoc (asciidoctor variant) from the original
Google Docs documents.
2015-09-27 23:22:08 -07:00
Peter Johnson
734e9a4461 Fix NT_GetEntryInfo implementation signature to match header.
Fixes #25.
2015-09-27 21:08:15 -07:00
Peter Johnson
90959defd9 Provide more extensive listener features.
This enables listeners to be notified of not only value updates, but also flag
changes and deletions by using a bitmask to specify what notifications are
desired.  The old API (which only provided a new/not new) flag is still
supported.  This also subsumes the feature to listen to local changes (that's
one of the bitmask options).
2015-09-27 01:55:32 -07:00
Peter Johnson
51064f5e75 Fix client initial flags setting.
Before the server has assigned the id, the client doesn't generate flags
update messages.  This behavior is correct, but the client must then send
the appropriate flags update message when the id is finally assigned by
the server.
2015-09-27 01:55:32 -07:00
Peter Johnson
3e8afc14b0 Java NetworkTable: perform string comparion correctly. 2015-09-27 01:55:32 -07:00
Peter Johnson
424bf51a7b Implement local notification.
The default behavior is to only notify remote changes, but for some
applications (e.g. GUI's) it's advantageous to know about local
changes as well.

This is (slightly) optimized in that local changes only result in
additional resources being consumed if (any) local listeners have been
created.
2015-09-23 00:56:08 -07:00
Fredric Silberberg
75358e6c45 This adds a maven publish routine for ntcore to replace the networktables
java routine.

Change-Id: Ie4665f9f47c11cb66b6f255d5fe24e91c186a88e
2015-09-21 15:23:44 -04:00
Peter Johnson
e2879b7bf2 Fix JNI embed location on Windows.
Make it Windows version agnostic and fix the amd64 runtime / x86-64 build
architecture naming difference.

See artf4198.
2015-09-20 10:56:06 -07:00
Peter Johnson (294)
b80d2f6659 Merge "Updated gradle version." 2015-09-19 12:32:53 -07:00
Peter Johnson
4c83259acb C++ NetworkTable: Provide AddSubTableListener().
This matches the implementation provided by Java NetworkTable, with the
exception that the subtable is not provided (because it's not a value).
The listener still can get access to the subtable by calling
source->getSubTable(key).
2015-09-19 12:25:21 -07:00
Fredric Silberberg
9c50e9f964 Updated gradle version.
Change-Id: If233899c69ad3036b65328334d3d318b5b860dad
2015-09-19 15:06:17 -04:00
Peter Johnson
a3effbfb9f Java NetworkTable: Don't use ipAddress when starting server.
This matches the C++ behavior.  Using the IP address here is confusing to
users because it's actually the listen address.
2015-09-19 11:45:07 -07:00
Peter Johnson
90ce262bb3 C++ NetworkTable: Provide SetPort() method.
This was previously only available in Java.
2015-09-19 11:44:14 -07:00
Peter Johnson
23448c8277 NetworkTable interface: Provide method to set persistent filename. 2015-09-19 11:40:31 -07:00
Peter Johnson
d9fa086ec0 Include the ARM JDK JNI headers.
These are GPL-licensed.  This removes the dependency on the ARM JDK being
installed.

Fixes #24.
2015-09-19 08:30:40 -07:00
Peter Johnson
3b91fac192 ntcore.def: Add JNI getEntries function. 2015-09-17 21:39:42 -07:00
Peter Johnson
e42f9b0603 Add EntryInfo class (missed in previous commit). 2015-09-16 00:53:14 -07:00
Peter Johnson
c5d456f3a6 Add ITable/NetworkTable GetKeys and GetSubTables accessors. 2015-09-16 00:51:05 -07:00
Peter Johnson
6cbc219427 Add ITable/NetworkTable accessors for new features. 2015-09-15 23:43:42 -07:00
Peter Johnson
4b06e74a14 Java: Return boolean from put functions.
The put functions return false if the key already exists with a different type.
2015-09-15 22:23:34 -07:00
Peter Johnson
42f973ebe0 Java: Don't raise illegal state exceptions unless really necessary.
- Ignore no-op calls to setServerMode() / setClientMode().
- Duplicate calls to initialize() act as a restart.
- shutdown() silently does nothing if not running.
2015-09-15 22:03:11 -07:00
Peter Johnson
84e7d5906c Java: Use Global instead of WeakGlobal for callbacks.
For some reason, weak globals don't work as they (unexpectedly) are
getting destroyed even though we save the callback in a map at the Java
level.
2015-09-15 21:32:51 -07:00
Peter Johnson
51eb96903c Java: Improve robustness against JVM crashes on exit.
The JVM doesn't always do a good job of telling JNI modules that the JVM
is going away, which results in a crash in the JavaGlobal and/or
JavaWeakGlobal destructors as they try to delete the associated references
after the JVM has already gone away.

To protect against this, the Notifier now has a static variable that's set
when the Notifier instance (a singleton) is destroyed.  This is used by
JavaGlobal and JavaWeakGlobal to detect when a process exit is in process.
2015-09-14 22:00:22 -07:00
Peter Johnson
6d8e796932 Disable logging on static instance destruction.
This avoids possible deadlocks on exit when a logger callback exists.
2015-09-12 21:44:51 -07:00
Peter Johnson
f7e603c7db Add DEBUG4 message for messages received during client handshake. 2015-09-11 19:19:15 -07:00
Peter Johnson
30ad381b6c Notify on entries created/modified during handshake. 2015-09-11 19:18:50 -07:00
Peter Johnson
5181c4e5be Java: Don't free locals after detaching thread.
We use a smart pointer to hold local java variables, and it was getting
destructed after DetachCurrentThread() was called, causing a JVM crash.
2015-09-11 16:28:58 -07:00
Peter Johnson
a2ec638db8 Java: Use empty string as default IP rather than null.
Using null can crash the JVM if initialize() is called before setIPAddress.
2015-09-11 12:06:22 -07:00
Peter Johnson
953a2ce807 Implement keep-alives. 2015-09-08 23:17:11 -07:00
Peter Johnson
e1efb7364e Don't allow update intervals slower than 1 second. 2015-09-06 11:41:35 -07:00
Peter Johnson
123ba9c670 Use SmallVector instead of malloc buffers for WireEncoder. 2015-09-06 11:00:44 -07:00
Peter Johnson
d3e63e0078 Change cmake to output same jar name (ntcore) as gradle. 2015-09-05 23:19:22 -07:00
Fredric Silberberg
21e21d3b8b Fixed the Windows build. Also added ensuring that vs2012 is installed if
vs2015 is detecting, and printing an error that actually makes sense if it
is not. Finally, added a .gitreview file, so that git-review will be able
to autodetect the host and project for ntcore automatically.

Change-Id: I3cb9910d03d4742619770c91c06e3d5d1ee0f031
2015-09-06 01:12:19 -04:00
Peter Johnson
702b6de734 Java: Fix crash on JVM exit.
Fixes #22.
2015-09-05 11:05:02 -07:00
Peter Johnson
6233b3477b Java: Fix fallback on external library. 2015-09-05 10:57:37 -07:00
Peter Johnson
07942bf422 Notifier: fix Stop() so it actually notifies the thread. 2015-09-05 10:55:24 -07:00
Peter Johnson
66f9f73cb3 Add gradle wrapper. 2015-09-03 21:31:31 -07:00
Peter Johnson
2dd9eafa4f Enable "make test" on cmake. 2015-09-03 21:31:31 -07:00
Fredric Silberberg
b1783cc1db Integrate googletest and googlemock. 2015-09-03 21:31:26 -07:00
Peter Johnson
c5c615b7d3 Add sublime text files to .gitignore. 2015-09-03 21:13:33 -07:00
Peter Johnson
897420a5f4 Reindent build.gradle. 2015-09-03 20:44:32 -07:00
Peter Johnson
550b04cff8 Merge pull request #21 from ThadHouse/master
Documents the C API
2015-08-31 21:05:26 -07:00
Thad House
46e0ac1258 Added documentation to the C interface
Client/Server functions.
2015-08-31 19:12:45 -07:00
Thad House
22d984a6bd Comments the interop functions in the C interface.
Properly space the comments.
2015-08-31 18:56:05 -07:00
Peter Johnson
8d6f96adb9 Add NT_FreeCharArray. 2015-08-29 08:58:53 -07:00
Peter Johnson
1f431754a9 Simplify C entry point function names.
Rename GetEntry*FromValue to GetValue*.
Rename a couple of NTStringArray to simply StringArray.
2015-08-29 08:48:36 -07:00
Peter Johnson
40093df91f Remove NT_AllocateNTString from ntcore.def. 2015-08-29 08:43:57 -07:00
Peter Johnson
f3bfee149c Change NT_GetEntry*FromValue to return copies.
Previously they returned references to the strings/arrays within the passed
NT_Value, which is different from the GetEntry* functions and risks
double-frees.
2015-08-29 08:39:40 -07:00
Peter Johnson
9b9b41f40e Reformat to match coding style. No functional changes. 2015-08-29 08:30:40 -07:00
Peter Johnson
a451fd3f04 Make string/raw getters/setters use char*+len instead of NT_String.
Also remove NT_AllocateString.

This avoids passing and returning struct NT_String by value.

Also make GetEntry*FromValue take a const NT_Value*.
2015-08-29 08:25:48 -07:00
Peter Johnson
7565207242 StartClient(): Make a local copy of server_name.
Previously we just held onto the const char* provided by the user.
This does not work in cases such as Java which provide a temporary
string.
2015-08-29 00:07:10 -07:00
Peter Johnson
e516200e09 Java: Add shutdown method to NetworkTable. 2015-08-28 23:57:37 -07:00
Peter Johnson
5beaf45773 TCPConnector: Add more info to debug messages. 2015-08-28 23:57:18 -07:00
Peter Johnson
1ca0157768 Java: Add backwards compat shims for array types. 2015-08-28 21:09:46 -07:00
Peter Johnson
dbe4168d8d Java: allow both object arrays and native arrays.
This allows easier use of things like ArrayList<Double>.
2015-08-28 20:48:29 -07:00
Peter Johnson
969916851c Need to return nullptr, not false. 2015-08-28 17:17:20 -07:00
Peter Johnson
b00b4cb185 Avoid warnings by using sprintf_s on MSVC.
Also use std::snprintf on other platforms.
2015-08-28 14:16:49 -07:00
Peter Johnson
2b9e7c6af1 Silence MSVC warnings regarding bool conversions. 2015-08-28 14:07:51 -07:00
Peter Johnson
0d9aaa86c6 Silence unused variable warning. 2015-08-28 14:07:18 -07:00
Peter Johnson
28b613d60c Silence MSVC winsock deprecated warnings. 2015-08-28 14:06:46 -07:00
Peter Johnson
b971c741d7 Fix JNI for Windows and implement JNI getValue functions. 2015-08-28 13:52:16 -07:00
Peter Johnson
ecadb117da Merge pull request #5 from ThadHouse/master
Add Getters, Setters, and Allocators to the C interface
2015-08-28 13:40:21 -07:00
Thad House
4b7dfc0254 Implements individual getters and setters for the C interface.
Starting to add Getters, Setters, and Allocators to the C interface

Because of the union in the NT_Value structure, some languages would
have a difficult time with the interop. This commit adds individual
getters and setters to the C interface to make interop easier.

In addition, some languages cannot allocate native memory in the same
heap that the C code would use. This adds allocation functions to make
sure that all our memory is allocated and can be freed properly from the
same heap.

The reason the getters are not individual get functions are because that
would require the calling code to first get the type, and then call the
specific getter for that type. Doing combined get functions causes
interop code to only have to cross interop boundaries once to get the
value instead of twice, for a light performance increase. However, this
could be changed without much work.

NT getters and setters round 2

Fixed some of the code based on the comments in the pull request.

Creates individual getters.

Should work better then 1 single getter.

Fixes end of file new line, and fixes function nameing

SetNTValue... made less sense then SetEntry... Matches the getter
naming.

Fixed methods to be less leaky.

Fixed Formatting, Fixed return values on Bool and Double. Added Contains Key

Changed ContainsKey to GetType. Also renamed Arr to Array

In public functions, I think I like Array better then Arr. Also, make
the getters that use value check for a null value, which should prevent
segfaults.

Fixes C++ Type functions to work properly

NTString Set functions still do not work properly though. I need some
help on there. Error message is in the pull request.

Changes Get functions to return status and have pointer to data passed in to be set.

Fixes NT_Strings

Added  new functions to ntcore.def

Fixes NT_PostRpcResponse in the def file

Was NT_PostRpcRepsonse, which was failing the build.

Removed unused parameter from setters

Since we were forcing exports in the cmake build, they were seen in
windows, but since the header didnt match the implementation they
wouldn't export on linux. So fixed that. Linux builds now work properly,
tested on a physical RIO.

Added a DisposeEntryInfoArray method.

There was no way to free the array returned from GetEntryInfo

Adds NT_DisposeEntryInfoArray to the def file.

Implement automatic persistent saves.

Also loads persistent file on server start.

Update TODO.

raw_istream and kin: a few cleanups.

anchor() doesn't seem to change compiler output in current compilers, so
remove it.  Use default where appropriate rather than empty bodies.

Clean up trailing whitespace.

Dispatcher: Move several fixed initial values to header.

Uninline constructors to reduce GetInstance() inlined code size.

Logger: Move m_min_level init to header.

Replaced time.h with std::chrono

This implementation returns the same values as the previous one on both a Linux machine and the roboRIO.

Value: Use variant of enable_if to fix MakeString/MakeRaw in GCC.

Tested on GCC 4.8, GCC 4.9, and clang 3.6.

Don't dispose in ConvertToC for NT_String and NT_Value.

Fixes #16.

Fixed Gradle build to actually export proper functions

Finishes fixes in pull request

Changes array setters to be const

To build RPC, needed a way to allocate a Char Array

Since after the callback, the C code explicitly frees, a way to make
sure to allocate the callback return string from the same heap was
needed.

Adds const to NTString setters.

Removes Const from NTString setters
2015-08-28 13:37:49 -07:00
Peter Johnson
a990859db6 Initial commit of Java wrappers.
The JNI bindings are built directly into the shared library.  In the gradle
build, all built shared libraries are embedded into the generated jar.

Java bindings may be disabled via -DWITHOUT_JAVA (cmake) or -PskipJava=true
(gradle).

TODO:
- getEntryInfo() and RPC are not yet implemented.
- The cmake build doesn't integrate the built objects into the jar.
- The Java client and server tests are not built (but have been manually
  tested).

This has not yet been tested on Windows.
2015-08-28 12:43:49 -07:00
Peter Johnson
9c576b10d0 NetworkTable: Don't prefix path with / if key is empty.
This avoids NetworkTable("").putValue("foo") resulting in key "//foo".
2015-08-28 12:24:33 -07:00
Peter Johnson
b28807d791 Client and server tests: Prefix keys for compatibility.
The NetworkTable interface prefixes with /, so this makes simple
interoperability testing easier.
2015-08-28 12:23:41 -07:00
Peter Johnson
b488cdd6ff Support immediate notify of connection listener.
Also only perform immediate notification to the callback actually
requesting the notification, not all existing callbacks.

Offset returned uids by 1 so uid=0 can be used to indicate immediate
notification.
2015-08-28 00:13:56 -07:00
Peter Johnson
302cc064c6 ConnectionListener: Use bool instead of int for connected parameter. 2015-08-27 23:48:40 -07:00
Peter Johnson
6e4d7ca933 NetworkTable: Protect listeners with mutex. 2015-08-27 23:39:52 -07:00
Peter Johnson
6c8a5935c9 NetworkTable: Fix table and key listener behavior.
The implemented behavior didn't match the old networktables implementation.
2015-08-27 22:22:51 -07:00
Peter Johnson
86445b6670 Import llvm::SmallPtrSet. 2015-08-27 22:16:56 -07:00
Peter Johnson
330ba39939 Unbreak Unix build. 2015-08-24 21:45:41 -07:00
Peter Johnson
0f4eecebe6 Fix StorageTest on MSVC.
MSVC outputs %g with a 3-digit instead of a 2-digit exponent.
2015-08-24 21:30:07 -07:00
Peter Johnson
a3dbe9a800 Fix Windows client.
Windows returns WSAEWOULDBLOCK on a connect() attempt on a nonblocking socket.

Also wrap socket error handling so errors are correctly reported on Windows.

Fixes #19.
2015-08-24 21:21:13 -07:00
Peter Johnson
822dc45834 Close persistent file before attempting to rename.
Windows requires the file be closed in order to rename it.
2015-08-24 20:38:33 -07:00
Peter Johnson
b8a99690b6 Fix non-unit tests build on Windows. 2015-08-24 20:22:41 -07:00
Peter Johnson
48b1120c31 Add some basic non-unit tests. 2015-08-24 20:07:36 -07:00
Peter Johnson
c27a1cec48 Unbreak StorageTest. 2015-08-22 23:26:22 -07:00
Peter Johnson
9d4a66a400 Merge pull request #17 from 333fred/master
Fixed Gradle build to actually export proper functions

Fixes #13.
2015-08-23 00:15:10 -05:00
Fredric Silberberg
c846dff524 Fixed Gradle build to actually export proper functions 2015-08-23 01:10:39 -04:00
Peter Johnson
29f73cb5c1 Don't dispose in ConvertToC for NT_String and NT_Value.
Fixes #16.
2015-08-22 19:31:53 -07:00
Peter Johnson
a8836b7665 Value: Use variant of enable_if to fix MakeString/MakeRaw in GCC.
Tested on GCC 4.8, GCC 4.9, and clang 3.6.
2015-08-22 14:01:33 -07:00
Peter Johnson
96bf5c24b5 Merge pull request #4 from calcmogul/master
Replaced time.h with std::chrono
2015-08-20 22:40:59 -07:00
Tyler Veness
ab9de550d9 Replaced time.h with std::chrono
This implementation returns the same values as the previous one on both a Linux machine and the roboRIO.
2015-08-20 16:04:55 -07:00
Peter Johnson
9cb9c3beb0 Logger: Move m_min_level init to header. 2015-08-19 22:04:31 -07:00
Peter Johnson
2d1bc2f4c7 Uninline constructors to reduce GetInstance() inlined code size. 2015-08-19 21:49:18 -07:00
Peter Johnson
c6bed1f464 Dispatcher: Move several fixed initial values to header. 2015-08-19 21:16:44 -07:00
Peter Johnson
c41341c7e3 Clean up trailing whitespace. 2015-08-19 20:41:59 -07:00
Peter Johnson
f0e31487f0 raw_istream and kin: a few cleanups.
anchor() doesn't seem to change compiler output in current compilers, so
remove it.  Use default where appropriate rather than empty bodies.
2015-08-19 20:37:27 -07:00
Peter Johnson
a34143ae75 Update TODO. 2015-08-19 19:18:09 -07:00
Peter Johnson
ca9ce0f3a3 Implement automatic persistent saves.
Also loads persistent file on server start.
2015-08-19 19:18:09 -07:00
Peter Johnson
a5ccafd924 Merge pull request #3 from 333fred/gradle-changes
Gradle changes
2015-08-18 14:17:53 -07:00
Fredric Silberberg
9458da0454 Added building for arm, x86, and x64 with Gradle. This only builds ntcore currently, I'm working getting Google Test to work. 2015-08-15 21:46:21 -07:00
Peter Johnson
80247e98e5 Use relative include paths in tcpsockets. 2015-08-13 23:07:45 -07:00
Peter Johnson
293d005432 Turn on logging in unit tests. 2015-08-13 22:14:17 -07:00
Peter Johnson
a395e3577f Notifier: Fix condition variable race. 2015-08-13 21:35:33 -07:00
Peter Johnson
8d7cdeabbf Implement remote procedure calls. 2015-08-13 21:32:16 -07:00
Peter Johnson
e199e3571b Revert "Don't error on strict-aliasing warnings."
This reverts commit 492463411d.
2015-08-12 17:17:19 -07:00
Peter Johnson
e9618df1b5 Avoid pointer aliasing for double/bits conversions.
Instead use the llvm MathExtras.h functions for this, which use union
aliasing.
2015-08-12 17:15:10 -07:00
Peter Johnson
c34ba968f1 Message: Remove ArrayRef-taking ExecuteRpc/RpcResponse. 2015-08-12 17:11:09 -07:00
Peter Johnson
0cbcfbc3f0 Import llvm::DenseMap.
Bring in (most of) MathExtras.h as well, as it's shared by SmallVector and
DenseMap.
2015-08-12 17:08:45 -07:00
Peter Johnson
492463411d Don't error on strict-aliasing warnings.
These warnings occur in release mode for the double-to-uint64 cast used
for transmitting double values.
2015-08-04 20:38:31 -07:00
Peter Johnson
cd53feb193 Log DEBUG() macros: avoid spurious warnings in release builds. 2015-08-04 20:36:39 -07:00
Peter Johnson
00feb67064 Only use enable_if template on Windows.
This isn't required and doesn't compile on older GCC versions.
2015-08-04 19:59:45 -07:00
Peter Johnson
b3eed38187 Get build working on Windows (MSVC 2013).
Windows needs static libraries to build the tests as gtest/gmock are built statically.
2015-08-04 01:29:06 -07:00
Peter Johnson
f683a5c63c Export C API functions on Win32. 2015-08-04 00:15:00 -07:00
Peter Johnson
7d409f071e Add win32 tcpsockets implementation. 2015-08-04 00:01:13 -07:00
Peter Johnson
4146db6fc8 Visual Studio 2013 compilation fixes.
- Missing header file callouts in some cases (library deltas)
- Lack of support for auto parameters in lambdas
- Defining of ERROR by windows.h
- Dispatcher::Connection needs a move constructor (default not generated)
- Need explicit enable_if on std::string move template in Value to avoid trying to move const char[] (string literal)
- Compile flags
2015-08-03 01:27:02 -07:00
Peter Johnson
a86f65db1e Dispatcher: Implement transmit combining.
This handles most of the major cases, but not a loop of delete/assign, which
should be uncommon anyway.
2015-08-02 23:21:23 -07:00
Peter Johnson
53a0531def Storage::ProcessIncoming(): Don't override parameter with local. 2015-08-02 23:20:42 -07:00
Peter Johnson
7db00575c9 NetworkConnection: Add a bit more debugging. 2015-08-02 22:23:14 -07:00
Peter Johnson
5b65bfb64d Storage: Fix comparison for client update-on-assign. 2015-08-02 22:18:46 -07:00
Peter Johnson
3b0eb56cf6 Update TODO. 2015-08-02 21:47:56 -07:00
Peter Johnson
e9073a3cc0 Implement notifiers.
The notifier thread is lazily started when the first notifier is added.
This avoids the extra thread/processing overhead when notifiers are not used.
2015-08-02 21:47:01 -07:00
Peter Johnson
538a19fd47 Implement GetConnections(). 2015-08-02 10:47:05 -07:00
Peter Johnson
84ff80710c Refactor TCP-specific pieces of Dispatcher. 2015-08-02 00:33:41 -07:00
Peter Johnson
0dcaf56ed1 Add NetworkAcceptor and NetworkStream interfaces.
These allow mocking of TCPAcceptor and TCPStream respectively.
2015-08-02 00:06:27 -07:00
Peter Johnson
6703968f73 Dispatcher: Fix shutdown order race.
We need to wait until after the dispatch and client/server threads have
been stopped before closing connections, as these threads can add connections.
2015-08-01 23:37:13 -07:00
Peter Johnson
8ec65dbfc8 Use unique_ptr instead of shared_ptr for m_server_acceptor. 2015-08-01 20:29:16 -07:00
Peter Johnson
4670ef6ec5 Refactor StorageTest base class. 2015-08-01 16:33:52 -07:00
Peter Johnson
35e6400174 Storage: Add vector include. 2015-08-01 16:33:39 -07:00
Peter Johnson
67de7af7b2 Storage: Use unique_ptr instead of shared_ptr for Entry. 2015-08-01 11:47:35 -07:00
Peter Johnson
3b207ad2c3 StorageTest: Fix string comparison for Warn().
Previously this was comparing pointers rather than the string contents.
2015-08-01 11:45:41 -07:00
Peter Johnson
b5274a495e Dispatcher: Don't call Storage::GetInstance() internally.
This makes it difficult to test.  Instead, store reference as member variable,
and populate it at constuction (with an alternate constructor available for
test purposes).
2015-08-01 11:15:04 -07:00
Peter Johnson
11508b77d1 Ensure initial synchronization is atomic. 2015-07-31 23:56:06 -07:00
Peter Johnson
0a10778697 NetworkConnection: Kill write thread when read dies and vice-versa. 2015-07-31 23:40:16 -07:00
Peter Johnson
ecbf76e94b Update tcpsockets classes to use log framework. 2015-07-31 23:34:54 -07:00
Peter Johnson
6c0103639c Make LOG() usable from other namespaces. 2015-07-31 23:33:41 -07:00
Peter Johnson
c2eb4a766e Dispatcher: Provide some INFO-level connection messages. 2015-07-31 23:26:38 -07:00
Peter Johnson
06e8d835dd Provide ostream output for StringRef. 2015-07-31 23:20:59 -07:00
Peter Johnson
3a71acec52 Automatically reconnect client.
Also clean up some condition variable handling to make it more robust.
2015-07-31 23:14:26 -07:00
Peter Johnson
a9af4589ac Don't send empty message lists from dispatch.
This terminates the write thread.
2015-07-31 22:49:43 -07:00
Peter Johnson
4356e313ec Add logging framework.
DEBUG messages are completely optimized out if NDEBUG is defined.
2015-07-31 22:41:26 -07:00
Peter Johnson
afcfdb13a0 Clean up CMakeLists.txt a bit. 2015-07-31 20:57:56 -07:00
Peter Johnson
3a570add4e Build as a shared rather than static library. 2015-07-31 20:54:25 -07:00
Peter Johnson
ead125555c Implement client/server handshaking. 2015-07-31 20:32:52 -07:00
Peter Johnson
98ad6d1b43 Message: Handle receiving Server Hello. 2015-07-31 20:14:15 -07:00
Peter Johnson
978cdadda0 Storage::GetEntryType(): Check for null entry. 2015-07-31 14:16:13 -07:00
Peter Johnson
cde7782c21 Make StorageEntry a struct and move into Storage class. 2015-07-31 13:48:33 -07:00
Peter Johnson
138ebf5b4d Storage: generate messages rather than intermediate updates. 2015-07-31 13:21:19 -07:00
Peter Johnson
a127bca0e4 Push down null check for m_queue_outgoing. 2015-07-30 00:06:50 -07:00
Peter Johnson
83be99e78c Immediately process incoming messages.
This required moving message processing into the Storage class.
2015-07-29 23:45:04 -07:00
Peter Johnson
5b5e3ae6aa Dispatcher: Start implementing processing of incoming messages. 2015-07-29 20:33:26 -07:00
Peter Johnson
f6576b18f7 Storage: Add more Dispatcher accessors. 2015-07-29 20:33:13 -07:00
Peter Johnson
9a621e9272 Various NetworkConnection improvements.
- Keep connection state.
- Store remote id
- Getter for proto_rev
- Cleanup on Stop()
- Cleaner termination of write thread.
2015-07-29 20:31:59 -07:00
Peter Johnson
c01f2977ac StorageEntry: Make value() const. 2015-07-28 22:29:58 -07:00
Peter Johnson
683c53babc Message::str(): Return StringRef. 2015-07-28 22:07:02 -07:00
Peter Johnson
5823e3c780 Storage: Add CreateEntry function for Dispatcher use. 2015-07-28 22:06:42 -07:00
Peter Johnson
a0d30ffef1 Storage: Use StringMap instead of ConcurrentQueue for updates.
Updates are merged or themselves updated as user code changes.  This avoids
the need for the dispatcher to do this and also avoids the need for disabling
updates when the dispatcher isn't running, because there's no risk of memory
usage piling up.
2015-07-26 20:41:48 -07:00
Peter Johnson
fb1b82e239 StorageEntry: Also store copy of name here.
This wastes a bit of space but is necessary for assign message generation.
2015-07-26 10:28:20 -07:00
Peter Johnson
3bc5699ba1 Storage: Provide accessor for global mutex. 2015-07-26 09:42:14 -07:00
Peter Johnson
18659257d3 Storage: Make setters globally atomic.
Previously, setters were locally but not globally atomic because they
used GetEntry() (globally atomic) in conjunction with locally atomic
gets/sets to the StorageEntry.  To support synchronizing network handshakes
they need to be globally atomic.

GetEntry() has been removed due to this issue, so a helper was added to
StorageTest instead.
2015-07-26 09:27:23 -07:00
Peter Johnson
3c7cb363ba NetworkConnection: Prefer emplace to push. 2015-07-25 10:47:53 -07:00
Peter Johnson
787d39851b Update gradle build to match cmake build. 2015-07-25 01:33:15 -07:00
Peter Johnson
ae070aca70 Value: Add type check functions. 2015-07-24 22:11:57 -07:00
Peter Johnson
63dd895e6d Pass CMAKE_TOOLCHAIN_FILE down to external project (gmock). 2015-07-23 22:31:51 -07:00
Peter Johnson
507b083e77 WireEncoderTest.cpp: Don't test compiler truncation. 2015-07-23 22:06:57 -07:00
Peter Johnson
13bc05d9ec leb128Test: Fix incorrectly sized constants. 2015-07-23 22:04:51 -07:00
Peter Johnson
3f24b86875 ITable: Add Persist function to make a key persistent. 2015-07-23 21:53:33 -07:00
Peter Johnson
1368f0ec8f NetworkTable: Use networktables.ini as persistence filename. 2015-07-23 21:47:54 -07:00
Peter Johnson
196fcf791b ITable: Const'ify getter functions. 2015-07-23 21:46:30 -07:00
Peter Johnson
6bccf528d7 ITableListener.h: Forward declare ITable. 2015-07-23 21:41:30 -07:00
Peter Johnson
1fc03803cd ITableListener::ValueChanged: Don't make key const. 2015-07-23 21:40:24 -07:00
Peter Johnson
8fa0e6c914 Add shims for old NetworkTable interface.
This provides classes for virtual subtables using path delimiters within
the global NetworkTable namespace.
2015-07-23 01:23:09 -07:00
Peter Johnson
6f940bcaaf Add immediate_notify and is_new to entry listener.
On the callback function, is_new indicates the value is newly added.

On adding a callback function, immediate_notify indicates the callback
should be called once (with is_new=true) for each matching entry that
already exists.
2015-07-23 01:02:53 -07:00
Peter Johnson
79f732f239 Import llvm::SmallString and dependencies.
Update StringRef and StringExtras with SmallVector functions.
2015-07-22 22:29:46 -07:00
Peter Johnson
593bc28446 Move StringMap.h and StringExtras.h to public includes.
While these aren't required by the public interface, they are generally
useful classes for users of the library.
2015-07-22 22:10:56 -07:00
Peter Johnson
9c204533e8 Value: Disambiguate std::string&& and StringRef.
Making the former a template causes the compiler to prefer the latter
when given a bare C string.
2015-07-22 22:08:13 -07:00
Peter Johnson
4c14f7823a ntcore_cpp.h: Comment cleanup. 2015-07-22 21:41:25 -07:00
Peter Johnson
4aa2d65bba Storage: Use std::forward and emplace for updates. 2015-07-21 22:43:44 -07:00
Peter Johnson
bb5848a033 ConcurrentQueue: Add emplace function.
Also use std::forward for rvalue push.
2015-07-21 22:43:02 -07:00
Peter Johnson
9f728b850e Add MSVC specific compiler flags. 2015-07-21 21:14:22 -07:00
Peter Johnson
b4c65dc210 Make global instance init thread-safe.
Use local statics except for Visual C++ < 2015.
2015-07-20 23:36:22 -07:00
Peter Johnson
5df62ac172 Storage: Disable use of update queue by default.
This ensures we don't "leak" memory for local use when the dispatch thread
is not running.
2015-07-20 22:24:47 -07:00
Peter Johnson
0979c1c9ca Storage, NetworkConnection: Don't in-place construct atomics.
Visual C++ 2013 doesn't support this.
2015-07-20 20:52:26 -07:00
Peter Johnson
8bbe5f9fdb ArrayRef: Add portability checks for constexpr. 2015-07-20 20:49:49 -07:00
Peter Johnson
3cd3d1691e Message: Use #define instead of constexpr. 2015-07-20 20:34:19 -07:00
Peter Johnson
6b2fb02bed Dispatcher: Don't in-place construct atomics.
Visual C++ 2013 doesn't support this.
2015-07-20 20:21:37 -07:00
Peter Johnson
8938a19810 Dispatcher: Avoid warning by using for(;;) instead of while(true). 2015-07-20 20:20:01 -07:00
Peter Johnson
158ae61811 Dispatcher::SetUpdateRate(): Explicitly convert to int. 2015-07-20 20:19:01 -07:00
Peter Johnson
98d45777c6 Remove unnecessary llvm qualifier. 2015-07-20 00:19:20 -07:00
Peter Johnson
d059022071 Add logging to TODO. 2015-07-19 23:52:12 -07:00
Peter Johnson
c9260ea785 Change GetEntryTypeFunc to std::function.
Also implement it as a member function of Dispatcher.
2015-07-19 23:17:14 -07:00
Peter Johnson
c9ca2f902e Add TODO list. 2015-07-19 22:56:48 -07:00
Peter Johnson
29691e0ac5 StorageTest: Add LoadPersistent and SavePersistent coverage. 2015-07-19 22:45:20 -07:00
Peter Johnson
a3fcce891f LoadPersistent: Fix various bugs. 2015-07-19 22:44:34 -07:00
Peter Johnson
8db016c223 SavePersistent: Sort in name order, fix list commas. 2015-07-19 21:10:20 -07:00
Peter Johnson
b0802f3e26 StorageTest: Add fixture classes, add GetEntryInfo test. 2015-07-19 19:43:27 -07:00
Peter Johnson
e4731a4e4e Storage::GetEntryInfo: Actually filter on types. 2015-07-19 19:42:13 -07:00
Peter Johnson
67ae9e1ba7 Add initial set of unit tests for Storage. 2015-07-19 18:11:36 -07:00
Peter Johnson
d6afbc56c4 Storage: Delete functions now delete from map.
This is ok due to the map storing shared_ptr.
2015-07-19 18:10:26 -07:00
Peter Johnson
ffb54872c0 Storage::SetEntryFlags(): Fix deadlock, check for empty name. 2015-07-19 17:50:31 -07:00
Peter Johnson
ead6b4960f Storage: Use make_shared instead of reset. 2015-07-19 16:46:59 -07:00
Peter Johnson
21b7acc397 Storage: Make testable, make EntriesMap typedef private. 2015-07-19 16:36:30 -07:00
Peter Johnson
173111c64c ConcurrentQueue: Make mutex mutable. 2015-07-19 16:36:08 -07:00
Peter Johnson
cf18355fe2 Unit tests: Prefer constructor to SetUp() in fixtures. 2015-07-19 16:30:04 -07:00
Peter Johnson
1cc148848b StartServer: Take persist_filename as a StringRef. 2015-07-19 16:11:56 -07:00
Peter Johnson
ec54904347 Tighten up C++ API implementation a bit. 2015-07-19 16:09:59 -07:00
Peter Johnson
0a18d2e57b Storage: Make individual entries thread safe.
Also use shared_ptr to refer to entries rather than names.
2015-07-19 16:02:21 -07:00
Peter Johnson
c08e2ed8fc ConcurrentQueue: Add size() function. 2015-07-18 01:32:21 -07:00
Peter Johnson
2437f06c7f Implement majority of Storage functionality.
It's also now thread-safe.
2015-07-18 01:29:51 -07:00
Peter Johnson
9b7e265762 Continue implementing client. 2015-07-18 01:29:24 -07:00
Peter Johnson
c4a7f6ec9b SavePersistent: Safely save through temp file.
Also change SavePersistent and LoadPersistent to take StringRef.
2015-07-18 00:39:08 -07:00
Peter Johnson
d05656b716 StorageEntry: Make data public, remove accessors.
Also add id and seq_num fields.
2015-07-17 23:41:25 -07:00
Peter Johnson
04789d9ae4 SequenceNumber: Add default constructor. 2015-07-17 23:41:05 -07:00
Peter Johnson
77acf1f35b Implement Flush() API. 2015-07-17 22:40:00 -07:00
Peter Johnson
412e8034de Start implementing client and server. 2015-07-17 22:39:36 -07:00
Peter Johnson
a6162ba990 NetworkConnection: Trigger threads as necessary in Stop(). 2015-07-17 22:28:47 -07:00
Peter Johnson
7c51178608 TCPAcceptor: Add shutdown() function. 2015-07-17 22:28:13 -07:00
Peter Johnson
899c489124 TCPStream: Shutdown on close. 2015-07-17 22:27:49 -07:00
Peter Johnson
3062e1e740 Message: Add data accessors. 2015-07-17 19:41:40 -07:00
Peter Johnson
854bfba7c9 Value: Set last_change field. 2015-07-17 11:16:03 -07:00
Peter Johnson
1d4de091f9 Implement nt::Now(). 2015-07-17 11:15:44 -07:00
Peter Johnson
440916cf2a Fix string terminator in char** output. 2015-07-17 10:16:46 -07:00
Peter Johnson
3f4feb2f5c Remove unused variable. 2015-07-17 10:16:31 -07:00
Peter Johnson
3025a7e51e Finish C wrappers. 2015-07-17 08:47:25 -07:00
Peter Johnson
fcbd2751ba Provide C++ API. Move all classes to "nt" namespace.
The C API is now just simple wrappers around the C++ API.
2015-07-17 07:21:07 -07:00
Peter Johnson
56f1481c24 Add Dispatcher. 2015-07-16 22:55:50 -07:00
Peter Johnson
2ea20b8e81 Value: Use NT_Value for internal storage.
This saves a tiny bit of space, but also allows for the NT_Value equivalent
of a Value to be provided with no copy cost (will be useful in the C API).
2015-07-16 21:44:37 -07:00
Peter Johnson
9906116d23 Don't base Value on NT_Value.
Also use std::string instead of NT_String.

Conversions to/from the internal structures will be done at the interface.
2015-07-16 01:38:27 -07:00
Peter Johnson
555725a05b NetworkConnection: Don't explicitly declare default move constructor. 2015-07-15 23:29:17 -07:00
Peter Johnson
13cbf4e288 Message: use shared_ptr.
NetworkConnection: Own the input and output queues.
2015-07-15 21:20:18 -07:00
Peter Johnson
beb92e6cbf NetworkConnection: Ignore duplicate Start() calls. 2015-07-14 23:15:30 -07:00
Peter Johnson
4d3fb3c497 Storage: Use unique_ptr for instance. 2015-07-14 23:15:08 -07:00
Peter Johnson
dbd0c98306 Message: implement MsgType constructor. 2015-07-14 23:09:56 -07:00
Peter Johnson
53fb702512 ConcurrentQueue: Add empty() function.
Change-Id: I563c0343f70a5e4577a6387914d821728cbdd007
2015-07-13 22:56:58 -07:00
Peter Johnson
e640708245 Start implementing network connectivity.
Change-Id: I82875bfd1c3a086033d22de636d4fb43455ebac3
2015-07-13 22:46:41 -07:00
Peter Johnson
8fdaf61ef1 Use typedef for GetEntryFunc function pointer.
Change-Id: I58d4be7783656eb712cb32cd17075b4f35886693
2015-07-13 22:45:35 -07:00
Peter Johnson
a5713252dc Message::Read(): restructure to read directly into Message.
Change-Id: Ibed3d6d334130c165543fd20987ac5d54b0696eb
2015-07-12 23:35:23 -07:00
Peter Johnson
f5ec5e180d Message: don't explicitly convert StringValue.
Change-Id: I2ab104d19e49c1b6d3384134587182ce9b8980f8
2015-07-12 23:14:48 -07:00
Peter Johnson
27e0f22c04 StringValue: Implictly convert/assign from StringRef.
Change-Id: I87f1e60a3e87db66c6efda824f9e66e919f0a5ea
2015-07-12 23:13:43 -07:00
Peter Johnson
2016bcb37a Replace MessageReader and MessageWriter with Message.
Change-Id: I4b23d5a1e0e39dc2487f252a0947f11328e33090
2015-07-12 11:24:34 -07:00
Peter Johnson
1760d32019 MessageReader: Rename Run() to ReadMessage().
Change-Id: Id6312478e331c4d7f7832e214a57ecf0338e0fcb
2015-07-11 09:33:35 -07:00
Peter Johnson
9808c6e62b Remove extra whitespace.
Change-Id: Ibbfe4f4e1b73f9dcf58cb3ae1f34ffa661ef5de0
2015-07-11 09:33:35 -07:00
Peter Johnson
071b278b71 MessageReader: Use rvalue refs and std::move for handlers.
Change-Id: Iedba512d64ef2674c18a88b9fb720b2a6346b902
2015-07-11 09:33:35 -07:00
Peter Johnson
f4673f3123 WireDecoder::Read(): Use const char instead of plain char.
Change-Id: I14932ccd174b70fa3f90676c66ac0907e6086238
MessageReader: Use StringRef for callbacks.
2015-07-11 09:33:35 -07:00
Peter Johnson
8ee4c36e02 MessageReader/MessageWriter: bring in proto_rev().
Change-Id: I7b4ce8a33fe480eb78fb36935de5480bdd1f6f13
2015-07-11 09:33:34 -07:00
Peter Johnson
0f876d1989 Use StringRef instead of NT_String in various places.
Change-Id: Ibd11e0e1c3157eb8647211797ef8b4aa63f58eb8
2015-07-11 09:33:34 -07:00
Peter Johnson
eecf0deeec Add WireDecoder test and finish WireEncoder test.
Change-Id: I0d2b3421df55f8f986678b694bbd5481e8fc6e6b
2015-07-11 09:33:34 -07:00
Peter Johnson
6aa32e8752 WireDecoder: Add overloads for StringValue and Value.
Change-Id: Idb41fd16fec8efc8b984c1a9b4d225829d16e344
StringValue: Add comparison operators.
2015-07-11 09:33:34 -07:00
Peter Johnson
a55b6565b8 WireDecoder ReadDouble: Use ref cast.
Change-Id: I47f23709960d13c005916b5d41d81339302adda5
2015-07-11 09:33:34 -07:00
Peter Johnson
c1c0c8d418 Optimize Write16/32/Double a bit.
Change-Id: I3d09a9d1b0b33da401312b3389234f7680da6f97
2015-07-11 09:33:34 -07:00
Peter Johnson
1634773529 Finish WireEncoder tests and fix a bug.
Change-Id: Iddb6003cf2050aebbda4650a5596342288432fde
2015-07-11 09:33:34 -07:00
Peter Johnson
547e2ad72b leb128 test: naming consistency
Change-Id: Ib37433110781d87f8736c82d4b8249d580b5a1dd
2015-07-11 09:33:34 -07:00
Peter Johnson
ca90648118 Add copyrights and header guards.
Change-Id: I1e4c22a1626095750b6ffa8e0edd5e078ef221ec
2015-07-11 09:33:34 -07:00
Peter Johnson
958fbaa819 ValueTest / StringValueTest: Make conversion function static.
Change-Id: Ia7411fd58cfd7ee9225a7c7f90534567e7ae02ba
2015-07-11 09:33:34 -07:00
Peter Johnson
fa19a54ab7 Separate ValueTest and StringValueTest into headers.
Change-Id: If326e6943a11f271ef939dc815a45ba0b4ee271c
2015-07-11 09:33:34 -07:00
Peter Johnson
c9c1b7e5d8 Rename test files.
Change-Id: If7a2894f21b86bf9e4036e3069a2e5602ca932b0
2015-07-11 09:33:34 -07:00
Peter Johnson
4d5e5c82d4 Start WireEncoder testing.
Change-Id: I0e4161f5b3cab167d3c3d650588671be8a1b78b3
2015-07-11 09:33:34 -07:00
Peter Johnson
9bd4a5ecc3 Add proto_rev accessors to WireEncoder and WireDecoder.
Change-Id: I401a0fbc675379c4d5b1dbcc42cbefe0311304f1
2015-07-11 09:33:34 -07:00
Peter Johnson
09d6619a58 Add LEB128 test.
Change-Id: Iaeb2d818226a281a905cb69ef12725e504c3a03d
2015-07-11 09:33:34 -07:00
Peter Johnson
e7ba40dcfd ReadUleb128: Take const buf.
Change-Id: Idd4637790938485a291a20eab4e14f5112c04c8a
2015-07-11 09:33:34 -07:00
Peter Johnson
ae42eee8e1 More Base64 fixes (correct decode return value).
Change-Id: Ic8f5eb7efd39e1d155a458aa41e430232bee7c7d
2015-07-11 09:33:34 -07:00
Peter Johnson
1e9b9b9a3e Base64: Fix a little differently.
Change-Id: I394a1c99e1ecf87b4e236cf0aced5f9429364ace
2015-07-11 09:33:34 -07:00
Peter Johnson
1225d3ef75 Slight whitespace fix.
Change-Id: I752a000775efefd45cf5c5be0a084e855f68e13f
2015-07-11 09:33:34 -07:00
Peter Johnson
407ded6b8c Use ASSERT_EQ with correct order of arguments.
Change-Id: Ieed4703283ae222df3aee8adb07ca1e65e863c62
2015-07-11 09:33:34 -07:00
Peter Johnson
c7b5266f9a Add Base64 tests and fix a couple of bugs found.
Change-Id: I9762fe018be78cf38aa506026e78139e2479cd98
2015-07-11 09:33:33 -07:00
Peter Johnson
5a0fccc9cf Add unit tests for StringValue and Value.
Add unit test framework to CMakeLists.txt.
Fix a couple of bugs found by unit tests.

Change-Id: I2092a7f0570fae0f19f9e083c4837ccefcc4ca1a
2015-07-11 09:33:33 -07:00
Peter Johnson
b66fb68f29 Finish LoadPersistent().
Change-Id: I5c4c439dc3d2585f2edae74f78c14f826b091186
2015-07-11 09:33:33 -07:00
Peter Johnson
cb30bb5d70 Rename base64 to Base64.
Change-Id: I0dea9f77ca898ab1a278a0b0163418f96f823725
2015-07-11 09:33:33 -07:00
Peter Johnson
40ebb9a844 C++-ify base64 functions.
Change-Id: I5cf7a8971b18b7a2700fe8d616733e32fa1e3282
2015-07-11 09:33:33 -07:00
Peter Johnson
b7a87bb6f9 Make StringValue noncopyable.
Change-Id: I5b02cf988aaa15c467fa62c96c951d2891bc43db
2015-07-11 09:33:33 -07:00
Peter Johnson
e38cce46ad Add missing llvm headers.
Change-Id: I2e913ef8289b2336a74690195085ca9f6e14d94e
2015-07-11 09:33:33 -07:00
Peter Johnson
f6deafee22 Add type-safe wrapper around NT_Value and NT_String.
Change-Id: Ib7ef5a6de9c8c7a1f5f6432083d1fb38328438dc
2015-07-11 09:33:33 -07:00
Peter Johnson
8d6a0786c8 Move all C api functions to ntcore.cpp.
Change-Id: I17b4f5fec30ecd684cf04af2bbd6b7346bfcd683
2015-07-11 09:33:33 -07:00
Peter Johnson
9ee3070667 Storage: Make entries private, add accessors.
Use range-based for in SavePersistent.

Change-Id: If43ed97379114b3bf8a5e95da99103791cd09d4d
2015-07-11 09:33:33 -07:00
Peter Johnson
05e084364a Start implementing LoadPersistent.
Switch to using fstream instead of stdio.

Change-Id: I600a8748a0b3dcf24740d63cc296df000abc388d
2015-07-11 09:33:33 -07:00
Peter Johnson
69e91244f4 Rename make_StringRef to MakeStringRef.
Change-Id: I18ca471c6e31f79956bcab9d4405afc355238a8f
2015-07-11 09:33:33 -07:00
Peter Johnson
e37a9d81f1 Cleanups and commenting.
Change-Id: I491a68af8614198af450942cd378c9486f27d338
2015-07-11 09:33:33 -07:00
Peter Johnson
95d0736bb6 More coding guidelines name changes, and use "using".
Change-Id: I48a898d13623749a55c469ba558155cd1467b4ce
2015-07-11 09:33:33 -07:00
Peter Johnson
de4ba1aa35 Fix up naming of Base64 and Leb128 functions.
Change-Id: I80a2493d822b59311ba0d7bd68b5ccf0e3b29e6a
2015-07-11 09:33:33 -07:00
Peter Johnson
d7ca3343bc File renames.
Change-Id: I3fa88f94593941a25f65eaabfcbbca2428613e6c
2015-07-11 09:33:33 -07:00
Peter Johnson
cee77a3228 Reformat per new coding guidelines.
Change-Id: Ib0e5d3a6fabe6db414d72b334ca7a7f33bc5726b
2015-07-11 09:33:33 -07:00
Peter Johnson
f5a82be9e5 timestamp.cpp: A few cleanups.
Change-Id: Ifcc93a27ddf901b8ec0c9e8de250e88e21536a8f
2015-07-11 09:33:33 -07:00
Peter Johnson
2a1ccaff1e Add timestamp function NT_Now().
Change-Id: I797a220308cd64ca0545222b433a18aa2294bac5
2015-07-11 09:33:33 -07:00
Peter Johnson
b195dfbe09 Add ConcurrentQueue implementation.
Change-Id: I28224d07c0b093bd520f0a1038cc808b1fac626c
2015-07-11 09:33:33 -07:00
Peter Johnson
0aab4c27e1 Use nullptr.
Change-Id: I469bbe4994ea22a22d2d72e47d72cab606d43eef
2015-07-11 09:33:32 -07:00
Peter Johnson
42ad98567c Use C++11 deleted functions for noncopyable.
Change-Id: I686f8871932c8bd611c74ef1e84a31530ea96d66
2015-07-11 09:33:32 -07:00
Peter Johnson
c06e625413 Fix code style for pointer and references.
Change-Id: I3ca5988f09aa4f81946dc3e53116c8151a981024
2015-07-11 09:33:32 -07:00
Peter Johnson
1a48e75d43 Implement SavePersistent.
Change-Id: I0b635b3e17dcfb6f238f57f2bff5575538ab7743
2015-07-11 09:33:32 -07:00
Peter Johnson
a896a3ade5 Import LLVM StringMap et al.
Change-Id: Ic48c722c2856c7aa36001935adbcf31b986ac1f3
2015-07-11 09:33:32 -07:00
Peter Johnson
62ef9e1c6b Remove extra Reserve calls.
Change-Id: I8d4142fa459cf74067e549363d4b88e2334faf5f
2015-07-11 09:33:32 -07:00
Peter Johnson
047cccda89 Refactor WireEncoder.
Change-Id: I50106755ce5571821d6e36767b16d08b91f054de
2015-07-11 09:33:32 -07:00
Peter Johnson
dbed3fea6f Move remaining read functions.
Change-Id: I415edc98fa06bb8e2c1a950ebdeb42775d915a77
2015-07-11 09:33:32 -07:00
Peter Johnson
b88a9295bf More refactoring.
Change-Id: Iaf937feb0486d2f008a47584c0a75edccbde2b34
2015-07-11 09:33:32 -07:00
Peter Johnson
c4d4679ed9 Finish EXECUTE_RPC and RPC_RESPONSE handling.
Change-Id: I927711c0625527093899f63c171302901ff8277a
2015-07-11 09:33:32 -07:00
Peter Johnson
c2063f3a88 Refactor MessageReader into WireDecoder.
Change-Id: If5842b4f6b9a7db3d3de515cd71324ab7ee82f50
2015-07-11 09:33:32 -07:00
Peter Johnson
03bae15b96 ntcore: Implement RPC_RESPONSE reading.
Change-Id: I80b678fb5fccc0ef21b6c5b9a89e49d18702e8a0
2015-07-11 09:33:32 -07:00
Peter Johnson
842fb957a6 ntcore: Initial commit.
Change-Id: Id8df275a34aaa628581b18e39014b880c29bf9b2
2015-07-11 09:33:32 -07:00
3562 changed files with 425013 additions and 125679 deletions

View File

@@ -0,0 +1,10 @@
name: "Validate Gradle Wrapper"
on: [push]
jobs:
validation:
name: "Validation"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: gradle/wrapper-validation-action@v1

15
.gitignore vendored
View File

@@ -1,11 +1,9 @@
# WPIlib Specific
dependency-reduced-pom.xml
/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/WPILibVersion.java
/wpilibc/shared/src/WPILibVersion.cpp
/wpilibj/src/main/java/edu/wpi/first/wpilibj/util/WPILibVersion.java
/wpilibc/src/main/native/cpp/WPILibVersion.cpp
doxygen.log
build*/
!buildSrc/
# Created by the jenkins test script
test-reports
@@ -15,6 +13,7 @@ test-reports
*.ipr
*.iws
.idea/
out/
# Created by http://www.gitignore.io
@@ -204,7 +203,6 @@ ipch/
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
@@ -217,3 +215,10 @@ ipch/
# Visual Studio 2015 cache/options directory
.vs/
# compile_commands
compile_commands.json
# clang configuration and clangd cache
.clang
.clangd/

View File

@@ -9,33 +9,26 @@ cppSrcFileInclude {
}
generatedFileExclude {
gmock/
ni-libraries/include/
ni-libraries/lib/
hal/src/main/native/athena/ctre/
hal/src/main/native/athena/frccansae/
hal/src/main/native/athena/visa/
hal/src/main/native/include/ctre/
UsageReporting\.h$
FRCNetComm\.java$
simulation/gz_msgs/src/include/simulation/gz_msgs/msgs\.h$
simulation/halsim_gui/src/main/native/include/portable-file-dialogs\.h$
}
modifiableFileExclude {
wpilibj/src/arm-linux-jni/
wpilibj/src/main/native/cpp/
\.patch$
\.png$
\.py$
\.so$
repoRootNameOverride {
wpilib
}
includeOtherLibs {
^HAL/
^llvm/
^cameraserver/
^cscore
^hal/
^imgui
^mockdata/
^networktables/
^ntcore
^opencv2/
^support/
}
includeProject {
^ctre/
^units/
^vision/
^wpi/
}

View File

@@ -1,40 +0,0 @@
sudo: true
dist: trusty
language: java
addons:
apt:
sources:
- deadsnakes
- ubuntu-toolchain-r-test
packages:
- g++-6
- python3.5
before_install:
- sudo sh -c 'echo "deb http://apt.llvm.org/trusty/ llvm-toolchain-trusty-5.0 main" > /etc/apt/sources.list.d/llvm.list'
- wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key|sudo apt-key add -
- sudo apt-get update -q || true
- sudo apt-get install clang-format-5.0 -y
install:
- wget https://bootstrap.pypa.io/get-pip.py
- sudo python3.5 get-pip.py
- python3.5 -m pip install --user wpiformat
- mkdir -p $HOME/latest-gcc-symlinks # see travis-ci/travis-ci#3668
- ln -s /usr/bin/g++-6 $HOME/latest-gcc-symlinks/g++
- ln -s /usr/bin/gcc-6 $HOME/latest-gcc-symlinks/gcc
- export PATH=$HOME/latest-gcc-symlinks:$PATH
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
script:
- python3.5 -m wpiformat -y 2018 -clang 5.0
- git --no-pager diff --exit-code HEAD # Ensure formatter made no changes
- ./gradlew --no-daemon --console=plain -PskipAthena :hal:halSimSharedLibrary :wpilibc:wpilibcSharedLibrary :wpilibj:wpilibJNISharedSharedLibrary :wpilibj:jar

View File

@@ -0,0 +1,6 @@
{
"enableCppIntellisense": true,
"currentLanguage": "cpp",
"projectYear": "2020",
"teamNumber": 0
}

146
CMakeLists.txt Normal file
View File

@@ -0,0 +1,146 @@
# Disable in-source builds to prevent source tree corruption.
if(" ${CMAKE_SOURCE_DIR}" STREQUAL " ${CMAKE_BINARY_DIR}")
message(FATAL_ERROR "
FATAL: In-source builds are not allowed.
You should create a separate directory for build files.
")
endif()
project(allwpilib)
cmake_minimum_required(VERSION 3.3.0)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/modules")
INCLUDE(CPack)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT AND MSVC)
set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Default install dir on windows" FORCE)
endif()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${CMAKE_BINARY_DIR}/jar)
# use, i.e. don't skip the full RPATH for the build tree
SET(CMAKE_SKIP_BUILD_RPATH FALSE)
# when building, don't use the install RPATH already
# (but later on when installing)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/wpilib/lib")
# add the automatically determined parts of the RPATH
# which point to directories outside the build tree to the install RPATH
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
# the RPATH to be used when installing, but only if it's not a system directory
LIST(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/wpilib/lib" isSystemDir)
IF("${isSystemDir}" STREQUAL "-1")
SET(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/wpilib/lib")
ENDIF("${isSystemDir}" STREQUAL "-1")
option(WITHOUT_JAVA "don't include java and JNI in the build" OFF)
option(BUILD_SHARED_LIBS "build with shared libs (needed for JNI)" ON)
option(WITHOUT_CSCORE "Don't build cscore (removes OpenCV requirement)" OFF)
option(WITHOUT_ALLWPILIB "Don't build allwpilib (removes OpenCV requirement)" ON)
option(WITH_TESTS "build unit tests (requires internet connection)" OFF)
option(USE_EXTERNAL_HAL "Use a separately built HAL" OFF)
set(EXTERNAL_HAL_FILE "" CACHE FILEPATH "Location to look for an external HAL CMake File")
option(USE_VCPKG_LIBUV "Use vcpkg libuv" OFF)
option(USE_VCPKG_EIGEN "Use vcpkg eigen" OFF)
option(FLAT_INSTALL_WPILIB "Use a flat install directory" OFF)
option(WITH_SIMULATION_MODULES "build simulation modules" OFF)
set(OPENCV_JAVA_INSTALL_DIR "" CACHE PATH "Location to search for the OpenCV jar file")
if (NOT WITHOUT_JAVA AND NOT BUILD_SHARED_LIBS)
message(FATAL_ERROR "
FATAL: Cannot build static libs with Java enabled.
Static libs requires both BUILD_SHARED_LIBS=OFF and
WITHOUT_JAVA=ON
")
endif()
if (WITHOUT_JAVA OR WITHOUT_CSCORE)
if(NOT "${OPENCV_JAVA_INSTALL_DIR}" STREQUAL "")
message(WARNING "
WARNING: OpenCV Java dir set but java is not enabled!
It will be ignored.
")
endif()
endif()
set( wpilib_dest wpilib)
set( include_dest wpilib/include )
set( main_lib_dest wpilib/lib )
set( java_lib_dest wpilib/java )
set( jni_lib_dest wpilib/jni )
if (MSVC OR FLAT_INSTALL_WPILIB)
set (wpilib_config_dir ${wpilib_dest})
else()
set (wpilib_config_dir share/wpilib)
endif()
if (USE_VCPKG_LIBUV)
set (LIBUV_VCPKG_REPLACE "find_package(unofficial-libuv CONFIG)")
endif()
if (USE_VCPKG_EIGEN)
set (EIGEN_VCPKG_REPLACE "find_package(Eigen3 CONFIG)")
endif()
if (MSVC OR FLAT_INSTALL_WPILIB)
set(WPIUTIL_DEP_REPLACE "include($\{SELF_DIR\}/wpiutil-config.cmake)")
set(NTCORE_DEP_REPLACE "include($\{SELF_DIR\}/ntcore-config.cmake)")
set(CSCORE_DEP_REPLACE_IMPL "include(\${SELF_DIR}/cscore-config.cmake)")
set(CAMERASERVER_DEP_REPLACE_IMPL "include(\${SELF_DIR}/cameraserver-config.cmake)")
set(HAL_DEP_REPLACE_IMPL "include(\${SELF_DIR}/hal-config.cmake)")
set(WPILIBC_DEP_REPLACE_IMPL "include(\${SELF_DIR}/wpilibc-config.cmake)")
else()
set(WPIUTIL_DEP_REPLACE "find_dependency(wpiutil)")
set(NTCORE_DEP_REPLACE "find_dependency(ntcore)")
set(CSCORE_DEP_REPLACE_IMPL "find_dependency(cscore)")
set(CAMERASERVER_DEP_REPLACE_IMPL "find_dependency(cameraserver)")
set(HAL_DEP_REPLACE_IMPL "find_dependency(hal)")
set(WPILIBC_DEP_REPLACE_IMPL "find_dependency(wpilibc)")
endif()
set(FILENAME_DEP_REPLACE "get_filename_component(SELF_DIR \"$\{CMAKE_CURRENT_LIST_FILE\}\" PATH)")
set(SELF_DIR "$\{SELF_DIR\}")
if (WITH_TESTS)
enable_testing()
add_subdirectory(googletest)
include(GoogleTest)
endif()
add_subdirectory(wpiutil)
add_subdirectory(ntcore)
if (NOT WITHOUT_CSCORE)
set(CSCORE_DEP_REPLACE ${CSCORE_DEP_REPLACE_IMPL})
set(CAMERASERVER_DEP_REPLACE ${CAMERASERVER_DEP_REPLACE_IMPL})
add_subdirectory(cscore)
add_subdirectory(cameraserver)
if (NOT WITHOUT_ALLWPILIB)
set(HAL_DEP_REPLACE ${HAL_DEP_REPLACE_IMPL})
set(WPILIBC_DEP_REPLACE ${WPILIBC_DEP_REPLACE_IMPL})
add_subdirectory(hal)
add_subdirectory(wpilibj)
add_subdirectory(wpilibc)
add_subdirectory(myRobot)
endif()
endif()
if (WITH_SIMULATION_MODULES AND NOT USE_EXTERNAL_HAL)
add_subdirectory(imgui)
add_subdirectory(simulation)
endif()
configure_file(wpilib-config.cmake.in ${CMAKE_BINARY_DIR}/wpilib-config.cmake )
install(FILES ${CMAKE_BINARY_DIR}/wpilib-config.cmake DESTINATION ${wpilib_config_dir})

View File

@@ -20,7 +20,7 @@ So you want to contribute your changes back to WPILib. Great! We have a few cont
- Substantial changes often need to have corresponding LabVIEW changes. To do this, we will work with NI on these large changes.
- Changes should have tests.
- Code should be well documented.
- This often involves ScreenSteps. To add content to ScreenSteps, we will work with you to get the appropriate articles written.
- This involves writing tutorials and/or usage guides for your submitted feature. These articles are then hosted on the [WPILib](https://docs.wpilib.org/) documentation website. See the [frc-docs repository](https://github.com/wpilibsuite/frc-docs) for more information.
## What to Contribute
@@ -37,7 +37,7 @@ So you want to contribute your changes back to WPILib. Great! We have a few cont
## Coding Guidelines
WPILib uses modified Google style guides for both C++ and Java, which can be found in the [styleguide repository](https://github.com/wpilibsuite/styleguide). Autoformatters are available for many popular editors at https://github.com/google/styleguide. Running wpiformat is required for all contributions and is enforced by our continuous integration system.
WPILib uses modified Google style guides for both C++ and Java, which can be found in the [styleguide repository](https://github.com/wpilibsuite/styleguide). Autoformatters are available for many popular editors at https://github.com/google/styleguide. Running wpiformat is required for all contributions and is enforced by our continuous integration system. We currently use clang-format 6.0 with wpiformat.
While the library should be fully formatted according to the styles, additional elements of the style guide were not followed when the library was initially created. All new code should follow the guidelines. If you are looking for some easy ramp-up tasks, finding areas that don't follow the style guide and fixing them is very welcome.
@@ -53,4 +53,4 @@ When you first submit changes, Travis-CI will attempt to run `./gradlew check` o
## Licensing
By contributing to WPILib, you agree that your code will be distributed with WPILib, and licensed under the license for the WPILib project. You should not contribute code that you do not have permission to relicense in this manner. This includes code that is licensed under the GPL that you do not have permission to relicense, as WPILib is not released under a copyleft license. Our license is the 3-clause BSD license, which you can find [here](license.txt).
By contributing to WPILib, you agree that your code will be distributed with WPILib, and licensed under the license for the WPILib project. You should not contribute code that you do not have permission to relicense in this manner. This includes code that is licensed under the GPL that you do not have permission to relicense, as WPILib is not released under a copyleft license. Our license is the 3-clause BSD license, which you can find [here](LICENSE.txt).

15
FasterBuilds.md Normal file
View File

@@ -0,0 +1,15 @@
# Faster Builds for Developers
When you run `./gradlew build`, it builds EVERYTHING. This means debug and release builds for desktop and all installed cross compilers. For many developers, this is way too much, and causes much developer pain.
To help with some of these things, common tasks have shortcuts to only build necessary things for common development and testing tasks.
## Development (Desktop)
For projects `wpiutil`, `ntcore`, `cscore`, `hal` `wpilibOldCommands`, `wpilibNewCommands` and `cameraserver`, a `testDesktopJava` and a `testDesktopCpp` task exists. These can be ran with `./gradlew :projectName:task`, and will only build the minimum things required to run those tests.
For `wpilibc`, a `testDesktopCpp` task exists. For `wpilibj`, a `testDesktopJava` task exists.
For `wpilibcExamples`, a `buildDesktopCpp` task exists (These can't be ran, but they can compile).
For `wpilibjExamples`, a `buildDesktopJava` task exists.

View File

@@ -1,4 +1,4 @@
Copyright (c) 2009-2017 FIRST
Copyright (c) 2009-2018 FIRST
All rights reserved.
Redistribution and use in source and binary forms, with or without

130
MavenArtifacts.md Normal file
View File

@@ -0,0 +1,130 @@
# WPILib Maven Artifacts
WPILib publishes its built artifacts to our Maven server for use by downstream projects. This document explains these locations, and the meanings of artifact names, classifiers, and versions.
## Repositories
We provide two repositories. These repositories are:
* (Release) https://frcmaven.wpi.edu/artifactory/release/
* (Development) https://frcmaven.wpi.edu/artifactory/development/
The release repository is where official WPILib releases are pushed.
The development repository is where development releases of every commit to [master](https://github.com/wpilibsuite/allwpilib/tree/master) is pushed.
## Artifact classifiers
We provide two base types of artifacts.
The first types are Java artifacts. These are usually published as `jar` files. Usually, the actual jar file is published with no classifier. The sources are published with the `-sources` classifier, and the javadocs are published with the `-javadoc` classifier.
The second types are native artifacts. These are usually published as `zip` files (except for the `JNI` artifact types, which are `jar` files. See below for information on this). The `-sources` and `-headers` classifiers contain the sources and headers respecively for the library. Each artifact also contains a classifier for each platform we publish. This platform is in the format `{os}{arch}`. The platform artifact only contains the binaries for a specific platform. In addition, we provide a `-all` classifier. This classifer combines all of the platform artifacts into a single artifact. This is useful for tools that cannot determine what version to use during builds. However, we recommend using the platform specific classifier when possible. Note that the binary artifacts never contain the headers, you always need the `-headers` classifier to get those.
## Artifact Names
WPILib builds four different types of artifacts.
##### C++ Only Libraries
When we publish C++ only libraries, they are published with the base artifact name as their artifact name, with a `-cpp` extension. All dependencies for the library are linked as shared libraries to the binary.
Example:
```
edu.wpi.first.wpilibc:wpilibc-cpp:version:classifier@zip
```
#### Java Only Libraries
When we publish Java only libraries, they are published with the base artifact name as their artifact name, with a `-java` extension.
Example:
```
edu.wpi.first.wpilibj:wpilibj-java:version
```
#### C++/Java Libraries without JNI
For libraries that are both C++ and Java, but without a JNI component, the C++ component is published with the `basename-cpp` artifact name, and the Java component is published with the `basename-java` artifact name.
Example:
```
edu.wpi.first.wpiutil:wpiutil-cpp:version:classifier@zip (C++)
edu.wpi.first.wpiutil:wpiutil-java:version (Java)
```
#### C++/Java Libraries with JNI
For libraries that are both C++ and Java with a JNI component there are three different artifact names. For Java, the component is published as `basename-java`. For C++, the `basename-cpp` artifact contains the C++ artifacts with all dependencies linked as shared libraries to the binary. These binaries DO contain the JNI entry points. The `basename-jni` artifact contains identical C++ binaries to the `-cpp` artifact, however all of its dependencies are statically linked, and only the JNI and C entry points are exported.
The `-jni` artifact should only be used in cases where you want to create a self contained Java application where the native artifacts are embedded in the jar. Note in an extraction scenario, extending off of the library is never supported, which is why the C++ entry points are not exposed. The name of the library is randomly generated during extraction. For pretty much all cases, and if you ever want to extend from a native library, you should use the `-cpp` artifacts. GradleRIO uses the `-cpp` artifacts for all platforms, even desktop, for this reason.
Example:
```
edu.wpi.first.ntcore:ntcore-cpp:version:classifier@zip (C++)
edu.wpi.first.ntcore:ntcore-jni:version:classifier (JNI jar library)
edu.wpi.first.ntcore:ntcore-java:version (Java)
```
## Provided Artifacts
This repository provides the following artifacts. Below each artifact is its dependencies. Note if ever using the `-jni` artifacts, no dependencies are needed for native binaries.
For C++, if building with static dependencies, the listed order should be the link order in your linker.
All artifacts are based at `edu.wpi.first.artifactname` in the repository.
* wpiutil
* hal
* wpiutil
* halsim
* imgui
* wpiutil
* ntcore
* wpiutil
* cscore
* opencv
* wpiutil
* cameraserver
* ntcore
* cscore
* opencv
* wpiutil
* wpilibj
* hal
* cameraserver
* ntcore
* cscore
* wpiutil
* wpilibc
* hal
* cameraserver
* ntcore
* cscore
* wpiutil
* wpilibNewCommands
* wpilibc
* hal
* cameraserver
* ntcore
* cscore
* wpiutil
* wpilibNewCommands
* wpilibc
* hal
* cameraserver
* ntcore
* cscore
* wpiutil
### Third Party Artifacts
This repository provides the builds of the following third party software.
All artifacts are based at `edu.wpi.first.thirdparty.frcYEAR` in the repository.
* googletest
* imgui
* opencv

140
README-CMAKE.md Normal file
View File

@@ -0,0 +1,140 @@
# WPILib CMake Support
WPILib is normally built with Gradle, however for some systems, such a linux based coprocessors, Gradle doesn't work correctly, especially if cscore is needed, which requires OpenCV. We provide the CMake build for these cases. Although it is supported on Windows, these docs will only go over linux builds.
## Libraries that get built
* wpiutil
* ntcore
* cscore
* cameraserver
* hal
* wpilib
By default, all libraries except for the HAL and WPILib get built with a default cmake setup. The libraries are built as shared libraries, and include the JNI libraries as well as building the Java jars.
## Prerequisites
The most common prerequisite is going to be OpenCV. OpenCV needs to be findable by cmake. On systems like the Jetson, this is installed by default. Otherwise, you will need to build cmake from source and install it.
In addition, if you want JNI and Java, you will need a JDK of at least version 8 installed. In addition, you need a `JAVA_HOME` environment variable set properly and set to the jdk directory.
## Build Options
The following build options are available:
* WITHOUT_JAVA (OFF Default)
* Enabling this option will disable Java and JNI builds. If this is off, `BUILD_SHARED_LIBS` must be on. Otherwise cmake will error.
* BUILD_SHARED_LIBS (ON Default)
* Disabling this option will cause cmake to build static libraries instead of shared libraries. If this is off, `WITHOUT_JAVA` must be on. Otherwise cmake will error.
* WITHOUT_CSCORE (OFF Default)
* Enabling this option will cause cscore to not be built. This will also implicitly disable cameraserver, the hal and wpilib as well, irrespective of their specific options. If this is on, the opencv build requirement is removed.
* WITHOUT_ALLWPILIB (ON Default)
* Disabling this option will build the hal and wpilib during the build. The HAL is the simulator hal, unless the external hal options are used. The cmake build has no capability to build for the RoboRIO.
* USE_EXTERNAL_HAL (OFF Default)
* TODO
* EXTERNAL_HAL_FILE
* TODO
* OPENCV_JAVA_INSTALL_DIR
* Set this option to the location of the archive of the OpenCV Java bindings (it should be called opencv-xxx.jar, with the x'es being version numbers). NOTE: set it to the LOCATION of the file, not the file itself!
## Build Setup
The WPILib CMake build does not allow in source builds. Because the `build` directory is used by gradle, we recommend a `buildcmake` directory in the root. This folder is included in the gitignore.
Once you have a build folder, run cmake configuration in that build directory with the following command.
```
cmake path/to/allwpilib/root
```
If you want to change any of the options, add `-DOPTIONHERE=VALUE` to the cmake command. This will check for any dependencies. If everything works properly this will succeed. If not, please check out the troubleshooting section for help.
If you want, you can also use `ccmake` in order to visually set these properties as well.
https://cmake.org/cmake/help/v3.0/manual/ccmake.1.html
Here is the link to the documentation for that program.
## Building
Once you have cmake setup. run `make` from the directory you configured cmake in. This will build all libraries possible. If you have a multicore system, we recommend running make with multiple jobs. The usual rule of thumb is 1.5x the number of cores you have. To run a multiple job build, run the following command with x being the number of jobs you want.
```
make -jx
```
## Installing
After build, the easiest way to use the libraries is to install them. Run the following command to install the libraries. This will install them so that they can be used from external cmake projects.
```
sudo make install
```
## Using the installed libraries for C++.
Using the libraries from C++ is the easiest way to use the built libraries.
To do so, create a new folder to contain your project. Add the following code below to a `CMakeLists.txt` file in that directory.
```
cmake_minimum_required(VERSION 3.5)
project(vision_app) # Project Name Here
find_package(wpilib REQUIRED)
add_executable(my_vision_app main.cpp) # exectuable name as first parameter
target_link_libraries(my_vision_app cameraserver ntcore cscore wpiutil)
```
If you are using them, `wpilibc` and `hal` should be added before the `cameraserver` declaration in the `target_link_libraries` function.
Add a `main.cpp` file to contain your code, and create a build folder. Move into the build folder, and run
```
cmake /path/to/folder/containing/CMakeLists
```
After that, run `make`. That will create your executable. Then you should be able to run `./my_vision_app` to run your application.
## Using the installed libraries for Java
TODO
## Troubleshooting
Below are some common issues that are run into when building.
#### Missing OpenCV
If you are missing OpenCV, you will get an error message similar to this.
```
CMake Error at cscore/CMakeLists.txt:3 (find_package):
By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "OpenCV", but
CMake did not find one.
Could not find a package configuration file provided by "OpenCV" with any
of the following names:
OpenCVConfig.cmake
opencv-config.cmake
Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
"OpenCV_DIR" to a directory containing one of the above files. If "OpenCV"
provides a separate development package or SDK, be sure it has been
installed.
```
If you get that, you need make sure opencv was installed, and then reattempt to configure. If that doesn't work, set the `OpenCV_DIR` variable to the directory where you built OpenCV.
#### Missing Java
If you are missing Java, you will get a message like the following.
```
CMake Error at /usr/share/cmake-3.5/Modules/FindPackageHandleStandardArgs.cmake:148 (message):
Could NOT find Java (missing: Java_JAVA_EXECUTABLE Java_JAR_EXECUTABLE
Java_JAVAC_EXECUTABLE Java_JAVAH_EXECUTABLE Java_JAVADOC_EXECUTABLE)
```
If this happens, make sure you have a JDK of at least version 8 installed, and that your JAVA_HOME variable is set properly to point to the JDK.
In addition, if you do not need Java, you can disable it with `-DWITHOUT_JAVA=ON`.

View File

@@ -1,6 +1,6 @@
# WPILib Project
[![Build Status](https://travis-ci.org/wpilibsuite/allwpilib.svg?branch=master)](https://travis-ci.org/wpilibsuite/allwpilib)
[![Build Status](https://dev.azure.com/wpilib/wpilib/_apis/build/status/wpilibsuite.allwpilib)](https://dev.azure.com/wpilib/wpilib/_build/latest?definitionId=1)
Welcome to the WPILib project. This repository contains the HAL, WPILibJ, and WPILibC projects. These are the core libraries for creating robot programs for the roboRIO.
@@ -15,7 +15,7 @@ Welcome to the WPILib project. This repository contains the HAL, WPILibJ, and WP
## WPILib Mission
The WPILib Mission is to enable FIRST Robotics teams to focus on writing game-specific software rather than focussing on hardware details - "raise the floor, don't lower the ceiling". We work to enable teams with limited programming knowledge and/or mentor experience to be as successful as possible, while not hampering the abilities of teams with more advanced programming capabilities. We support Kit of Parts control system components directly in the library. We also strive to keep parity between major features of each language (Java, C++, and NI's LabVIEW), so that teams aren't at a disadvantage for choosing a specific programming language. WPILib is an open source project, licensed under the BSD 3-clause license. You can find a copy of the license [here](license.txt).
The WPILib Mission is to enable FIRST Robotics teams to focus on writing game-specific software rather than focusing on hardware details - "raise the floor, don't lower the ceiling". We work to enable teams with limited programming knowledge and/or mentor experience to be as successful as possible, while not hampering the abilities of teams with more advanced programming capabilities. We support Kit of Parts control system components directly in the library. We also strive to keep parity between major features of each language (Java, C++, and NI's LabVIEW), so that teams aren't at a disadvantage for choosing a specific programming language. WPILib is an open source project, licensed under the BSD 3-clause license. You can find a copy of the license [here](LICENSE.txt).
# Building WPILib
@@ -24,11 +24,11 @@ Using Gradle makes building WPILib very straightforward. It only has a few depen
## Requirements
- A C++ compiler
- On Linux, gcc works fine
- On Windows, you need Visual Studio 2015 (the free community edition works fine).
- On Linux, GCC works fine
- On Windows, you need Visual Studio 2019 (the free community edition works fine).
Make sure to select the C++ Programming Language for installation
- [ARM Compiler Toolchain](http://first.wpi.edu/FRC/roborio/toolchains/)
* Note that for 2017-2018 and beyond, you will need version 5 or greater of gcc
- [ARM Compiler Toolchain](https://github.com/wpilibsuite/roborio-toolchain/releases)
* Note that for 2020 and beyond, you should use version 7 or greater of GCC
- Doxygen (Only required if you want to build the C++ documentation)
## Setup
@@ -79,23 +79,18 @@ There are a few tasks other than `build` available. To see them, run the meta-ta
wpiformat can be executed anywhere in the repository via `py -3 -m wpiformat` on Windows or `python3 -m wpiformat` on other platforms.
CMake is also supported for building. See [README-CMAKE.md](README-CMAKE.md).
## Publishing
If you are building to test with the Eclipse plugins or just want to export the build as a Maven-style dependency, simply run the `publish` task. This task will publish all available packages to ~/releases/maven/development. If you need to publish the project to a different repo, you can specify it with `-Prepo=repo_name`. Valid options are:
If you are building to test with other dependencies or just want to export the build as a Maven-style dependency, simply run the `publish` task. This task will publish all available packages to ~/releases/maven/development. If you need to publish the project to a different repo, you can specify it with `-Prepo=repo_name`. Valid options are:
- development - The default repo.
- beta - Publishes to ~/releases/maven/beta.
- stable - Publishes to ~/releases/maven/stable.
- release - Publishes to ~/releases/maven/release.
The following maven targets a published by this task:
- edu.wpi.first.wpilib.cmake:cpp-root:1.0.0 - roboRIO C++
- edu.wpi.first.wpilibc.simulation:WPILibCSim:0.1.0 - Simulation C++
- edu.wpi.first.wpilibj:wpilibJavaFinal:0.1.0-SNAPSHOT - roboRIO Java
- edu.wpi.first.wpilibj:wpilibJavaSim:0.1.0-SNAPSHOT - Simulation Java
- edu.wpi.first.wpilibj.simulation:SimDS:0.1.0-SNAPSHOT - The driverstation for controlling simulation.
- org.gazebosim:JavaGazebo:0.1.0-SNAPSHOT - Gazebo protocol for Java.
The maven artifacts are described in [MavenArtifacts.md](MavenArtifacts.md)
## Structure and Organization

809
ThirdPartyNotices.txt Normal file
View File

@@ -0,0 +1,809 @@
==============================================================================
Copyrights and Licenses for Third Party Software Distributed with WPILib
==============================================================================
The WPILib software contains code written by third parties. The copyrights,
license, and restrictions which apply to each piece of software is included
later in this file and/or inside of the individual applicable source files.
The disclaimer of warranty in the WPILib license above applies to all code in
WPILib, and nothing in any of the other licenses gives permission to use the
names of FIRST nor the names of the WPILib contributors to endorse or promote
products derived from this software.
The following pieces of software have additional or alternate copyrights,
licenses, and/or restrictions:
Program Locations
------- ---------
RoboRIO Libraries ni-libraries
Google Test gtest
LLVM wpiutil/src/main/native/include/wpi/{various files}
wpiutil/src/main/native/cpp/llvm/
wpiutil/src/main/native/cpp/leb128.cpp
wpiutil/src/test/native/cpp/leb128Test.cpp
JSON for Modern C++ wpiutil/src/main/native/include/wpi/json.h
wpiutil/src/main/native/cpp/json_*.cpp
wpiutil/src/test/native/cpp/json/
libuv wpiutil/src/main/native/include/uv.h
wpiutil/src/main/native/include/uv/
wpiutil/src/main/native/libuv/
sigslot wpiutil/src/main/native/include/wpi/Signal.h
wpiutil/src/test/native/cpp/sigslot/
tcpsockets wpiutil/src/main/native/cpp/TCP{Stream,Connector,Acceptor}.cpp
wpiutil/src/main/native/include/wpi/TCP*.h
Bootstrap wpiutil/src/main/native/resources/bootstrap-*
CoreUI wpiutil/src/main/native/resources/coreui-*
Feather Icons wpiutil/src/main/native/resources/feather-*
jQuery wpiutil/src/main/native/resources/jquery-*
popper.js wpiutil/src/main/native/resources/popper-*
units wpiutil/src/main/native/include/units/units.h
Eigen wpiutil/src/main/native/eigeninclude/
StackWalker wpiutil/src/main/native/windows/StackWalker.*
Team 254 Library wpilibj/src/main/java/edu/wpi/first/wpilibj/spline/SplineParameterizer.java
wpilibj/src/main/java/edu/wpi/first/wpilibj/trajectory/TrajectoryParameterizer.java
wpilibc/src/main/native/include/spline/SplineParameterizer.h
wpilibc/src/main/native/include/trajectory/TrajectoryParameterizer.h
wpilibc/src/main/native/cpp/trajectory/TrajectoryParameterizer.cpp
Portable File Dialogs simulation/halsim_gui/src/main/native/include/portable-file-dialogs.h
==============================================================================
Google Test License
==============================================================================
Copyright 2008, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================================================================
LLVM Release License
==============================================================================
University of Illinois/NCSA
Open Source License
Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.
All rights reserved.
Developed by:
LLVM Team
University of Illinois at Urbana-Champaign
http://llvm.org
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal with
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of the LLVM Team, University of Illinois at
Urbana-Champaign, nor the names of its contributors may be used to
endorse or promote products derived from this Software without specific
prior written permission.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
SOFTWARE.
==============================================================================
JSON for Modern C++ License
==============================================================================
__ _____ _____ _____
__| | __| | | | JSON for Modern C++
| | |__ | | | | | | version 2.1.1
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
libuv License
==============================================================================
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
==============================================================================
sigslot License
==============================================================================
Sigslot, a signal-slot library
https://github.com/palacaze/sigslot
MIT License
Copyright (c) 2017 Pierre-Antoine Lacaze
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
tcpsockets License
==============================================================================
Copyright (c) 2013 [Vic Hargrave - http://vichargrave.com]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================
Bootstrap License
==============================================================================
Copyright (c) 2011-2018 Twitter, Inc.
Copyright (c) 2011-2018 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
==============================================================================
CoreUI License
==============================================================================
Copyright (c) 2018 creativeLabs tukasz Holeczek.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
==============================================================================
Feather Icons License
==============================================================================
Copyright (c) 2013-2017 Cole Bemis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
==============================================================================
jQuery License
==============================================================================
Copyright JS Foundation and other contributors, https://js.foundation/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
popper.js License
==============================================================================
Copyright (c) 2016 Federico Zivolo and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
=============
units License
=============
The MIT License (MIT)
Copyright (c) 2016 Nic Holthaus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
=============
Eigen license
=============
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
===================
StackWalker License
===================
Copyright (c) 2005-2013, Jochen Kalmbach
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of Jochen Kalmbach nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================
Team 254 Library
================
MIT License
Copyright (c) 2018 Team 254
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,91 @@
# Testing steps for real hardware
trigger:
batch: true
branches:
include:
- master
stages:
- stage: Build
jobs:
- job: IntegrationTests
displayName: Integration Tests
pool:
vmImage: 'Ubuntu 16.04'
container:
image: wpilib/roborio-cross-ubuntu:2020-18.04
timeoutInMinutes: 0
steps:
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: false
testResultsFiles: '**/TEST-*.xml'
tasks: 'copyWpilibJIntegrationTestJarToOutput copyWpilibCTestLibrariesToOutput'
options: '-Ponlylinuxathena -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Integration Tests'
targetPath: 'build/integrationTestFiles'
- stage: TestBench
displayName: Test Bench
jobs:
- job: Cpp
displayName: C++
pool: RoboRioConnections
timeoutInMinutes: 30
workspace:
clean: all
steps:
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Integration Tests'
targetPath: 'build/integrationTestFiles'
- task: ShellScript@2
displayName: Run C++ Tests
inputs:
scriptPath: test-scripts/deploy-and-run-test-on-robot.sh
args: 'cpp -A "--gtest_output=xml:/home/admin/testResults/cppreport.xml"'
- task: PublishTestResults@2
displayName: Publish C++ Test Results
inputs:
testResultsFormat: 'JUnit'
testResultsFiles: '*.xml'
testRunTitle: 'C++ Test Report'
searchFolder: '$(System.DefaultWorkingDirectory)/test-reports'
- job: Java
pool: RoboRioConnections
timeoutInMinutes: 30
workspace:
clean: all
steps:
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Integration Tests'
targetPath: 'build/integrationTestFiles'
- task: ShellScript@2
displayName: Run Java Tests
inputs:
scriptPath: test-scripts/deploy-and-run-test-on-robot.sh
args: 'java'
- task: PublishTestResults@2
displayName: Publish Java Test Results
inputs:
testResultsFormat: 'JUnit'
testResultsFiles: '*.xml'
testRunTitle: 'Java Test Report'
searchFolder: '$(System.DefaultWorkingDirectory)/test-reports'

417
azure-pipelines.yml Normal file
View File

@@ -0,0 +1,417 @@
# Gradle
# Build your Java projects and run tests with Gradle using a Gradle wrapper script.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/vsts/pipelines/languages/java
resources:
containers:
- container: wpilib2020
image: wpilib/roborio-cross-ubuntu:2020-18.04
- container: raspbian
image: wpilib/raspbian-cross-ubuntu:10-18.04
- container: aarch64
image: wpilib/aarch64-cross-ubuntu:bionic-18.04
- container: ubuntu
image: wpilib/ubuntu-base:18.04
variables:
- group: Artifactory-Package-Publish
trigger:
batch: true
branches:
include:
- master
stages:
- stage: Build
jobs:
- job: Linux_Arm
pool:
vmImage: 'Ubuntu 16.04'
container: wpilib2020
timeoutInMinutes: 0
steps:
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: false
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-Ponlylinuxathena -PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: false
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-Ponlylinuxathena -PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Athena'
targetPath: 'build/allOutputs'
- job: Linux_Raspbian
pool:
vmImage: 'Ubuntu 16.04'
container: raspbian
timeoutInMinutes: 0
steps:
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-Ponlylinuxraspbian -PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-Ponlylinuxraspbian -PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Raspbian'
targetPath: 'build/allOutputs'
- job: Linux_Aarch64
pool:
vmImage: 'Ubuntu 16.04'
container: aarch64
timeoutInMinutes: 0
steps:
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-Ponlylinuxaarch64bionic -PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-Ponlylinuxaarch64bionic -PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Aarch64'
targetPath: 'build/allOutputs'
- job: Linux
pool:
vmImage: 'Ubuntu 16.04'
container: ubuntu
timeoutInMinutes: 0
steps:
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Linux'
targetPath: 'build/allOutputs'
- job: Styleguide
pool:
vmImage: 'Ubuntu 16.04'
container: ubuntu
timeoutInMinutes: 0
steps:
- script: |
sudo pip3 install wpiformat
displayName: 'Install wpiformat'
- script: |
git checkout -b master
wpiformat -clang 6.0
displayName: 'Run wpiformat'
- script: |
# Ensure formatter made no changes
git --no-pager diff --exit-code HEAD
displayName: 'Check wpiformat Output'
- job: CMakeBuild
pool:
vmImage: 'Ubuntu 16.04'
container: wpilib2020
timeoutInMinutes: 0
steps:
- task: CMake@1
inputs:
cmakeArgs: '-DWITHOUT_ALLWPILIB=OFF ..'
- script: |
make -j3
workingDirectory: 'build'
displayName: 'Build'
- job: Windows_64_Bit
pool:
vmImage: 'windows-2019'
timeoutInMinutes: 0
steps:
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
jdkVersionOption: '1.11'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PskipPMD -PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
jdkVersionOption: '1.11'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PskipPMD -PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Win64'
targetPath: 'build/allOutputs'
- job: Windows_32_Bit
pool:
vmImage: 'windows-2019'
timeoutInMinutes: 0
steps:
- powershell: |
mkdir build
$ProgressPreference = 'SilentlyContinue'
wget "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.4%2B11/OpenJDK11U-jdk_x86-32_windows_hotspot_11.0.4_11.zip" -O "build\jdk.zip"
displayName: 'Download JDK'
- task: JavaToolInstaller@0
inputs:
jdkSourceOption: localDirectory
jdkFile: 'build/jdk.zip'
jdkDestinationDirectory: 'build/jdkinst'
jdkArchitectureOption: x86
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx1024m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PskipPMD -PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx1024m'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PskipPMD -PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Win32'
targetPath: 'build/allOutputs'
- job: Mac
pool:
vmImage: 'macOS-10.14'
timeoutInMinutes: 0
steps:
- script: |
mkdir build
export JAVA_HOME=`/usr/libexec/java_home -v 11`
displayName: 'Setup JDK'
- task: Gradle@2
condition: and(succeeded(), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
jdkVersionOption: '1.11'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PbuildServer'
- task: Gradle@2
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
inputs:
workingDirectory: ''
gradleWrapperFile: 'gradlew'
gradleOptions: '-Xmx3072m'
jdkVersionOption: '1.11'
publishJUnitResults: true
testResultsFiles: '**/TEST-*.xml'
tasks: 'build'
options: '-PreleaseMode -PbuildServer'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Mac'
targetPath: 'build/allOutputs'
- stage: Combine
jobs:
- job: CombineJob
pool:
vmImage: 'macOS-10.14'
timeoutInMinutes: 0
steps:
- checkout: none
- script: |
git clone https://github.com/wpilibsuite/build-tools
displayName: 'Clone Combiner'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Mac'
targetPath: 'build-tools/combiner/products/build/allOutputs'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Win32'
targetPath: 'build-tools/combiner/products/build/allOutputs'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Win64'
targetPath: 'build-tools/combiner/products/build/allOutputs'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Linux'
targetPath: 'build-tools/combiner/products/build/allOutputs'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Raspbian'
targetPath: 'build-tools/combiner/products/build/allOutputs'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Athena'
targetPath: 'build-tools/combiner/products/build/allOutputs'
- task: DownloadPipelineArtifact@0
inputs:
artifactName: 'Aarch64'
targetPath: 'build-tools/combiner/products/build/allOutputs'
# PR Builds
- task: Gradle@2
inputs:
workingDirectory: 'build-tools/combiner'
gradleWrapperFile: 'build-tools/combiner/gradlew'
gradleOptions: '-Xmx3072m'
tasks: 'publish '
options: '-Pallwpilib'
condition: and(succeeded(), and(ne(variables['Build.SourceBranch'], 'refs/heads/master'), not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))))
# Master Builds
- task: Gradle@2
inputs:
workingDirectory: 'build-tools/combiner'
gradleWrapperFile: 'build-tools/combiner/gradlew'
gradleOptions: '-Xmx3072m'
tasks: 'publish '
options: '-Pallwpilib'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master'))
env:
RUN_AZURE_ARTIFACTORY_RELEASE: 'TRUE'
ARTIFACTORY_PUBLISH_USERNAME: $(PublishUserName)
ARTIFACTORY_PUBLISH_PASSWORD: $(PublishPassword)
# Tagged Builds
- task: Gradle@2
inputs:
workingDirectory: 'build-tools/combiner'
gradleWrapperFile: 'build-tools/combiner/gradlew'
gradleOptions: '-Xmx3072m'
tasks: 'publish '
options: '-Pallwpilib -PreleaseRepoPublish'
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))
env:
RUN_AZURE_ARTIFACTORY_RELEASE: 'TRUE'
ARTIFACTORY_PUBLISH_USERNAME: $(PublishUserName)
ARTIFACTORY_PUBLISH_PASSWORD: $(PublishPassword)
- script: |
echo "##vso[task.setvariable variable=UserHome]$HOME"
displayName: 'Set Home Variable'
- task: PublishPipelineArtifact@0
inputs:
artifactName: 'Maven'
targetPath: $(UserHome)/releases

View File

@@ -1,149 +1,53 @@
import edu.wpi.first.nativeutils.NativeUtils
import edu.wpi.first.nativeutils.tasks.JNIHeaders
buildscript {
repositories {
mavenLocal()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath 'gradle.plugin.edu.wpi.first:native-utils:1.5.1'
}
}
import edu.wpi.first.toolchain.*
plugins {
id 'net.ltgt.errorprone' version '0.0.10'
id 'edu.wpi.first.wpilib.versioning.WPILibVersioningPlugin' version '2.0'
id 'base'
id 'edu.wpi.first.wpilib.versioning.WPILibVersioningPlugin' version '4.0.1'
id 'edu.wpi.first.wpilib.repositories.WPILibRepositoriesPlugin' version '2020.2'
id 'edu.wpi.first.NativeUtils' apply false
id 'edu.wpi.first.GradleJni' version '0.10.1'
id 'edu.wpi.first.GradleVsCode' version '0.11.0'
id 'idea'
id 'visual-studio'
id 'net.ltgt.errorprone' version '1.1.1' apply false
id 'com.github.johnrengelman.shadow' version '5.2.0' apply false
}
ext.licenseFile = file("$rootDir/LICENSE.txt")
ext.getJNIHeadersClass = {
return JNIHeaders
if (project.hasProperty('buildServer')) {
wpilibVersioning.buildServerMode = true
}
ext.getClassifier = { binary->
return NativeUtils.getClassifier(binary)
if (project.hasProperty('releaseMode')) {
wpilibVersioning.releaseMode = true
}
ext.getPlatformPath = { binary->
return NativeUtils.getPlatformPath(binary)
}
ext.createComponentZipTasks = { components, name, base, type, project, func ->
def configMap = [:]
components.each {
if (it in NativeLibrarySpec && it.name == name) {
it.binaries.each {
def target = getClassifier(it)
if (configMap.containsKey(target)) {
configMap.get(target).add(it)
} else {
configMap.put(target, [])
configMap.get(target).add(it)
}
}
}
allprojects {
repositories {
mavenCentral()
}
def taskList = []
def outputsFolder = file("$project.buildDir/outputs")
def baseN = base + name
configMap.each { key, value ->
def task = project.tasks.create(baseN + "-${key}", type) {
description = 'Creates component archive for platform ' + key
destinationDir = outputsFolder
classifier = key
baseName = baseN + '-classifier'
duplicatesStrategy = 'exclude'
from(licenseFile) {
into '/'
}
func(it, value)
}
taskList.add(task)
project.build.dependsOn task
project.artifacts {
task
}
}
return taskList
}
ext.createAllCombined = { list, name, base, type, project ->
def outputsFolder = file("$project.buildDir/outputs")
def baseN = base + name
def task = project.tasks.create(baseN + '-all', type) {
description = 'Creates component archive for all classifiers'
destinationDir = outputsFolder
classifier = 'all'
baseName = baseN + '-classifier'
duplicatesStrategy = 'exclude'
list.each {
it.outputs.files.each {
from project.zipTree(it)
}
dependsOn it
}
}
project.build.dependsOn task
project.artifacts {
task
}
return task
}
ext.includeStandardZipFormat = { task, value ->
value.each { binary->
if (binary.buildable) {
if (binary instanceof SharedLibraryBinarySpec) {
task.dependsOn binary.buildTask
task.from(new File(binary.sharedLibraryFile.absolutePath + ".debug")) {
into getPlatformPath(binary) + '/shared'
}
task.from (binary.sharedLibraryFile) {
into getPlatformPath(binary) + '/shared'
}
task.from (binary.sharedLibraryLinkFile) {
into getPlatformPath(binary) + '/shared'
}
} else if (binary instanceof StaticLibraryBinarySpec) {
task.dependsOn binary.buildTask
task.from (binary.staticLibraryFile) {
into getPlatformPath(binary) + '/static'
}
}
}
if (project.hasProperty('releaseMode')) {
wpilibRepositories.addAllReleaseRepositories(it)
} else {
wpilibRepositories.addAllDevelopmentRepositories(it)
}
}
// Ensure that the WPILibVersioningPlugin is setup by setting the release type, if releaseType wasn't
// already specified on the command line
if (!hasProperty('releaseType')) {
WPILibVersion {
releaseType = 'dev'
}
buildScan {
termsOfServiceUrl = 'https://gradle.com/terms-of-service'
termsOfServiceAgree = 'yes'
publishAlways()
}
def pubVersion
ext.licenseFile = files("$rootDir/LICENSE.txt", "$rootDir/ThirdPartyNotices.txt")
if (project.hasProperty("publishVersion")) {
pubVersion = project.publishVersion
} else {
pubVersion = WPILibVersion.version
wpilibVersioning.version.set(project.publishVersion)
}
def outputsFolder = file("$buildDir/outputs")
wpilibVersioning.version.finalizeValue()
def outputsFolder = file("$buildDir/allOutputs")
def versionFile = file("$outputsFolder/version.txt")
@@ -158,45 +62,53 @@ task outputVersions() {
}
doLast {
versionFile.write pubVersion
versionFile.write wpilibVersioning.version.get()
}
}
task build() {}
task libraryBuild() {}
build.dependsOn outputVersions
task clean(type: Delete) {
delete buildDir
task copyAllOutputs(type: Copy) {
destinationDir outputsFolder
}
build.dependsOn copyAllOutputs
copyAllOutputs.dependsOn outputVersions
ext.addTaskToCopyAllOutputs = { task ->
copyAllOutputs.dependsOn task
copyAllOutputs.inputs.file task.archivePath
copyAllOutputs.from task.archivePath
}
subprojects {
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'checkstyle'
repositories {
mavenCentral()
def subproj = it
plugins.withType(NativeComponentPlugin) {
subproj.apply plugin: MultiBuilds
}
checkstyle {
toolVersion = "8.1"
configFile = new File(rootDir, "styleguide/checkstyle.xml")
}
apply from: "${rootDir}/shared/java/javastyle.gradle"
// Disables doclint in java 8.
if (JavaVersion.current().isJava8Compatible()) {
tasks.withType(Javadoc) {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
ext.setupWpilibRepo = { publishing ->
publishing.repositories.maven {
url = WPILibVersion.mavenLocalUrl
if (project.name != "docs") {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = '4.1'
ext.getCurrentArch = {
return NativePlatforms.desktop
}
wrapper {
gradleVersion = '6.0'
}

9
buildSrc/build.gradle Normal file
View File

@@ -0,0 +1,9 @@
repositories {
maven {
url "https://plugins.gradle.org/m2/"
mavenLocal()
}
}
dependencies {
implementation "edu.wpi.first:native-utils:2020.7.2"
}

View File

@@ -0,0 +1,70 @@
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.FileTree;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.language.base.internal.ProjectLayout;
import org.gradle.language.base.plugins.ComponentModelBasePlugin;
import org.gradle.language.nativeplatform.tasks.AbstractNativeSourceCompileTask;
import org.gradle.model.ModelMap;
import edu.wpi.first.toolchain.ToolchainExtension
import org.gradle.model.Mutate;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec;
import org.gradle.model.RuleSource;
import org.gradle.model.Validate;
import org.gradle.nativeplatform.NativeExecutableBinarySpec
import org.gradle.nativeplatform.NativeBinarySpec;
import org.gradle.nativeplatform.NativeComponentSpec;
import org.gradle.nativeplatform.NativeLibrarySpec;
import org.gradle.nativeplatform.SharedLibraryBinarySpec;
import org.gradle.nativeplatform.StaticLibraryBinarySpec;
import org.gradle.nativeplatform.platform.internal.NativePlatformInternal;
import org.gradle.nativeplatform.toolchain.NativeToolChain;
import org.gradle.nativeplatform.toolchain.NativeToolChainRegistry;
import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider;
import org.gradle.nativeplatform.toolchain.internal.ToolType;
import org.gradle.nativeplatform.toolchain.internal.gcc.AbstractGccCompatibleToolChain;
import org.gradle.nativeplatform.toolchain.internal.msvcpp.VisualCppToolChain;
import org.gradle.nativeplatform.toolchain.internal.tools.ToolRegistry;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.ComponentSpec;
import org.gradle.platform.base.ComponentSpecContainer;
import org.gradle.platform.base.BinaryContainer;
import org.gradle.platform.base.ComponentType;
import org.gradle.platform.base.TypeBuilder;
import org.gradle.nativeplatform.tasks.ObjectFilesToBinary;
import groovy.transform.CompileStatic;
import groovy.transform.CompileDynamic
import org.gradle.nativeplatform.BuildTypeContainer
@CompileStatic
class DisableBuildingGTest implements Plugin<Project> {
@CompileStatic
public void apply(Project project) {
}
@CompileStatic
static class Rules extends RuleSource {
@CompileDynamic
private static void setBuildableFalseDynamically(NativeBinarySpec binary) {
binary.buildable = false
}
@Validate
@CompileStatic
// TODO: Move this to tc plugin
void disableCrossTests(BinaryContainer binaries, ExtensionContainer extContainer) {
final ToolchainExtension ext = extContainer.getByType(ToolchainExtension.class);
for (GoogleTestTestSuiteBinarySpec binary : binaries.withType(GoogleTestTestSuiteBinarySpec.class)) {
if (ext.getCrossCompilers().findByName(binary.getTargetPlatform().getName()) != null) {
setBuildableFalseDynamically(binary)
}
}
}
}
}

View File

@@ -0,0 +1,88 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.FileTree;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.language.base.internal.ProjectLayout;
import org.gradle.language.base.plugins.ComponentModelBasePlugin;
import org.gradle.language.nativeplatform.tasks.AbstractNativeSourceCompileTask;
import org.gradle.model.ModelMap;
import org.gradle.model.Mutate;
import org.gradle.model.RuleSource;
import org.gradle.model.Validate;
import org.gradle.nativeplatform.NativeBinarySpec;
import org.gradle.nativeplatform.NativeComponentSpec;
import org.gradle.nativeplatform.NativeLibrarySpec;
import org.gradle.nativeplatform.SharedLibraryBinarySpec;
import org.gradle.nativeplatform.StaticLibraryBinarySpec;
import org.gradle.nativeplatform.platform.internal.NativePlatformInternal;
import org.gradle.nativeplatform.toolchain.NativeToolChain;
import org.gradle.nativeplatform.toolchain.NativeToolChainRegistry;
import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider;
import org.gradle.nativeplatform.toolchain.internal.ToolType;
import org.gradle.nativeplatform.toolchain.internal.gcc.AbstractGccCompatibleToolChain;
import org.gradle.nativeplatform.toolchain.internal.msvcpp.VisualCppToolChain;
import org.gradle.nativeplatform.toolchain.internal.tools.ToolRegistry;
import org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.ComponentSpec;
import org.gradle.platform.base.ComponentSpecContainer;
import org.gradle.platform.base.ComponentType;
import org.gradle.platform.base.TypeBuilder;
import org.gradle.nativeplatform.test.tasks.RunTestExecutable;
import org.gradle.platform.base.BinaryContainer;
import groovy.transform.CompileStatic;
@CompileStatic
class ExtraTasks implements Plugin<Project> {
@CompileStatic
public void apply(Project project) {
}
@CompileStatic
static class Rules extends RuleSource {
@Mutate
@CompileStatic
void createNativeCompileTask(ModelMap<Task> tasks, BinaryContainer binaries) {
tasks.create('compileCpp', Task) { oTask ->
def task = (Task) oTask
task.group = 'build'
task.description = 'Uber task to compile all native code for this project'
binaries.each { binary ->
if (binary instanceof NativeBinarySpec && binary.buildable) {
binary.tasks.withType(AbstractNativeSourceCompileTask) { compileTask ->
task.dependsOn compileTask
}
}
}
}
}
@Mutate
@CompileStatic
void createNativeTestTask(ModelMap<Task> tasks, BinaryContainer binaries) {
tasks.create('testCpp', Task) { oTask ->
def task = (Task) oTask
task.group = 'build'
task.description = 'Uber task to run all native tests for project'
binaries.each { binary ->
if (binary instanceof GoogleTestTestSuiteBinarySpec && binary.buildable) {
binary.tasks.withType(RunTestExecutable) { testTask ->
task.dependsOn testTask
}
}
}
}
}
}
}

View File

@@ -0,0 +1,48 @@
import groovy.transform.CompileStatic
import javax.inject.Inject
import jaci.gradle.deploy.artifact.MavenArtifact
import jaci.gradle.deploy.context.DeployContext
import org.gradle.api.Project
import jaci.gradle.ActionWrapper
import java.util.function.Function
@CompileStatic
class JREArtifact extends MavenArtifact {
Function<DeployContext, Boolean> buildRequiresJre = (Function<DeployContext, Boolean>){ true }
void setJreDependency(String dep) {
dependency = project.dependencies.add(configuration(), dep)
}
@Inject
JREArtifact(String name, Project project) {
super(name, project)
configuration = project.configurations.create(configuration())
onlyIf = { DeployContext ctx ->
(buildRequiresJre.apply(ctx) && jreMissing(ctx)) || project.hasProperty("force-redeploy-jre")
}
predeploy << new ActionWrapper({ DeployContext ctx ->
ctx.logger.log('Deploying RoboRIO JRE (this will take a while)...')
})
directory = '/tmp'
filename = 'frcjre.ipk'
postdeploy << new ActionWrapper({ DeployContext ctx ->
ctx.logger.log('Installing JRE...')
ctx.execute('opkg remove frc2020-openjdk*; opkg install /tmp/frcjre.ipk; rm /tmp/frcjre.ipk')
ctx.logger.log('JRE Deployed!')
})
}
String configuration() {
return name + 'frcjre'
}
boolean jreMissing(DeployContext ctx) {
return ctx.execute('if [[ -f "/usr/local/frc/JRE/bin/java" ]]; then echo OK; else echo MISSING; fi').result.contains("MISSING")
}
}

View File

@@ -0,0 +1,74 @@
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.FileTree;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.language.base.internal.ProjectLayout;
import org.gradle.language.base.plugins.ComponentModelBasePlugin;
import org.gradle.language.nativeplatform.tasks.AbstractNativeSourceCompileTask;
import org.gradle.model.ModelMap;
import edu.wpi.first.toolchain.ToolchainExtension
import org.gradle.model.Mutate;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec;
import org.gradle.model.RuleSource;
import org.gradle.model.Validate;
import org.gradle.nativeplatform.test.tasks.RunTestExecutable
import org.gradle.nativeplatform.NativeExecutableBinarySpec
import org.gradle.nativeplatform.NativeBinarySpec;
import org.gradle.nativeplatform.NativeComponentSpec;
import org.gradle.nativeplatform.NativeLibrarySpec;
import org.gradle.nativeplatform.SharedLibraryBinarySpec;
import org.gradle.nativeplatform.StaticLibraryBinarySpec;
import org.gradle.nativeplatform.platform.internal.NativePlatformInternal;
import org.gradle.nativeplatform.toolchain.NativeToolChain;
import org.gradle.nativeplatform.toolchain.NativeToolChainRegistry;
import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider;
import org.gradle.nativeplatform.toolchain.internal.ToolType;
import org.gradle.nativeplatform.toolchain.internal.gcc.AbstractGccCompatibleToolChain;
import org.gradle.nativeplatform.toolchain.internal.msvcpp.VisualCppToolChain;
import org.gradle.nativeplatform.toolchain.internal.tools.ToolRegistry;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.ComponentSpec;
import org.gradle.platform.base.ComponentSpecContainer;
import org.gradle.platform.base.BinaryContainer;
import org.gradle.platform.base.ComponentType;
import org.gradle.platform.base.TypeBuilder;
import org.gradle.nativeplatform.tasks.ObjectFilesToBinary;
import groovy.transform.CompileStatic;
import groovy.transform.CompileDynamic
import org.gradle.nativeplatform.BuildTypeContainer
@CompileStatic
class MultiBuilds implements Plugin<Project> {
@CompileStatic
public void apply(Project project) {
}
@CompileStatic
static class Rules extends RuleSource {
@CompileDynamic
private static void setBuildableFalseDynamically(NativeBinarySpec binary) {
binary.buildable = false
}
@Mutate
@CompileStatic
void disableReleaseGoogleTest(BinaryContainer binaries, ProjectLayout projectLayout) {
def project = (Project) projectLayout.projectIdentifier
if (project.hasProperty('testRelease')) {
return
}
binaries.withType(GoogleTestTestSuiteBinarySpec) { oSpec ->
GoogleTestTestSuiteBinarySpec spec = (GoogleTestTestSuiteBinarySpec) oSpec
if (spec.buildType.name == 'release') {
Rules.setBuildableFalseDynamically(spec)
}
}
}
}
}

View File

@@ -0,0 +1,133 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.FileTree;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.language.base.internal.ProjectLayout;
import org.gradle.language.base.plugins.ComponentModelBasePlugin;
import org.gradle.language.nativeplatform.tasks.AbstractNativeSourceCompileTask;
import org.gradle.model.ModelMap;
import org.gradle.model.Mutate;
import org.gradle.model.RuleSource;
import org.gradle.model.Validate;
import org.gradle.nativeplatform.NativeBinarySpec;
import org.gradle.nativeplatform.NativeComponentSpec;
import org.gradle.nativeplatform.NativeLibrarySpec;
import org.gradle.nativeplatform.SharedLibraryBinarySpec;
import org.gradle.nativeplatform.StaticLibraryBinarySpec;
import org.gradle.nativeplatform.platform.internal.NativePlatformInternal;
import org.gradle.nativeplatform.toolchain.NativeToolChain;
import org.gradle.nativeplatform.toolchain.NativeToolChainRegistry;
import org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider;
import org.gradle.nativeplatform.toolchain.internal.ToolType;
import org.gradle.nativeplatform.toolchain.internal.gcc.AbstractGccCompatibleToolChain;
import org.gradle.nativeplatform.toolchain.internal.msvcpp.VisualCppToolChain;
import org.gradle.nativeplatform.toolchain.internal.tools.ToolRegistry;
import org.gradle.platform.base.BinarySpec;
import org.gradle.platform.base.ComponentSpec;
import org.gradle.platform.base.ComponentSpecContainer;
import org.gradle.platform.base.BinaryContainer;
import org.gradle.platform.base.ComponentType;
import org.gradle.platform.base.TypeBuilder;
import org.gradle.nativeplatform.tasks.ObjectFilesToBinary;
import groovy.transform.CompileStatic;
import edu.wpi.first.nativeutils.tasks.ExportsGenerationTask
@CompileStatic
class SingleNativeBuild implements Plugin<Project> {
@CompileStatic
public void apply(Project project) {
}
@CompileStatic
static class Rules extends RuleSource {
@Mutate
@CompileStatic
void removeMacSystemIncludes(ModelMap<Task> tasks, BinaryContainer binaries) {
binaries.each {
if (!(it instanceof NativeBinarySpec)) {
return
}
NativeBinarySpec nativeBin = (NativeBinarySpec)it
if (nativeBin.targetPlatform.operatingSystem.isMacOsX()) {
nativeBin.tasks.withType(AbstractNativeSourceCompileTask) { AbstractNativeSourceCompileTask compileTask->
compileTask.getSystemIncludes().setFrom()
}
}
}
}
@Mutate
@CompileStatic
void setupSingleNativeBuild(ModelMap<Task> tasks, ComponentSpecContainer components, BinaryContainer binaryContainer, ProjectLayout projectLayout) {
Project project = (Project) projectLayout.projectIdentifier;
def nativeName = project.extensions.extraProperties.get('nativeName')
NativeLibrarySpec base = null
def subs = []
components.each { component ->
if (component.name == "${nativeName}Base") {
base = (NativeLibrarySpec) component
} else if (component.name == "${nativeName}" || component.name == "${nativeName}JNI") {
subs << component
}
}
subs.each {
((NativeLibrarySpec) it).binaries.each { oBinary ->
if (oBinary.buildable == false) {
return
}
NativeBinarySpec binary = (NativeBinarySpec) oBinary
NativeBinarySpec baseBin = null
base.binaries.each { oTmpBaseBin ->
if (oTmpBaseBin.buildable == false) {
return
}
def tmpBaseBin = (NativeBinarySpec) oTmpBaseBin
if (tmpBaseBin.targetPlatform.name == binary.targetPlatform.name &&
tmpBaseBin.buildType == binary.buildType) {
baseBin = tmpBaseBin
}
}
baseBin.tasks.withType(AbstractNativeSourceCompileTask) { oCompileTask ->
def compileTask = (AbstractNativeSourceCompileTask) oCompileTask
if (binary instanceof SharedLibraryBinarySpec) {
def sBinary = (SharedLibraryBinarySpec) binary
ObjectFilesToBinary link = (ObjectFilesToBinary) sBinary.tasks.link
ExportsGenerationTask exportsTask = binary.tasks.withType(ExportsGenerationTask)[0]
if (exportsTask != null) {
exportsTask.dependsOn compileTask
}
link.dependsOn compileTask
link.inputs.dir compileTask.objectFileDir
def tree = project.fileTree(compileTask.objectFileDir)
tree.include '**/*.o'
tree.include '**/*.obj'
link.source tree
} else if (binary instanceof StaticLibraryBinarySpec) {
def sBinary = (StaticLibraryBinarySpec) binary
ObjectFilesToBinary assemble = (ObjectFilesToBinary) sBinary.tasks.createStaticLib
assemble.dependsOn compileTask
assemble.inputs.dir compileTask.objectFileDir
def tree = project.fileTree(compileTask.objectFileDir)
tree.include '**/*.o'
tree.include '**/*.obj'
assemble.source tree
}
}
}
}
}
}
}

24
cameraserver/.styleguide Normal file
View File

@@ -0,0 +1,24 @@
cppHeaderFileInclude {
\.h$
\.inc$
}
cppSrcFileInclude {
\.cpp$
}
repoRootNameOverride {
cameraserver
}
includeOtherLibs {
^hal/
^networktables/
^opencv2/
^support/
^wpi/
}
includeGuardRoots {
cameraserver/src/main/native/include/
}

View File

@@ -0,0 +1,70 @@
project(cameraserver)
include(CompileWarnings)
include(AddTest)
find_package( OpenCV REQUIRED )
# Java bindings
if (NOT WITHOUT_JAVA)
find_package(Java REQUIRED)
include(UseJava)
set(CMAKE_JAVA_COMPILE_FLAGS "-Xlint:unchecked")
#find java files, copy them locally
set(OPENCV_JAVA_INSTALL_DIR ${OpenCV_INSTALL_PATH}/share/OpenCV/java/)
find_file(OPENCV_JAR_FILE NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin NO_DEFAULT_PATH)
file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java)
add_jar(cameraserver_jar ${JAVA_SOURCES} INCLUDE_JARS wpiutil_jar cscore_jar ntcore_jar ${OPENCV_JAR_FILE} OUTPUT_NAME cameraserver)
get_property(CAMERASERVER_JAR_FILE TARGET cameraserver_jar PROPERTY JAR_FILE)
install(FILES ${CAMERASERVER_JAR_FILE} DESTINATION "${java_lib_dest}")
set_property(TARGET cameraserver_jar PROPERTY FOLDER "java")
endif()
file(GLOB_RECURSE
cameraserver_native_src src/main/native/cpp/*.cpp)
add_library(cameraserver ${cameraserver_native_src})
set_target_properties(cameraserver PROPERTIES DEBUG_POSTFIX "d")
target_include_directories(cameraserver PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/main/native/include>
$<INSTALL_INTERFACE:${include_dest}/cameraserver>)
wpilib_target_warnings(cameraserver)
target_link_libraries(cameraserver PUBLIC ntcore cscore wpiutil ${OpenCV_LIBS})
set_property(TARGET cameraserver PROPERTY FOLDER "libraries")
install(TARGETS cameraserver EXPORT cameraserver DESTINATION "${main_lib_dest}")
install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/cameraserver")
if (NOT WITHOUT_JAVA AND MSVC)
install(TARGETS cameraserver RUNTIME DESTINATION "${jni_lib_dest}" COMPONENT Runtime)
endif()
if (MSVC OR FLAT_INSTALL_WPILIB)
set (cameraserver_config_dir ${wpilib_dest})
else()
set (cameraserver_config_dir share/cameraserver)
endif()
configure_file(cameraserver-config.cmake.in ${CMAKE_BINARY_DIR}/cameraserver-config.cmake )
install(FILES ${CMAKE_BINARY_DIR}/cameraserver-config.cmake DESTINATION ${cameraserver_config_dir})
install(EXPORT cameraserver DESTINATION ${cameraserver_config_dir})
file(GLOB multiCameraServer_src multiCameraServer/src/main/native/cpp/*.cpp)
add_executable(multiCameraServer ${multiCameraServer_src})
wpilib_target_warnings(multiCameraServer)
target_link_libraries(multiCameraServer cameraserver)
set_property(TARGET multiCameraServer PROPERTY FOLDER "examples")
if (WITH_TESTS)
wpilib_add_test(cameraserver src/test/native/cpp)
target_link_libraries(cameraserver_test cameraserver gtest)
endif()

77
cameraserver/build.gradle Normal file
View File

@@ -0,0 +1,77 @@
ext {
nativeName = 'cameraserver'
devMain = 'edu.wpi.first.cameraserver.DevMain'
}
evaluationDependsOn(':ntcore')
evaluationDependsOn(':cscore')
evaluationDependsOn(':hal')
apply from: "${rootDir}/shared/javacpp/setupBuild.gradle"
dependencies {
implementation project(':wpiutil')
implementation project(':ntcore')
implementation project(':cscore')
devImplementation project(':wpiutil')
devImplementation project(':ntcore')
devImplementation project(':cscore')
}
ext {
sharedCvConfigs = [cameraserver : [],
cameraserverBase: [],
cameraserverDev : [],
cameraserverTest: []]
staticCvConfigs = [:]
useJava = true
useCpp = true
}
apply from: "${rootDir}/shared/opencv.gradle"
nativeUtils.exportsConfigs {
cameraserver {
x86ExcludeSymbols = ['_CT??_R0?AV_System_error', '_CT??_R0?AVexception', '_CT??_R0?AVfailure',
'_CT??_R0?AVruntime_error', '_CT??_R0?AVsystem_error', '_CTA5?AVfailure',
'_TI5?AVfailure', '_CT??_R0?AVout_of_range', '_CTA3?AVout_of_range',
'_TI3?AVout_of_range', '_CT??_R0?AVbad_cast']
x64ExcludeSymbols = ['_CT??_R0?AV_System_error', '_CT??_R0?AVexception', '_CT??_R0?AVfailure',
'_CT??_R0?AVruntime_error', '_CT??_R0?AVsystem_error', '_CTA5?AVfailure',
'_TI5?AVfailure', '_CT??_R0?AVout_of_range', '_CTA3?AVout_of_range',
'_TI3?AVout_of_range', '_CT??_R0?AVbad_cast']
}
}
model {
components {}
binaries {
all {
if (!it.buildable || !(it instanceof NativeBinarySpec)) {
return
}
lib project: ':ntcore', library: 'ntcore', linkage: 'shared'
lib project: ':cscore', library: 'cscore', linkage: 'shared'
lib project: ':wpiutil', library: 'wpiutil', linkage: 'shared'
}
}
tasks {
def c = $.components
def found = false
def systemArch = getCurrentArch()
c.each {
if (it in NativeExecutableSpec && it.name == "${nativeName}Dev") {
it.binaries.each {
if (!found) {
def arch = it.targetPlatform.name
if (arch == systemArch) {
def filePath = it.tasks.install.installDirectory.get().toString() + File.separatorChar + 'lib'
found = true
}
}
}
}
}
}
}

View File

@@ -0,0 +1,8 @@
include(CMakeFindDependencyMacro)
@FILENAME_DEP_REPLACE@
@WPIUTIL_DEP_REPLACE@
@NTCORE_DEP_REPLACE@
@CSCORE_DEP_REPLACE@
find_dependency(OpenCV)
include(${SELF_DIR}/cameraserver.cmake)

View File

@@ -0,0 +1,62 @@
plugins {
id 'java'
id 'application'
id 'cpp'
id 'visual-studio'
}
apply plugin: 'edu.wpi.first.NativeUtils'
apply from: "${rootDir}/shared/config.gradle"
ext {
staticCvConfigs = [multiCameraServerCpp: []]
useJava = true
useCpp = true
skipDev = true
}
apply from: "${rootDir}/shared/opencv.gradle"
mainClassName = 'Main'
apply plugin: 'com.github.johnrengelman.shadow'
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
implementation project(':wpiutil')
implementation project(':ntcore')
implementation project(':cscore')
implementation project(':cameraserver')
}
model {
components {
multiCameraServerCpp(NativeExecutableSpec) {
targetBuildTypes 'release'
sources {
cpp {
source {
srcDirs = ['src/main/native/cpp']
includes = ['**/*.cpp']
}
exportedHeaders {
srcDirs = ['src/main/native/include']
includes = ['**/*.h']
}
}
}
binaries.all { binary ->
lib project: ':cameraserver', library: 'cameraserver', linkage: 'static'
lib project: ':ntcore', library: 'ntcore', linkage: 'static'
lib project: ':cscore', library: 'cscore', linkage: 'static'
lib project: ':wpiutil', library: 'wpiutil', linkage: 'static'
}
}
}
}

View File

@@ -0,0 +1,211 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import edu.wpi.cscore.VideoSource;
import edu.wpi.first.cameraserver.CameraServer;
import edu.wpi.first.networktables.NetworkTableInstance;
/*
JSON format:
{
"team": <team number>,
"ntmode": <"client" or "server", "client" if unspecified>
"cameras": [
{
"name": <camera name>
"path": <path, e.g. "/dev/video0">
"pixel format": <"MJPEG", "YUYV", etc> // optional
"width": <video mode width> // optional
"height": <video mode height> // optional
"fps": <video mode fps> // optional
"brightness": <percentage brightness> // optional
"white balance": <"auto", "hold", value> // optional
"exposure": <"auto", "hold", value> // optional
"properties": [ // optional
{
"name": <property name>
"value": <property value>
}
]
}
]
}
*/
public final class Main {
private static String configFile = "/boot/frc.json";
@SuppressWarnings("MemberName")
public static class CameraConfig {
public String name;
public String path;
public JsonObject config;
}
public static int team;
public static boolean server;
public static List<CameraConfig> cameras = new ArrayList<>();
private Main() {
}
/**
* Report parse error.
*/
public static void parseError(String str) {
System.err.println("config error in '" + configFile + "': " + str);
}
/**
* Read single camera configuration.
*/
public static boolean readCameraConfig(JsonObject config) {
CameraConfig cam = new CameraConfig();
// name
JsonElement nameElement = config.get("name");
if (nameElement == null) {
parseError("could not read camera name");
return false;
}
cam.name = nameElement.getAsString();
// path
JsonElement pathElement = config.get("path");
if (pathElement == null) {
parseError("camera '" + cam.name + "': could not read path");
return false;
}
cam.path = pathElement.getAsString();
cam.config = config;
cameras.add(cam);
return true;
}
/**
* Read configuration file.
*/
@SuppressWarnings("PMD.CyclomaticComplexity")
public static boolean readConfig() {
// parse file
JsonElement top;
try {
top = new JsonParser().parse(Files.newBufferedReader(Paths.get(configFile)));
} catch (IOException ex) {
System.err.println("could not open '" + configFile + "': " + ex);
return false;
}
// top level must be an object
if (!top.isJsonObject()) {
parseError("must be JSON object");
return false;
}
JsonObject obj = top.getAsJsonObject();
// team number
JsonElement teamElement = obj.get("team");
if (teamElement == null) {
parseError("could not read team number");
return false;
}
team = teamElement.getAsInt();
// ntmode (optional)
if (obj.has("ntmode")) {
String str = obj.get("ntmode").getAsString();
if ("client".equalsIgnoreCase(str)) {
server = false;
} else if ("server".equalsIgnoreCase(str)) {
server = true;
} else {
parseError("could not understand ntmode value '" + str + "'");
}
}
// cameras
JsonElement camerasElement = obj.get("cameras");
if (camerasElement == null) {
parseError("could not read cameras");
return false;
}
JsonArray cameras = camerasElement.getAsJsonArray();
for (JsonElement camera : cameras) {
if (!readCameraConfig(camera.getAsJsonObject())) {
return false;
}
}
return true;
}
/**
* Start running the camera.
*/
public static void startCamera(CameraConfig config) {
System.out.println("Starting camera '" + config.name + "' on " + config.path);
VideoSource camera = CameraServer.getInstance().startAutomaticCapture(
config.name, config.path);
Gson gson = new GsonBuilder().create();
camera.setConfigJson(gson.toJson(config.config));
}
/**
* Main.
*/
public static void main(String... args) {
if (args.length > 0) {
configFile = args[0];
}
// read configuration
if (!readConfig()) {
return;
}
// start NetworkTables
NetworkTableInstance ntinst = NetworkTableInstance.getDefault();
if (server) {
System.out.println("Setting up NetworkTables server");
ntinst.startServer();
} else {
System.out.println("Setting up NetworkTables client for team " + team);
ntinst.startClientTeam(team);
}
// start cameras
for (CameraConfig camera : cameras) {
startCamera(camera);
}
// loop forever
for (;;) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
return;
}
}
}
}

View File

@@ -0,0 +1,190 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include <cstdio>
#include <string>
#include <vector>
#include <networktables/NetworkTableInstance.h>
#include <wpi/StringRef.h>
#include <wpi/json.h>
#include <wpi/raw_istream.h>
#include <wpi/raw_ostream.h>
#include "cameraserver/CameraServer.h"
/*
JSON format:
{
"team": <team number>,
"ntmode": <"client" or "server", "client" if unspecified>
"cameras": [
{
"name": <camera name>
"path": <path, e.g. "/dev/video0">
"pixel format": <"MJPEG", "YUYV", etc> // optional
"width": <video mode width> // optional
"height": <video mode height> // optional
"fps": <video mode fps> // optional
"brightness": <percentage brightness> // optional
"white balance": <"auto", "hold", value> // optional
"exposure": <"auto", "hold", value> // optional
"properties": [ // optional
{
"name": <property name>
"value": <property value>
}
]
}
]
}
*/
#ifdef __RASPBIAN__
static const char* configFile = "/boot/frc.json";
#else
static const char* configFile = "frc.json";
#endif
namespace {
unsigned int team;
bool server = false;
struct CameraConfig {
std::string name;
std::string path;
wpi::json config;
};
std::vector<CameraConfig> cameras;
wpi::raw_ostream& ParseError() {
return wpi::errs() << "config error in '" << configFile << "': ";
}
bool ReadCameraConfig(const wpi::json& config) {
CameraConfig c;
// name
try {
c.name = config.at("name").get<std::string>();
} catch (const wpi::json::exception& e) {
ParseError() << "could not read camera name: " << e.what() << '\n';
return false;
}
// path
try {
c.path = config.at("path").get<std::string>();
} catch (const wpi::json::exception& e) {
ParseError() << "camera '" << c.name
<< "': could not read path: " << e.what() << '\n';
return false;
}
c.config = config;
cameras.emplace_back(std::move(c));
return true;
}
bool ReadConfig() {
// open config file
std::error_code ec;
wpi::raw_fd_istream is(configFile, ec);
if (ec) {
wpi::errs() << "could not open '" << configFile << "': " << ec.message()
<< '\n';
return false;
}
// parse file
wpi::json j;
try {
j = wpi::json::parse(is);
} catch (const wpi::json::parse_error& e) {
ParseError() << "byte " << e.byte << ": " << e.what() << '\n';
return false;
}
// top level must be an object
if (!j.is_object()) {
ParseError() << "must be JSON object\n";
return false;
}
// team number
try {
team = j.at("team").get<unsigned int>();
} catch (const wpi::json::exception& e) {
ParseError() << "could not read team number: " << e.what() << '\n';
return false;
}
// ntmode (optional)
if (j.count("ntmode") != 0) {
try {
auto str = j.at("ntmode").get<std::string>();
wpi::StringRef s(str);
if (s.equals_lower("client")) {
server = false;
} else if (s.equals_lower("server")) {
server = true;
} else {
ParseError() << "could not understand ntmode value '" << str << "'\n";
}
} catch (const wpi::json::exception& e) {
ParseError() << "could not read ntmode: " << e.what() << '\n';
}
}
// cameras
try {
for (auto&& camera : j.at("cameras")) {
if (!ReadCameraConfig(camera)) return false;
}
} catch (const wpi::json::exception& e) {
ParseError() << "could not read cameras: " << e.what() << '\n';
return false;
}
return true;
}
void StartCamera(const CameraConfig& config) {
wpi::outs() << "Starting camera '" << config.name << "' on " << config.path
<< '\n';
auto camera = frc::CameraServer::GetInstance()->StartAutomaticCapture(
config.name, config.path);
camera.SetConfigJson(config.config);
}
} // namespace
int main(int argc, char* argv[]) {
if (argc >= 2) configFile = argv[1];
// read configuration
if (!ReadConfig()) return EXIT_FAILURE;
// start NetworkTables
auto ntinst = nt::NetworkTableInstance::GetDefault();
if (server) {
wpi::outs() << "Setting up NetworkTables server\n";
ntinst.StartServer();
} else {
wpi::outs() << "Setting up NetworkTables client for team " << team << '\n';
ntinst.StartClientTeam(team);
}
// start cameras
for (auto&& camera : cameras) StartCamera(camera);
// loop forever
for (;;) std::this_thread::sleep_for(std::chrono::seconds(10));
}

View File

@@ -0,0 +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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.cameraserver;
public final class DevMain {
public static void main(String[] args) {
}
private DevMain() {
}
}

View File

@@ -0,0 +1,8 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
int main() {}

View File

@@ -0,0 +1,802 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.cameraserver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import edu.wpi.cscore.AxisCamera;
import edu.wpi.cscore.CameraServerJNI;
import edu.wpi.cscore.CvSink;
import edu.wpi.cscore.CvSource;
import edu.wpi.cscore.MjpegServer;
import edu.wpi.cscore.UsbCamera;
import edu.wpi.cscore.VideoEvent;
import edu.wpi.cscore.VideoException;
import edu.wpi.cscore.VideoListener;
import edu.wpi.cscore.VideoMode;
import edu.wpi.cscore.VideoMode.PixelFormat;
import edu.wpi.cscore.VideoProperty;
import edu.wpi.cscore.VideoSink;
import edu.wpi.cscore.VideoSource;
import edu.wpi.first.networktables.EntryListenerFlags;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
/**
* Singleton class for creating and keeping camera servers.
* Also publishes camera information to NetworkTables.
*/
@SuppressWarnings("PMD.TooManyMethods")
public final class CameraServer {
public static final int kBasePort = 1181;
@Deprecated
public static final int kSize640x480 = 0;
@Deprecated
public static final int kSize320x240 = 1;
@Deprecated
public static final int kSize160x120 = 2;
private static final String kPublishName = "/CameraPublisher";
private static CameraServer server;
/**
* Get the CameraServer instance.
*/
public static synchronized CameraServer getInstance() {
if (server == null) {
server = new CameraServer();
}
return server;
}
private final AtomicInteger m_defaultUsbDevice;
private String m_primarySourceName;
private final Map<String, VideoSource> m_sources;
private final Map<String, VideoSink> m_sinks;
private final Map<Integer, NetworkTable> m_tables; // indexed by source handle
// source handle indexed by sink handle
private final Map<Integer, Integer> m_fixedSources;
private final NetworkTable m_publishTable;
private final VideoListener m_videoListener; //NOPMD
private final int m_tableListener; //NOPMD
private int m_nextPort;
private String[] m_addresses;
@SuppressWarnings("JavadocMethod")
private static String makeSourceValue(int source) {
switch (VideoSource.getKindFromInt(CameraServerJNI.getSourceKind(source))) {
case kUsb:
return "usb:" + CameraServerJNI.getUsbCameraPath(source);
case kHttp: {
String[] urls = CameraServerJNI.getHttpCameraUrls(source);
if (urls.length > 0) {
return "ip:" + urls[0];
} else {
return "ip:";
}
}
case kCv:
return "cv:";
default:
return "unknown:";
}
}
@SuppressWarnings("JavadocMethod")
private static String makeStreamValue(String address, int port) {
return "mjpg:http://" + address + ":" + port + "/?action=stream";
}
@SuppressWarnings({"JavadocMethod", "PMD.AvoidUsingHardCodedIP"})
private synchronized String[] getSinkStreamValues(int sink) {
// Ignore all but MjpegServer
if (VideoSink.getKindFromInt(CameraServerJNI.getSinkKind(sink)) != VideoSink.Kind.kMjpeg) {
return new String[0];
}
// Get port
int port = CameraServerJNI.getMjpegServerPort(sink);
// Generate values
ArrayList<String> values = new ArrayList<>(m_addresses.length + 1);
String listenAddress = CameraServerJNI.getMjpegServerListenAddress(sink);
if (!listenAddress.isEmpty()) {
// If a listen address is specified, only use that
values.add(makeStreamValue(listenAddress, port));
} else {
// Otherwise generate for hostname and all interface addresses
values.add(makeStreamValue(CameraServerJNI.getHostname() + ".local", port));
for (String addr : m_addresses) {
if ("127.0.0.1".equals(addr)) {
continue; // ignore localhost
}
values.add(makeStreamValue(addr, port));
}
}
return values.toArray(new String[0]);
}
@SuppressWarnings({"JavadocMethod", "PMD.AvoidUsingHardCodedIP"})
private synchronized String[] getSourceStreamValues(int source) {
// Ignore all but HttpCamera
if (VideoSource.getKindFromInt(CameraServerJNI.getSourceKind(source))
!= VideoSource.Kind.kHttp) {
return new String[0];
}
// Generate values
String[] values = CameraServerJNI.getHttpCameraUrls(source);
for (int j = 0; j < values.length; j++) {
values[j] = "mjpg:" + values[j];
}
if (CameraServerSharedStore.getCameraServerShared().isRoboRIO()) {
// Look to see if we have a passthrough server for this source
// Only do this on the roboRIO
for (VideoSink i : m_sinks.values()) {
int sink = i.getHandle();
int sinkSource = CameraServerJNI.getSinkSource(sink);
if (source == sinkSource
&& VideoSink.getKindFromInt(CameraServerJNI.getSinkKind(sink))
== VideoSink.Kind.kMjpeg) {
// Add USB-only passthrough
String[] finalValues = Arrays.copyOf(values, values.length + 1);
int port = CameraServerJNI.getMjpegServerPort(sink);
finalValues[values.length] = makeStreamValue("172.22.11.2", port);
return finalValues;
}
}
}
return values;
}
@SuppressWarnings({"JavadocMethod", "PMD.AvoidUsingHardCodedIP", "PMD.CyclomaticComplexity"})
private synchronized void updateStreamValues() {
// Over all the sinks...
for (VideoSink i : m_sinks.values()) {
int sink = i.getHandle();
// Get the source's subtable (if none exists, we're done)
int source = Objects.requireNonNullElseGet(m_fixedSources.get(sink),
() -> CameraServerJNI.getSinkSource(sink));
if (source == 0) {
continue;
}
NetworkTable table = m_tables.get(source);
if (table != null) {
// Don't set stream values if this is a HttpCamera passthrough
if (VideoSource.getKindFromInt(CameraServerJNI.getSourceKind(source))
== VideoSource.Kind.kHttp) {
continue;
}
// Set table value
String[] values = getSinkStreamValues(sink);
if (values.length > 0) {
table.getEntry("streams").setStringArray(values);
}
}
}
// Over all the sources...
for (VideoSource i : m_sources.values()) {
int source = i.getHandle();
// Get the source's subtable (if none exists, we're done)
NetworkTable table = m_tables.get(source);
if (table != null) {
// Set table value
String[] values = getSourceStreamValues(source);
if (values.length > 0) {
table.getEntry("streams").setStringArray(values);
}
}
}
}
@SuppressWarnings("JavadocMethod")
private static String pixelFormatToString(PixelFormat pixelFormat) {
switch (pixelFormat) {
case kMJPEG:
return "MJPEG";
case kYUYV:
return "YUYV";
case kRGB565:
return "RGB565";
case kBGR:
return "BGR";
case kGray:
return "Gray";
default:
return "Unknown";
}
}
/// Provide string description of video mode.
/// The returned string is "{width}x{height} {format} {fps} fps".
@SuppressWarnings("JavadocMethod")
private static String videoModeToString(VideoMode mode) {
return mode.width + "x" + mode.height + " " + pixelFormatToString(mode.pixelFormat)
+ " " + mode.fps + " fps";
}
@SuppressWarnings("JavadocMethod")
private static String[] getSourceModeValues(int sourceHandle) {
VideoMode[] modes = CameraServerJNI.enumerateSourceVideoModes(sourceHandle);
String[] modeStrings = new String[modes.length];
for (int i = 0; i < modes.length; i++) {
modeStrings[i] = videoModeToString(modes[i]);
}
return modeStrings;
}
@SuppressWarnings({"JavadocMethod", "PMD.CyclomaticComplexity"})
private static void putSourcePropertyValue(NetworkTable table, VideoEvent event, boolean isNew) {
String name;
String infoName;
if (event.name.startsWith("raw_")) {
name = "RawProperty/" + event.name;
infoName = "RawPropertyInfo/" + event.name;
} else {
name = "Property/" + event.name;
infoName = "PropertyInfo/" + event.name;
}
NetworkTableEntry entry = table.getEntry(name);
try {
switch (event.propertyKind) {
case kBoolean:
if (isNew) {
entry.setDefaultBoolean(event.value != 0);
} else {
entry.setBoolean(event.value != 0);
}
break;
case kInteger:
case kEnum:
if (isNew) {
entry.setDefaultDouble(event.value);
table.getEntry(infoName + "/min").setDouble(
CameraServerJNI.getPropertyMin(event.propertyHandle));
table.getEntry(infoName + "/max").setDouble(
CameraServerJNI.getPropertyMax(event.propertyHandle));
table.getEntry(infoName + "/step").setDouble(
CameraServerJNI.getPropertyStep(event.propertyHandle));
table.getEntry(infoName + "/default").setDouble(
CameraServerJNI.getPropertyDefault(event.propertyHandle));
} else {
entry.setDouble(event.value);
}
break;
case kString:
if (isNew) {
entry.setDefaultString(event.valueStr);
} else {
entry.setString(event.valueStr);
}
break;
default:
break;
}
} catch (VideoException ignored) {
// ignore
}
}
@SuppressWarnings({"JavadocMethod", "PMD.UnusedLocalVariable", "PMD.ExcessiveMethodLength",
"PMD.NPathComplexity"})
private CameraServer() {
m_defaultUsbDevice = new AtomicInteger();
m_sources = new HashMap<>();
m_sinks = new HashMap<>();
m_fixedSources = new HashMap<>();
m_tables = new HashMap<>();
m_publishTable = NetworkTableInstance.getDefault().getTable(kPublishName);
m_nextPort = kBasePort;
m_addresses = new String[0];
// We publish sources to NetworkTables using the following structure:
// "/CameraPublisher/{Source.Name}/" - root
// - "source" (string): Descriptive, prefixed with type (e.g. "usb:0")
// - "streams" (string array): URLs that can be used to stream data
// - "description" (string): Description of the source
// - "connected" (boolean): Whether source is connected
// - "mode" (string): Current video mode
// - "modes" (string array): Available video modes
// - "Property/{Property}" - Property values
// - "PropertyInfo/{Property}" - Property supporting information
// Listener for video events
m_videoListener = new VideoListener(event -> {
switch (event.kind) {
case kSourceCreated: {
// Create subtable for the camera
NetworkTable table = m_publishTable.getSubTable(event.name);
m_tables.put(event.sourceHandle, table);
table.getEntry("source").setString(makeSourceValue(event.sourceHandle));
table.getEntry("description").setString(
CameraServerJNI.getSourceDescription(event.sourceHandle));
table.getEntry("connected").setBoolean(
CameraServerJNI.isSourceConnected(event.sourceHandle));
table.getEntry("streams").setStringArray(getSourceStreamValues(event.sourceHandle));
try {
VideoMode mode = CameraServerJNI.getSourceVideoMode(event.sourceHandle);
table.getEntry("mode").setDefaultString(videoModeToString(mode));
table.getEntry("modes").setStringArray(getSourceModeValues(event.sourceHandle));
} catch (VideoException ignored) {
// Do nothing. Let the other event handlers update this if there is an error.
}
break;
}
case kSourceDestroyed: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("source").setString("");
table.getEntry("streams").setStringArray(new String[0]);
table.getEntry("modes").setStringArray(new String[0]);
}
break;
}
case kSourceConnected: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
// update the description too (as it may have changed)
table.getEntry("description").setString(
CameraServerJNI.getSourceDescription(event.sourceHandle));
table.getEntry("connected").setBoolean(true);
}
break;
}
case kSourceDisconnected: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("connected").setBoolean(false);
}
break;
}
case kSourceVideoModesUpdated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("modes").setStringArray(getSourceModeValues(event.sourceHandle));
}
break;
}
case kSourceVideoModeChanged: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
table.getEntry("mode").setString(videoModeToString(event.mode));
}
break;
}
case kSourcePropertyCreated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
putSourcePropertyValue(table, event, true);
}
break;
}
case kSourcePropertyValueUpdated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
putSourcePropertyValue(table, event, false);
}
break;
}
case kSourcePropertyChoicesUpdated: {
NetworkTable table = m_tables.get(event.sourceHandle);
if (table != null) {
try {
String[] choices = CameraServerJNI.getEnumPropertyChoices(event.propertyHandle);
table.getEntry("PropertyInfo/" + event.name + "/choices").setStringArray(choices);
} catch (VideoException ignored) {
// ignore
}
}
break;
}
case kSinkSourceChanged:
case kSinkCreated:
case kSinkDestroyed:
case kNetworkInterfacesChanged: {
m_addresses = CameraServerJNI.getNetworkInterfaces();
updateStreamValues();
break;
}
default:
break;
}
}, 0x4fff, true);
// Listener for NetworkTable events
// We don't currently support changing settings via NT due to
// synchronization issues, so just update to current setting if someone
// else tries to change it.
m_tableListener = NetworkTableInstance.getDefault().addEntryListener(kPublishName + "/",
event -> {
String relativeKey = event.name.substring(kPublishName.length() + 1);
// get source (sourceName/...)
int subKeyIndex = relativeKey.indexOf('/');
if (subKeyIndex == -1) {
return;
}
String sourceName = relativeKey.substring(0, subKeyIndex);
VideoSource source = m_sources.get(sourceName);
if (source == null) {
return;
}
// get subkey
relativeKey = relativeKey.substring(subKeyIndex + 1);
// handle standard names
String propName;
if ("mode".equals(relativeKey)) {
// reset to current mode
event.getEntry().setString(videoModeToString(source.getVideoMode()));
return;
} else if (relativeKey.startsWith("Property/")) {
propName = relativeKey.substring(9);
} else if (relativeKey.startsWith("RawProperty/")) {
propName = relativeKey.substring(12);
} else {
return; // ignore
}
// everything else is a property
VideoProperty property = source.getProperty(propName);
switch (property.getKind()) {
case kNone:
return;
case kBoolean:
// reset to current setting
event.getEntry().setBoolean(property.get() != 0);
return;
case kInteger:
case kEnum:
// reset to current setting
event.getEntry().setDouble(property.get());
return;
case kString:
// reset to current setting
event.getEntry().setString(property.getString());
return;
default:
return;
}
}, EntryListenerFlags.kImmediate | EntryListenerFlags.kUpdate);
}
/**
* Start automatically capturing images to send to the dashboard.
*
* <p>You should call this method to see a camera feed on the dashboard.
* If you also want to perform vision processing on the roboRIO, use
* getVideo() to get access to the camera images.
*
* <p>The first time this overload is called, it calls
* {@link #startAutomaticCapture(int)} with device 0, creating a camera
* named "USB Camera 0". Subsequent calls increment the device number
* (e.g. 1, 2, etc).
*/
public UsbCamera startAutomaticCapture() {
UsbCamera camera = startAutomaticCapture(m_defaultUsbDevice.getAndIncrement());
CameraServerSharedStore.getCameraServerShared().reportUsbCamera(camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard.
*
* <p>This overload calls {@link #startAutomaticCapture(String, int)} with
* a name of "USB Camera {dev}".
*
* @param dev The device number of the camera interface
*/
public UsbCamera startAutomaticCapture(int dev) {
UsbCamera camera = new UsbCamera("USB Camera " + dev, dev);
startAutomaticCapture(camera);
CameraServerSharedStore.getCameraServerShared().reportUsbCamera(camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard.
*
* @param name The name to give the camera
* @param dev The device number of the camera interface
*/
public UsbCamera startAutomaticCapture(String name, int dev) {
UsbCamera camera = new UsbCamera(name, dev);
startAutomaticCapture(camera);
CameraServerSharedStore.getCameraServerShared().reportUsbCamera(camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard.
*
* @param name The name to give the camera
* @param path The device path (e.g. "/dev/video0") of the camera
*/
public UsbCamera startAutomaticCapture(String name, String path) {
UsbCamera camera = new UsbCamera(name, path);
startAutomaticCapture(camera);
CameraServerSharedStore.getCameraServerShared().reportUsbCamera(camera.getHandle());
return camera;
}
/**
* Start automatically capturing images to send to the dashboard from
* an existing camera.
*
* @param camera Camera
*/
public MjpegServer startAutomaticCapture(VideoSource camera) {
addCamera(camera);
MjpegServer server = addServer("serve_" + camera.getName());
server.setSource(camera);
return server;
}
/**
* Adds an Axis IP camera.
*
* <p>This overload calls {@link #addAxisCamera(String, String)} with
* name "Axis Camera".
*
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
public AxisCamera addAxisCamera(String host) {
return addAxisCamera("Axis Camera", host);
}
/**
* Adds an Axis IP camera.
*
* <p>This overload calls {@link #addAxisCamera(String, String[])} with
* name "Axis Camera".
*
* @param hosts Array of Camera host IPs/DNS names
*/
public AxisCamera addAxisCamera(String[] hosts) {
return addAxisCamera("Axis Camera", hosts);
}
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
public AxisCamera addAxisCamera(String name, String host) {
AxisCamera camera = new AxisCamera(name, host);
// Create a passthrough MJPEG server for USB access
startAutomaticCapture(camera);
CameraServerSharedStore.getCameraServerShared().reportAxisCamera(camera.getHandle());
return camera;
}
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param hosts Array of Camera host IPs/DNS names
*/
public AxisCamera addAxisCamera(String name, String[] hosts) {
AxisCamera camera = new AxisCamera(name, hosts);
// Create a passthrough MJPEG server for USB access
startAutomaticCapture(camera);
CameraServerSharedStore.getCameraServerShared().reportAxisCamera(camera.getHandle());
return camera;
}
/**
* Adds a virtual camera for switching between two streams. Unlike the
* other addCamera methods, this returns a VideoSink rather than a
* VideoSource. Calling setSource() on the returned object can be used
* to switch the actual source of the stream.
*/
public MjpegServer addSwitchedCamera(String name) {
// create a dummy CvSource
CvSource source = new CvSource(name, VideoMode.PixelFormat.kMJPEG, 160, 120, 30);
MjpegServer server = startAutomaticCapture(source);
synchronized (this) {
m_fixedSources.put(server.getHandle(), source.getHandle());
}
return server;
}
/**
* Get OpenCV access to the primary camera feed. This allows you to
* get images from the camera for image processing on the roboRIO.
*
* <p>This is only valid to call after a camera feed has been added
* with startAutomaticCapture() or addServer().
*/
public CvSink getVideo() {
VideoSource source;
synchronized (this) {
if (m_primarySourceName == null) {
throw new VideoException("no camera available");
}
source = m_sources.get(m_primarySourceName);
}
if (source == null) {
throw new VideoException("no camera available");
}
return getVideo(source);
}
/**
* Get OpenCV access to the specified camera. This allows you to get
* images from the camera for image processing on the roboRIO.
*
* @param camera Camera (e.g. as returned by startAutomaticCapture).
*/
public CvSink getVideo(VideoSource camera) {
String name = "opencv_" + camera.getName();
synchronized (this) {
VideoSink sink = m_sinks.get(name);
if (sink != null) {
VideoSink.Kind kind = sink.getKind();
if (kind != VideoSink.Kind.kCv) {
throw new VideoException("expected OpenCV sink, but got " + kind);
}
return (CvSink) sink;
}
}
CvSink newsink = new CvSink(name);
newsink.setSource(camera);
addServer(newsink);
return newsink;
}
/**
* Get OpenCV access to the specified camera. This allows you to get
* images from the camera for image processing on the roboRIO.
*
* @param name Camera name
*/
public CvSink getVideo(String name) {
VideoSource source;
synchronized (this) {
source = m_sources.get(name);
if (source == null) {
throw new VideoException("could not find camera " + name);
}
}
return getVideo(source);
}
/**
* Create a MJPEG stream with OpenCV input. This can be called to pass custom
* annotated images to the dashboard.
*
* @param name Name to give the stream
* @param width Width of the image being sent
* @param height Height of the image being sent
*/
public CvSource putVideo(String name, int width, int height) {
CvSource source = new CvSource(name, VideoMode.PixelFormat.kMJPEG, width, height, 30);
startAutomaticCapture(source);
return source;
}
/**
* Adds a MJPEG server at the next available port.
*
* @param name Server name
*/
public MjpegServer addServer(String name) {
int port;
synchronized (this) {
port = m_nextPort;
m_nextPort++;
}
return addServer(name, port);
}
/**
* Adds a MJPEG server.
*
* @param name Server name
*/
public MjpegServer addServer(String name, int port) {
MjpegServer server = new MjpegServer(name, port);
addServer(server);
return server;
}
/**
* Adds an already created server.
*
* @param server Server
*/
public void addServer(VideoSink server) {
synchronized (this) {
m_sinks.put(server.getName(), server);
}
}
/**
* Removes a server by name.
*
* @param name Server name
*/
public void removeServer(String name) {
synchronized (this) {
m_sinks.remove(name);
}
}
/**
* Get server for the primary camera feed.
*
* <p>This is only valid to call after a camera feed has been added
* with startAutomaticCapture() or addServer().
*/
public VideoSink getServer() {
synchronized (this) {
if (m_primarySourceName == null) {
throw new VideoException("no camera available");
}
return getServer("serve_" + m_primarySourceName);
}
}
/**
* Gets a server by name.
*
* @param name Server name
*/
public VideoSink getServer(String name) {
synchronized (this) {
return m_sinks.get(name);
}
}
/**
* Adds an already created camera.
*
* @param camera Camera
*/
public void addCamera(VideoSource camera) {
String name = camera.getName();
synchronized (this) {
if (m_primarySourceName == null) {
m_primarySourceName = name;
}
m_sources.put(name, camera);
}
}
/**
* Removes a camera by name.
*
* @param name Camera name
*/
public void removeCamera(String name) {
synchronized (this) {
m_sources.remove(name);
}
}
}

View File

@@ -0,0 +1,55 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.cameraserver;
public interface CameraServerShared {
/**
* get the main thread id func.
*
* @return the robotMainThreadId
*/
Long getRobotMainThreadId();
/**
* Report an error to the driver station.
*
* @param error the error to set
*/
void reportDriverStationError(String error);
/**
* Report an video server usage.
*
* @param id the usage id
*/
void reportVideoServer(int id);
/**
* Report a usb camera usage.
*
* @param id the usage id
*/
void reportUsbCamera(int id);
/**
* Report an axis camera usage.
*
* @param id the usage id
*/
void reportAxisCamera(int id);
/**
* Get if running on a roboRIO.
*
* @return true if on roboRIO
*/
default boolean isRoboRIO() {
return false;
}
}

View File

@@ -0,0 +1,58 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.cameraserver;
public final class CameraServerSharedStore {
private static CameraServerShared cameraServerShared;
private CameraServerSharedStore() {
}
/**
* get the CameraServerShared object.
*/
public static synchronized CameraServerShared getCameraServerShared() {
if (cameraServerShared == null) {
cameraServerShared = new CameraServerShared() {
@Override
public void reportVideoServer(int id) {
}
@Override
public void reportUsbCamera(int id) {
}
@Override
public void reportDriverStationError(String error) {
}
@Override
public void reportAxisCamera(int id) {
}
@Override
public Long getRobotMainThreadId() {
return null;
}
};
}
return cameraServerShared;
}
/**
* set the CameraServerShared object.
*/
public static synchronized void setCameraServerShared(CameraServerShared shared) {
cameraServerShared = shared;
}
}

View File

@@ -0,0 +1,26 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.vision;
import org.opencv.core.Mat;
/**
* A vision pipeline is responsible for running a group of
* OpenCV algorithms to extract data from an image.
*
* @see VisionRunner
* @see VisionThread
*/
public interface VisionPipeline {
/**
* Processes the image input and sets the result objects.
* Implementations should make these objects accessible.
*/
void process(Mat image);
}

View File

@@ -0,0 +1,128 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.vision;
import org.opencv.core.Mat;
import edu.wpi.cscore.CvSink;
import edu.wpi.cscore.VideoSource;
import edu.wpi.first.cameraserver.CameraServerSharedStore;
/**
* A vision runner is a convenient wrapper object to make it easy to run vision pipelines
* from robot code. The easiest way to use this is to run it in a {@link VisionThread}
* and use the listener to take snapshots of the pipeline's outputs.
*
* @see VisionPipeline
* @see VisionThread
* @see <a href="package-summary.html">vision</a>
*/
public class VisionRunner<P extends VisionPipeline> {
private final CvSink m_cvSink = new CvSink("VisionRunner CvSink");
private final P m_pipeline;
private final Mat m_image = new Mat();
private final Listener<? super P> m_listener;
private volatile boolean m_enabled = true;
/**
* Listener interface for a callback that should run after a pipeline has processed its input.
*
* @param <P> the type of the pipeline this listener is for
*/
@FunctionalInterface
public interface Listener<P extends VisionPipeline> {
/**
* Called when the pipeline has run. This shouldn't take much time to run because it will delay
* later calls to the pipeline's {@link VisionPipeline#process process} method. Copying the
* outputs and code that uses the copies should be <i>synchronized</i> on the same mutex to
* prevent multiple threads from reading and writing to the same memory at the same time.
*
* @param pipeline the vision pipeline that ran
*/
void copyPipelineOutputs(P pipeline);
}
/**
* Creates a new vision runner. It will take images from the {@code videoSource}, send them to
* the {@code pipeline}, and call the {@code listener} when the pipeline has finished to alert
* user code when it is safe to access the pipeline's outputs.
*
* @param videoSource the video source to use to supply images for the pipeline
* @param pipeline the vision pipeline to run
* @param listener a function to call after the pipeline has finished running
*/
public VisionRunner(VideoSource videoSource, P pipeline, Listener<? super P> listener) {
this.m_pipeline = pipeline;
this.m_listener = listener;
m_cvSink.setSource(videoSource);
}
/**
* Runs the pipeline one time, giving it the next image from the video source specified
* in the constructor. This will block until the source either has an image or throws an error.
* If the source successfully supplied a frame, the pipeline's image input will be set,
* the pipeline will run, and the listener specified in the constructor will be called to notify
* it that the pipeline ran.
*
* <p>This method is exposed to allow teams to add additional functionality or have their own
* ways to run the pipeline. Most teams, however, should just use {@link #runForever} in its own
* thread using a {@link VisionThread}.</p>
*/
public void runOnce() {
Long id = CameraServerSharedStore.getCameraServerShared().getRobotMainThreadId();
if (id != null && Thread.currentThread().getId() == id) {
throw new IllegalStateException(
"VisionRunner.runOnce() cannot be called from the main robot thread");
}
runOnceInternal();
}
private void runOnceInternal() {
long frameTime = m_cvSink.grabFrame(m_image);
if (frameTime == 0) {
// There was an error, report it
String error = m_cvSink.getError();
CameraServerSharedStore.getCameraServerShared().reportDriverStationError(error);
} else {
// No errors, process the image
m_pipeline.process(m_image);
m_listener.copyPipelineOutputs(m_pipeline);
}
}
/**
* A convenience method that calls {@link #runOnce()} in an infinite loop. This must
* be run in a dedicated thread, and cannot be used in the main robot thread because
* it will freeze the robot program.
*
* <p><strong>Do not call this method directly from the main thread.</strong></p>
*
* @throws IllegalStateException if this is called from the main robot thread
* @see VisionThread
*/
public void runForever() {
Long id = CameraServerSharedStore.getCameraServerShared().getRobotMainThreadId();
if (id != null && Thread.currentThread().getId() == id) {
throw new IllegalStateException(
"VisionRunner.runForever() cannot be called from the main robot thread");
}
while (m_enabled && !Thread.interrupted()) {
runOnceInternal();
}
}
/**
* Stop a RunForever() loop.
*/
public void stop() {
m_enabled = false;
}
}

View File

@@ -0,0 +1,47 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.vision;
import edu.wpi.cscore.VideoSource;
/**
* A vision thread is a special thread that runs a vision pipeline. It is a <i>daemon</i> thread;
* it does not prevent the program from exiting when all other non-daemon threads
* have finished running.
*
* @see VisionPipeline
* @see VisionRunner
* @see Thread#setDaemon(boolean)
*/
public class VisionThread extends Thread {
/**
* Creates a vision thread that continuously runs a {@link VisionPipeline}.
*
* @param visionRunner the runner for a vision pipeline
*/
public VisionThread(VisionRunner<?> visionRunner) {
super(visionRunner::runForever, "WPILib Vision Thread");
setDaemon(true);
}
/**
* Creates a new vision thread that continuously runs the given vision pipeline. This is
* equivalent to {@code new VisionThread(new VisionRunner<>(videoSource, pipeline, listener))}.
*
* @param videoSource the source for images the pipeline should process
* @param pipeline the pipeline to run
* @param listener the listener to copy outputs from the pipeline after it runs
* @param <P> the type of the pipeline
*/
public <P extends VisionPipeline> VisionThread(VideoSource videoSource,
P pipeline,
VisionRunner.Listener<? super P> listener) {
this(new VisionRunner<>(videoSource, pipeline, listener));
}
}

View File

@@ -0,0 +1,88 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
/**
* Classes in the {@code edu.wpi.first.vision} package are designed to
* simplify using OpenCV vision processing code from a robot program.
*
* <p>An example use case for grabbing a yellow tote from 2015 in autonomous:
* <br>
* <pre><code>
* public class Robot extends IterativeRobot
* implements VisionRunner.Listener&lt;MyFindTotePipeline&gt; {
*
* // A USB camera connected to the roboRIO.
* private {@link edu.wpi.cscore.VideoSource VideoSource} usbCamera;
*
* // A vision pipeline. This could be handwritten or generated by GRIP.
* // This has to implement {@link edu.wpi.first.vision.VisionPipeline}.
* // For this example, assume that it's perfect and will always see the tote.
* private MyFindTotePipeline findTotePipeline;
* private {@link edu.wpi.first.vision.VisionThread} findToteThread;
*
* // The object to synchronize on to make sure the vision thread doesn't
* // write to variables the main thread is using.
* private final Object visionLock = new Object();
*
* // The pipeline outputs we want
* private boolean pipelineRan = false; // lets us know when the pipeline has actually run
* private double angleToTote = 0;
* private double distanceToTote = 0;
*
* {@literal @}Override
* public void {@link edu.wpi.first.vision.VisionRunner.Listener#copyPipelineOutputs
* copyPipelineOutputs(MyFindTotePipeline pipeline)} {
* synchronized (visionLock) {
* // Take a snapshot of the pipeline's output because
* // it may have changed the next time this method is called!
* this.pipelineRan = true;
* this.angleToTote = pipeline.getAngleToTote();
* this.distanceToTote = pipeline.getDistanceToTote();
* }
* }
*
* {@literal @}Override
* public void robotInit() {
* usbCamera = CameraServer.getInstance().startAutomaticCapture(0);
* findTotePipeline = new MyFindTotePipeline();
* findToteThread = new VisionThread(usbCamera, findTotePipeline, this);
* }
*
* {@literal @}Override
* public void autonomousInit() {
* findToteThread.start();
* }
*
* {@literal @}Override
* public void autonomousPeriodic() {
* double angle;
* double distance;
* synchronized (visionLock) {
* if (!pipelineRan) {
* // Wait until the pipeline has run
* return;
* }
* // Copy the outputs to make sure they're all from the same run
* angle = this.angleToTote;
* distance = this.distanceToTote;
* }
* if (!aimedAtTote()) {
* turnToAngle(angle);
* } else if (!droveToTote()) {
* driveDistance(distance);
* } else if (!grabbedTote()) {
* grabTote();
* } else {
* // Tote was grabbed and we're done!
* return;
* }
* }
*
* }
* </code></pre>
*/
package edu.wpi.first.vision;

View File

@@ -0,0 +1,716 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "cameraserver/CameraServer.h"
#include <atomic>
#include <vector>
#include <networktables/NetworkTable.h>
#include <networktables/NetworkTableInstance.h>
#include <wpi/DenseMap.h>
#include <wpi/ManagedStatic.h>
#include <wpi/SmallString.h>
#include <wpi/StringMap.h>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#include "cameraserver/CameraServerShared.h"
#include "ntcore_cpp.h"
using namespace frc;
static constexpr char const* kPublishName = "/CameraPublisher";
struct CameraServer::Impl {
Impl();
std::shared_ptr<nt::NetworkTable> GetSourceTable(CS_Source source);
std::vector<std::string> GetSinkStreamValues(CS_Sink sink);
std::vector<std::string> GetSourceStreamValues(CS_Source source);
void UpdateStreamValues();
wpi::mutex m_mutex;
std::atomic<int> m_defaultUsbDevice{0};
std::string m_primarySourceName;
wpi::StringMap<cs::VideoSource> m_sources;
wpi::StringMap<cs::VideoSink> m_sinks;
wpi::DenseMap<CS_Sink, CS_Source> m_fixedSources;
wpi::DenseMap<CS_Source, std::shared_ptr<nt::NetworkTable>> m_tables;
std::shared_ptr<nt::NetworkTable> m_publishTable;
cs::VideoListener m_videoListener;
int m_tableListener;
int m_nextPort;
std::vector<std::string> m_addresses;
};
CameraServer* CameraServer::GetInstance() {
struct Creator {
static void* call() { return new CameraServer{}; }
};
struct Deleter {
static void call(void* ptr) { delete static_cast<CameraServer*>(ptr); }
};
static wpi::ManagedStatic<CameraServer, Creator, Deleter> instance;
return &(*instance);
}
static wpi::StringRef MakeSourceValue(CS_Source source,
wpi::SmallVectorImpl<char>& buf) {
CS_Status status = 0;
buf.clear();
switch (cs::GetSourceKind(source, &status)) {
case CS_SOURCE_USB: {
wpi::StringRef prefix{"usb:"};
buf.append(prefix.begin(), prefix.end());
auto path = cs::GetUsbCameraPath(source, &status);
buf.append(path.begin(), path.end());
break;
}
case CS_SOURCE_HTTP: {
wpi::StringRef prefix{"ip:"};
buf.append(prefix.begin(), prefix.end());
auto urls = cs::GetHttpCameraUrls(source, &status);
if (!urls.empty()) buf.append(urls[0].begin(), urls[0].end());
break;
}
case CS_SOURCE_CV:
return "cv:";
default:
return "unknown:";
}
return wpi::StringRef{buf.begin(), buf.size()};
}
static std::string MakeStreamValue(const wpi::Twine& address, int port) {
return ("mjpg:http://" + address + wpi::Twine(':') + wpi::Twine(port) +
"/?action=stream")
.str();
}
std::shared_ptr<nt::NetworkTable> CameraServer::Impl::GetSourceTable(
CS_Source source) {
std::scoped_lock lock(m_mutex);
return m_tables.lookup(source);
}
std::vector<std::string> CameraServer::Impl::GetSinkStreamValues(CS_Sink sink) {
CS_Status status = 0;
// Ignore all but MjpegServer
if (cs::GetSinkKind(sink, &status) != CS_SINK_MJPEG)
return std::vector<std::string>{};
// Get port
int port = cs::GetMjpegServerPort(sink, &status);
// Generate values
std::vector<std::string> values;
auto listenAddress = cs::GetMjpegServerListenAddress(sink, &status);
if (!listenAddress.empty()) {
// If a listen address is specified, only use that
values.emplace_back(MakeStreamValue(listenAddress, port));
} else {
// Otherwise generate for hostname and all interface addresses
values.emplace_back(MakeStreamValue(cs::GetHostname() + ".local", port));
for (const auto& addr : m_addresses) {
if (addr == "127.0.0.1") continue; // ignore localhost
values.emplace_back(MakeStreamValue(addr, port));
}
}
return values;
}
std::vector<std::string> CameraServer::Impl::GetSourceStreamValues(
CS_Source source) {
CS_Status status = 0;
// Ignore all but HttpCamera
if (cs::GetSourceKind(source, &status) != CS_SOURCE_HTTP)
return std::vector<std::string>{};
// Generate values
auto values = cs::GetHttpCameraUrls(source, &status);
for (auto& value : values) value = "mjpg:" + value;
#ifdef __FRC_ROBORIO__
// Look to see if we have a passthrough server for this source
// Only do this on the roboRIO
for (const auto& i : m_sinks) {
CS_Sink sink = i.second.GetHandle();
CS_Source sinkSource = cs::GetSinkSource(sink, &status);
if (source == sinkSource &&
cs::GetSinkKind(sink, &status) == CS_SINK_MJPEG) {
// Add USB-only passthrough
int port = cs::GetMjpegServerPort(sink, &status);
values.emplace_back(MakeStreamValue("172.22.11.2", port));
break;
}
}
#endif
// Set table value
return values;
}
void CameraServer::Impl::UpdateStreamValues() {
std::scoped_lock lock(m_mutex);
// Over all the sinks...
for (const auto& i : m_sinks) {
CS_Status status = 0;
CS_Sink sink = i.second.GetHandle();
// Get the source's subtable (if none exists, we're done)
CS_Source source = m_fixedSources.lookup(sink);
if (source == 0) source = cs::GetSinkSource(sink, &status);
if (source == 0) continue;
auto table = m_tables.lookup(source);
if (table) {
// Don't set stream values if this is a HttpCamera passthrough
if (cs::GetSourceKind(source, &status) == CS_SOURCE_HTTP) continue;
// Set table value
auto values = GetSinkStreamValues(sink);
if (!values.empty()) table->GetEntry("streams").SetStringArray(values);
}
}
// Over all the sources...
for (const auto& i : m_sources) {
CS_Source source = i.second.GetHandle();
// Get the source's subtable (if none exists, we're done)
auto table = m_tables.lookup(source);
if (table) {
// Set table value
auto values = GetSourceStreamValues(source);
if (!values.empty()) table->GetEntry("streams").SetStringArray(values);
}
}
}
static std::string PixelFormatToString(int pixelFormat) {
switch (pixelFormat) {
case cs::VideoMode::PixelFormat::kMJPEG:
return "MJPEG";
case cs::VideoMode::PixelFormat::kYUYV:
return "YUYV";
case cs::VideoMode::PixelFormat::kRGB565:
return "RGB565";
case cs::VideoMode::PixelFormat::kBGR:
return "BGR";
case cs::VideoMode::PixelFormat::kGray:
return "Gray";
default:
return "Unknown";
}
}
static std::string VideoModeToString(const cs::VideoMode& mode) {
std::string rv;
wpi::raw_string_ostream oss{rv};
oss << mode.width << "x" << mode.height;
oss << " " << PixelFormatToString(mode.pixelFormat) << " ";
oss << mode.fps << " fps";
return oss.str();
}
static std::vector<std::string> GetSourceModeValues(int source) {
std::vector<std::string> rv;
CS_Status status = 0;
for (const auto& mode : cs::EnumerateSourceVideoModes(source, &status))
rv.emplace_back(VideoModeToString(mode));
return rv;
}
static void PutSourcePropertyValue(nt::NetworkTable* table,
const cs::VideoEvent& event, bool isNew) {
wpi::SmallString<64> name;
wpi::SmallString<64> infoName;
if (wpi::StringRef{event.name}.startswith("raw_")) {
name = "RawProperty/";
name += event.name;
infoName = "RawPropertyInfo/";
infoName += event.name;
} else {
name = "Property/";
name += event.name;
infoName = "PropertyInfo/";
infoName += event.name;
}
wpi::SmallString<64> buf;
CS_Status status = 0;
nt::NetworkTableEntry entry = table->GetEntry(name);
switch (event.propertyKind) {
case CS_PROP_BOOLEAN:
if (isNew)
entry.SetDefaultBoolean(event.value != 0);
else
entry.SetBoolean(event.value != 0);
break;
case CS_PROP_INTEGER:
case CS_PROP_ENUM:
if (isNew) {
entry.SetDefaultDouble(event.value);
table->GetEntry(infoName + "/min")
.SetDouble(cs::GetPropertyMin(event.propertyHandle, &status));
table->GetEntry(infoName + "/max")
.SetDouble(cs::GetPropertyMax(event.propertyHandle, &status));
table->GetEntry(infoName + "/step")
.SetDouble(cs::GetPropertyStep(event.propertyHandle, &status));
table->GetEntry(infoName + "/default")
.SetDouble(cs::GetPropertyDefault(event.propertyHandle, &status));
} else {
entry.SetDouble(event.value);
}
break;
case CS_PROP_STRING:
if (isNew)
entry.SetDefaultString(event.valueStr);
else
entry.SetString(event.valueStr);
break;
default:
break;
}
}
CameraServer::Impl::Impl()
: m_publishTable{nt::NetworkTableInstance::GetDefault().GetTable(
kPublishName)},
m_nextPort(kBasePort) {
// We publish sources to NetworkTables using the following structure:
// "/CameraPublisher/{Source.Name}/" - root
// - "source" (string): Descriptive, prefixed with type (e.g. "usb:0")
// - "streams" (string array): URLs that can be used to stream data
// - "description" (string): Description of the source
// - "connected" (boolean): Whether source is connected
// - "mode" (string): Current video mode
// - "modes" (string array): Available video modes
// - "Property/{Property}" - Property values
// - "PropertyInfo/{Property}" - Property supporting information
// Listener for video events
m_videoListener = cs::VideoListener{
[=](const cs::VideoEvent& event) {
CS_Status status = 0;
switch (event.kind) {
case cs::VideoEvent::kSourceCreated: {
// Create subtable for the camera
auto table = m_publishTable->GetSubTable(event.name);
{
std::scoped_lock lock(m_mutex);
m_tables.insert(std::make_pair(event.sourceHandle, table));
}
wpi::SmallString<64> buf;
table->GetEntry("source").SetString(
MakeSourceValue(event.sourceHandle, buf));
wpi::SmallString<64> descBuf;
table->GetEntry("description")
.SetString(cs::GetSourceDescription(event.sourceHandle, descBuf,
&status));
table->GetEntry("connected")
.SetBoolean(cs::IsSourceConnected(event.sourceHandle, &status));
table->GetEntry("streams").SetStringArray(
GetSourceStreamValues(event.sourceHandle));
auto mode = cs::GetSourceVideoMode(event.sourceHandle, &status);
table->GetEntry("mode").SetDefaultString(VideoModeToString(mode));
table->GetEntry("modes").SetStringArray(
GetSourceModeValues(event.sourceHandle));
break;
}
case cs::VideoEvent::kSourceDestroyed: {
auto table = GetSourceTable(event.sourceHandle);
if (table) {
table->GetEntry("source").SetString("");
table->GetEntry("streams").SetStringArray(
std::vector<std::string>{});
table->GetEntry("modes").SetStringArray(
std::vector<std::string>{});
}
break;
}
case cs::VideoEvent::kSourceConnected: {
auto table = GetSourceTable(event.sourceHandle);
if (table) {
// update the description too (as it may have changed)
wpi::SmallString<64> descBuf;
table->GetEntry("description")
.SetString(cs::GetSourceDescription(event.sourceHandle,
descBuf, &status));
table->GetEntry("connected").SetBoolean(true);
}
break;
}
case cs::VideoEvent::kSourceDisconnected: {
auto table = GetSourceTable(event.sourceHandle);
if (table) table->GetEntry("connected").SetBoolean(false);
break;
}
case cs::VideoEvent::kSourceVideoModesUpdated: {
auto table = GetSourceTable(event.sourceHandle);
if (table)
table->GetEntry("modes").SetStringArray(
GetSourceModeValues(event.sourceHandle));
break;
}
case cs::VideoEvent::kSourceVideoModeChanged: {
auto table = GetSourceTable(event.sourceHandle);
if (table)
table->GetEntry("mode").SetString(VideoModeToString(event.mode));
break;
}
case cs::VideoEvent::kSourcePropertyCreated: {
auto table = GetSourceTable(event.sourceHandle);
if (table) PutSourcePropertyValue(table.get(), event, true);
break;
}
case cs::VideoEvent::kSourcePropertyValueUpdated: {
auto table = GetSourceTable(event.sourceHandle);
if (table) PutSourcePropertyValue(table.get(), event, false);
break;
}
case cs::VideoEvent::kSourcePropertyChoicesUpdated: {
auto table = GetSourceTable(event.sourceHandle);
if (table) {
wpi::SmallString<64> name{"PropertyInfo/"};
name += event.name;
name += "/choices";
auto choices =
cs::GetEnumPropertyChoices(event.propertyHandle, &status);
table->GetEntry(name).SetStringArray(choices);
}
break;
}
case cs::VideoEvent::kSinkSourceChanged:
case cs::VideoEvent::kSinkCreated:
case cs::VideoEvent::kSinkDestroyed:
case cs::VideoEvent::kNetworkInterfacesChanged: {
m_addresses = cs::GetNetworkInterfaces();
UpdateStreamValues();
break;
}
default:
break;
}
},
0x4fff, true};
// Listener for NetworkTable events
// We don't currently support changing settings via NT due to
// synchronization issues, so just update to current setting if someone
// else tries to change it.
wpi::SmallString<64> buf;
m_tableListener = nt::NetworkTableInstance::GetDefault().AddEntryListener(
kPublishName + wpi::Twine('/'),
[=](const nt::EntryNotification& event) {
wpi::StringRef relativeKey =
event.name.substr(wpi::StringRef(kPublishName).size() + 1);
// get source (sourceName/...)
auto subKeyIndex = relativeKey.find('/');
if (subKeyIndex == wpi::StringRef::npos) return;
wpi::StringRef sourceName = relativeKey.slice(0, subKeyIndex);
auto sourceIt = m_sources.find(sourceName);
if (sourceIt == m_sources.end()) return;
// get subkey
relativeKey = relativeKey.substr(subKeyIndex + 1);
// handle standard names
wpi::StringRef propName;
nt::NetworkTableEntry entry{event.entry};
if (relativeKey == "mode") {
// reset to current mode
entry.SetString(VideoModeToString(sourceIt->second.GetVideoMode()));
return;
} else if (relativeKey.startswith("Property/")) {
propName = relativeKey.substr(9);
} else if (relativeKey.startswith("RawProperty/")) {
propName = relativeKey.substr(12);
} else {
return; // ignore
}
// everything else is a property
auto property = sourceIt->second.GetProperty(propName);
switch (property.GetKind()) {
case cs::VideoProperty::kNone:
return;
case cs::VideoProperty::kBoolean:
entry.SetBoolean(property.Get() != 0);
return;
case cs::VideoProperty::kInteger:
case cs::VideoProperty::kEnum:
entry.SetDouble(property.Get());
return;
case cs::VideoProperty::kString:
entry.SetString(property.GetString());
return;
default:
return;
}
},
NT_NOTIFY_IMMEDIATE | NT_NOTIFY_UPDATE);
}
CameraServer::CameraServer() : m_impl(new Impl) {}
CameraServer::~CameraServer() {}
cs::UsbCamera CameraServer::StartAutomaticCapture() {
cs::UsbCamera camera = StartAutomaticCapture(m_impl->m_defaultUsbDevice++);
auto csShared = GetCameraServerShared();
csShared->ReportUsbCamera(camera.GetHandle());
return camera;
}
cs::UsbCamera CameraServer::StartAutomaticCapture(int dev) {
cs::UsbCamera camera{"USB Camera " + wpi::Twine(dev), dev};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportUsbCamera(camera.GetHandle());
return camera;
}
cs::UsbCamera CameraServer::StartAutomaticCapture(const wpi::Twine& name,
int dev) {
cs::UsbCamera camera{name, dev};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportUsbCamera(camera.GetHandle());
return camera;
}
cs::UsbCamera CameraServer::StartAutomaticCapture(const wpi::Twine& name,
const wpi::Twine& path) {
cs::UsbCamera camera{name, path};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportUsbCamera(camera.GetHandle());
return camera;
}
cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& host) {
return AddAxisCamera("Axis Camera", host);
}
cs::AxisCamera CameraServer::AddAxisCamera(const char* host) {
return AddAxisCamera("Axis Camera", host);
}
cs::AxisCamera CameraServer::AddAxisCamera(const std::string& host) {
return AddAxisCamera("Axis Camera", host);
}
cs::AxisCamera CameraServer::AddAxisCamera(wpi::ArrayRef<std::string> hosts) {
return AddAxisCamera("Axis Camera", hosts);
}
cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name,
const wpi::Twine& host) {
cs::AxisCamera camera{name, host};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportAxisCamera(camera.GetHandle());
return camera;
}
cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name,
const char* host) {
cs::AxisCamera camera{name, host};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportAxisCamera(camera.GetHandle());
return camera;
}
cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name,
const std::string& host) {
cs::AxisCamera camera{name, host};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportAxisCamera(camera.GetHandle());
return camera;
}
cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name,
wpi::ArrayRef<std::string> hosts) {
cs::AxisCamera camera{name, hosts};
StartAutomaticCapture(camera);
auto csShared = GetCameraServerShared();
csShared->ReportAxisCamera(camera.GetHandle());
return camera;
}
cs::MjpegServer CameraServer::AddSwitchedCamera(const wpi::Twine& name) {
// create a dummy CvSource
cs::CvSource source{name, cs::VideoMode::PixelFormat::kMJPEG, 160, 120, 30};
cs::MjpegServer server = StartAutomaticCapture(source);
m_impl->m_fixedSources[server.GetHandle()] = source.GetHandle();
return server;
}
cs::MjpegServer CameraServer::StartAutomaticCapture(
const cs::VideoSource& camera) {
AddCamera(camera);
auto server = AddServer(wpi::Twine("serve_") + camera.GetName());
server.SetSource(camera);
return server;
}
cs::CvSink CameraServer::GetVideo() {
cs::VideoSource source;
{
auto csShared = GetCameraServerShared();
std::scoped_lock lock(m_impl->m_mutex);
if (m_impl->m_primarySourceName.empty()) {
csShared->SetCameraServerError("no camera available");
return cs::CvSink{};
}
auto it = m_impl->m_sources.find(m_impl->m_primarySourceName);
if (it == m_impl->m_sources.end()) {
csShared->SetCameraServerError("no camera available");
return cs::CvSink{};
}
source = it->second;
}
return GetVideo(std::move(source));
}
cs::CvSink CameraServer::GetVideo(const cs::VideoSource& camera) {
wpi::SmallString<64> name{"opencv_"};
name += camera.GetName();
{
std::scoped_lock lock(m_impl->m_mutex);
auto it = m_impl->m_sinks.find(name);
if (it != m_impl->m_sinks.end()) {
auto kind = it->second.GetKind();
if (kind != cs::VideoSink::kCv) {
auto csShared = GetCameraServerShared();
csShared->SetCameraServerError("expected OpenCV sink, but got " +
wpi::Twine(kind));
return cs::CvSink{};
}
return *static_cast<cs::CvSink*>(&it->second);
}
}
cs::CvSink newsink{name};
newsink.SetSource(camera);
AddServer(newsink);
return newsink;
}
cs::CvSink CameraServer::GetVideo(const wpi::Twine& name) {
wpi::SmallString<64> nameBuf;
wpi::StringRef nameStr = name.toStringRef(nameBuf);
cs::VideoSource source;
{
std::scoped_lock lock(m_impl->m_mutex);
auto it = m_impl->m_sources.find(nameStr);
if (it == m_impl->m_sources.end()) {
auto csShared = GetCameraServerShared();
csShared->SetCameraServerError("could not find camera " + nameStr);
return cs::CvSink{};
}
source = it->second;
}
return GetVideo(source);
}
cs::CvSource CameraServer::PutVideo(const wpi::Twine& name, int width,
int height) {
cs::CvSource source{name, cs::VideoMode::kMJPEG, width, height, 30};
StartAutomaticCapture(source);
return source;
}
cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name) {
int port;
{
std::scoped_lock lock(m_impl->m_mutex);
port = m_impl->m_nextPort++;
}
return AddServer(name, port);
}
cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name, int port) {
cs::MjpegServer server{name, port};
AddServer(server);
return server;
}
void CameraServer::AddServer(const cs::VideoSink& server) {
std::scoped_lock lock(m_impl->m_mutex);
m_impl->m_sinks.try_emplace(server.GetName(), server);
}
void CameraServer::RemoveServer(const wpi::Twine& name) {
std::scoped_lock lock(m_impl->m_mutex);
wpi::SmallString<64> nameBuf;
m_impl->m_sinks.erase(name.toStringRef(nameBuf));
}
cs::VideoSink CameraServer::GetServer() {
wpi::SmallString<64> name;
{
std::scoped_lock lock(m_impl->m_mutex);
if (m_impl->m_primarySourceName.empty()) {
auto csShared = GetCameraServerShared();
csShared->SetCameraServerError("no camera available");
return cs::VideoSink{};
}
name = "serve_";
name += m_impl->m_primarySourceName;
}
return GetServer(name);
}
cs::VideoSink CameraServer::GetServer(const wpi::Twine& name) {
wpi::SmallString<64> nameBuf;
wpi::StringRef nameStr = name.toStringRef(nameBuf);
std::scoped_lock lock(m_impl->m_mutex);
auto it = m_impl->m_sinks.find(nameStr);
if (it == m_impl->m_sinks.end()) {
auto csShared = GetCameraServerShared();
csShared->SetCameraServerError("could not find server " + nameStr);
return cs::VideoSink{};
}
return it->second;
}
void CameraServer::AddCamera(const cs::VideoSource& camera) {
std::string name = camera.GetName();
std::scoped_lock lock(m_impl->m_mutex);
if (m_impl->m_primarySourceName.empty()) m_impl->m_primarySourceName = name;
m_impl->m_sources.try_emplace(name, camera);
}
void CameraServer::RemoveCamera(const wpi::Twine& name) {
std::scoped_lock lock(m_impl->m_mutex);
wpi::SmallString<64> nameBuf;
m_impl->m_sources.erase(name.toStringRef(nameBuf));
}
void CameraServer::SetSize(int size) {
std::scoped_lock lock(m_impl->m_mutex);
if (m_impl->m_primarySourceName.empty()) return;
auto it = m_impl->m_sources.find(m_impl->m_primarySourceName);
if (it == m_impl->m_sources.end()) return;
if (size == kSize160x120)
it->second.SetResolution(160, 120);
else if (size == kSize320x240)
it->second.SetResolution(320, 240);
else if (size == kSize640x480)
it->second.SetResolution(640, 480);
}

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "cameraserver/CameraServerShared.h"
#include <wpi/mutex.h>
namespace {
class DefaultCameraServerShared : public frc::CameraServerShared {
public:
void ReportUsbCamera(int id) override {}
void ReportAxisCamera(int id) override {}
void ReportVideoServer(int id) override {}
void SetCameraServerError(const wpi::Twine& error) override {}
void SetVisionRunnerError(const wpi::Twine& error) override {}
void ReportDriverStationError(const wpi::Twine& error) override {}
std::pair<std::thread::id, bool> GetRobotMainThreadId() const override {
return std::make_pair(std::thread::id(), false);
}
};
} // namespace
static std::unique_ptr<frc::CameraServerShared> cameraServerShared = nullptr;
static wpi::mutex setLock;
namespace frc {
CameraServerShared* GetCameraServerShared() {
std::unique_lock lock(setLock);
if (!cameraServerShared) {
cameraServerShared = std::make_unique<DefaultCameraServerShared>();
}
return cameraServerShared.get();
}
} // namespace frc
extern "C" {
void CameraServer_SetCameraServerShared(frc::CameraServerShared* shared) {
std::unique_lock lock(setLock);
cameraServerShared.reset(shared);
}
} // extern "C"

View File

@@ -0,0 +1,59 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "vision/VisionRunner.h"
#include <thread>
#include <opencv2/core/mat.hpp>
#include "cameraserver/CameraServerShared.h"
using namespace frc;
VisionRunnerBase::VisionRunnerBase(cs::VideoSource videoSource)
: m_image(std::make_unique<cv::Mat>()),
m_cvSink("VisionRunner CvSink"),
m_enabled(true) {
m_cvSink.SetSource(videoSource);
}
// Located here and not in header due to cv::Mat forward declaration.
VisionRunnerBase::~VisionRunnerBase() {}
void VisionRunnerBase::RunOnce() {
auto csShared = frc::GetCameraServerShared();
auto res = csShared->GetRobotMainThreadId();
if (res.second && (std::this_thread::get_id() == res.first)) {
csShared->SetVisionRunnerError(
"VisionRunner::RunOnce() cannot be called from the main robot thread");
return;
}
auto frameTime = m_cvSink.GrabFrame(*m_image);
if (frameTime == 0) {
auto error = m_cvSink.GetError();
csShared->ReportDriverStationError(error);
} else {
DoProcess(*m_image);
}
}
void VisionRunnerBase::RunForever() {
auto csShared = frc::GetCameraServerShared();
auto res = csShared->GetRobotMainThreadId();
if (res.second && (std::this_thread::get_id() == res.first)) {
csShared->SetVisionRunnerError(
"VisionRunner::RunForever() cannot be called from the main robot "
"thread");
return;
}
while (m_enabled) {
RunOnce();
}
}
void VisionRunnerBase::Stop() { m_enabled = false; }

View File

@@ -0,0 +1,298 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <memory>
#include <string>
#include <wpi/ArrayRef.h>
#include <wpi/Twine.h>
#include "cscore.h"
#include "cscore_cv.h"
namespace frc {
/**
* Singleton class for creating and keeping camera servers.
*
* Also publishes camera information to NetworkTables.
*/
class CameraServer {
public:
static constexpr uint16_t kBasePort = 1181;
static constexpr int kSize640x480 = 0;
static constexpr int kSize320x240 = 1;
static constexpr int kSize160x120 = 2;
/**
* Get the CameraServer instance.
*/
static CameraServer* GetInstance();
/**
* Start automatically capturing images to send to the dashboard.
*
* You should call this method to see a camera feed on the dashboard. If you
* also want to perform vision processing on the roboRIO, use getVideo() to
* get access to the camera images.
*
* The first time this overload is called, it calls StartAutomaticCapture()
* with device 0, creating a camera named "USB Camera 0". Subsequent calls
* increment the device number (e.g. 1, 2, etc).
*/
cs::UsbCamera StartAutomaticCapture();
/**
* Start automatically capturing images to send to the dashboard.
*
* This overload calls StartAutomaticCapture() with a name of "USB Camera
* {dev}".
*
* @param dev The device number of the camera interface
*/
cs::UsbCamera StartAutomaticCapture(int dev);
/**
* Start automatically capturing images to send to the dashboard.
*
* @param name The name to give the camera
* @param dev The device number of the camera interface
*/
cs::UsbCamera StartAutomaticCapture(const wpi::Twine& name, int dev);
/**
* Start automatically capturing images to send to the dashboard.
*
* @param name The name to give the camera
* @param path The device path (e.g. "/dev/video0") of the camera
*/
cs::UsbCamera StartAutomaticCapture(const wpi::Twine& name,
const wpi::Twine& path);
/**
* Start automatically capturing images to send to the dashboard from
* an existing camera.
*
* @param camera Camera
*/
cs::MjpegServer StartAutomaticCapture(const cs::VideoSource& camera);
/**
* Adds an Axis IP camera.
*
* This overload calls AddAxisCamera() with name "Axis Camera".
*
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
cs::AxisCamera AddAxisCamera(const wpi::Twine& host);
/**
* Adds an Axis IP camera.
*
* This overload calls AddAxisCamera() with name "Axis Camera".
*
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
cs::AxisCamera AddAxisCamera(const char* host);
/**
* Adds an Axis IP camera.
*
* This overload calls AddAxisCamera() with name "Axis Camera".
*
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
cs::AxisCamera AddAxisCamera(const std::string& host);
/**
* Adds an Axis IP camera.
*
* This overload calls AddAxisCamera() with name "Axis Camera".
*
* @param hosts Array of Camera host IPs/DNS names
*/
cs::AxisCamera AddAxisCamera(wpi::ArrayRef<std::string> hosts);
/**
* Adds an Axis IP camera.
*
* This overload calls AddAxisCamera() with name "Axis Camera".
*
* @param hosts Array of Camera host IPs/DNS names
*/
template <typename T>
cs::AxisCamera AddAxisCamera(std::initializer_list<T> hosts);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
cs::AxisCamera AddAxisCamera(const wpi::Twine& name, const wpi::Twine& host);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
cs::AxisCamera AddAxisCamera(const wpi::Twine& name, const char* host);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
cs::AxisCamera AddAxisCamera(const wpi::Twine& name, const std::string& host);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param hosts Array of Camera host IPs/DNS names
*/
cs::AxisCamera AddAxisCamera(const wpi::Twine& name,
wpi::ArrayRef<std::string> hosts);
/**
* Adds an Axis IP camera.
*
* @param name The name to give the camera
* @param hosts Array of Camera host IPs/DNS names
*/
template <typename T>
cs::AxisCamera AddAxisCamera(const wpi::Twine& name,
std::initializer_list<T> hosts);
/**
* Adds a virtual camera for switching between two streams. Unlike the
* other addCamera methods, this returns a VideoSink rather than a
* VideoSource. Calling SetSource() on the returned object can be used
* to switch the actual source of the stream.
*/
cs::MjpegServer AddSwitchedCamera(const wpi::Twine& name);
/**
* Get OpenCV access to the primary camera feed. This allows you to
* get images from the camera for image processing on the roboRIO.
*
* <p>This is only valid to call after a camera feed has been added
* with startAutomaticCapture() or addServer().
*/
cs::CvSink GetVideo();
/**
* Get OpenCV access to the specified camera. This allows you to get
* images from the camera for image processing on the roboRIO.
*
* @param camera Camera (e.g. as returned by startAutomaticCapture).
*/
cs::CvSink GetVideo(const cs::VideoSource& camera);
/**
* Get OpenCV access to the specified camera. This allows you to get
* images from the camera for image processing on the roboRIO.
*
* @param name Camera name
*/
cs::CvSink GetVideo(const wpi::Twine& name);
/**
* Create a MJPEG stream with OpenCV input. This can be called to pass custom
* annotated images to the dashboard.
*
* @param name Name to give the stream
* @param width Width of the image being sent
* @param height Height of the image being sent
*/
cs::CvSource PutVideo(const wpi::Twine& name, int width, int height);
/**
* Adds a MJPEG server at the next available port.
*
* @param name Server name
*/
cs::MjpegServer AddServer(const wpi::Twine& name);
/**
* Adds a MJPEG server.
*
* @param name Server name
*/
cs::MjpegServer AddServer(const wpi::Twine& name, int port);
/**
* Adds an already created server.
*
* @param server Server
*/
void AddServer(const cs::VideoSink& server);
/**
* Removes a server by name.
*
* @param name Server name
*/
void RemoveServer(const wpi::Twine& name);
/**
* Get server for the primary camera feed.
*
* This is only valid to call after a camera feed has been added with
* StartAutomaticCapture() or AddServer().
*/
cs::VideoSink GetServer();
/**
* Gets a server by name.
*
* @param name Server name
*/
cs::VideoSink GetServer(const wpi::Twine& name);
/**
* Adds an already created camera.
*
* @param camera Camera
*/
void AddCamera(const cs::VideoSource& camera);
/**
* Removes a camera by name.
*
* @param name Camera name
*/
void RemoveCamera(const wpi::Twine& name);
/**
* Sets the size of the image to use. Use the public kSize constants to set
* the correct mode, or set it directly on a camera and call the appropriate
* StartAutomaticCapture method.
*
* @deprecated Use SetResolution on the UsbCamera returned by
* StartAutomaticCapture() instead.
* @param size The size to use
*/
void SetSize(int size);
private:
CameraServer();
~CameraServer();
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace frc
#include "cameraserver/CameraServer.inc"

View File

@@ -20,7 +20,7 @@ inline cs::AxisCamera CameraServer::AddAxisCamera(
template <typename T>
inline cs::AxisCamera CameraServer::AddAxisCamera(
llvm::StringRef name, std::initializer_list<T> hosts) {
const wpi::Twine& name, std::initializer_list<T> hosts) {
std::vector<std::string> vec;
vec.reserve(hosts.size());
for (const auto& host : hosts) vec.emplace_back(host);

View File

@@ -0,0 +1,35 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <memory>
#include <thread>
#include <utility>
#include <wpi/Twine.h>
namespace frc {
class CameraServerShared {
public:
virtual ~CameraServerShared() = default;
virtual void ReportUsbCamera(int id) = 0;
virtual void ReportAxisCamera(int id) = 0;
virtual void ReportVideoServer(int id) = 0;
virtual void SetCameraServerError(const wpi::Twine& error) = 0;
virtual void SetVisionRunnerError(const wpi::Twine& error) = 0;
virtual void ReportDriverStationError(const wpi::Twine& error) = 0;
virtual std::pair<std::thread::id, bool> GetRobotMainThreadId() const = 0;
};
CameraServerShared* GetCameraServerShared();
} // namespace frc
extern "C" {
// Takes ownership
void CameraServer_SetCameraServerShared(frc::CameraServerShared* shared);
} // extern "C"

View File

@@ -0,0 +1,100 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <atomic>
#include <functional>
#include <memory>
#include "cscore.h"
#include "cscore_cv.h"
#include "vision/VisionPipeline.h"
namespace frc {
/**
* Non-template base class for VisionRunner.
*/
class VisionRunnerBase {
public:
/**
* Creates a new vision runner. It will take images from the {@code
* videoSource}, and call the virtual DoProcess() method.
*
* @param videoSource the video source to use to supply images for the
* pipeline
*/
explicit VisionRunnerBase(cs::VideoSource videoSource);
~VisionRunnerBase();
VisionRunnerBase(const VisionRunnerBase&) = delete;
VisionRunnerBase& operator=(const VisionRunnerBase&) = delete;
/**
* Runs the pipeline one time, giving it the next image from the video source
* specified in the constructor. This will block until the source either has
* an image or throws an error. If the source successfully supplied a frame,
* the pipeline's image input will be set, the pipeline will run, and the
* listener specified in the constructor will be called to notify it that the
* pipeline ran. This must be run in a dedicated thread, and cannot be used in
* the main robot thread because it will freeze the robot program.
*
* <p>This method is exposed to allow teams to add additional functionality or
* have their own ways to run the pipeline. Most teams, however, should just
* use {@link #runForever} in its own thread using a std::thread.</p>
*/
void RunOnce();
/**
* A convenience method that calls {@link #runOnce()} in an infinite loop.
* This must be run in a dedicated thread, and cannot be used in the main
* robot thread because it will freeze the robot program.
*
* <strong>Do not call this method directly from the main thread.</strong>
*/
void RunForever();
/**
* Stop a RunForever() loop.
*/
void Stop();
protected:
virtual void DoProcess(cv::Mat& image) = 0;
private:
std::unique_ptr<cv::Mat> m_image;
cs::CvSink m_cvSink;
std::atomic_bool m_enabled;
};
/**
* A vision runner is a convenient wrapper object to make it easy to run vision
* pipelines from robot code. The easiest way to use this is to run it in a
* std::thread and use the listener to take snapshots of the pipeline's outputs.
*
* @see VisionPipeline
*/
template <typename T>
class VisionRunner : public VisionRunnerBase {
public:
VisionRunner(cs::VideoSource videoSource, T* pipeline,
std::function<void(T&)> listener);
virtual ~VisionRunner() = default;
protected:
void DoProcess(cv::Mat& image) override;
private:
T* m_pipeline;
std::function<void(T&)> m_listener;
};
} // namespace frc
#include "VisionRunner.inc"

View File

@@ -0,0 +1,8 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
int main() { return 0; }

View File

@@ -0,0 +1,14 @@
include(CompileWarnings)
macro(wpilib_add_test name srcdir)
file(GLOB_RECURSE test_src ${srcdir}/*.cpp)
add_executable(${name}_test ${test_src})
wpilib_target_warnings(${name}_test)
if (BUILD_SHARED_LIBS)
target_compile_definitions(${name}_test PRIVATE -DGTEST_LINKED_AS_SHARED_LIBRARY)
endif()
if (MSVC)
target_compile_options(${name}_test PRIVATE /wd4251 /wd4101)
endif()
add_test(NAME ${name} COMMAND ${name}_test)
endmacro()

View File

@@ -0,0 +1,7 @@
macro(wpilib_target_warnings target)
if(NOT MSVC)
target_compile_options(${target} PRIVATE -Wall -pedantic -Wextra -Werror -Wno-unused-parameter -Wno-error=deprecated-declarations)
else()
target_compile_options(${target} PRIVATE /wd4244 /wd4267 /wd4146 /WX /wd4996)
endif()
endmacro()

View File

@@ -0,0 +1,26 @@
set(SCRIPTS_DIR "${CMAKE_CURRENT_LIST_DIR}/../scripts")
MACRO(GENERATE_RESOURCES inputDir outputDir prefix namespace outputFiles)
FILE(GLOB inputFiles ${inputDir}/*)
SET(${outputFiles})
FOREACH(input ${inputFiles})
GET_FILENAME_COMPONENT(inputBase ${input} NAME)
IF("${inputBase}" MATCHES "^\\.")
CONTINUE()
ENDIF()
SET(output "${outputDir}/${inputBase}.cpp")
LIST(APPEND ${outputFiles} "${output}")
ADD_CUSTOM_COMMAND(
OUTPUT ${output}
COMMAND ${CMAKE_COMMAND}
"-Dinput=${input}"
"-Doutput=${output}"
"-Dprefix=${prefix}"
"-Dnamespace=${namespace}"
-P "${SCRIPTS_DIR}/GenResource.cmake"
MAIN_DEPENDENCY ${input}
DEPENDS ${SCRIPTS_DIR}/GenResource.cmake
VERBATIM
)
ENDFOREACH()
ENDMACRO()

View File

@@ -0,0 +1,17 @@
MACRO(SUBDIR_LIST result curdir)
FILE(GLOB children RELATIVE ${curdir} ${curdir}/*)
SET(dirlist "")
FOREACH(child ${children})
IF(IS_DIRECTORY ${curdir}/${child})
LIST(APPEND dirlist ${child})
ENDIF()
ENDFOREACH()
SET(${result} ${dirlist})
ENDMACRO()
MACRO(ADD_ALL_SUBDIRECTORIES curdir)
SUBDIR_LIST (_SUBPROJECTS ${curdir})
FOREACH (dir ${_SUBPROJECTS})
ADD_SUBDIRECTORY (${dir})
ENDFOREACH ()
ENDMACRO()

View File

@@ -0,0 +1,23 @@
# Parameters: input output prefix namespace
FILE(READ ${input} fileHex HEX)
STRING(LENGTH "${fileHex}" fileHexSize)
MATH(EXPR fileSize "${fileHexSize} / 2")
GET_FILENAME_COMPONENT(inputBase ${input} NAME)
STRING(REGEX REPLACE "[^a-zA-Z0-9]" "_" funcName "${inputBase}")
SET(funcName "GetResource_${funcName}")
FILE(WRITE "${output}" "#include <stddef.h>\n#include <wpi/StringRef.h>\nextern \"C\" {\nstatic const unsigned char contents[] = {")
STRING(REGEX MATCHALL ".." outputData "${fileHex}")
STRING(REGEX REPLACE ";" ", 0x" outputData "${outputData}")
FILE(APPEND "${output}" " 0x${outputData} };\n")
FILE(APPEND "${output}" "const unsigned char* ${prefix}${funcName}(size_t* len) {\n *len = ${fileSize};\n return contents;\n}\n}\n")
IF(NOT namespace STREQUAL "")
FILE(APPEND "${output}" "namespace ${namespace} {\n")
ENDIF()
FILE(APPEND "${output}" "wpi::StringRef ${funcName}() {\n return wpi::StringRef(reinterpret_cast<const char*>(contents), ${fileSize});\n}\n")
IF(NOT namespace STREQUAL "")
FILE(APPEND "${output}" "}\n")
ENDIF()

View File

@@ -0,0 +1,4 @@
set(GCC_COMPILER_VERSION "" CACHE STRING "GCC Compiler version")
set(GNU_MACHINE "arm-frc2020-linux-gnueabi" CACHE STRING "GNU compiler triple")
set(SOFTFP yes)
include("${CMAKE_CURRENT_LIST_DIR}/arm.toolchain.cmake")

View File

@@ -0,0 +1,98 @@
set(GCC_COMPILER_VERSION "" CACHE STRING "GCC Compiler version")
set(GNU_MACHINE "arm-raspbian10-linux-gnueabi" CACHE STRING "GNU compiler triple")
if(COMMAND toolchain_save_config)
return() # prevent recursive call
endif()
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_VERSION 1)
if(NOT DEFINED CMAKE_SYSTEM_PROCESSOR)
set(CMAKE_SYSTEM_PROCESSOR arm)
else()
#message("CMAKE_SYSTEM_PROCESSOR=${CMAKE_SYSTEM_PROCESSOR}")
endif()
include("${CMAKE_CURRENT_LIST_DIR}/opencv/platforms/linux/gnu.toolchain.cmake")
if(CMAKE_SYSTEM_PROCESSOR STREQUAL arm AND NOT ARM_IGNORE_FP)
set(FLOAT_ABI_SUFFIX "")
if(NOT SOFTFP)
set(FLOAT_ABI_SUFFIX "hf")
endif()
endif()
if(NOT "x${GCC_COMPILER_VERSION}" STREQUAL "x")
set(__GCC_VER_SUFFIX "-${GCC_COMPILER_VERSION}")
endif()
if(NOT DEFINED CMAKE_C_COMPILER)
find_program(CMAKE_C_COMPILER NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-gcc${__GCC_VER_SUFFIX})
else()
#message(WARNING "CMAKE_C_COMPILER=${CMAKE_C_COMPILER} is defined")
endif()
if(NOT DEFINED CMAKE_CXX_COMPILER)
find_program(CMAKE_CXX_COMPILER NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-g++${__GCC_VER_SUFFIX})
else()
#message(WARNING "CMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} is defined")
endif()
if(NOT DEFINED CMAKE_LINKER)
find_program(CMAKE_LINKER NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ld${__GCC_VER_SUFFIX} ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ld)
else()
#message(WARNING "CMAKE_LINKER=${CMAKE_LINKER} is defined")
endif()
if(NOT DEFINED CMAKE_AR)
find_program(CMAKE_AR NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ar${__GCC_VER_SUFFIX} ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ar)
else()
#message(WARNING "CMAKE_AR=${CMAKE_AR} is defined")
endif()
if(NOT DEFINED ARM_LINUX_SYSROOT AND DEFINED GNU_MACHINE)
set(ARM_LINUX_SYSROOT /usr/${GNU_MACHINE}${FLOAT_ABI_SUFFIX})
endif()
if(NOT DEFINED CMAKE_CXX_FLAGS)
set(CMAKE_CXX_FLAGS "" CACHE INTERNAL "")
set(CMAKE_C_FLAGS "" CACHE INTERNAL "")
set(CMAKE_SHARED_LINKER_FLAGS "" CACHE INTERNAL "")
set(CMAKE_MODULE_LINKER_FLAGS "" CACHE INTERNAL "")
set(CMAKE_EXE_LINKER_FLAGS "" CACHE INTERNAL "")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -Wa,--noexecstack -fsigned-char -Wno-psabi")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fdata-sections -Wa,--noexecstack -fsigned-char -Wno-psabi")
if(CMAKE_SYSTEM_PROCESSOR STREQUAL arm)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,nocopyreloc")
endif()
if(CMAKE_SYSTEM_PROCESSOR STREQUAL arm)
set(ARM_LINKER_FLAGS "-Wl,--fix-cortex-a8 -Wl,--no-undefined -Wl,--gc-sections -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now")
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL aarch64)
set(ARM_LINKER_FLAGS "-Wl,--no-undefined -Wl,--gc-sections -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now")
endif()
set(CMAKE_SHARED_LINKER_FLAGS "${ARM_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}")
set(CMAKE_MODULE_LINKER_FLAGS "${ARM_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${ARM_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}")
else()
#message(WARNING "CMAKE_CXX_FLAGS='${CMAKE_CXX_FLAGS}' is defined")
endif()
if(USE_NEON)
message(WARNING "You use obsolete variable USE_NEON to enable NEON instruction set. Use -DENABLE_NEON=ON instead." )
set(ENABLE_NEON TRUE)
elseif(USE_VFPV3)
message(WARNING "You use obsolete variable USE_VFPV3 to enable VFPV3 instruction set. Use -DENABLE_VFPV3=ON instead." )
set(ENABLE_VFPV3 TRUE)
endif()
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${ARM_LINUX_SYSROOT})
if(EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${CUDA_TOOLKIT_ROOT_DIR})
endif()
set(TOOLCHAIN_CONFIG_VARS ${TOOLCHAIN_CONFIG_VARS}
ARM_LINUX_SYSROOT
ENABLE_NEON
ENABLE_VFPV3
CUDA_TOOLKIT_ROOT_DIR
)
toolchain_save_config()

View File

@@ -0,0 +1,97 @@
if(COMMAND toolchain_save_config)
return() # prevent recursive call
endif()
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_VERSION 1)
if(NOT DEFINED CMAKE_SYSTEM_PROCESSOR)
set(CMAKE_SYSTEM_PROCESSOR arm)
else()
#message("CMAKE_SYSTEM_PROCESSOR=${CMAKE_SYSTEM_PROCESSOR}")
endif()
include("${CMAKE_CURRENT_LIST_DIR}/gnu.toolchain.cmake")
if(CMAKE_SYSTEM_PROCESSOR STREQUAL arm AND NOT ARM_IGNORE_FP)
set(FLOAT_ABI_SUFFIX "")
if(NOT SOFTFP)
set(FLOAT_ABI_SUFFIX "hf")
endif()
endif()
if(NOT "x${GCC_COMPILER_VERSION}" STREQUAL "x")
set(__GCC_VER_SUFFIX "-${GCC_COMPILER_VERSION}")
endif()
if(NOT DEFINED CMAKE_C_COMPILER)
find_program(CMAKE_C_COMPILER NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-gcc${__GCC_VER_SUFFIX})
else()
#message(WARNING "CMAKE_C_COMPILER=${CMAKE_C_COMPILER} is defined")
endif()
if(NOT DEFINED CMAKE_CXX_COMPILER)
find_program(CMAKE_CXX_COMPILER NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-g++${__GCC_VER_SUFFIX})
else()
#message(WARNING "CMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} is defined")
endif()
if(NOT DEFINED CMAKE_LINKER)
find_program(CMAKE_LINKER NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ld${__GCC_VER_SUFFIX} ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ld)
else()
#message(WARNING "CMAKE_LINKER=${CMAKE_LINKER} is defined")
endif()
if(NOT DEFINED CMAKE_AR)
find_program(CMAKE_AR NAMES ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ar${__GCC_VER_SUFFIX} ${GNU_MACHINE}${FLOAT_ABI_SUFFIX}-ar)
else()
#message(WARNING "CMAKE_AR=${CMAKE_AR} is defined")
endif()
if(NOT DEFINED ARM_LINUX_SYSROOT AND DEFINED GNU_MACHINE)
set(ARM_LINUX_SYSROOT /usr/${GNU_MACHINE}${FLOAT_ABI_SUFFIX})
endif()
if(NOT DEFINED CMAKE_CXX_FLAGS)
set(CMAKE_CXX_FLAGS "" CACHE INTERNAL "")
set(CMAKE_C_FLAGS "" CACHE INTERNAL "")
set(CMAKE_SHARED_LINKER_FLAGS "" CACHE INTERNAL "")
set(CMAKE_MODULE_LINKER_FLAGS "" CACHE INTERNAL "")
set(CMAKE_EXE_LINKER_FLAGS "" CACHE INTERNAL "")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -Wa,--noexecstack -fsigned-char -Wno-psabi")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fdata-sections -Wa,--noexecstack -fsigned-char -Wno-psabi")
if(CMAKE_SYSTEM_PROCESSOR STREQUAL arm)
set(CMAKE_CXX_FLAGS "-mthumb ${CMAKE_CXX_FLAGS}")
set(CMAKE_C_FLAGS "-mthumb ${CMAKE_C_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,nocopyreloc")
endif()
if(CMAKE_SYSTEM_PROCESSOR STREQUAL arm)
set(ARM_LINKER_FLAGS "-Wl,--fix-cortex-a8 -Wl,--no-undefined -Wl,--gc-sections -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now")
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL aarch64)
set(ARM_LINKER_FLAGS "-Wl,--no-undefined -Wl,--gc-sections -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now")
endif()
set(CMAKE_SHARED_LINKER_FLAGS "${ARM_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}")
set(CMAKE_MODULE_LINKER_FLAGS "${ARM_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${ARM_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}")
else()
#message(WARNING "CMAKE_CXX_FLAGS='${CMAKE_CXX_FLAGS}' is defined")
endif()
if(USE_NEON)
message(WARNING "You use obsolete variable USE_NEON to enable NEON instruction set. Use -DENABLE_NEON=ON instead." )
set(ENABLE_NEON TRUE)
elseif(USE_VFPV3)
message(WARNING "You use obsolete variable USE_VFPV3 to enable VFPV3 instruction set. Use -DENABLE_VFPV3=ON instead." )
set(ENABLE_VFPV3 TRUE)
endif()
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${ARM_LINUX_SYSROOT})
if(EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${CUDA_TOOLKIT_ROOT_DIR})
endif()
set(TOOLCHAIN_CONFIG_VARS ${TOOLCHAIN_CONFIG_VARS}
ARM_LINUX_SYSROOT
ENABLE_NEON
ENABLE_VFPV3
CUDA_TOOLKIT_ROOT_DIR
)
toolchain_save_config()

View File

@@ -0,0 +1,134 @@
cmake_minimum_required(VERSION 2.8)
# load settings in case of "try compile"
set(TOOLCHAIN_CONFIG_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/toolchain.config.cmake")
get_property(__IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE)
if(__IN_TRY_COMPILE)
include("${CMAKE_CURRENT_SOURCE_DIR}/../toolchain.config.cmake" OPTIONAL) # CMAKE_BINARY_DIR is different
macro(toolchain_save_config)
# nothing
endmacro()
else()
macro(toolchain_save_config)
set(__config "#message(\"Load TOOLCHAIN config...\")\n")
get_cmake_property(__variableNames VARIABLES)
set(__vars_list ${ARGN})
list(APPEND __vars_list
${TOOLCHAIN_CONFIG_VARS}
CMAKE_SYSTEM_NAME
CMAKE_SYSTEM_VERSION
CMAKE_SYSTEM_PROCESSOR
CMAKE_C_COMPILER
CMAKE_CXX_COMPILER
CMAKE_C_FLAGS
CMAKE_CXX_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_EXE_LINKER_FLAGS
CMAKE_SKIP_RPATH
CMAKE_FIND_ROOT_PATH
GCC_COMPILER_VERSION
)
foreach(__var ${__variableNames})
foreach(_v ${__vars_list})
if("x${__var}" STREQUAL "x${_v}")
if(${__var} MATCHES " ")
set(__config "${__config}set(${__var} \"${${__var}}\")\n")
else()
set(__config "${__config}set(${__var} ${${__var}})\n")
endif()
endif()
endforeach()
endforeach()
if(EXISTS "${TOOLCHAIN_CONFIG_FILE}")
file(READ "${TOOLCHAIN_CONFIG_FILE}" __config_old)
endif()
if("${__config_old}" STREQUAL "${__config}")
# nothing
else()
#message("Update TOOLCHAIN config: ${__config}")
file(WRITE "${TOOLCHAIN_CONFIG_FILE}" "${__config}")
endif()
unset(__config)
unset(__config_old)
unset(__vars_list)
unset(__variableNames)
endmacro()
endif() # IN_TRY_COMPILE
if(NOT CMAKE_FIND_ROOT_PATH_MODE_LIBRARY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
endif()
if(NOT CMAKE_FIND_ROOT_PATH_MODE_INCLUDE)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
if(NOT CMAKE_FIND_ROOT_PATH_MODE_PACKAGE)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
endif()
if(NOT CMAKE_FIND_ROOT_PATH_MODE_PROGRAM)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
endif()
macro(__cmake_find_root_save_and_reset)
foreach(v
CMAKE_FIND_ROOT_PATH_MODE_LIBRARY
CMAKE_FIND_ROOT_PATH_MODE_INCLUDE
CMAKE_FIND_ROOT_PATH_MODE_PACKAGE
CMAKE_FIND_ROOT_PATH_MODE_PROGRAM
)
set(__save_${v} ${${v}})
set(${v} NEVER)
endforeach()
endmacro()
macro(__cmake_find_root_restore)
foreach(v
CMAKE_FIND_ROOT_PATH_MODE_LIBRARY
CMAKE_FIND_ROOT_PATH_MODE_INCLUDE
CMAKE_FIND_ROOT_PATH_MODE_PACKAGE
CMAKE_FIND_ROOT_PATH_MODE_PROGRAM
)
set(${v} ${__save_${v}})
unset(__save_${v})
endforeach()
endmacro()
# macro to find programs on the host OS
macro(find_host_program)
__cmake_find_root_save_and_reset()
if(CMAKE_HOST_WIN32)
SET(WIN32 1)
SET(UNIX)
elseif(CMAKE_HOST_APPLE)
SET(APPLE 1)
SET(UNIX)
endif()
find_program(${ARGN})
SET(WIN32)
SET(APPLE)
SET(UNIX 1)
__cmake_find_root_restore()
endmacro()
# macro to find packages on the host OS
macro(find_host_package)
__cmake_find_root_save_and_reset()
if(CMAKE_HOST_WIN32)
SET(WIN32 1)
SET(UNIX)
elseif(CMAKE_HOST_APPLE)
SET(APPLE 1)
SET(UNIX)
endif()
find_package(${ARGN})
SET(WIN32)
SET(APPLE)
SET(UNIX 1)
__cmake_find_root_restore()
endmacro()
set(CMAKE_SKIP_RPATH TRUE CACHE BOOL "If set, runtime paths are not added when using shared libraries.")

View File

@@ -1,235 +0,0 @@
import edu.wpi.first.nativeutils.*
import org.gradle.internal.os.OperatingSystem
def windowsCompilerArgs = ['/EHsc', '/DNOMINMAX', '/Zi', '/FS', '/Zc:inline', '/MT']
def windowsReleaseCompilerArgs = ['/O2']
def windowsLinkerArgs = [ '/DEBUG:FULL' ]
def windowsReleaseLinkerArgs = [ '/OPT:REF', '/OPT:ICF' ]
def linuxCompilerArgs = ['-std=c++11', '-Wformat=2', '-Wall', '-Wextra', '-Werror', '-pedantic', '-Wno-psabi', '-g',
'-Wno-unused-parameter', '-fPIC', '-rdynamic', '-Wno-error=deprecated-declarations', '-pthread']
def linuxLinkerArgs = ['-rdynamic', '-pthread']
def linuxReleaseCompilerArgs = ['-Og']
def linuxDebugCompilerArgs = ['-O0']
def linux32BitArg = '-m32'
def macCompilerArgs = ['-std=c++11', '-Wall', '-Wextra', '-Werror', '-pedantic-errors', '-fPIC', '-g',
'-Wno-unused-parameter', '-Wno-missing-field-initializers', '-Wno-unused-private-field',
'-Wno-unused-const-variable', '-pthread']
def macReleaseCompilerArgs = ['-O2']
def macDebugCompilerArgs = ['-O0']
def mac32BitArg = '-m32'
def buildAll = project.hasProperty('buildAll')
def windows64PlatformDetect = {
def arch = System.getProperty("os.arch")
def isWin = OperatingSystem.current().isWindows()
if (buildAll) {
return isWin
} else {
return isWin && arch == 'amd64'
}
}
def windows32PlatformDetect = {
def arch = System.getProperty("os.arch")
def isWin = OperatingSystem.current().isWindows()
if (buildAll) {
return isWin
} else {
return isWin && arch == 'x86'
}
}
def linux32IntelPlatformDetect = {
def arch = System.getProperty("os.arch")
def isLinux = OperatingSystem.current().isLinux()
def isIntel = (arch == 'amd64' || arch == 'i386')
if (buildAll) {
return isLinux && isIntel
} else {
return isLinux && arch == 'i386'
}
}
def linux64IntelPlatformDetect = {
def arch = System.getProperty("os.arch")
def isLinux = OperatingSystem.current().isLinux()
def isIntel = (arch == 'amd64' || arch == 'i386')
if (buildAll) {
return isLinux && isIntel
} else {
return isLinux && arch == 'amd64'
}
}
def linuxArmPlatformDetect = {
def arch = System.getProperty("os.arch")
def isIntel = (arch == 'amd64' || arch == 'i386')
return OperatingSystem.current().isLinux() && !isIntel
}
def mac64PlatformDetect = {
def arch = System.getProperty("os.arch")
def isMac = OperatingSystem.current().isMacOsX()
if (buildAll) {
return isMac
} else {
return isMac && arch == 'x86_64'
}
}
def mac32PlatformDetect = {
def arch = System.getProperty("os.arch")
def isMac = OperatingSystem.current().isMacOsX()
if (buildAll) {
return isMac
} else {
return isMac && arch == 'x86'
}
}
if (!project.hasProperty('skipAthena')) {
model {
buildConfigs {
roboRio(CrossBuildConfig) {
architecture = 'athena'
operatingSystem = 'linux'
toolChainPrefix = 'arm-frc-linux-gnueabi-'
compilerArgs = linuxCompilerArgs
linkerArgs = linuxLinkerArgs
debugCompilerArgs = linuxDebugCompilerArgs
releaseCompilerArgs = linuxReleaseCompilerArgs
releaseStripBinaries = true
compilerFamily = 'Gcc'
exclude << 'halSim'
exclude << 'halSimStaticDeps'
exclude << 'halSimTestingBase'
exclude << 'wpilibcTestingBase'
}
}
}
}
if (!project.hasProperty('onlyAthena')) {
model {
buildConfigs {
winX86(BuildConfig) {
architecture = 'x86'
operatingSystem = 'windows'
compilerArgs = windowsCompilerArgs
linkerArgs = windowsLinkerArgs
releaseCompilerArgs = windowsReleaseCompilerArgs
releaseLinkerArgs = windowsReleaseLinkerArgs
compilerFamily = 'VisualCpp'
detectPlatform = windows32PlatformDetect
exclude << 'halAthena'
}
winX64(BuildConfig) {
architecture = 'x86-64'
operatingSystem = 'windows'
compilerArgs = windowsCompilerArgs
linkerArgs = windowsLinkerArgs
releaseCompilerArgs = windowsReleaseCompilerArgs
releaseLinkerArgs = windowsReleaseLinkerArgs
compilerFamily = 'VisualCpp'
detectPlatform = windows64PlatformDetect
exclude << 'halAthena'
}
/* Disable 32 bit linux until we can figure out jenkins
linuxX86(BuildConfig) {
architecture = 'x86'
operatingSystem = 'linux'
compilerArgs = linuxCompilerArgs
compilerArgs << linux32BitArg
linkerArgs = linuxLinkerArgs
linkerArgs << linux32BitArg
debugCompilerArgs = linuxDebugCompilerArgs
releaseCompilerArgs = linuxReleaseCompilerArgs
releaseStripBinaries = true
compilerFamily = 'Gcc'
detectPlatform = linux32IntelPlatformDetect
exclude << 'halAthena'
}
*/
linuxX64(BuildConfig) {
architecture = 'x86-64'
operatingSystem = 'linux'
compilerArgs = linuxCompilerArgs
linkerArgs = linuxLinkerArgs
debugCompilerArgs = linuxDebugCompilerArgs
releaseCompilerArgs = linuxReleaseCompilerArgs
releaseStripBinaries = true
compilerFamily = 'Gcc'
detectPlatform = linux64IntelPlatformDetect
exclude << 'halAthena'
}
/* 32 bit Mac OS X not supported by OpenCV.
* If support is ever added, will add this back in
macX86(BuildConfig) {
architecture = 'x86'
operatingSystem = 'osx'
compilerArgs = macCompilerArgs
compilerArgs << mac32BitArg
linkerArgs << mac32BitArg
debugCompilerArgs = macDebugCompilerArgs
releaseCompilerArgs = macReleaseCompilerArgs
releaseStripBinaries = true
compilerFamily = 'Clang'
detectPlatform = mac32PlatformDetect
exclude << 'halAthena'
}
*/
macX64(BuildConfig) {
architecture = 'x86-64'
operatingSystem = 'osx'
compilerArgs = macCompilerArgs
debugCompilerArgs = macDebugCompilerArgs
releaseCompilerArgs = macReleaseCompilerArgs
releaseStripBinaries = true
compilerFamily = 'Clang'
detectPlatform = mac64PlatformDetect
exclude << 'halAthena'
}
}
}
}
if (project.hasProperty('linuxCross')) {
model {
buildConfigs {
linuxArm(CrossBuildConfig) {
architecture = 'nativearm'
operatingSystem = 'linux'
toolChainPrefix = 'PLEASE_PROVIDE_A_COMPILER_NAME'
compilerArgs = linuxCompilerArgs
linkerArgs = linuxLinkerArgs
debugCompilerArgs = linuxDebugCompilerArgs
releaseCompilerArgs = linuxReleaseCompilerArgs
releaseStripBinaries = true
skipByDefault = true
compilerFamily = 'Gcc'
exclude << 'gmock'
exclude << 'halAthena'
}
}
}
} else {
model {
buildConfigs {
linuxArm(BuildConfig) {
architecture = 'nativearm'
operatingSystem = 'linux'
compilerArgs = linuxCompilerArgs
linkerArgs = linuxLinkerArgs
debugCompilerArgs = linuxDebugCompilerArgs
releaseCompilerArgs = linuxReleaseCompilerArgs
releaseStripBinaries = true
compilerFamily = 'Gcc'
detectPlatform = linuxArmPlatformDetect
exclude << 'halAthena'
}
}
}
}

37
cscore/.styleguide Normal file
View File

@@ -0,0 +1,37 @@
cHeaderFileInclude {
_c\.h$
}
cppHeaderFileInclude {
(?<!_c)\.h$
\.hpp$
\.inc$
}
cppSrcFileInclude {
\.cpp$
}
licenseUpdateExclude {
src/main/native/cpp/default_init_allocator\.h$
}
includeGuardRoots {
cscore/src/main/native/cpp/
cscore/src/main/native/include/
cscore/src/main/native/linux/
cscore/src/main/native/osx/
cscore/src/main/native/windows/
cscore/src/main/test/native/cpp/
}
repoRootNameOverride {
cscore
}
includeOtherLibs {
^opencv2/
^support/
^tcpsockets/
^wpi/
}

136
cscore/CMakeLists.txt Normal file
View File

@@ -0,0 +1,136 @@
project(cscore)
include(SubDirList)
include(CompileWarnings)
include(AddTest)
find_package( OpenCV REQUIRED )
file(GLOB
cscore_native_src src/main/native/cpp/*.cpp)
file(GLOB cscore_linux_src src/main/native/linux/*.cpp)
file(GLOB cscore_osx_src src/main/native/osx/*.cpp)
file(GLOB cscore_windows_src src/main/native/windows/*.cpp)
add_library(cscore ${cscore_native_src})
set_target_properties(cscore PROPERTIES DEBUG_POSTFIX "d")
if(NOT MSVC)
if (APPLE)
target_sources(cscore PRIVATE ${cscore_osx_src})
else()
target_sources(cscore PRIVATE ${cscore_linux_src})
endif()
else()
target_sources(cscore PRIVATE ${cscore_windows_src})
target_compile_definitions(cscore PUBLIC -DNOMINMAX)
target_compile_definitions(cscore PRIVATE -D_CRT_SECURE_NO_WARNINGS)
endif()
target_include_directories(cscore PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/main/native/include>
$<INSTALL_INTERFACE:${include_dest}/cscore>)
target_include_directories(cscore PRIVATE src/main/native/cpp)
wpilib_target_warnings(cscore)
target_link_libraries(cscore PUBLIC wpiutil ${OpenCV_LIBS})
set_property(TARGET cscore PROPERTY FOLDER "libraries")
install(TARGETS cscore EXPORT cscore DESTINATION "${main_lib_dest}")
install(DIRECTORY src/main/native/include/ DESTINATION "${include_dest}/cscore")
if (MSVC OR FLAT_INSTALL_WPILIB)
set (cscore_config_dir ${wpilib_dest})
else()
set (cscore_config_dir share/cscore)
endif()
configure_file(cscore-config.cmake.in ${CMAKE_BINARY_DIR}/cscore-config.cmake )
install(FILES ${CMAKE_BINARY_DIR}/cscore-config.cmake DESTINATION ${cscore_config_dir})
install(EXPORT cscore DESTINATION ${cscore_config_dir})
SUBDIR_LIST(cscore_examples "${CMAKE_CURRENT_SOURCE_DIR}/examples")
foreach(example ${cscore_examples})
file(GLOB cscore_example_src examples/${example}/*.cpp)
if(cscore_example_src)
add_executable(cscore_${example} ${cscore_example_src})
wpilib_target_warnings(cscore_${example})
target_link_libraries(cscore_${example} cscore)
set_property(TARGET cscore_${example} PROPERTY FOLDER "examples")
endif()
endforeach()
# Java bindings
if (NOT WITHOUT_JAVA)
find_package(Java REQUIRED)
find_package(JNI REQUIRED)
include(UseJava)
set(CMAKE_JAVA_COMPILE_FLAGS "-Xlint:unchecked")
#find java files, copy them locally
if("${OPENCV_JAVA_INSTALL_DIR}" STREQUAL "")
set(OPENCV_JAVA_INSTALL_DIR ${OpenCV_INSTALL_PATH}/share/OpenCV/java/)
endif()
find_file(OPENCV_JAR_FILE NAMES opencv-${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.jar PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin NO_DEFAULT_PATH)
find_file(OPENCV_JNI_FILE NAMES libopencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.so
libopencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dylib
opencv_java${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll
PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin ${OpenCV_INSTALL_PATH}/bin/Release ${OpenCV_INSTALL_PATH}/bin/Debug ${OpenCV_INSTALL_PATH}/lib NO_DEFAULT_PATH)
file(GLOB
cscore_jni_src src/main/native/cpp/jni/CameraServerJNI.cpp)
file(GLOB_RECURSE JAVA_SOURCES src/main/java/*.java)
set(CMAKE_JNI_TARGET true)
if(${CMAKE_VERSION} VERSION_LESS "3.11.0")
set(CMAKE_JAVA_COMPILE_FLAGS "-h" "${CMAKE_CURRENT_BINARY_DIR}/jniheaders")
add_jar(cscore_jar ${JAVA_SOURCES} INCLUDE_JARS wpiutil_jar ${OPENCV_JAR_FILE} OUTPUT_NAME cscore)
else()
add_jar(cscore_jar ${JAVA_SOURCES} INCLUDE_JARS wpiutil_jar ${OPENCV_JAR_FILE} OUTPUT_NAME cscore GENERATE_NATIVE_HEADERS cscore_jni_headers)
endif()
get_property(CSCORE_JAR_FILE TARGET cscore_jar PROPERTY JAR_FILE)
install(FILES ${CSCORE_JAR_FILE} DESTINATION "${java_lib_dest}")
install(FILES ${OPENCV_JAR_FILE} DESTINATION "${java_lib_dest}")
if (MSVC)
install(FILES ${OPENCV_JNI_FILE} DESTINATION "${jni_lib_dest}")
foreach(cvFile ${OpenCV_LIBS})
find_file(${cvFile}Loc NAMES ${cvFile}${OpenCV_VERSION_MAJOR}${OpenCV_VERSION_MINOR}${OpenCV_VERSION_PATCH}.dll
PATHS ${OPENCV_JAVA_INSTALL_DIR} ${OpenCV_INSTALL_PATH}/bin ${OpenCV_INSTALL_PATH}/bin/Release ${OpenCV_INSTALL_PATH}/bin/Debug ${OpenCV_INSTALL_PATH}/lib NO_DEFAULT_PATH)
install(FILES ${${cvFile}Loc} DESTINATION "${jni_lib_dest}")
endforeach()
endif()
set_property(TARGET cscore_jar PROPERTY FOLDER "java")
add_library(cscorejni ${cscore_jni_src})
wpilib_target_warnings(cscorejni)
target_link_libraries(cscorejni PUBLIC cscore wpiutil ${OpenCV_LIBS})
set_property(TARGET cscorejni PROPERTY FOLDER "libraries")
if(${CMAKE_VERSION} VERSION_LESS "3.11.0")
target_include_directories(cscorejni PRIVATE ${JNI_INCLUDE_DIRS})
target_include_directories(cscorejni PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/jniheaders")
else()
target_link_libraries(cscorejni PRIVATE cscore_jni_headers)
endif()
add_dependencies(cscorejni cscore_jar)
if (MSVC)
install(TARGETS cscorejni RUNTIME DESTINATION "${jni_lib_dest}" COMPONENT Runtime)
endif()
install(TARGETS cscorejni EXPORT cscorejni DESTINATION "${main_lib_dest}")
endif()
if (WITH_TESTS)
wpilib_add_test(cscore src/test/native/cpp)
target_link_libraries(cscore_test cscore gmock)
endif()

137
cscore/build.gradle Normal file
View File

@@ -0,0 +1,137 @@
import org.gradle.internal.os.OperatingSystem
ext {
nativeName = 'cscore'
devMain = 'edu.wpi.cscore.DevMain'
}
// Removed because having the objective-cpp plugin added breaks
// embedded tools and its toolchain check. It causes an obj-cpp
// source set to be added to all binaries, even cross binaries
// with no support.
// if (OperatingSystem.current().isMacOsX()) {
// apply plugin: 'objective-cpp'
// }
apply from: "${rootDir}/shared/jni/setupBuild.gradle"
ext {
sharedCvConfigs = [cscore : [],
cscoreBase: [],
cscoreDev : [],
cscoreTest: [],
cscoreJNIShared: []]
staticCvConfigs = [cscoreJNI: []]
useJava = true
useCpp = true
splitSetup = {
if (it.targetPlatform.operatingSystem.isMacOsX()) {
it.sources {
// macObjCpp(ObjectiveCppSourceSet) {
// source {
// srcDirs = ['src/main/native/objcpp']
// include '**/*.mm'
// }
// exportedHeaders {
// srcDirs 'src/main/native/include'
// include '**/*.h'
// }
// }
cscoreMacCpp(CppSourceSet) {
source {
srcDirs 'src/main/native/osx'
include '**/*.cpp'
}
exportedHeaders {
srcDirs 'src/main/native/include', 'src/main/native/cpp'
include '**/*.h'
}
}
}
} else if (it.targetPlatform.operatingSystem.isLinux()) {
it.sources {
cscoreLinuxCpp(CppSourceSet) {
source {
srcDirs 'src/main/native/linux'
include '**/*.cpp'
}
exportedHeaders {
srcDirs 'src/main/native/include', 'src/main/native/cpp'
include '**/*.h'
}
}
}
} else if (it.targetPlatform.operatingSystem.isWindows()) {
it.sources {
cscoreWindowsCpp(CppSourceSet) {
source {
srcDirs 'src/main/native/windows'
include '**/*.cpp'
}
exportedHeaders {
srcDirs 'src/main/native/include', 'src/main/native/cpp'
include '**/*.h'
}
}
}
}
}
}
def examplesMap = [:];
File examplesTree = file("$projectDir/examples")
examplesTree.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
}).each {
sharedCvConfigs.put(it, [])
examplesMap.put(it, [])
}
apply from: "${rootDir}/shared/opencv.gradle"
nativeUtils.exportsConfigs {
cscore {
x86ExcludeSymbols = ['_CT??_R0?AV_System_error', '_CT??_R0?AVexception', '_CT??_R0?AVfailure',
'_CT??_R0?AVruntime_error', '_CT??_R0?AVsystem_error', '_CTA5?AVfailure',
'_TI5?AVfailure', '_CT??_R0?AVout_of_range', '_CTA3?AVout_of_range',
'_TI3?AVout_of_range', '_CT??_R0?AVbad_cast']
x64ExcludeSymbols = ['_CT??_R0?AV_System_error', '_CT??_R0?AVexception', '_CT??_R0?AVfailure',
'_CT??_R0?AVruntime_error', '_CT??_R0?AVsystem_error', '_CTA5?AVfailure',
'_TI5?AVfailure', '_CT??_R0?AVout_of_range', '_CTA3?AVout_of_range',
'_TI3?AVout_of_range', '_CT??_R0?AVbad_cast']
}
cscoreJNI {
x86SymbolFilter = { symbols ->
symbols.removeIf({ !it.startsWith('CS_') })
}
x64SymbolFilter = { symbols ->
symbols.removeIf({ !it.startsWith('CS_') })
}
}
}
model {
components {
examplesMap.each { key, value ->
"${key}"(NativeExecutableSpec) {
targetBuildTypes 'debug'
binaries.all {
lib project: ':wpiutil', library: 'wpiutil', linkage: 'shared'
lib library: 'cscore', linkage: 'shared'
}
sources {
cpp {
source {
srcDirs 'examples/' + "${key}"
include '**/*.cpp'
}
}
}
}
}
}
}

View File

@@ -0,0 +1,6 @@
include(CMakeFindDependencyMacro)
@FILENAME_DEP_REPLACE@
@WPIUTIL_DEP_REPLACE@
find_dependency(OpenCV)
include(${SELF_DIR}/cscore.cmake)

View File

@@ -0,0 +1,84 @@
/*----------------------------------------------------------------------------*/
/* 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 <wpi/SmallString.h>
#include <wpi/raw_ostream.h>
#include "cscore.h"
int main() {
CS_Status status = 0;
wpi::SmallString<64> buf;
for (const auto& caminfo : cs::EnumerateUsbCameras(&status)) {
wpi::outs() << caminfo.dev << ": " << caminfo.path << " (" << caminfo.name
<< ")\n";
if (!caminfo.otherPaths.empty()) {
wpi::outs() << "Other device paths:\n";
for (auto&& path : caminfo.otherPaths)
wpi::outs() << " " << path << '\n';
}
cs::UsbCamera camera{"usbcam", caminfo.dev};
wpi::outs() << "Properties:\n";
for (const auto& prop : camera.EnumerateProperties()) {
wpi::outs() << " " << prop.GetName();
switch (prop.GetKind()) {
case cs::VideoProperty::kBoolean:
wpi::outs() << " (bool): "
<< "value=" << prop.Get()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kInteger:
wpi::outs() << " (int): "
<< "value=" << prop.Get() << " min=" << prop.GetMin()
<< " max=" << prop.GetMax() << " step=" << prop.GetStep()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kString:
wpi::outs() << " (string): " << prop.GetString(buf);
break;
case cs::VideoProperty::kEnum: {
wpi::outs() << " (enum): "
<< "value=" << prop.Get();
auto choices = prop.GetChoices();
for (size_t i = 0; i < choices.size(); ++i) {
if (choices[i].empty()) continue;
wpi::outs() << "\n " << i << ": " << choices[i];
}
break;
}
default:
break;
}
wpi::outs() << '\n';
}
wpi::outs() << "Video Modes:\n";
for (const auto& mode : camera.EnumerateVideoModes()) {
wpi::outs() << " PixelFormat:";
switch (mode.pixelFormat) {
case cs::VideoMode::kMJPEG:
wpi::outs() << "MJPEG";
break;
case cs::VideoMode::kYUYV:
wpi::outs() << "YUYV";
break;
case cs::VideoMode::kRGB565:
wpi::outs() << "RGB565";
break;
default:
wpi::outs() << "Unknown";
break;
}
wpi::outs() << " Width:" << mode.width;
wpi::outs() << " Height:" << mode.height;
wpi::outs() << " FPS:" << mode.fps << '\n';
}
}
}

View File

@@ -0,0 +1,38 @@
/*----------------------------------------------------------------------------*/
/* 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 <cstdio>
#include <iostream>
#include <opencv2/core/core.hpp>
#include "cscore.h"
#include "cscore_cv.h"
int main() {
cs::HttpCamera camera{"httpcam", "http://localhost:8081/?action=stream"};
camera.SetVideoMode(cs::VideoMode::kMJPEG, 320, 240, 30);
cs::CvSink cvsink{"cvsink"};
cvsink.SetSource(camera);
cs::CvSource cvsource{"cvsource", cs::VideoMode::kMJPEG, 320, 240, 30};
cs::MjpegServer cvMjpegServer{"cvhttpserver", 8083};
cvMjpegServer.SetSource(cvsource);
cv::Mat test;
cv::Mat flip;
for (;;) {
uint64_t time = cvsink.GrabFrame(test);
if (time == 0) {
std::cout << "error: " << cvsink.GetError() << std::endl;
continue;
}
std::cout << "got frame at time " << time << " size " << test.size()
<< std::endl;
cv::flip(test, flip, 0);
cvsource.PutFrame(flip);
}
}

View File

@@ -0,0 +1,104 @@
/*----------------------------------------------------------------------------*/
/* 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 <chrono>
#include <thread>
#include <wpi/SmallString.h>
#include <wpi/raw_ostream.h>
#include "cscore.h"
int main(int argc, char** argv) {
if (argc < 2) {
wpi::errs() << "Usage: settings camera [prop val] ... -- [prop val]...\n";
wpi::errs() << " Example: settings 1 brightness 30 raw_contrast 10\n";
return 1;
}
int id;
if (wpi::StringRef{argv[1]}.getAsInteger(10, id)) {
wpi::errs() << "Expected number for camera\n";
return 2;
}
cs::UsbCamera camera{"usbcam", id};
// Set prior to connect
int arg = 2;
wpi::StringRef propName;
for (; arg < argc && wpi::StringRef{argv[arg]} != "--"; ++arg) {
if (propName.empty()) {
propName = argv[arg];
} else {
wpi::StringRef propVal{argv[arg]};
int intVal;
if (propVal.getAsInteger(10, intVal))
camera.GetProperty(propName).SetString(propVal);
else
camera.GetProperty(propName).Set(intVal);
propName = wpi::StringRef{};
}
}
if (arg < argc && wpi::StringRef{argv[arg]} == "--") ++arg;
// Wait to connect
while (!camera.IsConnected())
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Set rest
propName = wpi::StringRef{};
for (; arg < argc; ++arg) {
if (propName.empty()) {
propName = argv[arg];
} else {
wpi::StringRef propVal{argv[arg]};
int intVal;
if (propVal.getAsInteger(10, intVal))
camera.GetProperty(propName).SetString(propVal);
else
camera.GetProperty(propName).Set(intVal);
propName = wpi::StringRef{};
}
}
// Print settings
wpi::SmallString<64> buf;
wpi::outs() << "Properties:\n";
for (const auto& prop : camera.EnumerateProperties()) {
wpi::outs() << " " << prop.GetName();
switch (prop.GetKind()) {
case cs::VideoProperty::kBoolean:
wpi::outs() << " (bool): "
<< "value=" << prop.Get()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kInteger:
wpi::outs() << " (int): "
<< "value=" << prop.Get() << " min=" << prop.GetMin()
<< " max=" << prop.GetMax() << " step=" << prop.GetStep()
<< " default=" << prop.GetDefault();
break;
case cs::VideoProperty::kString:
wpi::outs() << " (string): " << prop.GetString(buf);
break;
case cs::VideoProperty::kEnum: {
wpi::outs() << " (enum): "
<< "value=" << prop.Get();
auto choices = prop.GetChoices();
for (size_t i = 0; i < choices.size(); ++i) {
if (choices[i].empty()) continue;
wpi::outs() << "\n " << i << ": " << choices[i];
}
break;
}
default:
break;
}
wpi::outs() << '\n';
}
}

View File

@@ -0,0 +1,40 @@
/*----------------------------------------------------------------------------*/
/* 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 <cstdio>
#include <iostream>
#include <opencv2/core/core.hpp>
#include "cscore.h"
#include "cscore_cv.h"
int main() {
cs::UsbCamera camera{"usbcam", 0};
camera.SetVideoMode(cs::VideoMode::kMJPEG, 320, 240, 30);
cs::MjpegServer mjpegServer{"httpserver", 8081};
mjpegServer.SetSource(camera);
cs::CvSink cvsink{"cvsink"};
cvsink.SetSource(camera);
cs::CvSource cvsource{"cvsource", cs::VideoMode::kMJPEG, 320, 240, 30};
cs::MjpegServer cvMjpegServer{"cvhttpserver", 8082};
cvMjpegServer.SetSource(cvsource);
cv::Mat test;
cv::Mat flip;
for (;;) {
uint64_t time = cvsink.GrabFrame(test);
if (time == 0) {
std::cout << "error: " << cvsink.GetError() << std::endl;
continue;
}
std::cout << "got frame at time " << time << " size " << test.size()
<< std::endl;
cv::flip(test, flip, 0);
cvsource.PutFrame(flip);
}
}

View File

@@ -0,0 +1,35 @@
/*----------------------------------------------------------------------------*/
/* 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 <cstdio>
#include <wpi/raw_ostream.h>
#include "cscore.h"
int main() {
wpi::outs() << "hostname: " << cs::GetHostname() << '\n';
wpi::outs() << "IPv4 network addresses:\n";
for (const auto& addr : cs::GetNetworkInterfaces())
wpi::outs() << " " << addr << '\n';
cs::UsbCamera camera{"usbcam", 0};
camera.SetVideoMode(cs::VideoMode::kMJPEG, 320, 240, 30);
cs::MjpegServer mjpegServer{"httpserver", 8081};
mjpegServer.SetSource(camera);
CS_Status status = 0;
cs::AddListener(
[&](const cs::RawEvent& event) {
wpi::outs() << "FPS=" << camera.GetActualFPS()
<< " MBPS=" << (camera.GetActualDataRate() / 1000000.0)
<< '\n';
},
cs::RawEvent::kTelemetryUpdated, false, &status);
cs::SetTelemetryPeriod(1.0);
std::getchar();
}

View File

@@ -0,0 +1,96 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import java.nio.ByteBuffer;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import edu.wpi.cscore.VideoMode.PixelFormat;
import edu.wpi.cscore.raw.RawFrame;
public class RawCVMatSink extends ImageSink {
RawFrame frame = new RawFrame();
Mat tmpMat;
ByteBuffer origByteBuffer;
int width;
int height;
int pixelFormat;
int bgrValue = PixelFormat.kBGR.getValue();
private int getCVFormat(PixelFormat pixelFormat) {
int type = 0;
switch (pixelFormat) {
case kYUYV:
case kRGB565:
type = CvType.CV_8UC2;
break;
case kBGR:
type = CvType.CV_8UC3;
break;
case kGray:
case kMJPEG:
default:
type = CvType.CV_8UC1;
break;
}
return type;
}
/**
* Create a sink for accepting OpenCV images.
* WaitForFrame() must be called on the created sink to get each new
* image.
*
* @param name Source name (arbitrary unique identifier)
*/
public RawCVMatSink(String name) {
super(CameraServerJNI.createRawSink(name));
}
/**
* Wait for the next frame and get the image.
* Times out (returning 0) after 0.225 seconds.
* The provided image will have three 3-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call GetError() to obtain the error
* message)
*/
public long grabFrame(Mat image) {
return grabFrame(image, 0.225);
}
/**
* Wait for the next frame and get the image.
* Times out (returning 0) after timeout seconds.
* The provided image will have three 3-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call GetError() to obtain the error
* message); the frame time is in 1 us increments.
*/
public long grabFrame(Mat image, double timeout) {
frame.setWidth(0);
frame.setHeight(0);
frame.setPixelFormat(bgrValue);
long rv = CameraServerJNI.grabSinkFrameTimeout(m_handle, frame, timeout);
if (rv <= 0) {
return rv;
}
if (frame.getDataByteBuffer() != origByteBuffer || width != frame.getWidth() || height != frame.getHeight() || pixelFormat != frame.getPixelFormat()) {
origByteBuffer = frame.getDataByteBuffer();
height = frame.getHeight();
width = frame.getWidth();
pixelFormat = frame.getPixelFormat();
tmpMat = new Mat(frame.getHeight(), frame.getWidth(), getCVFormat(VideoMode.getPixelFormatFromInt(pixelFormat)), origByteBuffer);
}
tmpMat.copyTo(image);
return rv;
}
}

View File

@@ -0,0 +1,59 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import org.opencv.core.Mat;
import edu.wpi.cscore.VideoMode.PixelFormat;
public class RawCVMatSource extends ImageSource {
/**
* Create an OpenCV source.
*
* @param name Source name (arbitrary unique identifier)
* @param mode Video mode being generated
*/
public RawCVMatSource(String name, VideoMode mode) {
super(CameraServerJNI.createRawSource(name,
mode.pixelFormat.getValue(),
mode.width,
mode.height,
mode.fps));
}
/**
* Create an OpenCV source.
*
* @param name Source name (arbitrary unique identifier)
* @param pixelFormat Pixel format
* @param width width
* @param height height
* @param fps fps
*/
public RawCVMatSource(String name, VideoMode.PixelFormat pixelFormat, int width, int height, int fps) {
super(CameraServerJNI.createRawSource(name, pixelFormat.getValue(), width, height, fps));
}
/**
* Put an OpenCV image and notify sinks.
*
* <p>Only 8-bit single-channel or 3-channel (with BGR channel order) images
* are supported. If the format, depth or channel order is different, use
* Mat.convertTo() and/or cvtColor() to convert it first.
*
* @param image OpenCV image
*/
public void putFrame(Mat image) {
int channels = image.channels();
if (channels != 1 && channels != 3) {
throw new VideoException("Unsupported Image Type");
}
int imgType = channels == 1 ? PixelFormat.kGray.getValue() : PixelFormat.kBGR.getValue();
CameraServerJNI.putRawSourceFrame(m_handle, image.dataAddr(), image.width(), image.height(), imgType, (int)image.total() * channels);
}
}

View File

@@ -0,0 +1,24 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import edu.wpi.first.wpiutil.RuntimeDetector;
public final class DevMain {
/**
* Main method.
*/
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println(RuntimeDetector.getPlatformPath());
System.out.println(CameraServerJNI.getHostname());
}
private DevMain() {
}
}

View File

@@ -0,0 +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. */
/*----------------------------------------------------------------------------*/
#include <iostream>
#include "cscore.h"
int main() { std::cout << cs::GetHostname() << std::endl; }

View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source that represents an Axis IP camera.
*/
public class AxisCamera extends HttpCamera {
private static String hostToUrl(String host) {
return "http://" + host + "/mjpg/video.mjpg";
}
private static String[] hostToUrl(String[] hosts) {
String[] urls = new String[hosts.length];
for (int i = 0; i < hosts.length; i++) {
urls[i] = hostToUrl(hosts[i]);
}
return urls;
}
/**
* Create a source for an Axis IP camera.
*
* @param name Source name (arbitrary unique identifier)
* @param host Camera host IP or DNS name (e.g. "10.x.y.11")
*/
public AxisCamera(String name, String host) {
super(name, hostToUrl(host), HttpCameraKind.kAxis);
}
/**
* Create a source for an Axis IP camera.
*
* @param name Source name (arbitrary unique identifier)
* @param hosts Array of Camera host IPs/DNS names
*/
public AxisCamera(String name, String[] hosts) {
super(name, hostToUrl(hosts), HttpCameraKind.kAxis);
}
}

View File

@@ -0,0 +1,72 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.opencv.core.Core;
import edu.wpi.first.wpiutil.RuntimeLoader;
public class CameraServerCvJNI {
static boolean libraryLoaded = false;
static RuntimeLoader<Core> loader = null;
public static class Helper {
private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true);
public static boolean getExtractOnStaticLoad() {
return extractOnStaticLoad.get();
}
public static void setExtractOnStaticLoad(boolean load) {
extractOnStaticLoad.set(load);
}
}
static {
String opencvName = Core.NATIVE_LIBRARY_NAME;
if (Helper.getExtractOnStaticLoad()) {
try {
CameraServerJNI.forceLoad();
loader = new RuntimeLoader<>(opencvName, RuntimeLoader.getDefaultExtractionRoot(), Core.class);
loader.loadLibraryHashed();
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
libraryLoaded = true;
}
}
/**
* Force load the library.
*/
public static synchronized void forceLoad() throws IOException {
if (libraryLoaded) {
return;
}
CameraServerJNI.forceLoad();
loader = new RuntimeLoader<>(Core.NATIVE_LIBRARY_NAME, RuntimeLoader.getDefaultExtractionRoot(), Core.class);
loader.loadLibrary();
libraryLoaded = true;
}
public static native int createCvSource(String name, int pixelFormat, int width, int height, int fps);
public static native void putSourceFrame(int source, long imageNativeObj);
public static native int createCvSink(String name);
//public static native int createCvSinkCallback(String name,
// void (*processFrame)(long time));
public static native long grabSinkFrame(int sink, long imageNativeObj);
public static native long grabSinkFrameTimeout(int sink, long imageNativeObj, double timeout);
}

View File

@@ -0,0 +1,255 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import edu.wpi.cscore.raw.RawFrame;
import edu.wpi.first.wpiutil.RuntimeLoader;
public class CameraServerJNI {
static boolean libraryLoaded = false;
static RuntimeLoader<CameraServerJNI> loader = null;
public static class Helper {
private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true);
public static boolean getExtractOnStaticLoad() {
return extractOnStaticLoad.get();
}
public static void setExtractOnStaticLoad(boolean load) {
extractOnStaticLoad.set(load);
}
}
static {
if (Helper.getExtractOnStaticLoad()) {
try {
loader = new RuntimeLoader<>("cscorejni", RuntimeLoader.getDefaultExtractionRoot(), CameraServerJNI.class);
loader.loadLibrary();
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
libraryLoaded = true;
}
}
/**
* Force load the library.
*/
public static synchronized void forceLoad() throws IOException {
if (libraryLoaded) {
return;
}
loader = new RuntimeLoader<>("cscorejni", RuntimeLoader.getDefaultExtractionRoot(), CameraServerJNI.class);
loader.loadLibrary();
libraryLoaded = true;
}
//
// Property Functions
//
public static native int getPropertyKind(int property);
public static native String getPropertyName(int property);
public static native int getProperty(int property);
public static native void setProperty(int property, int value);
public static native int getPropertyMin(int property);
public static native int getPropertyMax(int property);
public static native int getPropertyStep(int property);
public static native int getPropertyDefault(int property);
public static native String getStringProperty(int property);
public static native void setStringProperty(int property, String value);
public static native String[] getEnumPropertyChoices(int property);
//
// Source Creation Functions
//
public static native int createUsbCameraDev(String name, int dev);
public static native int createUsbCameraPath(String name, String path);
public static native int createHttpCamera(String name, String url, int kind);
public static native int createHttpCameraMulti(String name, String[] urls, int kind);
public static native int createRawSource(String name, int pixelFormat, int width, int height, int fps);
//
// Source Functions
//
public static native int getSourceKind(int source);
public static native String getSourceName(int source);
public static native String getSourceDescription(int source);
public static native long getSourceLastFrameTime(int source);
public static native void setSourceConnectionStrategy(int source, int strategy);
public static native boolean isSourceConnected(int source);
public static native boolean isSourceEnabled(int source);
public static native int getSourceProperty(int source, String name);
public static native int[] enumerateSourceProperties(int source);
public static native VideoMode getSourceVideoMode(int source);
public static native boolean setSourceVideoMode(int source, int pixelFormat, int width, int height, int fps);
public static native boolean setSourcePixelFormat(int source, int pixelFormat);
public static native boolean setSourceResolution(int source, int width, int height);
public static native boolean setSourceFPS(int source, int fps);
public static native boolean setSourceConfigJson(int source, String config);
public static native String getSourceConfigJson(int source);
public static native VideoMode[] enumerateSourceVideoModes(int source);
public static native int[] enumerateSourceSinks(int source);
public static native int copySource(int source);
public static native void releaseSource(int source);
//
// Camera Source Common Property Fuctions
//
public static native void setCameraBrightness(int source, int brightness);
public static native int getCameraBrightness(int source);
public static native void setCameraWhiteBalanceAuto(int source);
public static native void setCameraWhiteBalanceHoldCurrent(int source);
public static native void setCameraWhiteBalanceManual(int source, int value);
public static native void setCameraExposureAuto(int source);
public static native void setCameraExposureHoldCurrent(int source);
public static native void setCameraExposureManual(int source, int value);
//
// UsbCamera Source Functions
//
public static native String getUsbCameraPath(int source);
public static native UsbCameraInfo getUsbCameraInfo(int source);
//
// HttpCamera Source Functions
//
public static native int getHttpCameraKind(int source);
public static native void setHttpCameraUrls(int source, String[] urls);
public static native String[] getHttpCameraUrls(int source);
//
// Image Source Functions
//
public static native void putRawSourceFrameBB(int source, ByteBuffer data, int width, int height, int pixelFormat, int totalData);
public static native void putRawSourceFrame(int source, long data, int width, int height, int pixelFormat, int totalData);
public static void putRawSourceFrame(int source, RawFrame raw) {
putRawSourceFrame(source, raw.getDataPtr(), raw.getWidth(), raw.getHeight(), raw.getPixelFormat(), raw.getTotalData());
}
public static native void notifySourceError(int source, String msg);
public static native void setSourceConnected(int source, boolean connected);
public static native void setSourceDescription(int source, String description);
public static native int createSourceProperty(int source, String name, int kind, int minimum, int maximum, int step, int defaultValue, int value);
public static native void setSourceEnumPropertyChoices(int source, int property, String[] choices);
//
// Sink Creation Functions
//
public static native int createMjpegServer(String name, String listenAddress, int port);
public static native int createRawSink(String name);
//
// Sink Functions
//
public static native int getSinkKind(int sink);
public static native String getSinkName(int sink);
public static native String getSinkDescription(int sink);
public static native int getSinkProperty(int sink, String name);
public static native int[] enumerateSinkProperties(int sink);
public static native boolean setSinkConfigJson(int sink, String config);
public static native String getSinkConfigJson(int sink);
public static native void setSinkSource(int sink, int source);
public static native int getSinkSourceProperty(int sink, String name);
public static native int getSinkSource(int sink);
public static native int copySink(int sink);
public static native void releaseSink(int sink);
//
// MjpegServer Sink Functions
//
public static native String getMjpegServerListenAddress(int sink);
public static native int getMjpegServerPort(int sink);
//
// Image Sink Functions
//
public static native void setSinkDescription(int sink, String description);
private static native long grabRawSinkFrameImpl(int sink, RawFrame rawFrame, long rawFramePtr, ByteBuffer byteBuffer, int width, int height, int pixelFormat);
private static native long grabRawSinkFrameTimeoutImpl(int sink, RawFrame rawFrame, long rawFramePtr, ByteBuffer byteBuffer, int width, int height, int pixelFormat, double timeout);
public static long grabSinkFrame(int sink, RawFrame rawFrame) {
return grabRawSinkFrameImpl(sink, rawFrame, rawFrame.getFramePtr(), rawFrame.getDataByteBuffer(), rawFrame.getWidth(), rawFrame.getHeight(), rawFrame.getPixelFormat());
}
public static long grabSinkFrameTimeout(int sink, RawFrame rawFrame, double timeout) {
return grabRawSinkFrameTimeoutImpl(sink, rawFrame, rawFrame.getFramePtr(), rawFrame.getDataByteBuffer(), rawFrame.getWidth(), rawFrame.getHeight(), rawFrame.getPixelFormat(), timeout);
}
public static native String getSinkError(int sink);
public static native void setSinkEnabled(int sink, boolean enabled);
//
// Listener Functions
//
public static native int addListener(Consumer<VideoEvent> listener,
int eventMask, boolean immediateNotify);
public static native void removeListener(int handle);
//
// Telemetry Functions
//
public enum TelemetryKind {
kSourceBytesReceived(1),
kSourceFramesReceived(2);
@SuppressWarnings("MemberName")
private final int value;
TelemetryKind(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public static native void setTelemetryPeriod(double seconds);
public static native double getTelemetryElapsedTime();
public static native long getTelemetryValue(int handle, int kind);
public static long getTelemetryValue(int handle, TelemetryKind kind) {
return getTelemetryValue(handle, kind.getValue());
}
public static native double getTelemetryAverageValue(int handle, int kind);
public static double getTelemetryAverageValue(int handle, TelemetryKind kind) {
return getTelemetryAverageValue(handle, kind.getValue());
}
//
// Logging Functions
//
@FunctionalInterface
public interface LoggerFunction {
void apply(int level, String file, int line, String msg);
}
public static native void setLogger(LoggerFunction func, int minLevel);
//
// Utility Functions
//
public static native UsbCameraInfo[] enumerateUsbCameras();
public static native int[] enumerateSources();
public static native int[] enumerateSinks();
public static native String getHostname();
public static native String[] getNetworkInterfaces();
public static native long allocateRawFrame();
public static native void freeRawFrame(long frame);
}

View File

@@ -0,0 +1,77 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import org.opencv.core.Mat;
/**
* A sink for user code to accept video frames as OpenCV images.
* These sinks require the WPILib OpenCV builds.
* For an alternate OpenCV, see the documentation how to build your own
* with RawSink.
*/
public class CvSink extends ImageSink {
/**
* Create a sink for accepting OpenCV images.
* WaitForFrame() must be called on the created sink to get each new
* image.
*
* @param name Source name (arbitrary unique identifier)
*/
public CvSink(String name) {
super(CameraServerCvJNI.createCvSink(name));
}
/// Create a sink for accepting OpenCV images in a separate thread.
/// A thread will be created that calls WaitForFrame() and calls the
/// processFrame() callback each time a new frame arrives.
/// @param name Source name (arbitrary unique identifier)
/// @param processFrame Frame processing function; will be called with a
/// time=0 if an error occurred. processFrame should call GetImage()
/// or GetError() as needed, but should not call (except in very
/// unusual circumstances) WaitForImage().
//public CvSink(wpi::StringRef name,
// std::function<void(uint64_t time)> processFrame) {
// super(CameraServerJNI.createCvSinkCallback(name, processFrame));
//}
/**
* Wait for the next frame and get the image.
* Times out (returning 0) after 0.225 seconds.
* The provided image will have three 3-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call GetError() to obtain the error
* message)
*/
public long grabFrame(Mat image) {
return grabFrame(image, 0.225);
}
/**
* Wait for the next frame and get the image.
* Times out (returning 0) after timeout seconds.
* The provided image will have three 3-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call GetError() to obtain the error
* message); the frame time is in 1 us increments.
*/
public long grabFrame(Mat image, double timeout) {
return CameraServerCvJNI.grabSinkFrameTimeout(m_handle, image.nativeObj, timeout);
}
/**
* Wait for the next frame and get the image. May block forever.
* The provided image will have three 3-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call GetError() to obtain the error
* message); the frame time is in 1 us increments.
*/
public long grabFrameNoTimeout(Mat image) {
return CameraServerCvJNI.grabSinkFrame(m_handle, image.nativeObj);
}
}

View File

@@ -0,0 +1,59 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import org.opencv.core.Mat;
/**
* A source that represents a video camera.
* These sources require the WPILib OpenCV builds.
* For an alternate OpenCV, see the documentation how to build your own
* with RawSource.
*/
public class CvSource extends ImageSource {
/**
* Create an OpenCV source.
*
* @param name Source name (arbitrary unique identifier)
* @param mode Video mode being generated
*/
public CvSource(String name, VideoMode mode) {
super(CameraServerCvJNI.createCvSource(name,
mode.pixelFormat.getValue(),
mode.width,
mode.height,
mode.fps));
}
/**
* Create an OpenCV source.
*
* @param name Source name (arbitrary unique identifier)
* @param pixelFormat Pixel format
* @param width width
* @param height height
* @param fps fps
*/
public CvSource(String name, VideoMode.PixelFormat pixelFormat, int width, int height, int fps) {
super(CameraServerCvJNI.createCvSource(name, pixelFormat.getValue(), width, height, fps));
}
/**
* Put an OpenCV image and notify sinks.
*
* <p>Only 8-bit single-channel or 3-channel (with BGR channel order) images
* are supported. If the format, depth or channel order is different, use
* Mat.convertTo() and/or cvtColor() to convert it first.
*
* @param image OpenCV image
*/
public void putFrame(Mat image) {
CameraServerCvJNI.putSourceFrame(m_handle, image.nativeObj);
}
}

View File

@@ -0,0 +1,109 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source that represents a MJPEG-over-HTTP (IP) camera.
*/
public class HttpCamera extends VideoCamera {
public enum HttpCameraKind {
kUnknown(0), kMJPGStreamer(1), kCSCore(2), kAxis(3);
@SuppressWarnings("MemberName")
private final int value;
HttpCameraKind(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Convert from the numerical representation of kind to an enum type.
*
* @param kind The numerical representation of kind
* @return The kind
*/
public static HttpCameraKind getHttpCameraKindFromInt(int kind) {
switch (kind) {
case 1: return HttpCameraKind.kMJPGStreamer;
case 2: return HttpCameraKind.kCSCore;
case 3: return HttpCameraKind.kAxis;
default: return HttpCameraKind.kUnknown;
}
}
/**
* Create a source for a MJPEG-over-HTTP (IP) camera.
*
* @param name Source name (arbitrary unique identifier)
* @param url Camera URL (e.g. "http://10.x.y.11/video/stream.mjpg")
*/
public HttpCamera(String name, String url) {
super(CameraServerJNI.createHttpCamera(name, url, HttpCameraKind.kUnknown.getValue()));
}
/**
* Create a source for a MJPEG-over-HTTP (IP) camera.
*
* @param name Source name (arbitrary unique identifier)
* @param url Camera URL (e.g. "http://10.x.y.11/video/stream.mjpg")
* @param kind Camera kind (e.g. kAxis)
*/
public HttpCamera(String name, String url, HttpCameraKind kind) {
super(CameraServerJNI.createHttpCamera(name, url, kind.getValue()));
}
/**
* Create a source for a MJPEG-over-HTTP (IP) camera.
*
* @param name Source name (arbitrary unique identifier)
* @param urls Array of Camera URLs
*/
public HttpCamera(String name, String[] urls) {
super(CameraServerJNI.createHttpCameraMulti(name, urls, HttpCameraKind.kUnknown.getValue()));
}
/**
* Create a source for a MJPEG-over-HTTP (IP) camera.
*
* @param name Source name (arbitrary unique identifier)
* @param urls Array of Camera URLs
* @param kind Camera kind (e.g. kAxis)
*/
public HttpCamera(String name, String[] urls, HttpCameraKind kind) {
super(CameraServerJNI.createHttpCameraMulti(name, urls, kind.getValue()));
}
/**
* Get the kind of HTTP camera.
*
* <p>Autodetection can result in returning a different value than the camera
* was created with.
*/
public HttpCameraKind getHttpCameraKind() {
return getHttpCameraKindFromInt(CameraServerJNI.getHttpCameraKind(m_handle));
}
/**
* Change the URLs used to connect to the camera.
*/
public void setUrls(String[] urls) {
CameraServerJNI.setHttpCameraUrls(m_handle, urls);
}
/**
* Get the URLs used to connect to the camera.
*/
public String[] getUrls() {
return CameraServerJNI.getHttpCameraUrls(m_handle);
}
}

View File

@@ -0,0 +1,41 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
public abstract class ImageSink extends VideoSink {
protected ImageSink(int handle) {
super(handle);
}
/**
* Set sink description.
*
* @param description Description
*/
public void setDescription(String description) {
CameraServerJNI.setSinkDescription(m_handle, description);
}
/**
* Get error string. Call this if WaitForFrame() returns 0 to determine
* what the error is.
*/
public String getError() {
return CameraServerJNI.getSinkError(m_handle);
}
/**
* Enable or disable getting new frames.
* Disabling will cause processFrame (for callback-based CvSinks) to not
* be called and WaitForFrame() to not return. This can be used to save
* processor resources when frames are not needed.
*/
public void setEnabled(boolean enabled) {
CameraServerJNI.setSinkEnabled(m_handle, enabled);
}
}

View File

@@ -0,0 +1,162 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
public abstract class ImageSource extends VideoSource {
protected ImageSource(int handle) {
super(handle);
}
/**
* Signal sinks that an error has occurred. This should be called instead
* of NotifyFrame when an error occurs.
*/
public void notifyError(String msg) {
CameraServerJNI.notifySourceError(m_handle, msg);
}
/**
* Set source connection status. Defaults to true.
*
* @param connected True for connected, false for disconnected
*/
public void setConnected(boolean connected) {
CameraServerJNI.setSourceConnected(m_handle, connected);
}
/**
* Set source description.
*
* @param description Description
*/
public void setDescription(String description) {
CameraServerJNI.setSourceDescription(m_handle, description);
}
/**
* Create a property.
*
* @param name Property name
* @param kind Property kind
* @param minimum Minimum value
* @param maximum Maximum value
* @param step Step value
* @param defaultValue Default value
* @param value Current value
* @return Property
*/
public VideoProperty createProperty(String name,
VideoProperty.Kind kind,
int minimum,
int maximum,
int step,
int defaultValue,
int value) {
return new VideoProperty(
CameraServerJNI.createSourceProperty(m_handle,
name,
kind.getValue(),
minimum,
maximum,
step,
defaultValue,
value));
}
/**
* Create an integer property.
*
* @param name Property name
* @param minimum Minimum value
* @param maximum Maximum value
* @param step Step value
* @param defaultValue Default value
* @param value Current value
* @return Property
*/
public VideoProperty createIntegerProperty(String name,
int minimum,
int maximum,
int step,
int defaultValue,
int value) {
return new VideoProperty(
CameraServerJNI.createSourceProperty(m_handle,
name,
VideoProperty.Kind.kInteger.getValue(),
minimum,
maximum,
step,
defaultValue,
value));
}
/**
* Create a boolean property.
*
* @param name Property name
* @param defaultValue Default value
* @param value Current value
* @return Property
*/
public VideoProperty createBooleanProperty(String name, boolean defaultValue, boolean value) {
return new VideoProperty(
CameraServerJNI.createSourceProperty(m_handle,
name,
VideoProperty.Kind.kBoolean.getValue(),
0,
1,
1,
defaultValue ? 1 : 0,
value ? 1 : 0));
}
/**
* Create a string property.
*
* @param name Property name
* @param value Current value
* @return Property
*/
public VideoProperty createStringProperty(String name, String value) {
VideoProperty prop = new VideoProperty(
CameraServerJNI.createSourceProperty(m_handle,
name,
VideoProperty.Kind.kString.getValue(),
0,
0,
0,
0,
0));
prop.setString(value);
return prop;
}
/**
* Configure enum property choices.
*
* @param property Property
* @param choices Choices
*/
public void setEnumPropertyChoices(VideoProperty property, String[] choices) {
CameraServerJNI.setSourceEnumPropertyChoices(m_handle, property.m_handle, choices);
}
/**
* Configure enum property choices.
*
* @param property Property
* @param choices Choices
* @deprecated Use {@code setEnumPropertyChoices} instead.
*/
@Deprecated
@SuppressWarnings("MethodName")
public void SetEnumPropertyChoices(VideoProperty property, String[] choices) {
setEnumPropertyChoices(property, choices);
}
}

View File

@@ -0,0 +1,104 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A sink that acts as a MJPEG-over-HTTP network server.
*/
public class MjpegServer extends VideoSink {
/**
* Create a MJPEG-over-HTTP server sink.
*
* @param name Sink name (arbitrary unique identifier)
* @param listenAddress TCP listen address (empty string for all addresses)
* @param port TCP port number
*/
public MjpegServer(String name, String listenAddress, int port) {
super(CameraServerJNI.createMjpegServer(name, listenAddress, port));
}
/**
* Create a MJPEG-over-HTTP server sink.
*
* @param name Sink name (arbitrary unique identifier)
* @param port TCP port number
*/
public MjpegServer(String name, int port) {
this(name, "", port);
}
/**
* Get the listen address of the server.
*/
public String getListenAddress() {
return CameraServerJNI.getMjpegServerListenAddress(m_handle);
}
/**
* Get the port number of the server.
*/
public int getPort() {
return CameraServerJNI.getMjpegServerPort(m_handle);
}
/**
* Set the stream resolution for clients that don't specify it.
*
* <p>It is not necessary to set this if it is the same as the source
* resolution.
*
* <p>Setting this different than the source resolution will result in
* increased CPU usage, particularly for MJPEG source cameras, as it will
* decompress, resize, and recompress the image, instead of using the
* camera's MJPEG image directly.
*
* @param width width, 0 for unspecified
* @param height height, 0 for unspecified
*/
public void setResolution(int width, int height) {
CameraServerJNI.setProperty(CameraServerJNI.getSinkProperty(m_handle, "width"), width);
CameraServerJNI.setProperty(CameraServerJNI.getSinkProperty(m_handle, "height"), height);
}
/**
* Set the stream frames per second (FPS) for clients that don't specify it.
*
* <p>It is not necessary to set this if it is the same as the source FPS.
*
* @param fps FPS, 0 for unspecified
*/
public void setFPS(int fps) {
CameraServerJNI.setProperty(CameraServerJNI.getSinkProperty(m_handle, "fps"), fps);
}
/**
* Set the compression for clients that don't specify it.
*
* <p>Setting this will result in increased CPU usage for MJPEG source cameras
* as it will decompress and recompress the image instead of using the
* camera's MJPEG image directly.
*
* @param quality JPEG compression quality (0-100), -1 for unspecified
*/
public void setCompression(int quality) {
CameraServerJNI.setProperty(CameraServerJNI.getSinkProperty(m_handle, "compression"),
quality);
}
/**
* Set the default compression used for non-MJPEG sources. If not set,
* 80 is used. This function has no effect on MJPEG source cameras; use
* SetCompression() instead to force recompression of MJPEG source images.
*
* @param quality JPEG compression quality (0-100)
*/
public void setDefaultCompression(int quality) {
CameraServerJNI.setProperty(CameraServerJNI.getSinkProperty(m_handle, "default_compression"),
quality);
}
}

View File

@@ -0,0 +1,66 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source that represents a USB camera.
*/
public class UsbCamera extends VideoCamera {
/**
* Create a source for a USB camera based on device number.
*
* @param name Source name (arbitrary unique identifier)
* @param dev Device number (e.g. 0 for /dev/video0)
*/
public UsbCamera(String name, int dev) {
super(CameraServerJNI.createUsbCameraDev(name, dev));
}
/**
* Create a source for a USB camera based on device path.
*
* @param name Source name (arbitrary unique identifier)
* @param path Path to device (e.g. "/dev/video0" on Linux)
*/
public UsbCamera(String name, String path) {
super(CameraServerJNI.createUsbCameraPath(name, path));
}
/**
* Enumerate USB cameras on the local system.
*
* @return Vector of USB camera information (one for each camera)
*/
public static UsbCameraInfo[] enumerateUsbCameras() {
return CameraServerJNI.enumerateUsbCameras();
}
/**
* Get the path to the device.
*/
public String getPath() {
return CameraServerJNI.getUsbCameraPath(m_handle);
}
/**
* Get the full camera information for the device.
*/
public UsbCameraInfo getInfo() {
return CameraServerJNI.getUsbCameraInfo(m_handle);
}
/**
* Set how verbose the camera connection messages are.
*
* @param level 0=don't display Connecting message, 1=do display message
*/
public void setConnectVerbose(int level) {
CameraServerJNI.setProperty(CameraServerJNI.getSourceProperty(m_handle, "connect_verbose"),
level);
}
}

View File

@@ -0,0 +1,70 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* USB camera information.
*/
public class UsbCameraInfo {
/**
* Create a new set of UsbCameraInfo.
*
* @param dev Device number (e.g. N in '/dev/videoN' on Linux)
* @param path Path to device if available (e.g. '/dev/video0' on Linux)
* @param name Vendor/model name of the camera as provided by the USB driver
* @param otherPaths Other path aliases to device
* @param vendorId USB vendor id
* @param productId USB product id
*/
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
public UsbCameraInfo(int dev, String path, String name, String[] otherPaths, int vendorId,
int productId) {
this.dev = dev;
this.path = path;
this.name = name;
this.otherPaths = otherPaths;
this.vendorId = vendorId;
this.productId = productId;
}
/**
* Device number (e.g. N in '/dev/videoN' on Linux).
*/
@SuppressWarnings("MemberName")
public int dev;
/**
* Path to device if available (e.g. '/dev/video0' on Linux).
*/
@SuppressWarnings("MemberName")
public String path;
/**
* Vendor/model name of the camera as provided by the USB driver.
*/
@SuppressWarnings("MemberName")
public String name;
/**
* Other path aliases to device (e.g. '/dev/v4l/by-id/...' etc on Linux).
*/
@SuppressWarnings("MemberName")
public String[] otherPaths;
/**
* USB vendor id.
*/
@SuppressWarnings("MemberName")
public int vendorId;
/**
* USB product id.
*/
@SuppressWarnings("MemberName")
public int productId;
}

View File

@@ -0,0 +1,81 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source that represents a video camera.
*/
public class VideoCamera extends VideoSource {
public static class WhiteBalance {
public static final int kFixedIndoor = 3000;
public static final int kFixedOutdoor1 = 4000;
public static final int kFixedOutdoor2 = 5000;
public static final int kFixedFluorescent1 = 5100;
public static final int kFixedFlourescent2 = 5200;
}
protected VideoCamera(int handle) {
super(handle);
}
/**
* Set the brightness, as a percentage (0-100).
*/
public synchronized void setBrightness(int brightness) {
CameraServerJNI.setCameraBrightness(m_handle, brightness);
}
/**
* Get the brightness, as a percentage (0-100).
*/
public synchronized int getBrightness() {
return CameraServerJNI.getCameraBrightness(m_handle);
}
/**
* Set the white balance to auto.
*/
public synchronized void setWhiteBalanceAuto() {
CameraServerJNI.setCameraWhiteBalanceAuto(m_handle);
}
/**
* Set the white balance to hold current.
*/
public synchronized void setWhiteBalanceHoldCurrent() {
CameraServerJNI.setCameraWhiteBalanceHoldCurrent(m_handle);
}
/**
* Set the white balance to manual, with specified color temperature.
*/
public synchronized void setWhiteBalanceManual(int value) {
CameraServerJNI.setCameraWhiteBalanceManual(m_handle, value);
}
/**
* Set the exposure to auto aperture.
*/
public synchronized void setExposureAuto() {
CameraServerJNI.setCameraExposureAuto(m_handle);
}
/**
* Set the exposure to hold current.
*/
public synchronized void setExposureHoldCurrent() {
CameraServerJNI.setCameraExposureHoldCurrent(m_handle);
}
/**
* Set the exposure to manual, as a percentage (0-100).
*/
public synchronized void setExposureManual(int value) {
CameraServerJNI.setCameraExposureManual(m_handle, value);
}
}

View File

@@ -0,0 +1,133 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* Video event.
*/
public class VideoEvent {
public enum Kind {
kUnknown(0x0000),
kSourceCreated(0x0001),
kSourceDestroyed(0x0002),
kSourceConnected(0x0004),
kSourceDisconnected(0x0008),
kSourceVideoModesUpdated(0x0010),
kSourceVideoModeChanged(0x0020),
kSourcePropertyCreated(0x0040),
kSourcePropertyValueUpdated(0x0080),
kSourcePropertyChoicesUpdated(0x0100),
kSinkSourceChanged(0x0200),
kSinkCreated(0x0400),
kSinkDestroyed(0x0800),
kSinkEnabled(0x1000),
kSinkDisabled(0x2000),
kNetworkInterfacesChanged(0x4000),
kTelemetryUpdated(0x8000),
kSinkPropertyCreated(0x10000),
kSinkPropertyValueUpdated(0x20000),
kSinkPropertyChoicesUpdated(0x40000);
@SuppressWarnings("MemberName")
private final int value;
Kind(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Convert from the numerical representation of kind to an enum type.
*
* @param kind The numerical representation of kind
* @return The kind
*/
@SuppressWarnings("PMD.CyclomaticComplexity")
public static Kind getKindFromInt(int kind) {
switch (kind) {
case 0x0001: return Kind.kSourceCreated;
case 0x0002: return Kind.kSourceDestroyed;
case 0x0004: return Kind.kSourceConnected;
case 0x0008: return Kind.kSourceDisconnected;
case 0x0010: return Kind.kSourceVideoModesUpdated;
case 0x0020: return Kind.kSourceVideoModeChanged;
case 0x0040: return Kind.kSourcePropertyCreated;
case 0x0080: return Kind.kSourcePropertyValueUpdated;
case 0x0100: return Kind.kSourcePropertyChoicesUpdated;
case 0x0200: return Kind.kSinkSourceChanged;
case 0x0400: return Kind.kSinkCreated;
case 0x0800: return Kind.kSinkDestroyed;
case 0x1000: return Kind.kSinkEnabled;
case 0x2000: return Kind.kSinkDisabled;
case 0x4000: return Kind.kNetworkInterfacesChanged;
case 0x10000: return Kind.kSinkPropertyCreated;
case 0x20000: return Kind.kSinkPropertyValueUpdated;
case 0x40000: return Kind.kSinkPropertyChoicesUpdated;
default: return Kind.kUnknown;
}
}
@SuppressWarnings("PMD.ExcessiveParameterList")
VideoEvent(int kind, int source, int sink, String name, int pixelFormat,
int width, int height, int fps, int property, int propertyKind,
int value, String valueStr) {
this.kind = getKindFromInt(kind);
this.sourceHandle = source;
this.sinkHandle = sink;
this.name = name;
this.mode = new VideoMode(pixelFormat, width, height, fps);
this.propertyHandle = property;
this.propertyKind = VideoProperty.getKindFromInt(propertyKind);
this.value = value;
this.valueStr = valueStr;
}
@SuppressWarnings("MemberName")
public Kind kind;
// Valid for kSource* and kSink* respectively
@SuppressWarnings("MemberName")
public int sourceHandle;
@SuppressWarnings("MemberName")
public int sinkHandle;
// Source/sink/property name
@SuppressWarnings("MemberName")
public String name;
// Fields for kSourceVideoModeChanged event
@SuppressWarnings("MemberName")
public VideoMode mode;
// Fields for kSourceProperty* events
@SuppressWarnings("MemberName")
public int propertyHandle;
@SuppressWarnings("MemberName")
public VideoProperty.Kind propertyKind;
@SuppressWarnings("MemberName")
public int value;
@SuppressWarnings("MemberName")
public String valueStr;
public VideoSource getSource() {
return new VideoSource(CameraServerJNI.copySource(sourceHandle));
}
public VideoSink getSink() {
return new VideoSink(CameraServerJNI.copySink(sinkHandle));
}
public VideoProperty getProperty() {
return new VideoProperty(propertyHandle, propertyKind);
}
}

View File

@@ -0,0 +1,24 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* An exception raised by the camera server.
*/
public class VideoException extends RuntimeException {
private static final long serialVersionUID = -9155939328084105145L;
public VideoException(String msg) {
super(msg);
}
@Override
public String toString() {
return "VideoException [" + super.toString() + "]";
}
}

View File

@@ -0,0 +1,43 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
import java.util.function.Consumer;
/**
* An event listener. This calls back to a desigated callback function when
* an event matching the specified mask is generated by the library.
*/
public class VideoListener implements AutoCloseable {
/**
* Create an event listener.
*
* @param listener Listener function
* @param eventMask Bitmask of VideoEvent.Type values
* @param immediateNotify Whether callback should be immediately called with
* a representative set of events for the current library state.
*/
public VideoListener(Consumer<VideoEvent> listener, int eventMask,
boolean immediateNotify) {
m_handle = CameraServerJNI.addListener(listener, eventMask, immediateNotify);
}
@Override
public synchronized void close() {
if (m_handle != 0) {
CameraServerJNI.removeListener(m_handle);
}
m_handle = 0;
}
public boolean isValid() {
return m_handle != 0;
}
private int m_handle;
}

View File

@@ -0,0 +1,78 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* Video mode.
*/
public class VideoMode {
public enum PixelFormat {
kUnknown(0), kMJPEG(1), kYUYV(2), kRGB565(3), kBGR(4), kGray(5);
@SuppressWarnings("MemberName")
private final int value;
PixelFormat(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private static final PixelFormat[] m_pixelFormatValues = PixelFormat.values();
public static PixelFormat getPixelFormatFromInt(int pixelFormat) {
return m_pixelFormatValues[pixelFormat];
}
/**
* Create a new video mode.
*/
public VideoMode(int pixelFormat, int width, int height, int fps) {
this.pixelFormat = getPixelFormatFromInt(pixelFormat);
this.width = width;
this.height = height;
this.fps = fps;
}
/**
* Create a new video mode.
*/
public VideoMode(PixelFormat pixelFormat, int width, int height, int fps) {
this.pixelFormat = pixelFormat;
this.width = width;
this.height = height;
this.fps = fps;
}
/**
* Pixel format.
*/
@SuppressWarnings("MemberName")
public PixelFormat pixelFormat;
/**
* Width in pixels.
*/
@SuppressWarnings("MemberName")
public int width;
/**
* Height in pixels.
*/
@SuppressWarnings("MemberName")
public int height;
/**
* Frames per second.
*/
@SuppressWarnings("MemberName")
public int fps;
}

View File

@@ -0,0 +1,124 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source or sink property.
*/
public class VideoProperty {
public enum Kind {
kNone(0), kBoolean(1), kInteger(2), kString(4), kEnum(8);
@SuppressWarnings("MemberName")
private final int value;
Kind(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Convert from the numerical representation of kind to an enum type.
*
* @param kind The numerical representation of kind
* @return The kind
*/
public static Kind getKindFromInt(int kind) {
switch (kind) {
case 1: return Kind.kBoolean;
case 2: return Kind.kInteger;
case 4: return Kind.kString;
case 8: return Kind.kEnum;
default: return Kind.kNone;
}
}
public String getName() {
return CameraServerJNI.getPropertyName(m_handle);
}
public Kind getKind() {
return m_kind;
}
public boolean isValid() {
return m_kind != Kind.kNone;
}
// Kind checkers
public boolean isBoolean() {
return m_kind == Kind.kBoolean;
}
public boolean isInteger() {
return m_kind == Kind.kInteger;
}
public boolean isString() {
return m_kind == Kind.kString;
}
public boolean isEnum() {
return m_kind == Kind.kEnum;
}
public int get() {
return CameraServerJNI.getProperty(m_handle);
}
public void set(int value) {
CameraServerJNI.setProperty(m_handle, value);
}
public int getMin() {
return CameraServerJNI.getPropertyMin(m_handle);
}
public int getMax() {
return CameraServerJNI.getPropertyMax(m_handle);
}
public int getStep() {
return CameraServerJNI.getPropertyStep(m_handle);
}
public int getDefault() {
return CameraServerJNI.getPropertyDefault(m_handle);
}
// String-specific functions
public String getString() {
return CameraServerJNI.getStringProperty(m_handle);
}
public void setString(String value) {
CameraServerJNI.setStringProperty(m_handle, value);
}
// Enum-specific functions
public String[] getChoices() {
return CameraServerJNI.getEnumPropertyChoices(m_handle);
}
VideoProperty(int handle) {
m_handle = handle;
m_kind = getKindFromInt(CameraServerJNI.getPropertyKind(handle));
}
VideoProperty(int handle, Kind kind) {
m_handle = handle;
m_kind = kind;
}
int m_handle;
private Kind m_kind;
}

View File

@@ -0,0 +1,217 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source for video that provides a sequence of frames. Each frame may
* consist of multiple images (e.g. from a stereo or depth camera); these
* are called channels.
*/
public class VideoSink implements AutoCloseable {
public enum Kind {
kUnknown(0), kMjpeg(2), kCv(4), kRaw(8);
@SuppressWarnings("MemberName")
private final int value;
Kind(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Convert from the numerical representation of kind to an enum type.
*
* @param kind The numerical representation of kind
* @return The kind
*/
public static Kind getKindFromInt(int kind) {
switch (kind) {
case 2: return Kind.kMjpeg;
case 4: return Kind.kCv;
default: return Kind.kUnknown;
}
}
protected VideoSink(int handle) {
m_handle = handle;
}
@Override
public synchronized void close() {
if (m_handle != 0) {
CameraServerJNI.releaseSink(m_handle);
}
m_handle = 0;
}
public boolean isValid() {
return m_handle != 0;
}
public int getHandle() {
return m_handle;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
VideoSink sink = (VideoSink) other;
return m_handle == sink.m_handle;
}
@Override
public int hashCode() {
return m_handle;
}
/**
* Get the kind of the sink.
*/
public Kind getKind() {
return getKindFromInt(CameraServerJNI.getSinkKind(m_handle));
}
/**
* Get the name of the sink. The name is an arbitrary identifier
* provided when the sink is created, and should be unique.
*/
public String getName() {
return CameraServerJNI.getSinkName(m_handle);
}
/**
* Get the sink description. This is sink-kind specific.
*/
public String getDescription() {
return CameraServerJNI.getSinkDescription(m_handle);
}
/**
* Get a property of the sink.
*
* @param name Property name
* @return Property (kind Property::kNone if no property with
* the given name exists)
*/
public VideoProperty getProperty(String name) {
return new VideoProperty(CameraServerJNI.getSinkProperty(m_handle, name));
}
/**
* Enumerate all properties of this sink.
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public VideoProperty[] enumerateProperties() {
int[] handles = CameraServerJNI.enumerateSinkProperties(m_handle);
VideoProperty[] rv = new VideoProperty[handles.length];
for (int i = 0; i < handles.length; i++) {
rv[i] = new VideoProperty(handles[i]);
}
return rv;
}
/**
* Set properties from a JSON configuration string.
*
* <p>The format of the JSON input is:
*
* <pre>
* {
* "properties": [
* {
* "name": property name
* "value": property value
* }
* ]
* }
* </pre>
*
* @param config configuration
* @return True if set successfully
*/
public boolean setConfigJson(String config) {
return CameraServerJNI.setSinkConfigJson(m_handle, config);
}
/**
* Get a JSON configuration string.
*
* @return JSON configuration string
*/
public String getConfigJson() {
return CameraServerJNI.getSinkConfigJson(m_handle);
}
/**
* Configure which source should provide frames to this sink. Each sink
* can accept frames from only a single source, but a single source can
* provide frames to multiple clients.
*
* @param source Source
*/
public void setSource(VideoSource source) {
if (source == null) {
CameraServerJNI.setSinkSource(m_handle, 0);
} else {
CameraServerJNI.setSinkSource(m_handle, source.m_handle);
}
}
/**
* Get the connected source.
*
* @return Connected source; nullptr if no source connected.
*/
public VideoSource getSource() {
// While VideoSource.close() will call releaseSource(), getSinkSource()
// increments the internal reference count so this is okay to do.
return new VideoSource(CameraServerJNI.getSinkSource(m_handle));
}
/**
* Get a property of the associated source.
*
* @param name Property name
* @return Property (kind Property::kNone if no property with
* the given name exists or no source connected)
*/
public VideoProperty getSourceProperty(String name) {
return new VideoProperty(
CameraServerJNI.getSinkSourceProperty(m_handle, name));
}
/**
* Enumerate all existing sinks.
*
* @return Vector of sinks.
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static VideoSink[] enumerateSinks() {
int[] handles = CameraServerJNI.enumerateSinks();
VideoSink[] rv = new VideoSink[handles.length];
for (int i = 0; i < handles.length; i++) {
rv[i] = new VideoSink(handles[i]);
}
return rv;
}
protected int m_handle;
}

View File

@@ -0,0 +1,371 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore;
/**
* A source for video that provides a sequence of frames. Each frame may
* consist of multiple images (e.g. from a stereo or depth camera); these
* are called channels.
*/
public class VideoSource implements AutoCloseable {
public enum Kind {
kUnknown(0), kUsb(1), kHttp(2), kCv(4), kRaw(8);
@SuppressWarnings("MemberName")
private final int value;
Kind(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Connection strategy.
*/
public enum ConnectionStrategy {
/**
* Automatically connect or disconnect based on whether any sinks are
* connected to this source. This is the default behavior.
*/
kAutoManage(0),
/**
* Try to keep the connection open regardless of whether any sinks are
* connected.
*/
kKeepOpen(1),
/**
* Never open the connection. If this is set when the connection is open,
* close the connection.
*/
kForceClose(2);
@SuppressWarnings("MemberName")
private final int value;
ConnectionStrategy(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Convert from the numerical representation of kind to an enum type.
*
* @param kind The numerical representation of kind
* @return The kind
*/
public static Kind getKindFromInt(int kind) {
switch (kind) {
case 1: return Kind.kUsb;
case 2: return Kind.kHttp;
case 4: return Kind.kCv;
default: return Kind.kUnknown;
}
}
protected VideoSource(int handle) {
m_handle = handle;
}
@Override
public synchronized void close() {
if (m_handle != 0) {
CameraServerJNI.releaseSource(m_handle);
}
m_handle = 0;
}
public boolean isValid() {
return m_handle != 0;
}
public int getHandle() {
return m_handle;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
VideoSource source = (VideoSource) other;
return m_handle == source.m_handle;
}
@Override
public int hashCode() {
return m_handle;
}
/**
* Get the kind of the source.
*/
public Kind getKind() {
return getKindFromInt(CameraServerJNI.getSourceKind(m_handle));
}
/**
* Get the name of the source. The name is an arbitrary identifier
* provided when the source is created, and should be unique.
*/
public String getName() {
return CameraServerJNI.getSourceName(m_handle);
}
/**
* Get the source description. This is source-kind specific.
*/
public String getDescription() {
return CameraServerJNI.getSourceDescription(m_handle);
}
/**
* Get the last time a frame was captured.
* @return Time in 1 us increments.
*/
public long getLastFrameTime() {
return CameraServerJNI.getSourceLastFrameTime(m_handle);
}
/**
* Sets the connection strategy. By default, the source will automatically
* connect or disconnect based on whether any sinks are connected.
*
* <p>This function is non-blocking; look for either a connection open or
* close event or call {@link #isConnected()} to determine the connection
* state.
*
* @param strategy connection strategy (auto, keep open, or force close)
*/
public void setConnectionStrategy(ConnectionStrategy strategy) {
CameraServerJNI.setSourceConnectionStrategy(m_handle, strategy.getValue());
}
/**
* Returns if the source currently connected to whatever is providing the images.
*/
public boolean isConnected() {
return CameraServerJNI.isSourceConnected(m_handle);
}
/**
* Gets source enable status. This is determined with a combination of
* connection strategy and the number of sinks connected.
*
* @return True if enabled, false otherwise.
*/
public boolean isEnabled() {
return CameraServerJNI.isSourceEnabled(m_handle);
}
/**
* Get a property.
*
* @param name Property name
* @return Property contents (of kind Property::kNone if no property with
* the given name exists)
*/
public VideoProperty getProperty(String name) {
return new VideoProperty(CameraServerJNI.getSourceProperty(m_handle, name));
}
/**
* Enumerate all properties of this source.
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public VideoProperty[] enumerateProperties() {
int[] handles = CameraServerJNI.enumerateSourceProperties(m_handle);
VideoProperty[] rv = new VideoProperty[handles.length];
for (int i = 0; i < handles.length; i++) {
rv[i] = new VideoProperty(handles[i]);
}
return rv;
}
/**
* Get the current video mode.
*/
public VideoMode getVideoMode() {
return CameraServerJNI.getSourceVideoMode(m_handle);
}
/**
* Set the video mode.
* @param mode Video mode
*/
public boolean setVideoMode(VideoMode mode) {
return CameraServerJNI.setSourceVideoMode(m_handle,
mode.pixelFormat.getValue(),
mode.width,
mode.height,
mode.fps);
}
/**
* Set the video mode.
*
* @param pixelFormat desired pixel format
* @param width desired width
* @param height desired height
* @param fps desired FPS
* @return True if set successfully
*/
public boolean setVideoMode(VideoMode.PixelFormat pixelFormat, int width, int height, int fps) {
return CameraServerJNI.setSourceVideoMode(m_handle, pixelFormat.getValue(), width, height, fps);
}
/**
* Set the pixel format.
*
* @param pixelFormat desired pixel format
* @return True if set successfully
*/
public boolean setPixelFormat(VideoMode.PixelFormat pixelFormat) {
return CameraServerJNI.setSourcePixelFormat(m_handle, pixelFormat.getValue());
}
/**
* Set the resolution.
*
* @param width desired width
* @param height desired height
* @return True if set successfully
*/
public boolean setResolution(int width, int height) {
return CameraServerJNI.setSourceResolution(m_handle, width, height);
}
/**
* Set the frames per second (FPS).
*
* @param fps desired FPS
* @return True if set successfully
*/
public boolean setFPS(int fps) {
return CameraServerJNI.setSourceFPS(m_handle, fps);
}
/**
* Set video mode and properties from a JSON configuration string.
*
* <p>The format of the JSON input is:
*
* <pre>
* {
* "pixel format": "MJPEG", "YUYV", etc
* "width": video mode width
* "height": video mode height
* "fps": video mode fps
* "brightness": percentage brightness
* "white balance": "auto", "hold", or value
* "exposure": "auto", "hold", or value
* "properties": [
* {
* "name": property name
* "value": property value
* }
* ]
* }
* </pre>
*
* @param config configuration
* @return True if set successfully
*/
public boolean setConfigJson(String config) {
return CameraServerJNI.setSourceConfigJson(m_handle, config);
}
/**
* Get a JSON configuration string.
*
* @return JSON configuration string
*/
public String getConfigJson() {
return CameraServerJNI.getSourceConfigJson(m_handle);
}
/**
* Get the actual FPS.
*
* <p>CameraServerJNI#setTelemetryPeriod() must be called for this to be valid
* (throws VisionException if telemetry is not enabled).
*
* @return Actual FPS averaged over the telemetry period.
*/
public double getActualFPS() {
return CameraServerJNI.getTelemetryAverageValue(m_handle,
CameraServerJNI.TelemetryKind.kSourceFramesReceived);
}
/**
* Get the data rate (in bytes per second).
*
* <p>CameraServerJNI#setTelemetryPeriod() must be called for this to be valid
* (throws VisionException if telemetry is not enabled).
*
* @return Data rate averaged over the telemetry period.
*/
public double getActualDataRate() {
return CameraServerJNI.getTelemetryAverageValue(m_handle,
CameraServerJNI.TelemetryKind.kSourceBytesReceived);
}
/**
* Enumerate all known video modes for this source.
*/
public VideoMode[] enumerateVideoModes() {
return CameraServerJNI.enumerateSourceVideoModes(m_handle);
}
/**
* Enumerate all sinks connected to this source.
*
* @return Vector of sinks.
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public VideoSink[] enumerateSinks() {
int[] handles = CameraServerJNI.enumerateSourceSinks(m_handle);
VideoSink[] rv = new VideoSink[handles.length];
for (int i = 0; i < handles.length; i++) {
rv[i] = new VideoSink(handles[i]);
}
return rv;
}
/**
* Enumerate all existing sources.
*
* @return Vector of sources.
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static VideoSource[] enumerateSources() {
int[] handles = CameraServerJNI.enumerateSources();
VideoSource[] rv = new VideoSource[handles.length];
for (int i = 0; i < handles.length; i++) {
rv[i] = new VideoSource(handles[i]);
}
return rv;
}
protected int m_handle;
}

View File

@@ -0,0 +1,130 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore.raw;
import java.nio.ByteBuffer;
import edu.wpi.cscore.CameraServerJNI;
/**
* Class for storing raw frame data between image read call.
*
* <p>Data is reused for each frame read, rather then reallocating every frame.
*/
public class RawFrame implements AutoCloseable {
private final long m_framePtr;
private ByteBuffer m_dataByteBuffer;
private long m_dataPtr;
private int m_totalData;
private int m_width;
private int m_height;
private int m_pixelFormat;
/**
* Construct a new RawFrame.
*/
public RawFrame() {
m_framePtr = CameraServerJNI.allocateRawFrame();
}
/**
* Close the RawFrame, releasing native resources.
* Any images currently using the data will be invalidated.
*/
@Override
public void close() {
CameraServerJNI.freeRawFrame(m_framePtr);
}
/**
* Called from JNI to set data in class.
*/
public void setData(ByteBuffer dataByteBuffer, long dataPtr, int totalData,
int width, int height, int pixelFormat) {
m_dataByteBuffer = dataByteBuffer;
m_dataPtr = dataPtr;
m_totalData = totalData;
m_width = width;
m_height = height;
m_pixelFormat = pixelFormat;
}
/**
* Get the pointer to native representation of this frame.
*/
public long getFramePtr() {
return m_framePtr;
}
/**
* Get a ByteBuffer pointing to the frame data.
* This ByteBuffer is backed by the frame directly. Its lifetime is controlled by
* the frame. If a new frame gets read, it will overwrite the current one.
*/
public ByteBuffer getDataByteBuffer() {
return m_dataByteBuffer;
}
/**
* Get a long (is a char* in native code) pointing to the frame data.
* This pointer is backed by the frame directly. Its lifetime is controlled by
* the frame. If a new frame gets read, it will overwrite the current one.
*/
public long getDataPtr() {
return m_dataPtr;
}
/**
* Get the total length of the data stored in the frame.
*/
public int getTotalData() {
return m_totalData;
}
/**
* Get the width of the frame.
*/
public int getWidth() {
return m_width;
}
/**
* Set the width of the frame.
*/
public void setWidth(int width) {
this.m_width = width;
}
/**
* Get the height of the frame.
*/
public int getHeight() {
return m_height;
}
/**
* Set the height of the frame.
*/
public void setHeight(int height) {
this.m_height = height;
}
/**
* Get the PixelFormat of the frame.
*/
public int getPixelFormat() {
return m_pixelFormat;
}
/**
* Set the PixelFormat of the frame.
*/
public void setPixelFormat(int pixelFormat) {
this.m_pixelFormat = pixelFormat;
}
}

View File

@@ -0,0 +1,68 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore.raw;
import edu.wpi.cscore.CameraServerJNI;
import edu.wpi.cscore.ImageSink;
/**
* A sink for user code to accept video frames as raw bytes.
*
* <p>This is a complex API, most cases should use CvSink.
*/
public class RawSink extends ImageSink {
/**
* Create a sink for accepting raw images.
*
* <p>grabFrame() must be called on the created sink to get each new
* image.
*
* @param name Source name (arbitrary unique identifier)
*/
public RawSink(String name) {
super(CameraServerJNI.createRawSink(name));
}
/**
* Wait for the next frame and get the image.
* Times out (returning 0) after 0.225 seconds.
* The provided image will have three 8-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call getError() to obtain the error
* message); the frame time is in the same time base as wpi::Now(),
* and is in 1 us increments.
*/
protected long grabFrame(RawFrame frame) {
return grabFrame(frame, 0.225);
}
/**
* Wait for the next frame and get the image.
* Times out (returning 0) after timeout seconds.
* The provided image will have three 8-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call getError() to obtain the error
* message); the frame time is in the same time base as wpi::Now(),
* and is in 1 us increments.
*/
protected long grabFrame(RawFrame frame, double timeout) {
return CameraServerJNI.grabSinkFrameTimeout(m_handle, frame, timeout);
}
/**
* Wait for the next frame and get the image. May block forever.
* The provided image will have three 8-bit channels stored in BGR order.
*
* @return Frame time, or 0 on error (call getError() to obtain the error
* message); the frame time is in the same time base as wpi::Now(),
* and is in 1 us increments.
*/
protected long grabFrameNoTimeout(RawFrame frame) {
return CameraServerJNI.grabSinkFrame(m_handle, frame);
}
}

View File

@@ -0,0 +1,85 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
package edu.wpi.cscore.raw;
import edu.wpi.cscore.CameraServerJNI;
import edu.wpi.cscore.ImageSource;
import edu.wpi.cscore.VideoMode;
/**
* A source for user code to provide video frames as raw bytes.
*
* <p>This is a complex API, most cases should use CvSource.
*/
public class RawSource extends ImageSource {
/**
* Create a raw frame source.
*
* @param name Source name (arbitrary unique identifier)
* @param mode Video mode being generated
*/
public RawSource(String name, VideoMode mode) {
super(CameraServerJNI.createRawSource(name,
mode.pixelFormat.getValue(),
mode.width, mode.height,
mode.fps));
}
/**
* Create a raw frame source.
*
* @param name Source name (arbitrary unique identifier)
* @param pixelFormat Pixel format
* @param width width
* @param height height
* @param fps fps
*/
public RawSource(String name, VideoMode.PixelFormat pixelFormat, int width, int height, int fps) {
super(CameraServerJNI.createRawSource(name,
pixelFormat.getValue(),
width, height,
fps));
}
/**
* Put a raw image and notify sinks.
*
* @param image raw frame image
*/
protected void putFrame(RawFrame image) {
CameraServerJNI.putRawSourceFrame(m_handle, image);
}
/**
* Put a raw image and notify sinks.
*
* @param data raw frame data pointer
* @param width frame width
* @param height frame height
* @param pixelFormat pixel format
* @param totalData length of data in total
*/
protected void putFrame(long data, int width, int height, int pixelFormat, int totalData) {
CameraServerJNI.putRawSourceFrame(m_handle, data, width, height, pixelFormat, totalData);
}
/**
* Put a raw image and notify sinks.
*
* @param data raw frame data pointer
* @param width frame width
* @param height frame height
* @param pixelFormat pixel format
* @param totalData length of data in total
*/
protected void putFrame(long data, int width, int height, VideoMode.PixelFormat pixelFormat,
int totalData) {
CameraServerJNI.putRawSourceFrame(m_handle, data, width, height, pixelFormat.getValue(),
totalData);
}
}

View File

@@ -0,0 +1,109 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "ConfigurableSourceImpl.h"
#include <wpi/timestamp.h>
#include "Handle.h"
#include "Instance.h"
#include "Log.h"
#include "Notifier.h"
using namespace cs;
ConfigurableSourceImpl::ConfigurableSourceImpl(const wpi::Twine& name,
wpi::Logger& logger,
Notifier& notifier,
Telemetry& telemetry,
const VideoMode& mode)
: SourceImpl{name, logger, notifier, telemetry} {
m_mode = mode;
m_videoModes.push_back(m_mode);
}
ConfigurableSourceImpl::~ConfigurableSourceImpl() {}
void ConfigurableSourceImpl::Start() {
m_notifier.NotifySource(*this, CS_SOURCE_CONNECTED);
m_notifier.NotifySource(*this, CS_SOURCE_VIDEOMODES_UPDATED);
m_notifier.NotifySourceVideoMode(*this, m_mode);
}
bool ConfigurableSourceImpl::SetVideoMode(const VideoMode& mode,
CS_Status* status) {
{
std::scoped_lock lock(m_mutex);
m_mode = mode;
m_videoModes[0] = mode;
}
m_notifier.NotifySourceVideoMode(*this, mode);
return true;
}
void ConfigurableSourceImpl::NumSinksChanged() {
// ignore
}
void ConfigurableSourceImpl::NumSinksEnabledChanged() {
// ignore
}
void ConfigurableSourceImpl::NotifyError(const wpi::Twine& msg) {
PutError(msg, wpi::Now());
}
int ConfigurableSourceImpl::CreateProperty(const wpi::Twine& name,
CS_PropertyKind kind, int minimum,
int maximum, int step,
int defaultValue, int value) {
std::scoped_lock lock(m_mutex);
int ndx = CreateOrUpdateProperty(name,
[=] {
return std::make_unique<PropertyImpl>(
name, kind, minimum, maximum, step,
defaultValue, value);
},
[&](PropertyImpl& prop) {
// update all but value
prop.propKind = kind;
prop.minimum = minimum;
prop.maximum = maximum;
prop.step = step;
prop.defaultValue = defaultValue;
value = prop.value;
});
m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CREATED, name, ndx,
kind, value, wpi::Twine{});
return ndx;
}
int ConfigurableSourceImpl::CreateProperty(
const wpi::Twine& name, CS_PropertyKind kind, int minimum, int maximum,
int step, int defaultValue, int value,
std::function<void(CS_Property property)> onChange) {
// TODO
return 0;
}
void ConfigurableSourceImpl::SetEnumPropertyChoices(
int property, wpi::ArrayRef<std::string> choices, CS_Status* status) {
std::scoped_lock lock(m_mutex);
auto prop = GetProperty(property);
if (!prop) {
*status = CS_INVALID_PROPERTY;
return;
}
if (prop->propKind != CS_PROP_ENUM) {
*status = CS_WRONG_PROPERTY_TYPE;
return;
}
prop->enumChoices = choices;
m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CHOICES_UPDATED,
prop->name, property, CS_PROP_ENUM,
prop->value, wpi::Twine{});
}

View File

@@ -0,0 +1,56 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#ifndef CSCORE_CONFIGURABLESOURCEIMPL_H_
#define CSCORE_CONFIGURABLESOURCEIMPL_H_
#include <atomic>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <wpi/ArrayRef.h>
#include <wpi/Twine.h>
#include "SourceImpl.h"
namespace cs {
class ConfigurableSourceImpl : public SourceImpl {
protected:
ConfigurableSourceImpl(const wpi::Twine& name, wpi::Logger& logger,
Notifier& notifier, Telemetry& telemetry,
const VideoMode& mode);
public:
~ConfigurableSourceImpl() override;
void Start() override;
bool SetVideoMode(const VideoMode& mode, CS_Status* status) override;
void NumSinksChanged() override;
void NumSinksEnabledChanged() override;
// OpenCV-specific functions
void NotifyError(const wpi::Twine& msg);
int CreateProperty(const wpi::Twine& name, CS_PropertyKind kind, int minimum,
int maximum, int step, int defaultValue, int value);
int CreateProperty(const wpi::Twine& name, CS_PropertyKind kind, int minimum,
int maximum, int step, int defaultValue, int value,
std::function<void(CS_Property property)> onChange);
void SetEnumPropertyChoices(int property, wpi::ArrayRef<std::string> choices,
CS_Status* status);
private:
std::atomic_bool m_connected{true};
};
} // namespace cs
#endif // CSCORE_CONFIGURABLESOURCEIMPL_H_

View File

@@ -0,0 +1,254 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "CvSinkImpl.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <wpi/SmallString.h>
#include "Handle.h"
#include "Instance.h"
#include "Log.h"
#include "Notifier.h"
#include "c_util.h"
#include "cscore_cpp.h"
using namespace cs;
CvSinkImpl::CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger,
Notifier& notifier, Telemetry& telemetry)
: SinkImpl{name, logger, notifier, telemetry} {
m_active = true;
// m_thread = std::thread(&CvSinkImpl::ThreadMain, this);
}
CvSinkImpl::CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger,
Notifier& notifier, Telemetry& telemetry,
std::function<void(uint64_t time)> processFrame)
: SinkImpl{name, logger, notifier, telemetry} {}
CvSinkImpl::~CvSinkImpl() { Stop(); }
void CvSinkImpl::Stop() {
m_active = false;
// wake up any waiters by forcing an empty frame to be sent
if (auto source = GetSource()) source->Wakeup();
// join thread
if (m_thread.joinable()) m_thread.join();
}
uint64_t CvSinkImpl::GrabFrame(cv::Mat& image) {
SetEnabled(true);
auto source = GetSource();
if (!source) {
// Source disconnected; sleep for one second
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
auto frame = source->GetNextFrame(); // blocks
if (!frame) {
// Bad frame; sleep for 20 ms so we don't consume all processor time.
std::this_thread::sleep_for(std::chrono::milliseconds(20));
return 0; // signal error
}
if (!frame.GetCv(image)) {
// Shouldn't happen, but just in case...
std::this_thread::sleep_for(std::chrono::milliseconds(20));
return 0;
}
return frame.GetTime();
}
uint64_t CvSinkImpl::GrabFrame(cv::Mat& image, double timeout) {
SetEnabled(true);
auto source = GetSource();
if (!source) {
// Source disconnected; sleep for one second
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
auto frame = source->GetNextFrame(timeout); // blocks
if (!frame) {
// Bad frame; sleep for 20 ms so we don't consume all processor time.
std::this_thread::sleep_for(std::chrono::milliseconds(20));
return 0; // signal error
}
if (!frame.GetCv(image)) {
// Shouldn't happen, but just in case...
std::this_thread::sleep_for(std::chrono::milliseconds(20));
return 0;
}
return frame.GetTime();
}
// Send HTTP response and a stream of JPG-frames
void CvSinkImpl::ThreadMain() {
Enable();
while (m_active) {
auto source = GetSource();
if (!source) {
// Source disconnected; sleep for one second
std::this_thread::sleep_for(std::chrono::seconds(1));
continue;
}
SDEBUG4("waiting for frame");
Frame frame = source->GetNextFrame(); // blocks
if (!m_active) break;
if (!frame) {
// Bad frame; sleep for 10 ms so we don't consume all processor time.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
continue;
}
// TODO m_processFrame();
}
Disable();
}
namespace cs {
CS_Sink CreateCvSink(const wpi::Twine& name, CS_Status* status) {
auto& inst = Instance::GetInstance();
return inst.CreateSink(
CS_SINK_CV, std::make_shared<CvSinkImpl>(name, inst.logger, inst.notifier,
inst.telemetry));
}
CS_Sink CreateCvSinkCallback(const wpi::Twine& name,
std::function<void(uint64_t time)> processFrame,
CS_Status* status) {
auto& inst = Instance::GetInstance();
return inst.CreateSink(
CS_SINK_CV, std::make_shared<CvSinkImpl>(name, inst.logger, inst.notifier,
inst.telemetry, processFrame));
}
static constexpr unsigned SinkMask = CS_SINK_CV | CS_SINK_RAW;
void SetSinkDescription(CS_Sink sink, const wpi::Twine& description,
CS_Status* status) {
auto data = Instance::GetInstance().GetSink(sink);
if (!data || (data->kind & SinkMask) == 0) {
*status = CS_INVALID_HANDLE;
return;
}
static_cast<CvSinkImpl&>(*data->sink).SetDescription(description);
}
uint64_t GrabSinkFrame(CS_Sink sink, cv::Mat& image, CS_Status* status) {
auto data = Instance::GetInstance().GetSink(sink);
if (!data || data->kind != CS_SINK_CV) {
*status = CS_INVALID_HANDLE;
return 0;
}
return static_cast<CvSinkImpl&>(*data->sink).GrabFrame(image);
}
uint64_t GrabSinkFrameTimeout(CS_Sink sink, cv::Mat& image, double timeout,
CS_Status* status) {
auto data = Instance::GetInstance().GetSink(sink);
if (!data || data->kind != CS_SINK_CV) {
*status = CS_INVALID_HANDLE;
return 0;
}
return static_cast<CvSinkImpl&>(*data->sink).GrabFrame(image, timeout);
}
std::string GetSinkError(CS_Sink sink, CS_Status* status) {
auto data = Instance::GetInstance().GetSink(sink);
if (!data || (data->kind & SinkMask) == 0) {
*status = CS_INVALID_HANDLE;
return std::string{};
}
return static_cast<CvSinkImpl&>(*data->sink).GetError();
}
wpi::StringRef GetSinkError(CS_Sink sink, wpi::SmallVectorImpl<char>& buf,
CS_Status* status) {
auto data = Instance::GetInstance().GetSink(sink);
if (!data || (data->kind & SinkMask) == 0) {
*status = CS_INVALID_HANDLE;
return wpi::StringRef{};
}
return static_cast<CvSinkImpl&>(*data->sink).GetError(buf);
}
void SetSinkEnabled(CS_Sink sink, bool enabled, CS_Status* status) {
auto data = Instance::GetInstance().GetSink(sink);
if (!data || (data->kind & SinkMask) == 0) {
*status = CS_INVALID_HANDLE;
return;
}
static_cast<CvSinkImpl&>(*data->sink).SetEnabled(enabled);
}
} // namespace cs
extern "C" {
CS_Sink CS_CreateCvSink(const char* name, CS_Status* status) {
return cs::CreateCvSink(name, status);
}
CS_Sink CS_CreateCvSinkCallback(const char* name, void* data,
void (*processFrame)(void* data, uint64_t time),
CS_Status* status) {
return cs::CreateCvSinkCallback(
name, [=](uint64_t time) { processFrame(data, time); }, status);
}
void CS_SetSinkDescription(CS_Sink sink, const char* description,
CS_Status* status) {
return cs::SetSinkDescription(sink, description, status);
}
#if CV_VERSION_MAJOR < 4
uint64_t CS_GrabSinkFrame(CS_Sink sink, struct CvMat* image,
CS_Status* status) {
auto mat = cv::cvarrToMat(image);
return cs::GrabSinkFrame(sink, mat, status);
}
uint64_t CS_GrabSinkFrameTimeout(CS_Sink sink, struct CvMat* image,
double timeout, CS_Status* status) {
auto mat = cv::cvarrToMat(image);
return cs::GrabSinkFrameTimeout(sink, mat, timeout, status);
}
#endif // CV_VERSION_MAJOR < 4
uint64_t CS_GrabSinkFrameCpp(CS_Sink sink, cv::Mat* image, CS_Status* status) {
return cs::GrabSinkFrame(sink, *image, status);
}
uint64_t CS_GrabSinkFrameTimeoutCpp(CS_Sink sink, cv::Mat* image,
double timeout, CS_Status* status) {
return cs::GrabSinkFrameTimeout(sink, *image, timeout, status);
}
char* CS_GetSinkError(CS_Sink sink, CS_Status* status) {
wpi::SmallString<128> buf;
auto str = cs::GetSinkError(sink, buf, status);
if (*status != 0) return nullptr;
return cs::ConvertToC(str);
}
void CS_SetSinkEnabled(CS_Sink sink, CS_Bool enabled, CS_Status* status) {
return cs::SetSinkEnabled(sink, enabled, status);
}
} // extern "C"

View File

@@ -0,0 +1,52 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#ifndef CSCORE_CVSINKIMPL_H_
#define CSCORE_CVSINKIMPL_H_
#include <stdint.h>
#include <atomic>
#include <functional>
#include <thread>
#include <opencv2/core/core.hpp>
#include <wpi/Twine.h>
#include <wpi/condition_variable.h>
#include "Frame.h"
#include "SinkImpl.h"
namespace cs {
class SourceImpl;
class CvSinkImpl : public SinkImpl {
public:
CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier,
Telemetry& telemetry);
CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier,
Telemetry& telemetry,
std::function<void(uint64_t time)> processFrame);
~CvSinkImpl() override;
void Stop();
uint64_t GrabFrame(cv::Mat& image);
uint64_t GrabFrame(cv::Mat& image, double timeout);
private:
void ThreadMain();
std::atomic_bool m_active; // set to false to terminate threads
std::thread m_thread;
std::function<void(uint64_t time)> m_processFrame;
};
} // namespace cs
#endif // CSCORE_CVSINKIMPL_H_

View File

@@ -0,0 +1,234 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "CvSourceImpl.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <wpi/STLExtras.h>
#include <wpi/timestamp.h>
#include "Handle.h"
#include "Instance.h"
#include "Log.h"
#include "Notifier.h"
#include "c_util.h"
#include "cscore_cpp.h"
using namespace cs;
CvSourceImpl::CvSourceImpl(const wpi::Twine& name, wpi::Logger& logger,
Notifier& notifier, Telemetry& telemetry,
const VideoMode& mode)
: ConfigurableSourceImpl{name, logger, notifier, telemetry, mode} {}
CvSourceImpl::~CvSourceImpl() {}
void CvSourceImpl::PutFrame(cv::Mat& image) {
// We only support 8-bit images; convert if necessary.
cv::Mat finalImage;
if (image.depth() == CV_8U)
finalImage = image;
else
image.convertTo(finalImage, CV_8U);
std::unique_ptr<Image> dest;
switch (image.channels()) {
case 1:
dest =
AllocImage(VideoMode::kGray, image.cols, image.rows, image.total());
finalImage.copyTo(dest->AsMat());
break;
case 3:
dest = AllocImage(VideoMode::kBGR, image.cols, image.rows,
image.total() * 3);
finalImage.copyTo(dest->AsMat());
break;
case 4:
dest = AllocImage(VideoMode::kBGR, image.cols, image.rows,
image.total() * 3);
cv::cvtColor(finalImage, dest->AsMat(), cv::COLOR_BGRA2BGR);
break;
default:
SERROR("PutFrame: " << image.channels()
<< "-channel images not supported");
return;
}
SourceImpl::PutFrame(std::move(dest), wpi::Now());
}
namespace cs {
CS_Source CreateCvSource(const wpi::Twine& name, const VideoMode& mode,
CS_Status* status) {
auto& inst = Instance::GetInstance();
return inst.CreateSource(CS_SOURCE_CV, std::make_shared<CvSourceImpl>(
name, inst.logger, inst.notifier,
inst.telemetry, mode));
}
void PutSourceFrame(CS_Source source, cv::Mat& image, CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || data->kind != CS_SOURCE_CV) {
*status = CS_INVALID_HANDLE;
return;
}
static_cast<CvSourceImpl&>(*data->source).PutFrame(image);
}
static constexpr unsigned SourceMask = CS_SINK_CV | CS_SINK_RAW;
void NotifySourceError(CS_Source source, const wpi::Twine& msg,
CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || (data->kind & SourceMask) == 0) {
*status = CS_INVALID_HANDLE;
return;
}
static_cast<CvSourceImpl&>(*data->source).NotifyError(msg);
}
void SetSourceConnected(CS_Source source, bool connected, CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || (data->kind & SourceMask) == 0) {
*status = CS_INVALID_HANDLE;
return;
}
static_cast<CvSourceImpl&>(*data->source).SetConnected(connected);
}
void SetSourceDescription(CS_Source source, const wpi::Twine& description,
CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || (data->kind & SourceMask) == 0) {
*status = CS_INVALID_HANDLE;
return;
}
static_cast<CvSourceImpl&>(*data->source).SetDescription(description);
}
CS_Property CreateSourceProperty(CS_Source source, const wpi::Twine& name,
CS_PropertyKind kind, int minimum, int maximum,
int step, int defaultValue, int value,
CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || (data->kind & SourceMask) == 0) {
*status = CS_INVALID_HANDLE;
return -1;
}
int property = static_cast<CvSourceImpl&>(*data->source)
.CreateProperty(name, kind, minimum, maximum, step,
defaultValue, value);
return Handle{source, property, Handle::kProperty};
}
CS_Property CreateSourcePropertyCallback(
CS_Source source, const wpi::Twine& name, CS_PropertyKind kind, int minimum,
int maximum, int step, int defaultValue, int value,
std::function<void(CS_Property property)> onChange, CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || (data->kind & SourceMask) == 0) {
*status = CS_INVALID_HANDLE;
return -1;
}
int property = static_cast<CvSourceImpl&>(*data->source)
.CreateProperty(name, kind, minimum, maximum, step,
defaultValue, value, onChange);
return Handle{source, property, Handle::kProperty};
}
void SetSourceEnumPropertyChoices(CS_Source source, CS_Property property,
wpi::ArrayRef<std::string> choices,
CS_Status* status) {
auto data = Instance::GetInstance().GetSource(source);
if (!data || (data->kind & SourceMask) == 0) {
*status = CS_INVALID_HANDLE;
return;
}
// Get property index; also validate the source owns this property
Handle handle{property};
int i = handle.GetParentIndex();
if (i < 0) {
*status = CS_INVALID_HANDLE;
return;
}
auto data2 = Instance::GetInstance().GetSource(Handle{i, Handle::kSource});
if (!data2 || data->source.get() != data2->source.get()) {
*status = CS_INVALID_HANDLE;
return;
}
int propertyIndex = handle.GetIndex();
static_cast<CvSourceImpl&>(*data->source)
.SetEnumPropertyChoices(propertyIndex, choices, status);
}
} // namespace cs
extern "C" {
CS_Source CS_CreateCvSource(const char* name, const CS_VideoMode* mode,
CS_Status* status) {
return cs::CreateCvSource(name, static_cast<const cs::VideoMode&>(*mode),
status);
}
#if CV_VERSION_MAJOR < 4
void CS_PutSourceFrame(CS_Source source, struct CvMat* image,
CS_Status* status) {
auto mat = cv::cvarrToMat(image);
return cs::PutSourceFrame(source, mat, status);
}
#endif // CV_VERSION_MAJOR < 4
void CS_PutSourceFrameCpp(CS_Source source, cv::Mat* image, CS_Status* status) {
return cs::PutSourceFrame(source, *image, status);
}
void CS_NotifySourceError(CS_Source source, const char* msg,
CS_Status* status) {
return cs::NotifySourceError(source, msg, status);
}
void CS_SetSourceConnected(CS_Source source, CS_Bool connected,
CS_Status* status) {
return cs::SetSourceConnected(source, connected, status);
}
void CS_SetSourceDescription(CS_Source source, const char* description,
CS_Status* status) {
return cs::SetSourceDescription(source, description, status);
}
CS_Property CS_CreateSourceProperty(CS_Source source, const char* name,
enum CS_PropertyKind kind, int minimum,
int maximum, int step, int defaultValue,
int value, CS_Status* status) {
return cs::CreateSourceProperty(source, name, kind, minimum, maximum, step,
defaultValue, value, status);
}
CS_Property CS_CreateSourcePropertyCallback(
CS_Source source, const char* name, enum CS_PropertyKind kind, int minimum,
int maximum, int step, int defaultValue, int value, void* data,
void (*onChange)(void* data, CS_Property property), CS_Status* status) {
return cs::CreateSourcePropertyCallback(
source, name, kind, minimum, maximum, step, defaultValue, value,
[=](CS_Property property) { onChange(data, property); }, status);
}
void CS_SetSourceEnumPropertyChoices(CS_Source source, CS_Property property,
const char** choices, int count,
CS_Status* status) {
wpi::SmallVector<std::string, 8> vec;
vec.reserve(count);
for (int i = 0; i < count; ++i) vec.push_back(choices[i]);
return cs::SetSourceEnumPropertyChoices(source, property, vec, status);
}
} // extern "C"

View File

@@ -0,0 +1,41 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#ifndef CSCORE_CVSOURCEIMPL_H_
#define CSCORE_CVSOURCEIMPL_H_
#include <atomic>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <opencv2/core/core.hpp>
#include <wpi/ArrayRef.h>
#include <wpi/Twine.h>
#include "ConfigurableSourceImpl.h"
#include "SourceImpl.h"
namespace cs {
class CvSourceImpl : public ConfigurableSourceImpl {
public:
CvSourceImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier,
Telemetry& telemetry, const VideoMode& mode);
~CvSourceImpl() override;
// OpenCV-specific functions
void PutFrame(cv::Mat& image);
private:
std::atomic_bool m_connected{true};
};
} // namespace cs
#endif // CSCORE_CVSOURCEIMPL_H_

View File

@@ -0,0 +1,499 @@
/*----------------------------------------------------------------------------*/
/* 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. */
/*----------------------------------------------------------------------------*/
#include "Frame.h"
#include <cstdlib>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "Instance.h"
#include "Log.h"
#include "SourceImpl.h"
using namespace cs;
Frame::Frame(SourceImpl& source, const wpi::Twine& error, Time time)
: m_impl{source.AllocFrameImpl().release()} {
m_impl->refcount = 1;
m_impl->error = error.str();
m_impl->time = time;
}
Frame::Frame(SourceImpl& source, std::unique_ptr<Image> image, Time time)
: m_impl{source.AllocFrameImpl().release()} {
m_impl->refcount = 1;
m_impl->error.resize(0);
m_impl->time = time;
m_impl->images.push_back(image.release());
}
Image* Frame::GetNearestImage(int width, int height) const {
if (!m_impl) return nullptr;
std::scoped_lock lock(m_impl->mutex);
Image* found = nullptr;
// Ideally we want the smallest image at least width/height in size
for (auto i : m_impl->images) {
if (i->IsLarger(width, height) && (!found || (i->IsSmaller(*found))))
found = i;
}
if (found) return found;
// Find the largest image (will be less than width/height)
for (auto i : m_impl->images) {
if (!found || (i->IsLarger(*found))) found = i;
}
if (found) return found;
// Shouldn't reach this, but just in case...
return m_impl->images.empty() ? nullptr : m_impl->images[0];
}
Image* Frame::GetNearestImage(int width, int height,
VideoMode::PixelFormat pixelFormat,
int jpegQuality) const {
if (!m_impl) return nullptr;
std::scoped_lock lock(m_impl->mutex);
Image* found = nullptr;
// We want the smallest image at least width/height (or the next largest),
// but the primary search order is in order of conversion cost.
// If we don't find exactly what we want, we prefer non-JPEG source images
// (because JPEG source images require a decompression step).
// While the searching takes a little time, it pales in comparison to the
// image processing to come, so it's worth spending a little extra time
// looking for the most efficient conversion.
// 1) Same width, height, pixelFormat, and (possibly) JPEG quality
// (e.g. exactly what we want)
for (auto i : m_impl->images) {
if (i->Is(width, height, pixelFormat, jpegQuality)) return i;
}
// 2) Same width, height, different (but non-JPEG) pixelFormat (color conv)
// 2a) If we want JPEG output, prefer BGR over other pixel formats
if (pixelFormat == VideoMode::kMJPEG) {
for (auto i : m_impl->images) {
if (i->Is(width, height, VideoMode::kBGR)) return i;
}
}
for (auto i : m_impl->images) {
if (i->Is(width, height) && i->pixelFormat != VideoMode::kMJPEG) return i;
}
// 3) Different width, height, same pixelFormat (only if non-JPEG) (resample)
if (pixelFormat != VideoMode::kMJPEG) {
// 3a) Smallest image at least width/height in size
for (auto i : m_impl->images) {
if (i->IsLarger(width, height) && i->pixelFormat == pixelFormat &&
(!found || (i->IsSmaller(*found))))
found = i;
}
if (found) return found;
// 3b) Largest image (less than width/height)
for (auto i : m_impl->images) {
if (i->pixelFormat == pixelFormat && (!found || (i->IsLarger(*found))))
found = i;
}
if (found) return found;
}
// 4) Different width, height, different (but non-JPEG) pixelFormat
// (color conversion + resample)
// 4a) Smallest image at least width/height in size
for (auto i : m_impl->images) {
if (i->IsLarger(width, height) && i->pixelFormat != VideoMode::kMJPEG &&
(!found || (i->IsSmaller(*found))))
found = i;
}
if (found) return found;
// 4b) Largest image (less than width/height)
for (auto i : m_impl->images) {
if (i->pixelFormat != VideoMode::kMJPEG &&
(!found || (i->IsLarger(*found))))
found = i;
}
if (found) return found;
// 5) Same width, height, JPEG pixelFormat (decompression). As there may be
// multiple JPEG images, find the highest quality one.
for (auto i : m_impl->images) {
if (i->Is(width, height, VideoMode::kMJPEG) &&
(!found || i->jpegQuality > found->jpegQuality)) {
found = i;
// consider one without a quality setting to be the highest quality
// (e.g. directly from the camera)
if (i->jpegQuality == -1) break;
}
}
if (found) return found;
// 6) Different width, height, JPEG pixelFormat (decompression)
// 6a) Smallest image at least width/height in size
for (auto i : m_impl->images) {
if (i->IsLarger(width, height) && i->pixelFormat == VideoMode::kMJPEG &&
(!found || (i->IsSmaller(*found))))
found = i;
}
if (found) return found;
// 6b) Largest image (less than width/height)
for (auto i : m_impl->images) {
if (i->pixelFormat != VideoMode::kMJPEG &&
(!found || (i->IsLarger(*found))))
found = i;
}
if (found) return found;
// Shouldn't reach this, but just in case...
return m_impl->images.empty() ? nullptr : m_impl->images[0];
}
Image* Frame::ConvertImpl(Image* image, VideoMode::PixelFormat pixelFormat,
int requiredJpegQuality, int defaultJpegQuality) {
if (!image ||
image->Is(image->width, image->height, pixelFormat, requiredJpegQuality))
return image;
Image* cur = image;
// If the source image is a JPEG, we need to decode it before we can do
// anything else with it. Note that if the destination format is JPEG, we
// still need to do this (unless it was already a JPEG, in which case we
// would have returned above).
if (cur->pixelFormat == VideoMode::kMJPEG) {
cur = ConvertMJPEGToBGR(cur);
if (pixelFormat == VideoMode::kBGR) return cur;
}
// Color convert
switch (pixelFormat) {
case VideoMode::kRGB565:
// If source is YUYV or Gray, need to convert to BGR first
if (cur->pixelFormat == VideoMode::kYUYV) {
// Check to see if BGR version already exists...
if (Image* newImage =
GetExistingImage(cur->width, cur->height, VideoMode::kBGR))
cur = newImage;
else
cur = ConvertYUYVToBGR(cur);
} else if (cur->pixelFormat == VideoMode::kGray) {
// Check to see if BGR version already exists...
if (Image* newImage =
GetExistingImage(cur->width, cur->height, VideoMode::kBGR))
cur = newImage;
else
cur = ConvertGrayToBGR(cur);
}
return ConvertBGRToRGB565(cur);
case VideoMode::kGray:
// If source is YUYV or RGB565, need to convert to BGR first
if (cur->pixelFormat == VideoMode::kYUYV) {
// Check to see if BGR version already exists...
if (Image* newImage =
GetExistingImage(cur->width, cur->height, VideoMode::kBGR))
cur = newImage;
else
cur = ConvertYUYVToBGR(cur);
} else if (cur->pixelFormat == VideoMode::kRGB565) {
// Check to see if BGR version already exists...
if (Image* newImage =
GetExistingImage(cur->width, cur->height, VideoMode::kBGR))
cur = newImage;
else
cur = ConvertRGB565ToBGR(cur);
}
return ConvertBGRToGray(cur);
case VideoMode::kBGR:
case VideoMode::kMJPEG:
if (cur->pixelFormat == VideoMode::kYUYV) {
cur = ConvertYUYVToBGR(cur);
} else if (cur->pixelFormat == VideoMode::kRGB565) {
cur = ConvertRGB565ToBGR(cur);
} else if (cur->pixelFormat == VideoMode::kGray) {
if (pixelFormat == VideoMode::kBGR)
return ConvertGrayToBGR(cur);
else
return ConvertGrayToMJPEG(cur, defaultJpegQuality);
}
break;
case VideoMode::kYUYV:
default:
return nullptr; // Unsupported
}
// Compress if destination is JPEG
if (pixelFormat == VideoMode::kMJPEG)
cur = ConvertBGRToMJPEG(cur, defaultJpegQuality);
return cur;
}
Image* Frame::ConvertMJPEGToBGR(Image* image) {
if (!image || image->pixelFormat != VideoMode::kMJPEG) return nullptr;
// Allocate an BGR image
auto newImage =
m_impl->source.AllocImage(VideoMode::kBGR, image->width, image->height,
image->width * image->height * 3);
// Decode
cv::Mat newMat = newImage->AsMat();
cv::imdecode(image->AsInputArray(), cv::IMREAD_COLOR, &newMat);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertMJPEGToGray(Image* image) {
if (!image || image->pixelFormat != VideoMode::kMJPEG) return nullptr;
// Allocate an grayscale image
auto newImage =
m_impl->source.AllocImage(VideoMode::kGray, image->width, image->height,
image->width * image->height);
// Decode
cv::Mat newMat = newImage->AsMat();
cv::imdecode(image->AsInputArray(), cv::IMREAD_GRAYSCALE, &newMat);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertYUYVToBGR(Image* image) {
if (!image || image->pixelFormat != VideoMode::kYUYV) return nullptr;
// Allocate a BGR image
auto newImage =
m_impl->source.AllocImage(VideoMode::kBGR, image->width, image->height,
image->width * image->height * 3);
// Convert
cv::cvtColor(image->AsMat(), newImage->AsMat(), cv::COLOR_YUV2BGR_YUYV);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertBGRToRGB565(Image* image) {
if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr;
// Allocate a RGB565 image
auto newImage =
m_impl->source.AllocImage(VideoMode::kRGB565, image->width, image->height,
image->width * image->height * 2);
// Convert
cv::cvtColor(image->AsMat(), newImage->AsMat(), cv::COLOR_RGB2BGR565);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertRGB565ToBGR(Image* image) {
if (!image || image->pixelFormat != VideoMode::kRGB565) return nullptr;
// Allocate a BGR image
auto newImage =
m_impl->source.AllocImage(VideoMode::kBGR, image->width, image->height,
image->width * image->height * 3);
// Convert
cv::cvtColor(image->AsMat(), newImage->AsMat(), cv::COLOR_BGR5652RGB);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertBGRToGray(Image* image) {
if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr;
// Allocate a Grayscale image
auto newImage =
m_impl->source.AllocImage(VideoMode::kGray, image->width, image->height,
image->width * image->height);
// Convert
cv::cvtColor(image->AsMat(), newImage->AsMat(), cv::COLOR_BGR2GRAY);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertGrayToBGR(Image* image) {
if (!image || image->pixelFormat != VideoMode::kGray) return nullptr;
// Allocate a BGR image
auto newImage =
m_impl->source.AllocImage(VideoMode::kBGR, image->width, image->height,
image->width * image->height * 3);
// Convert
cv::cvtColor(image->AsMat(), newImage->AsMat(), cv::COLOR_GRAY2BGR);
// Save the result
Image* rv = newImage.release();
if (m_impl) {
std::scoped_lock lock(m_impl->mutex);
m_impl->images.push_back(rv);
}
return rv;
}
Image* Frame::ConvertBGRToMJPEG(Image* image, int quality) {
if (!image || image->pixelFormat != VideoMode::kBGR) return nullptr;
if (!m_impl) return nullptr;
std::scoped_lock lock(m_impl->mutex);
// Allocate a JPEG image. We don't actually know what the resulting size
// will be; while the destination will automatically grow, doing so will
// cause an extra malloc, so we don't want to be too conservative here.
// Per Wikipedia, Q=100 on a sample image results in 8.25 bits per pixel,
// this is a little bit more conservative in assuming 50% space savings over
// the equivalent BGR image.
auto newImage =
m_impl->source.AllocImage(VideoMode::kMJPEG, image->width, image->height,
image->width * image->height * 1.5);
// Compress
if (m_impl->compressionParams.empty()) {
m_impl->compressionParams.push_back(cv::IMWRITE_JPEG_QUALITY);
m_impl->compressionParams.push_back(quality);
} else {
m_impl->compressionParams[1] = quality;
}
cv::imencode(".jpg", image->AsMat(), newImage->vec(),
m_impl->compressionParams);
// Save the result
Image* rv = newImage.release();
m_impl->images.push_back(rv);
return rv;
}
Image* Frame::ConvertGrayToMJPEG(Image* image, int quality) {
if (!image || image->pixelFormat != VideoMode::kGray) return nullptr;
if (!m_impl) return nullptr;
std::scoped_lock lock(m_impl->mutex);
// Allocate a JPEG image. We don't actually know what the resulting size
// will be; while the destination will automatically grow, doing so will
// cause an extra malloc, so we don't want to be too conservative here.
// Per Wikipedia, Q=100 on a sample image results in 8.25 bits per pixel,
// this is a little bit more conservative in assuming 25% space savings over
// the equivalent grayscale image.
auto newImage =
m_impl->source.AllocImage(VideoMode::kMJPEG, image->width, image->height,
image->width * image->height * 0.75);
// Compress
if (m_impl->compressionParams.empty()) {
m_impl->compressionParams.push_back(cv::IMWRITE_JPEG_QUALITY);
m_impl->compressionParams.push_back(quality);
} else {
m_impl->compressionParams[1] = quality;
}
cv::imencode(".jpg", image->AsMat(), newImage->vec(),
m_impl->compressionParams);
// Save the result
Image* rv = newImage.release();
m_impl->images.push_back(rv);
return rv;
}
Image* Frame::GetImageImpl(int width, int height,
VideoMode::PixelFormat pixelFormat,
int requiredJpegQuality, int defaultJpegQuality) {
if (!m_impl) return nullptr;
std::scoped_lock lock(m_impl->mutex);
Image* cur = GetNearestImage(width, height, pixelFormat, requiredJpegQuality);
if (!cur || cur->Is(width, height, pixelFormat, requiredJpegQuality))
return cur;
WPI_DEBUG4(Instance::GetInstance().logger,
"converting image from " << cur->width << "x" << cur->height
<< " type " << cur->pixelFormat << " to "
<< width << "x" << height << " type "
<< pixelFormat);
// If the source image is a JPEG, we need to decode it before we can do
// anything else with it. Note that if the destination format is JPEG, we
// still need to do this (unless the width/height/compression were the same,
// in which case we already returned the existing JPEG above).
if (cur->pixelFormat == VideoMode::kMJPEG) cur = ConvertMJPEGToBGR(cur);
// Resize
if (!cur->Is(width, height)) {
// Allocate an image.
auto newImage = m_impl->source.AllocImage(
cur->pixelFormat, width, height,
width * height * (cur->size() / (cur->width * cur->height)));
// Resize
cv::Mat newMat = newImage->AsMat();
cv::resize(cur->AsMat(), newMat, newMat.size(), 0, 0);
// Save the result
cur = newImage.release();
m_impl->images.push_back(cur);
}
// Convert to output format
return ConvertImpl(cur, pixelFormat, requiredJpegQuality, defaultJpegQuality);
}
bool Frame::GetCv(cv::Mat& image, int width, int height) {
Image* rawImage = GetImage(width, height, VideoMode::kBGR);
if (!rawImage) return false;
rawImage->AsMat().copyTo(image);
return true;
}
void Frame::ReleaseFrame() {
for (auto image : m_impl->images)
m_impl->source.ReleaseImage(std::unique_ptr<Image>(image));
m_impl->images.clear();
m_impl->source.ReleaseFrameImpl(std::unique_ptr<Impl>(m_impl));
m_impl = nullptr;
}

Some files were not shown because too many files have changed in this diff Show More