Compare commits

...

347 Commits

Author SHA1 Message Date
Peter Johnson
e375b4a9ff CameraServer: auto-increment startAutomaticCapture(). (#468)
Also add GetServer() functions so the automatically created VideoSink can
be retrieved by user code if desired.
2017-01-20 01:07:37 -07:00
Thad House
ff141ab1ff Fixes exception on camera creation without plugged in camera (#470)
Would throw if the camera was disconnected. We handle this properly at
the JNI level to not have this crash the entire program, but the error
is still kind of annoying, and not really an error.
2017-01-20 01:02:27 -07:00
Peter Johnson
b8537be219 CameraServer: Remove NT-driven settings. (#467)
Unfortunately, due to the way NT synchronization is currently performed,
this has unexpected and undesirable behavior: when a dashboard (or any other
NT client) is left running between code restarts, when it reconnects, any
code settings will be overwritten by the NT synchronization process.  As
fixing this will require a fairly major NT change (and likely a user-visible
one), it's not desirable to do at this point in the year.

Instead, disable NT driven settings entirely (e.g. make the NT interface
publish only).  To emphasize the read-only nature of the NT values, attempts
to change the NT values will be immediately overridden by CameraServer.

To better inform users about the actual property names (e.g. for use in their
code), the "raw_" settings no longer have "raw_" removed from their names
(they are still placed in the "RawProperty" subtable).

This change also contains a couple of Java fixes:

* Make getInstance() thread-safe

* Properly synchronize access to m_tables between multiple threads.

* Use Hashtable instead of HashMap.
2017-01-19 12:30:07 -07:00
Austin Shalit
8f1b034b2f Fix typo in JavaDoc (#462) 2017-01-16 22:57:28 -07:00
Thad House
71d0a07e0a Fixes solenoid allocation error message (#455)
The error was NO_AVAILABLE_RESOURCES, which is not the proper error to
return. Instead,  just return the error directly from the allocation.
2017-01-14 23:59:05 -07:00
sciencewhiz
d322342494 Remove comments about Blue DS (#450)
It's unlikely that anyone is still using the Blue Kwikbyte DS from 2009,
and the reference is confusing to people who weren't around then.
2017-01-14 23:52:48 -07:00
Peter Johnson
bc7ab17692 CameraServer updates (#446)
* CameraServer: Add properties and video mode NT interchange.

* Automatically serve Axis cameras so they're accessible via USB.
2017-01-05 02:51:55 -08:00
Tyler Veness
7a049c29bd Added a conditional command that chooses 1 of 2 commands (#435)
Tests and documentation for ConditionalCommand were also added. This is a fixed version of #9, so it doesn't support lambdas.

Closes #9
2017-01-04 23:48:13 -08:00
Thad House
1fc375b31a Updates the gradle wrapper to version 3.3 (#445) 2017-01-04 22:08:48 -08:00
Austin Shalit
eee7f3991c Allow VisionRunner to stop (#442) 2017-01-04 19:41:07 -08:00
Thad House
2e3503517d Add OS level serial port (#426) 2017-01-04 19:38:17 -08:00
Austin Shalit
15e58acc76 Java SendableChooser no longer sets a default on addObject (#441) 2017-01-03 19:13:45 -08:00
Austin Shalit
5aa5e3e09e SendableChooser generic value (#433)
* Java SendableChooser now decorates with type (non-breaking change)

* C++ SendableChooser now is templated on the type instead of using void* and stores values (breaking change)

* C++ SendableChooser now uses llvm::StringMap instead of std::map
2017-01-03 14:40:31 -08:00
Tyler Veness
25ae7b2c2b Upgraded Doxygen gradle plugin to 0.3 (#440) 2017-01-02 10:03:37 -08:00
Tyler Veness
4b6dc9583a Corrected order of access specifiers in MockCommand class (#436) 2017-01-02 00:44:35 -08:00
Thad House
64eab1f7b3 Fixes missing Extern "C" from HAL Threads (#437)
Also fixes incorrect return value during set
2017-01-02 00:43:12 -08:00
Thad House
182f57216f Adds project and classpath ignores (#425)
VsCode now supports Java, but it creates these files, and there is no
way to turn it off. Will be adding this to a few other repos too.
2017-01-01 00:08:13 -08:00
Tyler Veness
65b091a39a Call SmartDashboard::init() in RobotBase constructor. (#428)
Fixes #427
2017-01-01 00:07:22 -08:00
Austin Shalit
ed1a94531a Update license headers to 2017 (#434) 2017-01-01 00:05:57 -08:00
Fred Silberberg
4e12ffb0ae Update the wpilib version plugin (#423) 2016-12-25 23:01:03 -08:00
Peter Johnson
4800c201e4 Add Axis camera creation functions and Http camera NT publishing. (#420) 2016-12-24 21:05:08 -06:00
Thad House
dc9a9e5d96 Fixes typo in SensorBase error message (#422) 2016-12-24 21:04:32 -06:00
Thad House
6844f05c3d Adds SetAllSolenoids function to CTRE PCM code (#419)
Closes #417.
2016-12-23 14:35:45 -06:00
Austin Shalit
8f67f2c24c Remove unused code and add pmd check (#395) 2016-12-23 13:20:13 -06:00
Thad House
cc246bb9ac Switches JNI to use new jni_util methods (#404)
* Uses WPIUtil string objects in JNI

* Switches JNI to use new jni_util classes
2016-12-23 13:13:17 -06:00
Sam Carlberg
bf9f0a9e6d Add vision pipeline API to make it easier to run OpenCV pipelines (#388) 2016-12-23 10:48:56 -06:00
Austin Shalit
c3160bad44 Update SendableChooser to use HashMap (#394) 2016-12-22 15:56:23 -08:00
Thad House
94b8ac42ca Adds CPP version of vision pipeline (#399) 2016-12-21 23:58:42 -06:00
Thad House
a03e3d7eb9 Fixes HAL to build without all headers included in HAL.h (#418) 2016-12-21 23:55:31 -06:00
Jaci R
a42ec08d16 Fix RoboRIO Cross-Toolchain GCC Status (#405)
* Dedicated RoboRIO Toolchain, allow Toolchain Path to change

* Add cCompiler Tool to correctly discover RoboRIO GCC on Mac

* Add @333fred requests for GString and ToolChainPath

* Add Toolchain Path option to README
2016-12-21 19:56:28 -08:00
Thad House
fddb6cd9d8 Fixes SPI Accumulator averages (#415) 2016-12-21 20:17:53 -06:00
Thad House
841f016017 Fixes SerialHelper when used with OS serial ports. (#411)
Also makes the SerialHelper API public so it can be used externally.
2016-12-21 00:16:05 -06:00
Thad House
8e4afc95c7 Switches C++ strings to StringRef (#336) 2016-12-21 00:08:24 -06:00
Tyler Veness
8cec948699 Fix typos (#409) 2016-12-19 22:06:39 -06:00
Tyler Veness
31ae7c942c Fixed signatures of deleted assignment operators (#408)
While it technically doesn't matter what the return type of the assignment operator is since it's deleted, assignment operators should return a reference instead of a value.
2016-12-19 11:24:23 -08:00
Tyler Veness
d0900626da Removed format.py shim (#393)
Now that our formatter is a Python package (wpiformat), the format.py shim for invoking it is no longer necessary. styleguide#29 should be merged before this patch.
2016-12-18 19:46:20 -08:00
Peter Johnson
0ee4cadca0 CameraServer: Workaround LabVIEW dashboard OpenCV compatibility. (#406)
The current LabVIEW dashboard (Beta 4) requires the source type to be either
"usb:" or "ip:" and does not support "cv:".  To work around this, use a source
type of "usb:" for OpenCV sources as well.

Workaround for #407.
2016-12-18 13:36:44 -08:00
Thad House
24b5a9c389 Adds UsageReporting include when using the LabVIEW shim (#401) 2016-12-16 22:42:45 -08:00
Austin Shalit
626220e9f3 Fix javadoc typo (#403) 2016-12-15 19:46:42 -08:00
Thad House
323d68d460 Fixes multiple initialization of HAL_BaseInitialize (#400) 2016-12-13 12:31:44 -08:00
Thad House
db2091dd94 Adds safe serial port write methods (#396)
The old method had a fairly large risk of undefined behavior, and the way the docs
were written could cause users to get confused.
Deprecate the old method and add StringRef method as preferred approach.
2016-12-10 22:40:44 -08:00
Thad House
8216d85e52 Adds check for PWM overallocation (#392) 2016-12-09 21:23:54 -08:00
Austin Shalit
a705eb1c61 Add PMD and solve issues (#389) 2016-12-07 21:24:44 -08:00
Thad House
77f664a6b1 Fixes simulator HAL builds (#391) 2016-12-06 19:56:31 -08:00
Austin Shalit
c30057e923 Remove unused imports (#387) 2016-12-05 21:36:52 -08:00
Peter Johnson
06108b9479 Update CameraServer support. (#386)
* Follow MixedCase rename.

* Add GetVideo function to get cameras by name.
2016-12-04 00:26:08 -08:00
sciencewhiz
16181523c9 Put language in version string (#377) 2016-12-02 20:36:22 -08:00
Jacob Caporuscio
7e0706cf83 Updated Usage Reporting for 2017 v8 Image (#385) 2016-12-02 18:16:49 -08:00
Thad House
bff67887fd Adds capabilities to support certain HAL functionality from LabVIEW (#382)
They can only include HAL/LV/HAL.h, HAL/cpp/*.h, and HAL/handles/*.h.
Nothing else will work properly.
2016-12-02 00:32:01 -08:00
Thad House
351ff5eb48 Adds new Threads API for priority setting while using std::thread (#379)
Also adds Java API for doing the same to Java threads (standard Java Thread.setPriority only works
when Java is run as root, even if the process has the right privileges).
2016-12-01 21:06:19 -08:00
Thad House
051df14046 Updates ni patch task to automatically switch all files to LF (#381)
Still requires manual intervention to make files not readonly, but
that's easier.
2016-11-29 20:20:49 -08:00
Thad House
ee0318f697 Updates NI Libraries to image 8 (#380) 2016-11-29 19:56:30 -08:00
Thad House
a6fb1efcbe Switches internal joystick errors to take StringRef (#378)
Previously this would have allocated the std::string every time, even if
the message wasn't printed. Now takes a StringRef, and only converts to
std::string when the message actually gets printed.
2016-11-26 21:22:39 -08:00
sciencewhiz
31fecc28a4 Check for NaN motor speed. Fixes artf5467. (#376) 2016-11-26 21:04:40 -08:00
Thad House
30b1efc354 Adds check to ensure all JNI symbols have been defined properly (#373) 2016-11-25 17:07:36 -08:00
Thad House
7d721eb569 Fixes memory leak in SerialHelper VISA (#366) 2016-11-25 15:52:21 -08:00
Fred Silberberg
d48aac5beb Gradle Update (#372)
This does a major cleanup on our gradle files, primarily converting all instances of manual dependency downloading to use the correct configuration-based method, which has the advantage of being both less code and more safe.
2016-11-24 23:44:35 -08:00
Fred Silberberg
14b56db99e Gradle 3.2.1 (#369)
Updated to gradle 3.2.1. This also moves all of the task graph listeners for dependency setup to use the gradle model, making it both safer and reducing line count.
2016-11-24 22:15:54 -08:00
Thad House
bfe429de51 Switches handles back to std::array (#367)
The binary size is being increased much less then when we originally
tried this. Using static arrays save a pointer indirection and will help
with cache in real time cases.
2016-11-24 21:55:20 -08:00
Thad House
57ef5cfd07 Splits out SerialHelper to allow using OS or VISA resources (#365)
Also removes regex and uses simple splits instead
2016-11-24 21:53:04 -08:00
Fred Silberberg
4bbb7c0bcc Fixed javadoc generation to actually download cscore and ntcore and include the source in its output. (#368) 2016-11-24 21:51:01 -08:00
Thad House
4de70bff5e Adds missing JNI method definitions (#371) 2016-11-24 21:49:34 -08:00
Peter Johnson
687f0c7dc0 Use const parameters in std::sort lambda. (#364)
This is more correct, and non-const fails on gcc 4.8.
2016-11-22 22:30:58 -08:00
Thad House
f3d66e92ec Searches for USB serial devices to get the correct VISA object (#363)
Fix was made in LabVIEW, and this matches what was done there.
2016-11-22 21:51:47 -08:00
Thad House
9a91ae54d6 Fixes incorrectly changed Java enums (#360)
Some enums need a specific value when they get passed to JNI
2016-11-20 20:32:52 -08:00
Tyler Veness
69422dc063 Replaced floats with doubles (#355)
This makes our APIs more consistent. With optimizations enabled, doubles are just as efficient as floats on ARMv7, so we should take advantage of the extra precision.
2016-11-20 07:25:03 -08:00
Dustin Spicuzza
7bcd243ec3 Reorder the HAL handle types (#357) 2016-11-20 00:01:24 -08:00
Thad House
8f70bea899 Fixes Athena Runtime build not including ntcore (#356) 2016-11-19 23:58:29 -08:00
Thad House
948c4275ad Fixes the wpilibj jar not getting updated during every build (#359) 2016-11-19 23:52:19 -08:00
Peter Johnson
03a1159915 Java CameraServer: Fix type cast exception. (#358)
Also fixes an unchecked warning.
2016-11-19 22:45:45 -08:00
Tyler Veness
1c8fb298b4 Ran formatter (#354) 2016-11-19 00:39:32 -08:00
Tyler Veness
b25a7cb370 Command::IsFinished() must be overriden by subclasses again (#353)
Documentation was added for InstantCommand and TimedCommand.
2016-11-19 00:26:22 -08:00
Tyler Veness
140c365e4b Added XboxController class (#140)
Joystick and Gamepad functionality was separated into cleaner interfaces.
2016-11-18 23:05:37 -08:00
Peter Johnson
8c93ceb728 Add cscore-based CameraServer. (#352)
Not fully functional yet, but implements basic functionality required for LabView dashboard interoperability.
2016-11-18 22:30:22 -08:00
Thad House
ac50d7cf8a Removes NiVision from allwpilib (#305) 2016-11-18 20:04:21 -08:00
Thad House
ecb873ff45 Fixes myRobotJava zipping before Java gets built (#351) 2016-11-18 19:44:13 -08:00
Thad House
78baa04ecc Adds OpenCV to myRobotJava (#350) 2016-11-18 16:20:30 -08:00
Krypton Cougars
b78f580d47 Adds default methods for Commands (#238) (#238)
Closes #235
2016-11-18 14:42:40 -08:00
Thad House
b115c75226 Adds SPI DIO to WPILib (#256) 2016-11-18 14:15:53 -08:00
Thad House
6bc092f3ae Updates SPI device pin (#348) 2016-11-18 14:14:51 -08:00
Thad House
f99a266ce4 Adds CsCore dependency to myRobotCpp (#349) 2016-11-18 14:14:11 -08:00
Fred Silberberg
1f724d58e0 Made the test scripts executable to fix -dirty on the version numbers. (#347) 2016-11-14 21:16:51 -08:00
Thad House
de4a246bb4 Adds OpenCV Loading to wpilib program startup (#338) 2016-11-11 22:32:13 -08:00
rrossbach
412b80da30 Fixes joystick button handling HAL JNI layer (buttons are in an (#341)
int, not a byte)
2016-11-10 20:21:54 -08:00
Thad House
47319960a5 Fixes a missed change to unique_ptr in the HAL (#337) 2016-11-08 16:53:17 -08:00
Thad House
b22d218236 Removes CANJaguar specific constants from JNI files (#339) 2016-11-08 16:52:24 -08:00
Thad House
6eb82bc314 Exclude genlinks.bat from HAL zip (#333) 2016-11-06 21:47:34 -08:00
Thad House
a06dd25d56 Adds cscore and opencv to wpilib (#332)
Unit tests now run using shared wpilib as well, since we had to add a ton
of sharedl ibraries anyway. Test scripts also updated to work properly.
2016-11-06 21:47:18 -08:00
Thad House
e1bb05bc52 Updates to the 2017 v7 image (#329) 2016-11-05 23:20:40 -07:00
Tyler Veness
8694a020ac Removed entries from .styleguide that are included in .gitignore (#331)
format.py now considers files that match patterns in .gitignore to be modifiable files. Therefore, listing them in .styleguide is redundant.
2016-11-05 08:39:46 -07:00
Thad House
1efb2e4d3d Deprecates Task and Semaphore, and changes other deprecations to use wpiutil version (#330) 2016-11-05 00:23:52 -07:00
Thad House
861726cefa Adds gradle task to fix NI libraries whenever new ones are added. (#325)
Generates genlinks, and modifies headers to make them self contained
2016-11-04 15:17:17 -07:00
Thad House
81212d80c6 Fixes ultrasonic declaration (#328)
Also adds test to ensure this doens't happen again
2016-11-04 15:02:29 -07:00
Thad House
2235a809c4 Fixes a missed change from the ni-libraries location change (#326) 2016-11-04 13:26:34 -07:00
Thad House
3fe0f49ac0 Moves NI headers to their own folder in the repo (#324) 2016-11-04 01:22:28 -07:00
Thad House
03d8f9193b Moves using namespace from ChipObject.h into hal namespace (#323) 2016-11-03 23:01:13 -07:00
Thad House
5e54969f6b Adds Task back into WPILibC (#320)
Note that deprecation has not been added yet, since we need to add the
deprecation API's for MSVC and GCC < 4.9.
2016-11-02 22:17:40 -07:00
Thad House
18ef5eb1bf C++ and Java tests for the new build system (#309) 2016-11-01 23:41:05 -07:00
Tyler Veness
b5e3d92e9d Remove errant "using namespace" in global namespace (#318) 2016-11-01 23:40:28 -07:00
Tyler Veness
ba8761e39e "using" directives are no longer used in global namespaces (#219) 2016-11-01 23:09:51 -07:00
Thad House
78f0b1562c Removes Task.h from wpilib.h header (#317) 2016-11-01 23:08:57 -07:00
Thad House
5c28b30028 Removes NetworkTables from Java executable jar (#303) 2016-11-01 22:34:52 -07:00
Peter Johnson
59267da72b Namespace all wpilibc functions/classes into "frc" namespace. (#311)
Base.h provides a backwards compatibility shim (enabled unless
NAMESPACED_WPILIB is defined) that does a "using namespace frc".
However, as some header files do not include Base.h, this may
be a breaking change in some corner cases (with an easy fix).

Fixes #218.
2016-11-01 22:33:12 -07:00
Dustin Spicuzza
36ad45c07d Delete .gitreview (#316) 2016-11-01 22:31:53 -07:00
Thad House
ecb2add791 Removes additional references to CANTalon from the library. (#312) 2016-11-01 20:13:26 -07:00
Thad House
9bbdaf300b Removes the task class from wpilib (#314)
Was required back on the cRIO, but there are much better alternatives
nowadays.
2016-11-01 20:12:08 -07:00
Thad House
bc492bb40e Removes the REAL definition from wpilib.h (#315)
Interferes with OpenCV, and is heavy namespace polution anyway.
2016-11-01 19:23:59 -07:00
Thad House
81221c4874 Moves JNI internal utility methods to frc namespace (#310) 2016-10-31 23:04:49 -07:00
Thad House
137b3d81fb Fixes JNI file not being copied to output directory for integration tests (#308) 2016-10-30 23:14:19 -07:00
Fred Silberberg
6741f47ef1 Update version plugin (#307) 2016-10-30 01:18:18 -07:00
Thad House
e75e9092a8 Fixes athena runtime zip not being built at the correct times (#306) 2016-10-27 22:01:28 -07:00
Thad House
247cef5ec2 Removes CANJaguar from wpilib (#300)
Now located at https://github.com/wpilibsuite/CANJaguar.
2016-10-27 10:54:52 -07:00
Thad House
29f999e2b2 Adds new handle structure and type for vendors (#297) 2016-10-26 23:09:33 -07:00
Thad House
5e3755493d Linking and maven publish location rewrite (#298)
* Links HAL shared instead of static, and doesn't include library in jar

* Strips shared object files, and includes debug in releases

* Zips the HAL libraries into a separate maven artifact

* Switches to shared wpiutil

* Switches wpilibc to shared

* Moves maven artifacts

wpilibc now in edu.wpi.first.wpilibc:athena
wpilibj now in edu.wpi.first.wpilibj:athena
wpilibj jni not in edu.wpi.first.wpilibj:athena-jni
hal now in edu.wpi.first.wpilib:hal
athena runtime added (hal, ntcore, wpiutil) edu.wpi.first.wpilib:athena-runtime

Changes made where wpilibc does NOT include all required artifacts anymore. Dependent on hal, wpiutil and ntcore packages to work correctly.
JNI does NOT include all required artifacts anymore. Dependent on hal and wpiutil packages to work correctly.
2016-10-25 20:46:09 -07:00
Thad House
70343c0b3f Fixes missing function for Timer::GetMatchTime() (#299) 2016-10-25 19:01:18 -07:00
Thad House
60e199b0bd Fixes format.py on windows (#293) 2016-10-24 22:17:02 -07:00
Thad House
1071686d81 Replaces C++ IsNewControlData semaphore with atomic bool, and Java code with AtomicBool (#187) 2016-10-24 20:32:43 -07:00
Tyler Veness
fdebdd520a Added format.py to Travis config (#236) 2016-10-23 21:37:43 -07:00
Tyler Veness
5ca5583fc3 Removed unnecessary set of parentheses and ran formatter (#290) 2016-10-23 16:34:00 -07:00
Thad House
75463a249f Implements threaded notifiers and interrupts in the HAL (#281) 2016-10-23 14:34:43 -07:00
Thad House
7280d241f0 Fixes DIO not erroring with too high of DIO number (#288) 2016-10-23 14:21:14 -07:00
Austin Shalit
963391cf39 Cleanup SolenoidBase, Solenoid, and DoubleSolenoid (#271) 2016-10-23 14:20:28 -07:00
Thad House
4f4c52d6d5 Switches JNI to use SafeThread from WPIUtil (#282) 2016-10-23 14:18:46 -07:00
Fred Silberberg
499da6d08d Updated the wpilib version plugin to 1.2. Fixes issues with submodules. (#289) 2016-10-23 14:17:59 -07:00
Austin Shalit
39e4d11f8e Remove .pullapprove.yml (#287) 2016-10-23 11:20:29 -07:00
Thad House
df4a2c07f0 Checks for system initialization in functions that can be called before creating handle based objects (#285) 2016-10-23 10:00:34 -07:00
Thad House
c46c490376 Adds wpiUtil to HAL and JNI (#280) 2016-10-23 09:51:30 -07:00
Thad House
f2751db5c2 Adds NI Libraries symbolic link (#286) 2016-10-22 14:21:26 -07:00
Thad House
2bff276adb Fixes a missed formatting issue (#283) 2016-10-21 08:30:49 -07:00
Fred Silberberg
e5e1a1a4d1 Moved version generation to the WPILib versioning plugin. (#277)
* Moved version generation to the WPILib versioning plugin. This also moves ntcore and wpilib to the latest available version.

* Fixed description string.

* Gave full path for ignored files.
2016-10-20 23:54:04 -07:00
Austin Shalit
0613f1d182 Cleanup encoder class (#272) 2016-10-19 22:39:47 -07:00
Austin Shalit
8b94e0933a Update README (#261)
Update the README to include instructions on how to image the test bench roboRIO.
2016-10-19 22:37:43 -07:00
Austin Shalit
23ef57561d Cleanup PowerDistributionPanel (#275) 2016-10-19 22:34:57 -07:00
Austin Shalit
33b95816ee Cleanup SensorBase class (#273) 2016-10-19 22:33:36 -07:00
Thad House
4c1e4fd80c Updates image to v6 (#278)
Added exports of the environment variables set in the frcRunRobot script to prevent fork calls.
2016-10-19 22:30:29 -07:00
Fred Silberberg
3784b665de Updated version for beta 1 (#270) 2016-10-13 18:50:39 -07:00
Kevin-OConnor
567ea1d58d Remove CAN TalonSRX from WPILib (moving to external library) (#268) 2016-10-13 18:50:20 -07:00
Austin Shalit
55346e28d0 DoubleSolenoid free reverse port handle instead of channel (#274) 2016-10-13 12:41:36 -07:00
Fred Silberberg
49b8c4ba78 Fixes the gradle dependencies for building (#269) 2016-10-12 21:06:33 -07:00
Thad House
f1c2b66569 Reverts the 2017 Image for Beta 1 (#264)
* Revert "Updated the rpath to point to the correct location for the Java integration tests. (#262)"

This reverts commit c313dde03a.

* Revert "Update image 2017 v5 (#254)"

This reverts commit 8d1c51b7e9.
2016-10-12 19:52:49 -07:00
Austin Shalit
27bf94fd06 Remove kDefaultPeriod from IterativeRobot (#232)
* Remove kDefaultPeriod from IterativeRobot

* Remove period

* Remove NextPeriodReady
2016-10-09 13:58:30 -07:00
Thad House
4896a77c86 Fixes guarantees for waitForData (#252)
As discussed in #234, we now check for the timeout case and handle a
timeout correctly.
2016-10-09 11:46:01 -07:00
Austin Shalit
d1d3f049f2 Solve scp file not found (#263)
Solves the scp file not found bug after installing a new image on the test bench.
2016-10-09 11:45:26 -07:00
Fred Silberberg
c313dde03a Updated the rpath to point to the correct location for the Java integration tests. (#262) 2016-10-08 13:08:26 -07:00
Fred Silberberg
8d1c51b7e9 Update image 2017 v5 (#254)
* Updated the image version and dependent libraries to 2017 v5.

* Updated version for beta 1

* Some additional library updates, task updates, and rpath updates
2016-10-08 00:13:31 -07:00
Thad House
a59e00e901 Adds a test to make sure WaitForData is properly waiting (#258) 2016-10-06 11:18:47 -07:00
Tyler Veness
7070162b98 Fixed lint errors (#259) 2016-10-06 11:05:09 -07:00
Thad House
9859c14ca1 Fixes status parameter in wrong location for initialization range functions (#260) 2016-10-06 11:04:38 -07:00
Thad House
64ebe7f5e5 Updates SmartDashboard with new NetworkTables3 functions (#162) 2016-10-03 09:59:18 -07:00
Thad House
8b2345a706 Removes an unnecessary function from HAL Power (#237)
Was not declared in header, so never used anywhere
2016-10-03 09:52:47 -07:00
Thad House
e65f9908d7 Makes IterativeRobot not double check for new control data (#253)
Previously could cause a race condition. Also moves wait to the top of
the loop in order to avoid having an initial loop be ran before data can
be check.

Sim is handled in #232, except that needs to be updated as well to move
the wait to the top of the loop.
2016-10-02 09:05:32 -07:00
Tyler Veness
fd52912d74 Fixed return value propagation of format.py (#251) 2016-10-02 08:10:22 -07:00
Fred Silberberg
9e7993905f Remove slack integration (#257)
Slack integration is useless noise that no one reads. This removes it.
2016-10-02 01:11:09 -07:00
Thad House
a656207220 Forces exceptions to throw on HAL handle creation functions (#209)
Fixes #199
2016-09-29 20:18:40 -07:00
Peter Johnson
81e63ea3a5 Fix simulation build with latest ntcore/wpiutil. (#250) 2016-09-28 20:45:03 -07:00
Tyler Veness
5dfae8d6bd Fixed include order (#245)
See wpilibsuite/styleguide (#11).
2016-09-25 16:50:13 -07:00
Peter Johnson
107a4cc1e2 Add wpiutil dependency. (#190) 2016-09-25 16:47:49 -07:00
Tyler Veness
35d51d68f7 Made a comment use more professional language (#249) 2016-09-23 22:16:33 -07:00
Tyler Veness
049fec470b Fixed compilation with GCC 6 (#248)
Since newer versions of GCC emit more warnings and errors, I tried building WPILib with GCC 6.2.0. This patch fixes compilation errors that occurred.
2016-09-23 20:27:11 -07:00
Tyler Veness
659dbef751 Ran format.py after writing unit tests for and fixing bugs in it (#239) 2016-09-21 23:48:54 -07:00
Tyler Veness
ac9b6f7b18 Implemented CircularBuffer resizing (#224) 2016-09-20 19:43:34 -07:00
Tyler Veness
425ed464ed Removed leading underscores from variable names (#246) 2016-09-20 12:41:42 -07:00
Austin Shalit
2c15bb247e Remove delay from periodic methods. (#243) 2016-09-20 12:34:17 -07:00
Austin Shalit
28e178b1a8 Update Compressor documentation (#244) 2016-09-20 12:31:16 -07:00
sciencewhiz
5d2a08443b Fix Typos. Fixes artf4853 (#242) 2016-09-18 08:43:22 -07:00
Tyler Veness
087eeec760 C standard library functions and types are now prefixed with std:: (#227) 2016-09-14 20:52:06 -07:00
Thad House
dbe03afb9a Fixes error in driver station control word cache (#222) 2016-09-13 21:22:25 -07:00
Thad House
2ecb939b35 Add a method to detect the HAL runtime version (#228) 2016-09-13 21:21:57 -07:00
Austin Shalit
1416fb8f67 Update Periodic JavaDoc (#231) 2016-09-13 21:21:25 -07:00
Tyler Veness
aeb6c4889b Added license template file (#225) 2016-09-13 20:28:07 -07:00
Thad House
c2fc6711d8 Switches enums to use a fixed size for their base (#230) 2016-09-13 20:27:38 -07:00
Thad House
f271185cbc Adds a RobotPeriodic method to IterativeRobot (#226)
Called globally during each IterativeRobot loop
2016-09-13 20:25:18 -07:00
Thad House
4fc7daedc9 Fixes incorrect deadband value being passed over PWM (#223) 2016-09-09 15:58:38 -07:00
Tyler Veness
6bfc008673 Replaced snake case variable names with mixed case (#221) 2016-09-06 19:43:24 -07:00
Tyler Veness
2c94d0ba2f Cleaned up integer type usage in the HAL (#192)
Replaced all uses of built-in types except char with stdint.h typedefs and all unsigned types with signed in the HAL
2016-09-06 19:39:28 -07:00
Tyler Veness
0cd05d1a42 Cleaned up integer type usage in wpilibc (#92)
Replaced all unsigned types to signed and int32_t with int in wpilibc
2016-09-06 00:01:45 -07:00
Tyler Veness
ff93050b31 Remove static_assert for sizeof(uint32_t) <= sizeof(void*) (#220)
According to #192, we don't cast integers to pointers anymore. The size static_assert is unnecessary.
2016-09-05 23:31:58 -07:00
Tyler Veness
05626cfafe Fixed cpplint.py warnings (#215)
* Fixed cpplint.py [build/include_order] and [build/include_what_you_use] warnings
* Fixed cpplint.py [readability/casting] warnings
* Updated .styleguide format
* Fixed cpplint.py [build/header_guard] warnings
2016-09-05 13:55:31 -07:00
Thad House
59ec54887d Switches notifier to use a typedef for the callback, and prepends HAL_ to InterruptHandlerFunction (#216) 2016-09-05 07:31:51 -07:00
Tyler Veness
028efff50d Ran format.py (#217) 2016-09-05 07:31:02 -07:00
Tyler Veness
2499771cf4 Added extensions to .styleguide (#214)
wpilibsuite/styleguide is going to use extensions specified in .styleguide instead of hardcoded extensions. This patch should be merged first to maintain correct operation.
2016-09-01 20:31:38 -07:00
Fred Silberberg
c989ae808b Updated gradle to 3.0 (#208) 2016-09-01 20:30:37 -07:00
Tyler Veness
93b486b6ba Replaced C-style casts found by GCC in HAL, wpilibc, and JNI (#211) 2016-08-24 21:39:16 -07:00
Thad House
2ec6132fcb Switches compiler from -O0 to -Og (#197)
Should be a heavy increase in performance
2016-08-21 19:15:58 -07:00
Thad House
8aba2b2850 Adds .vscode to styleguide ignore files (#210) 2016-08-21 12:35:58 -07:00
Tyler Veness
32c95fa0da Moved style guide documents and scripts to wpilibsuite/styleguide (#207) 2016-08-21 10:31:43 -07:00
Thad House
40365faeda Adds a static mutex to notifiers to stop destructor race condition (#204) 2016-08-15 19:56:32 -07:00
Thad House
776cb915bc Revert "PIDController queue now stores inputs instead of errors (#138)" (#205)
This reverts commit 7501ae65a1.
2016-08-13 23:49:31 -07:00
Thad House
5e9fe2f5cb Adds an ignore for Visual Studio Code files (#203) 2016-08-13 14:44:10 -07:00
Tyler Veness
7501ae65a1 PIDController queue now stores inputs instead of errors (#138)
Closes #29.
2016-08-12 22:04:44 -07:00
Peter Johnson
63469c00c4 run-tests-on-robot.sh: Save coredump on crash. (#201) 2016-08-12 19:18:48 -07:00
Fred Silberberg
3df257cdbb Set duplicate strategy for all jars and zips to prevent duplicates from occurring (#191) 2016-08-12 13:45:58 -07:00
Tyler Veness
45b8e9ab4f Renamed "pin" to "channel" and variables with underscores now use mixed case (#194) 2016-08-12 13:45:28 -07:00
Tyler Veness
227fdc1a60 Updated C++ style guide (#196)
include guard section now requires #pragma once, enumerators now exclusively use constant naming, and a mention of format.py was added to the "Formatting" section and CONTRIBUTING.md.
2016-08-12 07:14:49 -07:00
Tyler Veness
d347cebf67 Cleaned up odd formatting from static_cast by using "u" integer literal (#200) 2016-08-12 06:08:57 -07:00
Tyler Veness
3819cd0768 Updated cpplint.py and fixed its regexes for C-style casts (#193)
Additional C-style cast warnings thrown were also fixed.
2016-08-11 23:38:45 -07:00
Tyler Veness
e8f1fdda44 format.py now emits warnings for modified generated files (#195) 2016-08-11 23:10:10 -07:00
Tyler Veness
fd4719cb87 Fixed Doxygen comments for LinearDigitalFilter (#198) 2016-08-11 22:47:51 -07:00
Tyler Veness
6ef4745d86 Added Joystick::GetAxisType() (#98) 2016-08-07 10:19:19 -05:00
Thad House
62a980d3c8 Fixes Relay Constant Test (#189) 2016-07-26 13:53:45 -07:00
Thad House
866046edd1 Some general cleanups in the HAL (#188)
AnalogTrigger initialization checks are now in the correct order. Plus
frees no longer grab the structure if it is not needed.
2016-07-25 23:26:34 -07:00
Fredric Silberberg
8ac7e44f19 Updates gradle to 2.14.1 (#186) 2016-07-25 21:21:34 -07:00
Thad House
a831978cce Uses the fixed SensorBase functionality in the WPILib (#185) 2016-07-21 23:24:06 -07:00
Thad House
8da577b56f Moves FRCDriverStation to athena folder (#184) 2016-07-21 23:22:02 -07:00
Thad House
512ecf6490 Makes SensorBase checks use HAL check methods (#182) 2016-07-20 22:47:29 -07:00
Thad House
0901ae0808 Switches the HAL structs to use unique_ptr (#183) 2016-07-20 22:05:17 -07:00
Thad House
1ca291f20b Fixes a missed HAL_Bool change from int32 (#181) 2016-07-17 20:54:39 -07:00
Thad House
75eabfee1c Moves DriverStation HAL code to its own header and definition (#179)
To allow for future use as a plugin for the HAL simulator.
2016-07-17 19:42:33 -07:00
Tyler Veness
f7c3f13a7f Improve CircularBuffer documentation (#180) 2016-07-16 20:50:19 -07:00
Tyler Veness
57efd13f7f Replaced PIDController::Initialize() with delegating constructors (#178) 2016-07-16 12:50:17 -07:00
Thad House
7ddc153623 Fixes analog gyro casting to float then returning double (#177) 2016-07-15 18:13:51 -07:00
Tyler Veness
f9ebd3bde6 Fixed PIDController::GetError() for continuous inputs (#169)
Closes #31
2016-07-15 13:44:04 -07:00
Thad House
2c911b0f7a Adds a maximum time based cache to HALControlWord data (#158)
This is one of the calls with the delayed IPC. In the past, teams have
called an IsMode function so much that their code would start lagging.
This adds a cache, so the data is updated either when new data arrives
and we are notified of it, or after 50ms has passes since the last time
the cache was checked and updated.
2016-07-15 13:39:26 -07:00
Tyler Veness
1bf2d58db1 Reordered DriverStation functions in wpilibc and wpilibj to match wpilibc header (#166) 2016-07-14 20:50:38 -07:00
Tyler Veness
c93b5bedf9 Miscellaneous cleanups for wpilibc PID controller (#175)
* Reorder wpilibc PIDController's SetAbsoluteTolerance() and SetPercentTolerance() implementations to be consistent with header and wpilibj

* Added std:: prefix to fabs() calls in wpilibc PIDController
2016-07-14 13:51:32 -07:00
Thad House
dffaa0abb9 Moves HAL cpp headers from root to HAL directory (#174)
Could not include the ctre and NetComm folders, as those would require
changing ctre dependancies. Also removes a duplicated FRCComm header
that was not needed.
2016-07-14 00:17:29 -07:00
Tyler Veness
20c6525b1d Cleaned up wpilibj enums (#167)
* Converted enumerated constants in wpilibj to enums and made their implementation more consistent

* Reflowed text in JNI calls and updated JNI signatures
2016-07-13 23:39:58 -07:00
Fredric Silberberg
fe7165a8f7 Removed double-add of shared classpath. Fixes #157. (#164) 2016-07-13 22:20:30 -07:00
Thad House
d2aa168f66 Implements Better Error Messages from the HAL (#172)
* Makes the HAL provide a better error message for certain things.

* Makes Java error messages better

* Updates C++ errors.

* Moves handles header folder to HAL directory
2016-07-13 20:29:28 -07:00
Thad House
05c00430b3 Fixes CPP lint errors added to HAL. (#173) 2016-07-13 20:16:45 -07:00
Thad House
5305087162 Fixes a missed float to double change in the HAL. (#176) 2016-07-13 19:25:57 -07:00
Tyler Veness
6251697f60 Added Lint task and parallelized format.py (#161) 2016-07-12 21:59:09 -07:00
Thad House
ea1a1e6bc3 Makes the CANJaguar error status messages more useful (#165)
The previous version would just return the class name for the
DigitalOutput port. Now it actually gets the dio port value for better
readability.
2016-07-12 21:53:51 -07:00
Thad House
edf5ecd4a0 Changes HAL Headers to be C compliant. (#171) 2016-07-12 21:53:06 -07:00
Tyler Veness
1b1ee7f9f3 Renamed spiGetSemaphore() to spiGetMutex() (#170) 2016-07-12 15:11:41 -07:00
Tyler Veness
3fade171f9 Fixed inconsistencies in documentation (#168) 2016-07-12 10:50:21 -07:00
Tyler Veness
c99e89dfca Fixed the remaining cpplint.py warnings (#160)
Replaced std::sprintf in BaeUtilities.cpp with std::stringstream and marked GetVisionErrorText() in FrcError.cpp as NOLINT
2016-07-12 10:46:34 -07:00
Thad House
b51e85ae26 Switches HAL to fixed length signed integers, and adds our own HAL_Bool Type (#155)
* Switches HAL to fixed length signed integers, and adds our own HAL_Bool type

* Replaces HAL Floats with Doubles

Doubles are just as fast as floats with optimizations turned on, so
switches to all doubles. All made doubles for consistency.

* Prepends HAL/ to HAL include files. Also fixes some range errors
2016-07-12 10:45:14 -07:00
Thad House
4a98e68815 Moves the DS new data wait calls down to the HAL. (#156) 2016-07-10 23:10:05 -07:00
Tyler Veness
0cb288ffba Fixes warnings thrown by cpplint.py (#154)
* Fixed cpplint.py [runtime/int] warnings

* Fixed cpplint.py [readability/casting] warnings

* Fixed cpplint.py [readability/namespace] warnings

* Fixed cpplint.py [readability/braces] warnings

* Fixed cpplint.py [whitespace/braces] warnings

* Fixed cpplint.py [runtime/explicit] warnings

* Fixed cpplint.py [runtime/printf] warnings

* Fixed cpplint.py [readability/inheritance] warnings

* Fixed cpplint.py [whitespace/tab] warnings

* Fixed cpplint.py [build/storage_class] warnings

* Fixed cpplint.py [readability/multiline_comment] warnings

* Fixed cpplint.py [whitespace/semicolon] warnings

* Fixed cpplint.py [readability/check] warnings

* Fixed cpplint.py [runtime/arrays] warnings

* Ran format.py
2016-07-10 17:47:44 -07:00
Tyler Veness
e44a6e227a Refactored wpilibj HAL JNI to simplify generating it from HAL headers (#109)
wpilibj FRCNetworkCommunication.java is now generated from HAL headers and was renamed to FRCNetComm.java
2016-07-10 16:24:57 -07:00
Tyler Veness
aafca4ed7f Reduced duplication between formatting scripts with Task base class (#80)
Also added scripts for EOF newline management and for removing trailing whitespace. configure.bat was rewritten to use CRLF line endings. Documentation for the existing scripts was also improved.
2016-07-10 08:33:27 -07:00
Thad House
ea6876e81f Some general HAL cleanups (#153) 2016-07-09 17:38:18 -07:00
Tyler Veness
aa9c2b2c92 Made Log.h use std::chrono (#136) 2016-07-09 16:58:31 -07:00
Thad House
43a2eccdc9 Finishes Prefix Renames (#152) 2016-07-09 01:12:37 -07:00
Thad House
b637b9ee4c Prepends all HAL functions with HAL_ (#146) 2016-07-09 00:24:26 -07:00
Thad House
5ad28d58ec Switches PWMs to do scaling at the HAL level. (#143) 2016-07-08 21:29:29 -07:00
Thad House
be2647d44e Switches Java to use HAL Constants (#145) 2016-07-08 00:08:07 -07:00
Thad House
4a3e3a6324 Changes DigitalSource API for HAL ease of use (#144) 2016-07-07 21:43:55 -07:00
Thad House
7597e3c274 Switches handle resources to dynamic arrays (#142) 2016-07-07 21:32:41 -07:00
Thad House
0a983eeeb8 Moves Gyros to the HAL (#131) 2016-07-07 21:31:45 -07:00
Austin Shalit
b036bf2e34 Add method to get the port number of a Joystick (#137) 2016-07-04 09:18:28 -07:00
Tyler Veness
73602e6cb4 Added missing include for robot startup macro (#135) 2016-07-03 23:24:56 -07:00
Thad House
72455280a9 Removes unneeded resource includes from WPILibC files (#134) 2016-07-03 23:18:45 -07:00
Thad House
ea95bb85aa Adds Constants from new constants class to encoders (#133) 2016-07-03 21:52:49 -07:00
Thad House
fb865d3ee7 Adds a special exception and status message for a handle error (#127) 2016-07-03 17:27:06 -07:00
Thad House
36ac37db8c Moves Encoders to Handles and Moves WPILib Encoders to HAL (#124) 2016-07-03 15:22:22 -07:00
Thad House
b45e0917ae Adds port constants to the HAL (#130) 2016-07-02 23:19:14 -07:00
Thad House
0e127679c1 Removes some unused variables from DigitalInternal (#128) 2016-07-02 16:33:19 -07:00
Fredric Silberberg
2f36d508c4 Gradle 2.14 (#118)
Updates the gradle version to 2.14. In doing so, some model elements have changed. Additionally, some redundant elements have been removed from the gradle scripts.
2016-07-02 16:32:14 -07:00
Thad House
cf29d4560b Moves HAL PCM objects to header and HAL namespace (#129) 2016-07-02 11:58:49 -07:00
Thad House
8c4ad62422 Switches Solenoids to Handles (#126) 2016-07-02 09:24:54 -07:00
Thad House
62c217cd01 Switches compressor to handles (#125) 2016-07-02 08:22:44 -07:00
Thad House
0f105a26f7 Switches Counters to Handles (#123) 2016-07-01 00:29:08 -07:00
Thad House
47694ef810 Switches DigitalPWM to Handles (#121) 2016-06-30 23:43:00 -07:00
Thad House
f77a976fbb Switches resource errors to AllocationExceptions in JNI (#122) 2016-06-30 21:39:55 -07:00
Thad House
3593ecb17e Switches PWM and DIO to Handles (#120) 2016-06-30 21:39:09 -07:00
Thad House
9b2af0d090 Switches relays to handles (#119) 2016-06-29 19:58:14 -06:00
Thad House
e8e052712e Switches AnalogInputs and AnalogTriggers to Handles (#117)
Results in a breaking change to AnalogTrigger int constructor. If a user wants
multiple AnalogTriggers, they must use the AnalogInput constructor.
2016-06-27 21:32:30 -07:00
Thad House
77a1af44c4 Removes freePort from the HAL (#116)
It was a no-op, and most likely in the future it will be that way too.
Removing to clean up the API.
2016-06-27 13:38:33 -07:00
Thad House
5e2a76147c Moves handle definitions to main handle header (#115) 2016-06-27 13:36:38 -07:00
Thad House
e1d4845ccd Move Analog Outputs to Handles (#112) 2016-06-27 11:32:40 -07:00
PatrickPenguinTurtle
95d40ed01f Fixed issue with digital outputs used as pwm on mxp (#14)
When a digital output object that was tied to an mxp pin had enable pwm called on it
it would pwm on a pin 6 lower
 (although if this wasn't an mxp pin it wouldn't do anything at all.)
Fixed in Digital.cpp by adding 6 if it is an MXP pin in setPWMOutputChannel()
This should fix the CanJaguar test because when digitalOutputs used as PWM
were freed, the PWM generator was set to the number of pins, which meant it
was actually outputing on pin 20.

Change-Id: Ib48db3e6e3bf78659622145969d24011cc231ea6

Updated Hal to include some documentation about swaping mxp pins.

Cannot find NI related documentation as to the pin numbers being wrong though

Change-Id: I71d84431dc9bc7bf22aa29b6633e49723311b5f7

fixed formatting on changed files

Change-Id: I5b7c16cd798132b6b20c1d03f334a95b42d2ee11
2016-06-24 19:46:43 -07:00
Tyler Veness
aa22d4c33b Clarified that PID controller runs in discrete time (#107)
This was added to explain the apparent oversight with respect to controller behavior with different sample rates.
2016-06-20 23:25:23 -07:00
Thad House
046e043c4e Moves Interrupts over to Handles instead of pointers (#99) 2016-06-20 23:22:48 -07:00
Thad House
74fc10999b Fixes preferences formatting (#108) 2016-06-20 22:17:40 -07:00
Tyler Veness
cee9b2609d Added std:: prefix to more C standard library uses (#106) 2016-06-19 00:19:45 -07:00
Tyler Veness
daa0260a4e Deduplicated UsageReporting definitions (#104) 2016-06-19 00:15:57 -07:00
Tyler Veness
d66c61a36e Cleaned up robot startup and cleanup/shutdown code (#77)
Cleaned up RobotBase, removed singleton list from SensorBase, and removed unused typedefs and NULL_TASK macro from HAL's Task.hpp. Making the robot class instance static fixed non-POD statics used by the instance during destruction from being destroyed first.
2016-06-19 00:13:18 -07:00
Tyler Veness
ecc210f99a Rename Notifier::m_handlerMutex to Notifier::m_notifyMutex (#105)
A month ago, we discussed renaming this mutex to better reflect its current use, and this commit does that. The inline comment was also updated.
2016-06-18 02:20:29 -07:00
Thad House
3cacc2aba6 Switches indexed handles to shared_ptr (#101)
As discussed, the old method of was going to have issues, and was not
going to help in the case of the structs containing pointers. I think we
are just going to have to be careful, as guarenteeing the internal
pointers are const is going to be very difficult.
2016-06-18 00:59:53 -07:00
Peter Johnson
085c47b671 Unbreak wpilibc WritePreferencesToFile test. (#103)
ntcore recently changed GlobalDeleteAll() to not delete persistent values.
This test was relying on the old behavior to provide a clean slate.
2016-06-18 00:58:22 -07:00
Thad House
039515082a Fixes formatting in error.cpp (#102) 2016-06-17 21:35:00 -07:00
Thad House
c3908660b1 Switches all HAL Handle errors to be zero (#100)
As discussed, we don't really need the error checking specifically, as
we are just going to throw exceptions anyway, so this will make sure you
can check for 0 and be sure you catch any handle errors.
2016-06-17 20:21:25 -07:00
Thad House
fc515f4572 Changes HAL Port from a pointer to a handle (#93)
HAL Port is using a special handle, where the module and pin are bit
shifted straight into the handle. This is one of the few special cases
we have, but for the way port is used it is much cleaner and uses much
less memory.  Plus it is generic and not specific to one type.
2016-06-05 15:23:58 -07:00
Tyler Veness
5a82f73d9b Replaced .h C headers with c-prefixed version and added std:: prefix to C standard library usage (#90)
This was not done to stdint.h for brevity in type names. Also removed "using namespace std;".
2016-06-05 07:33:37 -07:00
Thad House
776a991d61 Moves Notifier over to handles (#97)
Internally, the linked list now uses shared_ptrs instead of raw
pointers. In addition, in the WPILib the notifier handle is now made
atomic. Then before the class is destructed, the handle is now set to 0.
This should help solve one of the existing race conditions. A 0 handle
is correctly handled down at the HAL level.
2016-06-05 07:29:47 -07:00
Thad House
8527f2c2a1 Fixes HandleResource classes (#95)
Issues were found when adding unit testing. The classes should now work
properly.
2016-06-03 11:24:58 -07:00
Thad House
c85b72b952 Fixes a few bugs in the initial handle implementation (#94)
Failure to check for invalid type on handle creation, and handle type
check was broken.
2016-06-01 20:12:50 -07:00
Peter Johnson
f0d9e19b5c ErrorBase: change to ostringstream. (#66)
This fixes a snprintf issue on 64-bit platforms by avoiding the use
of snprintf.
2016-06-01 00:12:55 -07:00
Tyler Veness
c7c011813f Made include ordering/organization more explicit in style guide (#86) 2016-05-31 23:46:44 -07:00
Thad House
d76f0d4022 Adds support for Handles to the HAL (#91)
Handles will be replacing opaque pointers in the HAL for better compatibility and easier error checking. This commits adds the initial resource manangement and definition for handles.
2016-05-31 23:45:47 -07:00
Peter Mitrano
de7678f2fc remove author requirement for now (#84)
waiting on a fix from pullapprove
2016-05-30 11:02:37 -04:00
Tyler Veness
2f7eff7091 Removed @author from comments (#88)
Keeping @author lines in the comments serves no functional purpose.
2016-05-29 09:24:04 -07:00
Tyler Veness
7a402b4170 Replaced "RoboRIO" with "roboRIO" in comments (#87) 2016-05-29 09:19:43 -07:00
Peter Johnson
10b4814e60 VisionAPI.cpp: Remove non-UTF8 characters. (#85) 2016-05-29 09:17:01 -07:00
Tyler Veness
613309c0a2 Replaced wpilibj class Init() methods with delegating constructors (#79) 2016-05-27 00:06:47 -07:00
Thad House
c622c03eff Places while loop around DS wait condition. (#83)
In case of Spontaneous wake ups, we should be checking a condition
variable as well.

Note that we can not use the existing m_newControlData, as that has a
possible race condition with existing user code that it does not look
like we could work around.
2016-05-26 23:05:08 -07:00
Thad House
ed7d2d6aa6 Splits the HAL Analog Implementation Files (#82) 2016-05-26 22:14:25 -07:00
Tyler Veness
51ff9e9f69 Classes which use I2C or SPI now do so via composition rather than inheritance (#72) 2016-05-26 21:37:23 -07:00
Tyler Veness
9f2f301fa4 Deduplicated FRC network communication headers (#71)
The network communication headers were moved to the include directory of the HAL and their copies were removed from wpilibc. Also, symModuleLink.h was removed because the function which it prototypes hasn't been used in WPILib since the roboRIO switch.
2016-05-26 20:20:58 -07:00
Tyler Veness
fa8bb3fa91 Remove obsolete timer functions and replace with std::chrono (#64)
Removed delayTicks(), delayMillis(), delaySeconds(), HAL_NO_WAIT, HAL_WAIT_FOREVER,
niTimestamp32(), and niTimestamp64().

Replaced clock_gettime() and usleep() with std::chrono.
2016-05-26 20:19:23 -07:00
Jonathan Leitschuh
4af0bbddee Add Travis Badge to ReadMe (#81)
This provides a quick navigation link to our travis build.
Additionally, it makes it so that the master build status can be confirmed quickly.
2016-05-26 15:54:12 -07:00
Tyler Veness
4aca3c2022 Removed extraneous curly braces around std::lock_guards in PIDController class (#78) 2016-05-26 12:59:34 -07:00
Tyler Veness
753ab85efb Removed commented out includes and imports (#76) 2016-05-26 12:59:01 -07:00
Thad House
da6b8c7ae1 Split HAL Digital Implementation files (#59)
Split to match the new headers. Uses a namespace 'hal' for internal functions and globals.
SPIAccumulator merged back into SPI header, as it was not a good split. Analog
accumulator will move back to analog input when the analog split is done.
2016-05-26 12:56:39 -07:00
Tyler Veness
305ab08f1c Renamed DriverStation::IsSysBrownedOut() to DriverStation::IsBrownedOut() to match the Java version. This changes the external API. (#67) 2016-05-25 23:09:24 -07:00
Tyler Veness
e9718fc7bf Replaced NULL with nullptr in C++ source files (#70) 2016-05-25 23:07:45 -07:00
Tyler Veness
8566878af4 Fixed C++ simulation build with Boost 1.60 (#49) 2016-05-25 22:41:58 -07:00
Tyler Veness
62812faf62 Clean up include guards and EOF newlines (#65)
* Replaced include guards with #pragma once

* All source files now have exactly one newline appended

Some files had either two newlines at the end or none (which isn't POSIX compliant). This patch fixes that.
2016-05-25 22:40:15 -07:00
Tyler Veness
d82635bbe1 Reordered headers according to the style guide (#58)
Subsections are alphabetized according to lexographic ordering. Also, HAL includes were moved from headers to source files where possible. This change may cause user code which uses HAL functionality and does not include the relevant HAL header (since it may have been provided by another WPILib header) to fail to compile.
2016-05-25 22:38:11 -07:00
Tyler Veness
a598e2d09b format.py: add missing 'sys' import (#69) 2016-05-25 21:11:43 -07:00
Tyler Veness
b5b2f0c7d8 Fixed typo in LinearDigitalFilter documentation (#62) 2016-05-25 20:27:34 -07:00
Tyler Veness
e6f6d24780 Removed empty default constructors and destructors from Gazebo plugins (#63) 2016-05-25 20:26:01 -07:00
Tyler Veness
21b2aabf18 Removed unused DS_LOG() macro (#61) 2016-05-25 20:25:06 -07:00
Tyler Veness
74f9da9da1 artf2612: Added Python script for updating license in source files (#57)
This is a follow-up of 3cd1253. A C++ program was written to automate the license update originally. That program was translated to Python so it can be kept in the repository and run when needed. It has been tested on Windows using the standard Python 3 installation and on Linux.

The original version skipped files that had "//" at the beginning since most were files that should be excluded. The relevant files are now in an exclusion list and the rest are processed normally. The .hpp file extension has been added as well. The script rewrote CompressorJNI.cpp to remove the carriage returns from its line endings.
2016-05-25 20:23:37 -07:00
Peter Johnson
e63830ed21 format.py: Fix running from styleguide directory on Windows. (#55) 2016-05-24 22:33:13 -07:00
Peter Johnson
eb51de65e5 format.py: Error out if no files found to format. (#56)
This can happen if the script is run from a directory other than the
project root or styleguide.
2016-05-24 22:16:53 -07:00
Peter Johnson
565a125dad Reformat for recent commits (#54) 2016-05-24 22:16:21 -07:00
Peter Johnson
3af8e7e9fd ControllerPower.cpp: Use quoted include instead of bracket for HAL. (#53)
This is consistent with all other source files.
2016-05-24 20:59:33 -07:00
Peter Mitrano
e3eae023da Cleanup of gazebo plugins (#46)
* Upgraded plugins for gazebo 7
* Fixed documentation on sensors
2016-05-24 20:27:24 -07:00
Thad House
6d9b3b0aaa Splits HAL Digital and Analog Headers into multiple headers (#52)
The Digital and Analog headers (and the implementations, but that will
be moved over later) are just too big and congested. This splits those
headers, and then changes the few things that needed to be changed in
WPILib to get the code working again. No function changes were made in
this commit.
2016-05-24 00:58:10 -07:00
Tyler Veness
9e99df1cf7 Removed sync group from SpeedController interface (#51)
CANJaguar is the only motor controller using sync groups, so that feature doesn't belong in an interface used by all motor controllers. If teams want to use sync groups, they should cast to the appropriate motor controller type themselves.
2016-05-23 20:42:58 -07:00
Thad House
e842ff7ad5 Explicitly stop the PIDController Notifier in the destructor (#48)
This helps reduce the probability of a PID Controller Segmentation Fault.
2016-05-22 23:24:10 -07:00
Peter Johnson
21b1e39b2a HAL Notifier: Use freelist to avoid use-after-free race. (#50)
As the notifierMutex is unlocked while the callback is being called in
alarmCallback(), it's possible for next to be invalidated due to a
cleanNotifier() call.  Now, instead of deleting the notifier immediately,
add it to a freelist to be cleaned up at the tail end of alarmCallback.
2016-05-22 23:21:45 -07:00
Thad House
8fc55c80a9 Renames all our .hpp HAL files to .h (#44)
Adds consistency, as the HAL was .hpp however all other code was .h.
2016-05-22 21:41:22 -07:00
Tyler Veness
248ca0c4a0 Added verbose flag to format.py (#47)
Making the "Processing" lines only print with a verbose option keeps the output clean.
2016-05-22 21:40:30 -07:00
Tyler Veness
0d655d7cec Ran formatter again (#45)
The previous wpilibc reformat missed an issue with CANTalon.h, and a patch merged since then didn't run the formatter.
2016-05-22 21:39:33 -07:00
Peter Mitrano
e71f454b9d Renamed folders for consistency, using sim/athena/shared schema (#27)
Rename the following folders:
hal/lib/Athena -> hal/lib/athena
hal/lib/Desktop -> hal/lib/sim
hal/lib/Shared -> hal/lib/shared
wpilibc/Athena -> wpilibc/athena
wpilibc/simulation -> wpilibc/sim

Windows users may need to run gradlew clean after updating.
2016-05-22 14:55:51 -07:00
Thad House
54092378e9 Changes HAL to return -1 to 1 for joysticks (#35)
First part of the HAL changes. Returns -1 to 1 for joysticks instead of
-128 to 127. Implemented by replacing the old structure with a new
structure that uses floats instead of shorts.
2016-05-21 01:42:16 -07:00
Thad House
a4f0c4fbe0 Implements locking in C++ DriverStation, and adds double buffering to DS Thread (#25)
Currently, about 5ms of every 20ms loop the DS thread would hold
the mutex, while grabbing data. During this time, and call to grab
joystick data would be blocked. This change grabs the joystick data
to a cache, and then grabs the mutex and moves the data references
around. This is much more efficient then the old code, and gives
teams more of their teleop loop time back for use.

Another major change this does is use preallocated arrays when entering
the JNI. Previously every JNI DS call would allocate an entire new array.
With a GC'd language where those arrays go on the heap, thats a problem,
and creates tons of garbage. That garbage is no longer created anymore,
as all arrays and byte buffers sent to JNI in the DS are preallocated.

In addition, GetJoystickName was always returning joystick 0 data, which
this fixes.
2016-05-21 00:41:15 -07:00
Omar Zrien
0965d60a71 Fixed a bug where using the two parameter constructor for CANTalon could cause invert-direction to not be initialized. (#26)
Original fix from Jacob Caporuscio
2016-05-20 23:08:35 -07:00
Peter Mitrano
f2d601d834 Use interrupt() in our interrupt exceptions (#24) 2016-05-20 23:06:07 -07:00
Tyler Veness
e14e45da76 Add format script which invokes clang-format on the C++ source code (#41)
On Windows machines, clang-format.exe must be in the PATH environment variable.
2016-05-20 17:30:37 -07:00
Peter Mitrano
68690643d2 Fix travis configuration to include compiling sim (#28) 2016-05-20 18:58:49 -04:00
Jonathan Leitschuh
00b2902102 Converts non hardware dependent tests to unit tests (#10) 2016-05-20 12:15:14 -07:00
Jonathan Leitschuh
975568c774 Adds Error Prone as compile time check to java projects (#13) 2016-05-20 10:48:41 -07:00
Jonathan Leitschuh
a834fff7b2 Applies Google Styleguide to Java parts of the library (#23)
This was partially applied to simulation but
simulation is a bit of a mess and has a lot of duplicated code.
2016-05-20 09:07:40 -07:00
Jonathan Leitschuh
64ab6e51fe Create .pullapprove.yml (#42) 2016-05-19 14:33:48 -04:00
PatrickPenguinTurtle
05a2089816 Fixed PCM tests by raising tolerance slightly (#15)
The PCM tests recently were failing by being slightly higher than voltage than expected. raised the tolerance to account for this.
Voltage was still clearly less than the on state while in the off state.

Change-Id: I8ac28867024f3ce7b4104fc03622e6133ac2b80f
2016-05-14 16:09:32 -04:00
Jonathan Leitschuh
b827f484be Add Slack Notification from Travis (#11) 2016-05-12 18:05:02 -04:00
Jonathan Leitschuh
000a98f193 Fix apt-get update -q causing build to fail (#20)
`sudo apt-get update -q` can fail a site doesn't respond.
This is the solution proposed here:
Related https://github.com/travis-ci/travis-ci/issues/5221
2016-05-12 17:51:57 -04:00
Fredric Silberberg
bb64dd3546 Updated README, and added in CONTRIBUTING. This adds tables of contents,
as well as fixing a few other issues.
2016-05-12 14:20:20 -04:00
Jonathan Leitschuh
d0c40b5ce2 Fixes indentation in .travis.yml 2016-05-11 15:06:06 -04:00
Jonathan Leitschuh
6794ff9ce8 Add Travis Build Configuration 2016-05-11 14:57:22 -04:00
Tyler Veness
083362bd86 Removed {@inheritDoc} from C++ sources and readded .inc files to Doxygen extension mapping
{@inheritDoc} doesn't exist in Doxygen, so I removed instances of it from the C++ source. It isn't needed anyway because Doxygen automatically fills in base class documentation for member functions in derived classes if no documentation is given. The extension mapping for .inc files was accidentally removed during the build system changes so this commit adds it back in.

Change-Id: I599e3bdafd76ee7d78a66090d81707cda5a399d7
2016-05-11 02:11:00 -07:00
Thad House
0f228e7b7d Implements a common PWMSpeedController base class
There was a lot of duplicated code between all 7 PWM speed controllers.
This moves all the duplicated code down to a base class, that will make
it easier to add speed controllers in future years if needed again. Also
if we need to add a method to all speed controllers, we only have to do
it in 1 place, and not 7.

Change-Id: I25eb1d097c0f5f7dbd7656db2f4a30d006d50f98
2016-05-11 01:01:31 -07:00
Tyler Veness
686f5d9fef Fix incorrect comments in the HAL I2C functions and incorrect return values for some I2C class member functions.
These issues were found and fixed while interfacing with an ITG3200 gyroscope. Fixes artf4173.

Change-Id: Id3c6b34aa707650480e90605e98ae1b44d7a7b98
2016-05-11 00:24:15 -07:00
Tyler Veness
ad8763fc8d Removed unused pcre.h header. If regexes are needed in the future, use C++11's regex header.
Change-Id: I0284943f3f09bbe9184885da6a486b82f73fd089
2016-05-10 23:12:36 -07:00
Thad House
1011b56b4c Fixes notifier restart error when last notifier is deleted
This actually isn't a large issue, since the HAL automatically creates a
notifier at the beginning to handle the time rollover, but during
testing without that, I noticed that deleting the last notifier would
disable notifiers for the entire lifetime of the program. This seemed to
be caused by the CLOSEST_TRIGGER static variable not being reset, and
causing new notifiers to never be added to the queue. This fixes that.
Not a bug that can be seen normally, but still a bug.

Change-Id: I6ac61c632918c90972cd0664aa833e3bc9e8c535
2016-05-10 23:06:13 -07:00
Peter Johnson
5904314a75 Improve ADXRS450 error detection.
Ensure the POR, PWR, and CST error bits are not set when reading the sample.

Reported by: Jared Russell, Austin Schuh

Change-Id: Ib38178d6b51880480aee86e13c16f9ba89a80693
2016-05-10 23:04:54 -07:00
Thad House
e852547344 Makes Java Timer timing more accurate
Java was using integer division for calulating Timer values, which
was causing Timer values to be concatinated, and only accurate
to the nearest millisecond. This changes it to use double division,
which matches C++ and makes timing much more accurate

Change-Id: I61b893f4ad5791bf4dfdd767ee4346c1ed4ea418
2016-05-10 23:02:35 -07:00
Peter Johnson
fa8b68419f Make Java AnalogGyro.getAngle() thread-safe.
In the Java implementation, "result" is an instance variable (to avoid
needing to perform a memory allocation on each call to getAngle).  However,
this means that calls to getAngle() from multiple threads can step on each
other.  Synchronize the method to avoid this issue.

Reported by: Jackson Gray (http://www.chiefdelphi.com/forums/showthread.php?threadid=145124)

Note this does not synchronize accesses between configuration methods such
as calibrate() and accessor methods such as getAngle().

Change-Id: I9ecc962d4fba66f6134fd801cfd607f155b41fe5
2016-05-09 20:36:36 -07:00
Fredric Silberberg
ec13d00b18 Fixed gradle build issue where files were not getting added to the wpilib java jar correctly.
Change-Id: I6c3cdd9906a94ff2d00340eb060a629d26c39a4a
2016-05-09 12:53:29 -07:00
Peter Johnson (294)
36447d86d8 Merge "Clear error buffer total when clearing the buffer contents" 2016-05-05 23:30:50 -07:00
Joe Ross
1e14403b3b Update POV documentation with examples of POV angles
Change-Id: If0f5b75366785b94a97b02694667fc00f8bfe196
2016-03-19 14:06:38 -07:00
Dustin Spicuzza
bee507eda8 Clear error buffer total when clearing the buffer contents
- Reported by Eli Barnett
- See http://www.chiefdelphi.com/forums/showthread.php?p=1559160`

Change-Id: I0efa4584452940bdfab3cc57c1823a8b33d387ff
2016-03-17 21:27:44 -04:00
1210 changed files with 59210 additions and 137351 deletions

89
.clang-format Normal file
View File

@@ -0,0 +1,89 @@
---
Language: Cpp
BasedOnStyle: Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IndentCaseLabels: true
IndentWidth: 2
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 8
UseTab: Never
...

9
.gitignore vendored
View File

@@ -8,6 +8,8 @@ dependency-reduced-pom.xml
/wpilibj/src/athena/cpp/nivision/*.java
/wpilibj/src/athena/cpp/nivision/nivision_funcs.txt
/wpilibj/src/athena/cpp/nivision/imaqdx_funcs.txt
/wpilibj/src/shared/java/edu/wpi/first/wpilibj/util/WPILibVersion.java
/wpilibc/shared/src/WPILibVersion.cpp
doxygen.log
# Created by the jenkins test script
@@ -181,3 +183,10 @@ NO
# Simulation folder stuff
!simulation/install_resources/*
# VSCode
.vscode/
#classpaths and projects
.project
.classpath

View File

@@ -1,5 +0,0 @@
[gerrit]
host=usfirst.collab.net
port=29418
project=allwpilib
defaultbranch=master

65
.styleguide Normal file
View File

@@ -0,0 +1,65 @@
cExtensions {
}
cppHeaderExtensions {
h
inc
}
cppSrcExtensions {
cpp
}
otherExtensions {
java
}
genFolderExclude {
FRC_FPGA_ChipObject
NetworkCommunication
ctre
frccansae
gtest
i2clib
msgs
ni-libraries
ni/vision
spilib
wpilibj/src/athena/cpp/nivision
visa
}
genFileExclude {
NIIMAQdx\.h$
can_proto\.h$
nivision\.h$
}
modifiableFolderExclude {
\.git
wpilibj/src/athena/cpp/include
wpilibj/src/athena/cpp/lib
}
modifiableFileExclude {
\.patch$
\.png$
\.py$
\.so$
}
includeRelated {
}
includeCSys {
}
includeCppSys {
}
includeOtherLibs {
}
includeProject {
^ctre/
}

6
.styleguide-license Normal file
View File

@@ -0,0 +1,6 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST {year}. All Rights Reserved.{padding}*/
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/

24
.travis.yml Normal file
View File

@@ -0,0 +1,24 @@
sudo: required
dist: trusty
language: java
before_install:
- sudo sh -c 'echo "deb http://packages.osrfoundation.org/gazebo/ubuntu-stable `lsb_release -cs` main" > /etc/apt/sources.list.d/gazebo-stable.list'
- wget http://packages.osrfoundation.org/gazebo.key -O - | sudo apt-key add -
- sudo add-apt-repository ppa:wpilib/toolchain -y
- sudo apt-get update -q || true
- sudo apt-get install frc-toolchain libgazebo7-dev protobuf-compiler libprotobuf-dev python3 clang-format-3.8 -y
install:
- pip3 install wpiformat
before_cache:
- rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
cache:
directories:
- $HOME/.gradle/caches/
- $HOME/.gradle/wrapper/
script:
- wpiformat
- git --no-pager diff --exit-code HEAD # Ensure formatter made no changes
- ./gradlew build -PmakeSim

View File

@@ -35,5 +35,5 @@ endif()
include_directories("build")
add_subdirectory(simulation/gz_msgs)
add_subdirectory(wpilibc/simulation)
add_subdirectory(wpilibc/sim)
add_subdirectory(simulation/frc_gazebo_plugins)

56
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,56 @@
# Contributing to WPILib
So you want to contribute your changes back to WPILib. Great! We have a few contributing rules that will help you make sure your changes will be accepted into the project. Please remember to follow the rules written here, and behave with Gracious Professionalism.
- [General Contribution Rules](#general-contribution-rules)
- [What to Contribute](#what-to-contribute)
- [Coding Guidelines](#coding-guidelines)
- [Submitting Changes](#submitting-changes)
- [Pull Request Format](#pull-request-format)
- [Merge Process](#merge-process)
- [Licensing](#licensing)
## General Contribution Rules
- Everything in the library must work for the 3000+ teams that will be using it.
- We need to be able to maintain submitted changes, even if you are no longer working on the project.
- Tool suite changes must be generally useful to a broad range of teams
- Excluding bug fixes, changes in one language generally need to have corresponding changes in other languages.
- Some features, such the addition of C++11 for WPILibC or Functional Interfaces for WPILibJ, are specific to that version of WPILib only.
- Substantial changes often need to have corresponding LabVIEW changes. To do this, we will work with NI on these large changes.
- 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.
## What to Contribute
- Bug reports and fixes
- We will generally accept bug fixes without too much question. If they are only implemented for one language, we will implement them for any other necessary languages. Bug reports are also welcome, please submit them to our GitHub issue tracker.
- While we do welcome improvements to the API, there are a few important rules to consider:
- Features must be added to both WPILibC and WPILibJ, with rare exceptions.
- During competition season, we will not merge any new feature additions. We want to ensure that the API is stable during the season to help minimize issues for teams.
- Ask about large changes before spending a bunch of time on them! You can create a new issue on our GitHub tracker for feature request/discussion and talk about it with us there.
- Features that make it easier for teams with less experience to be more successful are more likely to be accepted.
- Features in WPILib should be broadly applicable to all teams. Anything that is team specific should not be submitted.
- As a rule, we are happy with the general structure of WPILib. We are not interested in major rewrites of all of WPILib. We are open to talking about ideas, but backwards compatibility is very important for WPILib, so be sure to keep this in mind when proposing major changes.
- Generally speaking, we do not accept code for specific sensors. We have to be able to test the sensor in hardware on the WPILib test bed. Additionally, hardware availability for teams is important. Therefore, as a general rule, the library only directly supports hardware that is in the Kit of Parts. If you are a company interested in getting a sensor into the Kit of Parts, please contact FIRST directly at frcparts@firstinspires.org.
## Coding Guidelines
WPILib uses modified Google style guides for both C++ and Java, which can be found in the [styleguide repository](https://github.com/wpilibsuite/styleguide). Autoformatters are available for many popular editors at https://github.com/google/styleguide. Running wpiformat is required for all contributions and is enforced by our continuous integration system.
While the library should be fully formatted according to the styles, additional elements of the style guide were not followed when the library was initially created. All new code should follow the guidelines. If you are looking for some easy ramp-up tasks, finding areas that don't follow the style guide and fixing them is very welcome.
## Submitting Changes
### Pull Request Format
Changes should be submitted as a Pull Request against the master branch of WPILib. For most changes, we ask that you squash your changes down to a single commit. For particularly large changes, multiple commits are ok, but assume one commit unless asked otherwise. No change will be merged unless it is up to date with the current master. We will also not merge any changes with merge commits in them; please rebase off of master before submitting a pull request. We do this to make sure that the git history isn't too cluttered.
### Merge Process
When you first submit changes, Travis-CI will attempt to run `./gradlew check` on your change. If this fails, you will need to fix any issues that it sees. Once Travis passes, we will begin the review process in more earnest. One or more WPILib team members will review your change. This will be a back-and-forth process with the WPILib team and the greater community. Once we are satisfied that your change is ready, we will allow our Jenkins instance to test it. This will run the full gamut of checks, including integration tests on actual hardware. Once all tests have passed and the team is satisfied, we will merge your change into the WPILib repository.
## 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).

View File

@@ -1,36 +1,66 @@
# WPILib Project
[![Build Status](https://travis-ci.org/wpilibsuite/allwpilib.svg?branch=master)](https://travis-ci.org/wpilibsuite/allwpilib)
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.
- [WPILib Mission](#wpilib-mission)
- [Building WPILib](#building-wpilib)
- [Requirements](#requirements)
- [Setup](#setup)
- [Building](#building)
- [Publishing](#publishing)
- [Structure and Organization](#structure-and-organization)
- [Contributing to WPILib](#contributing-to-wpilib)
## 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).
# Building WPILib
Building WPILib is very straightforward. WPILib uses Gradle to compile. It only has a few dependencies on outside tools, including the ARM cross compiler.
Using Gradle makes building WPILib very straightforward. It only has a few dependencies on outside tools, such as the ARM cross compiler for creating roboRIO binaries.
## Requirements
- [ARM Compiler Toolchain](http://first.wpi.edu/FRC/roborio/toolchains/)
- Doxygen (Only required if you want to build the C++ documentation)
- [wpiformat](https://github.com/wpilibsuite/styleguide)
## Setup
Clone the WPILib Repo. If the toolchains are not installed, install them, and make sure they are available on the system PATH.
Clone the WPILib repository. If the toolchains are not installed, install them, and make sure they are available on the system PATH.
See the [styleguide README](https://github.com/wpilibsuite/styleguide/blob/master/README.md) for wpiformat setup instructions.
## Building
All build steps are executed using the Gradle wrapper, `gradlew`. Each target that Gradle can build is referred to as a task. The most common Gradle task to use is `build`. This will build all of the outputs created by WPILib. To run, open a console and cd into the cloned WPILib directory. Then:
All build steps are executed using the Gradle wrapper, `gradlew`. Each target that Gradle can build is referred to as a task. The most common Gradle task to use is `build`. This will build all the outputs created by WPILib. To run, open a console and cd into the cloned WPILib directory. Then:
```bash
./gradlew build
```
To build a specific subproject, such as wpilibc, you must access the subproject and run the build task only on that project. Accessing a subproject in Gradle is quite easy. Simply use `:subproject_name:task_name` with the Gradle wrapper. For example, building just wpilibc:
To build a specific subproject, such as WPILibC, you must access the subproject and run the build task only on that project. Accessing a subproject in Gradle is quite easy. Simply use `:subproject_name:task_name` with the Gradle wrapper. For example, building just WPILibC:
```bash
./gradlew :wpilibc:build
```
If you also want simulation to be build, add -PmakeSim. This requires gazebo_transport. We have tested on 14.04 and 15.05, but any correct install of gazebo should work, even on windows if you build from source. Correct means cmake needs to be able to find gazebo-config.cmake, which you get for free with ubuntu installs.
If you have installed the FRC Toolchain to a directory other than the default, or if the Toolchain location is not on your System PATH, you can pass the `toolChainPath` property to specify where it is located. Example:
```bash
./gradlew build -PtoolChainPath=some/path/to/frc/toolchain/bin
```
If you also want simulation to be built, add -PmakeSim. This requires gazebo_transport. We have tested on 14.04 and 15.05, but any correct install of Gazebo should work, even on Windows if you build Gazebo from source. Correct means CMake needs to be able to find gazebo-config.cmake. See [The Gazebo website](https://gazebosim.org/) for installation instructions.
```bash
./gradlew build -PmakeSim
```
C++ simulation tasks (including plugins, gz_msgs, and wpilibcSim) all depend on gazebo_transport. In order for this to build you must have installed gazebo. See [The Gazebo website](https://gazebosim.org/) for installation instructions.
If you prefer to use CMake directly, the you can still do so.
The common cmake tasks are wpilibcSim, frc_gazebo_plugins, and gz_msgs
The common CMake tasks are wpilibcSim, frc_gazebo_plugins, and gz_msgs
```bash
mkdir build #run this in the root of allwpilib
@@ -39,13 +69,15 @@ cmake ..
make
```
The gradlew wrapper only exists in the root of the main project, so be sure to run all commands from there. All of the subprojects have build tasks that can be run. Gradle automatically determines and rebuilds dependencies, so if you make a change to the HAL and then run `:wpilibc:build`, the HAL will be rebuilt, then wpilibc.
The gradlew wrapper only exists in the root of the main project, so be sure to run all commands from there. All of the subprojects have build tasks that can be run. Gradle automatically determines and rebuilds dependencies, so if you make a change in the HAL and then run `./gradlew :wpilibc:build`, the HAL will be rebuilt, then WPILibC.
There are a few tasks other than `build` available. To see them, run the meta-task `tasks`. This will print a list of all available tasks, with a description of each task.
wpiformat can be executed anywhere in the repository via `py -3 -m wpiformat` on Windows or `python3 -m wpiformat` on other platforms.
## 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 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:
- development - The default repo.
- beta - Publishes to ~/releases/maven/beta.
@@ -54,20 +86,25 @@ If you are building to test with the eclipse plugins or just want to export the
The following maven targets a published by this task:
- edu.wpi.first.wpilib.cmake:cpp-root:1.0.0 - RoboRIO C++
- 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: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.
## Structure and Organization
The main wpilib code you're probably looking for is in wpilibj and wpilibc. Those directories are split into shared, sim, and athena. Athena contains the wpilib code meant to run on your RoboRIO. Sim is wpilib code meant to run on your computer with gazebo, and shared is code shared between the two. Shared code must be platform-independent, since it will be compiled with both the ARM cross-compiler and whatever desktop compiler you are using (g++, msvc, etc...).
The main WPILib code you're probably looking for is in WPILibJ and WPILibC. Those directories are split into shared, sim, and athena. Athena contains the WPILib code meant to run on your roboRIO. Sim is WPILib code meant to run on your computer with Gazebo, and shared is code shared between the two. Shared code must be platform-independent, since it will be compiled with both the ARM cross-compiler and whatever desktop compiler you are using (g++, msvc, etc...).
The Simulation directory contains extra simulation tools and libraries, such as gz_msgs and JavaGazebo. See sub-directories for more information.
The integration test directories for C++ and Java contain test code that runs on our test-system. When you submit code for review, it is tested by those programs. If you add new functionality you should make sure to write tests for it so we don't break it in the future.
The hal directory contains more C++ code meant to run on the RoboRIO. HAL is an acronym for "Hardware Abstraction Layer", and it interfaces with the NI Libraries. The NI Libraries contain the low-level code for controlling devices on your robot. The NI Libraries are found in the ni-libraries folder.
The hal directory contains more C++ code meant to run on the roboRIO. HAL is an acronym for "Hardware Abstraction Layer", and it interfaces with the NI Libraries. The NI Libraries contain the low-level code for controlling devices on your robot. The NI Libraries are found in the ni-libraries folder.
The styleguide directory contains the styleguide for C++ and Java code. Anything submitted to the wpilib project needs to follow the code style guides outlined in there.
The [styleguide repository](https://github.com/wpilibsuite/styleguide) contains our style guides for C++ and Java code. Anything submitted to the WPILib project needs to follow the code style guides outlined in there. For details about the style, please see the contributors document [here](CONTRIBUTING.md#coding-guidelines).
# Contributing to WPILib
See [CONTRIBUTING.md](CONTRIBUTING.md).

View File

@@ -1,32 +1,49 @@
def enableSimulation = hasProperty('enableSimulation')
if (!hasProperty('repo')) {
ext.repo = 'development'
plugins {
id 'net.ltgt.errorprone' version '0.0.8'
id 'edu.wpi.first.wpilib.versioning.WPILibVersioningPlugin' version '1.6'
}
def repoBaseUrl = "http://first.wpi.edu/FRC/roborio/maven/${repo}"
def publishUrl = "${System.getProperty('user.home')}/releases/maven/${repo}"
// 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'
}
}
def enableSimulation = hasProperty('makeSim')
ext.simulationInstallDir = "$rootDir/build/install/simulation"
allprojects {
ext.enableSimulation = enableSimulation
ext.repo = repo
repositories {
mavenCentral()
maven {
url publishUrl
}
maven {
url repoBaseUrl
}
}
ext.ntcoreDep = { lang, classifier, extension = null ->
return "edu.wpi.first.wpilib.networktables.$lang:NetworkTables:+:$classifier${extension == null ? '' : '@' + extension}"
}
ext.cscoreDep = { lang, classifier, extension = null ->
return "edu.wpi.cscore.$lang:cscore:+:$classifier${extension == null ? '' : '@' + extension}"
}
ext.wpiUtilDep = { classifier ->
return "edu.wpi.first.wpilib:wpiutil:+:$classifier@zip"
}
}
subprojects {
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'checkstyle'
checkstyle {
toolVersion = "6.18"
configFile = new File(rootDir, "styleguide/checkstyle.xml")
}
ext.armBuild = true
@@ -36,12 +53,17 @@ subprojects {
options.addStringOption('Xdoclint:none', '-quiet')
}
}
ext.setupWpilibRepo = { publishing ->
publishing.repositories.maven {
url = "${System.getProperty('user.home')}/releases/maven/${repo}"
url = WPILibVersion.mavenLocalUrl
}
}
}
apply from: 'cppSettings.gradle'
apply from: 'ni-libraries/ni-libraries.gradle'
task wrapper(type: Wrapper) {
gradleVersion = '3.3'
}

View File

@@ -1,46 +1,46 @@
:: This file is a helper for allC++Sim
::
:: Usage: cd /build && ../configure
::
:: WARNING -- this is only temporary, and only meant for debug, and only works on my computer
@set WS=C:\Users\peter\gz-ws
@set BOOST_PATH=%WS%\boost_1_56_0
@set BOOST_LIBRARY_DIR=%BOOST_PATH%\lib64-msvc-12.0
@set PROTOBUF_PATH=%WS%\protobuf-2.6.0-win64-vc12
@set OGRE_PATH=%WS%\ogre_src_v1-8-1-vc12-x64-release-debug\build\install\Debug
@set OGRE_INCLUDE_DIR=%OGRE_PATH%\include;%OGRE_PATH%\include\OGRE;%OGRE_PATH%\include\OGRE\RTShaderSystem;%OGRE_PATH%\include\OGRE\Terrain;%OGRE_PATH%\include\OGRE\Paging
@set OGRE_LIBRARY_DIR=%OGRE_PATH%\lib\Debug
set OGRE_LIB_SUFFIX=_d.lib
@set OGRE_LIBS=%OGRE_LIBRARY_DIR%\OgreMain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreOverlay%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreRTShaderSystem%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreTerrain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgrePaging%OGRE_LIB_SUFFIX%
@set OGRE_LIBS=%OGRE_LIBRARY_DIR%\OgreMain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreRTShaderSystem%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreTerrain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgrePaging%OGRE_LIB_SUFFIX%
@set FREEIMAGE_PATH=%WS%\FreeImage-vc12-x64-release-debug
@set FREEIMAGE_INCLUDE_DIR=%FREEIMAGE_PATH%\Source
@set TBB_PATH=%WS%\tbb43_20141023oss
@set TBB_INCLUDEDIR=%TBB_PATH%\include
@set DLFCN_WIN32_PATH=%WS%\dlfcn-win32-vc12-x64-release-debug\build\install\Debug
@set DLFCN_WIN32_INCLUDE_DIR=%DLFCN_WIN32_PATH%\include
@set TINY_XML_INCLUDE_DIR=%WS%\sdformat\src\win\tinyxml
@set GAZEBO_PATH=%WS%\gazebo\build\install\Debug\lib\cmake\gazebo
@set SDFORMAT_PATH=%WS%\sdformat\build\install\Debug\lib\cmake\sdformat
@set IGNITION-MATH_PATH=%WS%\ign-math\build\install\Debug\lib\cmake\ignition-math2
@set INCLUDE=%TINY_XML_INCLUDE_DIR%;%FREEIMAGE_INCLUDE_DIR%;%TBB_INCLUDEDIR%;%DLFCN_WIN32_INCLUDE_DIR%;%INCLUDE%
@set LIB=%LIB%
cmake -G "NMake Makefiles"^
-DCMAKE_INSTALL_PREFIX=build^
-DCMAKE_PREFIX_PATH="%GAZEBO_PATH%;%SDFORMAT_PATH%;%IGNITION-MATH_PATH%"^
-DOGRE_FOUND=1^
-DOGRE_INCLUDE_DIRS="%OGRE_INCLUDE_DIR%"^
-DOGRE_LIBRARIES="%OGRE_LIBS%"^
-DPROTOBUF_SRC_ROOT_FOLDER="%PROTOBUF_PATH%"^
-DBOOST_ROOT="%BOOST_PATH%"^
-DBOOST_LIBRARYDIR="%BOOST_LIBRARY_DIR%"^
..
:: This file is a helper for allC++Sim
::
:: Usage: cd /build && ../configure
::
:: WARNING -- this is only temporary, and only meant for debug, and only works on my computer
@set WS=C:\Users\peter\gz-ws
@set BOOST_PATH=%WS%\boost_1_56_0
@set BOOST_LIBRARY_DIR=%BOOST_PATH%\lib64-msvc-12.0
@set PROTOBUF_PATH=%WS%\protobuf-2.6.0-win64-vc12
@set OGRE_PATH=%WS%\ogre_src_v1-8-1-vc12-x64-release-debug\build\install\Debug
@set OGRE_INCLUDE_DIR=%OGRE_PATH%\include;%OGRE_PATH%\include\OGRE;%OGRE_PATH%\include\OGRE\RTShaderSystem;%OGRE_PATH%\include\OGRE\Terrain;%OGRE_PATH%\include\OGRE\Paging
@set OGRE_LIBRARY_DIR=%OGRE_PATH%\lib\Debug
set OGRE_LIB_SUFFIX=_d.lib
@set OGRE_LIBS=%OGRE_LIBRARY_DIR%\OgreMain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreOverlay%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreRTShaderSystem%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreTerrain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgrePaging%OGRE_LIB_SUFFIX%
@set OGRE_LIBS=%OGRE_LIBRARY_DIR%\OgreMain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreRTShaderSystem%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgreTerrain%OGRE_LIB_SUFFIX%;%OGRE_LIBRARY_DIR%\OgrePaging%OGRE_LIB_SUFFIX%
@set FREEIMAGE_PATH=%WS%\FreeImage-vc12-x64-release-debug
@set FREEIMAGE_INCLUDE_DIR=%FREEIMAGE_PATH%\Source
@set TBB_PATH=%WS%\tbb43_20141023oss
@set TBB_INCLUDEDIR=%TBB_PATH%\include
@set DLFCN_WIN32_PATH=%WS%\dlfcn-win32-vc12-x64-release-debug\build\install\Debug
@set DLFCN_WIN32_INCLUDE_DIR=%DLFCN_WIN32_PATH%\include
@set TINY_XML_INCLUDE_DIR=%WS%\sdformat\src\win\tinyxml
@set GAZEBO_PATH=%WS%\gazebo\build\install\Debug\lib\cmake\gazebo
@set SDFORMAT_PATH=%WS%\sdformat\build\install\Debug\lib\cmake\sdformat
@set IGNITION-MATH_PATH=%WS%\ign-math\build\install\Debug\lib\cmake\ignition-math2
@set INCLUDE=%TINY_XML_INCLUDE_DIR%;%FREEIMAGE_INCLUDE_DIR%;%TBB_INCLUDEDIR%;%DLFCN_WIN32_INCLUDE_DIR%;%INCLUDE%
@set LIB=%LIB%
cmake -G "NMake Makefiles"^
-DCMAKE_INSTALL_PREFIX=build^
-DCMAKE_PREFIX_PATH="%GAZEBO_PATH%;%SDFORMAT_PATH%;%IGNITION-MATH_PATH%"^
-DOGRE_FOUND=1^
-DOGRE_INCLUDE_DIRS="%OGRE_INCLUDE_DIR%"^
-DOGRE_LIBRARIES="%OGRE_LIBS%"^
-DPROTOBUF_SRC_ROOT_FOLDER="%PROTOBUF_PATH%"^
-DBOOST_ROOT="%BOOST_PATH%"^
-DBOOST_LIBRARYDIR="%BOOST_LIBRARY_DIR%"^
..

View File

@@ -1,101 +1,179 @@
// This regex matches either a Windows or Unix style file separator, then the lib part of the library,
// then the name of the library itself, and finally the .so extension at the end. The name of the library
// is in the libName capture group, which is extracted and used for the linker flags
def libPattern = /.*((\\/|\\).*)+lib(?<libName>.+).so$/
def niLibraryArgs = []
def niLibraryPath = file('ni-libraries').path
// These add the nilibraries shared library to the linker args
def niLibraryPath = file('ni-libraries/lib').path
def niLibrary = niLibraryPath + "/libnilibraries.so"
// The NI Library tree includes all non-wpi libraries, which is everything that doesn't have libwpi in the name
def niLibraryTree = fileTree(niLibraryPath)
niLibraryTree.include '*.so'
niLibraryTree.exclude '*wpi*.so'
configurations.create('armDeps')
// This adds all linker flags to the list of ni library linker flags
niLibraryTree.each { lib ->
def nameMatcher = (lib.path =~ libPattern)
if (nameMatcher[0].size() > 1) {
def name = nameMatcher.group('libName')
niLibraryArgs << '-l' + name
dependencies {
armDeps ntcoreDep('cpp', 'arm', 'zip')
armDeps wpiUtilDep('arm')
armDeps cscoreDep('cpp', 'athena-uberzip', 'zip')
}
def depLocation = "$buildDir/dependencies"
configurations.armDeps.files.each { file ->
def depName = file.name.substring(0, file.name.indexOf('-'))
def t = tasks.create("downloadArm${depName.capitalize()}", Copy) {
description = "Downloads and unzips the $depName dependency."
group = 'Dependencies'
from zipTree(file)
into "$depLocation/${depName.toLowerCase()}"
}
}
def armNtDependency =
project.dependencies.create("edu.wpi.first.wpilib.networktables.cpp:NetworkTables:3.0.0-SNAPSHOT:arm@zip")
def armConfig = project.configurations.detachedConfiguration(armNtDependency)
armConfig.setTransitive(false)
def armNetTables = armConfig.files[0].canonicalFile
def desktopNetTables
if (project.hasProperty('makeSim')){
def desktopNtDependency =
project.dependencies.create("edu.wpi.first.wpilib.networktables.cpp:NetworkTables:3.0.0-SNAPSHOT:desktop@zip")
def desktopConfig = project.configurations.detachedConfiguration(desktopNtDependency)
desktopConfig.setTransitive(false)
desktopNetTables = desktopConfig.files[0].canonicalFile
task downloadNetworkTables {
description = 'Downloads all needed versions of networktables.'
group = 'Dependencies'
dependsOn downloadArmNetworkTables
}
def netTablesUnzipLocation = "$buildDir/networktables"
task downloadWpiutil {
description = 'Downloads all needed versions of WPIUtil.'
group = 'Dependencies'
dependsOn downloadArmWpiutil
}
// Create a task that will unzip the networktables files into a temporary build directory
task unzipNetworkTables(type: Copy) {
description = 'Unzips the networktables maven dependency so that the include files and libraries can be used'
group = 'WPILib'
if (project.hasProperty('makeSim')){
from zipTree(desktopNetTables)
task downloadCscore {
description = 'Downloads all needed versions of cscore.'
group = 'Dependencies'
dependsOn downloadArmCscore
}
if (enableSimulation) {
configurations.create('nativeDeps')
dependencies {
nativeDeps ntcoreDep('cpp', 'desktop', 'zip')
nativeDeps wpiUtilDep('desktop')
}
from zipTree(armNetTables)
into netTablesUnzipLocation
configurations.nativeDeps.files.each { file ->
def depName = file.name.substring(0, file.name.indexOf('-'))
def t = tasks.create("downloadNative${depName.capitalize()}", Copy) {
description = "Downloads and unzips the $depName dependency."
group = 'Dependencies'
from zipTree(file)
into "$depLocation/${depName.toLowerCase()}"
}
}
downloadNetworkTables.dependsOn downloadNativeNetworkTables
downloadWpiutil.dependsOn downloadNativeWpiutil
}
def netTablesUnzipLocation = "$depLocation/networktables"
def wpiUtilUnzipLocation = "$depLocation/wpiutil"
def csCoreUnzipLocation = "$depLocation/cscore"
task clean(type: Delete) {
description = "Deletes the build directory"
group = "Build"
delete buildDir
}
subprojects {
plugins.withType(CppPlugin).whenPluginAdded {
// This defines a project property that projects depending on network tables can use to setup that dependency.
ext.defineNetworkTablesProperties = {
ext.netTables = netTablesUnzipLocation
ext.netTablesInclude = "$netTablesUnzipLocation/include"
ext.netLibArmLocation = "$netTablesUnzipLocation/Linux/arm"
if (project.hasProperty('makeSim')){
ext.netLibDesktopLocation = "$netTablesUnzipLocation/Linux/amd64"
}
ext.netSharedLib = "$netLibArmLocation/libntcore.so"
ext.netStaticLib = "$netLibArmLocation/libntcore.a"
if (!hasProperty("toolChainPath")) {
ext.toolChainPath = null
}
task addNetworkTablesLibraryLinks() {
description = 'Adds the linker flags for the networktables libraries retreived from maven'
group = 'WPILib'
dependsOn project(':').unzipNetworkTables
doLast {
binaries.all {
tasks.withType(CppCompile) {
// desktop version doesn't use all the NI libraries
// so only do this for arm libraries
String architecture = targetPlatform.architecture
if (architecture.contains('arm')){
linker.args netStaticLib
}
}
}
}
subprojects {
ext.defineWpiUtilProperties = {
ext.wpiUtil = wpiUtilUnzipLocation
ext.wpiUtilInclude = "$wpiUtilUnzipLocation/include"
ext.wpiUtilLibArmLocation = "$wpiUtilUnzipLocation/Linux/arm"
if (enableSimulation) {
ext.wpiUtilLibDesktopLocation = "$wpiUtilUnzipLocation/Linux/amd64"
}
ext.wpiUtilSharedLib = "$wpiUtilLibArmLocation/libwpiutil.so"
ext.wpiUtilSharedLibDebug = "$wpiUtilLibArmLocation/libwpiutil.so.debug"
ext.wpiUtilStaticLib = "$wpiUtilLibArmLocation/libwpiutil.a"
ext.addWpiUtilLibraryLinks = { compileTask, linker, targetPlatform ->
compileTask.dependsOn project(':').downloadWpiutil
String architecture = targetPlatform.architecture
if (architecture.contains('arm')) {
linker.args wpiUtilSharedLib
}
}
ext.addStaticWpiUtilLibraryLinks = { compileTask, linker, targetPlatform ->
compileTask.dependsOn project(':').downloadWpiutil
String architecture = targetPlatform.architecture
if (architecture.contains('arm')) {
linker.args wpiUtilStaticLib
}
}
}
// This defines a project property that projects depending on network tables can use to setup that dependency.
ext.defineNetworkTablesProperties = {
ext.netTables = netTablesUnzipLocation
ext.netTablesInclude = "$netTablesUnzipLocation/include"
ext.netLibArmLocation = "$netTablesUnzipLocation/Linux/arm"
if (enableSimulation) {
ext.netLibDesktopLocation = "$netTablesUnzipLocation/Linux/amd64"
}
ext.netSharedLib = "$netLibArmLocation/libntcore.so"
ext.netSharedLibDebug = "$netLibArmLocation/libntcore.so.debug"
ext.netStaticLib = "$netLibArmLocation/libntcore.a"
ext.addNetworkTablesLibraryLinks = { compileTask, linker, targetPlatform ->
compileTask.dependsOn project(':').downloadNetworkTables
String architecture = targetPlatform.architecture
if (architecture.contains('arm')) {
linker.args netSharedLib
}
addWpiUtilLibraryLinks(compileTask, linker, targetPlatform)
}
ext.addStaticNetworkTablesLibraryLinks = { compileTask, linker, targetPlatform ->
compileTask.dependsOn project(':').downloadNetworkTables
String architecture = targetPlatform.architecture
if (architecture.contains('arm')) {
linker.args netStaticLib
}
addStaticWpiUtilLibraryLinks(compileTask, linker, targetPlatform)
}
}
// This defines a project property that projects depending on cscore can use to setup that dependency.
ext.defineCsCoreProperties = {
ext.csCore = csCoreUnzipLocation
ext.csCoreInclude = "$csCoreUnzipLocation/include"
ext.csLibArmLocation = "$csCoreUnzipLocation/lib"
ext.csSharedLib = "$csLibArmLocation/libcscore.so"
ext.cvSharedLib = "$csLibArmLocation/libopencv.so"
ext.addCsCoreLibraryLinks = { compileTask, linker, targetPlatform ->
compileTask.dependsOn project(':').downloadCscore
String architecture = targetPlatform.architecture
if (architecture.contains('arm')) {
linker.args << '-L' + csLibArmLocation
linker.args csSharedLib
linker.args cvSharedLib
}
}
}
ext.defineCrossCompilerProperties = {
// We use a custom-built cross compiler with the prefix arm-frc-linux-gnueabi-<util name>
// If this ever changes, the prefix will need to be changed here
ext.compilerPrefix = 'arm-frc-linux-gnueabi-'
}
plugins.withType(CppPlugin).whenPluginAdded {
defineCrossCompilerProperties()
model {
buildTypes {
debug
}
// Adds a custom toolchain for our compiler prefix and options
toolChains {
gcc(Gcc) {
target('arm') {
// We use a custom-built cross compiler with the prefix arm-frc-linux-gnueabi-<util name>
// If this ever changes, the prefix will need to be changed here
def compilerPrefix = 'arm-frc-linux-gnueabi-'
roborioGcc(Gcc) {
if (toolChainPath != null)
path toolChainPath
target('roborio-arm') {
cCompiler.executable = compilerPrefix + cCompiler.executable
cppCompiler.executable = compilerPrefix + cppCompiler.executable
linker.executable = compilerPrefix + linker.executable
assembler.executable = compilerPrefix + assembler.executable
@@ -103,7 +181,7 @@ subprojects {
// arm, and doesn't understand this flag, so it is removed from both
cppCompiler.withArguments { args ->
args << '-std=c++1y' << '-Wformat=2' << '-Wall' << '-Wextra' << '-Werror' << '-pedantic'
args << '-Wno-psabi' << '-Wno-unused-parameter' << '-fPIC' << '-O0' << '-g3' << '-rdynamic'
args << '-Wno-psabi' << '-Wno-unused-parameter' << '-fPIC' << '-Og' << '-g3' << '-rdynamic'
//TODO: When the compiler allows us to actually call deprecated functions from within
// deprecated function, remove this line (this will cause calling deprecated functions
// to be treated as a warning rather than an error).
@@ -117,74 +195,45 @@ subprojects {
staticLibArchiver.executable = compilerPrefix + staticLibArchiver.executable
}
}
// Workaround for OS X. Macs for some reason want to use Xcode's gcc
// (which just wraps Clang), so we have to explicitly make it so
// that trying to compile with Clang will call gcc instead
macGcc(Clang) {
target('arm') {
// We use a custom-built cross compiler with the prefix arm-frc-linux-gnueabi-<util name>
// If this ever changes, the prefix will need to be changed here
def compilerPrefix = 'arm-frc-linux-gnueabi-'
cppCompiler.executable = compilerPrefix + 'g++'
linker.executable = compilerPrefix + 'g++'
assembler.executable = compilerPrefix + 'gcc'
// Gradle auto-adds the -m32 argument to the linker and compiler. Our compiler only supports
// arm, and doesn't understand this flag, so it is removed from both
cppCompiler.withArguments { args ->
args << '-std=c++1y' << '-Wformat=2' << '-Wall' << '-Wextra' << '-Werror' << '-pedantic'
args << '-Wno-psabi' << '-Wno-unused-parameter' << '-fPIC' << '-O0' << '-g3' << '-rdynamic'
//TODO: When the compiler allows us to actually call deprecated functions from within
// deprecated function, remove this line (this will cause calling deprecated functions
// to be treated as a warning rather than an error).
args << '-Wno-error=deprecated-declarations'
args.remove('-m32')
}
linker.withArguments { args ->
args << '-rdynamic'
args.remove('-m32')
}
staticLibArchiver.executable = compilerPrefix + 'ar'
}
}
}
// The only platform is arm linux
platforms {
arm {
'roborio-arm' {
architecture 'arm'
operatingSystem 'linux'
}
}
}
ext.niLibraryHeadersRoot = "${rootDir}/ni-libraries/include"
ext.niLibraryHeadersChipObject = "${rootDir}/ni-libraries/include/FRC_FPGA_ChipObject"
ext.binTool = { tool ->
if (toolChainPath != null) return "${toolChainPath}/${compilerPrefix}${tool}"
return "${compilerPrefix}${tool}"
}
// This task adds the appropriate linker flags for the NI libraries
task addNiLibraryLinks() {
description = 'Adds the linker flags for the NI libraries in the ni-library folders'
group = 'WPILib'
doLast {
binaries.all {
tasks.withType(CppCompile) {
// desktop version doesn't use all the NI libraries
// so only do this for arm libraries
String architecture = targetPlatform.architecture
if (architecture.contains('arm')){
linker.args << '-L' + niLibraryPath
linker.args.addAll(niLibraryArgs)
}
}
}
model {
repositories {
libs(PrebuiltLibraries) { libs ->
// Loops through all .so files (except files matching *libwpi*.so) in ../ni-libraries
// and includes them for linking
niLibraryTree.each { niLib ->
libs.create(niLib) {
binaries.withType(SharedLibraryBinary) {
sharedLibraryFile = file(niLib.path)
}
}
}
ext.addNiLibraryLinks = { linker, targetPlatform ->
String architecture = targetPlatform.architecture
if (architecture.contains('arm')){
linker.args << '-L' + niLibraryPath
linker.args niLibrary
}
}
// This task sets up the shared libraries to be stripped
ext.debugStripSetup = { project->
if (!project.hasProperty('debug')) {
project.tasks.whenObjectAdded { task ->
def name = task.name.toLowerCase()
if (name.contains('link') && name.contains('sharedlibrary')) {
def library = task.outputFile.absolutePath
def debugLibrary = task.outputFile.absolutePath + ".debug"
task.doLast {
exec { commandLine binTool('objcopy'), '--only-keep-debug', library, debugLibrary }
exec { commandLine binTool('strip'), '-g', library }
exec { commandLine binTool('objcopy'), "--add-gnu-debuglink=$debugLibrary", library }
}
}
}

178
gen/wpilibj_frcnetcomm.py Executable file
View File

@@ -0,0 +1,178 @@
#!/usr/bin/env python3
# This script generates the network communication interface for wpilibj.
#
# This script takes no arguments and should be invoked from either the gen
# directory or the root directory of the project.
from datetime import date
import os
import re
import subprocess
# Check that the current directory is part of a Git repository
def inGitRepo(directory):
ret = subprocess.run(["git", "rev-parse"], stderr = subprocess.DEVNULL)
return ret.returncode == 0
def main():
if not inGitRepo("."):
print("Error: not invoked within a Git repository", file = sys.stderr)
sys.exit(1)
# Handle running in either the root or gen directories
configPath = "."
if os.getcwd().rpartition(os.sep)[2] == "gen":
configPath = ".."
outputName = configPath + \
"/wpilibj/src/athena/java/edu/wpi/first/wpilibj/hal/FRCNetComm.java"
# Set initial copyright year and get current year
year = "2016"
currentYear = str(date.today().year)
# Start writing output file
with open(outputName + ".tmp", "w") as temp:
# Write first line of comment
temp.write("/*")
for i in range(0, 76):
temp.write("-")
temp.write("*/\n")
# Write second line of comment
temp.write("/* Copyright (c) FIRST ")
if year != currentYear:
temp.write(year)
temp.write("-")
temp.write(currentYear)
temp.write(". All Rights Reserved.")
for i in range(0, 24):
temp.write(" ")
if year == currentYear:
for i in range(0, 5):
temp.write(" ")
temp.write("*/\n")
# Write rest of lines of comment
temp.write("""\
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*""")
for i in range(0, 76):
temp.write("-")
temp.write("*/\n")
# Write preamble
temp.write("""
package edu.wpi.first.wpilibj.hal;
import edu.wpi.first.wpilibj.hal.JNIWrapper;
/**
* JNI wrapper for library <b>FRC_NetworkCommunication</b><br>.
*/
@SuppressWarnings(\"MethodName\")
public class FRCNetComm extends JNIWrapper {
""")
# Read enums from C++ source files
firstEnum = True
for fileName in ["LoadOut.h", "UsageReporting.h"]:
with open(configPath + "/hal/include/FRC_NetworkCommunication/" + \
fileName, "r") as cppSource:
while True:
# Read until an enum is encountered
line = ""
pos = -1
while line.find("enum") == -1:
line = cppSource.readline()
if line == "":
break
if line == "":
break
# If "{" is on next line, read next line
if line.find("{") == -1:
line = cppSource.readline()
# Write enum to output file as interface
values = []
line = cppSource.readline()
while line.find("}") == -1:
if line == "\n":
values.append("")
else:
if line[0] != "#":
line = line.strip()
if line[len(line) - 1] == ",":
values.append(line[0:len(line) - 1])
else:
values.append(line)
line = cppSource.readline()
# Extract enum name
nameStart = 0
for i, c in enumerate(line):
if c != " " and c != "}":
nameStart = i
break
enumName = line[nameStart:len(line) - 2]
# Write comment for interface name
# Only add newline if not the first enum
if firstEnum == True:
firstEnum = False
else:
temp.write("\n")
temp.write(" /**\n"
" * ")
# Splits camelcase string into words
enumCamel = re.findall(r'[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))',
enumName)
temp.write(enumCamel[0] + " ")
for i in range(1, len(enumCamel)):
temp.write(enumCamel[i][0].lower() + \
enumCamel[i][1:len(enumCamel[i])] + " ")
temp.write("from " + fileName + "\n"
" */\n"
" @SuppressWarnings(\"TypeName\")\n"
" public interface " + enumName + " {\n")
# Write enum values
count = 0
for value in values:
# Pass through empty lines
if value == "":
temp.write("\n")
continue
if value.find("=") == -1:
value = value + " = " + str(count)
count += 1
# Add scoping for values from a different enum
if enumName != "tModuleType" and \
value.find("kModuleType") != -1:
value = value.replace("kModuleType",
"tModuleType.kModuleType")
temp.write(" int " + value[0:len(value)] + ";\n")
# Write end of enum
temp.write(" }\n")
# Write closing brace for file
temp.write("}\n")
# Replace old output file
try:
os.remove(outputName)
except OSError:
pass
os.rename(outputName + ".tmp", outputName)
if __name__ == "__main__":
main()

Binary file not shown.

View File

@@ -1,6 +1,6 @@
#Sat Nov 21 18:19:09 EST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-bin.zip
#Wed Jan 04 21:49:36 PST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip

68
gradlew vendored
View File

@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
##############################################################################
##
@@ -6,12 +6,30 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -30,6 +48,7 @@ die ( ) {
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
@@ -40,26 +59,11 @@ case "`uname`" in
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -85,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@@ -150,11 +154,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

14
gradlew.bat vendored
View File

@@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@@ -46,10 +46,9 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@@ -60,11 +59,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line

View File

@@ -1,47 +1,160 @@
// There are two hal libraries that are built
// - Desktop which is used by simulation (gcc/msvc)
// - Athena which is used by the roborio (arm)
// - desktop which is used by simulation (gcc/msvc)
// - athena which is used by the roborio (arm)
apply plugin: 'cpp'
plugins {
id 'cpp'
id 'maven-publish'
}
defineWpiUtilProperties()
debugStripSetup(project)
model {
components {
HALAthena(NativeLibrarySpec) {
targetPlatform 'arm'
tasks.withType(CppCompile) {
dependsOn addNiLibraryLinks
targetPlatform 'roborio-arm'
binaries.all {
tasks.withType(CppCompile) {
addNiLibraryLinks(linker, targetPlatform)
addWpiUtilLibraryLinks(it, linker, targetPlatform)
}
}
sources {
cpp {
source {
srcDirs = ["lib/Athena", "lib/Athena/FRC_FPGA_ChipObject", "lib/Shared"]
srcDirs = ["lib/athena", niLibraryHeadersRoot, "lib/shared"]
includes = ["**/*.cpp"]
}
exportedHeaders {
srcDirs = ["include", "lib/Athena", "lib/Athena/FRC_FPGA_ChipObject", "lib/Shared"]
srcDirs = ["include", niLibraryHeadersRoot, wpiUtilInclude]
}
}
}
}
// HALDesktop(NativeLibrarySpec) {
// binaries.all {
// if (toolChain in Gcc){
// cppCompiler.args "-std=c++1y"
// }
// }
//
// sources {
// cpp {
// source {
// srcDirs = ["lib/Desktop", "lib/Shared"]
// includes = ["**/*.cpp"]
// }
// exportedHeaders {
// srcDirs = ["include", "lib/Desktop", "lib/Shared"]
// }
// }
// }
// }
}
tasks { tasks ->
tasks.halZip.dependsOn tasks.HALAthenaSharedLibrary
tasks.athenaRuntimeZip.dependsOn tasks.HALAthenaSharedLibrary
}
}
task halZip(type: Zip) {
description = 'Zips the HAL'
group = 'WPILib'
baseName = 'hal'
destinationDir = project.buildDir
duplicatesStrategy = 'exclude'
// Include the shared library file and header files from this project
model {
binaries {
withType(SharedLibraryBinarySpec) { spec ->
spec.headerDirs.each {
def normalizedIt = it.toString().replace('/', '\\')
def normalizedWPIUtil = wpiUtilInclude.toString().replace('/', '\\')
// exclude the wpiUtil library, and any NI libraries (NI libraries grabbed later)
if (normalizedIt != normalizedWPIUtil) {
from(it) {
into 'include'
// We don't want to include any of the .cpp files that are in some of the header directories
exclude '**/*.cpp'
}
}
}
from(spec.sharedLibraryFile) {
into 'lib'
}
from(new File(spec.sharedLibraryFile.absolutePath + ".debug")) {
into 'lib'
}
}
}
}
// Finally, include all of the shared library objects from the ni directory
from(project.file('../ni-libraries/lib')) {
into 'lib'
exclude 'genlinks'
exclude 'genlinks.bat'
exclude 'libwpi.so'
}
}
task athenaRuntimeZip(type: Zip) {
description = 'Zips the Athena Runtime libraries'
group = 'WPILib'
baseName = 'athena-runtime'
destinationDir = project.buildDir
duplicatesStrategy = 'exclude'
// Include the static library file and header files from this project
model {
binaries {
withType(SharedLibraryBinarySpec) { spec ->
spec.headerDirs.each {
from(it) {
into 'include'
// We don't want to include any of the .cpp files that are in some of the header directories
exclude '**/*.cpp'
}
}
from(spec.sharedLibraryFile) {
into 'lib'
}
from(new File(spec.sharedLibraryFile.absolutePath + ".debug")) {
into 'lib'
}
}
}
}
defineNetworkTablesProperties()
dependsOn project(':').downloadNetworkTables
from(project.file(netTablesInclude)) {
into 'include'
}
from (file(netSharedLib)) {
into 'lib'
}
from (file(netSharedLibDebug)) {
into 'lib'
}
from (file(wpiUtilSharedLib)) {
into 'lib'
}
from (file(wpiUtilSharedLibDebug)) {
into 'lib'
}
}
publishing {
publications {
hal(MavenPublication) {
artifact halZip
groupId 'edu.wpi.first.wpilib'
artifactId 'hal'
version WPILibVersion.version
}
athenaruntime(MavenPublication) {
artifact athenaRuntimeZip
groupId 'edu.wpi.first.wpilib'
artifactId 'athena-runtime'
version WPILibVersion.version
}
}
setupWpilibRepo(it)
}
build.dependsOn halZip
build.dependsOn athenaRuntimeZip

View File

@@ -0,0 +1,28 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "HAL/Types.h"
enum HAL_AccelerometerRange : int32_t {
HAL_AccelerometerRange_k2G = 0,
HAL_AccelerometerRange_k4G = 1,
HAL_AccelerometerRange_k8G = 2,
};
#ifdef __cplusplus
extern "C" {
#endif
void HAL_SetAccelerometerActive(HAL_Bool active);
void HAL_SetAccelerometerRange(HAL_AccelerometerRange range);
double HAL_GetAccelerometerX(void);
double HAL_GetAccelerometerY(void);
double HAL_GetAccelerometerZ(void);
#ifdef __cplusplus
}
#endif

View File

@@ -1,15 +0,0 @@
#pragma once
enum AccelerometerRange {
kRange_2G = 0,
kRange_4G = 1,
kRange_8G = 2,
};
extern "C" {
void setAccelerometerActive(bool);
void setAccelerometerRange(AccelerometerRange);
double getAccelerometerX();
double getAccelerometerY();
double getAccelerometerZ();
}

View File

@@ -1,78 +0,0 @@
#pragma once
#include <stdint.h>
enum AnalogTriggerType
{
kInWindow = 0,
kState = 1,
kRisingPulse = 2,
kFallingPulse = 3
};
extern "C"
{
// Analog output functions
void* initializeAnalogOutputPort(void* port_pointer, int32_t *status);
void freeAnalogOutputPort(void* analog_port_pointer);
void setAnalogOutput(void* analog_port_pointer, double voltage, int32_t *status);
double getAnalogOutput(void* analog_port_pointer, int32_t *status);
bool checkAnalogOutputChannel(uint32_t pin);
// Analog input functions
void* initializeAnalogInputPort(void* port_pointer, int32_t *status);
void freeAnalogInputPort(void* analog_port_pointer);
bool checkAnalogModule(uint8_t module);
bool checkAnalogInputChannel(uint32_t pin);
void setAnalogSampleRate(double samplesPerSecond, int32_t *status);
float getAnalogSampleRate(int32_t *status);
void setAnalogAverageBits(void* analog_port_pointer, uint32_t bits, int32_t *status);
uint32_t getAnalogAverageBits(void* analog_port_pointer, int32_t *status);
void setAnalogOversampleBits(void* analog_port_pointer, uint32_t bits, int32_t *status);
uint32_t getAnalogOversampleBits(void* analog_port_pointer, int32_t *status);
int16_t getAnalogValue(void* analog_port_pointer, int32_t *status);
int32_t getAnalogAverageValue(void* analog_port_pointer, int32_t *status);
int32_t getAnalogVoltsToValue(void* analog_port_pointer, double voltage, int32_t *status);
float getAnalogVoltage(void* analog_port_pointer, int32_t *status);
float getAnalogAverageVoltage(void* analog_port_pointer, int32_t *status);
uint32_t getAnalogLSBWeight(void* analog_port_pointer, int32_t *status);
int32_t getAnalogOffset(void* analog_port_pointer, int32_t *status);
bool isAccumulatorChannel(void* analog_port_pointer, int32_t *status);
void initAccumulator(void* analog_port_pointer, int32_t *status);
void resetAccumulator(void* analog_port_pointer, int32_t *status);
void setAccumulatorCenter(void* analog_port_pointer, int32_t center, int32_t *status);
void setAccumulatorDeadband(void* analog_port_pointer, int32_t deadband, int32_t *status);
int64_t getAccumulatorValue(void* analog_port_pointer, int32_t *status);
uint32_t getAccumulatorCount(void* analog_port_pointer, int32_t *status);
void getAccumulatorOutput(void* analog_port_pointer, int64_t *value, uint32_t *count,
int32_t *status);
void* initializeAnalogTrigger(void* port_pointer, uint32_t *index, int32_t *status);
void cleanAnalogTrigger(void* analog_trigger_pointer, int32_t *status);
void setAnalogTriggerLimitsRaw(void* analog_trigger_pointer, int32_t lower, int32_t upper,
int32_t *status);
void setAnalogTriggerLimitsVoltage(void* analog_trigger_pointer, double lower, double upper,
int32_t *status);
void setAnalogTriggerAveraged(void* analog_trigger_pointer, bool useAveragedValue,
int32_t *status);
void setAnalogTriggerFiltered(void* analog_trigger_pointer, bool useFilteredValue,
int32_t *status);
bool getAnalogTriggerInWindow(void* analog_trigger_pointer, int32_t *status);
bool getAnalogTriggerTriggerState(void* analog_trigger_pointer, int32_t *status);
bool getAnalogTriggerOutput(void* analog_trigger_pointer, AnalogTriggerType type,
int32_t *status);
//// Float JNA Hack
// Float
int getAnalogSampleRateIntHack(int32_t *status);
int getAnalogVoltageIntHack(void* analog_port_pointer, int32_t *status);
int getAnalogAverageVoltageIntHack(void* analog_port_pointer, int32_t *status);
// Doubles
void setAnalogSampleRateIntHack(int samplesPerSecond, int32_t *status);
int32_t getAnalogVoltsToValueIntHack(void* analog_port_pointer, int voltage, int32_t *status);
void setAnalogTriggerLimitsVoltageIntHack(void* analog_trigger_pointer, int lower, int upper,
int32_t *status);
}

View File

@@ -0,0 +1,36 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_Bool HAL_IsAccumulatorChannel(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
void HAL_InitAccumulator(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
void HAL_ResetAccumulator(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
void HAL_SetAccumulatorCenter(HAL_AnalogInputHandle analogPortHandle,
int32_t center, int32_t* status);
void HAL_SetAccumulatorDeadband(HAL_AnalogInputHandle analogPortHandle,
int32_t deadband, int32_t* status);
int64_t HAL_GetAccumulatorValue(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
int64_t HAL_GetAccumulatorCount(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
void HAL_GetAccumulatorOutput(HAL_AnalogInputHandle analogPortHandle,
int64_t* value, int64_t* count, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,38 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle handle,
int32_t* status);
void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status);
void HAL_FreeAnalogGyro(HAL_GyroHandle handle);
void HAL_SetAnalogGyroParameters(HAL_GyroHandle handle,
double voltsPerDegreePerSecond, double offset,
int32_t center, int32_t* status);
void HAL_SetAnalogGyroVoltsPerDegreePerSecond(HAL_GyroHandle handle,
double voltsPerDegreePerSecond,
int32_t* status);
void HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status);
void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status);
void HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts,
int32_t* status);
double HAL_GetAnalogGyroAngle(HAL_GyroHandle handle, int32_t* status);
double HAL_GetAnalogGyroRate(HAL_GyroHandle handle, int32_t* status);
double HAL_GetAnalogGyroOffset(HAL_GyroHandle handle, int32_t* status);
int32_t HAL_GetAnalogGyroCenter(HAL_GyroHandle handle, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,50 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle,
int32_t* status);
void HAL_FreeAnalogInputPort(HAL_AnalogInputHandle analogPortHandle);
HAL_Bool HAL_CheckAnalogModule(int32_t module);
HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel);
void HAL_SetAnalogSampleRate(double samplesPerSecond, int32_t* status);
double HAL_GetAnalogSampleRate(int32_t* status);
void HAL_SetAnalogAverageBits(HAL_AnalogInputHandle analogPortHandle,
int32_t bits, int32_t* status);
int32_t HAL_GetAnalogAverageBits(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
void HAL_SetAnalogOversampleBits(HAL_AnalogInputHandle analogPortHandle,
int32_t bits, int32_t* status);
int32_t HAL_GetAnalogOversampleBits(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
int32_t HAL_GetAnalogValue(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
int32_t HAL_GetAnalogAverageValue(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
int32_t HAL_GetAnalogVoltsToValue(HAL_AnalogInputHandle analogPortHandle,
double voltage, int32_t* status);
double HAL_GetAnalogVoltage(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
double HAL_GetAnalogAverageVoltage(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
int32_t HAL_GetAnalogLSBWeight(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
int32_t HAL_GetAnalogOffset(HAL_AnalogInputHandle analogPortHandle,
int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,28 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle,
int32_t* status);
void HAL_FreeAnalogOutputPort(HAL_AnalogOutputHandle analogOutputHandle);
void HAL_SetAnalogOutput(HAL_AnalogOutputHandle analogOutputHandle,
double voltage, int32_t* status);
double HAL_GetAnalogOutput(HAL_AnalogOutputHandle analogOutputHandle,
int32_t* status);
HAL_Bool HAL_CheckAnalogOutputChannel(int32_t channel);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,47 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
enum HAL_AnalogTriggerType : int32_t {
HAL_Trigger_kInWindow = 0,
HAL_Trigger_kState = 1,
HAL_Trigger_kRisingPulse = 2,
HAL_Trigger_kFallingPulse = 3
};
#ifdef __cplusplus
extern "C" {
#endif
HAL_AnalogTriggerHandle HAL_InitializeAnalogTrigger(
HAL_AnalogInputHandle portHandle, int32_t* index, int32_t* status);
void HAL_CleanAnalogTrigger(HAL_AnalogTriggerHandle analogTriggerHandle,
int32_t* status);
void HAL_SetAnalogTriggerLimitsRaw(HAL_AnalogTriggerHandle analogTriggerHandle,
int32_t lower, int32_t upper,
int32_t* status);
void HAL_SetAnalogTriggerLimitsVoltage(
HAL_AnalogTriggerHandle analogTriggerHandle, double lower, double upper,
int32_t* status);
void HAL_SetAnalogTriggerAveraged(HAL_AnalogTriggerHandle analogTriggerHandle,
HAL_Bool useAveragedValue, int32_t* status);
void HAL_SetAnalogTriggerFiltered(HAL_AnalogTriggerHandle analogTriggerHandle,
HAL_Bool useFilteredValue, int32_t* status);
HAL_Bool HAL_GetAnalogTriggerInWindow(
HAL_AnalogTriggerHandle analogTriggerHandle, int32_t* status);
HAL_Bool HAL_GetAnalogTriggerTriggerState(
HAL_AnalogTriggerHandle analogTriggerHandle, int32_t* status);
HAL_Bool HAL_GetAnalogTriggerOutput(HAL_AnalogTriggerHandle analogTriggerHandle,
HAL_AnalogTriggerType type,
int32_t* status);
#ifdef __cplusplus
}
#endif

35
hal/include/HAL/CAN.h Normal file
View File

@@ -0,0 +1,35 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "FRC_NetworkCommunication/CANSessionMux.h"
void canTxSend(uint32_t arbID, uint8_t length,
int32_t period = CAN_SEND_PERIOD_NO_REPEAT);
void canTxPackInt8(uint32_t arbID, uint8_t offset, uint8_t value);
void canTxPackInt16(uint32_t arbID, uint8_t offset, uint16_t value);
void canTxPackInt32(uint32_t arbID, uint8_t offset, uint32_t value);
void canTxPackFXP16(uint32_t arbID, uint8_t offset, double value);
void canTxPackFXP32(uint32_t arbID, uint8_t offset, double value);
uint8_t canTxUnpackInt8(uint32_t arbID, uint8_t offset);
uint32_t canTxUnpackInt32(uint32_t arbID, uint8_t offset);
uint16_t canTxUnpackInt16(uint32_t arbID, uint8_t offset);
double canTxUnpackFXP16(uint32_t arbID, uint8_t offset);
double canTxUnpackFXP32(uint32_t arbID, uint8_t offset);
bool canRxReceive(uint32_t arbID);
uint8_t canRxUnpackInt8(uint32_t arbID, uint8_t offset);
uint16_t canRxUnpackInt16(uint32_t arbID, uint8_t offset);
uint32_t canRxUnpackInt32(uint32_t arbID, uint8_t offset);
double canRxUnpackFXP16(uint32_t arbID, uint8_t offset);
double canRxUnpackFXP32(uint32_t arbID, uint8_t offset);

View File

@@ -1,26 +0,0 @@
#pragma once
#include <stdint.h>
#include "FRC_NetworkCommunication/CANSessionMux.h"
void canTxSend(uint32_t arbID, uint8_t length, int32_t period = CAN_SEND_PERIOD_NO_REPEAT);
void canTxPackInt8 (uint32_t arbID, uint8_t offset, uint8_t value);
void canTxPackInt16(uint32_t arbID, uint8_t offset, uint16_t value);
void canTxPackInt32(uint32_t arbID, uint8_t offset, uint32_t value);
void canTxPackFXP16(uint32_t arbID, uint8_t offset, double value);
void canTxPackFXP32(uint32_t arbID, uint8_t offset, double value);
uint8_t canTxUnpackInt8 (uint32_t arbID, uint8_t offset);
uint32_t canTxUnpackInt32(uint32_t arbID, uint8_t offset);
uint16_t canTxUnpackInt16(uint32_t arbID, uint8_t offset);
double canTxUnpackFXP16(uint32_t arbID, uint8_t offset);
double canTxUnpackFXP32(uint32_t arbID, uint8_t offset);
bool canRxReceive(uint32_t arbID);
uint8_t canRxUnpackInt8 (uint32_t arbID, uint8_t offset);
uint16_t canRxUnpackInt16(uint32_t arbID, uint8_t offset);
uint32_t canRxUnpackInt32(uint32_t arbID, uint8_t offset);
double canRxUnpackFXP16(uint32_t arbID, uint8_t offset);
double canRxUnpackFXP32(uint32_t arbID, uint8_t offset);

View File

@@ -1,829 +0,0 @@
/**
* @brief CAN TALON SRX driver.
*
* The TALON SRX is designed to instrument all runtime signals periodically.
* The default periods are chosen to support 16 TALONs with 10ms update rate
* for control (throttle or setpoint). However these can be overridden with
* SetStatusFrameRate. @see SetStatusFrameRate
* The getters for these unsolicited signals are auto generated at the bottom
* of this module.
*
* Likewise most control signals are sent periodically using the fire-and-forget
* CAN API. The setters for these unsolicited signals are auto generated at the
* bottom of this module.
*
* Signals that are not available in an unsolicited fashion are the Close Loop
* gains. For teams that have a single profile for their TALON close loop they
* can use either the webpage to configure their TALONs once or set the PIDF,
* Izone, CloseLoopRampRate, etc... once in the robot application. These
* parameters are saved to flash so once they are loaded in the TALON, they
* will persist through power cycles and mode changes.
*
* For teams that have one or two profiles to switch between, they can use the
* same strategy since there are two slots to choose from and the
* ProfileSlotSelect is periodically sent in the 10 ms control frame.
*
* For teams that require changing gains frequently, they can use the soliciting
* API to get and set those parameters. Most likely they will only need to set
* them in a periodic fashion as a function of what motion the application is
* attempting. If this API is used, be mindful of the CAN utilization reported
* in the driver station.
*
* If calling application has used the config routines to configure the
* selected feedback sensor, then all positions are measured in floating point
* precision rotations. All sensor velocities are specified in floating point
* precision RPM.
* @see ConfigPotentiometerTurns
* @see ConfigEncoderCodesPerRev
* HOWEVER, if calling application has not called the config routine for
* selected feedback sensor, then all getters/setters for position/velocity use
* the native engineering units of the Talon SRX firm (just like in 2015).
* Signals explained below.
*
* Encoder position is measured in encoder edges. Every edge is counted
* (similar to roboRIO 4X mode). Analog position is 10 bits, meaning 1024
* ticks per rotation (0V => 3.3V). Use SetFeedbackDeviceSelect to select
* which sensor type you need. Once you do that you can use GetSensorPosition()
* and GetSensorVelocity(). These signals are updated on CANBus every 20ms (by
* default). If a relative sensor is selected, you can zero (or change the
* current value) using SetSensorPosition.
*
* Analog Input and quadrature position (and velocity) are also explicitly
* reported in GetEncPosition, GetEncVel, GetAnalogInWithOv, GetAnalogInVel.
* These signals are available all the time, regardless of what sensor is
* selected at a rate of 100ms. This allows easy instrumentation for "in the
* pits" checking of all sensors regardless of modeselect. The 100ms rate is
* overridable for teams who want to acquire sensor data for processing, not
* just instrumentation. Or just select the sensor using
* SetFeedbackDeviceSelect to get it at 20ms.
*
* Velocity is in position ticks / 100ms.
*
* All output units are in respect to duty cycle (throttle) which is -1023(full
* reverse) to +1023 (full forward). This includes demand (which specifies
* duty cycle when in duty cycle mode) and rampRamp, which is in throttle units
* per 10ms (if nonzero).
*
* Pos and velocity close loops are calc'd as
* err = target - posOrVel.
* iErr += err;
* if( (IZone!=0) and abs(err) > IZone)
* ClearIaccum()
* output = P X err + I X iErr + D X dErr + F X target
* dErr = err - lastErr
* P, I, and D gains are always positive. F can be negative.
* Motor direction can be reversed using SetRevMotDuringCloseLoopEn if
* sensor and motor are out of phase. Similarly feedback sensor can also be
* reversed (multiplied by -1) if you prefer the sensor to be inverted.
*
* P gain is specified in throttle per error tick. For example, a value of 102
* is ~9.9% (which is 102/1023) throttle per 1 ADC unit(10bit) or 1 quadrature
* encoder edge depending on selected sensor.
*
* I gain is specified in throttle per integrated error. For example, a value
* of 10 equates to ~0.99% (which is 10/1023) for each accumulated ADC unit
* (10 bit) or 1 quadrature encoder edge depending on selected sensor.
* Close loop and integral accumulator runs every 1ms.
*
* D gain is specified in throttle per derivative error. For example a value of
* 102 equates to ~9.9% (which is 102/1023) per change of 1 unit (ADC or
* encoder) per ms.
*
* I Zone is specified in the same units as sensor position (ADC units or
* quadrature edges). If pos/vel error is outside of this value, the
* integrated error will auto-clear...
* if( (IZone!=0) and abs(err) > IZone)
* ClearIaccum()
* ...this is very useful in preventing integral windup and is highly
* recommended if using full PID to keep stability low.
*
* CloseLoopRampRate is in throttle units per 1ms. Set to zero to disable
* ramping. Works the same as RampThrottle but only is in effect when a close
* loop mode and profile slot is selected.
*
* auto generated using spreadsheet and wpiclassgen.py
* @link https://docs.google.com/spreadsheets/d/1OU_ZV7fZLGYUQ-Uhc8sVAmUmWTlT8XBFYK8lfjg_tac/edit#gid=1766046967
*/
#ifndef CanTalonSRX_H_
#define CanTalonSRX_H_
#include "ctre/ctre.h" //BIT Defines + Typedefs, TALON_Control_6_MotProfAddTrajPoint_t
#include "ctre/CtreCanNode.h"
#include <FRC_NetworkCommunication/CANSessionMux.h> //CAN Comm
#include <map>
#include <atomic>
#include <deque>
#include <mutex>
class CanTalonSRX : public CtreCanNode {
private:
// Use this for determining whether the default move constructor has been
// called; this prevents us from calling the destructor twice.
struct HasBeenMoved {
HasBeenMoved(HasBeenMoved &&other) {
other.moved = true;
moved = false;
}
HasBeenMoved() = default;
std::atomic<bool> moved{false};
operator bool() const { return moved; }
} m_hasBeenMoved;
// Vars for opening a CAN stream if caller needs signals that require
// soliciting
uint32_t _can_h; //!< Session handle for catching response params.
int32_t _can_stat; //!< Session handle status.
struct tCANStreamMessage _msgBuff[20];
static int const kMsgCapacity = 20;
typedef std::map<uint32_t, uint32_t> sigs_t;
// Catches signal updates that are solicited. Expect this to be very few.
sigs_t _sigs;
void OpenSessionIfNeedBe();
void ProcessStreamMessages();
/**
* Called in various places to double check we are using the best control
* frame. If the Talon firmware is too old, use control 1 framing, which
* does not allow setting control signals until robot is enabled. If Talon
* firmware can suport control5, use that since that frame can be
* transmitted during robot-disable. If calling application uses setParam
* to set the signal eLegacyControlMode, caller can force using control1
* if needed for some reason.
*/
void UpdateControlId();
/**
* @return true if Talon is reporting that it supports control5, and therefore
* RIO can send control5 to update control params (even when
* disabled).
*/
bool IsControl5Supported();
/**
* Get a copy of the control frame to send.
* @param [out] pointer to eight byte array to fill.
*/
void GetControlFrameCopy(uint8_t *toFill);
/**
* @return the tx task that transmits Control6 (motion profile control).
* If it's not scheduled, then schedule it. This is part
* of making the lazy-framing that only peforms MotionProf framing
* when needed to save bandwidth.
*/
CtreCanNode::txTask<TALON_Control_6_MotProfAddTrajPoint_t> GetControl6();
/**
* Caller is either pushing a new motion profile point, or is
* calling the Process buffer routine. In either case check our
* flow control to see if we need to start sending control6.
*/
void ReactToMotionProfileCall();
/**
* Update the NextPt signals inside the control frame given the next pt to
* send.
* @param control pointer to the CAN frame payload containing control6. Only
* the signals that serialize the next trajectory point are
* updated from the contents of newPt.
* @param newPt point to the next trajectory that needs to be inserted into
* Talon RAM.
*/
void CopyTrajPtIntoControl(
TALON_Control_6_MotProfAddTrajPoint_t *control,
const TALON_Control_6_MotProfAddTrajPoint_t *newPt);
//---------------------- General Control framing ---------------------------//
/**
* Frame period for control1 or control5, depending on which one we are using.
*/
int _controlPeriodMs = kDefaultControlPeriodMs;
/**
* Frame Period of the motion profile control6 frame.
*/
int _control6PeriodMs = kDefaultControl6PeriodMs;
/**
* When using control5, we still need to send a frame to enable robot. This
* controls the period. This only is used when we are in the control5 state.
* @see ControlFrameSelControl5
*/
int _enablePeriodMs = kDefaultEnablePeriodMs;
/**
* ArbID to use for control frame. Should be either CONTROL_1 or CONTROL_5.
*/
uint32_t _controlFrameArbId;
/**
* Boolean flag to signal calling applications intent to allow using control5
* assuming Talon firmware supports it. This can be cleared to force control1
* framing.
*/
bool _useControl5ifSupported = true;
//--------------------- Buffering Motion Profile ---------------------------//
/**
* Top level Buffer for motion profile trajectory buffering.
* Basically this buffers up the eight byte CAN frame payloads that are
* handshaked into the Talon RAM.
* TODO: Should this be moved into a separate header, and if so where
* logically should it reside?
* TODO: Add compression so that multiple CAN frames can be compressed into
* one exchange.
*/
class TrajectoryBuffer {
public:
void Clear() { _motProfTopBuffer.clear(); }
/**
* push caller's uncompressed simple trajectory point.
*/
void Push(TALON_Control_6_MotProfAddTrajPoint_huff0_t &pt) {
_motProfTopBuffer.push_back(pt);
}
/**
* Get the next trajectory point CAN frame to send.
* Underlying layer may compress the next few points together
* into one control_6 frame.
*/
TALON_Control_6_MotProfAddTrajPoint_t *Front() {
/* TODO : peek ahead and use compression strategies */
_lastFront = _motProfTopBuffer.front();
return (TALON_Control_6_MotProfAddTrajPoint_t *)&_lastFront;
}
void Pop() {
/* TODO : pop multiple points if last front'd point was compressed. */
_motProfTopBuffer.pop_front();
}
unsigned int GetNumTrajectories() { return _motProfTopBuffer.size(); }
bool IsEmpty() { return _motProfTopBuffer.empty(); }
private:
std::deque<TALON_Control_6_MotProfAddTrajPoint_huff0_t> _motProfTopBuffer;
TALON_Control_6_MotProfAddTrajPoint_huff0_t _lastFront;
};
TrajectoryBuffer _motProfTopBuffer;
/**
* To keep buffers from getting out of control, place a cap on the top level
* buffer. Calling application
* can stream addition points as they are fed to Talon.
* Approx memory footprint is this capacity X 8 bytes.
*/
static const int kMotionProfileTopBufferCapacity = 2048;
/**
* Flow control for streaming trajectories.
*/
int32_t _motProfFlowControl = -1;
/**
* Since we may need the MP pts to be emptied into Talon in the background
* make sure the buffering is thread-safe.
*/
std::mutex _mutMotProf;
/**
* Send a one shot frame to set an arbitrary signal.
* Most signals are in the control frame so avoid using this API unless you
* have to.
* Use this api for...
* -A motor controller profile signal eProfileParam_XXXs. These are backed up
* in flash. If you are gain-scheduling then call this periodically.
* -Default brake and limit switch signals... eOnBoot_XXXs. Avoid doing this,
* use the override signals in the control frame.
* Talon will automatically send a PARAM_RESPONSE after the set, so
* GetParamResponse will catch the latest value after a couple ms.
*/
CTR_Code SetParamRaw(uint32_t paramEnum, int32_t rawBits);
/**
* Checks cached CAN frames and updating solicited signals.
*/
CTR_Code GetParamResponseRaw(uint32_t paramEnum, int32_t &rawBits);
public:
// default control update rate is 10ms.
static const int kDefaultControlPeriodMs = 10;
// default enable update rate is 50ms (when using the new control5 frame).
static const int kDefaultEnablePeriodMs = 50;
// Default update rate for motion profile control 6. This only takes effect
// when calling uses MP functions.
static const int kDefaultControl6PeriodMs = 10;
explicit CanTalonSRX(int deviceNumber = 0,
int controlPeriodMs = kDefaultControlPeriodMs,
int enablePeriodMs = kDefaultEnablePeriodMs);
~CanTalonSRX();
void Set(double value);
/* mode select enumerations */
// Demand is 11bit signed duty cycle [-1023,1023].
static const int kMode_DutyCycle = 0;
// Position PIDF.
static const int kMode_PositionCloseLoop = 1;
// Velocity PIDF.
static const int kMode_VelocityCloseLoop = 2;
// Current close loop - not done.
static const int kMode_CurrentCloseLoop = 3;
// Voltage Compensation Mode - not done. Demand is fixed pt target 8.8 volts.
static const int kMode_VoltCompen = 4;
// Demand is the 6 bit Device ID of the 'master' TALON SRX.
static const int kMode_SlaveFollower = 5;
// Demand is '0' (Disabled), '1' (Enabled), or '2' (Hold).
static const int kMode_MotionProfile = 6;
// Zero the output (honors brake/coast) regardless of demand.
// Might be useful if we need to change modes but can't atomically
// change all the signals we want in between.
static const int kMode_NoDrive = 15;
/* limit switch enumerations */
static const int kLimitSwitchOverride_UseDefaultsFromFlash = 1;
static const int kLimitSwitchOverride_DisableFwd_DisableRev = 4;
static const int kLimitSwitchOverride_DisableFwd_EnableRev = 5;
static const int kLimitSwitchOverride_EnableFwd_DisableRev = 6;
static const int kLimitSwitchOverride_EnableFwd_EnableRev = 7;
/* brake override enumerations */
static const int kBrakeOverride_UseDefaultsFromFlash = 0;
static const int kBrakeOverride_OverrideCoast = 1;
static const int kBrakeOverride_OverrideBrake = 2;
/* feedback device enumerations */
static const int kFeedbackDev_DigitalQuadEnc = 0;
static const int kFeedbackDev_AnalogPot = 2;
static const int kFeedbackDev_AnalogEncoder = 3;
static const int kFeedbackDev_CountEveryRisingEdge = 4;
static const int kFeedbackDev_CountEveryFallingEdge = 5;
static const int kFeedbackDev_PosIsPulseWidth = 8;
/* ProfileSlotSelect enumerations*/
static const int kProfileSlotSelect_Slot0 = 0;
static const int kProfileSlotSelect_Slot1 = 1;
/* status frame rate types */
static const int kStatusFrame_General = 0;
static const int kStatusFrame_Feedback = 1;
static const int kStatusFrame_Encoder = 2;
static const int kStatusFrame_AnalogTempVbat = 3;
static const int kStatusFrame_PulseWidthMeas = 4;
static const int kStatusFrame_MotionProfile = 5;
/* Motion Profile status bits */
static const int kMotionProfileFlag_ActTraj_IsValid = 0x1;
static const int kMotionProfileFlag_HasUnderrun = 0x2;
static const int kMotionProfileFlag_IsUnderrun = 0x4;
static const int kMotionProfileFlag_ActTraj_IsLast = 0x8;
static const int kMotionProfileFlag_ActTraj_VelOnly = 0x10;
/* Motion Profile Set Output */
// Motor output is neutral, Motion Profile Executer is not running.
static const int kMotionProf_Disabled = 0;
// Motor output is updated from Motion Profile Executer, MPE will
// process the buffered points.
static const int kMotionProf_Enable = 1;
// Motor output is updated from Motion Profile Executer, MPE will
// stay processing current trajectory point.
static const int kMotionProf_Hold = 2;
/**
* Signal enumeration for generic signal access.
* Although every signal is enumerated, only use this for traffic that must
* be solicited.
* Use the auto generated getters/setters at bottom of this header as much as
* possible.
*/
enum param_t {
eProfileParamSlot0_P = 1,
eProfileParamSlot0_I = 2,
eProfileParamSlot0_D = 3,
eProfileParamSlot0_F = 4,
eProfileParamSlot0_IZone = 5,
eProfileParamSlot0_CloseLoopRampRate = 6,
eProfileParamSlot1_P = 11,
eProfileParamSlot1_I = 12,
eProfileParamSlot1_D = 13,
eProfileParamSlot1_F = 14,
eProfileParamSlot1_IZone = 15,
eProfileParamSlot1_CloseLoopRampRate = 16,
eProfileParamSoftLimitForThreshold = 21,
eProfileParamSoftLimitRevThreshold = 22,
eProfileParamSoftLimitForEnable = 23,
eProfileParamSoftLimitRevEnable = 24,
eOnBoot_BrakeMode = 31,
eOnBoot_LimitSwitch_Forward_NormallyClosed = 32,
eOnBoot_LimitSwitch_Reverse_NormallyClosed = 33,
eOnBoot_LimitSwitch_Forward_Disable = 34,
eOnBoot_LimitSwitch_Reverse_Disable = 35,
eFault_OverTemp = 41,
eFault_UnderVoltage = 42,
eFault_ForLim = 43,
eFault_RevLim = 44,
eFault_HardwareFailure = 45,
eFault_ForSoftLim = 46,
eFault_RevSoftLim = 47,
eStckyFault_OverTemp = 48,
eStckyFault_UnderVoltage = 49,
eStckyFault_ForLim = 50,
eStckyFault_RevLim = 51,
eStckyFault_ForSoftLim = 52,
eStckyFault_RevSoftLim = 53,
eAppliedThrottle = 61,
eCloseLoopErr = 62,
eFeedbackDeviceSelect = 63,
eRevMotDuringCloseLoopEn = 64,
eModeSelect = 65,
eProfileSlotSelect = 66,
eRampThrottle = 67,
eRevFeedbackSensor = 68,
eLimitSwitchEn = 69,
eLimitSwitchClosedFor = 70,
eLimitSwitchClosedRev = 71,
eSensorPosition = 73,
eSensorVelocity = 74,
eCurrent = 75,
eBrakeIsEnabled = 76,
eEncPosition = 77,
eEncVel = 78,
eEncIndexRiseEvents = 79,
eQuadApin = 80,
eQuadBpin = 81,
eQuadIdxpin = 82,
eAnalogInWithOv = 83,
eAnalogInVel = 84,
eTemp = 85,
eBatteryV = 86,
eResetCount = 87,
eResetFlags = 88,
eFirmVers = 89,
eSettingsChanged = 90,
eQuadFilterEn = 91,
ePidIaccum = 93,
eStatus1FrameRate = 94, // TALON_Status_1_General_10ms_t
eStatus2FrameRate = 95, // TALON_Status_2_Feedback_20ms_t
eStatus3FrameRate = 96, // TALON_Status_3_Enc_100ms_t
eStatus4FrameRate = 97, // TALON_Status_4_AinTempVbat_100ms_t
eStatus6FrameRate = 98, // TALON_Status_6_Eol_t
eStatus7FrameRate = 99, // TALON_Status_7_Debug_200ms_t
eClearPositionOnIdx = 100,
// reserved,
// reserved,
// reserved,
ePeakPosOutput = 104,
eNominalPosOutput = 105,
ePeakNegOutput = 106,
eNominalNegOutput = 107,
eQuadIdxPolarity = 108,
eStatus8FrameRate = 109, // TALON_Status_8_PulseWid_100ms_t
eAllowPosOverflow = 110,
eProfileParamSlot0_AllowableClosedLoopErr = 111,
eNumberPotTurns = 112,
eNumberEncoderCPR = 113,
ePwdPosition = 114,
eAinPosition = 115,
eProfileParamVcompRate = 116,
eProfileParamSlot1_AllowableClosedLoopErr = 117,
eStatus9FrameRate = 118, // TALON_Status_9_MotProfBuffer_100ms_t
eMotionProfileHasUnderrunErr = 119,
eReserved120 = 120,
eLegacyControlMode = 121,
};
//---- setters and getters that use the solicated param request/response ---//
/**
* Send a one shot frame to set an arbitrary signal.
* Most signals are in the control frame so avoid using this API unless you
* have to.
* Use this api for...
* -A motor controller profile signal eProfileParam_XXXs. These are backed
* up in flash. If you are gain-scheduling then call this periodically.
* -Default brake and limit switch signals... eOnBoot_XXXs. Avoid doing
* this, use the override signals in the control frame.
* Talon will automatically send a PARAM_RESPONSE after the set, so
* GetParamResponse will catch the latest value after a couple ms.
*/
CTR_Code SetParam(param_t paramEnum, double value);
/**
* Asks TALON to immedietely respond with signal value. This API is only used
* for signals that are not sent periodically.
* This can be useful for reading params that rarely change like Limit Switch
* settings and PIDF values.
* @param param to request.
*/
CTR_Code RequestParam(param_t paramEnum);
CTR_Code GetParamResponse(param_t paramEnum, double &value);
CTR_Code GetParamResponseInt32(param_t paramEnum, int &value);
//----------- getters and setters that use param request/response ----------//
/**
* These signals are backed up in flash and will survive a power cycle.
* If your application requires changing these values consider using both
* slots and switch between slot0 <=> slot1.
* If your application requires changing these signals frequently then it
* makes sense to leverage this API.
* Getters don't block, so it may require several calls to get the latest
* value.
*/
CTR_Code SetPgain(unsigned slotIdx, double gain);
CTR_Code SetIgain(unsigned slotIdx, double gain);
CTR_Code SetDgain(unsigned slotIdx, double gain);
CTR_Code SetFgain(unsigned slotIdx, double gain);
CTR_Code SetIzone(unsigned slotIdx, int zone);
CTR_Code SetCloseLoopRampRate(unsigned slotIdx, int closeLoopRampRate);
CTR_Code SetVoltageCompensationRate(double voltagePerMs);
CTR_Code SetSensorPosition(int pos);
CTR_Code SetForwardSoftLimit(int forwardLimit);
CTR_Code SetReverseSoftLimit(int reverseLimit);
CTR_Code SetForwardSoftEnable(int enable);
CTR_Code SetReverseSoftEnable(int enable);
CTR_Code GetPgain(unsigned slotIdx, double &gain);
CTR_Code GetIgain(unsigned slotIdx, double &gain);
CTR_Code GetDgain(unsigned slotIdx, double &gain);
CTR_Code GetFgain(unsigned slotIdx, double &gain);
CTR_Code GetIzone(unsigned slotIdx, int &zone);
CTR_Code GetCloseLoopRampRate(unsigned slotIdx, int &closeLoopRampRate);
CTR_Code GetVoltageCompensationRate(double &voltagePerMs);
CTR_Code GetForwardSoftLimit(int &forwardLimit);
CTR_Code GetReverseSoftLimit(int &reverseLimit);
CTR_Code GetForwardSoftEnable(int &enable);
CTR_Code GetReverseSoftEnable(int &enable);
CTR_Code GetPulseWidthRiseToFallUs(int &param);
CTR_Code IsPulseWidthSensorPresent(int &param);
CTR_Code SetModeSelect(int modeSelect, int demand);
/**
* Change the periodMs of a TALON's status frame. See kStatusFrame_* enums
* for what's available.
*/
CTR_Code SetStatusFrameRate(unsigned frameEnum, unsigned periodMs);
/**
* Clear all sticky faults in TALON.
*/
CTR_Code ClearStickyFaults();
/**
* Calling application can opt to speed up the handshaking between the robot
* API and the Talon to increase the
* download rate of the Talon's Motion Profile. Ideally the period should be
* no more than half the period
* of a trajectory point.
*/
void ChangeMotionControlFramePeriod(uint32_t periodMs);
/**
* Clear the buffered motion profile in both Talon RAM (bottom), and in the
* API (top).
*/
void ClearMotionProfileTrajectories();
/**
* Retrieve just the buffer count for the api-level (top) buffer.
* This routine performs no CAN or data structure lookups, so its fast and
* ideal if caller needs to quickly poll the progress of trajectory points
* being emptied into Talon's RAM. Otherwise just use GetMotionProfileStatus.
* @return number of trajectory points in the top buffer.
*/
uint32_t GetMotionProfileTopLevelBufferCount();
/**
* Retrieve just the buffer full for the api-level (top) buffer.
* This routine performs no CAN or data structure lookups, so its fast and
* ideal if caller needs to quickly poll. Otherwise just use
* GetMotionProfileStatus.
* @return number of trajectory points in the top buffer.
*/
bool IsMotionProfileTopLevelBufferFull();
/**
* Push another trajectory point into the top level buffer (which is emptied
* into the Talon's bottom buffer as room allows).
* @param targPos servo position in native Talon units (sensor units).
* @param targVel velocity to feed-forward in native Talon units (sensor
* units per 100ms).
* @param profileSlotSelect which slot to pull PIDF gains from. Currently
* supports 0 or 1.
* @param timeDurMs time in milliseconds of how long to apply this point.
* @param velOnly set to nonzero to signal Talon that only the feed-foward
* velocity should be used, i.e. do not perform PID on
* position. This is equivalent to setting PID gains to zero,
* but much more efficient and synchronized to MP.
* @param isLastPoint set to nonzero to signal Talon to keep processing this
* trajectory point, instead of jumping to the next one
* when timeDurMs expires. Otherwise MP executer will
* eventually see an empty buffer after the last point
* expires, causing it to assert the IsUnderRun flag.
* However this may be desired if calling application
* nevers wants to terminate the MP.
* @param zeroPos set to nonzero to signal Talon to "zero" the selected
* position sensor before executing this trajectory point.
* Typically the first point should have this set only thus
* allowing the remainder of the MP positions to be relative
* to zero.
* @return CTR_OKAY if trajectory point push ok. CTR_BufferFull if buffer is
* full due to kMotionProfileTopBufferCapacity.
*/
CTR_Code PushMotionProfileTrajectory(int targPos, int targVel,
int profileSlotSelect, int timeDurMs,
int velOnly, int isLastPoint,
int zeroPos);
/**
* This must be called periodically to funnel the trajectory points from the
* API's top level buffer to the Talon's bottom level buffer. Recommendation
* is to call this twice as fast as the executation rate of the motion
* profile. So if MP is running with 20ms trajectory points, try calling
* this routine every 10ms. All motion profile functions are thread-safe
* through the use of a mutex, so there is no harm in having the caller
* utilize threading.
*/
void ProcessMotionProfileBuffer();
/**
* Retrieve all status information.
* Since this all comes from one CAN frame, its ideal to have one routine to
* retrieve the frame once and decode everything.
* @param [out] flags bitfield for status bools. Starting with least
* significant bit: IsValid, HasUnderrun, IsUnderrun, IsLast, VelOnly.
*
* IsValid set when MP executer is processing a trajectory point,
* and that point's status is instrumented with IsLast,
* VelOnly, targPos, targVel. However if MP executor is
* not processing a trajectory point, then this flag is
* false, and the instrumented signals will be zero.
* HasUnderrun is set anytime the MP executer is ready to pop
* another trajectory point from the Talon's RAM,
* but the buffer is empty. It can only be cleared
* by using SetParam(eMotionProfileHasUnderrunErr,0);
* IsUnderrun is set when the MP executer is ready for another
* point, but the buffer is empty, and cleared when
* the MP executer does not need another point.
* HasUnderrun shadows this registor when this
* register gets set, however HasUnderrun stays
* asserted until application has process it, and
* IsUnderrun auto-clears when the condition is
* resolved.
* IsLast is set/cleared based on the MP executer's current
* trajectory point's IsLast value. This assumes
* IsLast was set when PushMotionProfileTrajectory
* was used to insert the currently processed trajectory
* point.
* VelOnly is set/cleared based on the MP executer's current
* trajectory point's VelOnly value.
*
* @param [out] profileSlotSelect The currently processed trajectory point's
* selected slot. This can differ in the currently selected slot used
* for Position and Velocity servo modes.
* @param [out] targPos The currently processed trajectory point's position
* in native units. This param is zero if IsValid is zero.
* @param [out] targVel The currently processed trajectory point's velocity
* in native units. This param is zero if IsValid is zero.
* @param [out] topBufferRem The remaining number of points in the top level
* buffer.
* @param [out] topBufferCnt The number of points in the top level buffer to
* be sent to Talon.
* @param [out] btmBufferCnt The number of points in the bottom level buffer
* inside Talon.
* @return CTR error code
*/
CTR_Code GetMotionProfileStatus(uint32_t &flags, uint32_t &profileSlotSelect,
int32_t &targPos, int32_t &targVel,
uint32_t &topBufferRemaining,
uint32_t &topBufferCnt,
uint32_t &btmBufferCnt,
uint32_t &outputEnable);
//------------------------ auto generated ------------------------------------//
/* This API is optimal since it uses the fire-and-forget CAN interface.
* These signals should cover the majority of all use cases.
*/
CTR_Code GetFault_OverTemp(int &param);
CTR_Code GetFault_UnderVoltage(int &param);
CTR_Code GetFault_ForLim(int &param);
CTR_Code GetFault_RevLim(int &param);
CTR_Code GetFault_HardwareFailure(int &param);
CTR_Code GetFault_ForSoftLim(int &param);
CTR_Code GetFault_RevSoftLim(int &param);
CTR_Code GetStckyFault_OverTemp(int &param);
CTR_Code GetStckyFault_UnderVoltage(int &param);
CTR_Code GetStckyFault_ForLim(int &param);
CTR_Code GetStckyFault_RevLim(int &param);
CTR_Code GetStckyFault_ForSoftLim(int &param);
CTR_Code GetStckyFault_RevSoftLim(int &param);
CTR_Code GetAppliedThrottle(int &param);
CTR_Code GetCloseLoopErr(int &param);
CTR_Code GetFeedbackDeviceSelect(int &param);
CTR_Code GetModeSelect(int &param);
CTR_Code GetLimitSwitchEn(int &param);
CTR_Code GetLimitSwitchClosedFor(int &param);
CTR_Code GetLimitSwitchClosedRev(int &param);
CTR_Code GetSensorPosition(int &param);
CTR_Code GetSensorVelocity(int &param);
CTR_Code GetCurrent(double &param);
CTR_Code GetBrakeIsEnabled(int &param);
CTR_Code GetEncPosition(int &param);
CTR_Code GetEncVel(int &param);
CTR_Code GetEncIndexRiseEvents(int &param);
CTR_Code GetQuadApin(int &param);
CTR_Code GetQuadBpin(int &param);
CTR_Code GetQuadIdxpin(int &param);
CTR_Code GetAnalogInWithOv(int &param);
CTR_Code GetAnalogInVel(int &param);
CTR_Code GetTemp(double &param);
CTR_Code GetBatteryV(double &param);
CTR_Code GetResetCount(int &param);
CTR_Code GetResetFlags(int &param);
CTR_Code GetFirmVers(int &param);
CTR_Code GetPulseWidthPosition(int &param);
CTR_Code GetPulseWidthVelocity(int &param);
CTR_Code GetPulseWidthRiseToRiseUs(int &param);
CTR_Code GetActTraj_IsValid(int &param);
CTR_Code GetActTraj_ProfileSlotSelect(int &param);
CTR_Code GetActTraj_VelOnly(int &param);
CTR_Code GetActTraj_IsLast(int &param);
CTR_Code GetOutputType(int &param);
CTR_Code GetHasUnderrun(int &param);
CTR_Code GetIsUnderrun(int &param);
CTR_Code GetNextID(int &param);
CTR_Code GetBufferIsFull(int &param);
CTR_Code GetCount(int &param);
CTR_Code GetActTraj_Velocity(int &param);
CTR_Code GetActTraj_Position(int &param);
CTR_Code SetDemand(int param);
CTR_Code SetOverrideLimitSwitchEn(int param);
CTR_Code SetFeedbackDeviceSelect(int param);
CTR_Code SetRevMotDuringCloseLoopEn(int param);
CTR_Code SetOverrideBrakeType(int param);
CTR_Code SetModeSelect(int param);
CTR_Code SetProfileSlotSelect(int param);
CTR_Code SetRampThrottle(int param);
CTR_Code SetRevFeedbackSensor(int param);
};
extern "C" {
void *c_TalonSRX_Create3(int deviceNumber, int controlPeriodMs, int enablePeriodMs);
void *c_TalonSRX_Create2(int deviceNumber, int controlPeriodMs);
void *c_TalonSRX_Create1(int deviceNumber);
void c_TalonSRX_Destroy(void *handle);
void c_TalonSRX_Set(void *handle, double value);
CTR_Code c_TalonSRX_SetParam(void *handle, int paramEnum, double value);
CTR_Code c_TalonSRX_RequestParam(void *handle, int paramEnum);
CTR_Code c_TalonSRX_GetParamResponse(void *handle, int paramEnum, double *value);
CTR_Code c_TalonSRX_GetParamResponseInt32(void *handle, int paramEnum, int *value);
CTR_Code c_TalonSRX_SetPgain(void *handle, int slotIdx, double gain);
CTR_Code c_TalonSRX_SetIgain(void *handle, int slotIdx, double gain);
CTR_Code c_TalonSRX_SetDgain(void *handle, int slotIdx, double gain);
CTR_Code c_TalonSRX_SetFgain(void *handle, int slotIdx, double gain);
CTR_Code c_TalonSRX_SetIzone(void *handle, int slotIdx, int zone);
CTR_Code c_TalonSRX_SetCloseLoopRampRate(void *handle, int slotIdx, int closeLoopRampRate);
CTR_Code c_TalonSRX_SetVoltageCompensationRate(void *handle, double voltagePerMs);
CTR_Code c_TalonSRX_SetSensorPosition(void *handle, int pos);
CTR_Code c_TalonSRX_SetForwardSoftLimit(void *handle, int forwardLimit);
CTR_Code c_TalonSRX_SetReverseSoftLimit(void *handle, int reverseLimit);
CTR_Code c_TalonSRX_SetForwardSoftEnable(void *handle, int enable);
CTR_Code c_TalonSRX_SetReverseSoftEnable(void *handle, int enable);
CTR_Code c_TalonSRX_GetPgain(void *handle, int slotIdx, double *gain);
CTR_Code c_TalonSRX_GetIgain(void *handle, int slotIdx, double *gain);
CTR_Code c_TalonSRX_GetDgain(void *handle, int slotIdx, double *gain);
CTR_Code c_TalonSRX_GetFgain(void *handle, int slotIdx, double *gain);
CTR_Code c_TalonSRX_GetIzone(void *handle, int slotIdx, int *zone);
CTR_Code c_TalonSRX_GetCloseLoopRampRate(void *handle, int slotIdx, int *closeLoopRampRate);
CTR_Code c_TalonSRX_GetVoltageCompensationRate(void *handle, double *voltagePerMs);
CTR_Code c_TalonSRX_GetForwardSoftLimit(void *handle, int *forwardLimit);
CTR_Code c_TalonSRX_GetReverseSoftLimit(void *handle, int *reverseLimit);
CTR_Code c_TalonSRX_GetForwardSoftEnable(void *handle, int *enable);
CTR_Code c_TalonSRX_GetReverseSoftEnable(void *handle, int *enable);
CTR_Code c_TalonSRX_GetPulseWidthRiseToFallUs(void *handle, int *param);
CTR_Code c_TalonSRX_IsPulseWidthSensorPresent(void *handle, int *param);
CTR_Code c_TalonSRX_SetModeSelect2(void *handle, int modeSelect, int demand);
CTR_Code c_TalonSRX_SetStatusFrameRate(void *handle, int frameEnum, int periodMs);
CTR_Code c_TalonSRX_ClearStickyFaults(void *handle);
void c_TalonSRX_ChangeMotionControlFramePeriod(void *handle, int periodMs);
void c_TalonSRX_ClearMotionProfileTrajectories(void *handle);
int c_TalonSRX_GetMotionProfileTopLevelBufferCount(void *handle);
int c_TalonSRX_IsMotionProfileTopLevelBufferFull(void *handle);
CTR_Code c_TalonSRX_PushMotionProfileTrajectory(void *handle, int targPos, int targVel, int profileSlotSelect, int timeDurMs, int velOnly, int isLastPoint, int zeroPos);
void c_TalonSRX_ProcessMotionProfileBuffer(void *handle);
CTR_Code c_TalonSRX_GetMotionProfileStatus(void *handle, int *flags, int *profileSlotSelect, int *targPos, int *targVel, int *topBufferRemaining, int *topBufferCnt, int *btmBufferCnt, int *outputEnable);
CTR_Code c_TalonSRX_GetFault_OverTemp(void *handle, int *param);
CTR_Code c_TalonSRX_GetFault_UnderVoltage(void *handle, int *param);
CTR_Code c_TalonSRX_GetFault_ForLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetFault_RevLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetFault_HardwareFailure(void *handle, int *param);
CTR_Code c_TalonSRX_GetFault_ForSoftLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetFault_RevSoftLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetStckyFault_OverTemp(void *handle, int *param);
CTR_Code c_TalonSRX_GetStckyFault_UnderVoltage(void *handle, int *param);
CTR_Code c_TalonSRX_GetStckyFault_ForLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetStckyFault_RevLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetStckyFault_ForSoftLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetStckyFault_RevSoftLim(void *handle, int *param);
CTR_Code c_TalonSRX_GetAppliedThrottle(void *handle, int *param);
CTR_Code c_TalonSRX_GetCloseLoopErr(void *handle, int *param);
CTR_Code c_TalonSRX_GetFeedbackDeviceSelect(void *handle, int *param);
CTR_Code c_TalonSRX_GetModeSelect(void *handle, int *param);
CTR_Code c_TalonSRX_GetLimitSwitchEn(void *handle, int *param);
CTR_Code c_TalonSRX_GetLimitSwitchClosedFor(void *handle, int *param);
CTR_Code c_TalonSRX_GetLimitSwitchClosedRev(void *handle, int *param);
CTR_Code c_TalonSRX_GetSensorPosition(void *handle, int *param);
CTR_Code c_TalonSRX_GetSensorVelocity(void *handle, int *param);
CTR_Code c_TalonSRX_GetCurrent(void *handle, double *param);
CTR_Code c_TalonSRX_GetBrakeIsEnabled(void *handle, int *param);
CTR_Code c_TalonSRX_GetEncPosition(void *handle, int *param);
CTR_Code c_TalonSRX_GetEncVel(void *handle, int *param);
CTR_Code c_TalonSRX_GetEncIndexRiseEvents(void *handle, int *param);
CTR_Code c_TalonSRX_GetQuadApin(void *handle, int *param);
CTR_Code c_TalonSRX_GetQuadBpin(void *handle, int *param);
CTR_Code c_TalonSRX_GetQuadIdxpin(void *handle, int *param);
CTR_Code c_TalonSRX_GetAnalogInWithOv(void *handle, int *param);
CTR_Code c_TalonSRX_GetAnalogInVel(void *handle, int *param);
CTR_Code c_TalonSRX_GetTemp(void *handle, double *param);
CTR_Code c_TalonSRX_GetBatteryV(void *handle, double *param);
CTR_Code c_TalonSRX_GetResetCount(void *handle, int *param);
CTR_Code c_TalonSRX_GetResetFlags(void *handle, int *param);
CTR_Code c_TalonSRX_GetFirmVers(void *handle, int *param);
CTR_Code c_TalonSRX_GetPulseWidthPosition(void *handle, int *param);
CTR_Code c_TalonSRX_GetPulseWidthVelocity(void *handle, int *param);
CTR_Code c_TalonSRX_GetPulseWidthRiseToRiseUs(void *handle, int *param);
CTR_Code c_TalonSRX_GetActTraj_IsValid(void *handle, int *param);
CTR_Code c_TalonSRX_GetActTraj_ProfileSlotSelect(void *handle, int *param);
CTR_Code c_TalonSRX_GetActTraj_VelOnly(void *handle, int *param);
CTR_Code c_TalonSRX_GetActTraj_IsLast(void *handle, int *param);
CTR_Code c_TalonSRX_GetOutputType(void *handle, int *param);
CTR_Code c_TalonSRX_GetHasUnderrun(void *handle, int *param);
CTR_Code c_TalonSRX_GetIsUnderrun(void *handle, int *param);
CTR_Code c_TalonSRX_GetNextID(void *handle, int *param);
CTR_Code c_TalonSRX_GetBufferIsFull(void *handle, int *param);
CTR_Code c_TalonSRX_GetCount(void *handle, int *param);
CTR_Code c_TalonSRX_GetActTraj_Velocity(void *handle, int *param);
CTR_Code c_TalonSRX_GetActTraj_Position(void *handle, int *param);
CTR_Code c_TalonSRX_SetDemand(void *handle, int param);
CTR_Code c_TalonSRX_SetOverrideLimitSwitchEn(void *handle, int param);
CTR_Code c_TalonSRX_SetFeedbackDeviceSelect(void *handle, int param);
CTR_Code c_TalonSRX_SetRevMotDuringCloseLoopEn(void *handle, int param);
CTR_Code c_TalonSRX_SetOverrideBrakeType(void *handle, int param);
CTR_Code c_TalonSRX_SetModeSelect(void *handle, int param);
CTR_Code c_TalonSRX_SetProfileSlotSelect(void *handle, int param);
CTR_Code c_TalonSRX_SetRampThrottle(void *handle, int param);
CTR_Code c_TalonSRX_SetRevFeedbackSensor(void *handle, int param);
}
#endif

View File

@@ -1,5 +1,5 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Copyright (c) FIRST 2008-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
@@ -13,19 +13,13 @@
#include <stdint.h>
#include "FRC_FPGA_ChipObject/RoboRIO_FRC_ChipObject_Aliases.h"
#include "FRC_FPGA_ChipObject/tDMAChannelDescriptor.h"
#include "FRC_FPGA_ChipObject/tDMAManager.h"
#include "FRC_FPGA_ChipObject/tInterruptManager.h"
#include "FRC_FPGA_ChipObject/tSystem.h"
#include "FRC_FPGA_ChipObject/tSystemInterface.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/nInterfaceGlobals.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAI.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAO.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAccel.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAccumulator.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAI.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAlarm.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAnalogTrigger.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tAO.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tBIST.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tCounter.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tDIO.h"
@@ -33,13 +27,20 @@
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tEncoder.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tGlobal.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tInterrupt.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tPower.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tPWM.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tPower.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tRelay.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tSPI.h"
#include "FRC_FPGA_ChipObject/nRoboRIO_FPGANamespace/tSysWatchdog.h"
#include "FRC_FPGA_ChipObject/tDMAChannelDescriptor.h"
#include "FRC_FPGA_ChipObject/tDMAManager.h"
#include "FRC_FPGA_ChipObject/tInterruptManager.h"
#include "FRC_FPGA_ChipObject/tSystem.h"
#include "FRC_FPGA_ChipObject/tSystemInterface.h"
// FIXME: these should not be here!
namespace hal {
using namespace nFPGA;
using namespace nRoboRIO_FPGANamespace;
} // namespace hal
#pragma GCC diagnostic pop

View File

@@ -0,0 +1,48 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_CompressorHandle HAL_InitializeCompressor(int32_t module, int32_t* status);
HAL_Bool HAL_CheckCompressorModule(int32_t module);
HAL_Bool HAL_GetCompressor(HAL_CompressorHandle compressorHandle,
int32_t* status);
void HAL_SetCompressorClosedLoopControl(HAL_CompressorHandle compressorHandle,
HAL_Bool value, int32_t* status);
HAL_Bool HAL_GetCompressorClosedLoopControl(
HAL_CompressorHandle compressorHandle, int32_t* status);
HAL_Bool HAL_GetCompressorPressureSwitch(HAL_CompressorHandle compressorHandle,
int32_t* status);
double HAL_GetCompressorCurrent(HAL_CompressorHandle compressorHandle,
int32_t* status);
HAL_Bool HAL_GetCompressorCurrentTooHighFault(
HAL_CompressorHandle compressorHandle, int32_t* status);
HAL_Bool HAL_GetCompressorCurrentTooHighStickyFault(
HAL_CompressorHandle compressorHandle, int32_t* status);
HAL_Bool HAL_GetCompressorShortedStickyFault(
HAL_CompressorHandle compressorHandle, int32_t* status);
HAL_Bool HAL_GetCompressorShortedFault(HAL_CompressorHandle compressorHandle,
int32_t* status);
HAL_Bool HAL_GetCompressorNotConnectedStickyFault(
HAL_CompressorHandle compressorHandle, int32_t* status);
HAL_Bool HAL_GetCompressorNotConnectedFault(
HAL_CompressorHandle compressorHandle, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,33 +0,0 @@
/**
* Compressor.h
* Methods for interacting with a compressor with the CAN PCM device
*/
#include <stdint.h>
#ifndef __HAL_COMPRESSOR_H__
#define __HAL_COMPRESSOR_H__
extern "C" {
void *initializeCompressor(uint8_t module);
bool checkCompressorModule(uint8_t module);
bool getCompressor(void *pcm_pointer, int32_t *status);
void setClosedLoopControl(void *pcm_pointer, bool value, int32_t *status);
bool getClosedLoopControl(void *pcm_pointer, int32_t *status);
bool getPressureSwitch(void *pcm_pointer, int32_t *status);
float getCompressorCurrent(void *pcm_pointer, int32_t *status);
bool getCompressorCurrentTooHighFault(void *pcm_pointer, int32_t *status);
bool getCompressorCurrentTooHighStickyFault(void *pcm_pointer, int32_t *status);
bool getCompressorShortedStickyFault(void *pcm_pointer, int32_t *status);
bool getCompressorShortedFault(void *pcm_pointer, int32_t *status);
bool getCompressorNotConnectedStickyFault(void *pcm_pointer, int32_t *status);
bool getCompressorNotConnectedFault(void *pcm_pointer, int32_t *status);
void clearAllPCMStickyFaults(void *pcm_pointer, int32_t *status);
}
#endif

View File

@@ -0,0 +1,19 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HAL_GetSystemClockTicksPerMicrosecond(void);
#ifdef __cplusplus
}
#endif

73
hal/include/HAL/Counter.h Normal file
View File

@@ -0,0 +1,73 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/AnalogTrigger.h"
#include "HAL/Types.h"
enum HAL_Counter_Mode : int32_t {
HAL_Counter_kTwoPulse = 0,
HAL_Counter_kSemiperiod = 1,
HAL_Counter_kPulseLength = 2,
HAL_Counter_kExternalDirection = 3
};
#ifdef __cplusplus
extern "C" {
#endif
HAL_CounterHandle HAL_InitializeCounter(HAL_Counter_Mode mode, int32_t* index,
int32_t* status);
void HAL_FreeCounter(HAL_CounterHandle counterHandle, int32_t* status);
void HAL_SetCounterAverageSize(HAL_CounterHandle counterHandle, int32_t size,
int32_t* status);
void HAL_SetCounterUpSource(HAL_CounterHandle counterHandle,
HAL_Handle digitalSourceHandle,
HAL_AnalogTriggerType analogTriggerType,
int32_t* status);
void HAL_SetCounterUpSourceEdge(HAL_CounterHandle counterHandle,
HAL_Bool risingEdge, HAL_Bool fallingEdge,
int32_t* status);
void HAL_ClearCounterUpSource(HAL_CounterHandle counterHandle, int32_t* status);
void HAL_SetCounterDownSource(HAL_CounterHandle counterHandle,
HAL_Handle digitalSourceHandle,
HAL_AnalogTriggerType analogTriggerType,
int32_t* status);
void HAL_SetCounterDownSourceEdge(HAL_CounterHandle counterHandle,
HAL_Bool risingEdge, HAL_Bool fallingEdge,
int32_t* status);
void HAL_ClearCounterDownSource(HAL_CounterHandle counterHandle,
int32_t* status);
void HAL_SetCounterUpDownMode(HAL_CounterHandle counterHandle, int32_t* status);
void HAL_SetCounterExternalDirectionMode(HAL_CounterHandle counterHandle,
int32_t* status);
void HAL_SetCounterSemiPeriodMode(HAL_CounterHandle counterHandle,
HAL_Bool highSemiPeriod, int32_t* status);
void HAL_SetCounterPulseLengthMode(HAL_CounterHandle counterHandle,
double threshold, int32_t* status);
int32_t HAL_GetCounterSamplesToAverage(HAL_CounterHandle counterHandle,
int32_t* status);
void HAL_SetCounterSamplesToAverage(HAL_CounterHandle counterHandle,
int32_t samplesToAverage, int32_t* status);
void HAL_ResetCounter(HAL_CounterHandle counterHandle, int32_t* status);
int32_t HAL_GetCounter(HAL_CounterHandle counterHandle, int32_t* status);
double HAL_GetCounterPeriod(HAL_CounterHandle counterHandle, int32_t* status);
void HAL_SetCounterMaxPeriod(HAL_CounterHandle counterHandle, double maxPeriod,
int32_t* status);
void HAL_SetCounterUpdateWhenEmpty(HAL_CounterHandle counterHandle,
HAL_Bool enabled, int32_t* status);
HAL_Bool HAL_GetCounterStopped(HAL_CounterHandle counterHandle,
int32_t* status);
HAL_Bool HAL_GetCounterDirection(HAL_CounterHandle counterHandle,
int32_t* status);
void HAL_SetCounterReverseDirection(HAL_CounterHandle counterHandle,
HAL_Bool reverseDirection, int32_t* status);
#ifdef __cplusplus
}
#endif

45
hal/include/HAL/DIO.h Normal file
View File

@@ -0,0 +1,45 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle,
HAL_Bool input, int32_t* status);
HAL_Bool HAL_CheckDIOChannel(int32_t channel);
void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle);
HAL_DigitalPWMHandle HAL_AllocateDigitalPWM(int32_t* status);
void HAL_FreeDigitalPWM(HAL_DigitalPWMHandle pwmGenerator, int32_t* status);
void HAL_SetDigitalPWMRate(double rate, int32_t* status);
void HAL_SetDigitalPWMDutyCycle(HAL_DigitalPWMHandle pwmGenerator,
double dutyCycle, int32_t* status);
void HAL_SetDigitalPWMOutputChannel(HAL_DigitalPWMHandle pwmGenerator,
int32_t channel, int32_t* status);
void HAL_SetDIO(HAL_DigitalHandle dioPortHandle, HAL_Bool value,
int32_t* status);
HAL_Bool HAL_GetDIO(HAL_DigitalHandle dioPortHandle, int32_t* status);
HAL_Bool HAL_GetDIODirection(HAL_DigitalHandle dioPortHandle, int32_t* status);
void HAL_Pulse(HAL_DigitalHandle dioPortHandle, double pulseLength,
int32_t* status);
HAL_Bool HAL_IsPulsing(HAL_DigitalHandle dioPortHandle, int32_t* status);
HAL_Bool HAL_IsAnyPulsing(int32_t* status);
void HAL_SetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t filterIndex,
int32_t* status);
int32_t HAL_GetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t* status);
void HAL_SetFilterPeriod(int32_t filterIndex, int64_t value, int32_t* status);
int64_t HAL_GetFilterPeriod(int32_t filterIndex, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,139 +0,0 @@
#pragma once
#include <stdint.h>
#include "HAL/cpp/priority_mutex.h"
enum Mode
{
kTwoPulse = 0,
kSemiperiod = 1,
kPulseLength = 2,
kExternalDirection = 3
};
priority_recursive_mutex& spiGetSemaphore(uint8_t port);
extern "C"
{
void* initializeDigitalPort(void* port_pointer, int32_t *status);
void freeDigitalPort(void* digital_port_pointer);
bool checkPWMChannel(void* digital_port_pointer);
bool checkRelayChannel(void* digital_port_pointer);
void setPWM(void* digital_port_pointer, unsigned short value, int32_t *status);
bool allocatePWMChannel(void* digital_port_pointer, int32_t *status);
void freePWMChannel(void* digital_port_pointer, int32_t *status);
unsigned short getPWM(void* digital_port_pointer, int32_t *status);
void latchPWMZero(void* digital_port_pointer, int32_t *status);
void setPWMPeriodScale(void* digital_port_pointer, uint32_t squelchMask, int32_t *status);
void* allocatePWM(int32_t *status);
void freePWM(void* pwmGenerator, int32_t *status);
void setPWMRate(double rate, int32_t *status);
void setPWMDutyCycle(void* pwmGenerator, double dutyCycle, int32_t *status);
void setPWMOutputChannel(void* pwmGenerator, uint32_t pin, int32_t *status);
void setRelayForward(void* digital_port_pointer, bool on, int32_t *status);
void setRelayReverse(void* digital_port_pointer, bool on, int32_t *status);
bool getRelayForward(void* digital_port_pointer, int32_t *status);
bool getRelayReverse(void* digital_port_pointer, int32_t *status);
bool allocateDIO(void* digital_port_pointer, bool input, int32_t *status);
void freeDIO(void* digital_port_pointer, int32_t *status);
void setDIO(void* digital_port_pointer, short value, int32_t *status);
bool getDIO(void* digital_port_pointer, int32_t *status);
bool getDIODirection(void* digital_port_pointer, int32_t *status);
void pulse(void* digital_port_pointer, double pulseLength, int32_t *status);
bool isPulsing(void* digital_port_pointer, int32_t *status);
bool isAnyPulsing(int32_t *status);
void setFilterSelect(void* digital_port_pointer, int filter_index,
int32_t* status);
int getFilterSelect(void* digital_port_pointer, int32_t* status);
void setFilterPeriod(int filter_index, uint32_t value, int32_t* status);
uint32_t getFilterPeriod(int filter_index, int32_t* status);
void* initializeCounter(Mode mode, uint32_t *index, int32_t *status);
void freeCounter(void* counter_pointer, int32_t *status);
void setCounterAverageSize(void* counter_pointer, int32_t size, int32_t *status);
void setCounterUpSource(void* counter_pointer, uint32_t pin, bool analogTrigger, int32_t *status);
void setCounterUpSourceEdge(void* counter_pointer, bool risingEdge, bool fallingEdge,
int32_t *status);
void clearCounterUpSource(void* counter_pointer, int32_t *status);
void setCounterDownSource(void* counter_pointer, uint32_t pin, bool analogTrigger, int32_t *status);
void setCounterDownSourceEdge(void* counter_pointer, bool risingEdge, bool fallingEdge,
int32_t *status);
void clearCounterDownSource(void* counter_pointer, int32_t *status);
void setCounterUpDownMode(void* counter_pointer, int32_t *status);
void setCounterExternalDirectionMode(void* counter_pointer, int32_t *status);
void setCounterSemiPeriodMode(void* counter_pointer, bool highSemiPeriod, int32_t *status);
void setCounterPulseLengthMode(void* counter_pointer, double threshold, int32_t *status);
int32_t getCounterSamplesToAverage(void* counter_pointer, int32_t *status);
void setCounterSamplesToAverage(void* counter_pointer, int samplesToAverage, int32_t *status);
void resetCounter(void* counter_pointer, int32_t *status);
int32_t getCounter(void* counter_pointer, int32_t *status);
double getCounterPeriod(void* counter_pointer, int32_t *status);
void setCounterMaxPeriod(void* counter_pointer, double maxPeriod, int32_t *status);
void setCounterUpdateWhenEmpty(void* counter_pointer, bool enabled, int32_t *status);
bool getCounterStopped(void* counter_pointer, int32_t *status);
bool getCounterDirection(void* counter_pointer, int32_t *status);
void setCounterReverseDirection(void* counter_pointer, bool reverseDirection, int32_t *status);
void* initializeEncoder(uint8_t port_a_module, uint32_t port_a_pin, bool port_a_analog_trigger,
uint8_t port_b_module, uint32_t port_b_pin, bool port_b_analog_trigger,
bool reverseDirection, int32_t *index, int32_t *status); // TODO: fix routing
void freeEncoder(void* encoder_pointer, int32_t *status);
void resetEncoder(void* encoder_pointer, int32_t *status);
int32_t getEncoder(void* encoder_pointer, int32_t *status); // Raw value
double getEncoderPeriod(void* encoder_pointer, int32_t *status);
void setEncoderMaxPeriod(void* encoder_pointer, double maxPeriod, int32_t *status);
bool getEncoderStopped(void* encoder_pointer, int32_t *status);
bool getEncoderDirection(void* encoder_pointer, int32_t *status);
void setEncoderReverseDirection(void* encoder_pointer, bool reverseDirection, int32_t *status);
void setEncoderSamplesToAverage(void* encoder_pointer, uint32_t samplesToAverage,
int32_t *status);
uint32_t getEncoderSamplesToAverage(void* encoder_pointer, int32_t *status);
void setEncoderIndexSource(void *encoder_pointer, uint32_t pin, bool analogTrigger, bool activeHigh,
bool edgeSensitive, int32_t *status);
uint16_t getLoopTiming(int32_t *status);
void spiInitialize(uint8_t port, int32_t *status);
int32_t spiTransaction(uint8_t port, uint8_t *dataToSend, uint8_t *dataReceived, uint8_t size);
int32_t spiWrite(uint8_t port, uint8_t* dataToSend, uint8_t sendSize);
int32_t spiRead(uint8_t port, uint8_t *buffer, uint8_t count);
void spiClose(uint8_t port);
void spiSetSpeed(uint8_t port, uint32_t speed);
void spiSetOpts(uint8_t port, int msb_first, int sample_on_trailing, int clk_idle_high);
void spiSetChipSelectActiveHigh(uint8_t port, int32_t *status);
void spiSetChipSelectActiveLow(uint8_t port, int32_t *status);
int32_t spiGetHandle(uint8_t port);
void spiSetHandle(uint8_t port, int32_t handle);
void spiInitAccumulator(uint8_t port, uint32_t period, uint32_t cmd,
uint8_t xfer_size, uint32_t valid_mask,
uint32_t valid_value, uint8_t data_shift,
uint8_t data_size, bool is_signed, bool big_endian,
int32_t *status);
void spiFreeAccumulator(uint8_t port, int32_t *status);
void spiResetAccumulator(uint8_t port, int32_t *status);
void spiSetAccumulatorCenter(uint8_t port, int32_t center, int32_t *status);
void spiSetAccumulatorDeadband(uint8_t port, int32_t deadband, int32_t *status);
int32_t spiGetAccumulatorLastValue(uint8_t port, int32_t *status);
int64_t spiGetAccumulatorValue(uint8_t port, int32_t *status);
uint32_t spiGetAccumulatorCount(uint8_t port, int32_t *status);
double spiGetAccumulatorAverage(uint8_t port, int32_t *status);
void spiGetAccumulatorOutput(uint8_t port, int64_t *value, uint32_t *count,
int32_t *status);
void i2CInitialize(uint8_t port, int32_t *status);
int32_t i2CTransaction(uint8_t port, uint8_t deviceAddress, uint8_t *dataToSend, uint8_t sendSize, uint8_t *dataReceived, uint8_t receiveSize);
int32_t i2CWrite(uint8_t port, uint8_t deviceAddress, uint8_t *dataToSend, uint8_t sendSize);
int32_t i2CRead(uint8_t port, uint8_t deviceAddress, uint8_t *buffer, uint8_t count);
void i2CClose(uint8_t port);
//// Float JNA Hack
// double
void setPWMRateIntHack(int rate, int32_t *status);
void setPWMDutyCycleIntHack(void* pwmGenerator, int32_t dutyCycle, int32_t *status);
}

View File

@@ -0,0 +1,122 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2013-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <cstddef>
#include "HAL/Types.h"
#define HAL_IO_CONFIG_DATA_SIZE 32
#define HAL_SYS_STATUS_DATA_SIZE 44
#define HAL_USER_STATUS_DATA_SIZE \
(984 - HAL_IO_CONFIG_DATA_SIZE - HAL_SYS_STATUS_DATA_SIZE)
#define HALFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Input 17
#define HALFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Output 18
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Header 19
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Extra1 20
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Vertices1 21
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Extra2 22
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Vertices2 23
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Joystick 24
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Custom 25
struct HAL_ControlWord {
uint32_t enabled : 1;
uint32_t autonomous : 1;
uint32_t test : 1;
uint32_t eStop : 1;
uint32_t fmsAttached : 1;
uint32_t dsAttached : 1;
uint32_t control_reserved : 26;
};
enum HAL_AllianceStationID : int32_t {
HAL_AllianceStationID_kRed1,
HAL_AllianceStationID_kRed2,
HAL_AllianceStationID_kRed3,
HAL_AllianceStationID_kBlue1,
HAL_AllianceStationID_kBlue2,
HAL_AllianceStationID_kBlue3,
};
/* The maximum number of axes that will be stored in a single HALJoystickAxes
* struct. This is used for allocating buffers, not bounds checking, since
* there are usually less axes in practice.
*/
#define HAL_kMaxJoystickAxes 12
#define HAL_kMaxJoystickPOVs 12
struct HAL_JoystickAxes {
int16_t count;
float axes[HAL_kMaxJoystickAxes];
};
struct HAL_JoystickPOVs {
int16_t count;
int16_t povs[HAL_kMaxJoystickPOVs];
};
struct HAL_JoystickButtons {
uint32_t buttons;
uint8_t count;
};
struct HAL_JoystickDescriptor {
uint8_t isXbox;
uint8_t type;
char name[256];
uint8_t axisCount;
uint8_t axisTypes[HAL_kMaxJoystickAxes];
uint8_t buttonCount;
uint8_t povCount;
};
#ifdef __cplusplus
extern "C" {
#endif
int32_t HAL_SetErrorData(const char* errors, int32_t errorsLength,
int32_t waitMs);
int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode,
const char* details, const char* location,
const char* callStack, HAL_Bool printMsg);
int32_t HAL_GetControlWord(HAL_ControlWord* controlWord);
HAL_AllianceStationID HAL_GetAllianceStation(int32_t* status);
int32_t HAL_GetJoystickAxes(int32_t joystickNum, HAL_JoystickAxes* axes);
int32_t HAL_GetJoystickPOVs(int32_t joystickNum, HAL_JoystickPOVs* povs);
int32_t HAL_GetJoystickButtons(int32_t joystickNum,
HAL_JoystickButtons* buttons);
int32_t HAL_GetJoystickDescriptor(int32_t joystickNum,
HAL_JoystickDescriptor* desc);
HAL_Bool HAL_GetJoystickIsXbox(int32_t joystickNum);
int32_t HAL_GetJoystickType(int32_t joystickNum);
char* HAL_GetJoystickName(int32_t joystickNum);
int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis);
int32_t HAL_SetJoystickOutputs(int32_t joystickNum, int64_t outputs,
int32_t leftRumble, int32_t rightRumble);
double HAL_GetMatchTime(int32_t* status);
#ifndef HAL_USE_LABVIEW
void HAL_WaitForDSData(void);
void HAL_InitializeDriverStation(void);
void HAL_ObserveUserProgramStarting(void);
void HAL_ObserveUserProgramDisabled(void);
void HAL_ObserveUserProgramAutonomous(void);
void HAL_ObserveUserProgramTeleop(void);
void HAL_ObserveUserProgramTest(void);
#endif // HAL_USE_LABVIEW
#ifdef __cplusplus
} // extern "C"
#endif

79
hal/include/HAL/Encoder.h Normal file
View File

@@ -0,0 +1,79 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/AnalogTrigger.h"
#include "HAL/Types.h"
enum HAL_EncoderIndexingType : int32_t {
HAL_kResetWhileHigh,
HAL_kResetWhileLow,
HAL_kResetOnFallingEdge,
HAL_kResetOnRisingEdge
};
enum HAL_EncoderEncodingType : int32_t {
HAL_Encoder_k1X,
HAL_Encoder_k2X,
HAL_Encoder_k4X
};
#ifdef __cplusplus
extern "C" {
#endif
HAL_EncoderHandle HAL_InitializeEncoder(
HAL_Handle digitalSourceHandleA, HAL_AnalogTriggerType analogTriggerTypeA,
HAL_Handle digitalSourceHandleB, HAL_AnalogTriggerType analogTriggerTypeB,
HAL_Bool reverseDirection, HAL_EncoderEncodingType encodingType,
int32_t* status);
void HAL_FreeEncoder(HAL_EncoderHandle encoderHandle, int32_t* status);
int32_t HAL_GetEncoder(HAL_EncoderHandle encoderHandle, int32_t* status);
int32_t HAL_GetEncoderRaw(HAL_EncoderHandle encoderHandle, int32_t* status);
int32_t HAL_GetEncoderEncodingScale(HAL_EncoderHandle encoderHandle,
int32_t* status);
void HAL_ResetEncoder(HAL_EncoderHandle encoderHandle, int32_t* status);
double HAL_GetEncoderPeriod(HAL_EncoderHandle encoderHandle, int32_t* status);
void HAL_SetEncoderMaxPeriod(HAL_EncoderHandle encoderHandle, double maxPeriod,
int32_t* status);
HAL_Bool HAL_GetEncoderStopped(HAL_EncoderHandle encoderHandle,
int32_t* status);
HAL_Bool HAL_GetEncoderDirection(HAL_EncoderHandle encoderHandle,
int32_t* status);
double HAL_GetEncoderDistance(HAL_EncoderHandle encoderHandle, int32_t* status);
double HAL_GetEncoderRate(HAL_EncoderHandle encoderHandle, int32_t* status);
void HAL_SetEncoderMinRate(HAL_EncoderHandle encoderHandle, double minRate,
int32_t* status);
void HAL_SetEncoderDistancePerPulse(HAL_EncoderHandle encoderHandle,
double distancePerPulse, int32_t* status);
void HAL_SetEncoderReverseDirection(HAL_EncoderHandle encoderHandle,
HAL_Bool reverseDirection, int32_t* status);
void HAL_SetEncoderSamplesToAverage(HAL_EncoderHandle encoderHandle,
int32_t samplesToAverage, int32_t* status);
int32_t HAL_GetEncoderSamplesToAverage(HAL_EncoderHandle encoderHandle,
int32_t* status);
void HAL_SetEncoderIndexSource(HAL_EncoderHandle encoderHandle,
HAL_Handle digitalSourceHandle,
HAL_AnalogTriggerType analogTriggerType,
HAL_EncoderIndexingType type, int32_t* status);
int32_t HAL_GetEncoderFPGAIndex(HAL_EncoderHandle encoderHandle,
int32_t* status);
double HAL_GetEncoderDecodingScaleFactor(HAL_EncoderHandle encoderHandle,
int32_t* status);
double HAL_GetEncoderDistancePerPulse(HAL_EncoderHandle encoderHandle,
int32_t* status);
HAL_EncoderEncodingType HAL_GetEncoderEncodingType(
HAL_EncoderHandle encoderHandle, int32_t* status);
#ifdef __cplusplus
}
#endif

117
hal/include/HAL/Errors.h Normal file
View File

@@ -0,0 +1,117 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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
#define CTR_RxTimeout_MESSAGE "CTRE CAN Receive Timeout"
#define CTR_TxTimeout_MESSAGE "CTRE CAN Transmit Timeout"
#define CTR_InvalidParamValue_MESSAGE "CTRE CAN Invalid Parameter"
#define CTR_UnexpectedArbId_MESSAGE \
"CTRE Unexpected Arbitration ID (CAN Node ID)"
#define CTR_TxFailed_MESSAGE "CTRE CAN Transmit Error"
#define CTR_SigNotUpdated_MESSAGE "CTRE CAN Signal Not Updated"
#define NiFpga_Status_FifoTimeout_MESSAGE "NIFPGA: FIFO timeout error"
#define NiFpga_Status_TransferAborted_MESSAGE "NIFPGA: Transfer aborted error"
#define NiFpga_Status_MemoryFull_MESSAGE \
"NIFPGA: Memory Allocation failed, memory full"
#define NiFpga_Status_SoftwareFault_MESSAGE "NIFPGA: Unexpected software error"
#define NiFpga_Status_InvalidParameter_MESSAGE "NIFPGA: Invalid Parameter"
#define NiFpga_Status_ResourceNotFound_MESSAGE "NIFPGA: Resource not found"
#define NiFpga_Status_ResourceNotInitialized_MESSAGE \
"NIFPGA: Resource not initialized"
#define NiFpga_Status_HardwareFault_MESSAGE "NIFPGA: Hardware Fault"
#define NiFpga_Status_IrqTimeout_MESSAGE "NIFPGA: Interrupt timeout"
#define ERR_CANSessionMux_InvalidBuffer_MESSAGE "CAN: Invalid Buffer"
#define ERR_CANSessionMux_MessageNotFound_MESSAGE "CAN: Message not found"
#define WARN_CANSessionMux_NoToken_MESSAGE "CAN: No token"
#define ERR_CANSessionMux_NotAllowed_MESSAGE "CAN: Not allowed"
#define ERR_CANSessionMux_NotInitialized_MESSAGE "CAN: Not initialized"
#define SAMPLE_RATE_TOO_HIGH 1001
#define SAMPLE_RATE_TOO_HIGH_MESSAGE \
"HAL: Analog module sample rate is too high"
#define VOLTAGE_OUT_OF_RANGE 1002
#define VOLTAGE_OUT_OF_RANGE_MESSAGE \
"HAL: Voltage to convert to raw value is out of range [0; 5]"
#define LOOP_TIMING_ERROR 1004
#define LOOP_TIMING_ERROR_MESSAGE \
"HAL: Digital module loop timing is not the expected value"
#define SPI_WRITE_NO_MOSI 1012
#define SPI_WRITE_NO_MOSI_MESSAGE \
"HAL: Cannot write to SPI port with no MOSI output"
#define SPI_READ_NO_MISO 1013
#define SPI_READ_NO_MISO_MESSAGE \
"HAL: Cannot read from SPI port with no MISO input"
#define SPI_READ_NO_DATA 1014
#define SPI_READ_NO_DATA_MESSAGE "HAL: No data available to read from SPI"
#define INCOMPATIBLE_STATE 1015
#define INCOMPATIBLE_STATE_MESSAGE \
"HAL: Incompatible State: The operation cannot be completed"
#define NO_AVAILABLE_RESOURCES -1004
#define NO_AVAILABLE_RESOURCES_MESSAGE "HAL: No available resources to allocate"
#define NULL_PARAMETER -1005
#define NULL_PARAMETER_MESSAGE "HAL: A pointer parameter to a method is NULL"
#define ANALOG_TRIGGER_LIMIT_ORDER_ERROR -1010
#define ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE \
"HAL: AnalogTrigger limits error. Lower limit > Upper Limit"
#define ANALOG_TRIGGER_PULSE_OUTPUT_ERROR -1011
#define ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE \
"HAL: Attempted to read AnalogTrigger pulse output."
#define PARAMETER_OUT_OF_RANGE -1028
#define PARAMETER_OUT_OF_RANGE_MESSAGE "HAL: A parameter is out of range."
#define RESOURCE_IS_ALLOCATED -1029
#define RESOURCE_IS_ALLOCATED_MESSAGE "HAL: Resource already allocated"
#define RESOURCE_OUT_OF_RANGE -1030
#define RESOURCE_OUT_OF_RANGE_MESSAGE \
"HAL: The requested resource is out of range."
#define HAL_INVALID_ACCUMULATOR_CHANNEL -1035
#define HAL_INVALID_ACCUMULATOR_CHANNEL_MESSAGE \
"HAL: The requested input is not an accumulator channel"
#define HAL_COUNTER_NOT_SUPPORTED -1058
#define HAL_COUNTER_NOT_SUPPORTED_MESSAGE \
"HAL: Counter mode not supported for encoder method"
#define HAL_PWM_SCALE_ERROR -1072
#define HAL_PWM_SCALE_ERROR_MESSAGE \
"HAL: The PWM Scale Factors are out of range"
#define HAL_HANDLE_ERROR -1098
#define HAL_HANDLE_ERROR_MESSAGE \
"HAL: A handle parameter was passed incorrectly"
#define HAL_SERIAL_PORT_NOT_FOUND -1123
#define HAL_SERIAL_PORT_NOT_FOUND_MESSAGE \
"HAL: The specified serial port device was not found"
#define HAL_SERIAL_PORT_OPEN_ERROR -1124
#define HAL_SERIAL_PORT_OPEN_ERROR_MESSAGE \
"HAL: The serial port could not be opened"
#define HAL_SERIAL_PORT_ERROR -1125
#define HAL_SERIAL_PORT_ERROR_MESSAGE \
"HAL: There was an error on the serial port"
#define HAL_THREAD_PRIORITY_ERROR -1152
#define HAL_THREAD_PRIORITY_ERROR_MESSAGE \
"HAL: Getting or setting the priority of a thread has failed";
#define HAL_THREAD_PRIORITY_RANGE_ERROR -1153
#define HAL_THREAD_PRIORITY_RANGE_ERROR_MESSAGE \
"HAL: The priority requested to be set is invalid"
#define VI_ERROR_SYSTEM_ERROR_MESSAGE "HAL - VISA: System Error";
#define VI_ERROR_INV_OBJECT_MESSAGE "HAL - VISA: Invalid Object"
#define VI_ERROR_RSRC_LOCKED_MESSAGE "HAL - VISA: Resource Locked"
#define VI_ERROR_RSRC_NFOUND_MESSAGE "HAL - VISA: Resource Not Found"
#define VI_ERROR_INV_RSRC_NAME_MESSAGE "HAL - VISA: Invalid Resource Name"
#define VI_ERROR_QUEUE_OVERFLOW_MESSAGE "HAL - VISA: Queue Overflow"
#define VI_ERROR_IO_MESSAGE "HAL - VISA: General IO Error"
#define VI_ERROR_ASRL_PARITY_MESSAGE "HAL - VISA: Parity Error"
#define VI_ERROR_ASRL_FRAMING_MESSAGE "HAL - VISA: Framing Error"
#define VI_ERROR_ASRL_OVERRUN_MESSAGE "HAL - VISA: Buffer Overrun Error"
#define VI_ERROR_RSRC_BUSY_MESSAGE "HAL - VISA: Resource Busy"
#define VI_ERROR_INV_PARAMETER_MESSAGE "HAL - VISA: Invalid Parameter"

View File

@@ -1,64 +0,0 @@
#pragma once
#define CTR_RxTimeout_MESSAGE "CTRE CAN Recieve Timeout"
#define CTR_TxTimeout_MESSAGE "CTRE CAN Transmit Timeout"
#define CTR_InvalidParamValue_MESSAGE "CTRE CAN Invalid Parameter"
#define CTR_UnexpectedArbId_MESSAGE "CTRE Unexpected Arbitration ID (CAN Node ID)"
#define CTR_TxFailed_MESSAGE "CTRE CAN Transmit Error"
#define CTR_SigNotUpdated_MESSAGE "CTRE CAN Signal Not Updated"
#define NiFpga_Status_FifoTimeout_MESSAGE "NIFPGA: FIFO timeout error"
#define NiFpga_Status_TransferAborted_MESSAGE "NIFPGA: Transfer aborted error"
#define NiFpga_Status_MemoryFull_MESSAGE "NIFPGA: Memory Allocation failed, memory full"
#define NiFpga_Status_SoftwareFault_MESSAGE "NIFPGA: Unexepected software error"
#define NiFpga_Status_InvalidParameter_MESSAGE "NIFPGA: Invalid Parameter"
#define NiFpga_Status_ResourceNotFound_MESSAGE "NIFPGA: Resource not found"
#define NiFpga_Status_ResourceNotInitialized_MESSAGE "NIFPGA: Resource not initialized"
#define NiFpga_Status_HardwareFault_MESSAGE "NIFPGA: Hardware Fault"
#define NiFpga_Status_IrqTimeout_MESSAGE "NIFPGA: Interrupt timeout"
#define ERR_CANSessionMux_InvalidBuffer_MESSAGE "CAN: Invalid Buffer"
#define ERR_CANSessionMux_MessageNotFound_MESSAGE "CAN: Message not found"
#define WARN_CANSessionMux_NoToken_MESSAGE "CAN: No token"
#define ERR_CANSessionMux_NotAllowed_MESSAGE "CAN: Not allowed"
#define ERR_CANSessionMux_NotInitialized_MESSAGE "CAN: Not initialized"
#define SAMPLE_RATE_TOO_HIGH 1001
#define SAMPLE_RATE_TOO_HIGH_MESSAGE "HAL: Analog module sample rate is too high"
#define VOLTAGE_OUT_OF_RANGE 1002
#define VOLTAGE_OUT_OF_RANGE_MESSAGE "HAL: Voltage to convert to raw value is out of range [0; 5]"
#define LOOP_TIMING_ERROR 1004
#define LOOP_TIMING_ERROR_MESSAGE "HAL: Digital module loop timing is not the expected value"
#define SPI_WRITE_NO_MOSI 1012
#define SPI_WRITE_NO_MOSI_MESSAGE "HAL: Cannot write to SPI port with no MOSI output"
#define SPI_READ_NO_MISO 1013
#define SPI_READ_NO_MISO_MESSAGE "HAL: Cannot read from SPI port with no MISO input"
#define SPI_READ_NO_DATA 1014
#define SPI_READ_NO_DATA_MESSAGE "HAL: No data available to read from SPI"
#define INCOMPATIBLE_STATE 1015
#define INCOMPATIBLE_STATE_MESSAGE "HAL: Incompatible State: The operation cannot be completed"
#define NO_AVAILABLE_RESOURCES -1004
#define NO_AVAILABLE_RESOURCES_MESSAGE "HAL: No available resources to allocate"
#define NULL_PARAMETER -1005
#define NULL_PARAMETER_MESSAGE "HAL: A pointer parameter to a method is NULL"
#define ANALOG_TRIGGER_LIMIT_ORDER_ERROR -1010
#define ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE "HAL: AnalogTrigger limits error. Lower limit > Upper Limit"
#define ANALOG_TRIGGER_PULSE_OUTPUT_ERROR -1011
#define ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE "HAL: Attempted to read AnalogTrigger pulse output."
#define PARAMETER_OUT_OF_RANGE -1028
#define PARAMETER_OUT_OF_RANGE_MESSAGE "HAL: A parameter is out of range."
#define RESOURCE_IS_ALLOCATED -1029
#define RESOURCE_IS_ALLOCATED_MESSAGE "HAL: Resource already allocated"
#define VI_ERROR_SYSTEM_ERROR_MESSAGE "HAL - VISA: System Error";
#define VI_ERROR_INV_OBJECT_MESSAGE "HAL - VISA: Invalid Object"
#define VI_ERROR_RSRC_LOCKED_MESSAGE "HAL - VISA: Resource Locked"
#define VI_ERROR_RSRC_NFOUND_MESSAGE "HAL - VISA: Resource Not Found"
#define VI_ERROR_INV_RSRC_NAME_MESSAGE "HAL - VISA: Invalid Resource Name"
#define VI_ERROR_QUEUE_OVERFLOW_MESSAGE "HAL - VISA: Queue Overflow"
#define VI_ERROR_IO_MESSAGE "HAL - VISA: General IO Error"
#define VI_ERROR_ASRL_PARITY_MESSAGE "HAL - VISA: Parity Error"
#define VI_ERROR_ASRL_FRAMING_MESSAGE "HAL - VISA: Framing Error"
#define VI_ERROR_ASRL_OVERRUN_MESSAGE "HAL - VISA: Buffer Overrun Error"
#define VI_ERROR_RSRC_BUSY_MESSAGE "HAL - VISA: Resource Busy"
#define VI_ERROR_INV_PARAMETER_MESSAGE "HAL - VISA: Invalid Parameter"

85
hal/include/HAL/HAL.h Normal file
View File

@@ -0,0 +1,85 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2013-2017. All Rights Reserved. */
/* Open Source Software - may be 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>
#ifndef HAL_USE_LABVIEW
#include "HAL/Accelerometer.h"
#include "HAL/AnalogAccumulator.h"
#include "HAL/AnalogGyro.h"
#include "HAL/AnalogInput.h"
#include "HAL/AnalogOutput.h"
#include "HAL/AnalogTrigger.h"
#include "HAL/Compressor.h"
#include "HAL/Constants.h"
#include "HAL/Counter.h"
#include "HAL/DIO.h"
#include "HAL/DriverStation.h"
#include "HAL/Errors.h"
#include "HAL/I2C.h"
#include "HAL/Interrupts.h"
#include "HAL/Notifier.h"
#include "HAL/PDP.h"
#include "HAL/PWM.h"
#include "HAL/Ports.h"
#include "HAL/Power.h"
#include "HAL/Relay.h"
#include "HAL/SPI.h"
#include "HAL/SerialPort.h"
#include "HAL/Solenoid.h"
#endif // HAL_USE_LABVIEW
#include "FRC_NetworkCommunication/UsageReporting.h"
#include "HAL/Types.h"
namespace HALUsageReporting = nUsageReporting;
enum HAL_RuntimeType : int32_t { HAL_Athena, HAL_Mock };
#ifdef __cplusplus
extern "C" {
#endif
const char* HAL_GetErrorMessage(int32_t code);
int32_t HAL_GetFPGAVersion(int32_t* status);
int64_t HAL_GetFPGARevision(int32_t* status);
HAL_RuntimeType HAL_GetRuntimeType();
HAL_Bool HAL_GetFPGAButton(int32_t* status);
HAL_Bool HAL_GetSystemActive(int32_t* status);
HAL_Bool HAL_GetBrownedOut(int32_t* status);
void HAL_BaseInitialize(int32_t* status);
#ifndef HAL_USE_LABVIEW
HAL_PortHandle HAL_GetPort(int32_t channel);
HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel);
uint64_t HAL_GetFPGATime(int32_t* status);
int32_t HAL_Initialize(int32_t mode);
// ifdef's definition is to allow for default parameters in C++.
#ifdef __cplusplus
int64_t HAL_Report(int32_t resource, int32_t instanceNumber,
int32_t context = 0, const char* feature = nullptr);
#else
int64_t HAL_Report(int32_t resource, int32_t instanceNumber, int32_t context,
const char* feature);
#endif
#endif // HAL_USE_LABVIEW
#ifdef __cplusplus
}
#endif

View File

@@ -1,271 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2013. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#include <cmath>
#include "Accelerometer.hpp"
#include "Analog.hpp"
#include "Compressor.hpp"
#include "Digital.hpp"
#include "Solenoid.hpp"
#include "Notifier.hpp"
#include "Interrupts.hpp"
#include "Errors.hpp"
#include "PDP.hpp"
#include "Power.hpp"
#include "SerialPort.hpp"
#include "Utilities.hpp"
#include "Semaphore.hpp"
#include "Task.hpp"
#define HAL_IO_CONFIG_DATA_SIZE 32
#define HAL_SYS_STATUS_DATA_SIZE 44
#define HAL_USER_STATUS_DATA_SIZE (984 - HAL_IO_CONFIG_DATA_SIZE - HAL_SYS_STATUS_DATA_SIZE)
#define HALFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Input 17
#define HALFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Output 18
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Header 19
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Extra1 20
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Vertices1 21
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Extra2 22
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Vertices2 23
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Joystick 24
#define HALFRC_NetworkCommunication_DynamicType_Kinect_Custom 25
namespace HALUsageReporting
{
enum tResourceType
{
kResourceType_Controller,
kResourceType_Module,
kResourceType_Language,
kResourceType_CANPlugin,
kResourceType_Accelerometer,
kResourceType_ADXL345,
kResourceType_AnalogChannel,
kResourceType_AnalogTrigger,
kResourceType_AnalogTriggerOutput,
kResourceType_CANJaguar,
kResourceType_Compressor,
kResourceType_Counter,
kResourceType_Dashboard,
kResourceType_DigitalInput,
kResourceType_DigitalOutput,
kResourceType_DriverStationCIO,
kResourceType_DriverStationEIO,
kResourceType_DriverStationLCD,
kResourceType_Encoder,
kResourceType_GearTooth,
kResourceType_Gyro,
kResourceType_I2C,
kResourceType_Framework,
kResourceType_Jaguar,
kResourceType_Joystick,
kResourceType_Kinect,
kResourceType_KinectStick,
kResourceType_PIDController,
kResourceType_Preferences,
kResourceType_PWM,
kResourceType_Relay,
kResourceType_RobotDrive,
kResourceType_SerialPort,
kResourceType_Servo,
kResourceType_Solenoid,
kResourceType_SPI,
kResourceType_Task,
kResourceType_Ultrasonic,
kResourceType_Victor,
kResourceType_Button,
kResourceType_Command,
kResourceType_AxisCamera,
kResourceType_PCVideoServer,
kResourceType_SmartDashboard,
kResourceType_Talon,
kResourceType_HiTechnicColorSensor,
kResourceType_HiTechnicAccel,
kResourceType_HiTechnicCompass,
kResourceType_SRF08,
kResourceType_AnalogOutput,
kResourceType_VictorSP,
kResourceType_TalonSRX,
kResourceType_CANTalonSRX,
kResourceType_ADXL362,
kResourceType_ADXRS450,
kResourceType_RevSPARK,
kResourceType_MindsensorsSD540,
kResourceType_DigitalFilter,
};
enum tInstances
{
kLanguage_LabVIEW = 1,
kLanguage_CPlusPlus = 2,
kLanguage_Java = 3,
kLanguage_Python = 4,
kCANPlugin_BlackJagBridge = 1,
kCANPlugin_2CAN = 2,
kFramework_Iterative = 1,
kFramework_Sample = 2,
kFramework_CommandControl = 3,
kRobotDrive_ArcadeStandard = 1,
kRobotDrive_ArcadeButtonSpin = 2,
kRobotDrive_ArcadeRatioCurve = 3,
kRobotDrive_Tank = 4,
kRobotDrive_MecanumPolar = 5,
kRobotDrive_MecanumCartesian = 6,
kDriverStationCIO_Analog = 1,
kDriverStationCIO_DigitalIn = 2,
kDriverStationCIO_DigitalOut = 3,
kDriverStationEIO_Acceleration = 1,
kDriverStationEIO_AnalogIn = 2,
kDriverStationEIO_AnalogOut = 3,
kDriverStationEIO_Button = 4,
kDriverStationEIO_LED = 5,
kDriverStationEIO_DigitalIn = 6,
kDriverStationEIO_DigitalOut = 7,
kDriverStationEIO_FixedDigitalOut = 8,
kDriverStationEIO_PWM = 9,
kDriverStationEIO_Encoder = 10,
kDriverStationEIO_TouchSlider = 11,
kADXL345_SPI = 1,
kADXL345_I2C = 2,
kCommand_Scheduler = 1,
kSmartDashboard_Instance = 1,
};
}
struct HALControlWord {
uint32_t enabled : 1;
uint32_t autonomous : 1;
uint32_t test :1;
uint32_t eStop : 1;
uint32_t fmsAttached:1;
uint32_t dsAttached:1;
uint32_t control_reserved : 26;
};
enum HALAllianceStationID {
kHALAllianceStationID_red1,
kHALAllianceStationID_red2,
kHALAllianceStationID_red3,
kHALAllianceStationID_blue1,
kHALAllianceStationID_blue2,
kHALAllianceStationID_blue3,
};
/* The maximum number of axes that will be stored in a single HALJoystickAxes
struct. This is used for allocating buffers, not bounds checking, since
there are usually less axes in practice. */
static const size_t kMaxJoystickAxes = 12;
static const size_t kMaxJoystickPOVs = 12;
struct HALJoystickAxes {
uint16_t count;
int16_t axes[kMaxJoystickAxes];
};
struct HALJoystickPOVs {
uint16_t count;
int16_t povs[kMaxJoystickPOVs];
};
struct HALJoystickButtons {
uint32_t buttons;
uint8_t count;
};
struct HALJoystickDescriptor {
uint8_t isXbox;
uint8_t type;
char name[256];
uint8_t axisCount;
uint8_t axisTypes[kMaxJoystickAxes];
uint8_t buttonCount;
uint8_t povCount;
};
inline float intToFloat(int value)
{
return (float)value;
}
inline int floatToInt(float value)
{
return round(value);
}
extern "C"
{
extern const uint32_t dio_kNumSystems;
extern const uint32_t solenoid_kNumDO7_0Elements;
extern const uint32_t interrupt_kNumSystems;
extern const uint32_t kSystemClockTicksPerMicrosecond;
void* getPort(uint8_t pin);
void* getPortWithModule(uint8_t module, uint8_t pin);
void freePort(void* port);
const char* getHALErrorMessage(int32_t code);
uint16_t getFPGAVersion(int32_t *status);
uint32_t getFPGARevision(int32_t *status);
uint64_t getFPGATime(int32_t *status);
bool getFPGAButton(int32_t *status);
int HALSetErrorData(const char *errors, int errorsLength, int wait_ms);
int HALSendError(int isError, int32_t errorCode, int isLVCode,
const char *details, const char *location, const char *callStack,
int printMsg);
int HALGetControlWord(HALControlWord *data);
int HALGetAllianceStation(enum HALAllianceStationID *allianceStation);
int HALGetJoystickAxes(uint8_t joystickNum, HALJoystickAxes *axes);
int HALGetJoystickPOVs(uint8_t joystickNum, HALJoystickPOVs *povs);
int HALGetJoystickButtons(uint8_t joystickNum, HALJoystickButtons *buttons);
int HALGetJoystickDescriptor(uint8_t joystickNum, HALJoystickDescriptor *desc);
int HALGetJoystickIsXbox(uint8_t joystickNum);
int HALGetJoystickType(uint8_t joystickNum);
char* HALGetJoystickName(uint8_t joystickNum);
int HALGetJoystickAxisType(uint8_t joystickNum, uint8_t axis);
int HALSetJoystickOutputs(uint8_t joystickNum, uint32_t outputs, uint16_t leftRumble, uint16_t rightRumble);
int HALGetMatchTime(float *matchTime);
void HALSetNewDataSem(MULTIWAIT_ID sem);
bool HALGetSystemActive(int32_t *status);
bool HALGetBrownedOut(int32_t *status);
int HALInitialize(int mode = 0);
void HALNetworkCommunicationObserveUserProgramStarting();
void HALNetworkCommunicationObserveUserProgramDisabled();
void HALNetworkCommunicationObserveUserProgramAutonomous();
void HALNetworkCommunicationObserveUserProgramTeleop();
void HALNetworkCommunicationObserveUserProgramTest();
uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context = 0,
const char *feature = NULL);
}
// TODO: HACKS for now...
extern "C"
{
void NumericArrayResize();
void RTSetCleanupProc();
void EDVR_CreateReference();
void Occur();
}

27
hal/include/HAL/I2C.h Normal file
View File

@@ -0,0 +1,27 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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>
#ifdef __cplusplus
extern "C" {
#endif
void HAL_InitializeI2C(int32_t port, int32_t* status);
int32_t HAL_TransactionI2C(int32_t port, int32_t deviceAddress,
uint8_t* dataToSend, int32_t sendSize,
uint8_t* dataReceived, int32_t receiveSize);
int32_t HAL_WriteI2C(int32_t port, int32_t deviceAddress, uint8_t* dataToSend,
int32_t sendSize);
int32_t HAL_ReadI2C(int32_t port, int32_t deviceAddress, uint8_t* buffer,
int32_t count);
void HAL_CloseI2C(int32_t port);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,50 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/AnalogTrigger.h"
#include "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*HAL_InterruptHandlerFunction)(uint32_t interruptAssertedMask,
void* param);
HAL_InterruptHandle HAL_InitializeInterrupts(HAL_Bool watcher, int32_t* status);
void HAL_CleanInterrupts(HAL_InterruptHandle interruptHandle, int32_t* status);
int64_t HAL_WaitForInterrupt(HAL_InterruptHandle interruptHandle,
double timeout, HAL_Bool ignorePrevious,
int32_t* status);
void HAL_EnableInterrupts(HAL_InterruptHandle interruptHandle, int32_t* status);
void HAL_DisableInterrupts(HAL_InterruptHandle interruptHandle,
int32_t* status);
double HAL_ReadInterruptRisingTimestamp(HAL_InterruptHandle interruptHandle,
int32_t* status);
double HAL_ReadInterruptFallingTimestamp(HAL_InterruptHandle interruptHandle,
int32_t* status);
void HAL_RequestInterrupts(HAL_InterruptHandle interruptHandle,
HAL_Handle digitalSourceHandle,
HAL_AnalogTriggerType analogTriggerType,
int32_t* status);
void HAL_AttachInterruptHandler(HAL_InterruptHandle interruptHandle,
HAL_InterruptHandlerFunction handler,
void* param, int32_t* status);
void HAL_AttachInterruptHandlerThreaded(HAL_InterruptHandle interruptHandle,
HAL_InterruptHandlerFunction handler,
void* param, int32_t* status);
void HAL_SetInterruptUpSourceEdge(HAL_InterruptHandle interruptHandle,
HAL_Bool risingEdge, HAL_Bool fallingEdge,
int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,26 +0,0 @@
#pragma once
#include <stdint.h>
#include <iostream>
#include "errno.h"
extern "C"
{
typedef void (*InterruptHandlerFunction)(uint32_t interruptAssertedMask, void *param);
void* initializeInterrupts(uint32_t interruptIndex, bool watcher, int32_t *status);
void cleanInterrupts(void* interrupt_pointer, int32_t *status);
uint32_t waitForInterrupt(void* interrupt_pointer, double timeout, bool ignorePrevious, int32_t *status);
void enableInterrupts(void* interrupt_pointer, int32_t *status);
void disableInterrupts(void* interrupt_pointer, int32_t *status);
double readRisingTimestamp(void* interrupt_pointer, int32_t *status);
double readFallingTimestamp(void* interrupt_pointer, int32_t *status);
void requestInterrupts(void* interrupt_pointer, uint8_t routing_module, uint32_t routing_pin,
bool routing_analog_trigger, int32_t *status);
void attachInterruptHandler(void* interrupt_pointer, InterruptHandlerFunction handler,
void* param, int32_t *status);
void setInterruptUpSourceEdge(void* interrupt_pointer, bool risingEdge, bool fallingEdge,
int32_t *status);
}

View File

@@ -0,0 +1,14 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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
#define HAL_USE_LABVIEW
#include "HAL/DriverStation.h"
#include "HAL/HAL.h"
#include "HAL/Types.h"

View File

@@ -0,0 +1,32 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*HAL_NotifierProcessFunction)(uint64_t currentTime,
HAL_NotifierHandle handle);
HAL_NotifierHandle HAL_InitializeNotifier(HAL_NotifierProcessFunction process,
void* param, int32_t* status);
HAL_NotifierHandle HAL_InitializeNotifierThreaded(
HAL_NotifierProcessFunction process, void* param, int32_t* status);
void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status);
void* HAL_GetNotifierParam(HAL_NotifierHandle notifierHandle, int32_t* status);
void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle,
uint64_t triggerTime, int32_t* status);
void HAL_StopNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,12 +0,0 @@
#pragma once
#include <stdint.h>
extern "C"
{
void* initializeNotifier(void (*process)(uint64_t, void*), void* param, int32_t *status);
void cleanNotifier(void* notifier_pointer, int32_t *status);
void* getNotifierParam(void* notifier_pointer, int32_t *status);
void updateNotifierAlarm(void* notifier_pointer, uint64_t triggerTime, int32_t *status);
void stopNotifierAlarm(void* notifier_pointer, int32_t *status);
}

View File

@@ -0,0 +1,50 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "SerialPort.h"
#ifdef __cplusplus
extern "C" {
#endif
void HAL_InitializeOSSerialPort(HAL_SerialPort port, int32_t* status);
void HAL_SetOSSerialBaudRate(HAL_SerialPort port, int32_t baud,
int32_t* status);
void HAL_SetOSSerialDataBits(HAL_SerialPort port, int32_t bits,
int32_t* status);
void HAL_SetOSSerialParity(HAL_SerialPort port, int32_t parity,
int32_t* status);
void HAL_SetOSSerialStopBits(HAL_SerialPort port, int32_t stopBits,
int32_t* status);
void HAL_SetOSSerialWriteMode(HAL_SerialPort port, int32_t mode,
int32_t* status);
void HAL_SetOSSerialFlowControl(HAL_SerialPort port, int32_t flow,
int32_t* status);
void HAL_SetOSSerialTimeout(HAL_SerialPort port, double timeout,
int32_t* status);
void HAL_EnableOSSerialTermination(HAL_SerialPort port, char terminator,
int32_t* status);
void HAL_DisableOSSerialTermination(HAL_SerialPort port, int32_t* status);
void HAL_SetOSSerialReadBufferSize(HAL_SerialPort port, int32_t size,
int32_t* status);
void HAL_SetOSSerialWriteBufferSize(HAL_SerialPort port, int32_t size,
int32_t* status);
int32_t HAL_GetOSSerialBytesReceived(HAL_SerialPort port, int32_t* status);
int32_t HAL_ReadOSSerial(HAL_SerialPort port, char* buffer, int32_t count,
int32_t* status);
int32_t HAL_WriteOSSerial(HAL_SerialPort port, const char* buffer,
int32_t count, int32_t* status);
void HAL_FlushOSSerial(HAL_SerialPort port, int32_t* status);
void HAL_ClearOSSerial(HAL_SerialPort port, int32_t* status);
void HAL_CloseOSSerial(HAL_SerialPort port, int32_t* status);
#ifdef __cplusplus
}
#endif

32
hal/include/HAL/PDP.h Normal file
View File

@@ -0,0 +1,32 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
void HAL_InitializePDP(int32_t module, int32_t* status);
HAL_Bool HAL_CheckPDPChannel(int32_t channel);
HAL_Bool HAL_CheckPDPModule(int32_t module);
double HAL_GetPDPTemperature(int32_t module, int32_t* status);
double HAL_GetPDPVoltage(int32_t module, int32_t* status);
double HAL_GetPDPChannelCurrent(int32_t module, int32_t channel,
int32_t* status);
double HAL_GetPDPTotalCurrent(int32_t module, int32_t* status);
double HAL_GetPDPTotalPower(int32_t module, int32_t* status);
double HAL_GetPDPTotalEnergy(int32_t module, int32_t* status);
void HAL_ResetPDPTotalEnergy(int32_t module, int32_t* status);
void HAL_ClearPDPStickyFaults(int32_t module, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,16 +0,0 @@
#pragma once
#include <stdint.h>
extern "C"
{
void initializePDP(uint8_t module);
double getPDPTemperature(uint8_t module, int32_t *status);
double getPDPVoltage(uint8_t module, int32_t *status);
double getPDPChannelCurrent(uint8_t module, uint8_t channel, int32_t *status);
double getPDPTotalCurrent(uint8_t module, int32_t *status);
double getPDPTotalPower(uint8_t module, int32_t *status);
double getPDPTotalEnergy(uint8_t module, int32_t *status);
void resetPDPTotalEnergy(uint8_t module, int32_t *status);
void clearPDPStickyFaults(uint8_t module, int32_t *status);
}

55
hal/include/HAL/PWM.h Normal file
View File

@@ -0,0 +1,55 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle,
int32_t* status);
void HAL_FreePWMPort(HAL_DigitalHandle pwmPortHandle, int32_t* status);
HAL_Bool HAL_CheckPWMChannel(int32_t channel);
void HAL_SetPWMConfig(HAL_DigitalHandle pwmPortHandle, double maxPwm,
double deadbandMaxPwm, double centerPwm,
double deadbandMinPwm, double minPwm, int32_t* status);
void HAL_SetPWMConfigRaw(HAL_DigitalHandle pwmPortHandle, int32_t maxPwm,
int32_t deadbandMaxPwm, int32_t centerPwm,
int32_t deadbandMinPwm, int32_t minPwm,
int32_t* status);
void HAL_GetPWMConfigRaw(HAL_DigitalHandle pwmPortHandle, int32_t* maxPwm,
int32_t* deadbandMaxPwm, int32_t* centerPwm,
int32_t* deadbandMinPwm, int32_t* minPwm,
int32_t* status);
void HAL_SetPWMEliminateDeadband(HAL_DigitalHandle pwmPortHandle,
HAL_Bool eliminateDeadband, int32_t* status);
HAL_Bool HAL_GetPWMEliminateDeadband(HAL_DigitalHandle pwmPortHandle,
int32_t* status);
void HAL_SetPWMRaw(HAL_DigitalHandle pwmPortHandle, int32_t value,
int32_t* status);
void HAL_SetPWMSpeed(HAL_DigitalHandle pwmPortHandle, double speed,
int32_t* status);
void HAL_SetPWMPosition(HAL_DigitalHandle pwmPortHandle, double position,
int32_t* status);
void HAL_SetPWMDisabled(HAL_DigitalHandle pwmPortHandle, int32_t* status);
int32_t HAL_GetPWMRaw(HAL_DigitalHandle pwmPortHandle, int32_t* status);
double HAL_GetPWMSpeed(HAL_DigitalHandle pwmPortHandle, int32_t* status);
double HAL_GetPWMPosition(HAL_DigitalHandle pwmPortHandle, int32_t* status);
void HAL_LatchPWMZero(HAL_DigitalHandle pwmPortHandle, int32_t* status);
void HAL_SetPWMPeriodScale(HAL_DigitalHandle pwmPortHandle, int32_t squelchMask,
int32_t* status);
int32_t HAL_GetLoopTiming(int32_t* status);
#ifdef __cplusplus
}
#endif

36
hal/include/HAL/Ports.h Normal file
View File

@@ -0,0 +1,36 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HAL_GetNumAccumulators(void);
int32_t HAL_GetNumAnalogTriggers(void);
int32_t HAL_GetNumAnalogInputs(void);
int32_t HAL_GetNumAnalogOutputs(void);
int32_t HAL_GetNumCounters(void);
int32_t HAL_GetNumDigitalHeaders(void);
int32_t HAL_GetNumPWMHeaders(void);
int32_t HAL_GetNumDigitalChannels(void);
int32_t HAL_GetNumPWMChannels(void);
int32_t HAL_GetNumDigitalPWMOutputs(void);
int32_t HAL_GetNumEncoders(void);
int32_t HAL_GetNumInterrupts(void);
int32_t HAL_GetNumRelayChannels(void);
int32_t HAL_GetNumRelayHeaders(void);
int32_t HAL_GetNumPCMModules(void);
int32_t HAL_GetNumSolenoidChannels(void);
int32_t HAL_GetNumPDPModules(void);
int32_t HAL_GetNumPDPChannels(void);
#ifdef __cplusplus
}
#endif

34
hal/include/HAL/Power.h Normal file
View File

@@ -0,0 +1,34 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
double HAL_GetVinVoltage(int32_t* status);
double HAL_GetVinCurrent(int32_t* status);
double HAL_GetUserVoltage6V(int32_t* status);
double HAL_GetUserCurrent6V(int32_t* status);
HAL_Bool HAL_GetUserActive6V(int32_t* status);
int32_t HAL_GetUserCurrentFaults6V(int32_t* status);
double HAL_GetUserVoltage5V(int32_t* status);
double HAL_GetUserCurrent5V(int32_t* status);
HAL_Bool HAL_GetUserActive5V(int32_t* status);
int32_t HAL_GetUserCurrentFaults5V(int32_t* status);
double HAL_GetUserVoltage3V3(int32_t* status);
double HAL_GetUserCurrent3V3(int32_t* status);
HAL_Bool HAL_GetUserActive3V3(int32_t* status);
int32_t HAL_GetUserCurrentFaults3V3(int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,21 +0,0 @@
#pragma once
#include <stdint.h>
extern "C"
{
float getVinVoltage(int32_t *status);
float getVinCurrent(int32_t *status);
float getUserVoltage6V(int32_t *status);
float getUserCurrent6V(int32_t *status);
bool getUserActive6V(int32_t *status);
int getUserCurrentFaults6V(int32_t *status);
float getUserVoltage5V(int32_t *status);
float getUserCurrent5V(int32_t *status);
bool getUserActive5V(int32_t *status);
int getUserCurrentFaults5V(int32_t *status);
float getUserVoltage3V3(int32_t *status);
float getUserCurrent3V3(int32_t *status);
bool getUserActive3V3(int32_t *status);
int getUserCurrentFaults3V3(int32_t *status);
}

29
hal/include/HAL/Relay.h Normal file
View File

@@ -0,0 +1,29 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd,
int32_t* status);
void HAL_FreeRelayPort(HAL_RelayHandle relayPortHandle);
HAL_Bool HAL_CheckRelayChannel(int32_t channel);
void HAL_SetRelay(HAL_RelayHandle relayPortHandle, HAL_Bool on,
int32_t* status);
HAL_Bool HAL_GetRelay(HAL_RelayHandle relayPortHandle, int32_t* status);
#ifdef __cplusplus
}
#endif

50
hal/include/HAL/SPI.h Normal file
View File

@@ -0,0 +1,50 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
void HAL_InitializeSPI(int32_t port, int32_t* status);
int32_t HAL_TransactionSPI(int32_t port, uint8_t* dataToSend,
uint8_t* dataReceived, int32_t size);
int32_t HAL_WriteSPI(int32_t port, uint8_t* dataToSend, int32_t sendSize);
int32_t HAL_ReadSPI(int32_t port, uint8_t* buffer, int32_t count);
void HAL_CloseSPI(int32_t port);
void HAL_SetSPISpeed(int32_t port, int32_t speed);
void HAL_SetSPIOpts(int32_t port, HAL_Bool msbFirst, HAL_Bool sampleOnTrailing,
HAL_Bool clkIdleHigh);
void HAL_SetSPIChipSelectActiveHigh(int32_t port, int32_t* status);
void HAL_SetSPIChipSelectActiveLow(int32_t port, int32_t* status);
int32_t HAL_GetSPIHandle(int32_t port);
void HAL_SetSPIHandle(int32_t port, int32_t handle);
void HAL_InitSPIAccumulator(int32_t port, int32_t period, int32_t cmd,
int32_t xferSize, int32_t validMask,
int32_t validValue, int32_t dataShift,
int32_t dataSize, HAL_Bool isSigned,
HAL_Bool bigEndian, int32_t* status);
void HAL_FreeSPIAccumulator(int32_t port, int32_t* status);
void HAL_ResetSPIAccumulator(int32_t port, int32_t* status);
void HAL_SetSPIAccumulatorCenter(int32_t port, int32_t center, int32_t* status);
void HAL_SetSPIAccumulatorDeadband(int32_t port, int32_t deadband,
int32_t* status);
int32_t HAL_GetSPIAccumulatorLastValue(int32_t port, int32_t* status);
int64_t HAL_GetSPIAccumulatorValue(int32_t port, int32_t* status);
int64_t HAL_GetSPIAccumulatorCount(int32_t port, int32_t* status);
double HAL_GetSPIAccumulatorAverage(int32_t port, int32_t* status);
void HAL_GetSPIAccumulatorOutput(int32_t port, int64_t* value, int64_t* count,
int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,21 +0,0 @@
#pragma once
#include "cpp/priority_condition_variable.h"
#include "cpp/priority_mutex.h"
typedef priority_mutex* MUTEX_ID;
typedef priority_condition_variable* MULTIWAIT_ID;
typedef priority_condition_variable::native_handle_type NATIVE_MULTIWAIT_ID;
extern "C" {
MUTEX_ID initializeMutexNormal();
void deleteMutex(MUTEX_ID sem);
void takeMutex(MUTEX_ID sem);
bool tryTakeMutex(MUTEX_ID sem);
void giveMutex(MUTEX_ID sem);
MULTIWAIT_ID initializeMultiWait();
void deleteMultiWait(MULTIWAIT_ID sem);
void takeMultiWait(MULTIWAIT_ID sem, MUTEX_ID m);
void giveMultiWait(MULTIWAIT_ID sem);
}

View File

@@ -0,0 +1,50 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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>
enum HAL_SerialPort : int32_t {
HAL_SerialPort_Onboard = 0,
HAL_SerialPort_MXP = 1,
HAL_SerialPort_USB1 = 2,
HAL_SerialPort_USB2 = 3
};
#ifdef __cplusplus
extern "C" {
#endif
void HAL_InitializeSerialPort(HAL_SerialPort port, int32_t* status);
void HAL_SetSerialBaudRate(HAL_SerialPort port, int32_t baud, int32_t* status);
void HAL_SetSerialDataBits(HAL_SerialPort port, int32_t bits, int32_t* status);
void HAL_SetSerialParity(HAL_SerialPort port, int32_t parity, int32_t* status);
void HAL_SetSerialStopBits(HAL_SerialPort port, int32_t stopBits,
int32_t* status);
void HAL_SetSerialWriteMode(HAL_SerialPort port, int32_t mode, int32_t* status);
void HAL_SetSerialFlowControl(HAL_SerialPort port, int32_t flow,
int32_t* status);
void HAL_SetSerialTimeout(HAL_SerialPort port, double timeout, int32_t* status);
void HAL_EnableSerialTermination(HAL_SerialPort port, char terminator,
int32_t* status);
void HAL_DisableSerialTermination(HAL_SerialPort port, int32_t* status);
void HAL_SetSerialReadBufferSize(HAL_SerialPort port, int32_t size,
int32_t* status);
void HAL_SetSerialWriteBufferSize(HAL_SerialPort port, int32_t size,
int32_t* status);
int32_t HAL_GetSerialBytesReceived(HAL_SerialPort port, int32_t* status);
int32_t HAL_ReadSerial(HAL_SerialPort port, char* buffer, int32_t count,
int32_t* status);
int32_t HAL_WriteSerial(HAL_SerialPort port, const char* buffer, int32_t count,
int32_t* status);
void HAL_FlushSerial(HAL_SerialPort port, int32_t* status);
void HAL_ClearSerial(HAL_SerialPort port, int32_t* status);
void HAL_CloseSerial(HAL_SerialPort port, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,25 +0,0 @@
#pragma once
#include <stdint.h>
extern "C"
{
void serialInitializePort(uint8_t port, int32_t *status);
void serialSetBaudRate(uint8_t port, uint32_t baud, int32_t *status);
void serialSetDataBits(uint8_t port, uint8_t bits, int32_t *status);
void serialSetParity(uint8_t port, uint8_t parity, int32_t *status);
void serialSetStopBits(uint8_t port, uint8_t stopBits, int32_t *status);
void serialSetWriteMode(uint8_t port, uint8_t mode, int32_t *status);
void serialSetFlowControl(uint8_t port, uint8_t flow, int32_t *status);
void serialSetTimeout(uint8_t port, float timeout, int32_t *status);
void serialEnableTermination(uint8_t port, char terminator, int32_t *status);
void serialDisableTermination(uint8_t port, int32_t *status);
void serialSetReadBufferSize(uint8_t port, uint32_t size, int32_t *status);
void serialSetWriteBufferSize(uint8_t port, uint32_t size, int32_t *status);
int32_t serialGetBytesReceived(uint8_t port, int32_t *status);
uint32_t serialRead(uint8_t port, char* buffer, int32_t count, int32_t *status);
uint32_t serialWrite(uint8_t port, const char *buffer, int32_t count, int32_t *status);
void serialFlush(uint8_t port, int32_t *status);
void serialClear(uint8_t port, int32_t *status);
void serialClose(uint8_t port, int32_t *status);
}

View File

@@ -0,0 +1,35 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
#ifdef __cplusplus
extern "C" {
#endif
HAL_SolenoidHandle HAL_InitializeSolenoidPort(HAL_PortHandle portHandle,
int32_t* status);
void HAL_FreeSolenoidPort(HAL_SolenoidHandle solenoidPortHandle);
HAL_Bool HAL_CheckSolenoidModule(int32_t module);
HAL_Bool HAL_CheckSolenoidChannel(int32_t channel);
HAL_Bool HAL_GetSolenoid(HAL_SolenoidHandle solenoidPortHandle,
int32_t* status);
int32_t HAL_GetAllSolenoids(int32_t module, int32_t* status);
void HAL_SetSolenoid(HAL_SolenoidHandle solenoidPortHandle, HAL_Bool value,
int32_t* status);
void HAL_SetAllSolenoids(int32_t module, int32_t state, int32_t* status);
int32_t HAL_GetPCMSolenoidBlackList(int32_t module, int32_t* status);
HAL_Bool HAL_GetPCMSolenoidVoltageStickyFault(int32_t module, int32_t* status);
HAL_Bool HAL_GetPCMSolenoidVoltageFault(int32_t module, int32_t* status);
void HAL_ClearAllPCMStickyFaults(int32_t module, int32_t* status);
#ifdef __cplusplus
}
#endif

View File

@@ -1,19 +0,0 @@
#pragma once
#include <stdint.h>
extern "C"
{
void* initializeSolenoidPort(void* port_pointer, int32_t *status);
void freeSolenoidPort(void* solenoid_port_pointer);
bool checkSolenoidModule(uint8_t module);
bool getSolenoid(void* solenoid_port_pointer, int32_t *status);
uint8_t getAllSolenoids(void* solenoid_port_pointer, int32_t *status);
void setSolenoid(void* solenoid_port_pointer, bool value, int32_t *status);
int getPCMSolenoidBlackList(void* solenoid_port_pointer, int32_t *status);
bool getPCMSolenoidVoltageStickyFault(void* solenoid_port_pointer, int32_t *status);
bool getPCMSolenoidVoltageFault(void* solenoid_port_pointer, int32_t *status);
void clearAllPCMStickyFaults_sol(void *solenoid_port_pointer, int32_t *status);
}

View File

@@ -1,40 +0,0 @@
#pragma once
#include <stdint.h>
#include <pthread.h>
#ifndef _FUNCPTR_DEFINED
#define _FUNCPTR_DEFINED
#ifdef __cplusplus
typedef int (*FUNCPTR)(...);
/* ptr to function returning int */
#else
typedef int (*FUNCPTR) (); /* ptr to function returning int */
#endif /* __cplusplus */
#endif /* _FUNCPTR_DEFINED */
#ifndef _STATUS_DEFINED
#define _STATUS_DEFINED
typedef int STATUS;
#endif /* _STATUS_DEFINED */
#ifndef OK
#define OK 0
#endif /* OK */
#ifndef ERROR
#define ERROR (-1)
#endif /* ERROR */
#define NULL_TASK NULL
typedef pthread_t* TASK;
extern "C" {
// Note: These constants used to be declared extern and were defined in
// Task.cpp. This caused issues with the JNI bindings for java, and so the
// instantiations were moved here.
const int32_t HAL_taskLib_ILLEGAL_PRIORITY = 22; // 22 is EINVAL
STATUS verifyTaskID(TASK task);
STATUS setTaskPriority(TASK task, int priority); // valid priority [1..99]
STATUS getTaskPriority(TASK task, int* priority);
}

28
hal/include/HAL/Threads.h Normal file
View File

@@ -0,0 +1,28 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "HAL/Types.h"
#ifdef _WIN32
#include <windows.h>
#define NativeThreadHandle const HANDLE*
#else
#include <pthread.h>
#define NativeThreadHandle const pthread_t*
#endif
extern "C" {
int32_t HAL_GetThreadPriority(NativeThreadHandle handle, HAL_Bool* isRealTime,
int32_t* status);
int32_t HAL_GetCurrentThreadPriority(HAL_Bool* isRealTime, int32_t* status);
HAL_Bool HAL_SetThreadPriority(NativeThreadHandle handle, HAL_Bool realTime,
int32_t priority, int32_t* status);
HAL_Bool HAL_SetCurrentThreadPriority(HAL_Bool realTime, int32_t priority,
int32_t* status);
}

46
hal/include/HAL/Types.h Normal file
View File

@@ -0,0 +1,46 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#pragma once
#include <stdint.h>
#define HAL_kInvalidHandle 0
typedef int32_t HAL_Handle;
typedef HAL_Handle HAL_PortHandle;
typedef HAL_Handle HAL_AnalogInputHandle;
typedef HAL_Handle HAL_AnalogOutputHandle;
typedef HAL_Handle HAL_AnalogTriggerHandle;
typedef HAL_Handle HAL_CompressorHandle;
typedef HAL_Handle HAL_CounterHandle;
typedef HAL_Handle HAL_DigitalHandle;
typedef HAL_Handle HAL_DigitalPWMHandle;
typedef HAL_Handle HAL_EncoderHandle;
typedef HAL_Handle HAL_FPGAEncoderHandle;
typedef HAL_Handle HAL_GyroHandle;
typedef HAL_Handle HAL_InterruptHandle;
typedef HAL_Handle HAL_NotifierHandle;
typedef HAL_Handle HAL_RelayHandle;
typedef HAL_Handle HAL_SolenoidHandle;
typedef int32_t HAL_Bool;

View File

@@ -1,13 +0,0 @@
#pragma once
#include <stdint.h>
extern "C"
{
extern const int32_t HAL_NO_WAIT;
extern const int32_t HAL_WAIT_FOREVER;
void delayTicks(int32_t ticks);
void delayMillis(double ms);
void delaySeconds(double s);
}

111
hal/include/HAL/cpp/Log.h Normal file
View File

@@ -0,0 +1,111 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
inline std::string NowTime();
enum TLogLevel {
logNONE,
logERROR,
logWARNING,
logINFO,
logDEBUG,
logDEBUG1,
logDEBUG2,
logDEBUG3,
logDEBUG4
};
class Log {
public:
Log();
virtual ~Log();
std::ostringstream& Get(TLogLevel level = logINFO);
public:
static TLogLevel& ReportingLevel();
static std::string ToString(TLogLevel level);
static TLogLevel FromString(const std::string& level);
protected:
std::ostringstream os;
private:
Log(const Log&);
Log& operator=(const Log&);
};
inline Log::Log() {}
inline std::ostringstream& Log::Get(TLogLevel level) {
os << "- " << NowTime();
os << " " << ToString(level) << ": ";
os << std::string(level > logDEBUG ? level - logDEBUG : 0, '\t');
return os;
}
inline Log::~Log() {
os << std::endl;
std::cerr << os.str();
}
inline TLogLevel& Log::ReportingLevel() {
static TLogLevel reportingLevel = logDEBUG4;
return reportingLevel;
}
inline std::string Log::ToString(TLogLevel level) {
static const char* const buffer[] = {"NONE", "ERROR", "WARNING",
"INFO", "DEBUG", "DEBUG1",
"DEBUG2", "DEBUG3", "DEBUG4"};
return buffer[level];
}
inline TLogLevel Log::FromString(const std::string& level) {
if (level == "DEBUG4") return logDEBUG4;
if (level == "DEBUG3") return logDEBUG3;
if (level == "DEBUG2") return logDEBUG2;
if (level == "DEBUG1") return logDEBUG1;
if (level == "DEBUG") return logDEBUG;
if (level == "INFO") return logINFO;
if (level == "WARNING") return logWARNING;
if (level == "ERROR") return logERROR;
if (level == "NONE") return logNONE;
Log().Get(logWARNING) << "Unknown logging level '" << level
<< "'. Using INFO level as default.";
return logINFO;
}
typedef Log FILELog;
#define FILE_LOG(level) \
if (level > FILELog::ReportingLevel()) \
; \
else \
Log().Get(level)
inline std::string NowTime() {
std::stringstream ss;
ss << std::setfill('0') << std::setw(2);
using namespace std::chrono;
auto now = system_clock::now().time_since_epoch();
ss << duration_cast<hours>(now).count() % 24 << ":"
<< duration_cast<minutes>(now).count() % 60 << ":"
<< duration_cast<seconds>(now).count() % 60 << "."
<< duration_cast<milliseconds>(now).count() % 1000;
return ss.str();
}

View File

@@ -1,46 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#pragma once
#include "../Errors.hpp"
#include "HAL/cpp/priority_mutex.h"
#include <stdint.h>
#include <vector>
// TODO: Replace this with something appropriate to avoid conflicts with
// wpilibC++ Resource class (which performs an essentially identical function).
namespace hal {
/**
* The Resource class is a convenient way to track allocated resources.
* It tracks them as indicies in the range [0 .. elements - 1].
* E.g. the library uses this to track hardware channel allocation.
*
* The Resource class does not allocate the hardware channels or other
* resources; it just tracks which indices were marked in use by
* Allocate and not yet freed by Free.
*/
class Resource
{
public:
Resource(const Resource&) = delete;
Resource& operator=(const Resource&) = delete;
explicit Resource(uint32_t size);
virtual ~Resource() = default;
static void CreateResourceObject(Resource **r, uint32_t elements);
uint32_t Allocate(const char *resourceDesc);
uint32_t Allocate(uint32_t index, const char *resourceDesc);
void Free(uint32_t index);
private:
std::vector<bool> m_isAllocated;
priority_recursive_mutex m_allocateLock;
static priority_recursive_mutex m_createLock;
};
} // namespace hal

View File

@@ -0,0 +1,41 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <condition_variable>
#include "HAL/cpp/priority_mutex.h"
#include "support/deprecated.h"
class WPI_DEPRECATED(
"Semaphore scheduled for removal in 2018. Recommended to replace with a "
"std::mutex and std::condition_variable") Semaphore {
public:
explicit Semaphore(int32_t count = 0);
Semaphore(Semaphore&&);
Semaphore& operator=(Semaphore&&);
void give();
void take();
// @return true if semaphore was locked successfully. false if not.
bool tryTake();
static const int32_t kNoWait = 0;
static const int32_t kWaitForever = -1;
static const int32_t kEmpty = 0;
static const int32_t kFull = 1;
private:
priority_mutex m_mutex;
std::condition_variable_any m_condition;
int32_t m_count = 0;
};

View File

@@ -1,30 +0,0 @@
#pragma once
#include <cstdint>
#include <condition_variable>
#include "HAL/cpp/priority_mutex.h"
class Semaphore {
public:
explicit Semaphore(uint32_t count = 0);
Semaphore(Semaphore&&);
Semaphore& operator=(Semaphore&&);
void give();
void take();
// @return true if semaphore was locked successfully. false if not.
bool tryTake();
static const int32_t kNoWait = 0;
static const int32_t kWaitForever = -1;
static const uint32_t kEmpty = 0;
static const uint32_t kFull = 1;
private:
priority_mutex m_mutex;
std::condition_variable_any m_condition;
uint32_t m_count = 0;
};

View File

@@ -0,0 +1,51 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <string>
#include <vector>
#include "HAL/SerialPort.h"
#include "HAL/cpp/priority_mutex.h"
#include "llvm/SmallString.h"
#include "llvm/SmallVector.h"
namespace hal {
class SerialHelper {
public:
SerialHelper();
std::string GetVISASerialPortName(HAL_SerialPort port, int32_t* status);
std::string GetOSSerialPortName(HAL_SerialPort port, int32_t* status);
std::vector<std::string> GetVISASerialPortList(int32_t* status);
std::vector<std::string> GetOSSerialPortList(int32_t* status);
private:
void SortHubPathVector();
void CoiteratedSort(llvm::SmallVectorImpl<llvm::SmallString<16>>& vec);
void QueryHubPaths(int32_t* status);
int32_t GetIndexForPort(HAL_SerialPort port, int32_t* status);
// Vectors to hold data before sorting.
// Note we will most likely have at max 2 instances, and the longest string
// is around 12, so these should never touch the heap;
llvm::SmallVector<llvm::SmallString<16>, 4> m_visaResource;
llvm::SmallVector<llvm::SmallString<16>, 4> m_osResource;
llvm::SmallVector<llvm::SmallString<16>, 4> m_unsortedHubPath;
llvm::SmallVector<llvm::SmallString<16>, 4> m_sortedHubPath;
int32_t m_resourceHandle;
static priority_mutex m_nameMutex;
static std::string m_usbNames[2];
};
} // namespace hal

View File

@@ -0,0 +1,47 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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
// Define make_unique for C++11-only compilers
#if __cplusplus == 201103L
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
namespace std {
template <class T>
struct _Unique_if {
typedef unique_ptr<T> _Single_object;
};
template <class T>
struct _Unique_if<T[]> {
typedef unique_ptr<T[]> _Unknown_bound;
};
template <class T, size_t N>
struct _Unique_if<T[N]> {
typedef void _Known_bound;
};
template <class T, class... Args>
typename _Unique_if<T>::_Single_object make_unique(Args&&... args) {
return unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <class T>
typename _Unique_if<T>::_Unknown_bound make_unique(size_t n) {
typedef typename remove_extent<T>::type U;
return unique_ptr<T>(new U[n]());
}
template <class T, class... Args>
typename _Unique_if<T>::_Known_bound make_unique(Args&&...) = delete;
} // namespace std
#endif

View File

@@ -1,5 +1,5 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
@@ -18,10 +18,12 @@
#include <condition_variable>
#include <memory>
#include <utility>
#include "priority_mutex.h"
class priority_condition_variable {
typedef std::chrono::system_clock clock_t;
typedef std::chrono::system_clock clock;
public:
typedef std::condition_variable::native_handle_type native_handle_type;
@@ -30,7 +32,8 @@ class priority_condition_variable {
~priority_condition_variable() = default;
priority_condition_variable(const priority_condition_variable&) = delete;
priority_condition_variable& operator=(const priority_condition_variable&) = delete;
priority_condition_variable& operator=(const priority_condition_variable&) =
delete;
void notify_one() noexcept {
std::lock_guard<std::mutex> lock(*m_mutex);
@@ -42,7 +45,7 @@ class priority_condition_variable {
m_cond.notify_all();
}
template<typename Lock>
template <typename Lock>
void wait(Lock& _lock) {
std::shared_ptr<std::mutex> _mutex = m_mutex;
std::unique_lock<std::mutex> my_lock(*_mutex);
@@ -54,14 +57,16 @@ class priority_condition_variable {
m_cond.wait(my_lock2);
}
template<typename Lock, typename Predicate>
template <typename Lock, typename Predicate>
void wait(Lock& lock, Predicate p) {
while (!p()) { wait(lock); }
while (!p()) {
wait(lock);
}
}
template<typename Lock, typename Clock, typename Duration>
std::cv_status wait_until(Lock& _lock,
const std::chrono::time_point<Clock, Duration>& atime) {
template <typename Lock, typename Clock, typename Duration>
std::cv_status wait_until(
Lock& _lock, const std::chrono::time_point<Clock, Duration>& atime) {
std::shared_ptr<std::mutex> _mutex = m_mutex;
std::unique_lock<std::mutex> my_lock(*_mutex);
Unlock<Lock> unlock(_lock);
@@ -72,9 +77,11 @@ class priority_condition_variable {
return m_cond.wait_until(my_lock2, atime);
}
template<typename Lock, typename Clock, typename Duration, typename Predicate>
template <typename Lock, typename Clock, typename Duration,
typename Predicate>
bool wait_until(Lock& lock,
const std::chrono::time_point<Clock, Duration>& atime, Predicate p) {
const std::chrono::time_point<Clock, Duration>& atime,
Predicate p) {
while (!p()) {
if (wait_until(lock, atime) == std::cv_status::timeout) {
return p();
@@ -83,35 +90,36 @@ class priority_condition_variable {
return true;
}
template<typename Lock, typename Rep, typename Period>
std::cv_status wait_for(Lock& lock, const std::chrono::duration<Rep, Period>& rtime) {
return wait_until(lock, clock_t::now() + rtime);
template <typename Lock, typename Rep, typename Period>
std::cv_status wait_for(Lock& lock,
const std::chrono::duration<Rep, Period>& rtime) {
return wait_until(lock, clock::now() + rtime);
}
template<typename Lock, typename Rep, typename Period, typename Predicate>
template <typename Lock, typename Rep, typename Period, typename Predicate>
bool wait_for(Lock& lock, const std::chrono::duration<Rep, Period>& rtime,
Predicate p) {
return wait_until(lock, clock_t::now() + rtime, std::move(p));
Predicate p) {
return wait_until(lock, clock::now() + rtime, std::move(p));
}
native_handle_type native_handle() {
return m_cond.native_handle();
}
native_handle_type native_handle() { return m_cond.native_handle(); }
private:
std::condition_variable m_cond;
std::shared_ptr<std::mutex> m_mutex;
// scoped unlock - unlocks in ctor, re-locks in dtor
template<typename Lock>
template <typename Lock>
struct Unlock {
explicit Unlock(Lock& lk) : m_lock(lk) { lk.unlock(); }
~Unlock() /*noexcept(false)*/ {
if (std::uncaught_exception()) {
try { m_lock.lock(); } catch(...) {}
}
else {
try {
m_lock.lock();
} catch (...) {
}
} else {
m_lock.lock();
}
}

View File

@@ -1,5 +1,5 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
@@ -10,22 +10,22 @@
// Allows usage with std::lock_guard without including <mutex> separately
#include <mutex>
#ifdef FRC_SIMULATOR
#if defined(FRC_SIMULATOR) || defined(_WIN32)
// We do not want to use pthreads if in the simulator; however, in the
// simulator, we do not care about priority inversion.
typedef std::mutex priority_mutex;
typedef std::recursive_mutex priority_recursive_mutex;
#else // Covers rest of file.
#else // Covers rest of file.
#include <pthread.h>
class priority_recursive_mutex {
public:
typedef pthread_mutex_t *native_handle_type;
typedef pthread_mutex_t* native_handle_type;
constexpr priority_recursive_mutex() noexcept = default;
priority_recursive_mutex(const priority_recursive_mutex &) = delete;
priority_recursive_mutex &operator=(const priority_recursive_mutex &) = delete;
priority_recursive_mutex(const priority_recursive_mutex&) = delete;
priority_recursive_mutex& operator=(const priority_recursive_mutex&) = delete;
// Lock the mutex, blocking until it's available.
void lock();
@@ -36,11 +36,11 @@ class priority_recursive_mutex {
// Tries to lock the mutex.
bool try_lock() noexcept;
pthread_mutex_t *native_handle();
pthread_mutex_t* native_handle();
private:
// Do the equivalent of setting PTHREAD_PRIO_INHERIT and
// PTHREAD_MUTEX_RECURSIVE_NP.
// Do the equivalent of setting PTHREAD_PRIO_INHERIT and
// PTHREAD_MUTEX_RECURSIVE_NP.
#if __WORDSIZE == 64
pthread_mutex_t m_mutex = {
{0, 0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, 0, {0, 0}}};
@@ -52,11 +52,11 @@ class priority_recursive_mutex {
class priority_mutex {
public:
typedef pthread_mutex_t *native_handle_type;
typedef pthread_mutex_t* native_handle_type;
constexpr priority_mutex() noexcept = default;
priority_mutex(const priority_mutex &) = delete;
priority_mutex &operator=(const priority_mutex &) = delete;
priority_mutex(const priority_mutex&) = delete;
priority_mutex& operator=(const priority_mutex&) = delete;
// Lock the mutex, blocking until it's available.
void lock();
@@ -67,16 +67,14 @@ class priority_mutex {
// Tries to lock the mutex.
bool try_lock() noexcept;
pthread_mutex_t *native_handle();
pthread_mutex_t* native_handle();
private:
// Do the equivalent of setting PTHREAD_PRIO_INHERIT.
// Do the equivalent of setting PTHREAD_PRIO_INHERIT.
#if __WORDSIZE == 64
pthread_mutex_t m_mutex = {
{0, 0, 0, 0, 0x20, 0, 0, {0, 0}}};
pthread_mutex_t m_mutex = {{0, 0, 0, 0, 0x20, 0, 0, {0, 0}}};
#else
pthread_mutex_t m_mutex = {
{0, 0, 0, 0x20, 0, {0}}};
pthread_mutex_t m_mutex = {{0, 0, 0, 0x20, 0, {0}}};
#endif
};

View File

@@ -0,0 +1,95 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <array>
#include <memory>
#include "HAL/Errors.h"
#include "HAL/Types.h"
#include "HAL/cpp/make_unique.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
namespace hal {
/**
* The DigitalHandleResource class is a way to track handles. This version
* allows a limited number of handles that are allocated by index.
* The enum value is seperate, as 2 enum values are allowed per handle
* Because they are allocated by index, each individual index holds its own
* mutex, which reduces contention heavily.]
*
* @tparam THandle The Handle Type (Must be typedefed from HAL_Handle)
* @tparam TStruct The struct type held by this resource
* @tparam size The number of resources allowed to be allocated
*
*/
template <typename THandle, typename TStruct, int16_t size>
class DigitalHandleResource {
friend class DigitalHandleResourceTest;
public:
DigitalHandleResource() = default;
DigitalHandleResource(const DigitalHandleResource&) = delete;
DigitalHandleResource& operator=(const DigitalHandleResource&) = delete;
THandle Allocate(int16_t index, HAL_HandleEnum enumValue, int32_t* status);
std::shared_ptr<TStruct> Get(THandle handle, HAL_HandleEnum enumValue);
void Free(THandle handle, HAL_HandleEnum enumValue);
private:
std::array<std::shared_ptr<TStruct>, size> m_structures;
std::array<priority_mutex, size> m_handleMutexes;
};
template <typename THandle, typename TStruct, int16_t size>
THandle DigitalHandleResource<THandle, TStruct, size>::Allocate(
int16_t index, HAL_HandleEnum enumValue, int32_t* status) {
// don't aquire the lock if we can fail early.
if (index < 0 || index >= size) {
*status = RESOURCE_OUT_OF_RANGE;
return HAL_kInvalidHandle;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// check for allocation, otherwise allocate and return a valid handle
if (m_structures[index] != nullptr) {
*status = RESOURCE_IS_ALLOCATED;
return HAL_kInvalidHandle;
}
m_structures[index] = std::make_shared<TStruct>();
return static_cast<THandle>(hal::createHandle(index, enumValue));
}
template <typename THandle, typename TStruct, int16_t size>
std::shared_ptr<TStruct> DigitalHandleResource<THandle, TStruct, size>::Get(
THandle handle, HAL_HandleEnum enumValue) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) {
return nullptr;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// return structure. Null will propogate correctly, so no need to manually
// check.
return m_structures[index];
}
template <typename THandle, typename TStruct, int16_t size>
void DigitalHandleResource<THandle, TStruct, size>::Free(
THandle handle, HAL_HandleEnum enumValue) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) return;
// lock and deallocated handle
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
m_structures[index].reset();
}
} // namespace hal

View File

@@ -0,0 +1,98 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Types.h"
/* General Handle Data Layout
* Bits 0-15: Handle Index
* Bits 16-23: Unused
* Bits 24-30: Handle Type
* Bit 31: 1 if handle error, 0 if no error
*
* Other specialized handles will use different formats, however Bits 24-31 are
* always reserved for type and error handling.
*/
namespace hal {
constexpr int16_t InvalidHandleIndex = -1;
enum class HAL_HandleEnum {
Undefined = 0,
DIO = 1,
Port = 2,
Notifier = 3,
Interrupt = 4,
AnalogOutput = 5,
AnalogInput = 6,
AnalogTrigger = 7,
Relay = 8,
PWM = 9,
DigitalPWM = 10,
Counter = 11,
FPGAEncoder = 12,
Encoder = 13,
Compressor = 14,
Solenoid = 15,
AnalogGyro = 16,
Vendor = 17
};
static inline int16_t getHandleIndex(HAL_Handle handle) {
// mask and return last 16 bits
return static_cast<int16_t>(handle & 0xffff);
}
static inline HAL_HandleEnum getHandleType(HAL_Handle handle) {
// mask first 8 bits and cast to enum
return static_cast<HAL_HandleEnum>((handle >> 24) & 0xff);
}
static inline bool isHandleType(HAL_Handle handle, HAL_HandleEnum handleType) {
return handleType == getHandleType(handle);
}
static inline int16_t getHandleTypedIndex(HAL_Handle handle,
HAL_HandleEnum enumType) {
if (!isHandleType(handle, enumType)) return InvalidHandleIndex;
return getHandleIndex(handle);
}
/* specialized functions for Port handle
* Port Handle Data Layout
* Bits 0-7: Channel Number
* Bits 8-15: Module Number
* Bits 16-23: Unused
* Bits 24-30: Handle Type
* Bit 31: 1 if handle error, 0 if no error
*/
// using a 16 bit value so we can store 0-255 and still report error
static inline int16_t getPortHandleChannel(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
return static_cast<uint8_t>(handle & 0xff);
}
// using a 16 bit value so we can store 0-255 and still report error
static inline int16_t getPortHandleModule(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
return static_cast<uint8_t>((handle >> 8) & 0xff);
}
// using a 16 bit value so we can store 0-255 and still report error
static inline int16_t getPortHandleSPIEnable(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
return static_cast<uint8_t>((handle >> 16) & 0xff);
}
HAL_PortHandle createPortHandle(uint8_t channel, uint8_t module);
HAL_PortHandle createPortHandleForSPI(uint8_t channel);
HAL_Handle createHandle(int16_t index, HAL_HandleEnum handleType);
} // namespace hal

View File

@@ -0,0 +1,112 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <vector>
#include "HAL/Errors.h"
#include "HAL/Types.h"
#include "HAL/cpp/make_unique.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
namespace hal {
/**
* The IndexedClassedHandleResource class is a way to track handles. This
* version
* allows a limited number of handles that are allocated by index.
* Because they are allocated by index, each individual index holds its own
* mutex, which reduces contention heavily.]
*
* @tparam THandle The Handle Type (Must be typedefed from HAL_Handle)
* @tparam TStruct The struct type held by this resource
* @tparam size The number of resources allowed to be allocated
* @tparam enumValue The type value stored in the handle
*
*/
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
class IndexedClassedHandleResource {
friend class IndexedClassedHandleResourceTest;
public:
IndexedClassedHandleResource();
IndexedClassedHandleResource(const IndexedClassedHandleResource&) = delete;
IndexedClassedHandleResource& operator=(const IndexedClassedHandleResource&) =
delete;
THandle Allocate(int16_t index, std::shared_ptr<TStruct> toSet,
int32_t* status);
std::shared_ptr<TStruct> Get(THandle handle);
void Free(THandle handle);
private:
// Dynamic array to shrink HAL file size.
std::unique_ptr<std::shared_ptr<TStruct>[]> m_structures;
std::unique_ptr<priority_mutex[]> m_handleMutexes;
};
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
IndexedClassedHandleResource<THandle, TStruct, size,
enumValue>::IndexedClassedHandleResource() {
m_structures = std::make_unique<std::shared_ptr<TStruct>[]>(size);
m_handleMutexes = std::make_unique<priority_mutex[]>(size);
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
THandle
IndexedClassedHandleResource<THandle, TStruct, size, enumValue>::Allocate(
int16_t index, std::shared_ptr<TStruct> toSet, int32_t* status) {
// don't aquire the lock if we can fail early.
if (index < 0 || index >= size) {
*status = RESOURCE_OUT_OF_RANGE;
return HAL_kInvalidHandle;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// check for allocation, otherwise allocate and return a valid handle
if (m_structures[index] != nullptr) {
*status = RESOURCE_IS_ALLOCATED;
return HAL_kInvalidHandle;
}
m_structures[index] = toSet;
return static_cast<THandle>(hal::createHandle(index, enumValue));
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
std::shared_ptr<TStruct> IndexedClassedHandleResource<
THandle, TStruct, size, enumValue>::Get(THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) {
return nullptr;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// return structure. Null will propogate correctly, so no need to manually
// check.
return m_structures[index];
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
void IndexedClassedHandleResource<THandle, TStruct, size, enumValue>::Free(
THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) return;
// lock and deallocated handle
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
m_structures[index].reset();
}
} // namespace hal

View File

@@ -0,0 +1,99 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <array>
#include <memory>
#include "HAL/Errors.h"
#include "HAL/Types.h"
#include "HAL/cpp/make_unique.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
namespace hal {
/**
* The IndexedHandleResource class is a way to track handles. This version
* allows a limited number of handles that are allocated by index.
* Because they are allocated by index, each individual index holds its own
* mutex, which reduces contention heavily.]
*
* @tparam THandle The Handle Type (Must be typedefed from HAL_Handle)
* @tparam TStruct The struct type held by this resource
* @tparam size The number of resources allowed to be allocated
* @tparam enumValue The type value stored in the handle
*
*/
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
class IndexedHandleResource {
friend class IndexedHandleResourceTest;
public:
IndexedHandleResource() = default;
IndexedHandleResource(const IndexedHandleResource&) = delete;
IndexedHandleResource& operator=(const IndexedHandleResource&) = delete;
THandle Allocate(int16_t index, int32_t* status);
std::shared_ptr<TStruct> Get(THandle handle);
void Free(THandle handle);
private:
std::array<std::shared_ptr<TStruct>, size> m_structures;
std::array<priority_mutex, size> m_handleMutexes;
};
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
THandle IndexedHandleResource<THandle, TStruct, size, enumValue>::Allocate(
int16_t index, int32_t* status) {
// don't aquire the lock if we can fail early.
if (index < 0 || index >= size) {
*status = RESOURCE_OUT_OF_RANGE;
return HAL_kInvalidHandle;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// check for allocation, otherwise allocate and return a valid handle
if (m_structures[index] != nullptr) {
*status = RESOURCE_IS_ALLOCATED;
return HAL_kInvalidHandle;
}
m_structures[index] = std::make_shared<TStruct>();
return static_cast<THandle>(hal::createHandle(index, enumValue));
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
std::shared_ptr<TStruct>
IndexedHandleResource<THandle, TStruct, size, enumValue>::Get(THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) {
return nullptr;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// return structure. Null will propogate correctly, so no need to manually
// check.
return m_structures[index];
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
void IndexedHandleResource<THandle, TStruct, size, enumValue>::Free(
THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) return;
// lock and deallocated handle
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
m_structures[index].reset();
}
} // namespace hal

View File

@@ -0,0 +1,101 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <array>
#include <memory>
#include "HAL/Types.h"
#include "HAL/cpp/make_unique.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
namespace hal {
/**
* The LimitedClassedHandleResource class is a way to track handles. This
* version
* allows a limited number of handles that are allocated sequentially.
*
* @tparam THandle The Handle Type (Must be typedefed from HAL_Handle)
* @tparam TStruct The struct type held by this resource
* @tparam size The number of resources allowed to be allocated
* @tparam enumValue The type value stored in the handle
*
*/
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
class LimitedClassedHandleResource {
friend class LimitedClassedHandleResourceTest;
public:
LimitedClassedHandleResource() = default;
LimitedClassedHandleResource(const LimitedClassedHandleResource&) = delete;
LimitedClassedHandleResource& operator=(const LimitedClassedHandleResource&) =
delete;
THandle Allocate(std::shared_ptr<TStruct> toSet);
std::shared_ptr<TStruct> Get(THandle handle);
void Free(THandle handle);
private:
std::array<std::shared_ptr<TStruct>, size> m_structures;
std::array<priority_mutex, size> m_handleMutexes;
priority_mutex m_allocateMutex;
};
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
THandle
LimitedClassedHandleResource<THandle, TStruct, size, enumValue>::Allocate(
std::shared_ptr<TStruct> toSet) {
// globally lock to loop through indices
std::lock_guard<priority_mutex> sync(m_allocateMutex);
int16_t i;
for (i = 0; i < size; i++) {
if (m_structures[i] == nullptr) {
// if a false index is found, grab its specific mutex
// and allocate it.
std::lock_guard<priority_mutex> sync(m_handleMutexes[i]);
m_structures[i] = toSet;
return static_cast<THandle>(createHandle(i, enumValue));
}
}
return HAL_kInvalidHandle;
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
std::shared_ptr<TStruct> LimitedClassedHandleResource<
THandle, TStruct, size, enumValue>::Get(THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) {
return nullptr;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// return structure. Null will propogate correctly, so no need to manually
// check.
return m_structures[index];
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
void LimitedClassedHandleResource<THandle, TStruct, size, enumValue>::Free(
THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) return;
// lock and deallocated handle
std::lock_guard<priority_mutex> sync(m_allocateMutex);
std::lock_guard<priority_mutex> lock(m_handleMutexes[index]);
m_structures[index].reset();
}
} // namespace hal

View File

@@ -0,0 +1,97 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <array>
#include <memory>
#include "HAL/Types.h"
#include "HAL/cpp/make_unique.h"
#include "HAL/cpp/priority_mutex.h"
#include "HandlesInternal.h"
namespace hal {
/**
* The LimitedHandleResource class is a way to track handles. This version
* allows a limited number of handles that are allocated sequentially.
*
* @tparam THandle The Handle Type (Must be typedefed from HAL_Handle)
* @tparam TStruct The struct type held by this resource
* @tparam size The number of resources allowed to be allocated
* @tparam enumValue The type value stored in the handle
*
*/
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
class LimitedHandleResource {
friend class LimitedHandleResourceTest;
public:
LimitedHandleResource() = default;
LimitedHandleResource(const LimitedHandleResource&) = delete;
LimitedHandleResource& operator=(const LimitedHandleResource&) = delete;
THandle Allocate();
std::shared_ptr<TStruct> Get(THandle handle);
void Free(THandle handle);
private:
std::array<std::shared_ptr<TStruct>, size> m_structures;
std::array<priority_mutex, size> m_handleMutexes;
priority_mutex m_allocateMutex;
};
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
THandle LimitedHandleResource<THandle, TStruct, size, enumValue>::Allocate() {
// globally lock to loop through indices
std::lock_guard<priority_mutex> sync(m_allocateMutex);
int16_t i;
for (i = 0; i < size; i++) {
if (m_structures[i] == nullptr) {
// if a false index is found, grab its specific mutex
// and allocate it.
std::lock_guard<priority_mutex> sync(m_handleMutexes[i]);
m_structures[i] = std::make_shared<TStruct>();
return static_cast<THandle>(createHandle(i, enumValue));
}
}
return HAL_kInvalidHandle;
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
std::shared_ptr<TStruct>
LimitedHandleResource<THandle, TStruct, size, enumValue>::Get(THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) {
return nullptr;
}
std::lock_guard<priority_mutex> sync(m_handleMutexes[index]);
// return structure. Null will propogate correctly, so no need to manually
// check.
return m_structures[index];
}
template <typename THandle, typename TStruct, int16_t size,
HAL_HandleEnum enumValue>
void LimitedHandleResource<THandle, TStruct, size, enumValue>::Free(
THandle handle) {
// get handle index, and fail early if index out of range or wrong handle
int16_t index = getHandleTypedIndex(handle, enumValue);
if (index < 0 || index >= size) return;
// lock and deallocated handle
std::lock_guard<priority_mutex> sync(m_allocateMutex);
std::lock_guard<priority_mutex> lock(m_handleMutexes[index]);
m_structures[index].reset();
}
} // namespace hal

View File

@@ -0,0 +1,88 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2017. All Rights Reserved. */
/* Open Source Software - may be 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 <vector>
#include "HAL/Types.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
namespace hal {
/**
* The UnlimitedHandleResource class is a way to track handles. This version
* allows an unlimted number of handles that are allocated sequentially. When
* possible, indices are reused to save memory usage and keep the array length
* down.
* However, automatic array management has not been implemented, but might be in
* the future.
* Because we have to loop through the allocator, we must use a global mutex.
* @tparam THandle The Handle Type (Must be typedefed from HAL_Handle)
* @tparam TStruct The struct type held by this resource
* @tparam enumValue The type value stored in the handle
*
*/
template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
class UnlimitedHandleResource {
friend class UnlimitedHandleResourceTest;
public:
UnlimitedHandleResource() = default;
UnlimitedHandleResource(const UnlimitedHandleResource&) = delete;
UnlimitedHandleResource& operator=(const UnlimitedHandleResource&) = delete;
THandle Allocate(std::shared_ptr<TStruct> structure);
std::shared_ptr<TStruct> Get(THandle handle);
void Free(THandle handle);
private:
std::vector<std::shared_ptr<TStruct>> m_structures;
priority_mutex m_handleMutex;
};
template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
THandle UnlimitedHandleResource<THandle, TStruct, enumValue>::Allocate(
std::shared_ptr<TStruct> structure) {
std::lock_guard<priority_mutex> sync(m_handleMutex);
size_t i;
for (i = 0; i < m_structures.size(); i++) {
if (m_structures[i] == nullptr) {
m_structures[i] = structure;
return static_cast<THandle>(createHandle(i, enumValue));
}
}
if (i >= INT16_MAX) return HAL_kInvalidHandle;
m_structures.push_back(structure);
return static_cast<THandle>(createHandle(static_cast<int16_t>(i), enumValue));
}
template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
std::shared_ptr<TStruct>
UnlimitedHandleResource<THandle, TStruct, enumValue>::Get(THandle handle) {
int16_t index = getHandleTypedIndex(handle, enumValue);
std::lock_guard<priority_mutex> sync(m_handleMutex);
if (index < 0 || index >= static_cast<int16_t>(m_structures.size()))
return nullptr;
return m_structures[index];
}
template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
void UnlimitedHandleResource<THandle, TStruct, enumValue>::Free(
THandle handle) {
int16_t index = getHandleTypedIndex(handle, enumValue);
std::lock_guard<priority_mutex> sync(m_handleMutex);
if (index < 0 || index >= static_cast<int16_t>(m_structures.size())) return;
m_structures[index].reset();
}
} // namespace hal

View File

@@ -1,119 +0,0 @@
#pragma once
#include <sstream>
#include <iomanip>
#include <string>
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#endif
inline std::string NowTime();
enum TLogLevel {logNONE, logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4};
class Log
{
public:
Log();
virtual ~Log();
std::ostringstream& Get(TLogLevel level = logINFO);
public:
static TLogLevel& ReportingLevel();
static std::string ToString(TLogLevel level);
static TLogLevel FromString(const std::string& level);
protected:
std::ostringstream os;
private:
Log(const Log&);
Log& operator =(const Log&);
};
inline Log::Log()
{
}
inline std::ostringstream& Log::Get(TLogLevel level)
{
os << "- " << NowTime();
os << " " << ToString(level) << ": ";
os << std::string(level > logDEBUG ? level - logDEBUG : 0, '\t');
return os;
}
inline Log::~Log()
{
os << std::endl;
fprintf(stderr, "%s", os.str().c_str());
fflush(stderr);
}
inline TLogLevel& Log::ReportingLevel()
{
static TLogLevel reportingLevel = logDEBUG4;
return reportingLevel;
}
inline std::string Log::ToString(TLogLevel level)
{
static const char* const buffer[] = {"NONE", "ERROR", "WARNING", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"};
return buffer[level];
}
inline TLogLevel Log::FromString(const std::string& level)
{
if (level == "DEBUG4")
return logDEBUG4;
if (level == "DEBUG3")
return logDEBUG3;
if (level == "DEBUG2")
return logDEBUG2;
if (level == "DEBUG1")
return logDEBUG1;
if (level == "DEBUG")
return logDEBUG;
if (level == "INFO")
return logINFO;
if (level == "WARNING")
return logWARNING;
if (level == "ERROR")
return logERROR;
if (level == "NONE")
return logNONE;
Log().Get(logWARNING) << "Unknown logging level '" << level << "'. Using INFO level as default.";
return logINFO;
}
typedef Log FILELog;
#define FILE_LOG(level) \
if (level > FILELog::ReportingLevel()) ; \
else Log().Get(level)
#ifdef _WIN32
inline std::string NowTime()
{
SYSTEMTIME st;
GetLocalTime(&st);
char result[100] = {0};
sprintf(result, "%d:%d:%d.%d", st.wHour , st.wMinute , st.wSecond , st.wMilliseconds);
return result;
}
#else
inline std::string NowTime()
{
char buffer[11];
time_t t;
time(&t);
tm * r = gmtime(&t);
strftime(buffer, sizeof(buffer), "%H:%M:%S", r);
struct timeval tv;
gettimeofday(&tv, 0);
char result[100] = {0};
sprintf(result, "%s.%03ld", buffer, (long)tv.tv_usec / 1000);
return result;
}
#endif

View File

@@ -16,6 +16,13 @@ public:
*/
CTR_Code SetSolenoid(unsigned char idx, bool en);
/* Set all PCM solenoid states
*
* @Return - CTR_Code - Error code (if any) for setting solenoids
* @Param - state Bitfield to set all solenoids to
*/
CTR_Code SetAllSolenoids(UINT8 state);
/* Enables PCM Closed Loop Control of Compressor via pressure switch
* @Return - CTR_Code - Error code (if any) for setting solenoid
* @Param - en - Enable / Disable Closed Loop Control
@@ -192,6 +199,7 @@ public:
extern "C" {
void * c_PCM_Init(void);
CTR_Code c_SetSolenoid(void * handle,unsigned char idx,INT8 param);
CTR_Code c_SetAllSolenoids(void * handle,UINT8 state);
CTR_Code c_SetClosedLoopControl(void * handle,INT8 param);
CTR_Code c_ClearStickyFaults(void * handle,INT8 param);
CTR_Code c_GetSolenoid(void * handle,UINT8 idx,INT8 * status);

View File

@@ -1,245 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Accelerometer.hpp"
#include "ChipObject.h"
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
// The 7-bit I2C address with a 0 "send" bit
static const uint8_t kSendAddress = (0x1c << 1) | 0;
// The 7-bit I2C address with a 1 "receive" bit
static const uint8_t kReceiveAddress = (0x1c << 1) | 1;
static const uint8_t kControlTxRx = 1;
static const uint8_t kControlStart = 2;
static const uint8_t kControlStop = 4;
static tAccel *accel = 0;
static AccelerometerRange accelerometerRange;
// Register addresses
enum Register {
kReg_Status = 0x00,
kReg_OutXMSB = 0x01,
kReg_OutXLSB = 0x02,
kReg_OutYMSB = 0x03,
kReg_OutYLSB = 0x04,
kReg_OutZMSB = 0x05,
kReg_OutZLSB = 0x06,
kReg_Sysmod = 0x0B,
kReg_IntSource = 0x0C,
kReg_WhoAmI = 0x0D,
kReg_XYZDataCfg = 0x0E,
kReg_HPFilterCutoff = 0x0F,
kReg_PLStatus = 0x10,
kReg_PLCfg = 0x11,
kReg_PLCount = 0x12,
kReg_PLBfZcomp = 0x13,
kReg_PLThsReg = 0x14,
kReg_FFMtCfg = 0x15,
kReg_FFMtSrc = 0x16,
kReg_FFMtThs = 0x17,
kReg_FFMtCount = 0x18,
kReg_TransientCfg = 0x1D,
kReg_TransientSrc = 0x1E,
kReg_TransientThs = 0x1F,
kReg_TransientCount = 0x20,
kReg_PulseCfg = 0x21,
kReg_PulseSrc = 0x22,
kReg_PulseThsx = 0x23,
kReg_PulseThsy = 0x24,
kReg_PulseThsz = 0x25,
kReg_PulseTmlt = 0x26,
kReg_PulseLtcy = 0x27,
kReg_PulseWind = 0x28,
kReg_ASlpCount = 0x29,
kReg_CtrlReg1 = 0x2A,
kReg_CtrlReg2 = 0x2B,
kReg_CtrlReg3 = 0x2C,
kReg_CtrlReg4 = 0x2D,
kReg_CtrlReg5 = 0x2E,
kReg_OffX = 0x2F,
kReg_OffY = 0x30,
kReg_OffZ = 0x31
};
extern "C" uint32_t getFPGATime(int32_t *status);
static void writeRegister(Register reg, uint8_t data);
static uint8_t readRegister(Register reg);
/**
* Initialize the accelerometer.
*/
static void initializeAccelerometer() {
int32_t status;
if(!accel) {
accel = tAccel::create(&status);
// Enable I2C
accel->writeCNFG(1, &status);
// Set the counter to 100 kbps
accel->writeCNTR(213, &status);
// The device identification number should be 0x2a
assert(readRegister(kReg_WhoAmI) == 0x2a);
}
}
static void writeRegister(Register reg, uint8_t data) {
int32_t status = 0;
uint32_t initialTime;
accel->writeADDR(kSendAddress, &status);
// Send a start transmit/receive message with the register address
accel->writeCNTL(kControlStart | kControlTxRx, &status);
accel->writeDATO(reg, &status);
accel->strobeGO(&status);
// Execute and wait until it's done (up to a millisecond)
initialTime = getFPGATime(&status);
while(accel->readSTAT(&status) & 1) {
if(getFPGATime(&status) > initialTime + 1000) break;
}
// Send a stop transmit/receive message with the data
accel->writeCNTL(kControlStop | kControlTxRx, &status);
accel->writeDATO(data, &status);
accel->strobeGO(&status);
// Execute and wait until it's done (up to a millisecond)
initialTime = getFPGATime(&status);
while(accel->readSTAT(&status) & 1) {
if(getFPGATime(&status) > initialTime + 1000) break;
}
fflush(stdout);
}
static uint8_t readRegister(Register reg) {
int32_t status = 0;
uint32_t initialTime;
// Send a start transmit/receive message with the register address
accel->writeADDR(kSendAddress, &status);
accel->writeCNTL(kControlStart | kControlTxRx, &status);
accel->writeDATO(reg, &status);
accel->strobeGO(&status);
// Execute and wait until it's done (up to a millisecond)
initialTime = getFPGATime(&status);
while(accel->readSTAT(&status) & 1) {
if(getFPGATime(&status) > initialTime + 1000) break;
}
// Receive a message with the data and stop
accel->writeADDR(kReceiveAddress, &status);
accel->writeCNTL(kControlStart | kControlStop | kControlTxRx, &status);
accel->strobeGO(&status);
// Execute and wait until it's done (up to a millisecond)
initialTime = getFPGATime(&status);
while(accel->readSTAT(&status) & 1) {
if(getFPGATime(&status) > initialTime + 1000) break;
}
fflush(stdout);
return accel->readDATI(&status);
}
/**
* Convert a 12-bit raw acceleration value into a scaled double in units of
* 1 g-force, taking into account the accelerometer range.
*/
static double unpackAxis(int16_t raw) {
// The raw value is actually 12 bits, not 16, so we need to propogate the
// 2's complement sign bit to the unused 4 bits for this to work with
// negative numbers.
raw <<= 4;
raw >>= 4;
switch(accelerometerRange) {
case kRange_2G: return raw / 1024.0;
case kRange_4G: return raw / 512.0;
case kRange_8G: return raw / 256.0;
default: return 0.0;
}
}
extern "C" {
/**
* Set the accelerometer to active or standby mode. It must be in standby
* mode to change any configuration.
*/
void setAccelerometerActive(bool active) {
initializeAccelerometer();
uint8_t ctrlReg1 = readRegister(kReg_CtrlReg1);
ctrlReg1 &= ~1; // Clear the existing active bit
writeRegister(kReg_CtrlReg1, ctrlReg1 | (active? 1 : 0));
}
/**
* Set the range of values that can be measured (either 2, 4, or 8 g-forces).
* The accelerometer should be in standby mode when this is called.
*/
void setAccelerometerRange(AccelerometerRange range) {
initializeAccelerometer();
accelerometerRange = range;
uint8_t xyzDataCfg = readRegister(kReg_XYZDataCfg);
xyzDataCfg &= ~3; // Clear the existing two range bits
writeRegister(kReg_XYZDataCfg, xyzDataCfg | range);
}
/**
* Get the x-axis acceleration
*
* This is a floating point value in units of 1 g-force
*/
double getAccelerometerX() {
initializeAccelerometer();
int raw = (readRegister(kReg_OutXMSB) << 4) | (readRegister(kReg_OutXLSB) >> 4);
return unpackAxis(raw);
}
/**
* Get the y-axis acceleration
*
* This is a floating point value in units of 1 g-force
*/
double getAccelerometerY() {
initializeAccelerometer();
int raw = (readRegister(kReg_OutYMSB) << 4) | (readRegister(kReg_OutYLSB) >> 4);
return unpackAxis(raw);
}
/**
* Get the z-axis acceleration
*
* This is a floating point value in units of 1 g-force
*/
double getAccelerometerZ() {
initializeAccelerometer();
int raw = (readRegister(kReg_OutZMSB) << 4) | (readRegister(kReg_OutZLSB) >> 4);
return unpackAxis(raw);
}
} // extern "C"

View File

@@ -1,756 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Analog.hpp"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/Port.h"
#include "HAL/HAL.hpp"
#include "ChipObject.h"
#include "HAL/cpp/Resource.hpp"
#include "FRC_NetworkCommunication/AICalibration.h"
#include "FRC_NetworkCommunication/LoadOut.h"
static const long kTimebase = 40000000; ///< 40 MHz clock
static const long kDefaultOversampleBits = 0;
static const long kDefaultAverageBits = 7;
static const float kDefaultSampleRate = 50000.0;
static const uint32_t kAnalogInputPins = 8;
static const uint32_t kAnalogOutputPins = 2;
static const uint32_t kAccumulatorNumChannels = 2;
static const uint32_t kAccumulatorChannels[] = {0, 1};
struct AnalogPort {
Port port;
tAccumulator *accumulator;
};
static bool analogSampleRateSet = false;
static priority_recursive_mutex analogRegisterWindowMutex;
static tAI* analogInputSystem = NULL;
static tAO* analogOutputSystem = NULL;
static uint32_t analogNumChannelsToActivate = 0;
extern "C" {
// Utility methods defined below.
static uint32_t getAnalogNumActiveChannels(int32_t *status);
static uint32_t getAnalogNumChannelsToActivate(int32_t *status);
static void setAnalogNumChannelsToActivate(uint32_t channels);
static bool analogSystemInitialized = false;
/**
* Initialize the analog System.
*/
void initializeAnalog(int32_t *status) {
std::lock_guard<priority_recursive_mutex> sync(analogRegisterWindowMutex);
if (analogSystemInitialized) return;
analogInputSystem = tAI::create(status);
analogOutputSystem = tAO::create(status);
setAnalogNumChannelsToActivate(kAnalogInputPins);
setAnalogSampleRate(kDefaultSampleRate, status);
analogSystemInitialized = true;
}
/**
* Initialize the analog input port using the given port object.
*/
void* initializeAnalogInputPort(void* port_pointer, int32_t *status) {
initializeAnalog(status);
Port* port = (Port*) port_pointer;
// Initialize port structure
AnalogPort* analog_port = new AnalogPort();
analog_port->port = *port;
if (isAccumulatorChannel(analog_port, status)) {
analog_port->accumulator = tAccumulator::create(port->pin, status);
} else analog_port->accumulator = NULL;
// Set default configuration
analogInputSystem->writeScanList(port->pin, port->pin, status);
setAnalogAverageBits(analog_port, kDefaultAverageBits, status);
setAnalogOversampleBits(analog_port, kDefaultOversampleBits, status);
return analog_port;
}
void freeAnalogInputPort(void* analog_port_pointer) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (!port) return;
delete port->accumulator;
delete port;
}
/**
* Initialize the analog output port using the given port object.
*/
void* initializeAnalogOutputPort(void* port_pointer, int32_t *status) {
initializeAnalog(status);
Port* port = (Port*) port_pointer;
// Initialize port structure
AnalogPort* analog_port = new AnalogPort();
analog_port->port = *port;
analog_port->accumulator = NULL;
return analog_port;
}
void freeAnalogOutputPort(void* analog_port_pointer) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (!port) return;
delete port->accumulator;
delete port;
}
/**
* Check that the analog module number is valid.
*
* @return Analog module is valid and present
*/
bool checkAnalogModule(uint8_t module) {
return module == 1;
}
/**
* Check that the analog output channel number is value.
* Verify that the analog channel number is one of the legal channel numbers. Channel numbers
* are 0-based.
*
* @return Analog channel is valid
*/
bool checkAnalogInputChannel(uint32_t pin) {
if (pin < kAnalogInputPins)
return true;
return false;
}
/**
* Check that the analog output channel number is value.
* Verify that the analog channel number is one of the legal channel numbers. Channel numbers
* are 0-based.
*
* @return Analog channel is valid
*/
bool checkAnalogOutputChannel(uint32_t pin) {
if (pin < kAnalogOutputPins)
return true;
return false;
}
void setAnalogOutput(void* analog_port_pointer, double voltage, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
uint16_t rawValue = (uint16_t)(voltage / 5.0 * 0x1000);
if(voltage < 0.0) rawValue = 0;
else if(voltage > 5.0) rawValue = 0x1000;
analogOutputSystem->writeMXP(port->port.pin, rawValue, status);
}
double getAnalogOutput(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
uint16_t rawValue = analogOutputSystem->readMXP(port->port.pin, status);
return rawValue * 5.0 / 0x1000;
}
/**
* Set the sample rate.
*
* This is a global setting for the Athena and effects all channels.
*
* @param samplesPerSecond The number of samples per channel per second.
*/
void setAnalogSampleRate(double samplesPerSecond, int32_t *status) {
// TODO: This will change when variable size scan lists are implemented.
// TODO: Need float comparison with epsilon.
//wpi_assert(!sampleRateSet || GetSampleRate() == samplesPerSecond);
analogSampleRateSet = true;
// Compute the convert rate
uint32_t ticksPerSample = (uint32_t)((float)kTimebase / samplesPerSecond);
uint32_t ticksPerConversion = ticksPerSample / getAnalogNumChannelsToActivate(status);
// ticksPerConversion must be at least 80
if (ticksPerConversion < 80) {
if ((*status) >= 0) *status = SAMPLE_RATE_TOO_HIGH;
ticksPerConversion = 80;
}
// Atomically set the scan size and the convert rate so that the sample rate is constant
tAI::tConfig config;
config.ScanSize = getAnalogNumChannelsToActivate(status);
config.ConvertRate = ticksPerConversion;
analogInputSystem->writeConfig(config, status);
// Indicate that the scan size has been commited to hardware.
setAnalogNumChannelsToActivate(0);
}
/**
* Get the current sample rate.
*
* This assumes one entry in the scan list.
* This is a global setting for the Athena and effects all channels.
*
* @return Sample rate.
*/
float getAnalogSampleRate(int32_t *status) {
uint32_t ticksPerConversion = analogInputSystem->readLoopTiming(status);
uint32_t ticksPerSample = ticksPerConversion * getAnalogNumActiveChannels(status);
return (float)kTimebase / (float)ticksPerSample;
}
/**
* Set the number of averaging bits.
*
* This sets the number of averaging bits. The actual number of averaged samples is 2**bits.
* Use averaging to improve the stability of your measurement at the expense of sampling rate.
* The averaging is done automatically in the FPGA.
*
* @param analog_port_pointer Pointer to the analog port to configure.
* @param bits Number of bits to average.
*/
void setAnalogAverageBits(void* analog_port_pointer, uint32_t bits, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
analogInputSystem->writeAverageBits(port->port.pin, bits, status);
}
/**
* Get the number of averaging bits.
*
* This gets the number of averaging bits from the FPGA. The actual number of averaged samples is 2**bits.
* The averaging is done automatically in the FPGA.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return Bits to average.
*/
uint32_t getAnalogAverageBits(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
uint32_t result = analogInputSystem->readAverageBits(port->port.pin, status);
return result;
}
/**
* Set the number of oversample bits.
*
* This sets the number of oversample bits. The actual number of oversampled values is 2**bits.
* Use oversampling to improve the resolution of your measurements at the expense of sampling rate.
* The oversampling is done automatically in the FPGA.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @param bits Number of bits to oversample.
*/
void setAnalogOversampleBits(void* analog_port_pointer, uint32_t bits, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
analogInputSystem->writeOversampleBits(port->port.pin, bits, status);
}
/**
* Get the number of oversample bits.
*
* This gets the number of oversample bits from the FPGA. The actual number of oversampled values is
* 2**bits. The oversampling is done automatically in the FPGA.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return Bits to oversample.
*/
uint32_t getAnalogOversampleBits(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
uint32_t result = analogInputSystem->readOversampleBits(port->port.pin, status);
return result;
}
/**
* Get a sample straight from the channel on this module.
*
* The sample is a 12-bit value representing the 0V to 5V range of the A/D converter in the module.
* The units are in A/D converter codes. Use GetVoltage() to get the analog value in calibrated units.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return A sample straight from the channel on this module.
*/
int16_t getAnalogValue(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
int16_t value;
if (!checkAnalogInputChannel(port->port.pin)) {
return 0;
}
tAI::tReadSelect readSelect;
readSelect.Channel = port->port.pin;
readSelect.Averaged = false;
{
std::lock_guard<priority_recursive_mutex> sync(analogRegisterWindowMutex);
analogInputSystem->writeReadSelect(readSelect, status);
analogInputSystem->strobeLatchOutput(status);
value = (int16_t) analogInputSystem->readOutput(status);
}
return value;
}
/**
* Get a sample from the output of the oversample and average engine for the channel.
*
* The sample is 12-bit + the value configured in SetOversampleBits().
* The value configured in SetAverageBits() will cause this value to be averaged 2**bits number of samples.
* This is not a sliding window. The sample will not change until 2**(OversamplBits + AverageBits) samples
* have been acquired from the module on this channel.
* Use GetAverageVoltage() to get the analog value in calibrated units.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return A sample from the oversample and average engine for the channel.
*/
int32_t getAnalogAverageValue(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
int32_t value;
if (!checkAnalogInputChannel(port->port.pin)) {
return 0;
}
tAI::tReadSelect readSelect;
readSelect.Channel = port->port.pin;
readSelect.Averaged = true;
{
std::lock_guard<priority_recursive_mutex> sync(analogRegisterWindowMutex);
analogInputSystem->writeReadSelect(readSelect, status);
analogInputSystem->strobeLatchOutput(status);
value = (int32_t) analogInputSystem->readOutput(status);
}
return value;
}
/**
* Get a scaled sample straight from the channel on this module.
*
* The value is scaled to units of Volts using the calibrated scaling data from GetLSBWeight() and GetOffset().
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return A scaled sample straight from the channel on this module.
*/
float getAnalogVoltage(void* analog_port_pointer, int32_t *status) {
int16_t value = getAnalogValue(analog_port_pointer, status);
uint32_t LSBWeight = getAnalogLSBWeight(analog_port_pointer, status);
int32_t offset = getAnalogOffset(analog_port_pointer, status);
float voltage = LSBWeight * 1.0e-9 * value - offset * 1.0e-9;
return voltage;
}
/**
* Get a scaled sample from the output of the oversample and average engine for the channel.
*
* The value is scaled to units of Volts using the calibrated scaling data from GetLSBWeight() and GetOffset().
* Using oversampling will cause this value to be higher resolution, but it will update more slowly.
* Using averaging will cause this value to be more stable, but it will update more slowly.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return A scaled sample from the output of the oversample and average engine for the channel.
*/
float getAnalogAverageVoltage(void* analog_port_pointer, int32_t *status) {
int32_t value = getAnalogAverageValue(analog_port_pointer, status);
uint32_t LSBWeight = getAnalogLSBWeight(analog_port_pointer, status);
int32_t offset = getAnalogOffset(analog_port_pointer, status);
uint32_t oversampleBits = getAnalogOversampleBits(analog_port_pointer, status);
float voltage = ((LSBWeight * 1.0e-9 * value) / (float)(1 << oversampleBits)) - offset * 1.0e-9;
return voltage;
}
/**
* Convert a voltage to a raw value for a specified channel.
*
* This process depends on the calibration of each channel, so the channel
* must be specified.
*
* @todo This assumes raw values. Oversampling not supported as is.
*
* @param analog_port_pointer Pointer to the analog port to use.
* @param voltage The voltage to convert.
* @return The raw value for the channel.
*/
int32_t getAnalogVoltsToValue(void* analog_port_pointer, double voltage, int32_t *status) {
if (voltage > 5.0) {
voltage = 5.0;
*status = VOLTAGE_OUT_OF_RANGE;
}
if (voltage < 0.0) {
voltage = 0.0;
*status = VOLTAGE_OUT_OF_RANGE;
}
uint32_t LSBWeight = getAnalogLSBWeight(analog_port_pointer, status);
int32_t offset = getAnalogOffset(analog_port_pointer, status);
int32_t value = (int32_t) ((voltage + offset * 1.0e-9) / (LSBWeight * 1.0e-9));
return value;
}
/**
* Get the factory scaling least significant bit weight constant.
* The least significant bit weight constant for the channel that was calibrated in
* manufacturing and stored in an eeprom in the module.
*
* Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9)
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return Least significant bit weight.
*/
uint32_t getAnalogLSBWeight(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
uint32_t lsbWeight = FRC_NetworkCommunication_nAICalibration_getLSBWeight(0, port->port.pin, status); // XXX: aiSystemIndex == 0?
return lsbWeight;
}
/**
* Get the factory scaling offset constant.
* The offset constant for the channel that was calibrated in manufacturing and stored
* in an eeprom in the module.
*
* Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9)
*
* @param analog_port_pointer Pointer to the analog port to use.
* @return Offset constant.
*/
int32_t getAnalogOffset(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
int32_t offset = FRC_NetworkCommunication_nAICalibration_getOffset(0, port->port.pin, status); // XXX: aiSystemIndex == 0?
return offset;
}
/**
* Return the number of channels on the module in use.
*
* @return Active channels.
*/
static uint32_t getAnalogNumActiveChannels(int32_t *status) {
uint32_t scanSize = analogInputSystem->readConfig_ScanSize(status);
if (scanSize == 0)
return 8;
return scanSize;
}
/**
* Get the number of active channels.
*
* This is an internal function to allow the atomic update of both the
* number of active channels and the sample rate.
*
* When the number of channels changes, use the new value. Otherwise,
* return the curent value.
*
* @return Value to write to the active channels field.
*/
static uint32_t getAnalogNumChannelsToActivate(int32_t *status) {
if(analogNumChannelsToActivate == 0) return getAnalogNumActiveChannels(status);
return analogNumChannelsToActivate;
}
/**
* Set the number of active channels.
*
* Store the number of active channels to set. Don't actually commit to hardware
* until SetSampleRate().
*
* @param channels Number of active channels.
*/
static void setAnalogNumChannelsToActivate(uint32_t channels) {
analogNumChannelsToActivate = channels;
}
//// Accumulator Stuff
/**
* Is the channel attached to an accumulator.
*
* @return The analog channel is attached to an accumulator.
*/
bool isAccumulatorChannel(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
for (uint32_t i=0; i < kAccumulatorNumChannels; i++) {
if (port->port.pin == kAccumulatorChannels[i]) return true;
}
return false;
}
/**
* Initialize the accumulator.
*/
void initAccumulator(void* analog_port_pointer, int32_t *status) {
setAccumulatorCenter(analog_port_pointer, 0, status);
resetAccumulator(analog_port_pointer, status);
}
/**
* Resets the accumulator to the initial value.
*/
void resetAccumulator(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (port->accumulator == NULL) {
*status = NULL_PARAMETER;
return;
}
port->accumulator->strobeReset(status);
}
/**
* Set the center value of the accumulator.
*
* The center value is subtracted from each A/D value before it is added to the accumulator. This
* is used for the center value of devices like gyros and accelerometers to make integration work
* and to take the device offset into account when integrating.
*
* This center value is based on the output of the oversampled and averaged source from channel 1.
* Because of this, any non-zero oversample bits will affect the size of the value for this field.
*/
void setAccumulatorCenter(void* analog_port_pointer, int32_t center, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (port->accumulator == NULL) {
*status = NULL_PARAMETER;
return;
}
port->accumulator->writeCenter(center, status);
}
/**
* Set the accumulator's deadband.
*/
void setAccumulatorDeadband(void* analog_port_pointer, int32_t deadband, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (port->accumulator == NULL) {
*status = NULL_PARAMETER;
return;
}
port->accumulator->writeDeadband(deadband, status);
}
/**
* Read the accumulated value.
*
* Read the value that has been accumulating on channel 1.
* The accumulator is attached after the oversample and average engine.
*
* @return The 64-bit value accumulated since the last Reset().
*/
int64_t getAccumulatorValue(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (port->accumulator == NULL) {
*status = NULL_PARAMETER;
return 0;
}
int64_t value = port->accumulator->readOutput_Value(status);
return value;
}
/**
* Read the number of accumulated values.
*
* Read the count of the accumulated values since the accumulator was last Reset().
*
* @return The number of times samples from the channel were accumulated.
*/
uint32_t getAccumulatorCount(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (port->accumulator == NULL) {
*status = NULL_PARAMETER;
return 0;
}
return port->accumulator->readOutput_Count(status);
}
/**
* Read the accumulated value and the number of accumulated values atomically.
*
* This function reads the value and count from the FPGA atomically.
* This can be used for averaging.
*
* @param value Pointer to the 64-bit accumulated output.
* @param count Pointer to the number of accumulation cycles.
*/
void getAccumulatorOutput(void* analog_port_pointer, int64_t *value, uint32_t *count, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
if (port->accumulator == NULL) {
*status = NULL_PARAMETER;
return;
}
if (value == NULL || count == NULL) {
*status = NULL_PARAMETER;
return;
}
tAccumulator::tOutput output = port->accumulator->readOutput(status);
*value = output.Value;
*count = output.Count;
}
struct trigger_t {
tAnalogTrigger* trigger;
AnalogPort* port;
uint32_t index;
};
typedef struct trigger_t AnalogTrigger;
static hal::Resource *triggers = NULL;
void* initializeAnalogTrigger(void* port_pointer, uint32_t *index, int32_t *status) {
Port* port = (Port*) port_pointer;
hal::Resource::CreateResourceObject(&triggers, tAnalogTrigger::kNumSystems);
AnalogTrigger* trigger = new AnalogTrigger();
trigger->port = (AnalogPort*) initializeAnalogInputPort(port, status);
trigger->index = triggers->Allocate("Analog Trigger");
*index = trigger->index;
// TODO: if (index == ~0ul) { CloneError(triggers); return; }
trigger->trigger = tAnalogTrigger::create(trigger->index, status);
trigger->trigger->writeSourceSelect_Channel(port->pin, status);
return trigger;
}
void cleanAnalogTrigger(void* analog_trigger_pointer, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
if (!trigger) return;
triggers->Free(trigger->index);
delete trigger->trigger;
freeAnalogInputPort(trigger->port);
delete trigger;
}
void setAnalogTriggerLimitsRaw(void* analog_trigger_pointer, int32_t lower, int32_t upper, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
if (lower > upper) {
*status = ANALOG_TRIGGER_LIMIT_ORDER_ERROR;
}
trigger->trigger->writeLowerLimit(lower, status);
trigger->trigger->writeUpperLimit(upper, status);
}
/**
* Set the upper and lower limits of the analog trigger.
* The limits are given as floating point voltage values.
*/
void setAnalogTriggerLimitsVoltage(void* analog_trigger_pointer, double lower, double upper, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
if (lower > upper) {
*status = ANALOG_TRIGGER_LIMIT_ORDER_ERROR;
}
// TODO: This depends on the averaged setting. Only raw values will work as is.
trigger->trigger->writeLowerLimit(getAnalogVoltsToValue(trigger->port, lower, status), status);
trigger->trigger->writeUpperLimit(getAnalogVoltsToValue(trigger->port, upper, status), status);
}
/**
* Configure the analog trigger to use the averaged vs. raw values.
* If the value is true, then the averaged value is selected for the analog trigger, otherwise
* the immediate value is used.
*/
void setAnalogTriggerAveraged(void* analog_trigger_pointer, bool useAveragedValue, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
if (trigger->trigger->readSourceSelect_Filter(status) != 0) {
*status = INCOMPATIBLE_STATE;
// TODO: wpi_setWPIErrorWithContext(IncompatibleMode, "Hardware does not support average and filtering at the same time.");
}
trigger->trigger->writeSourceSelect_Averaged(useAveragedValue, status);
}
/**
* Configure the analog trigger to use a filtered value.
* The analog trigger will operate with a 3 point average rejection filter. This is designed to
* help with 360 degree pot applications for the period where the pot crosses through zero.
*/
void setAnalogTriggerFiltered(void* analog_trigger_pointer, bool useFilteredValue, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
if (trigger->trigger->readSourceSelect_Averaged(status) != 0) {
*status = INCOMPATIBLE_STATE;
// TODO: wpi_setWPIErrorWithContext(IncompatibleMode, "Hardware does not support average and filtering at the same time.");
}
trigger->trigger->writeSourceSelect_Filter(useFilteredValue, status);
}
/**
* Return the InWindow output of the analog trigger.
* True if the analog input is between the upper and lower limits.
* @return The InWindow output of the analog trigger.
*/
bool getAnalogTriggerInWindow(void* analog_trigger_pointer, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
return trigger->trigger->readOutput_InHysteresis(trigger->index, status) != 0;
}
/**
* Return the TriggerState output of the analog trigger.
* True if above upper limit.
* False if below lower limit.
* If in Hysteresis, maintain previous state.
* @return The TriggerState output of the analog trigger.
*/
bool getAnalogTriggerTriggerState(void* analog_trigger_pointer, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
return trigger->trigger->readOutput_OverLimit(trigger->index, status) != 0;
}
/**
* Get the state of the analog trigger output.
* @return The state of the analog trigger output.
*/
bool getAnalogTriggerOutput(void* analog_trigger_pointer, AnalogTriggerType type, int32_t *status) {
AnalogTrigger* trigger = (AnalogTrigger*) analog_trigger_pointer;
bool result = false;
switch(type) {
case kInWindow:
result = trigger->trigger->readOutput_InHysteresis(trigger->index, status);
break; // XXX: Backport
case kState:
result = trigger->trigger->readOutput_OverLimit(trigger->index, status);
break; // XXX: Backport
case kRisingPulse:
case kFallingPulse:
*status = ANALOG_TRIGGER_PULSE_OUTPUT_ERROR;
return false;
}
return result;
}
//// Float JNA Hack
// Float
int getAnalogSampleRateIntHack(int32_t *status) {
return floatToInt(getAnalogSampleRate(status));
}
int getAnalogVoltageIntHack(void* analog_port_pointer, int32_t *status) {
return floatToInt(getAnalogVoltage(analog_port_pointer, status));
}
int getAnalogAverageVoltageIntHack(void* analog_port_pointer, int32_t *status) {
return floatToInt(getAnalogAverageVoltage(analog_port_pointer, status));
}
// Doubles
void setAnalogSampleRateIntHack(int samplesPerSecond, int32_t *status) {
setAnalogSampleRate(intToFloat(samplesPerSecond), status);
}
int32_t getAnalogVoltsToValueIntHack(void* analog_port_pointer, int voltage, int32_t *status) {
return getAnalogVoltsToValue(analog_port_pointer, intToFloat(voltage), status);
}
void setAnalogTriggerLimitsVoltageIntHack(void* analog_trigger_pointer, int lower, int upper, int32_t *status) {
setAnalogTriggerLimitsVoltage(analog_trigger_pointer, intToFloat(lower), intToFloat(upper), status);
}
} // extern "C"

View File

@@ -1,127 +0,0 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Open Source Software - may be 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 "HAL/Compressor.hpp"
#include "ctre/PCM.h"
#include <iostream>
static const int NUM_MODULE_NUMBERS = 63;
extern PCM *PCM_modules[NUM_MODULE_NUMBERS];
extern void initializePCM(int module);
extern "C" {
void *initializeCompressor(uint8_t module) {
initializePCM(module);
return PCM_modules[module];
}
bool checkCompressorModule(uint8_t module) {
return module < NUM_MODULE_NUMBERS;
}
bool getCompressor(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressor(value);
return value;
}
void setClosedLoopControl(void *pcm_pointer, bool value, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
*status = module->SetClosedLoopControl(value);
}
bool getClosedLoopControl(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetClosedLoopControl(value);
return value;
}
bool getPressureSwitch(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetPressure(value);
return value;
}
float getCompressorCurrent(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
float value;
*status = module->GetCompressorCurrent(value);
return value;
}
bool getCompressorCurrentTooHighFault(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressorCurrentTooHighFault(value);
return value;
}
bool getCompressorCurrentTooHighStickyFault(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressorCurrentTooHighStickyFault(value);
return value;
}
bool getCompressorShortedStickyFault(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressorShortedStickyFault(value);
return value;
}
bool getCompressorShortedFault(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressorShortedFault(value);
return value;
}
bool getCompressorNotConnectedStickyFault(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressorNotConnectedStickyFault(value);
return value;
}
bool getCompressorNotConnectedFault(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
bool value;
*status = module->GetCompressorNotConnectedFault(value);
return value;
}
void clearAllPCMStickyFaults(void *pcm_pointer, int32_t *status) {
PCM *module = (PCM *)pcm_pointer;
*status = module->ClearStickyFaults();
}
} // extern "C"

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __FRC_FPGA_ChipObject_Aliases_h__
#define __FRC_FPGA_ChipObject_Aliases_h__
#define nRuntimeFPGANamespace nFRC_2012_1_6_4
#define nInvariantFPGANamespace nFRC_C0EF_1_1_0
#endif // __FRC_FPGA_ChipObject_Aliases_h__

View File

@@ -1,15 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_C0EF_1_1_0_nInterfaceGlobals_h__
#define __nFRC_C0EF_1_1_0_nInterfaceGlobals_h__
namespace nFPGA
{
namespace nFRC_C0EF_1_1_0
{
extern unsigned int g_currentTargetClass;
}
}
#endif // __nFRC_C0EF_1_1_0_nInterfaceGlobals_h__

View File

@@ -1,73 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_C0EF_1_1_0_AI_h__
#define __nFRC_C0EF_1_1_0_AI_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_C0EF_1_1_0
{
class tAI
{
public:
tAI(){}
virtual ~tAI(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tAI* create(unsigned char sys_index, tRioStatusCode *status);
virtual unsigned char getSystemIndex() = 0;
typedef enum
{
kNumSystems = 2,
} tIfaceConstants;
typedef enum
{
} tCalOK_IfaceConstants;
virtual bool readCalOK(tRioStatusCode *status) = 0;
typedef enum
{
} tDoneTime_IfaceConstants;
virtual unsigned int readDoneTime(tRioStatusCode *status) = 0;
typedef enum
{
kNumOffsetRegisters = 8,
} tOffset_IfaceConstants;
virtual signed int readOffset(unsigned char reg_index, tRioStatusCode *status) = 0;
typedef enum
{
kNumLSBWeightRegisters = 8,
} tLSBWeight_IfaceConstants;
virtual unsigned int readLSBWeight(unsigned char reg_index, tRioStatusCode *status) = 0;
private:
tAI(const tAI&);
void operator=(const tAI&);
};
}
}
#endif // __nFRC_C0EF_1_1_0_AI_h__

View File

@@ -1,69 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_C0EF_1_1_0_Global_h__
#define __nFRC_C0EF_1_1_0_Global_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_C0EF_1_1_0
{
class tGlobal
{
public:
tGlobal(){}
virtual ~tGlobal(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tGlobal* create(tRioStatusCode *status);
typedef enum
{
kNumSystems = 1,
} tIfaceConstants;
typedef enum
{
} tVersion_IfaceConstants;
virtual unsigned short readVersion(tRioStatusCode *status) = 0;
typedef enum
{
} tLocalTime_IfaceConstants;
virtual unsigned int readLocalTime(tRioStatusCode *status) = 0;
typedef enum
{
} tRevision_IfaceConstants;
virtual unsigned int readRevision(tRioStatusCode *status) = 0;
typedef enum
{
} tReserved_IfaceConstants;
virtual unsigned char readReserved(tRioStatusCode *status) = 0;
private:
tGlobal(const tGlobal&);
void operator=(const tGlobal&);
};
}
}
#endif // __nFRC_C0EF_1_1_0_Global_h__

View File

@@ -1,79 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_C0EF_1_1_0_LoadOut_h__
#define __nFRC_C0EF_1_1_0_LoadOut_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_C0EF_1_1_0
{
class tLoadOut
{
public:
tLoadOut(){}
virtual ~tLoadOut(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tLoadOut* create(tRioStatusCode *status);
typedef enum
{
kNumSystems = 1,
} tIfaceConstants;
typedef enum
{
} tReady_IfaceConstants;
virtual bool readReady(tRioStatusCode *status) = 0;
typedef enum
{
} tDoneTime_IfaceConstants;
virtual unsigned int readDoneTime(tRioStatusCode *status) = 0;
typedef enum
{
kNumVendorIDRegisters = 8,
} tVendorID_IfaceConstants;
virtual unsigned short readVendorID(unsigned char reg_index, tRioStatusCode *status) = 0;
typedef enum
{
kNumSerialNumberRegisters = 8,
} tSerialNumber_IfaceConstants;
virtual unsigned int readSerialNumber(unsigned char reg_index, tRioStatusCode *status) = 0;
typedef enum
{
kNumModuleIDRegisters = 8,
} tModuleID_IfaceConstants;
virtual unsigned short readModuleID(unsigned char reg_index, tRioStatusCode *status) = 0;
private:
tLoadOut(const tLoadOut&);
void operator=(const tLoadOut&);
};
}
}
#endif // __nFRC_C0EF_1_1_0_LoadOut_h__

View File

@@ -1,15 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2016_16_1_0_nInterfaceGlobals_h__
#define __nFRC_2016_16_1_0_nInterfaceGlobals_h__
namespace nFPGA
{
namespace nFRC_2016_16_1_0
{
extern unsigned int g_currentTargetClass;
}
}
#endif // __nFRC_2016_16_1_0_nInterfaceGlobals_h__

View File

@@ -1,87 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2016_16_1_0_Accumulator_h__
#define __nFRC_2016_16_1_0_Accumulator_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_2016_16_1_0
{
class tAccumulator
{
public:
tAccumulator(){}
virtual ~tAccumulator(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tAccumulator* create(unsigned char sys_index, tRioStatusCode *status);
virtual unsigned char getSystemIndex() = 0;
typedef enum
{
kNumSystems = 2,
} tIfaceConstants;
typedef
union{
struct{
signed long long Value;
unsigned Count : 32;
};
struct{
unsigned value : 32;
unsigned value2 : 32;
unsigned value3 : 32;
};
} tOutput;
typedef enum
{
} tOutput_IfaceConstants;
virtual tOutput readOutput(tRioStatusCode *status) = 0;
virtual signed long long readOutput_Value(tRioStatusCode *status) = 0;
virtual unsigned int readOutput_Count(tRioStatusCode *status) = 0;
typedef enum
{
} tCenter_IfaceConstants;
virtual void writeCenter(signed int value, tRioStatusCode *status) = 0;
virtual signed int readCenter(tRioStatusCode *status) = 0;
typedef enum
{
} tDeadband_IfaceConstants;
virtual void writeDeadband(signed int value, tRioStatusCode *status) = 0;
virtual signed int readDeadband(tRioStatusCode *status) = 0;
typedef enum
{
} tReset_IfaceConstants;
virtual void strobeReset(tRioStatusCode *status) = 0;
private:
tAccumulator(const tAccumulator&);
void operator=(const tAccumulator&);
};
}
}
#endif // __nFRC_2016_16_1_0_Accumulator_h__

View File

@@ -1,57 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2016_16_1_0_Alarm_h__
#define __nFRC_2016_16_1_0_Alarm_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_2016_16_1_0
{
class tAlarm
{
public:
tAlarm(){}
virtual ~tAlarm(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tAlarm* create(tRioStatusCode *status);
typedef enum
{
kNumSystems = 1,
} tIfaceConstants;
typedef enum
{
} tEnable_IfaceConstants;
virtual void writeEnable(bool value, tRioStatusCode *status) = 0;
virtual bool readEnable(tRioStatusCode *status) = 0;
typedef enum
{
} tTriggerTime_IfaceConstants;
virtual void writeTriggerTime(unsigned int value, tRioStatusCode *status) = 0;
virtual unsigned int readTriggerTime(tRioStatusCode *status) = 0;
private:
tAlarm(const tAlarm&);
void operator=(const tAlarm&);
};
}
}
#endif // __nFRC_2016_16_1_0_Alarm_h__

View File

@@ -1,15 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2012_1_6_4_nInterfaceGlobals_h__
#define __nFRC_2012_1_6_4_nInterfaceGlobals_h__
namespace nFPGA
{
namespace nFRC_2012_1_6_4
{
extern unsigned int g_currentTargetClass;
}
}
#endif // __nFRC_2012_1_6_4_nInterfaceGlobals_h__

View File

@@ -1,149 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2012_1_6_4_AI_h__
#define __nFRC_2012_1_6_4_AI_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_2012_1_6_4
{
class tAI
{
public:
tAI(){}
virtual ~tAI(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tAI* create(unsigned char sys_index, tRioStatusCode *status);
virtual unsigned char getSystemIndex() = 0;
typedef enum
{
kNumSystems = 2,
} tIfaceConstants;
typedef
union{
struct{
#ifdef __vxworks
unsigned Channel : 3;
unsigned Module : 1;
unsigned Averaged : 1;
#else
unsigned Averaged : 1;
unsigned Module : 1;
unsigned Channel : 3;
#endif
};
struct{
unsigned value : 5;
};
} tReadSelect;
typedef
union{
struct{
#ifdef __vxworks
unsigned ScanSize : 3;
unsigned ConvertRate : 26;
#else
unsigned ConvertRate : 26;
unsigned ScanSize : 3;
#endif
};
struct{
unsigned value : 29;
};
} tConfig;
typedef enum
{
} tConfig_IfaceConstants;
virtual void writeConfig(tConfig value, tRioStatusCode *status) = 0;
virtual void writeConfig_ScanSize(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_ConvertRate(unsigned int value, tRioStatusCode *status) = 0;
virtual tConfig readConfig(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_ScanSize(tRioStatusCode *status) = 0;
virtual unsigned int readConfig_ConvertRate(tRioStatusCode *status) = 0;
typedef enum
{
} tLoopTiming_IfaceConstants;
virtual unsigned int readLoopTiming(tRioStatusCode *status) = 0;
typedef enum
{
kNumOversampleBitsElements = 8,
} tOversampleBits_IfaceConstants;
virtual void writeOversampleBits(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readOversampleBits(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
kNumAverageBitsElements = 8,
} tAverageBits_IfaceConstants;
virtual void writeAverageBits(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readAverageBits(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
kNumScanListElements = 8,
} tScanList_IfaceConstants;
virtual void writeScanList(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readScanList(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
} tOutput_IfaceConstants;
virtual signed int readOutput(tRioStatusCode *status) = 0;
typedef enum
{
} tLatchOutput_IfaceConstants;
virtual void strobeLatchOutput(tRioStatusCode *status) = 0;
typedef enum
{
} tReadSelect_IfaceConstants;
virtual void writeReadSelect(tReadSelect value, tRioStatusCode *status) = 0;
virtual void writeReadSelect_Channel(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeReadSelect_Module(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeReadSelect_Averaged(bool value, tRioStatusCode *status) = 0;
virtual tReadSelect readReadSelect(tRioStatusCode *status) = 0;
virtual unsigned char readReadSelect_Channel(tRioStatusCode *status) = 0;
virtual unsigned char readReadSelect_Module(tRioStatusCode *status) = 0;
virtual bool readReadSelect_Averaged(tRioStatusCode *status) = 0;
private:
tAI(const tAI&);
void operator=(const tAI&);
};
}
}
#endif // __nFRC_2012_1_6_4_AI_h__

View File

@@ -1,133 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2012_1_6_4_AnalogTrigger_h__
#define __nFRC_2012_1_6_4_AnalogTrigger_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_2012_1_6_4
{
class tAnalogTrigger
{
public:
tAnalogTrigger(){}
virtual ~tAnalogTrigger(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tAnalogTrigger* create(unsigned char sys_index, tRioStatusCode *status);
virtual unsigned char getSystemIndex() = 0;
typedef enum
{
kNumSystems = 8,
} tIfaceConstants;
typedef
union{
struct{
#ifdef __vxworks
unsigned InHysteresis : 1;
unsigned OverLimit : 1;
unsigned Rising : 1;
unsigned Falling : 1;
#else
unsigned Falling : 1;
unsigned Rising : 1;
unsigned OverLimit : 1;
unsigned InHysteresis : 1;
#endif
};
struct{
unsigned value : 4;
};
} tOutput;
typedef
union{
struct{
#ifdef __vxworks
unsigned Channel : 3;
unsigned Module : 1;
unsigned Averaged : 1;
unsigned Filter : 1;
unsigned FloatingRollover : 1;
signed RolloverLimit : 8;
#else
signed RolloverLimit : 8;
unsigned FloatingRollover : 1;
unsigned Filter : 1;
unsigned Averaged : 1;
unsigned Module : 1;
unsigned Channel : 3;
#endif
};
struct{
unsigned value : 15;
};
} tSourceSelect;
typedef enum
{
} tSourceSelect_IfaceConstants;
virtual void writeSourceSelect(tSourceSelect value, tRioStatusCode *status) = 0;
virtual void writeSourceSelect_Channel(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeSourceSelect_Module(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeSourceSelect_Averaged(bool value, tRioStatusCode *status) = 0;
virtual void writeSourceSelect_Filter(bool value, tRioStatusCode *status) = 0;
virtual void writeSourceSelect_FloatingRollover(bool value, tRioStatusCode *status) = 0;
virtual void writeSourceSelect_RolloverLimit(signed short value, tRioStatusCode *status) = 0;
virtual tSourceSelect readSourceSelect(tRioStatusCode *status) = 0;
virtual unsigned char readSourceSelect_Channel(tRioStatusCode *status) = 0;
virtual unsigned char readSourceSelect_Module(tRioStatusCode *status) = 0;
virtual bool readSourceSelect_Averaged(tRioStatusCode *status) = 0;
virtual bool readSourceSelect_Filter(tRioStatusCode *status) = 0;
virtual bool readSourceSelect_FloatingRollover(tRioStatusCode *status) = 0;
virtual signed short readSourceSelect_RolloverLimit(tRioStatusCode *status) = 0;
typedef enum
{
} tUpperLimit_IfaceConstants;
virtual void writeUpperLimit(signed int value, tRioStatusCode *status) = 0;
virtual signed int readUpperLimit(tRioStatusCode *status) = 0;
typedef enum
{
} tLowerLimit_IfaceConstants;
virtual void writeLowerLimit(signed int value, tRioStatusCode *status) = 0;
virtual signed int readLowerLimit(tRioStatusCode *status) = 0;
typedef enum
{
kNumOutputElements = 8,
} tOutput_IfaceConstants;
virtual tOutput readOutput(unsigned char bitfield_index, tRioStatusCode *status) = 0;
virtual bool readOutput_InHysteresis(unsigned char bitfield_index, tRioStatusCode *status) = 0;
virtual bool readOutput_OverLimit(unsigned char bitfield_index, tRioStatusCode *status) = 0;
virtual bool readOutput_Rising(unsigned char bitfield_index, tRioStatusCode *status) = 0;
virtual bool readOutput_Falling(unsigned char bitfield_index, tRioStatusCode *status) = 0;
private:
tAnalogTrigger(const tAnalogTrigger&);
void operator=(const tAnalogTrigger&);
};
}
}
#endif // __nFRC_2012_1_6_4_AnalogTrigger_h__

View File

@@ -1,219 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2012_1_6_4_Counter_h__
#define __nFRC_2012_1_6_4_Counter_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_2012_1_6_4
{
class tCounter
{
public:
tCounter(){}
virtual ~tCounter(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tCounter* create(unsigned char sys_index, tRioStatusCode *status);
virtual unsigned char getSystemIndex() = 0;
typedef enum
{
kNumSystems = 8,
} tIfaceConstants;
typedef
union{
struct{
#ifdef __vxworks
unsigned Direction : 1;
signed Value : 31;
#else
signed Value : 31;
unsigned Direction : 1;
#endif
};
struct{
unsigned value : 32;
};
} tOutput;
typedef
union{
struct{
#ifdef __vxworks
unsigned UpSource_Channel : 4;
unsigned UpSource_Module : 1;
unsigned UpSource_AnalogTrigger : 1;
unsigned DownSource_Channel : 4;
unsigned DownSource_Module : 1;
unsigned DownSource_AnalogTrigger : 1;
unsigned IndexSource_Channel : 4;
unsigned IndexSource_Module : 1;
unsigned IndexSource_AnalogTrigger : 1;
unsigned IndexActiveHigh : 1;
unsigned UpRisingEdge : 1;
unsigned UpFallingEdge : 1;
unsigned DownRisingEdge : 1;
unsigned DownFallingEdge : 1;
unsigned Mode : 2;
unsigned PulseLengthThreshold : 6;
unsigned Enable : 1;
#else
unsigned Enable : 1;
unsigned PulseLengthThreshold : 6;
unsigned Mode : 2;
unsigned DownFallingEdge : 1;
unsigned DownRisingEdge : 1;
unsigned UpFallingEdge : 1;
unsigned UpRisingEdge : 1;
unsigned IndexActiveHigh : 1;
unsigned IndexSource_AnalogTrigger : 1;
unsigned IndexSource_Module : 1;
unsigned IndexSource_Channel : 4;
unsigned DownSource_AnalogTrigger : 1;
unsigned DownSource_Module : 1;
unsigned DownSource_Channel : 4;
unsigned UpSource_AnalogTrigger : 1;
unsigned UpSource_Module : 1;
unsigned UpSource_Channel : 4;
#endif
};
struct{
unsigned value : 32;
};
} tConfig;
typedef
union{
struct{
#ifdef __vxworks
unsigned Period : 23;
signed Count : 8;
unsigned Stalled : 1;
#else
unsigned Stalled : 1;
signed Count : 8;
unsigned Period : 23;
#endif
};
struct{
unsigned value : 32;
};
} tTimerOutput;
typedef
union{
struct{
#ifdef __vxworks
unsigned StallPeriod : 24;
unsigned AverageSize : 7;
unsigned UpdateWhenEmpty : 1;
#else
unsigned UpdateWhenEmpty : 1;
unsigned AverageSize : 7;
unsigned StallPeriod : 24;
#endif
};
struct{
unsigned value : 32;
};
} tTimerConfig;
typedef enum
{
} tOutput_IfaceConstants;
virtual tOutput readOutput(tRioStatusCode *status) = 0;
virtual bool readOutput_Direction(tRioStatusCode *status) = 0;
virtual signed int readOutput_Value(tRioStatusCode *status) = 0;
typedef enum
{
} tConfig_IfaceConstants;
virtual void writeConfig(tConfig value, tRioStatusCode *status) = 0;
virtual void writeConfig_UpSource_Channel(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_UpSource_Module(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_UpSource_AnalogTrigger(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_DownSource_Channel(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_DownSource_Module(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_DownSource_AnalogTrigger(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_IndexSource_Channel(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_IndexSource_Module(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_IndexSource_AnalogTrigger(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_IndexActiveHigh(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_UpRisingEdge(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_UpFallingEdge(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_DownRisingEdge(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_DownFallingEdge(bool value, tRioStatusCode *status) = 0;
virtual void writeConfig_Mode(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeConfig_PulseLengthThreshold(unsigned short value, tRioStatusCode *status) = 0;
virtual void writeConfig_Enable(bool value, tRioStatusCode *status) = 0;
virtual tConfig readConfig(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_UpSource_Channel(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_UpSource_Module(tRioStatusCode *status) = 0;
virtual bool readConfig_UpSource_AnalogTrigger(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_DownSource_Channel(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_DownSource_Module(tRioStatusCode *status) = 0;
virtual bool readConfig_DownSource_AnalogTrigger(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_IndexSource_Channel(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_IndexSource_Module(tRioStatusCode *status) = 0;
virtual bool readConfig_IndexSource_AnalogTrigger(tRioStatusCode *status) = 0;
virtual bool readConfig_IndexActiveHigh(tRioStatusCode *status) = 0;
virtual bool readConfig_UpRisingEdge(tRioStatusCode *status) = 0;
virtual bool readConfig_UpFallingEdge(tRioStatusCode *status) = 0;
virtual bool readConfig_DownRisingEdge(tRioStatusCode *status) = 0;
virtual bool readConfig_DownFallingEdge(tRioStatusCode *status) = 0;
virtual unsigned char readConfig_Mode(tRioStatusCode *status) = 0;
virtual unsigned short readConfig_PulseLengthThreshold(tRioStatusCode *status) = 0;
virtual bool readConfig_Enable(tRioStatusCode *status) = 0;
typedef enum
{
} tTimerOutput_IfaceConstants;
virtual tTimerOutput readTimerOutput(tRioStatusCode *status) = 0;
virtual unsigned int readTimerOutput_Period(tRioStatusCode *status) = 0;
virtual signed char readTimerOutput_Count(tRioStatusCode *status) = 0;
virtual bool readTimerOutput_Stalled(tRioStatusCode *status) = 0;
typedef enum
{
} tReset_IfaceConstants;
virtual void strobeReset(tRioStatusCode *status) = 0;
typedef enum
{
} tTimerConfig_IfaceConstants;
virtual void writeTimerConfig(tTimerConfig value, tRioStatusCode *status) = 0;
virtual void writeTimerConfig_StallPeriod(unsigned int value, tRioStatusCode *status) = 0;
virtual void writeTimerConfig_AverageSize(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeTimerConfig_UpdateWhenEmpty(bool value, tRioStatusCode *status) = 0;
virtual tTimerConfig readTimerConfig(tRioStatusCode *status) = 0;
virtual unsigned int readTimerConfig_StallPeriod(tRioStatusCode *status) = 0;
virtual unsigned char readTimerConfig_AverageSize(tRioStatusCode *status) = 0;
virtual bool readTimerConfig_UpdateWhenEmpty(tRioStatusCode *status) = 0;
private:
tCounter(const tCounter&);
void operator=(const tCounter&);
};
}
}
#endif // __nFRC_2012_1_6_4_Counter_h__

View File

@@ -1,330 +0,0 @@
// Copyright (c) National Instruments 2008. All Rights Reserved.
// Do Not Edit... this file is generated!
#ifndef __nFRC_2012_1_6_4_DIO_h__
#define __nFRC_2012_1_6_4_DIO_h__
#include "tSystemInterface.h"
namespace nFPGA
{
namespace nFRC_2012_1_6_4
{
class tDIO
{
public:
tDIO(){}
virtual ~tDIO(){}
virtual tSystemInterface* getSystemInterface() = 0;
static tDIO* create(unsigned char sys_index, tRioStatusCode *status);
virtual unsigned char getSystemIndex() = 0;
typedef enum
{
kNumSystems = 2,
} tIfaceConstants;
typedef
union{
struct{
#ifdef __vxworks
unsigned Period : 16;
unsigned MinHigh : 16;
#else
unsigned MinHigh : 16;
unsigned Period : 16;
#endif
};
struct{
unsigned value : 32;
};
} tPWMConfig;
typedef
union{
struct{
#ifdef __vxworks
unsigned RelayFwd : 8;
unsigned RelayRev : 8;
unsigned I2CHeader : 4;
#else
unsigned I2CHeader : 4;
unsigned RelayRev : 8;
unsigned RelayFwd : 8;
#endif
};
struct{
unsigned value : 20;
};
} tSlowValue;
typedef
union{
struct{
#ifdef __vxworks
unsigned Transaction : 1;
unsigned Done : 1;
unsigned Aborted : 1;
unsigned DataReceivedHigh : 24;
#else
unsigned DataReceivedHigh : 24;
unsigned Aborted : 1;
unsigned Done : 1;
unsigned Transaction : 1;
#endif
};
struct{
unsigned value : 27;
};
} tI2CStatus;
typedef
union{
struct{
#ifdef __vxworks
unsigned Address : 8;
unsigned BytesToRead : 3;
unsigned BytesToWrite : 3;
unsigned DataToSendHigh : 16;
unsigned BitwiseHandshake : 1;
#else
unsigned BitwiseHandshake : 1;
unsigned DataToSendHigh : 16;
unsigned BytesToWrite : 3;
unsigned BytesToRead : 3;
unsigned Address : 8;
#endif
};
struct{
unsigned value : 31;
};
} tI2CConfig;
typedef
union{
struct{
#ifdef __vxworks
unsigned PeriodPower : 4;
unsigned OutputSelect_0 : 4;
unsigned OutputSelect_1 : 4;
unsigned OutputSelect_2 : 4;
unsigned OutputSelect_3 : 4;
#else
unsigned OutputSelect_3 : 4;
unsigned OutputSelect_2 : 4;
unsigned OutputSelect_1 : 4;
unsigned OutputSelect_0 : 4;
unsigned PeriodPower : 4;
#endif
};
struct{
unsigned value : 20;
};
} tDO_PWMConfig;
typedef enum
{
kNumFilterSelectElements = 16,
} tFilterSelect_IfaceConstants;
virtual void writeFilterSelect(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readFilterSelect(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
} tI2CDataToSend_IfaceConstants;
virtual void writeI2CDataToSend(unsigned int value, tRioStatusCode *status) = 0;
virtual unsigned int readI2CDataToSend(tRioStatusCode *status) = 0;
typedef enum
{
} tDO_IfaceConstants;
virtual void writeDO(unsigned short value, tRioStatusCode *status) = 0;
virtual unsigned short readDO(tRioStatusCode *status) = 0;
typedef enum
{
kNumFilterPeriodElements = 3,
} tFilterPeriod_IfaceConstants;
virtual void writeFilterPeriod(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readFilterPeriod(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
} tOutputEnable_IfaceConstants;
virtual void writeOutputEnable(unsigned short value, tRioStatusCode *status) = 0;
virtual unsigned short readOutputEnable(tRioStatusCode *status) = 0;
typedef enum
{
} tPulse_IfaceConstants;
virtual void writePulse(unsigned short value, tRioStatusCode *status) = 0;
virtual unsigned short readPulse(tRioStatusCode *status) = 0;
typedef enum
{
} tSlowValue_IfaceConstants;
virtual void writeSlowValue(tSlowValue value, tRioStatusCode *status) = 0;
virtual void writeSlowValue_RelayFwd(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeSlowValue_RelayRev(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeSlowValue_I2CHeader(unsigned char value, tRioStatusCode *status) = 0;
virtual tSlowValue readSlowValue(tRioStatusCode *status) = 0;
virtual unsigned char readSlowValue_RelayFwd(tRioStatusCode *status) = 0;
virtual unsigned char readSlowValue_RelayRev(tRioStatusCode *status) = 0;
virtual unsigned char readSlowValue_I2CHeader(tRioStatusCode *status) = 0;
typedef enum
{
} tI2CStatus_IfaceConstants;
virtual tI2CStatus readI2CStatus(tRioStatusCode *status) = 0;
virtual unsigned char readI2CStatus_Transaction(tRioStatusCode *status) = 0;
virtual bool readI2CStatus_Done(tRioStatusCode *status) = 0;
virtual bool readI2CStatus_Aborted(tRioStatusCode *status) = 0;
virtual unsigned int readI2CStatus_DataReceivedHigh(tRioStatusCode *status) = 0;
typedef enum
{
} tI2CDataReceived_IfaceConstants;
virtual unsigned int readI2CDataReceived(tRioStatusCode *status) = 0;
typedef enum
{
} tDI_IfaceConstants;
virtual unsigned short readDI(tRioStatusCode *status) = 0;
typedef enum
{
} tPulseLength_IfaceConstants;
virtual void writePulseLength(unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readPulseLength(tRioStatusCode *status) = 0;
typedef enum
{
kNumPWMPeriodScaleElements = 10,
} tPWMPeriodScale_IfaceConstants;
virtual void writePWMPeriodScale(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readPWMPeriodScale(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
kNumDO_PWMDutyCycleElements = 4,
} tDO_PWMDutyCycle_IfaceConstants;
virtual void writeDO_PWMDutyCycle(unsigned char bitfield_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readDO_PWMDutyCycle(unsigned char bitfield_index, tRioStatusCode *status) = 0;
typedef enum
{
} tBFL_IfaceConstants;
virtual void writeBFL(bool value, tRioStatusCode *status) = 0;
virtual bool readBFL(tRioStatusCode *status) = 0;
typedef enum
{
} tI2CConfig_IfaceConstants;
virtual void writeI2CConfig(tI2CConfig value, tRioStatusCode *status) = 0;
virtual void writeI2CConfig_Address(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeI2CConfig_BytesToRead(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeI2CConfig_BytesToWrite(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeI2CConfig_DataToSendHigh(unsigned short value, tRioStatusCode *status) = 0;
virtual void writeI2CConfig_BitwiseHandshake(bool value, tRioStatusCode *status) = 0;
virtual tI2CConfig readI2CConfig(tRioStatusCode *status) = 0;
virtual unsigned char readI2CConfig_Address(tRioStatusCode *status) = 0;
virtual unsigned char readI2CConfig_BytesToRead(tRioStatusCode *status) = 0;
virtual unsigned char readI2CConfig_BytesToWrite(tRioStatusCode *status) = 0;
virtual unsigned short readI2CConfig_DataToSendHigh(tRioStatusCode *status) = 0;
virtual bool readI2CConfig_BitwiseHandshake(tRioStatusCode *status) = 0;
typedef enum
{
} tDO_PWMConfig_IfaceConstants;
virtual void writeDO_PWMConfig(tDO_PWMConfig value, tRioStatusCode *status) = 0;
virtual void writeDO_PWMConfig_PeriodPower(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeDO_PWMConfig_OutputSelect_0(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeDO_PWMConfig_OutputSelect_1(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeDO_PWMConfig_OutputSelect_2(unsigned char value, tRioStatusCode *status) = 0;
virtual void writeDO_PWMConfig_OutputSelect_3(unsigned char value, tRioStatusCode *status) = 0;
virtual tDO_PWMConfig readDO_PWMConfig(tRioStatusCode *status) = 0;
virtual unsigned char readDO_PWMConfig_PeriodPower(tRioStatusCode *status) = 0;
virtual unsigned char readDO_PWMConfig_OutputSelect_0(tRioStatusCode *status) = 0;
virtual unsigned char readDO_PWMConfig_OutputSelect_1(tRioStatusCode *status) = 0;
virtual unsigned char readDO_PWMConfig_OutputSelect_2(tRioStatusCode *status) = 0;
virtual unsigned char readDO_PWMConfig_OutputSelect_3(tRioStatusCode *status) = 0;
typedef enum
{
} tI2CStart_IfaceConstants;
virtual void strobeI2CStart(tRioStatusCode *status) = 0;
typedef enum
{
} tLoopTiming_IfaceConstants;
virtual unsigned short readLoopTiming(tRioStatusCode *status) = 0;
typedef enum
{
} tPWMConfig_IfaceConstants;
virtual void writePWMConfig(tPWMConfig value, tRioStatusCode *status) = 0;
virtual void writePWMConfig_Period(unsigned short value, tRioStatusCode *status) = 0;
virtual void writePWMConfig_MinHigh(unsigned short value, tRioStatusCode *status) = 0;
virtual tPWMConfig readPWMConfig(tRioStatusCode *status) = 0;
virtual unsigned short readPWMConfig_Period(tRioStatusCode *status) = 0;
virtual unsigned short readPWMConfig_MinHigh(tRioStatusCode *status) = 0;
typedef enum
{
kNumPWMValueRegisters = 10,
} tPWMValue_IfaceConstants;
virtual void writePWMValue(unsigned char reg_index, unsigned char value, tRioStatusCode *status) = 0;
virtual unsigned char readPWMValue(unsigned char reg_index, tRioStatusCode *status) = 0;
private:
tDIO(const tDIO&);
void operator=(const tDIO&);
};
}
}
#endif // __nFRC_2012_1_6_4_DIO_h__

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