Files
allwpilib/hal/src/main/native/cpp/jni/HALUtil.cpp

476 lines
14 KiB
C++
Raw Normal View History

// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "HALUtil.h"
#include <jni.h>
2018-05-13 17:09:56 -07:00
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <string>
#include <fmt/format.h>
2018-05-13 17:09:56 -07:00
#include <wpi/jni_util.h>
#include "edu_wpi_first_hal_HALUtil.h"
#include "hal/CAN.h"
#include "hal/DriverStation.h"
#include "hal/Errors.h"
#include "hal/HAL.h"
using namespace wpi::java;
2014-01-06 09:27:51 -05:00
#define kRioStatusOffset -63000
#define kRioStatusSuccess 0
#define kRIOStatusBufferInvalidSize (kRioStatusOffset - 80)
#define kRIOStatusOperationTimedOut -52007
#define kRIOStatusFeatureNotSupported (kRioStatusOffset - 193)
#define kRIOStatusResourceNotInitialized -52010
static_assert(edu_wpi_first_hal_HALUtil_RUNTIME_ROBORIO == HAL_Runtime_RoboRIO);
static_assert(edu_wpi_first_hal_HALUtil_RUNTIME_ROBORIO2 ==
HAL_Runtime_RoboRIO2);
static_assert(edu_wpi_first_hal_HALUtil_RUNTIME_SIMULATION ==
HAL_Runtime_Simulation);
static_assert(edu_wpi_first_hal_HALUtil_RUNTIME_SYSTEMCORE ==
HAL_Runtime_SystemCore);
2018-05-13 17:09:56 -07:00
static JavaVM* jvm = nullptr;
static JException illegalArgExCls;
static JException indexOobExCls;
static JException boundaryExCls;
static JException allocationExCls;
static JException halHandleExCls;
static JException uncleanStatusExCls;
static JException nullPointerEx;
static JClass powerDistributionVersionCls;
static JClass canStatusCls;
static JClass matchInfoDataCls;
2025-02-25 19:07:01 -08:00
static JClass canReceiveMessageCls;
static JClass canStreamMessageCls;
static JClass halValueCls;
static JClass revPHVersionCls;
static JClass canStreamOverflowExCls;
static const JClassInit classes[] = {
{"edu/wpi/first/hal/PowerDistributionVersion",
&powerDistributionVersionCls},
{"edu/wpi/first/hal/can/CANStatus", &canStatusCls},
{"edu/wpi/first/hal/MatchInfoData", &matchInfoDataCls},
2025-02-25 19:07:01 -08:00
{"edu/wpi/first/hal/can/CANReceiveMessage", &canReceiveMessageCls},
{"edu/wpi/first/hal/can/CANStreamMessage", &canStreamMessageCls},
{"edu/wpi/first/hal/HALValue", &halValueCls},
{"edu/wpi/first/hal/REVPHVersion", &revPHVersionCls},
{"edu/wpi/first/hal/can/CANStreamOverflowException",
&canStreamOverflowExCls}};
static const JExceptionInit exceptions[] = {
{"java/lang/IllegalArgumentException", &illegalArgExCls},
{"java/lang/IndexOutOfBoundsException", &indexOobExCls},
{"edu/wpi/first/hal/util/BoundaryException", &boundaryExCls},
{"edu/wpi/first/hal/util/AllocationException", &allocationExCls},
{"edu/wpi/first/hal/util/HalHandleException", &halHandleExCls},
{"edu/wpi/first/hal/util/UncleanStatusException", &uncleanStatusExCls},
{"java/lang/NullPointerException", &nullPointerEx}};
namespace hal {
void ThrowUncleanStatusException(JNIEnv* env, std::string_view msg,
int32_t status) {
static jmethodID func =
env->GetMethodID(uncleanStatusExCls, "<init>", "(ILjava/lang/String;)V");
jobject exception =
env->NewObject(uncleanStatusExCls, func, static_cast<jint>(status),
MakeJString(env, msg));
env->Throw(static_cast<jthrowable>(exception));
}
void ThrowAllocationException(JNIEnv* env, const char* lastError,
int32_t status) {
allocationExCls.Throw(env,
fmt::format("Code: {}\n{}", status, lastError).c_str());
}
2018-05-13 17:09:56 -07:00
void ThrowHalHandleException(JNIEnv* env, int32_t status) {
const char* message = HAL_GetLastError(&status);
halHandleExCls.Throw(env,
fmt::format(" Code: {}. {}", status, message).c_str());
}
2018-05-13 17:09:56 -07:00
void ReportError(JNIEnv* env, int32_t status, bool doThrow) {
if (status == 0) {
return;
}
const char* message = HAL_GetLastError(&status);
if (status == HAL_HANDLE_ERROR) {
2016-07-09 01:12:37 -07:00
ThrowHalHandleException(env, status);
return;
}
if (doThrow && status < 0) {
ThrowUncleanStatusException(
env, fmt::format(" Code: {}. {}", status, message).c_str(), status);
} else {
std::string func;
auto stack = GetJavaStackTrace(env, &func, "edu.wpi.first");
// Make a copy of message for safety, calling back into the HAL might
// invalidate the string.
std::string lastMessage{message};
HAL_SendError(1, status, 0, lastMessage.c_str(), func.c_str(),
stack.c_str(), 1);
}
}
2018-05-13 17:09:56 -07:00
void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange,
int32_t requestedValue) {
if (status == 0) {
return;
}
const char* lastError = HAL_GetLastError(&status);
2018-05-13 17:09:56 -07:00
if (status == NO_AVAILABLE_RESOURCES || status == RESOURCE_IS_ALLOCATED ||
status == RESOURCE_OUT_OF_RANGE) {
ThrowAllocationException(env, lastError, status);
return;
}
if (status == HAL_HANDLE_ERROR) {
ThrowHalHandleException(env, status);
return;
}
ThrowUncleanStatusException(
env, fmt::format(" Code: {}. {}", status, lastError).c_str(), status);
}
void ThrowNullPointerException(JNIEnv* env, std::string_view msg) {
nullPointerEx.Throw(env, msg);
}
void ThrowCANStreamOverflowException(JNIEnv* env, jobjectArray messages,
jint length) {
static jmethodID constructor =
env->GetMethodID(canStreamOverflowExCls, "<init>",
"([Ledu/wpi/first/hal/CANStreamMessage;I)V");
jobject exception =
env->NewObject(canStreamOverflowExCls, constructor, messages, length);
env->Throw(static_cast<jthrowable>(exception));
}
void ThrowIllegalArgumentException(JNIEnv* env, std::string_view msg) {
illegalArgExCls.Throw(env, msg);
}
void ThrowIndexOutOfBoundsException(JNIEnv* env, std::string_view msg) {
indexOobExCls.Throw(env, msg);
}
2018-05-13 17:09:56 -07:00
void ThrowBoundaryException(JNIEnv* env, double value, double lower,
double upper) {
static jmethodID getMessage = nullptr;
if (!getMessage) {
getMessage = env->GetStaticMethodID(boundaryExCls, "getMessage",
"(DDD)Ljava/lang/String;");
}
static jmethodID constructor = nullptr;
if (!constructor) {
constructor =
env->GetMethodID(boundaryExCls, "<init>", "(Ljava/lang/String;)V");
}
2018-05-13 17:09:56 -07:00
jobject msg = env->CallStaticObjectMethod(
boundaryExCls, getMessage, static_cast<jdouble>(value),
static_cast<jdouble>(lower), static_cast<jdouble>(upper));
jobject ex = env->NewObject(boundaryExCls, constructor, msg);
env->Throw(static_cast<jthrowable>(ex));
}
jobject CreateREVPHVersion(JNIEnv* env, uint32_t firmwareMajor,
uint32_t firmwareMinor, uint32_t firmwareFix,
uint32_t hardwareMinor, uint32_t hardwareMajor,
uint32_t uniqueId) {
static jmethodID constructor =
env->GetMethodID(revPHVersionCls, "<init>", "(IIIIII)V");
return env->NewObject(
revPHVersionCls, constructor, static_cast<jint>(firmwareMajor),
static_cast<jint>(firmwareMinor), static_cast<jint>(firmwareFix),
static_cast<jint>(hardwareMinor), static_cast<jint>(hardwareMajor),
static_cast<jint>(uniqueId));
}
2018-05-13 17:09:56 -07:00
void SetCanStatusObject(JNIEnv* env, jobject canStatus,
float percentBusUtilization, uint32_t busOffCount,
uint32_t txFullCount, uint32_t receiveErrorCount,
uint32_t transmitErrorCount) {
2018-05-13 17:09:56 -07:00
static jmethodID func =
env->GetMethodID(canStatusCls, "setStatus", "(DIIII)V");
env->CallVoidMethod(
canStatus, func, static_cast<jdouble>(percentBusUtilization),
static_cast<jint>(busOffCount), static_cast<jint>(txFullCount),
static_cast<jint>(receiveErrorCount),
static_cast<jint>(transmitErrorCount));
}
void SetMatchInfoObject(JNIEnv* env, jobject matchStatus,
const HAL_MatchInfo& matchInfo) {
2018-05-13 17:09:56 -07:00
static jmethodID func =
env->GetMethodID(matchInfoDataCls, "setData",
"(Ljava/lang/String;Ljava/lang/String;III)V");
env->CallVoidMethod(
matchStatus, func, MakeJString(env, matchInfo.eventName),
MakeJString(env,
{reinterpret_cast<const char*>(matchInfo.gameSpecificMessage),
matchInfo.gameSpecificMessageSize}),
static_cast<jint>(matchInfo.matchNumber),
static_cast<jint>(matchInfo.replayNumber),
static_cast<jint>(matchInfo.matchType));
}
2025-02-25 19:07:01 -08:00
jbyteArray SetCANReceiveMessageObject(JNIEnv* env, jobject canData,
int32_t length, int32_t flags,
uint64_t timestamp) {
static jmethodID func =
env->GetMethodID(canReceiveMessageCls, "setReceiveData", "(IIJ)[B");
2018-05-21 16:09:38 -07:00
jbyteArray retVal = static_cast<jbyteArray>(env->CallObjectMethod(
2025-02-25 19:07:01 -08:00
canData, func, static_cast<jint>(length), static_cast<jint>(flags),
static_cast<jlong>(timestamp)));
2018-05-21 16:09:38 -07:00
return retVal;
}
jbyteArray SetCANStreamObject(JNIEnv* env, jobject canStreamData,
2025-07-14 23:46:57 -07:00
int32_t length, int32_t flags, uint32_t messageId,
uint64_t timestamp) {
static jmethodID func =
2025-07-14 23:46:57 -07:00
env->GetMethodID(canStreamMessageCls, "setStreamData", "(IIIJ)[B");
jbyteArray retVal = static_cast<jbyteArray>(env->CallObjectMethod(
2025-07-14 23:46:57 -07:00
canStreamData, func, static_cast<jint>(length), static_cast<jint>(flags),
2025-02-25 19:07:01 -08:00
static_cast<jint>(messageId), static_cast<jlong>(timestamp)));
return retVal;
}
jobject CreateHALValue(JNIEnv* env, const HAL_Value& value) {
static jmethodID fromNative = env->GetStaticMethodID(
halValueCls, "fromNative", "(IJD)Ledu/wpi/first/hal/HALValue;");
jlong value1 = 0;
jdouble value2 = 0.0;
switch (value.type) {
case HAL_BOOLEAN:
value1 = value.data.v_boolean;
break;
case HAL_DOUBLE:
value2 = value.data.v_double;
break;
case HAL_ENUM:
value1 = value.data.v_enum;
break;
case HAL_INT:
value1 = value.data.v_int;
break;
case HAL_LONG:
value1 = value.data.v_long;
break;
default:
break;
}
return env->CallStaticObjectMethod(
halValueCls, fromNative, static_cast<jint>(value.type), value1, value2);
}
jobject CreatePowerDistributionVersion(JNIEnv* env, uint32_t firmwareMajor,
uint32_t firmwareMinor,
uint32_t firmwareFix,
uint32_t hardwareMinor,
uint32_t hardwareMajor,
uint32_t uniqueId) {
static jmethodID constructor =
env->GetMethodID(powerDistributionVersionCls, "<init>", "(IIIIII)V");
return env->NewObject(
powerDistributionVersionCls, constructor,
static_cast<jint>(firmwareMajor), static_cast<jint>(firmwareMinor),
static_cast<jint>(firmwareFix), static_cast<jint>(hardwareMinor),
static_cast<jint>(hardwareMajor), static_cast<jint>(uniqueId));
}
jobject CreateCANStreamMessage(JNIEnv* env) {
static jmethodID constructor =
env->GetMethodID(canStreamMessageCls, "<init>", "()V");
return env->NewObject(canStreamMessageCls, constructor);
}
JavaVM* GetJVM() {
return jvm;
}
2018-04-29 13:29:07 -07:00
namespace sim {
2018-05-13 17:09:56 -07:00
jint SimOnLoad(JavaVM* vm, void* reserved);
void SimOnUnload(JavaVM* vm, void* reserved);
} // namespace sim
2018-04-29 13:29:07 -07:00
} // namespace hal
using namespace hal;
extern "C" {
2014-01-06 09:27:51 -05:00
//
// indicate JNI version support desired and load classes
2014-01-06 09:27:51 -05:00
//
2018-05-13 17:09:56 -07:00
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
jvm = vm;
2018-05-13 17:09:56 -07:00
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
for (auto& c : classes) {
*c.cls = JClass(env, c.name);
if (!*c.cls) {
return JNI_ERR;
}
}
for (auto& c : exceptions) {
*c.cls = JException(env, c.name);
if (!*c.cls) {
return JNI_ERR;
}
}
2018-05-21 16:09:38 -07:00
2018-04-29 13:29:07 -07:00
return sim::SimOnLoad(vm, reserved);
2014-01-06 09:27:51 -05:00
}
2018-05-13 17:09:56 -07:00
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {
2018-04-29 13:29:07 -07:00
sim::SimOnUnload(vm, reserved);
2018-05-13 17:09:56 -07:00
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return;
}
// Delete global references
for (auto& c : classes) {
c.cls->free(env);
}
for (auto& c : exceptions) {
c.cls->free(env);
}
jvm = nullptr;
}
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getSerialNumber
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_edu_wpi_first_hal_HALUtil_getSerialNumber
(JNIEnv* env, jclass)
{
Change C APIs to a unified string implementation (#6299) Currently in the entire C API of WPILib we have ~8 different ways of handling strings. The C API actually isn't built for pure C callers (We don't actually have any of those). Instead, they're built for interop between languages like LabVIEW and C# which can talk to C API's directly. For output parameters, the choice was fairly obvious. An output struct containing a const string pointer and a length makes the most sense. Its easy to use these from most other languages, and doesn't require special null termination handling. Freeing these is also easy, as if you ever receive one of these string structures, theres just a single function call to free it. Input parameters are a bit more complex. To be used from pure C, and from LabVIEW, a null terminated string is the best in most cases. However, null terminated strings in general have a lot of downsides. Additionally, from LabVIEW there are other considerations around encoding that having a wrapper struct helps make a bit easier. From a language like C#, a wrapper struct is by far the easiest, as custom marshalling can make it trivial to marshal both UTF8 and UTF16 strings down. The final consideration is its nice to have an identical concept for both input and output. It makes the rules fairly easy to understand. WPILib will not have any APIs that manipulate a string allocated externally. This means WPI_String can be const, as across the boundary it is always const. If a WPILib API takes a const WPI_String*, WPILib will not manipulate or attempt to free that string, and that string is treated as an input. It is up to the caller to handle that memory, WPILib will never hold onto that memory longer than the call. If a WPILib API takes a WPI_String*, that string is an output. WPILib will allocate that API with WPI_AllocateString(), fill in the string, and return to the caller. When the caller is done with the string, they must free it with WPI_FreeString(). If an output struct contains a WPI_String member, that member is considered read only, and should not be explicitly freed. The caller should call the free function for that struct. If an array of WPI_Strings are returned, each individual string is considered read only, and should not be explicitly freed. The free function for that array should be called by the caller. If an input struct containing a WPI_String, or an input array of WPI_Strings is passed to WPILib, the individual strings will not be manipulated or freed by WPILib, and the caller owns and should free that memory. Callbacks also follow these rules. The most common is a callback either getting passed a const WPI_String* or a struct containing a WPI_String. In both of these cases, the callback target should consider these strings read only, and not attempt to free them or manipulate them.
2024-05-13 05:35:14 -07:00
WPI_String serialNum;
HAL_GetSerialNumber(&serialNum);
jstring ret = MakeJString(env, wpi::to_string_view(&serialNum));
WPI_FreeString(&serialNum);
return ret;
}
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getComments
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_edu_wpi_first_hal_HALUtil_getComments
(JNIEnv* env, jclass)
{
Change C APIs to a unified string implementation (#6299) Currently in the entire C API of WPILib we have ~8 different ways of handling strings. The C API actually isn't built for pure C callers (We don't actually have any of those). Instead, they're built for interop between languages like LabVIEW and C# which can talk to C API's directly. For output parameters, the choice was fairly obvious. An output struct containing a const string pointer and a length makes the most sense. Its easy to use these from most other languages, and doesn't require special null termination handling. Freeing these is also easy, as if you ever receive one of these string structures, theres just a single function call to free it. Input parameters are a bit more complex. To be used from pure C, and from LabVIEW, a null terminated string is the best in most cases. However, null terminated strings in general have a lot of downsides. Additionally, from LabVIEW there are other considerations around encoding that having a wrapper struct helps make a bit easier. From a language like C#, a wrapper struct is by far the easiest, as custom marshalling can make it trivial to marshal both UTF8 and UTF16 strings down. The final consideration is its nice to have an identical concept for both input and output. It makes the rules fairly easy to understand. WPILib will not have any APIs that manipulate a string allocated externally. This means WPI_String can be const, as across the boundary it is always const. If a WPILib API takes a const WPI_String*, WPILib will not manipulate or attempt to free that string, and that string is treated as an input. It is up to the caller to handle that memory, WPILib will never hold onto that memory longer than the call. If a WPILib API takes a WPI_String*, that string is an output. WPILib will allocate that API with WPI_AllocateString(), fill in the string, and return to the caller. When the caller is done with the string, they must free it with WPI_FreeString(). If an output struct contains a WPI_String member, that member is considered read only, and should not be explicitly freed. The caller should call the free function for that struct. If an array of WPI_Strings are returned, each individual string is considered read only, and should not be explicitly freed. The free function for that array should be called by the caller. If an input struct containing a WPI_String, or an input array of WPI_Strings is passed to WPILib, the individual strings will not be manipulated or freed by WPILib, and the caller owns and should free that memory. Callbacks also follow these rules. The most common is a callback either getting passed a const WPI_String* or a struct containing a WPI_String. In both of these cases, the callback target should consider these strings read only, and not attempt to free them or manipulate them.
2024-05-13 05:35:14 -07:00
WPI_String comments;
HAL_GetComments(&comments);
jstring ret = MakeJString(env, wpi::to_string_view(&comments));
WPI_FreeString(&comments);
return ret;
}
2023-09-02 02:34:18 -04:00
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getTeamNumber
* Signature: ()I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_HALUtil_getTeamNumber
(JNIEnv* env, jclass)
{
return HAL_GetTeamNumber();
}
2014-01-06 09:27:51 -05:00
/*
* Class: edu_wpi_first_hal_HALUtil
2014-01-06 09:27:51 -05:00
* Method: getFPGATime
* Signature: ()J
2014-01-06 09:27:51 -05:00
*/
JNIEXPORT jlong JNICALL
Java_edu_wpi_first_hal_HALUtil_getFPGATime
2018-05-13 17:09:56 -07:00
(JNIEnv* env, jclass)
{
int32_t status = 0;
jlong returnValue = HAL_GetFPGATime(&status);
CheckStatus(env, status);
return returnValue;
2014-01-06 09:27:51 -05:00
}
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getHALRuntimeType
* Signature: ()I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_HALUtil_getHALRuntimeType
2018-05-13 17:09:56 -07:00
(JNIEnv* env, jclass)
{
jint returnValue = HAL_GetRuntimeType();
return returnValue;
}
2014-01-06 09:27:51 -05:00
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getHALErrorMessage
2014-01-06 09:27:51 -05:00
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_edu_wpi_first_hal_HALUtil_getHALErrorMessage
2018-05-13 17:09:56 -07:00
(JNIEnv* paramEnv, jclass, jint paramId)
{
const char* msg = HAL_GetErrorMessage(paramId);
return MakeJString(paramEnv, msg);
2014-01-06 09:27:51 -05:00
}
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getHALErrno
* Signature: ()I
*/
JNIEXPORT jint JNICALL
Java_edu_wpi_first_hal_HALUtil_getHALErrno
2018-05-13 17:09:56 -07:00
(JNIEnv*, jclass)
{
return errno;
}
/*
* Class: edu_wpi_first_hal_HALUtil
* Method: getHALstrerror
* Signature: (I)Ljava/lang/String;
*/
2018-05-13 17:09:56 -07:00
JNIEXPORT jstring JNICALL
Java_edu_wpi_first_hal_HALUtil_getHALstrerror
2018-05-13 17:09:56 -07:00
(JNIEnv* env, jclass, jint errorCode)
{
const char* msg = std::strerror(errno);
return MakeJString(env, msg);
}
} // extern "C"