Add braces to C++ single-line loops and conditionals (NFC) (#2973)

This makes code easier to read and more consistent between C++ and Java.
Also update clang-format settings to always add a line break (even if no braces are used).
This commit is contained in:
Peter Johnson
2020-12-28 12:58:06 -08:00
committed by GitHub
parent 0291a3ff56
commit 2aed432b4b
634 changed files with 10716 additions and 3938 deletions

View File

@@ -123,7 +123,8 @@ static void writeRegister(Register reg, uint8_t data) {
// Execute and wait until it's done (up to a millisecond)
initialTime = HAL_GetFPGATime(&status);
while (accel->readSTAT(&status) & 1) {
if (HAL_GetFPGATime(&status) > initialTime + 1000) break;
if (HAL_GetFPGATime(&status) > initialTime + 1000)
break;
}
// Send a stop transmit/receive message with the data
@@ -134,7 +135,8 @@ static void writeRegister(Register reg, uint8_t data) {
// Execute and wait until it's done (up to a millisecond)
initialTime = HAL_GetFPGATime(&status);
while (accel->readSTAT(&status) & 1) {
if (HAL_GetFPGATime(&status) > initialTime + 1000) break;
if (HAL_GetFPGATime(&status) > initialTime + 1000)
break;
}
}
@@ -151,7 +153,8 @@ static uint8_t readRegister(Register reg) {
// Execute and wait until it's done (up to a millisecond)
initialTime = HAL_GetFPGATime(&status);
while (accel->readSTAT(&status) & 1) {
if (HAL_GetFPGATime(&status) > initialTime + 1000) break;
if (HAL_GetFPGATime(&status) > initialTime + 1000)
break;
}
// Receive a message with the data and stop
@@ -162,7 +165,8 @@ static uint8_t readRegister(Register reg) {
// Execute and wait until it's done (up to a millisecond)
initialTime = HAL_GetFPGATime(&status);
while (accel->readSTAT(&status) & 1) {
if (HAL_GetFPGATime(&status) > initialTime + 1000) break;
if (HAL_GetFPGATime(&status) > initialTime + 1000)
break;
}
return accel->readDATI(&status);

View File

@@ -25,7 +25,8 @@ HAL_Bool HAL_IsAccumulatorChannel(HAL_AnalogInputHandle analogPortHandle,
return false;
}
for (int32_t i = 0; i < kNumAccumulators; i++) {
if (port->channel == kAccumulatorChannels[i]) return true;
if (port->channel == kAccumulatorChannels[i])
return true;
}
return false;
}

View File

@@ -48,7 +48,9 @@ void InitializeAnalogGyro() {
} // namespace hal
static void Wait(double seconds) {
if (seconds < 0.0) return;
if (seconds < 0.0) {
return;
}
std::this_thread::sleep_for(std::chrono::duration<double>(seconds));
}
@@ -69,8 +71,9 @@ HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analogHandle,
auto handle = analogGyroHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
// Initialize port structure
auto gyro = analogGyroHandles->Get(handle);
@@ -97,17 +100,25 @@ void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) {
gyro->voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond;
HAL_SetAnalogAverageBits(gyro->handle, kAverageBits, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
HAL_SetAnalogOversampleBits(gyro->handle, kOversampleBits, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
double sampleRate =
kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits));
HAL_SetAnalogSampleRate(sampleRate, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
Wait(0.1);
HAL_SetAnalogGyroDeadband(handle, 0.0, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
}
void HAL_FreeAnalogGyro(HAL_GyroHandle handle) {
@@ -148,14 +159,18 @@ void HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status) {
return;
}
HAL_ResetAccumulator(gyro->handle, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
const double sampleTime = 1.0 / HAL_GetAnalogSampleRate(status);
const double overSamples =
1 << HAL_GetAnalogOversampleBits(gyro->handle, status);
const double averageSamples =
1 << HAL_GetAnalogAverageBits(gyro->handle, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
Wait(sampleTime * overSamples * averageSamples);
}
@@ -167,7 +182,9 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) {
}
HAL_InitAccumulator(gyro->handle, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
wpi::outs() << "Calibrating analog gyro for " << kCalibrationSampleTime
<< " seconds." << '\n';
Wait(kCalibrationSampleTime);
@@ -175,7 +192,9 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) {
int64_t value;
int64_t count;
HAL_GetAccumulatorOutput(gyro->handle, &value, &count, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
gyro->center = static_cast<int32_t>(
static_cast<double>(value) / static_cast<double>(count) + 0.5);
@@ -183,7 +202,9 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) {
gyro->offset = static_cast<double>(value) / static_cast<double>(count) -
static_cast<double>(gyro->center);
HAL_SetAccumulatorCenter(gyro->handle, gyro->center, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
HAL_ResetAnalogGyro(handle, status);
}
@@ -197,7 +218,9 @@ void HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts,
int32_t deadband = static_cast<int32_t>(
volts * 1e9 / HAL_GetAnalogLSBWeight(gyro->handle, status) *
(1 << HAL_GetAnalogOversampleBits(gyro->handle, status)));
if (*status != 0) return;
if (*status != 0) {
return;
}
HAL_SetAccumulatorDeadband(gyro->handle, deadband, status);
}

View File

@@ -28,7 +28,9 @@ HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle,
hal::init::CheckInit();
initializeAnalog(status);
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex) {
@@ -38,8 +40,9 @@ HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle,
HAL_AnalogInputHandle handle = analogInputHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
// Initialize port structure
auto analog_port = analogInputHandles->Get(handle);
@@ -66,7 +69,9 @@ void HAL_FreeAnalogInputPort(HAL_AnalogInputHandle analogPortHandle) {
analogInputHandles->Free(analogPortHandle);
}
HAL_Bool HAL_CheckAnalogModule(int32_t module) { return module == 1; }
HAL_Bool HAL_CheckAnalogModule(int32_t module) {
return module == 1;
}
HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel) {
return channel < kNumAnalogInputs && channel >= 0;
@@ -80,13 +85,17 @@ void HAL_SetAnalogSampleRate(double samplesPerSecond, int32_t* status) {
// TODO: Need double comparison with epsilon.
// wpi_assert(!sampleRateSet || GetSampleRate() == samplesPerSecond);
initializeAnalog(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
setAnalogSampleRate(samplesPerSecond, status);
}
double HAL_GetAnalogSampleRate(int32_t* status) {
initializeAnalog(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
uint32_t ticksPerConversion = analogInputSystem->readLoopTiming(status);
uint32_t ticksPerSample =
ticksPerConversion * getAnalogNumActiveChannels(status);

View File

@@ -40,9 +40,13 @@ void InitializeAnalogInternal() {
void initializeAnalog(int32_t* status) {
hal::init::CheckInit();
if (analogSystemInitialized) return;
if (analogSystemInitialized) {
return;
}
std::scoped_lock lock(analogRegisterWindowMutex);
if (analogSystemInitialized) return;
if (analogSystemInitialized) {
return;
}
analogInputSystem.reset(tAI::create(status));
analogOutputSystem.reset(tAO::create(status));
setAnalogNumChannelsToActivate(kNumAnalogInputs);
@@ -52,7 +56,9 @@ void initializeAnalog(int32_t* status) {
int32_t getAnalogNumActiveChannels(int32_t* status) {
int32_t scanSize = analogInputSystem->readConfig_ScanSize(status);
if (scanSize == 0) return 8;
if (scanSize == 0) {
return 8;
}
return scanSize;
}
@@ -61,8 +67,9 @@ void setAnalogNumChannelsToActivate(int32_t channels) {
}
int32_t getAnalogNumChannelsToActivate(int32_t* status) {
if (analogNumChannelsToActivate == 0)
if (analogNumChannelsToActivate == 0) {
return getAnalogNumActiveChannels(status);
}
return analogNumChannelsToActivate;
}
@@ -79,7 +86,9 @@ void setAnalogSampleRate(double samplesPerSecond, int32_t* status) {
ticksPerSample / getAnalogNumChannelsToActivate(status);
// ticksPerConversion must be at least 80
if (ticksPerConversion < 80) {
if ((*status) >= 0) *status = SAMPLE_RATE_TOO_HIGH;
if ((*status) >= 0) {
*status = SAMPLE_RATE_TOO_HIGH;
}
ticksPerConversion = 80;
}

View File

@@ -43,7 +43,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle,
hal::init::CheckInit();
initializeAnalog(status);
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex) {
@@ -54,8 +56,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle,
HAL_AnalogOutputHandle handle =
analogOutputHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = analogOutputHandles->Get(handle);
if (port == nullptr) { // would only error on thread issue
@@ -82,10 +85,11 @@ void HAL_SetAnalogOutput(HAL_AnalogOutputHandle analogOutputHandle,
uint16_t rawValue = static_cast<uint16_t>(voltage / 5.0 * 0x1000);
if (voltage < 0.0)
if (voltage < 0.0) {
rawValue = 0;
else if (voltage > 5.0)
} else if (voltage > 5.0) {
rawValue = 0x1000;
}
analogOutputSystem->writeMXP(port->channel, rawValue, status);
}

View File

@@ -359,10 +359,11 @@ void HAL_SetCounterReverseDirection(HAL_CounterHandle counterHandle,
}
if (counter->counter->readConfig_Mode(status) ==
HAL_Counter_kExternalDirection) {
if (reverseDirection)
if (reverseDirection) {
HAL_SetCounterDownSourceEdge(counterHandle, true, true, status);
else
} else {
HAL_SetCounterDownSourceEdge(counterHandle, false, true, status);
}
}
}

View File

@@ -44,7 +44,9 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle,
hal::init::CheckInit();
initializeDigital(status);
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex || channel >= kNumDigitalChannels) {
@@ -55,8 +57,9 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle,
auto handle =
digitalChannelHandles->Allocate(channel, HAL_HandleEnum::DIO, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO);
if (port == nullptr) { // would only occur on thread issue.
@@ -124,7 +127,8 @@ HAL_Bool HAL_CheckDIOChannel(int32_t channel) {
void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle) {
auto port = digitalChannelHandles->Get(dioPortHandle, HAL_HandleEnum::DIO);
// no status, so no need to check for a proper free.
if (port == nullptr) return;
if (port == nullptr)
return;
digitalChannelHandles->Free(dioPortHandle, HAL_HandleEnum::DIO);
// Wait for no other object to hold this handle.
@@ -186,7 +190,9 @@ void HAL_SetDigitalPWMRate(double rate, int32_t* status) {
// higher freq.
// TODO: Round in the linear rate domain.
initializeDigital(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
uint16_t pwmPeriodPower = static_cast<uint16_t>(
std::log(1.0 / (16 * 1.0E-6 * rate)) / std::log(2.0) + 0.5);
digitalSystem->writePWMPeriodPower(pwmPeriodPower, status);
@@ -200,10 +206,16 @@ void HAL_SetDigitalPWMDutyCycle(HAL_DigitalPWMHandle pwmGenerator,
return;
}
int32_t id = *port;
if (dutyCycle > 1.0) dutyCycle = 1.0;
if (dutyCycle < 0.0) dutyCycle = 0.0;
if (dutyCycle > 1.0) {
dutyCycle = 1.0;
}
if (dutyCycle < 0.0) {
dutyCycle = 0.0;
}
double rawDutyCycle = 256.0 * dutyCycle;
if (rawDutyCycle > 255.5) rawDutyCycle = 255.5;
if (rawDutyCycle > 255.5) {
rawDutyCycle = 255.5;
}
{
std::scoped_lock lock(digitalPwmMutex);
uint16_t pwmPeriodPower = digitalSystem->readPWMPeriodPower(status);
@@ -248,7 +260,9 @@ void HAL_SetDIO(HAL_DigitalHandle dioPortHandle, HAL_Bool value,
return;
}
if (value != 0 && value != 1) {
if (value != 0) value = 1;
if (value != 0) {
value = 1;
}
}
{
std::scoped_lock lock(digitalDIOMutex);
@@ -407,7 +421,9 @@ HAL_Bool HAL_IsPulsing(HAL_DigitalHandle dioPortHandle, int32_t* status) {
HAL_Bool HAL_IsAnyPulsing(int32_t* status) {
initializeDigital(status);
if (*status != 0) return false;
if (*status != 0) {
return false;
}
tDIO::tPulse pulseRegister = digitalSystem->readPulse(status);
return pulseRegister.Headers != 0 && pulseRegister.MXP != 0 &&
pulseRegister.SPIPort != 0;
@@ -456,7 +472,9 @@ int32_t HAL_GetFilterSelect(HAL_DigitalHandle dioPortHandle, int32_t* status) {
void HAL_SetFilterPeriod(int32_t filterIndex, int64_t value, int32_t* status) {
initializeDigital(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
std::scoped_lock lock(digitalDIOMutex);
digitalSystem->writeFilterPeriodHdr(filterIndex, value, status);
if (*status == 0) {
@@ -466,7 +484,9 @@ void HAL_SetFilterPeriod(int32_t filterIndex, int64_t value, int32_t* status) {
int64_t HAL_GetFilterPeriod(int32_t filterIndex, int32_t* status) {
initializeDigital(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
uint32_t hdrPeriod = 0;
uint32_t mxpPeriod = 0;
{

View File

@@ -124,7 +124,8 @@ void HAL_FreeDMA(HAL_DMAHandle handle) {
auto dma = dmaHandles->Get(handle);
dmaHandles->Free(handle);
if (!dma) return;
if (!dma)
return;
int32_t status = 0;
if (dma->manager) {
@@ -514,7 +515,9 @@ void HAL_SetDMAExternalTrigger(HAL_DMAHandle handle,
auto isExternalClock = dma->aDMA->readConfig_ExternalClock(status);
if (*status == 0 && !isExternalClock) {
dma->aDMA->writeConfig_ExternalClock(true, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
} else if (*status != 0) {
return;
}
@@ -554,7 +557,9 @@ void HAL_StartDMA(HAL_DMAHandle handle, int32_t queueDepth, int32_t* status) {
}
tDMA::tConfig config = dma->aDMA->readConfig(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
{
size_t accum_size = 0;

View File

@@ -43,8 +43,12 @@ void InitializeDigitalInternal() {
} // namespace init
namespace detail {
wpi::mutex& UnsafeGetDIOMutex() { return digitalDIOMutex; }
tDIO* UnsafeGetDigialSystem() { return digitalSystem.get(); }
wpi::mutex& UnsafeGetDIOMutex() {
return digitalDIOMutex;
}
tDIO* UnsafeGetDigialSystem() {
return digitalSystem.get();
}
int32_t ComputeDigitalMask(HAL_DigitalHandle handle, int32_t* status) {
auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO);
if (port == nullptr) {
@@ -69,11 +73,15 @@ void initializeDigital(int32_t* status) {
static std::atomic_bool initialized{false};
static wpi::mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return;
if (initialized) {
return;
}
std::scoped_lock lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return;
if (initialized) {
return;
}
digitalSystem.reset(tDIO::create(status));
@@ -89,7 +97,8 @@ void initializeDigital(int32_t* status) {
// Make sure that the 9403 IONode has had a chance to initialize before
// continuing.
while (pwmSystem->readLoopTiming(status) == 0) std::this_thread::yield();
while (pwmSystem->readLoopTiming(status) == 0)
std::this_thread::yield();
if (pwmSystem->readLoopTiming(status) != kExpectedLoopTiming) {
*status = LOOP_TIMING_ERROR; // NOTE: Doesn't display the error
@@ -160,7 +169,9 @@ bool remapDigitalSource(HAL_Handle digitalSourceHandle,
}
}
int32_t remapMXPChannel(int32_t channel) { return channel - 10; }
int32_t remapMXPChannel(int32_t channel) {
return channel - 10;
}
int32_t remapMXPPWMChannel(int32_t channel) {
if (channel < 14) {
@@ -170,7 +181,9 @@ int32_t remapMXPPWMChannel(int32_t channel) {
}
}
int32_t remapSPIChannel(int32_t channel) { return channel - 26; }
int32_t remapSPIChannel(int32_t channel) {
return channel - 26;
}
} // namespace hal

View File

@@ -98,13 +98,15 @@ bool remapDigitalSource(HAL_Handle digitalSourceHandle,
*/
constexpr int32_t remapDigitalChannelToBitfieldChannel(int32_t channel) {
// First 10 are headers
if (channel < kNumDigitalHeaders) return channel;
// 2nd group of 16 are mxp. So if mxp port, add 6, since they start at 10
else if (channel < kNumDigitalMXPChannels)
if (channel < kNumDigitalHeaders) {
return channel;
// 2nd group of 16 are mxp. So if mxp port, add 6, since they start at 10
} else if (channel < kNumDigitalMXPChannels) {
return channel + 6;
// Assume SPI, so remove MXP channels
else
// Assume SPI, so remove MXP channels
} else {
return channel - kNumDigitalMXPChannels;
}
}
/**

View File

@@ -60,15 +60,23 @@ void Encoder::SetupCounter(HAL_Handle digitalSourceHandleA,
m_encodingScale = encodingType == HAL_Encoder_k1X ? 1 : 2;
m_counter =
HAL_InitializeCounter(HAL_Counter_kExternalDirection, &m_index, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
HAL_SetCounterMaxPeriod(m_counter, 0.5, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
HAL_SetCounterUpSource(m_counter, digitalSourceHandleA, analogTriggerTypeA,
status);
if (*status != 0) return;
if (*status != 0) {
return;
}
HAL_SetCounterDownSource(m_counter, digitalSourceHandleB, analogTriggerTypeB,
status);
if (*status != 0) return;
if (*status != 0) {
return;
}
if (encodingType == HAL_Encoder_k1X) {
HAL_SetCounterUpSourceEdge(m_counter, true, false, status);
HAL_SetCounterAverageSize(m_counter, 1, status);
@@ -240,7 +248,9 @@ bool GetEncoderBaseHandle(HAL_EncoderHandle handle,
HAL_FPGAEncoderHandle* fpgaHandle,
HAL_CounterHandle* counterHandle) {
auto encoder = encoderHandles->Get(handle);
if (!handle) return false;
if (!handle) {
return false;
}
*fpgaHandle = encoder->m_encoder;
*counterHandle = encoder->m_counter;
@@ -258,7 +268,9 @@ HAL_EncoderHandle HAL_InitializeEncoder(
auto encoder = std::make_shared<Encoder>(
digitalSourceHandleA, analogTriggerTypeA, digitalSourceHandleB,
analogTriggerTypeB, reverseDirection, encodingType, status);
if (*status != 0) return HAL_kInvalidHandle; // return in creation error
if (*status != 0) {
return HAL_kInvalidHandle; // return in creation error
}
auto handle = encoderHandles->Allocate(encoder);
if (handle == HAL_kInvalidHandle) {
*status = NO_AVAILABLE_RESOURCES;

View File

@@ -158,7 +158,8 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode,
auto curTime = std::chrono::steady_clock::now();
int i;
for (i = 0; i < KEEP_MSGS; ++i) {
if (prevMsg[i] == details) break;
if (prevMsg[i] == details)
break;
}
int retval = 0;
if (i == KEEP_MSGS || (curTime - prevMsgTime[i]) >= std::chrono::seconds(1)) {
@@ -304,7 +305,9 @@ char* HAL_GetJoystickName(int32_t joystickNum) {
}
}
void HAL_FreeJoystickName(char* name) { std::free(name); }
void HAL_FreeJoystickName(char* name) {
std::free(name);
}
int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) {
HAL_JoystickDescriptor joystickDesc;
@@ -360,7 +363,9 @@ HAL_Bool HAL_IsNewControlData(void) {
std::scoped_lock lock{*newDSDataAvailableMutex};
int& lastCount = GetThreadLocalLastCount();
int currentCount = newDSDataAvailableCounter;
if (lastCount == currentCount) return false;
if (lastCount == currentCount) {
return false;
}
lastCount = currentCount;
return true;
}
@@ -368,7 +373,9 @@ HAL_Bool HAL_IsNewControlData(void) {
/**
* Waits for the newest DS packet to arrive. Note that this is a blocking call.
*/
void HAL_WaitForDSData(void) { HAL_WaitForDSDataTimeout(0); }
void HAL_WaitForDSData(void) {
HAL_WaitForDSDataTimeout(0);
}
/**
* Waits for the newest DS packet to arrive. If timeout is <= 0, this will wait
@@ -406,7 +413,9 @@ constexpr int32_t refNumber = 42;
static void newDataOccur(uint32_t refNum) {
// Since we could get other values, require our specific handle
// to signal our threads
if (refNum != refNumber) return;
if (refNum != refNumber) {
return;
}
std::scoped_lock lock{*newDSDataAvailableMutex};
// Notify all threads
++newDSDataAvailableCounter;
@@ -422,11 +431,15 @@ void HAL_InitializeDriverStation(void) {
static std::atomic_bool initialized{false};
static wpi::mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return;
if (initialized) {
return;
}
std::scoped_lock lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return;
if (initialized) {
return;
}
// Set up the occur function internally with NetComm
NetCommRPCProxy_SetOccurFuncPointer(newDataOccur);
@@ -440,6 +453,8 @@ void HAL_InitializeDriverStation(void) {
* Releases the DS Mutex to allow proper shutdown of any threads that are
* waiting on it.
*/
void HAL_ReleaseDSMutex(void) { newDataOccur(refNumber); }
void HAL_ReleaseDSMutex(void) {
newDataOccur(refNumber);
}
} // extern "C"

View File

@@ -92,14 +92,20 @@ extern "C" {
HAL_PortHandle HAL_GetPort(int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
if (channel < 0 || channel >= 255) {
return HAL_kInvalidHandle;
}
return createPortHandle(channel, 1);
}
HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
if (module < 0 || module >= 255) return HAL_kInvalidHandle;
if (channel < 0 || channel >= 255) {
return HAL_kInvalidHandle;
}
if (module < 0 || module >= 255) {
return HAL_kInvalidHandle;
}
return createPortHandle(channel, module);
}
@@ -232,7 +238,9 @@ const char* HAL_GetErrorMessage(int32_t code) {
}
}
HAL_RuntimeType HAL_GetRuntimeType(void) { return HAL_Athena; }
HAL_RuntimeType HAL_GetRuntimeType(void) {
return HAL_Athena;
}
int32_t HAL_GetFPGAVersion(int32_t* status) {
if (!global) {
@@ -259,11 +267,15 @@ uint64_t HAL_GetFPGATime(int32_t* status) {
uint64_t upper1 = global->readLocalTimeUpper(status);
uint32_t lower = global->readLocalTime(status);
uint64_t upper2 = global->readLocalTimeUpper(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
if (upper1 != upper2) {
// Rolled over between the lower call, reread lower
lower = global->readLocalTime(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
}
return (upper2 << 32) + lower;
}
@@ -272,7 +284,9 @@ uint64_t HAL_ExpandFPGATime(uint32_t unexpanded_lower, int32_t* status) {
// Capture the current FPGA time. This will give us the upper half of the
// clock.
uint64_t fpga_time = HAL_GetFPGATime(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
// Now, we need to detect the case where the lower bits rolled over after we
// sampled. In that case, the upper bits will be 1 bigger than they should
@@ -319,7 +333,9 @@ static bool killExistingProgram(int timeout, int mode) {
std::fstream fs;
// By making this both in/out, it won't give us an error if it doesnt exist
fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
if (fs.bad()) return false;
if (fs.bad()) {
return false;
}
pid_t pid = 0;
if (!fs.eof() && !fs.fail()) {
@@ -359,11 +375,15 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) {
static std::atomic_bool initialized{false};
static wpi::mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return true;
if (initialized) {
return true;
}
std::scoped_lock lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return true;
if (initialized) {
return true;
}
hal::init::InitializeHAL();
@@ -394,7 +414,9 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) {
global.reset(tGlobal::create(&status));
watchdog.reset(tSysWatchdog::create(&status));
if (status != 0) return false;
if (status != 0) {
return false;
}
HAL_InitializeDriverStation();

View File

@@ -9,6 +9,8 @@
namespace hal {
namespace init {
std::atomic_bool HAL_IsInitialized{false};
void RunInitialize() { HAL_Initialize(500, 0); }
void RunInitialize() {
HAL_Initialize(500, 0);
}
} // namespace init
} // namespace hal

View File

@@ -11,7 +11,9 @@ namespace init {
extern std::atomic_bool HAL_IsInitialized;
extern void RunInitialize();
static inline void CheckInit() {
if (HAL_IsInitialized.load(std::memory_order_relaxed)) return;
if (HAL_IsInitialized.load(std::memory_order_relaxed)) {
return;
}
RunInitialize();
}

View File

@@ -41,7 +41,9 @@ extern "C" {
void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) {
hal::init::CheckInit();
initializeDigital(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
if (port < 0 || port > 1) {
// Set port out of range error here
@@ -51,7 +53,9 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) {
if (port == HAL_I2C_kOnboard) {
std::scoped_lock lock(digitalI2COnBoardMutex);
i2COnboardObjCount++;
if (i2COnboardObjCount > 1) return;
if (i2COnboardObjCount > 1) {
return;
}
int handle = open("/dev/i2c-2", O_RDWR);
if (handle < 0) {
std::printf("Failed to open onboard i2c bus: %s\n", std::strerror(errno));
@@ -61,7 +65,9 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) {
} else {
std::scoped_lock lock(digitalI2CMXPMutex);
i2CMXPObjCount++;
if (i2CMXPObjCount > 1) return;
if (i2CMXPObjCount > 1) {
return;
}
if ((i2CMXPDigitalHandle1 = HAL_InitializeDIOPort(
HAL_GetPort(24), false, status)) == HAL_kInvalidHandle) {
return;

View File

@@ -28,7 +28,9 @@ class InterruptThread : public wpi::SafeThread {
std::unique_lock lock(m_mutex);
while (m_active) {
m_cond.wait(lock, [&] { return !m_active || m_notify; });
if (!m_active) break;
if (!m_active) {
break;
}
m_notify = false;
HAL_InterruptHandlerFunction handler = m_handler;
uint32_t mask = m_mask;
@@ -49,14 +51,16 @@ class InterruptThreadOwner : public wpi::SafeThreadOwner<InterruptThread> {
public:
void SetFunc(HAL_InterruptHandlerFunction handler, void* param) {
auto thr = GetThread();
if (!thr) return;
if (!thr)
return;
thr->m_handler = handler;
thr->m_param = param;
}
void Notify(uint32_t mask) {
auto thr = GetThread();
if (!thr) return;
if (!thr)
return;
thr->m_mask = mask;
thr->m_notify = true;
thr->m_cond.notify_one();

View File

@@ -75,8 +75,10 @@ static void alarmCallback() {
// process all notifiers
notifierHandles->ForEach([&](HAL_NotifierHandle handle, Notifier* notifier) {
if (notifier->triggerTime == UINT64_MAX) return;
if (currentTime == 0) currentTime = HAL_GetFPGATime(&status);
if (notifier->triggerTime == UINT64_MAX)
return;
if (currentTime == 0)
currentTime = HAL_GetFPGATime(&status);
std::unique_lock lock(notifier->mutex);
if (notifier->triggerTime < currentTime) {
notifier->triggerTime = UINT64_MAX;
@@ -102,19 +104,25 @@ static void notifierThreadMain() {
tInterruptManager manager{1 << kTimerInterruptNumber, true, &status};
while (notifierRunning) {
auto triggeredMask = manager.watch(10000, false, &status);
if (!notifierRunning) break;
if (triggeredMask == 0) continue;
if (!notifierRunning) {
break;
}
if (triggeredMask == 0)
continue;
alarmCallback();
}
}
static void cleanupNotifierAtExit() {
int32_t status = 0;
if (notifierAlarm) notifierAlarm->writeEnable(false, &status);
if (notifierAlarm)
notifierAlarm->writeEnable(false, &status);
notifierAlarm = nullptr;
notifierRunning = false;
hal::ReleaseFPGAInterrupt(kTimerInterruptNumber);
if (notifierThread.joinable()) notifierThread.join();
if (notifierThread.joinable()) {
notifierThread.join();
}
}
namespace hal {
@@ -130,8 +138,9 @@ extern "C" {
HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) {
hal::init::CheckInit();
if (!notifierAtexitRegistered.test_and_set())
if (!notifierAtexitRegistered.test_and_set()) {
std::atexit(cleanupNotifierAtExit);
}
if (notifierRefCount.fetch_add(1) == 0) {
std::scoped_lock lock(notifierMutex);
@@ -154,7 +163,8 @@ void HAL_SetNotifierName(HAL_NotifierHandle notifierHandle, const char* name,
void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier)
return;
{
std::scoped_lock lock(notifier->mutex);
@@ -167,7 +177,8 @@ void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
auto notifier = notifierHandles->Free(notifierHandle);
if (!notifier) return;
if (!notifier)
return;
// Just in case HAL_StopNotifier() wasn't called...
{
@@ -184,10 +195,13 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
// here (the atomic fetch_sub will prevent multiple parallel entries
// into this function)
if (notifierAlarm) notifierAlarm->writeEnable(false, status);
if (notifierAlarm)
notifierAlarm->writeEnable(false, status);
notifierRunning = false;
hal::ReleaseFPGAInterrupt(kTimerInterruptNumber);
if (notifierThread.joinable()) notifierThread.join();
if (notifierThread.joinable()) {
notifierThread.join();
}
std::scoped_lock lock(notifierMutex);
notifierAlarm = nullptr;
@@ -198,7 +212,8 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle,
uint64_t triggerTime, int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier)
return;
{
std::scoped_lock lock(notifier->mutex);
@@ -215,14 +230,16 @@ void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle,
notifierAlarm->writeTriggerTime(static_cast<uint32_t>(closestTrigger),
status);
// Enable the alarm.
if (!wasActive) notifierAlarm->writeEnable(true, status);
if (!wasActive)
notifierAlarm->writeEnable(true, status);
}
}
void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle,
int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier)
return;
{
std::scoped_lock lock(notifier->mutex);
@@ -233,7 +250,8 @@ void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle,
uint64_t HAL_WaitForNotifierAlarm(HAL_NotifierHandle notifierHandle,
int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return 0;
if (!notifier)
return 0;
std::unique_lock lock(notifier->mutex);
notifier->cond.wait(lock, [&] {
return !notifier->active || notifier->triggeredTime != UINT64_MAX;

View File

@@ -306,15 +306,21 @@ void HAL_GetPDPAllChannelCurrents(HAL_PDPHandle handle, double* currents,
PdpStatus1 pdpStatus;
HAL_ReadCANPacketTimeout(handle, Status1, pdpStatus.data, &length,
&receivedTimestamp, TimeoutMs, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
PdpStatus2 pdpStatus2;
HAL_ReadCANPacketTimeout(handle, Status2, pdpStatus2.data, &length,
&receivedTimestamp, TimeoutMs, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
PdpStatus3 pdpStatus3;
HAL_ReadCANPacketTimeout(handle, Status3, pdpStatus3.data, &length,
&receivedTimestamp, TimeoutMs, status);
if (*status != 0) return;
if (*status != 0) {
return;
}
currents[0] = ((static_cast<uint32_t>(pdpStatus.bits.chan1_h8) << 2) |
pdpStatus.bits.chan1_l2) *

View File

@@ -71,7 +71,9 @@ HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle,
hal::init::CheckInit();
initializeDigital(status);
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex || channel >= kNumPWMChannels) {
@@ -90,8 +92,9 @@ HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle,
auto handle =
digitalChannelHandles->Allocate(channel, HAL_HandleEnum::PWM, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::PWM);
if (port == nullptr) { // would only occur on thread issue.
@@ -160,7 +163,9 @@ void HAL_SetPWMConfig(HAL_DigitalHandle pwmPortHandle, double max,
// calculate the loop time in milliseconds
double loopTime =
HAL_GetPWMLoopTiming(status) / (kSystemClockTicksPerMicrosecond * 1e3);
if (*status != 0) return;
if (*status != 0) {
return;
}
int32_t maxPwm = static_cast<int32_t>((max - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
@@ -356,7 +361,9 @@ double HAL_GetPWMSpeed(HAL_DigitalHandle pwmPortHandle, int32_t* status) {
}
int32_t value = HAL_GetPWMRaw(pwmPortHandle, status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
DigitalPort* dPort = port.get();
if (value == kPwmDisabled) {
@@ -388,7 +395,9 @@ double HAL_GetPWMPosition(HAL_DigitalHandle pwmPortHandle, int32_t* status) {
}
int32_t value = HAL_GetPWMRaw(pwmPortHandle, status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
DigitalPort* dPort = port.get();
if (value < GetMinNegativePwm(dPort)) {
@@ -430,22 +439,30 @@ void HAL_SetPWMPeriodScale(HAL_DigitalHandle pwmPortHandle, int32_t squelchMask,
int32_t HAL_GetPWMLoopTiming(int32_t* status) {
initializeDigital(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
return pwmSystem->readLoopTiming(status);
}
uint64_t HAL_GetPWMCycleStartTime(int32_t* status) {
initializeDigital(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
uint64_t upper1 = pwmSystem->readCycleStartTimeUpper(status);
uint32_t lower = pwmSystem->readCycleStartTime(status);
uint64_t upper2 = pwmSystem->readCycleStartTimeUpper(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
if (upper1 != upper2) {
// Rolled over between the lower call, reread lower
lower = pwmSystem->readCycleStartTime(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
}
return (upper2 << 32) + lower;
}

View File

@@ -16,25 +16,65 @@ void InitializePorts() {}
extern "C" {
int32_t HAL_GetNumAccumulators(void) { return kNumAccumulators; }
int32_t HAL_GetNumAnalogTriggers(void) { return kNumAnalogTriggers; }
int32_t HAL_GetNumAnalogInputs(void) { return kNumAnalogInputs; }
int32_t HAL_GetNumAnalogOutputs(void) { return kNumAnalogOutputs; }
int32_t HAL_GetNumCounters(void) { return kNumCounters; }
int32_t HAL_GetNumDigitalHeaders(void) { return kNumDigitalHeaders; }
int32_t HAL_GetNumPWMHeaders(void) { return kNumPWMHeaders; }
int32_t HAL_GetNumDigitalChannels(void) { return kNumDigitalChannels; }
int32_t HAL_GetNumPWMChannels(void) { return kNumPWMChannels; }
int32_t HAL_GetNumDigitalPWMOutputs(void) { return kNumDigitalPWMOutputs; }
int32_t HAL_GetNumEncoders(void) { return kNumEncoders; }
int32_t HAL_GetNumInterrupts(void) { return kNumInterrupts; }
int32_t HAL_GetNumRelayChannels(void) { return kNumRelayChannels; }
int32_t HAL_GetNumRelayHeaders(void) { return kNumRelayHeaders; }
int32_t HAL_GetNumPCMModules(void) { return kNumPCMModules; }
int32_t HAL_GetNumSolenoidChannels(void) { return kNumSolenoidChannels; }
int32_t HAL_GetNumPDPModules(void) { return kNumPDPModules; }
int32_t HAL_GetNumPDPChannels(void) { return kNumPDPChannels; }
int32_t HAL_GetNumDutyCycles(void) { return kNumDutyCycles; }
int32_t HAL_GetNumAddressableLEDs(void) { return kNumAddressableLEDs; }
int32_t HAL_GetNumAccumulators(void) {
return kNumAccumulators;
}
int32_t HAL_GetNumAnalogTriggers(void) {
return kNumAnalogTriggers;
}
int32_t HAL_GetNumAnalogInputs(void) {
return kNumAnalogInputs;
}
int32_t HAL_GetNumAnalogOutputs(void) {
return kNumAnalogOutputs;
}
int32_t HAL_GetNumCounters(void) {
return kNumCounters;
}
int32_t HAL_GetNumDigitalHeaders(void) {
return kNumDigitalHeaders;
}
int32_t HAL_GetNumPWMHeaders(void) {
return kNumPWMHeaders;
}
int32_t HAL_GetNumDigitalChannels(void) {
return kNumDigitalChannels;
}
int32_t HAL_GetNumPWMChannels(void) {
return kNumPWMChannels;
}
int32_t HAL_GetNumDigitalPWMOutputs(void) {
return kNumDigitalPWMOutputs;
}
int32_t HAL_GetNumEncoders(void) {
return kNumEncoders;
}
int32_t HAL_GetNumInterrupts(void) {
return kNumInterrupts;
}
int32_t HAL_GetNumRelayChannels(void) {
return kNumRelayChannels;
}
int32_t HAL_GetNumRelayHeaders(void) {
return kNumRelayHeaders;
}
int32_t HAL_GetNumPCMModules(void) {
return kNumPCMModules;
}
int32_t HAL_GetNumSolenoidChannels(void) {
return kNumSolenoidChannels;
}
int32_t HAL_GetNumPDPModules(void) {
return kNumPDPModules;
}
int32_t HAL_GetNumPDPChannels(void) {
return kNumPDPChannels;
}
int32_t HAL_GetNumDutyCycles(void) {
return kNumDutyCycles;
}
int32_t HAL_GetNumAddressableLEDs(void) {
return kNumAddressableLEDs;
}
} // extern "C"

View File

@@ -44,7 +44,9 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd,
hal::init::CheckInit();
initializeDigital(status);
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex) {
@@ -52,12 +54,15 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd,
return HAL_kInvalidHandle;
}
if (!fwd) channel += kNumRelayHeaders; // add 4 to reverse channels
if (!fwd) {
channel += kNumRelayHeaders; // add 4 to reverse channels
}
auto handle = relayHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = relayHandles->Get(handle);
if (port == nullptr) { // would only occur on thread issue.
@@ -105,7 +110,9 @@ void HAL_SetRelay(HAL_RelayHandle relayPortHandle, HAL_Bool on,
relays = relaySystem->readValue_Reverse(status);
}
if (*status != 0) return; // bad status read
if (*status != 0) {
return; // bad status read
}
if (on) {
relays |= 1 << port->channel;

View File

@@ -51,7 +51,9 @@ static bool SPIInUseByAuto(HAL_SPIPort port) {
// SPI engine conflicts with any other chip selects on the same SPI device.
// There are two SPI devices: one for ports 0-3 (onboard), the other for port
// 4 (MXP).
if (!spiAutoRunning) return false;
if (!spiAutoRunning) {
return false;
}
std::scoped_lock lock(spiAutoMutex);
return (spiAutoPort >= 0 && spiAutoPort <= 3 && port >= 0 && port <= 3) ||
(spiAutoPort == 4 && port == 4);
@@ -70,7 +72,9 @@ static void CommonSPIPortInit(int32_t* status) {
if (spiPortCount.fetch_add(1) == 0) {
// Have not been initialized yet
initializeDigital(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
// MISO
if ((digitalHandles[3] = HAL_InitializeDIOPort(createPortHandleForSPI(29),
false, status)) ==
@@ -105,11 +109,15 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) {
}
int handle;
if (HAL_GetSPIHandle(port) != 0) return;
if (HAL_GetSPIHandle(port) != 0) {
return;
}
switch (port) {
case HAL_SPI_kOnboardCS0:
CommonSPIPortInit(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
// CS0 is not a DIO port, so nothing to allocate
handle = open("/dev/spidev0.0", O_RDWR);
if (handle < 0) {
@@ -122,7 +130,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) {
break;
case HAL_SPI_kOnboardCS1:
CommonSPIPortInit(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
// CS1, Allocate
if ((digitalHandles[0] = HAL_InitializeDIOPort(createPortHandleForSPI(26),
false, status)) ==
@@ -143,7 +153,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) {
break;
case HAL_SPI_kOnboardCS2:
CommonSPIPortInit(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
// CS2, Allocate
if ((digitalHandles[1] = HAL_InitializeDIOPort(createPortHandleForSPI(27),
false, status)) ==
@@ -164,7 +176,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) {
break;
case HAL_SPI_kOnboardCS3:
CommonSPIPortInit(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
// CS3, Allocate
if ((digitalHandles[2] = HAL_InitializeDIOPort(createPortHandleForSPI(28),
false, status)) ==
@@ -185,7 +199,9 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) {
break;
case HAL_SPI_kMXP:
initializeDigital(status);
if (*status != 0) return;
if (*status != 0) {
return;
}
if ((digitalHandles[5] = HAL_InitializeDIOPort(createPortHandleForSPI(14),
false, status)) ==
HAL_kInvalidHandle) {
@@ -242,7 +258,9 @@ int32_t HAL_TransactionSPI(HAL_SPIPort port, const uint8_t* dataToSend,
return -1;
}
if (SPIInUseByAuto(port)) return -1;
if (SPIInUseByAuto(port)) {
return -1;
}
struct spi_ioc_transfer xfer;
std::memset(&xfer, 0, sizeof(xfer));
@@ -260,7 +278,9 @@ int32_t HAL_WriteSPI(HAL_SPIPort port, const uint8_t* dataToSend,
return -1;
}
if (SPIInUseByAuto(port)) return -1;
if (SPIInUseByAuto(port)) {
return -1;
}
struct spi_ioc_transfer xfer;
std::memset(&xfer, 0, sizeof(xfer));
@@ -276,7 +296,9 @@ int32_t HAL_ReadSPI(HAL_SPIPort port, uint8_t* buffer, int32_t count) {
return -1;
}
if (SPIInUseByAuto(port)) return -1;
if (SPIInUseByAuto(port)) {
return -1;
}
struct spi_ioc_transfer xfer;
std::memset(&xfer, 0, sizeof(xfer));
@@ -468,7 +490,9 @@ void HAL_FreeSPIAuto(HAL_SPIPort port, int32_t* status) {
}
std::scoped_lock lock(spiAutoMutex);
if (spiAutoPort != port) return;
if (spiAutoPort != port) {
return;
}
spiAutoPort = kSpiMaxHandles;
// disable by setting to internal clock and setting rate=0

View File

@@ -414,7 +414,9 @@ int32_t HAL_GetSerialBytesReceived(HAL_SerialPortHandle handle,
int32_t HAL_ReadSerial(HAL_SerialPortHandle handle, char* buffer, int32_t count,
int32_t* status) {
// Don't do anything if 0 bytes were requested
if (count == 0) return 0;
if (count == 0) {
return 0;
}
auto port = serialPortHandles->Get(handle);
if (!port) {

View File

@@ -6,7 +6,9 @@
extern "C" {
HAL_SimDeviceHandle HAL_CreateSimDevice(const char* name) { return 0; }
HAL_SimDeviceHandle HAL_CreateSimDevice(const char* name) {
return 0;
}
void HAL_FreeSimDevice(HAL_SimDeviceHandle handle) {}

View File

@@ -105,7 +105,9 @@ HAL_Bool HAL_GetSolenoid(HAL_SolenoidHandle solenoidPortHandle,
}
int32_t HAL_GetAllSolenoids(int32_t module, int32_t* status) {
if (!checkPCMInit(module, status)) return 0;
if (!checkPCMInit(module, status)) {
return 0;
}
uint8_t value;
*status = PCM_modules[module]->GetAllSolenoids(value);
@@ -125,13 +127,17 @@ void HAL_SetSolenoid(HAL_SolenoidHandle solenoidPortHandle, HAL_Bool value,
}
void HAL_SetAllSolenoids(int32_t module, int32_t state, int32_t* status) {
if (!checkPCMInit(module, status)) return;
if (!checkPCMInit(module, status)) {
return;
}
*status = PCM_modules[module]->SetAllSolenoids(state);
}
int32_t HAL_GetPCMSolenoidBlackList(int32_t module, int32_t* status) {
if (!checkPCMInit(module, status)) return 0;
if (!checkPCMInit(module, status)) {
return 0;
}
uint8_t value;
*status = PCM_modules[module]->GetSolenoidBlackList(value);
@@ -139,7 +145,9 @@ int32_t HAL_GetPCMSolenoidBlackList(int32_t module, int32_t* status) {
return value;
}
HAL_Bool HAL_GetPCMSolenoidVoltageStickyFault(int32_t module, int32_t* status) {
if (!checkPCMInit(module, status)) return 0;
if (!checkPCMInit(module, status)) {
return 0;
}
bool value;
*status = PCM_modules[module]->GetSolenoidStickyFault(value);
@@ -147,7 +155,9 @@ HAL_Bool HAL_GetPCMSolenoidVoltageStickyFault(int32_t module, int32_t* status) {
return value;
}
HAL_Bool HAL_GetPCMSolenoidVoltageFault(int32_t module, int32_t* status) {
if (!checkPCMInit(module, status)) return false;
if (!checkPCMInit(module, status)) {
return false;
}
bool value;
*status = PCM_modules[module]->GetSolenoidFault(value);
@@ -155,7 +165,9 @@ HAL_Bool HAL_GetPCMSolenoidVoltageFault(int32_t module, int32_t* status) {
return value;
}
void HAL_ClearAllPCMStickyFaults(int32_t module, int32_t* status) {
if (!checkPCMInit(module, status)) return;
if (!checkPCMInit(module, status)) {
return;
}
*status = PCM_modules[module]->ClearStickyFaults();
}

View File

@@ -66,11 +66,12 @@ HAL_Bool HAL_SetThreadPriority(NativeThreadHandle handle, HAL_Bool realTime,
int policy;
pthread_getschedparam(*reinterpret_cast<const pthread_t*>(handle), &policy,
&sch);
if (scheduler == SCHED_FIFO || scheduler == SCHED_RR)
if (scheduler == SCHED_FIFO || scheduler == SCHED_RR) {
sch.sched_priority = priority;
else
} else {
// Only need to set 0 priority for non RT thread
sch.sched_priority = 0;
}
if (pthread_setschedparam(*reinterpret_cast<const pthread_t*>(handle),
scheduler, &sch)) {
*status = HAL_THREAD_PRIORITY_ERROR;

View File

@@ -191,25 +191,30 @@ void SerialHelper::QueryHubPaths(int32_t* status) {
// Open the resource, grab its interface name, and close it.
ViSession vSession;
*status = viOpen(m_resourceHandle, desc, VI_NULL, VI_NULL, &vSession);
if (*status < 0) goto done;
if (*status < 0)
goto done;
*status = 0;
*status = viGetAttribute(vSession, VI_ATTR_INTF_INST_NAME, &osName);
// Ignore an error here, as we want to close the session on an error
// Use a separate close variable so we can check
ViStatus closeStatus = viClose(vSession);
if (*status < 0) goto done;
if (closeStatus < 0) goto done;
if (*status < 0)
goto done;
if (closeStatus < 0)
goto done;
*status = 0;
// split until (/dev/
wpi::StringRef devNameRef = wpi::StringRef{osName}.split("(/dev/").second;
// String not found, continue
if (devNameRef.equals("")) continue;
if (devNameRef.equals(""))
continue;
// Split at )
wpi::StringRef matchString = devNameRef.split(')').first;
if (matchString.equals(devNameRef)) continue;
if (matchString.equals(devNameRef))
continue;
// Search directories to get a list of system accessors
// The directories we need are not symbolic, so we can safely
@@ -218,11 +223,15 @@ void SerialHelper::QueryHubPaths(int32_t* status) {
for (auto p = wpi::sys::fs::recursive_directory_iterator(
"/sys/devices/soc0", ec, false);
p != wpi::sys::fs::recursive_directory_iterator(); p.increment(ec)) {
if (ec) break;
if (ec)
break;
wpi::StringRef path{p->path()};
if (path.find("amba") == wpi::StringRef::npos) continue;
if (path.find("usb") == wpi::StringRef::npos) continue;
if (path.find(matchString) == wpi::StringRef::npos) continue;
if (path.find("amba") == wpi::StringRef::npos)
continue;
if (path.find("usb") == wpi::StringRef::npos)
continue;
if (path.find(matchString) == wpi::StringRef::npos)
continue;
wpi::SmallVector<wpi::StringRef, 16> pathSplitVec;
// Split path into individual directories
@@ -246,11 +255,13 @@ void SerialHelper::QueryHubPaths(int32_t* status) {
// Get the index for our device
int hubIndex = findtty;
if (findtty == -1) hubIndex = findregex;
if (findtty == -1)
hubIndex = findregex;
int devStart = findusb + 1;
if (hubIndex < devStart) continue;
if (hubIndex < devStart)
continue;
// Add our devices to our list
m_unsortedHubPath.emplace_back(

View File

@@ -8,7 +8,9 @@
extern "C" {
int32_t HALSIM_FindAddressableLEDForChannel(int32_t channel) { return 0; }
int32_t HALSIM_FindAddressableLEDForChannel(int32_t channel) {
return 0;
}
void HALSIM_ResetAddressableLEDData(int32_t index) {}

View File

@@ -9,7 +9,9 @@
extern "C" {
void HALSIM_ResetAnalogInData(int32_t index) {}
HAL_SimDeviceHandle HALSIM_GetAnalogInSimDevice(int32_t index) { return 0; }
HAL_SimDeviceHandle HALSIM_GetAnalogInSimDevice(int32_t index) {
return 0;
}
#define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \
HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, AnalogIn##CAPINAME, RETURN)

View File

@@ -8,7 +8,9 @@
extern "C" {
int32_t HALSIM_FindAnalogTriggerForChannel(int32_t channel) { return 0; }
int32_t HALSIM_FindAnalogTriggerForChannel(int32_t channel) {
return 0;
}
void HALSIM_ResetAnalogTriggerData(int32_t index) {}

View File

@@ -9,7 +9,9 @@
extern "C" {
void HALSIM_ResetDIOData(int32_t index) {}
HAL_SimDeviceHandle HALSIM_GetDIOSimDevice(int32_t index) { return 0; }
HAL_SimDeviceHandle HALSIM_GetDIOSimDevice(int32_t index) {
return 0;
}
#define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \
HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, DIO##CAPINAME, RETURN)

View File

@@ -7,7 +7,9 @@
#include "hal/simulation/SimDataValue.h"
extern "C" {
int32_t HALSIM_FindDigitalPWMForChannel(int32_t channel) { return 0; }
int32_t HALSIM_FindDigitalPWMForChannel(int32_t channel) {
return 0;
}
void HALSIM_ResetDigitalPWMData(int32_t index) {}

View File

@@ -7,13 +7,19 @@
#include "hal/simulation/SimDataValue.h"
extern "C" {
int32_t HALSIM_FindDutyCycleForChannel(int32_t channel) { return 0; }
int32_t HALSIM_FindDutyCycleForChannel(int32_t channel) {
return 0;
}
void HALSIM_ResetDutyCycleData(int32_t index) {}
int32_t HALSIM_GetDutyCycleDigitalChannel(int32_t index) { return 0; }
int32_t HALSIM_GetDutyCycleDigitalChannel(int32_t index) {
return 0;
}
HAL_SimDeviceHandle HALSIM_GetDutyCycleSimDevice(int32_t index) { return 0; }
HAL_SimDeviceHandle HALSIM_GetDutyCycleSimDevice(int32_t index) {
return 0;
}
#define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \
HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, DutyCycle##CAPINAME, RETURN)

View File

@@ -7,15 +7,23 @@
#include "hal/simulation/SimDataValue.h"
extern "C" {
int32_t HALSIM_FindEncoderForChannel(int32_t channel) { return 0; }
int32_t HALSIM_FindEncoderForChannel(int32_t channel) {
return 0;
}
void HALSIM_ResetEncoderData(int32_t index) {}
int32_t HALSIM_GetEncoderDigitalChannelA(int32_t index) { return 0; }
int32_t HALSIM_GetEncoderDigitalChannelA(int32_t index) {
return 0;
}
int32_t HALSIM_GetEncoderDigitalChannelB(int32_t index) { return 0; }
int32_t HALSIM_GetEncoderDigitalChannelB(int32_t index) {
return 0;
}
HAL_SimDeviceHandle HALSIM_GetEncoderSimDevice(int32_t index) { return 0; }
HAL_SimDeviceHandle HALSIM_GetEncoderSimDevice(int32_t index) {
return 0;
}
#define DEFINE_CAPI(TYPE, CAPINAME, RETURN) \
HAL_SIMDATAVALUE_STUB_CAPI(TYPE, HALSIM, Encoder##CAPINAME, RETURN)
@@ -32,11 +40,15 @@ DEFINE_CAPI(double, DistancePerPulse, 0)
void HALSIM_SetEncoderDistance(int32_t index, double distance) {}
double HALSIM_GetEncoderDistance(int32_t index) { return 0; }
double HALSIM_GetEncoderDistance(int32_t index) {
return 0;
}
void HALSIM_SetEncoderRate(int32_t index, double rate) {}
double HALSIM_GetEncoderRate(int32_t index) { return 0; }
double HALSIM_GetEncoderRate(int32_t index) {
return 0;
}
void HALSIM_RegisterEncoderAllCallbacks(int32_t index,
HAL_NotifyCallback callback,

View File

@@ -12,7 +12,9 @@ void HALSIM_WaitForProgramStart(void) {}
void HALSIM_SetProgramStarted(void) {}
HAL_Bool HALSIM_GetProgramStarted(void) { return false; }
HAL_Bool HALSIM_GetProgramStarted(void) {
return false;
}
void HALSIM_RestartTiming(void) {}
@@ -20,7 +22,9 @@ void HALSIM_PauseTiming(void) {}
void HALSIM_ResumeTiming(void) {}
HAL_Bool HALSIM_IsTimingPaused(void) { return false; }
HAL_Bool HALSIM_IsTimingPaused(void) {
return false;
}
void HALSIM_StepTiming(uint64_t delta) {}

View File

@@ -6,9 +6,13 @@
extern "C" {
uint64_t HALSIM_GetNextNotifierTimeout(void) { return 0; }
uint64_t HALSIM_GetNextNotifierTimeout(void) {
return 0;
}
int32_t HALSIM_GetNumNotifiers(void) { return 0; }
int32_t HALSIM_GetNumNotifiers(void) {
return 0;
}
int32_t HALSIM_GetNotifierInfo(struct HALSIM_NotifierInfo* arr, int32_t size) {
return 0;

View File

@@ -21,7 +21,9 @@ DEFINE_CAPI(HAL_Bool, ClosedLoopEnabled, false)
DEFINE_CAPI(HAL_Bool, PressureSwitch, false)
DEFINE_CAPI(double, CompressorCurrent, 0)
void HALSIM_GetPCMAllSolenoids(int32_t index, uint8_t* values) { *values = 0; }
void HALSIM_GetPCMAllSolenoids(int32_t index, uint8_t* values) {
*values = 0;
}
void HALSIM_SetPCMAllSolenoids(int32_t index, uint8_t values) {}

View File

@@ -19,7 +19,9 @@ DEFINE_CAPI(double, Voltage, 0)
HAL_SIMDATAVALUE_STUB_CAPI_CHANNEL(double, HALSIM, PDPCurrent, 0)
void HALSIM_GetPDPAllCurrents(int32_t index, double* currents) {
for (int i = 0; i < hal::kNumPDPChannels; i++) currents[i] = 0;
for (int i = 0; i < hal::kNumPDPChannels; i++) {
currents[i] = 0;
}
}
void HALSIM_SetPDPAllCurrents(int32_t index, const double* currents) {}

View File

@@ -10,7 +10,9 @@ extern "C" {
void HALSIM_SetSimDeviceEnabled(const char* prefix, HAL_Bool enabled) {}
HAL_Bool HALSIM_IsSimDeviceEnabled(const char* name) { return false; }
HAL_Bool HALSIM_IsSimDeviceEnabled(const char* name) {
return false;
}
int32_t HALSIM_RegisterSimDeviceCreatedCallback(
const char* prefix, void* param, HALSIM_SimDeviceCallback callback,
@@ -28,9 +30,13 @@ int32_t HALSIM_RegisterSimDeviceFreedCallback(const char* prefix, void* param,
void HALSIM_CancelSimDeviceFreedCallback(int32_t uid) {}
HAL_SimDeviceHandle HALSIM_GetSimDeviceHandle(const char* name) { return 0; }
HAL_SimDeviceHandle HALSIM_GetSimDeviceHandle(const char* name) {
return 0;
}
const char* HALSIM_GetSimDeviceName(HAL_SimDeviceHandle handle) { return ""; }
const char* HALSIM_GetSimDeviceName(HAL_SimDeviceHandle handle) {
return "";
}
HAL_SimDeviceHandle HALSIM_GetSimValueDeviceHandle(HAL_SimValueHandle handle) {
return 0;

View File

@@ -52,10 +52,16 @@ void HAL_SetMain(void* param, void (*mainFunc)(void*),
gExitFunc = exitFunc;
}
HAL_Bool HAL_HasMain(void) { return gHasMain; }
HAL_Bool HAL_HasMain(void) {
return gHasMain;
}
void HAL_RunMain(void) { gMainFunc(gMainParam); }
void HAL_RunMain(void) {
gMainFunc(gMainParam);
}
void HAL_ExitMain(void) { gExitFunc(gMainParam); }
void HAL_ExitMain(void) {
gExitFunc(gMainParam);
}
} // extern "C"

View File

@@ -77,9 +77,13 @@ HAL_PortHandle createPortHandleForSPI(uint8_t channel) {
}
HAL_Handle createHandle(int16_t index, HAL_HandleEnum handleType,
int16_t version) {
if (index < 0) return HAL_kInvalidHandle;
if (index < 0) {
return HAL_kInvalidHandle;
}
uint8_t hType = static_cast<uint8_t>(handleType);
if (hType == 0 || hType > 127) return HAL_kInvalidHandle;
if (hType == 0 || hType > 127) {
return HAL_kInvalidHandle;
}
// set last 8 bits, then shift to first 8 bits
HAL_Handle handle = hType;
handle = handle << 8;

View File

@@ -194,11 +194,15 @@ Java_edu_wpi_first_hal_CANAPIJNI_readCANPacketNew
if (!CheckStatus(env, status)) {
return false;
}
if (dataLength > 8) dataLength = 8;
if (dataLength > 8) {
dataLength = 8;
}
jbyteArray toSetArray = SetCANDataObject(env, data, dataLength, timestamp);
auto javaLen = env->GetArrayLength(toSetArray);
if (javaLen < dataLength) dataLength = javaLen;
if (javaLen < dataLength) {
dataLength = javaLen;
}
env->SetByteArrayRegion(toSetArray, 0, dataLength,
reinterpret_cast<jbyte*>(dataTemp));
return true;
@@ -226,11 +230,15 @@ Java_edu_wpi_first_hal_CANAPIJNI_readCANPacketLatest
if (!CheckStatus(env, status)) {
return false;
}
if (dataLength > 8) dataLength = 8;
if (dataLength > 8) {
dataLength = 8;
}
jbyteArray toSetArray = SetCANDataObject(env, data, dataLength, timestamp);
auto javaLen = env->GetArrayLength(toSetArray);
if (javaLen < dataLength) dataLength = javaLen;
if (javaLen < dataLength) {
dataLength = javaLen;
}
env->SetByteArrayRegion(toSetArray, 0, dataLength,
reinterpret_cast<jbyte*>(dataTemp));
return true;
@@ -259,11 +267,15 @@ Java_edu_wpi_first_hal_CANAPIJNI_readCANPacketTimeout
if (!CheckStatus(env, status)) {
return false;
}
if (dataLength > 8) dataLength = 8;
if (dataLength > 8) {
dataLength = 8;
}
jbyteArray toSetArray = SetCANDataObject(env, data, dataLength, timestamp);
auto javaLen = env->GetArrayLength(toSetArray);
if (javaLen < dataLength) dataLength = javaLen;
if (javaLen < dataLength) {
dataLength = javaLen;
}
env->SetByteArrayRegion(toSetArray, 0, dataLength,
reinterpret_cast<jbyte*>(dataTemp));
return true;

View File

@@ -61,7 +61,9 @@ Java_edu_wpi_first_hal_can_CANJNI_FRCNetCommCANSessionMuxReceiveMessage
HAL_CAN_ReceiveMessage(messageIDPtr, messageIDMask, buffer, &dataSize,
timeStampPtr, &status);
if (!CheckCANStatus(env, status, *messageIDPtr)) return nullptr;
if (!CheckCANStatus(env, status, *messageIDPtr)) {
return nullptr;
}
return MakeJByteArray(env,
wpi::StringRef{reinterpret_cast<const char*>(buffer),
static_cast<size_t>(dataSize)});
@@ -85,7 +87,9 @@ Java_edu_wpi_first_hal_can_CANJNI_GetCANStatus
HAL_CAN_GetCANStatus(&percentBusUtilization, &busOffCount, &txFullCount,
&receiveErrorCount, &transmitErrorCount, &status);
if (!CheckStatus(env, status)) return;
if (!CheckStatus(env, status)) {
return;
}
SetCanStatusObject(env, canStatus, percentBusUtilization, busOffCount,
txFullCount, receiveErrorCount, transmitErrorCount);

View File

@@ -104,7 +104,9 @@ void ThrowHalHandleException(JNIEnv* env, int32_t status) {
}
void ReportError(JNIEnv* env, int32_t status, bool doThrow) {
if (status == 0) return;
if (status == 0) {
return;
}
if (status == HAL_HANDLE_ERROR) {
ThrowHalHandleException(env, status);
}
@@ -123,7 +125,9 @@ void ReportError(JNIEnv* env, int32_t status, bool doThrow) {
void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange,
int32_t requestedValue) {
if (status == 0) return;
if (status == 0) {
return;
}
if (status == NO_AVAILABLE_RESOURCES || status == RESOURCE_IS_ALLOCATED ||
status == RESOURCE_OUT_OF_RANGE) {
ThrowAllocationException(env, minRange, maxRange, requestedValue, status);
@@ -139,7 +143,9 @@ void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange,
}
void ReportCANError(JNIEnv* env, int32_t status, int message_id) {
if (status >= 0) return;
if (status >= 0) {
return;
}
switch (status) {
case kRioStatusSuccess:
// Everything is ok... don't throw.
@@ -147,9 +153,10 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) {
case HAL_ERR_CANSessionMux_InvalidBuffer:
case kRIOStatusBufferInvalidSize: {
static jmethodID invalidBufConstruct = nullptr;
if (!invalidBufConstruct)
if (!invalidBufConstruct) {
invalidBufConstruct =
env->GetMethodID(canInvalidBufferExCls, "<init>", "()V");
}
jobject exception =
env->NewObject(canInvalidBufferExCls, invalidBufConstruct);
env->Throw(static_cast<jthrowable>(exception));
@@ -158,9 +165,10 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) {
case HAL_ERR_CANSessionMux_MessageNotFound:
case kRIOStatusOperationTimedOut: {
static jmethodID messageNotFoundConstruct = nullptr;
if (!messageNotFoundConstruct)
if (!messageNotFoundConstruct) {
messageNotFoundConstruct =
env->GetMethodID(canMessageNotFoundExCls, "<init>", "()V");
}
jobject exception =
env->NewObject(canMessageNotFoundExCls, messageNotFoundConstruct);
env->Throw(static_cast<jthrowable>(exception));
@@ -177,9 +185,10 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) {
case HAL_ERR_CANSessionMux_NotInitialized:
case kRIOStatusResourceNotInitialized: {
static jmethodID notInitConstruct = nullptr;
if (!notInitConstruct)
if (!notInitConstruct) {
notInitConstruct =
env->GetMethodID(canNotInitializedExCls, "<init>", "()V");
}
jobject exception =
env->NewObject(canNotInitializedExCls, notInitConstruct);
env->Throw(static_cast<jthrowable>(exception));
@@ -202,14 +211,16 @@ void ThrowIllegalArgumentException(JNIEnv* env, wpi::StringRef msg) {
void ThrowBoundaryException(JNIEnv* env, double value, double lower,
double upper) {
static jmethodID getMessage = nullptr;
if (!getMessage)
if (!getMessage) {
getMessage = env->GetStaticMethodID(boundaryExCls, "getMessage",
"(DDD)Ljava/lang/String;");
}
static jmethodID constructor = nullptr;
if (!constructor)
if (!constructor) {
constructor =
env->GetMethodID(boundaryExCls, "<init>", "(Ljava/lang/String;)V");
}
jobject msg = env->CallStaticObjectMethod(
boundaryExCls, getMessage, static_cast<jdouble>(value),
@@ -299,7 +310,9 @@ jobject CreateHALValue(JNIEnv* env, const HAL_Value& value) {
value1, value2);
}
JavaVM* GetJVM() { return jvm; }
JavaVM* GetJVM() {
return jvm;
}
namespace sim {
jint SimOnLoad(JavaVM* vm, void* reserved);
@@ -319,17 +332,22 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
jvm = vm;
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
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;
if (!*c.cls) {
return JNI_ERR;
}
}
for (auto& c : exceptions) {
*c.cls = JException(env, c.name);
if (!*c.cls) return JNI_ERR;
if (!*c.cls) {
return JNI_ERR;
}
}
return sim::SimOnLoad(vm, reserved);
@@ -339,8 +357,9 @@ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {
sim::SimOnUnload(vm, reserved);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return;
}
// Delete global references
for (auto& c : classes) {

View File

@@ -21,25 +21,33 @@ void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange,
int32_t requestedValue);
inline bool CheckStatus(JNIEnv* env, int32_t status, bool doThrow = true) {
if (status != 0) ReportError(env, status, doThrow);
if (status != 0) {
ReportError(env, status, doThrow);
}
return status == 0;
}
inline bool CheckStatusRange(JNIEnv* env, int32_t status, int32_t minRange,
int32_t maxRange, int32_t requestedValue) {
if (status != 0) ThrowError(env, status, minRange, maxRange, requestedValue);
if (status != 0) {
ThrowError(env, status, minRange, maxRange, requestedValue);
}
return status == 0;
}
inline bool CheckStatusForceThrow(JNIEnv* env, int32_t status) {
if (status != 0) ThrowError(env, status, 0, 0, 0);
if (status != 0) {
ThrowError(env, status, 0, 0, 0);
}
return status == 0;
}
void ReportCANError(JNIEnv* env, int32_t status, int32_t message_id);
inline bool CheckCANStatus(JNIEnv* env, int32_t status, int32_t message_id) {
if (status != 0) ReportCANError(env, status, message_id);
if (status != 0) {
ReportCANError(env, status, message_id);
}
return status == 0;
}

View File

@@ -46,7 +46,9 @@ class InterruptJNI : public wpi::SafeThreadOwner<InterruptThreadJNI> {
void Notify(uint32_t mask) {
auto thr = GetThread();
if (!thr) return;
if (!thr) {
return;
}
thr->m_notify = true;
thr->m_mask = mask;
thr->m_cond.notify_one();
@@ -56,10 +58,16 @@ class InterruptJNI : public wpi::SafeThreadOwner<InterruptThreadJNI> {
void InterruptJNI::SetFunc(JNIEnv* env, jobject func, jmethodID mid,
jobject param) {
auto thr = GetThread();
if (!thr) return;
if (!thr) {
return;
}
// free global references
if (thr->m_func) env->DeleteGlobalRef(thr->m_func);
if (thr->m_param) env->DeleteGlobalRef(thr->m_param);
if (thr->m_func) {
env->DeleteGlobalRef(thr->m_func);
}
if (thr->m_param) {
env->DeleteGlobalRef(thr->m_param);
}
// create global references
thr->m_func = env->NewGlobalRef(func);
thr->m_param = param ? env->NewGlobalRef(param) : nullptr;
@@ -74,14 +82,20 @@ void InterruptThreadJNI::Main() {
args.group = nullptr;
jint rs = GetJVM()->AttachCurrentThreadAsDaemon(
reinterpret_cast<void**>(&env), &args);
if (rs != JNI_OK) return;
if (rs != JNI_OK) {
return;
}
std::unique_lock lock(m_mutex);
while (m_active) {
m_cond.wait(lock, [&] { return !m_active || m_notify; });
if (!m_active) break;
if (!m_active) {
break;
}
m_notify = false;
if (!m_func) continue;
if (!m_func) {
continue;
}
jobject func = m_func;
jmethodID mid = m_mid;
uint32_t mask = m_mask;
@@ -96,8 +110,12 @@ void InterruptThreadJNI::Main() {
}
// free global references
if (m_func) env->DeleteGlobalRef(m_func);
if (m_param) env->DeleteGlobalRef(m_param);
if (m_func) {
env->DeleteGlobalRef(m_func);
}
if (m_param) {
env->DeleteGlobalRef(m_param);
}
GetJVM()->DetachCurrentThread();
}

View File

@@ -367,7 +367,9 @@ Java_edu_wpi_first_hal_SPIJNI_spiReadAutoReceivedData__I_3IID
jint retval =
HAL_ReadSPIAutoReceivedData(static_cast<HAL_SPIPort>(port),
recvBuf.data(), numToRead, timeout, &status);
if (!CheckStatus(env, status)) return retval;
if (!CheckStatus(env, status)) {
return retval;
}
if (numToRead > 0) {
env->SetIntArrayRegion(buffer, 0, numToRead,
reinterpret_cast<const jint*>(recvBuf.data()));

View File

@@ -93,11 +93,15 @@ Java_edu_wpi_first_hal_SimDeviceJNI_createSimValueEnum
for (size_t i = 0; i < len; ++i) {
JLocal<jstring> elem{
env, static_cast<jstring>(env->GetObjectArrayElement(options, i))};
if (!elem) return 0;
if (!elem) {
return 0;
}
arr.push_back(JStringRef{env, elem}.str());
}
wpi::SmallVector<const char*, 8> carr;
for (auto&& val : arr) carr.push_back(val.c_str());
for (auto&& val : arr) {
carr.push_back(val.c_str());
}
return HAL_CreateSimValueEnum(device, JStringRef{env, name}.c_str(),
direction, len, carr.data(), initialValue);
}
@@ -114,18 +118,24 @@ Java_edu_wpi_first_hal_SimDeviceJNI_createSimValueEnumDouble
{
size_t len = env->GetArrayLength(options);
size_t len2 = env->GetArrayLength(optionValues);
if (len != len2) return 0;
if (len != len2) {
return 0;
}
std::vector<std::string> arr;
arr.reserve(len);
for (size_t i = 0; i < len; ++i) {
JLocal<jstring> elem{
env, static_cast<jstring>(env->GetObjectArrayElement(options, i))};
if (!elem) return 0;
if (!elem) {
return 0;
}
arr.push_back(JStringRef{env, elem}.str());
}
wpi::SmallVector<const char*, 8> carr;
for (auto&& val : arr) carr.push_back(val.c_str());
for (auto&& val : arr) {
carr.push_back(val.c_str());
}
return HAL_CreateSimValueEnumDouble(
device, JStringRef{env, name}.c_str(), direction, len, carr.data(),
JDoubleArrayRef{env, optionValues}.array().data(), initialValue);

View File

@@ -82,7 +82,9 @@ void BufferCallbackStore::performCallback(const char* name, uint8_t* buffer,
}
}
void BufferCallbackStore::free(JNIEnv* env) { m_call.free(env); }
void BufferCallbackStore::free(JNIEnv* env) {
m_call.free(env);
}
SIM_JniHandle sim::AllocateBufferCallback(
JNIEnv* env, jint index, jobject callback,
@@ -105,7 +107,9 @@ SIM_JniHandle sim::AllocateBufferCallback(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle handle = static_cast<SIM_JniHandle>(handleTmp);
auto data = callbackHandles->Get(handle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, buffer, length);
};

View File

@@ -69,7 +69,9 @@ void CallbackStore::performCallback(const char* name, const HAL_Value* value) {
}
}
void CallbackStore::free(JNIEnv* env) { m_call.free(env); }
void CallbackStore::free(JNIEnv* env) {
m_call.free(env);
}
SIM_JniHandle sim::AllocateCallback(JNIEnv* env, jint index, jobject callback,
jboolean initialNotify,
@@ -92,7 +94,9 @@ SIM_JniHandle sim::AllocateCallback(JNIEnv* env, jint index, jobject callback,
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle handle = static_cast<SIM_JniHandle>(handleTmp);
auto data = callbackHandles->Get(handle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, value);
};
@@ -132,7 +136,9 @@ SIM_JniHandle sim::AllocateChannelCallback(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle handle = static_cast<SIM_JniHandle>(handleTmp);
auto data = callbackHandles->Get(handle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, value);
};
@@ -174,7 +180,9 @@ SIM_JniHandle sim::AllocateCallbackNoIndex(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle handle = static_cast<SIM_JniHandle>(handleTmp);
auto data = callbackHandles->Get(handle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, value);
};

View File

@@ -74,7 +74,9 @@ void ConstBufferCallbackStore::performCallback(const char* name,
}
}
void ConstBufferCallbackStore::free(JNIEnv* env) { m_call.free(env); }
void ConstBufferCallbackStore::free(JNIEnv* env) {
m_call.free(env);
}
SIM_JniHandle sim::AllocateConstBufferCallback(
JNIEnv* env, jint index, jobject callback,
@@ -97,7 +99,9 @@ SIM_JniHandle sim::AllocateConstBufferCallback(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle handle = static_cast<SIM_JniHandle>(handleTmp);
auto data = callbackHandles->Get(handle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, buffer, length);
};

View File

@@ -233,7 +233,9 @@ static SIM_JniHandle AllocateDeviceCallback(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle jnihandle = static_cast<SIM_JniHandle>(handleTmp);
auto data = deviceCallbackHandles->Get(jnihandle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, handle);
};
@@ -287,7 +289,9 @@ static SIM_JniHandle AllocateValueCallback(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle jnihandle = static_cast<SIM_JniHandle>(handleTmp);
auto data = valueCallbackHandles->Get(jnihandle);
if (!data) return;
if (!data) {
return;
}
data->performCallback(name, handle, direction, *value);
};
@@ -312,27 +316,39 @@ namespace sim {
bool InitializeSimDeviceDataJNI(JNIEnv* env) {
simDeviceInfoCls = JClass(
env, "edu/wpi/first/hal/simulation/SimDeviceDataJNI$SimDeviceInfo");
if (!simDeviceInfoCls) return false;
if (!simDeviceInfoCls) {
return false;
}
simValueInfoCls =
JClass(env, "edu/wpi/first/hal/simulation/SimDeviceDataJNI$SimValueInfo");
if (!simValueInfoCls) return false;
if (!simValueInfoCls) {
return false;
}
simDeviceCallbackCls =
JClass(env, "edu/wpi/first/hal/simulation/SimDeviceCallback");
if (!simDeviceCallbackCls) return false;
if (!simDeviceCallbackCls) {
return false;
}
simDeviceCallbackCallback = env->GetMethodID(simDeviceCallbackCls, "callback",
"(Ljava/lang/String;I)V");
if (!simDeviceCallbackCallback) return false;
if (!simDeviceCallbackCallback) {
return false;
}
simValueCallbackCls =
JClass(env, "edu/wpi/first/hal/simulation/SimValueCallback");
if (!simValueCallbackCls) return false;
if (!simValueCallbackCls) {
return false;
}
simValueCallbackCallback = env->GetMethodID(
simValueCallbackCls, "callbackNative", "(Ljava/lang/String;IZIJD)V");
if (!simValueCallbackCallback) return false;
if (!simValueCallbackCallback) {
return false;
}
static hal::UnlimitedHandleResource<SIM_JniHandle, DeviceCallbackStore,
hal::HAL_HandleEnum::SimulationJni>
@@ -495,7 +511,9 @@ Java_edu_wpi_first_hal_simulation_SimDeviceDataJNI_enumerateSimDevices
size_t numElems = arr.size();
jobjectArray jarr =
env->NewObjectArray(arr.size(), simDeviceInfoCls, nullptr);
if (!jarr) return nullptr;
if (!jarr) {
return nullptr;
}
for (size_t i = 0; i < numElems; ++i) {
JLocal<jobject> elem{env, arr[i].MakeJava(env)};
env->SetObjectArrayElement(jarr, i, elem.obj());
@@ -617,7 +635,9 @@ Java_edu_wpi_first_hal_simulation_SimDeviceDataJNI_enumerateSimValues
// convert to java
size_t numElems = arr.size();
jobjectArray jarr = env->NewObjectArray(arr.size(), simValueInfoCls, nullptr);
if (!jarr) return nullptr;
if (!jarr) {
return nullptr;
}
for (size_t i = 0; i < numElems; ++i) {
JLocal<jobject> elem{env, arr[i].MakeJava(env)};
env->SetObjectArrayElement(jarr, i, elem.obj());
@@ -635,11 +655,15 @@ Java_edu_wpi_first_hal_simulation_SimDeviceDataJNI_getSimValueEnumOptions
(JNIEnv* env, jclass, jint handle)
{
static JClass stringCls{env, "java/lang/String"};
if (!stringCls) return nullptr;
if (!stringCls) {
return nullptr;
}
int32_t numElems = 0;
const char** elems = HALSIM_GetSimValueEnumOptions(handle, &numElems);
jobjectArray jarr = env->NewObjectArray(numElems, stringCls, nullptr);
if (!jarr) return nullptr;
if (!jarr) {
return nullptr;
}
for (int32_t i = 0; i < numElems; ++i) {
JLocal<jstring> elem{env, MakeJString(env, elems[i])};
env->SetObjectArrayElement(jarr, i, elem.obj());

View File

@@ -34,55 +34,75 @@ jint SimOnLoad(JavaVM* vm, void* reserved) {
jvm = vm;
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
notifyCallbackCls =
JClass(env, "edu/wpi/first/hal/simulation/NotifyCallback");
if (!notifyCallbackCls) return JNI_ERR;
if (!notifyCallbackCls) {
return JNI_ERR;
}
notifyCallbackCallback = env->GetMethodID(notifyCallbackCls, "callbackNative",
"(Ljava/lang/String;IJD)V");
if (!notifyCallbackCallback) return JNI_ERR;
if (!notifyCallbackCallback) {
return JNI_ERR;
}
bufferCallbackCls =
JClass(env, "edu/wpi/first/hal/simulation/BufferCallback");
if (!bufferCallbackCls) return JNI_ERR;
if (!bufferCallbackCls) {
return JNI_ERR;
}
bufferCallbackCallback = env->GetMethodID(bufferCallbackCls, "callback",
"(Ljava/lang/String;[BI)V");
if (!bufferCallbackCallback) return JNI_ERR;
if (!bufferCallbackCallback) {
return JNI_ERR;
}
constBufferCallbackCls =
JClass(env, "edu/wpi/first/hal/simulation/ConstBufferCallback");
if (!constBufferCallbackCls) return JNI_ERR;
if (!constBufferCallbackCls) {
return JNI_ERR;
}
constBufferCallbackCallback = env->GetMethodID(
constBufferCallbackCls, "callback", "(Ljava/lang/String;[BI)V");
if (!constBufferCallbackCallback) return JNI_ERR;
if (!constBufferCallbackCallback) {
return JNI_ERR;
}
spiReadAutoReceiveBufferCallbackCls = JClass(
env, "edu/wpi/first/hal/simulation/SpiReadAutoReceiveBufferCallback");
if (!spiReadAutoReceiveBufferCallbackCls) return JNI_ERR;
if (!spiReadAutoReceiveBufferCallbackCls) {
return JNI_ERR;
}
spiReadAutoReceiveBufferCallbackCallback =
env->GetMethodID(spiReadAutoReceiveBufferCallbackCls, "callback",
"(Ljava/lang/String;[II)I");
if (!spiReadAutoReceiveBufferCallbackCallback) return JNI_ERR;
if (!spiReadAutoReceiveBufferCallbackCallback) {
return JNI_ERR;
}
InitializeStore();
InitializeBufferStore();
InitializeConstBufferStore();
InitializeSpiBufferStore();
if (!InitializeSimDeviceDataJNI(env)) return JNI_ERR;
if (!InitializeSimDeviceDataJNI(env)) {
return JNI_ERR;
}
return JNI_VERSION_1_6;
}
void SimOnUnload(JavaVM* vm, void* reserved) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK)
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return;
}
notifyCallbackCls.free(env);
bufferCallbackCls.free(env);
@@ -92,13 +112,21 @@ void SimOnUnload(JavaVM* vm, void* reserved) {
jvm = nullptr;
}
JavaVM* GetJVM() { return jvm; }
JavaVM* GetJVM() {
return jvm;
}
jmethodID GetNotifyCallback() { return notifyCallbackCallback; }
jmethodID GetNotifyCallback() {
return notifyCallbackCallback;
}
jmethodID GetBufferCallback() { return bufferCallbackCallback; }
jmethodID GetBufferCallback() {
return bufferCallbackCallback;
}
jmethodID GetConstBufferCallback() { return constBufferCallbackCallback; }
jmethodID GetConstBufferCallback() {
return constBufferCallbackCallback;
}
jmethodID GetSpiReadAutoReceiveBufferCallback() {
return spiReadAutoReceiveBufferCallbackCallback;

View File

@@ -110,7 +110,9 @@ SIM_JniHandle sim::AllocateSpiBufferCallback(
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
SIM_JniHandle handle = static_cast<SIM_JniHandle>(handleTmp);
auto data = callbackHandles->Get(handle);
if (!data) return;
if (!data) {
return;
}
*outputCount = data->performCallback(name, buffer, numToRead);
};

View File

@@ -513,7 +513,9 @@ class SimDevice {
SimDevice(const char* name, int index, int channel);
~SimDevice() {
if (m_handle != HAL_kInvalidHandle) HAL_FreeSimDevice(m_handle);
if (m_handle != HAL_kInvalidHandle) {
HAL_FreeSimDevice(m_handle);
}
}
SimDevice(const SimDevice&) = delete;
@@ -639,7 +641,9 @@ class SimDevice {
std::initializer_list<const char*> options,
std::initializer_list<double> optionValues,
int32_t initialValue) {
if (options.size() != optionValues.size()) return {};
if (options.size() != optionValues.size()) {
return {};
}
return HAL_CreateSimValueEnumDouble(
m_handle, name, direction, options.size(),
const_cast<const char**>(options.begin()), optionValues.begin(),
@@ -666,7 +670,9 @@ class SimDevice {
wpi::ArrayRef<const char*> options,
wpi::ArrayRef<double> optionValues,
int32_t initialValue) {
if (options.size() != optionValues.size()) return {};
if (options.size() != optionValues.size()) {
return {};
}
return HAL_CreateSimValueEnumDouble(
m_handle, name, direction, options.size(),
const_cast<const char**>(options.data()), optionValues.data(),

View File

@@ -73,7 +73,9 @@ void UnsafeManipulateDIO(HAL_DigitalHandle handle, int32_t* status,
wpi::mutex& dioMutex = detail::UnsafeGetDIOMutex();
tDIO* dSys = detail::UnsafeGetDigialSystem();
auto mask = detail::ComputeDigitalMask(handle, status);
if (status != 0) return;
if (status != 0) {
return;
}
std::scoped_lock lock(dioMutex);
tDIO::tOutputEnable enableOE = dSys->readOutputEnable(status);

View File

@@ -88,7 +88,9 @@ 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 = GetIndex(handle, enumValue);
if (index < 0 || index >= size) return;
if (index < 0 || index >= size) {
return;
}
// lock and deallocated handle
std::scoped_lock lock(m_handleMutexes[index]);
m_structures[index].reset();

View File

@@ -128,9 +128,13 @@ static inline bool isHandleCorrectVersion(HAL_Handle handle, int16_t version) {
static inline int16_t getHandleTypedIndex(HAL_Handle handle,
HAL_HandleEnum enumType,
int16_t version) {
if (!isHandleType(handle, enumType)) return InvalidHandleIndex;
if (!isHandleType(handle, enumType)) {
return InvalidHandleIndex;
}
#if !defined(__FRC_ROBORIO__)
if (!isHandleCorrectVersion(handle, version)) return InvalidHandleIndex;
if (!isHandleCorrectVersion(handle, version)) {
return InvalidHandleIndex;
}
#endif
return getHandleIndex(handle);
}
@@ -152,7 +156,9 @@ static inline int16_t getHandleTypedIndex(HAL_Handle handle,
* @return the port channel
*/
static inline int16_t getPortHandleChannel(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
if (!isHandleType(handle, HAL_HandleEnum::Port)) {
return InvalidHandleIndex;
}
return static_cast<uint8_t>(handle & 0xff);
}
@@ -164,7 +170,9 @@ static inline int16_t getPortHandleChannel(HAL_PortHandle handle) {
* @return the port module
*/
static inline int16_t getPortHandleModule(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
if (!isHandleType(handle, HAL_HandleEnum::Port)) {
return InvalidHandleIndex;
}
return static_cast<uint8_t>((handle >> 8) & 0xff);
}
@@ -176,7 +184,9 @@ static inline int16_t getPortHandleModule(HAL_PortHandle handle) {
* @return the port SPI channel
*/
static inline int16_t getPortHandleSPIEnable(HAL_PortHandle handle) {
if (!isHandleType(handle, HAL_HandleEnum::Port)) return InvalidHandleIndex;
if (!isHandleType(handle, HAL_HandleEnum::Port)) {
return InvalidHandleIndex;
}
return static_cast<uint8_t>((handle >> 16) & 0xff);
}

View File

@@ -98,7 +98,9 @@ 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 = GetIndex(handle);
if (index < 0 || index >= size) return;
if (index < 0 || index >= size) {
return;
}
// lock and deallocated handle
std::scoped_lock lock(m_handleMutexes[index]);
m_structures[index].reset();

View File

@@ -92,7 +92,9 @@ 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 = GetIndex(handle);
if (index < 0 || index >= size) return;
if (index < 0 || index >= size) {
return;
}
// lock and deallocated handle
std::scoped_lock lock(m_handleMutexes[index]);
m_structures[index].reset();

View File

@@ -93,7 +93,9 @@ 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 = GetIndex(handle);
if (index < 0 || index >= size) return;
if (index < 0 || index >= size) {
return;
}
// lock and deallocated handle
std::scoped_lock allocateLock(m_allocateMutex);
std::scoped_lock handleLock(m_handleMutexes[index]);

View File

@@ -88,7 +88,9 @@ 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 = GetIndex(handle);
if (index < 0 || index >= size) return;
if (index < 0 || index >= size) {
return;
}
// lock and deallocated handle
std::scoped_lock allocateLock(m_allocateMutex);
std::scoped_lock handleLock(m_handleMutexes[index]);

View File

@@ -71,7 +71,9 @@ THandle UnlimitedHandleResource<THandle, TStruct, enumValue>::Allocate(
return static_cast<THandle>(createHandle(i, enumValue, m_version));
}
}
if (i >= INT16_MAX) return HAL_kInvalidHandle;
if (i >= INT16_MAX) {
return HAL_kInvalidHandle;
}
m_structures.push_back(structure);
return static_cast<THandle>(
@@ -83,8 +85,9 @@ std::shared_ptr<TStruct>
UnlimitedHandleResource<THandle, TStruct, enumValue>::Get(THandle handle) {
int16_t index = GetIndex(handle);
std::scoped_lock lock(m_handleMutex);
if (index < 0 || index >= static_cast<int16_t>(m_structures.size()))
if (index < 0 || index >= static_cast<int16_t>(m_structures.size())) {
return nullptr;
}
return m_structures[index];
}
@@ -93,8 +96,9 @@ std::shared_ptr<TStruct>
UnlimitedHandleResource<THandle, TStruct, enumValue>::Free(THandle handle) {
int16_t index = GetIndex(handle);
std::scoped_lock lock(m_handleMutex);
if (index < 0 || index >= static_cast<int16_t>(m_structures.size()))
if (index < 0 || index >= static_cast<int16_t>(m_structures.size())) {
return nullptr;
}
return std::move(m_structures[index]);
}

View File

@@ -27,7 +27,9 @@ class SimCallbackRegistryBase {
public:
void Cancel(int32_t uid) {
std::scoped_lock lock(m_mutex);
if (m_callbacks && uid > 0) m_callbacks->erase(uid - 1);
if (m_callbacks && uid > 0) {
m_callbacks->erase(uid - 1);
}
}
void Reset() {
@@ -40,13 +42,19 @@ class SimCallbackRegistryBase {
protected:
int32_t DoRegister(RawFunctor callback, void* param) {
// Must return -1 on a null callback for error handling
if (callback == nullptr) return -1;
if (!m_callbacks) m_callbacks = std::make_unique<CallbackVector>();
if (callback == nullptr) {
return -1;
}
if (!m_callbacks) {
m_callbacks = std::make_unique<CallbackVector>();
}
return m_callbacks->emplace_back(param, callback) + 1;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE void DoReset() {
if (m_callbacks) m_callbacks->clear();
if (m_callbacks) {
m_callbacks->clear();
}
}
mutable wpi::recursive_spinlock m_mutex;
@@ -78,9 +86,10 @@ class SimCallbackRegistry : public impl::SimCallbackRegistryBase {
#endif
if (m_callbacks) {
const char* name = GetName();
for (auto&& cb : *m_callbacks)
for (auto&& cb : *m_callbacks) {
reinterpret_cast<CallbackFunction>(cb.callback)(name, cb.param,
std::forward<U>(u)...);
}
}
}

View File

@@ -43,7 +43,9 @@ class SimDataValueBase : protected SimCallbackRegistryBase {
HAL_Bool initialNotify, const char* name) {
std::unique_lock lock(m_mutex);
int32_t newUid = DoRegister(reinterpret_cast<RawFunctor>(callback), param);
if (newUid == -1) return -1;
if (newUid == -1) {
return -1;
}
if (initialNotify) {
// We know that the callback is not null because of earlier null check
HAL_Value value = MakeValue(m_value);
@@ -59,9 +61,10 @@ class SimDataValueBase : protected SimCallbackRegistryBase {
m_value = value;
if (m_callbacks) {
HAL_Value halValue = MakeValue(value);
for (auto&& cb : *m_callbacks)
for (auto&& cb : *m_callbacks) {
reinterpret_cast<HAL_NotifyCallback>(cb.callback)(name, cb.param,
&halValue);
}
}
}
}

View File

@@ -22,7 +22,13 @@ void HAL_SetAccelerometerActive(HAL_Bool active) {
void HAL_SetAccelerometerRange(HAL_AccelerometerRange range) {
SimAccelerometerData[0].range = range;
}
double HAL_GetAccelerometerX(void) { return SimAccelerometerData[0].x; }
double HAL_GetAccelerometerY(void) { return SimAccelerometerData[0].y; }
double HAL_GetAccelerometerZ(void) { return SimAccelerometerData[0].z; }
double HAL_GetAccelerometerX(void) {
return SimAccelerometerData[0].x;
}
double HAL_GetAccelerometerY(void) {
return SimAccelerometerData[0].y;
}
double HAL_GetAccelerometerZ(void) {
return SimAccelerometerData[0].z;
}
} // extern "C"

View File

@@ -83,7 +83,9 @@ HAL_AddressableLEDHandle HAL_InitializeAddressableLED(
void HAL_FreeAddressableLED(HAL_AddressableLEDHandle handle) {
auto led = ledHandles->Get(handle);
ledHandles->Free(handle);
if (!led) return;
if (!led) {
return;
}
SimAddressableLEDData[led->index].running = false;
SimAddressableLEDData[led->index].initialized = false;
}

View File

@@ -24,7 +24,9 @@ HAL_Bool HAL_IsAccumulatorChannel(HAL_AnalogInputHandle analogPortHandle,
return false;
}
for (int32_t i = 0; i < kNumAccumulators; i++) {
if (port->channel == kAccumulatorChannels[i]) return true;
if (port->channel == kAccumulatorChannels[i]) {
return true;
}
}
return false;
}

View File

@@ -50,8 +50,9 @@ HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analogHandle,
auto handle = analogGyroHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
// Initialize port structure
auto gyro = analogGyroHandles->Get(handle);
@@ -75,7 +76,9 @@ void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) {
void HAL_FreeAnalogGyro(HAL_GyroHandle handle) {
auto gyro = analogGyroHandles->Get(handle);
analogGyroHandles->Free(handle);
if (gyro == nullptr) return;
if (gyro == nullptr) {
return;
}
SimAnalogGyroData[gyro->index].initialized = false;
}

View File

@@ -31,8 +31,9 @@ HAL_AnalogInputHandle HAL_InitializeAnalogInputPort(HAL_PortHandle portHandle,
HAL_AnalogInputHandle handle = analogInputHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
// Initialize port structure
auto analog_port = analogInputHandles->Get(handle);
@@ -58,12 +59,16 @@ void HAL_FreeAnalogInputPort(HAL_AnalogInputHandle analogPortHandle) {
auto port = analogInputHandles->Get(analogPortHandle);
// no status, so no need to check for a proper free.
analogInputHandles->Free(analogPortHandle);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
SimAnalogInData[port->channel].initialized = false;
SimAnalogInData[port->channel].accumulatorInitialized = false;
}
HAL_Bool HAL_CheckAnalogModule(int32_t module) { return module == 1; }
HAL_Bool HAL_CheckAnalogModule(int32_t module) {
return module == 1;
}
HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel) {
return channel < kNumAnalogInputs && channel >= 0;
@@ -72,14 +77,18 @@ HAL_Bool HAL_CheckAnalogInputChannel(int32_t channel) {
void HAL_SetAnalogInputSimDevice(HAL_AnalogInputHandle handle,
HAL_SimDeviceHandle device) {
auto port = analogInputHandles->Get(handle);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
SimAnalogInData[port->channel].simDevice = device;
}
void HAL_SetAnalogSampleRate(double samplesPerSecond, int32_t* status) {
// No op
}
double HAL_GetAnalogSampleRate(int32_t* status) { return kDefaultSampleRate; }
double HAL_GetAnalogSampleRate(int32_t* status) {
return kDefaultSampleRate;
}
void HAL_SetAnalogAverageBits(HAL_AnalogInputHandle analogPortHandle,
int32_t bits, int32_t* status) {
auto port = analogInputHandles->Get(analogPortHandle);

View File

@@ -47,8 +47,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle,
HAL_AnalogOutputHandle handle =
analogOutputHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = analogOutputHandles->Get(handle);
if (port == nullptr) { // would only error on thread issue
@@ -66,7 +67,9 @@ HAL_AnalogOutputHandle HAL_InitializeAnalogOutputPort(HAL_PortHandle portHandle,
void HAL_FreeAnalogOutputPort(HAL_AnalogOutputHandle analogOutputHandle) {
// no status, so no need to check for a proper free.
auto port = analogOutputHandles->Get(analogOutputHandle);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
analogOutputHandles->Free(analogOutputHandle);
SimAnalogOutData[port->channel].initialized = false;
}

View File

@@ -99,7 +99,9 @@ void HAL_CleanAnalogTrigger(HAL_AnalogTriggerHandle analogTriggerHandle,
int32_t* status) {
auto trigger = analogTriggerHandles->Get(analogTriggerHandle);
analogTriggerHandles->Free(analogTriggerHandle);
if (trigger == nullptr) return;
if (trigger == nullptr) {
return;
}
SimAnalogTriggerData[trigger->index].initialized = false;
// caller owns the analog input handle.
}
@@ -128,10 +130,14 @@ void HAL_SetAnalogTriggerLimitsRaw(HAL_AnalogTriggerHandle analogTriggerHandle,
double trigLower =
GetAnalogValueToVoltage(trigger->analogHandle, lower, status);
if (status != 0) return;
if (status != 0) {
return;
}
double trigUpper =
GetAnalogValueToVoltage(trigger->analogHandle, upper, status);
if (status != 0) return;
if (status != 0) {
return;
}
SimAnalogTriggerData[trigger->index].triggerUpperBound = trigUpper;
SimAnalogTriggerData[trigger->index].triggerLowerBound = trigLower;

View File

@@ -35,7 +35,9 @@ extern "C" {
HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle,
HAL_Bool input, int32_t* status) {
hal::init::CheckInit();
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex) {
@@ -46,8 +48,9 @@ HAL_DigitalHandle HAL_InitializeDIOPort(HAL_PortHandle portHandle,
auto handle =
digitalChannelHandles->Allocate(channel, HAL_HandleEnum::DIO, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO);
if (port == nullptr) { // would only occur on thread issue.
@@ -72,13 +75,17 @@ void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle) {
auto port = digitalChannelHandles->Get(dioPortHandle, HAL_HandleEnum::DIO);
// no status, so no need to check for a proper free.
digitalChannelHandles->Free(dioPortHandle, HAL_HandleEnum::DIO);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
SimDIOData[port->channel].initialized = false;
}
void HAL_SetDIOSimDevice(HAL_DigitalHandle handle, HAL_SimDeviceHandle device) {
auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::DIO);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
SimDIOData[port->channel].simDevice = device;
}
@@ -104,7 +111,9 @@ HAL_DigitalPWMHandle HAL_AllocateDigitalPWM(int32_t* status) {
void HAL_FreeDigitalPWM(HAL_DigitalPWMHandle pwmGenerator, int32_t* status) {
auto port = digitalPWMHandles->Get(pwmGenerator);
digitalPWMHandles->Free(pwmGenerator);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
int32_t id = *port;
SimDigitalPWMData[id].initialized = false;
}
@@ -129,8 +138,12 @@ void HAL_SetDigitalPWMDutyCycle(HAL_DigitalPWMHandle pwmGenerator,
return;
}
int32_t id = *port;
if (dutyCycle > 1.0) dutyCycle = 1.0;
if (dutyCycle < 0.0) dutyCycle = 0.0;
if (dutyCycle > 1.0) {
dutyCycle = 1.0;
}
if (dutyCycle < 0.0) {
dutyCycle = 0.0;
}
SimDigitalPWMData[id].dutyCycle = dutyCycle;
}
@@ -153,7 +166,9 @@ void HAL_SetDIO(HAL_DigitalHandle dioPortHandle, HAL_Bool value,
return;
}
if (value != 0 && value != 1) {
if (value != 0) value = 1;
if (value != 0) {
value = 1;
}
}
SimDIOData[port->channel].value = value;
}
@@ -176,8 +191,12 @@ HAL_Bool HAL_GetDIO(HAL_DigitalHandle dioPortHandle, int32_t* status) {
return false;
}
HAL_Bool value = SimDIOData[port->channel].value;
if (value > 1) value = 1;
if (value < 0) value = 0;
if (value > 1) {
value = 1;
}
if (value < 0) {
value = 0;
}
return value;
}
@@ -188,8 +207,12 @@ HAL_Bool HAL_GetDIODirection(HAL_DigitalHandle dioPortHandle, int32_t* status) {
return false;
}
HAL_Bool value = SimDIOData[port->channel].isInput;
if (value > 1) value = 1;
if (value < 0) value = 0;
if (value > 1) {
value = 1;
}
if (value < 0) {
value = 0;
}
return value;
}

View File

@@ -5,7 +5,9 @@
#include "hal/DMA.h"
extern "C" {
HAL_DMAHandle HAL_InitializeDMA(int32_t* status) { return HAL_kInvalidHandle; }
HAL_DMAHandle HAL_InitializeDMA(int32_t* status) {
return HAL_kInvalidHandle;
}
void HAL_FreeDMA(HAL_DMAHandle handle) {}
void HAL_SetDMAPause(HAL_DMAHandle handle, HAL_Bool pause, int32_t* status) {}
@@ -47,7 +49,9 @@ void HAL_SetDMAExternalTrigger(HAL_DMAHandle handle,
void HAL_StartDMA(HAL_DMAHandle handle, int32_t queueDepth, int32_t* status) {}
void HAL_StopDMA(HAL_DMAHandle handle, int32_t* status) {}
void* HAL_GetDMADirectPointer(HAL_DMAHandle handle) { return nullptr; }
void* HAL_GetDMADirectPointer(HAL_DMAHandle handle) {
return nullptr;
}
enum HAL_DMAReadStatus HAL_ReadDMADirect(void* dmaPointer,
HAL_DMASample* dmaSample,

View File

@@ -52,7 +52,9 @@ bool remapDigitalSource(HAL_Handle digitalSourceHandle,
}
}
int32_t remapMXPChannel(int32_t channel) { return channel - 10; }
int32_t remapMXPChannel(int32_t channel) {
return channel - 10;
}
int32_t remapMXPPWMChannel(int32_t channel) {
if (channel < 14) {

View File

@@ -56,9 +56,10 @@ 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) {
auto errorHandler = sendErrorHandler.load();
if (errorHandler)
if (errorHandler) {
return errorHandler(isError, errorCode, isLVCode, details, location,
callStack, printMsg);
}
// Avoid flooding console by keeping track of previous 5 error
// messages and only printing again if they're longer than 1 second old.
static constexpr int KEEP_MSGS = 5;
@@ -76,7 +77,9 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode,
auto curTime = fpga_clock::now();
int i;
for (i = 0; i < KEEP_MSGS; ++i) {
if (prevMsg[i] == details) break;
if (prevMsg[i] == details) {
break;
}
}
int retval = 0;
if (i == KEEP_MSGS || (curTime - prevMsgTime[i]) >= std::chrono::seconds(1)) {
@@ -177,9 +180,13 @@ char* HAL_GetJoystickName(int32_t joystickNum) {
return name;
}
void HAL_FreeJoystickName(char* name) { std::free(name); }
void HAL_FreeJoystickName(char* name) {
std::free(name);
}
int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) { return 0; }
int32_t HAL_GetJoystickAxisType(int32_t joystickNum, int32_t axis) {
return 0;
}
int32_t HAL_SetJoystickOutputs(int32_t joystickNum, int64_t outputs,
int32_t leftRumble, int32_t rightRumble) {
@@ -197,7 +204,9 @@ int32_t HAL_GetMatchInfo(HAL_MatchInfo* info) {
return 0;
}
void HAL_ObserveUserProgramStarting(void) { HALSIM_SetProgramStarted(); }
void HAL_ObserveUserProgramStarting(void) {
HALSIM_SetProgramStarted();
}
void HAL_ObserveUserProgramDisabled(void) {
// TODO
@@ -228,12 +237,16 @@ HAL_Bool HAL_IsNewControlData(void) {
std::scoped_lock lock(newDSDataAvailableMutex);
int& lastCount = GetThreadLocalLastCount();
int currentCount = newDSDataAvailableCounter;
if (lastCount == currentCount) return false;
if (lastCount == currentCount) {
return false;
}
lastCount = currentCount;
return true;
}
void HAL_WaitForDSData(void) { HAL_WaitForDSDataTimeout(0); }
void HAL_WaitForDSData(void) {
HAL_WaitForDSDataTimeout(0);
}
HAL_Bool HAL_WaitForDSDataTimeout(double timeout) {
std::unique_lock lock(newDSDataAvailableMutex);
@@ -270,7 +283,9 @@ constexpr int32_t refNumber = 42;
static int32_t newDataOccur(uint32_t refNum) {
// Since we could get other values, require our specific handle
// to signal our threads
if (refNum != refNumber) return 0;
if (refNum != refNumber) {
return 0;
}
SimDriverStationData->CallNewDataCallbacks();
std::scoped_lock lock(newDSDataAvailableMutex);
// Nofify all threads
@@ -284,11 +299,15 @@ void HAL_InitializeDriverStation(void) {
static std::atomic_bool initialized{false};
static wpi::mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return;
if (initialized) {
return;
}
std::scoped_lock lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return;
if (initialized) {
return;
}
SimDriverStationData->ResetData();
@@ -300,6 +319,8 @@ void HAL_InitializeDriverStation(void) {
initialized = true;
}
void HAL_ReleaseDSMutex(void) { newDataOccur(refNumber); }
void HAL_ReleaseDSMutex(void) {
newDataOccur(refNumber);
}
} // extern "C"

View File

@@ -62,14 +62,18 @@ HAL_DutyCycleHandle HAL_InitializeDutyCycle(HAL_Handle digitalSourceHandle,
void HAL_FreeDutyCycle(HAL_DutyCycleHandle dutyCycleHandle) {
auto dutyCycle = dutyCycleHandles->Get(dutyCycleHandle);
dutyCycleHandles->Free(dutyCycleHandle);
if (dutyCycle == nullptr) return;
if (dutyCycle == nullptr) {
return;
}
SimDutyCycleData[dutyCycle->index].initialized = false;
}
void HAL_SetDutyCycleSimDevice(HAL_EncoderHandle handle,
HAL_SimDeviceHandle device) {
auto dutyCycle = dutyCycleHandles->Get(handle);
if (dutyCycle == nullptr) return;
if (dutyCycle == nullptr) {
return;
}
SimDutyCycleData[dutyCycle->index].simDevice = device;
}

View File

@@ -93,7 +93,9 @@ HAL_EncoderHandle HAL_InitializeEncoder(
void HAL_FreeEncoder(HAL_EncoderHandle encoderHandle, int32_t* status) {
auto encoder = encoderHandles->Get(encoderHandle);
encoderHandles->Free(encoderHandle);
if (encoder == nullptr) return;
if (encoder == nullptr) {
return;
}
if (isHandleType(encoder->nativeHandle, HAL_HandleEnum::FPGAEncoder)) {
fpgaEncoderHandles->Free(encoder->nativeHandle);
} else if (isHandleType(encoder->nativeHandle, HAL_HandleEnum::Counter)) {
@@ -105,7 +107,9 @@ void HAL_FreeEncoder(HAL_EncoderHandle encoderHandle, int32_t* status) {
void HAL_SetEncoderSimDevice(HAL_EncoderHandle handle,
HAL_SimDeviceHandle device) {
auto encoder = encoderHandles->Get(handle);
if (encoder == nullptr) return;
if (encoder == nullptr) {
return;
}
SimEncoderData[encoder->index].simDevice = device;
}

View File

@@ -85,7 +85,9 @@ int HAL_LoadOneExtension(const char* library) {
auto init = reinterpret_cast<halsim_extension_init_func_t*>(
DLSYM(handle, "HALSIM_InitExtension"));
if (init) rc = (*init)();
if (init) {
rc = (*init)();
}
if (rc != 0) {
wpi::outs() << "HAL Extensions: Failed to load extension\n";
@@ -114,7 +116,9 @@ int HAL_LoadExtensions(void) {
for (auto& libref : libraries) {
wpi::SmallString<128> library(libref);
rc = HAL_LoadOneExtension(library.c_str());
if (rc < 0) break;
if (rc < 0) {
break;
}
}
return rc;
}
@@ -122,8 +126,9 @@ int HAL_LoadExtensions(void) {
void HAL_RegisterExtension(const char* name, void* data) {
std::scoped_lock lock(gExtensionRegistryMutex);
gExtensionRegistry.emplace_back(name, data);
for (auto&& listener : gExtensionListeners)
for (auto&& listener : gExtensionListeners) {
listener.second(listener.first, name, data);
}
}
void HAL_RegisterExtensionListener(void* param,
@@ -131,8 +136,9 @@ void HAL_RegisterExtensionListener(void* param,
void* data)) {
std::scoped_lock lock(gExtensionRegistryMutex);
gExtensionListeners.emplace_back(param, func);
for (auto&& extension : gExtensionRegistry)
for (auto&& extension : gExtensionRegistry) {
func(param, extension.first, extension.second);
}
}
void HAL_SetShowExtensionsNotFoundMessages(HAL_Bool showMessage) {

View File

@@ -43,8 +43,9 @@ class SimPeriodicCallbackRegistry : public impl::SimCallbackRegistryBase {
std::scoped_lock lock(m_mutex);
#endif
if (m_callbacks) {
for (auto&& cb : *m_callbacks)
for (auto&& cb : *m_callbacks) {
reinterpret_cast<HALSIM_SimPeriodicCallback>(cb.callback)(cb.param);
}
}
}
};
@@ -122,14 +123,20 @@ extern "C" {
HAL_PortHandle HAL_GetPort(int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
if (channel < 0 || channel >= 255) {
return HAL_kInvalidHandle;
}
return createPortHandle(channel, 1);
}
HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
if (module < 0 || module >= 255) return HAL_kInvalidHandle;
if (channel < 0 || channel >= 255) {
return HAL_kInvalidHandle;
}
if (module < 0 || module >= 255) {
return HAL_kInvalidHandle;
}
return createPortHandle(channel, module);
}
@@ -250,9 +257,13 @@ const char* HAL_GetErrorMessage(int32_t code) {
}
}
HAL_RuntimeType HAL_GetRuntimeType(void) { return runtimeType; }
HAL_RuntimeType HAL_GetRuntimeType(void) {
return runtimeType;
}
void HALSIM_SetRuntimeType(HAL_RuntimeType type) { runtimeType = type; }
void HALSIM_SetRuntimeType(HAL_RuntimeType type) {
runtimeType = type;
}
int32_t HAL_GetFPGAVersion(int32_t* status) {
return 2018; // Automatically script this at some point
@@ -262,13 +273,17 @@ int64_t HAL_GetFPGARevision(int32_t* status) {
return 0; // TODO: Find a better number to return;
}
uint64_t HAL_GetFPGATime(int32_t* status) { return hal::GetFPGATime(); }
uint64_t HAL_GetFPGATime(int32_t* status) {
return hal::GetFPGATime();
}
uint64_t HAL_ExpandFPGATime(uint32_t unexpanded_lower, int32_t* status) {
// Capture the current FPGA time. This will give us the upper half of the
// clock.
uint64_t fpga_time = HAL_GetFPGATime(status);
if (*status != 0) return 0;
if (*status != 0) {
return 0;
}
// Now, we need to detect the case where the lower bits rolled over after we
// sampled. In that case, the upper bits will be 1 bigger than they should
@@ -302,11 +317,15 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) {
static std::atomic_bool initialized{false};
static wpi::mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return true;
if (initialized) {
return true;
}
std::scoped_lock lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return true;
if (initialized) {
return true;
}
hal::init::InitializeHAL();
@@ -334,7 +353,9 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) {
#endif // _WIN32
wpi::outs().SetUnbuffered();
if (HAL_LoadExtensions() < 0) return false;
if (HAL_LoadExtensions() < 0) {
return false;
}
return true; // Add initialization if we need to at a later point
}
@@ -355,9 +376,13 @@ void HAL_OnShutdown(void* param, void (*func)(void*)) {
gOnShutdown.emplace_back(param, func);
}
void HAL_SimPeriodicBefore(void) { gSimPeriodicBefore(); }
void HAL_SimPeriodicBefore(void) {
gSimPeriodicBefore();
}
void HAL_SimPeriodicAfter(void) { gSimPeriodicAfter(); }
void HAL_SimPeriodicAfter(void) {
gSimPeriodicAfter();
}
int32_t HALSIM_RegisterSimPeriodicBeforeCallback(
HALSIM_SimPeriodicCallback callback, void* param) {

View File

@@ -9,6 +9,8 @@
namespace hal {
namespace init {
std::atomic_bool HAL_IsInitialized{false};
void RunInitialize() { HAL_Initialize(500, 0); }
void RunInitialize() {
HAL_Initialize(500, 0);
}
} // namespace init
} // namespace hal

View File

@@ -11,7 +11,9 @@ namespace init {
extern std::atomic_bool HAL_IsInitialized;
extern void RunInitialize();
static inline void CheckInit() {
if (HAL_IsInitialized.load(std::memory_order_relaxed)) return;
if (HAL_IsInitialized.load(std::memory_order_relaxed)) {
return;
}
RunInitialize();
}

View File

@@ -37,5 +37,7 @@ int32_t HAL_ReadI2C(HAL_I2CPort port, int32_t deviceAddress, uint8_t* buffer,
SimI2CData[port].Read(deviceAddress, buffer, count);
return 0;
}
void HAL_CloseI2C(HAL_I2CPort port) { SimI2CData[port].initialized = false; }
void HAL_CloseI2C(HAL_I2CPort port) {
SimI2CData[port].initialized = false;
}
} // extern "C"

View File

@@ -125,18 +125,30 @@ static void ProcessInterruptDigitalSynchronous(const char* name, void* param,
SynchronousWaitDataHandle handle =
static_cast<SynchronousWaitDataHandle>(handleTmp);
auto interruptData = synchronousInterruptHandles->Get(handle);
if (interruptData == nullptr) return;
if (interruptData == nullptr) {
return;
}
auto interrupt = interruptHandles->Get(interruptData->interruptHandle);
if (interrupt == nullptr) return;
if (interrupt == nullptr) {
return;
}
// Have a valid interrupt
if (value->type != HAL_Type::HAL_BOOLEAN) return;
if (value->type != HAL_Type::HAL_BOOLEAN) {
return;
}
bool retVal = value->data.v_boolean;
// If no change in interrupt, return;
if (retVal == interrupt->previousState) return;
if (retVal == interrupt->previousState) {
return;
}
// If its a falling change, and we dont fire on falling return
if (interrupt->previousState && !interrupt->fireOnDown) return;
if (interrupt->previousState && !interrupt->fireOnDown) {
return;
}
// If its a rising change, and we dont fire on rising return.
if (!interrupt->previousState && !interrupt->fireOnUp) return;
if (!interrupt->previousState && !interrupt->fireOnUp) {
return;
}
interruptData->waitPredicate = true;
@@ -158,11 +170,17 @@ static void ProcessInterruptAnalogSynchronous(const char* name, void* param,
SynchronousWaitDataHandle handle =
static_cast<SynchronousWaitDataHandle>(handleTmp);
auto interruptData = synchronousInterruptHandles->Get(handle);
if (interruptData == nullptr) return;
if (interruptData == nullptr) {
return;
}
auto interrupt = interruptHandles->Get(interruptData->interruptHandle);
if (interrupt == nullptr) return;
if (interrupt == nullptr) {
return;
}
// Have a valid interrupt
if (value->type != HAL_Type::HAL_DOUBLE) return;
if (value->type != HAL_Type::HAL_DOUBLE) {
return;
}
int32_t status = 0;
bool retVal = GetAnalogTriggerValue(interrupt->portHandle,
interrupt->trigType, &status);
@@ -173,11 +191,17 @@ static void ProcessInterruptAnalogSynchronous(const char* name, void* param,
interruptData->waitCond.notify_all();
}
// If no change in interrupt, return;
if (retVal == interrupt->previousState) return;
if (retVal == interrupt->previousState) {
return;
}
// If its a falling change, and we dont fire on falling return
if (interrupt->previousState && !interrupt->fireOnDown) return;
if (interrupt->previousState && !interrupt->fireOnDown) {
return;
}
// If its a rising change, and we dont fire on rising return.
if (!interrupt->previousState && !interrupt->fireOnUp) return;
if (!interrupt->previousState && !interrupt->fireOnUp) {
return;
}
interruptData->waitPredicate = true;
@@ -204,7 +228,9 @@ static int64_t WaitForInterruptDigital(HAL_InterruptHandle handle,
int32_t digitalIndex = GetDigitalInputChannel(interrupt->portHandle, &status);
if (status != 0) return WaitResult::Timeout;
if (status != 0) {
return WaitResult::Timeout;
}
interrupt->previousState = SimDIOData[digitalIndex].value;
@@ -235,7 +261,9 @@ static int64_t WaitForInterruptDigital(HAL_InterruptHandle handle,
(void)synchronousInterruptHandles->Free(dataHandle);
// Check for what to return
if (timedOut) return WaitResult::Timeout;
if (timedOut) {
return WaitResult::Timeout;
}
// True => false, Falling
if (interrupt->previousState) {
// Set our return value and our timestamps
@@ -265,12 +293,16 @@ static int64_t WaitForInterruptAnalog(HAL_InterruptHandle handle,
interrupt->previousState = GetAnalogTriggerValue(
interrupt->portHandle, interrupt->trigType, &status);
if (status != 0) return WaitResult::Timeout;
if (status != 0) {
return WaitResult::Timeout;
}
int32_t analogIndex =
GetAnalogTriggerInputIndex(interrupt->portHandle, &status);
if (status != 0) return WaitResult::Timeout;
if (status != 0) {
return WaitResult::Timeout;
}
int32_t uid = SimAnalogInData[analogIndex].voltage.RegisterCallback(
&ProcessInterruptAnalogSynchronous,
@@ -299,7 +331,9 @@ static int64_t WaitForInterruptAnalog(HAL_InterruptHandle handle,
(void)synchronousInterruptHandles->Free(dataHandle);
// Check for what to return
if (timedOut) return WaitResult::Timeout;
if (timedOut) {
return WaitResult::Timeout;
}
// True => false, Falling
if (interrupt->previousState) {
// Set our return value and our timestamps
@@ -342,28 +376,40 @@ static void ProcessInterruptDigitalAsynchronous(const char* name, void* param,
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
HAL_InterruptHandle handle = static_cast<HAL_InterruptHandle>(handleTmp);
auto interrupt = interruptHandles->Get(handle);
if (interrupt == nullptr) return;
if (interrupt == nullptr) {
return;
}
// Have a valid interrupt
if (value->type != HAL_Type::HAL_BOOLEAN) return;
if (value->type != HAL_Type::HAL_BOOLEAN) {
return;
}
bool retVal = value->data.v_boolean;
// If no change in interrupt, return;
if (retVal == interrupt->previousState) return;
if (retVal == interrupt->previousState) {
return;
}
int32_t mask = 0;
if (interrupt->previousState) {
interrupt->previousState = retVal;
interrupt->fallingTimestamp = hal::GetFPGATime();
mask = 1 << (8 + interrupt->index);
if (!interrupt->fireOnDown) return;
if (!interrupt->fireOnDown) {
return;
}
} else {
interrupt->previousState = retVal;
interrupt->risingTimestamp = hal::GetFPGATime();
mask = 1 << (interrupt->index);
if (!interrupt->fireOnUp) return;
if (!interrupt->fireOnUp) {
return;
}
}
// run callback
auto callback = interrupt->callbackFunction;
if (callback == nullptr) return;
if (callback == nullptr) {
return;
}
callback(mask, interrupt->callbackParam);
}
@@ -374,31 +420,45 @@ static void ProcessInterruptAnalogAsynchronous(const char* name, void* param,
uintptr_t handleTmp = reinterpret_cast<uintptr_t>(param);
HAL_InterruptHandle handle = static_cast<HAL_InterruptHandle>(handleTmp);
auto interrupt = interruptHandles->Get(handle);
if (interrupt == nullptr) return;
if (interrupt == nullptr) {
return;
}
// Have a valid interrupt
if (value->type != HAL_Type::HAL_DOUBLE) return;
if (value->type != HAL_Type::HAL_DOUBLE) {
return;
}
int32_t status = 0;
bool retVal = GetAnalogTriggerValue(interrupt->portHandle,
interrupt->trigType, &status);
if (status != 0) return;
if (status != 0) {
return;
}
// If no change in interrupt, return;
if (retVal == interrupt->previousState) return;
if (retVal == interrupt->previousState) {
return;
}
int mask = 0;
if (interrupt->previousState) {
interrupt->previousState = retVal;
interrupt->fallingTimestamp = hal::GetFPGATime();
if (!interrupt->fireOnDown) return;
if (!interrupt->fireOnDown) {
return;
}
mask = 1 << (8 + interrupt->index);
} else {
interrupt->previousState = retVal;
interrupt->risingTimestamp = hal::GetFPGATime();
if (!interrupt->fireOnUp) return;
if (!interrupt->fireOnUp) {
return;
}
mask = 1 << (interrupt->index);
}
// run callback
auto callback = interrupt->callbackFunction;
if (callback == nullptr) return;
if (callback == nullptr) {
return;
}
callback(mask, interrupt->callbackParam);
}
@@ -406,7 +466,9 @@ static void EnableInterruptsDigital(HAL_InterruptHandle handle,
Interrupt* interrupt) {
int32_t status = 0;
int32_t digitalIndex = GetDigitalInputChannel(interrupt->portHandle, &status);
if (status != 0) return;
if (status != 0) {
return;
}
interrupt->previousState = SimDIOData[digitalIndex].value;
@@ -421,12 +483,16 @@ static void EnableInterruptsAnalog(HAL_InterruptHandle handle,
int32_t status = 0;
int32_t analogIndex =
GetAnalogTriggerInputIndex(interrupt->portHandle, &status);
if (status != 0) return;
if (status != 0) {
return;
}
status = 0;
interrupt->previousState = GetAnalogTriggerValue(
interrupt->portHandle, interrupt->trigType, &status);
if (status != 0) return;
if (status != 0) {
return;
}
int32_t uid = SimAnalogInData[analogIndex].voltage.RegisterCallback(
&ProcessInterruptAnalogAsynchronous,
@@ -469,20 +535,26 @@ void HAL_DisableInterrupts(HAL_InterruptHandle interruptHandle,
}
// No need to disable if we are already disabled
if (interrupt->callbackId < 0) return;
if (interrupt->callbackId < 0) {
return;
}
if (interrupt->isAnalog) {
// Do analog
int32_t status = 0;
int32_t analogIndex =
GetAnalogTriggerInputIndex(interrupt->portHandle, &status);
if (status != 0) return;
if (status != 0) {
return;
}
SimAnalogInData[analogIndex].voltage.CancelCallback(interrupt->callbackId);
} else {
int32_t status = 0;
int32_t digitalIndex =
GetDigitalInputChannel(interrupt->portHandle, &status);
if (status != 0) return;
if (status != 0) {
return;
}
SimDIOData[digitalIndex].value.CancelCallback(interrupt->callbackId);
}
interrupt->callbackId = -1;

View File

@@ -22,7 +22,9 @@ static std::atomic<uint64_t> programStepTime{0};
namespace hal {
namespace init {
void InitializeMockHooks() { wpi::SetNowImpl(GetFPGATime); }
void InitializeMockHooks() {
wpi::SetNowImpl(GetFPGATime);
}
} // namespace init
} // namespace hal
@@ -30,11 +32,15 @@ namespace hal {
void RestartTiming() {
programStartTime = wpi::NowDefault();
programStepTime = 0;
if (programPauseTime != 0) programPauseTime = programStartTime.load();
if (programPauseTime != 0) {
programPauseTime = programStartTime.load();
}
}
void PauseTiming() {
if (programPauseTime == 0) programPauseTime = wpi::NowDefault();
if (programPauseTime == 0) {
programPauseTime = wpi::NowDefault();
}
}
void ResumeTiming() {
@@ -44,20 +50,32 @@ void ResumeTiming() {
}
}
bool IsTimingPaused() { return programPauseTime != 0; }
bool IsTimingPaused() {
return programPauseTime != 0;
}
void StepTiming(uint64_t delta) { programStepTime += delta; }
void StepTiming(uint64_t delta) {
programStepTime += delta;
}
uint64_t GetFPGATime() {
uint64_t curTime = programPauseTime;
if (curTime == 0) curTime = wpi::NowDefault();
if (curTime == 0) {
curTime = wpi::NowDefault();
}
return curTime + programStepTime - programStartTime;
}
double GetFPGATimestamp() { return GetFPGATime() * 1.0e-6; }
double GetFPGATimestamp() {
return GetFPGATime() * 1.0e-6;
}
void SetProgramStarted() { programStarted = true; }
bool GetProgramStarted() { return programStarted; }
void SetProgramStarted() {
programStarted = true;
}
bool GetProgramStarted() {
return programStarted;
}
} // namespace hal
using namespace hal;
@@ -72,11 +90,17 @@ void HALSIM_WaitForProgramStart(void) {
}
}
void HALSIM_SetProgramStarted(void) { SetProgramStarted(); }
void HALSIM_SetProgramStarted(void) {
SetProgramStarted();
}
HAL_Bool HALSIM_GetProgramStarted(void) { return GetProgramStarted(); }
HAL_Bool HALSIM_GetProgramStarted(void) {
return GetProgramStarted();
}
void HALSIM_RestartTiming(void) { RestartTiming(); }
void HALSIM_RestartTiming(void) {
RestartTiming();
}
void HALSIM_PauseTiming(void) {
PauseTiming();
@@ -88,7 +112,9 @@ void HALSIM_ResumeTiming(void) {
ResumeNotifiers();
}
HAL_Bool HALSIM_IsTimingPaused(void) { return IsTimingPaused(); }
HAL_Bool HALSIM_IsTimingPaused(void) {
return IsTimingPaused();
}
void HALSIM_StepTiming(uint64_t delta) {
WaitNotifiers();

View File

@@ -68,7 +68,9 @@ void InitializeNotifier() {
}
} // namespace init
void PauseNotifiers() { notifiersPaused = true; }
void PauseNotifiers() {
notifiersPaused = true;
}
void ResumeNotifiers() {
notifiersPaused = false;
@@ -107,7 +109,9 @@ void WaitNotifiers() {
// No longer need to wait for it, put at end so it can be erased
std::swap(it, waiters[--end]);
}
if (count == 0) break;
if (count == 0) {
break;
}
waiters.resize(count);
notifiersWaiterCond.wait_for(ulock, std::chrono::duration<double>(1));
}
@@ -148,7 +152,9 @@ void WakeupWaitNotifiers() {
// No longer need to wait for it, put at end so it can be erased
it.swap(waiters[--end]);
}
if (count == 0) break;
if (count == 0) {
break;
}
waiters.resize(count);
notifiersWaiterCond.wait_for(ulock, std::chrono::duration<double>(1));
}
@@ -171,14 +177,18 @@ HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) {
void HAL_SetNotifierName(HAL_NotifierHandle notifierHandle, const char* name,
int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier) {
return;
}
std::scoped_lock lock(notifier->mutex);
notifier->name = name;
}
void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier) {
return;
}
{
std::scoped_lock lock(notifier->mutex);
@@ -190,7 +200,9 @@ void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
auto notifier = notifierHandles->Free(notifierHandle);
if (!notifier) return;
if (!notifier) {
return;
}
// Just in case HAL_StopNotifier() wasn't called...
{
@@ -204,7 +216,9 @@ void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) {
void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle,
uint64_t triggerTime, int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier) {
return;
}
{
std::scoped_lock lock(notifier->mutex);
@@ -219,7 +233,9 @@ void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle,
void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle,
int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return;
if (!notifier) {
return;
}
{
std::scoped_lock lock(notifier->mutex);
@@ -230,7 +246,9 @@ void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle,
uint64_t HAL_WaitForNotifierAlarm(HAL_NotifierHandle notifierHandle,
int32_t* status) {
auto notifier = notifierHandles->Get(notifierHandle);
if (!notifier) return 0;
if (!notifier) {
return 0;
}
std::unique_lock ulock(notifiersWaiterMutex);
std::unique_lock lock(notifier->mutex);
@@ -265,8 +283,9 @@ uint64_t HALSIM_GetNextNotifierTimeout(void) {
notifierHandles->ForEach([&](HAL_NotifierHandle, Notifier* notifier) {
std::scoped_lock lock(notifier->mutex);
if (notifier->active && notifier->waitTimeValid &&
timeout > notifier->waitTime)
timeout > notifier->waitTime) {
timeout = notifier->waitTime;
}
});
return timeout;
}
@@ -275,7 +294,9 @@ int32_t HALSIM_GetNumNotifiers(void) {
int32_t count = 0;
notifierHandles->ForEach([&](HAL_NotifierHandle, Notifier* notifier) {
std::scoped_lock lock(notifier->mutex);
if (notifier->active) ++count;
if (notifier->active) {
++count;
}
});
return count;
}
@@ -284,7 +305,9 @@ int32_t HALSIM_GetNotifierInfo(struct HALSIM_NotifierInfo* arr, int32_t size) {
int32_t num = 0;
notifierHandles->ForEach([&](HAL_NotifierHandle handle, Notifier* notifier) {
std::scoped_lock lock(notifier->mutex);
if (!notifier->active) return;
if (!notifier->active) {
return;
}
if (num < size) {
arr[num].handle = handle;
if (notifier->name.empty()) {

View File

@@ -51,7 +51,9 @@ HAL_Bool HAL_CheckPDPChannel(int32_t channel) {
return channel < kNumPDPChannels && channel >= 0;
}
void HAL_CleanPDP(HAL_PDPHandle handle) { HAL_CleanCAN(handle); }
void HAL_CleanPDP(HAL_PDPHandle handle) {
HAL_CleanCAN(handle);
}
double HAL_GetPDPTemperature(HAL_PDPHandle handle, int32_t* status) {
auto module = hal::can::GetCANModuleFromHandle(handle, status);

View File

@@ -24,7 +24,9 @@ extern "C" {
HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle,
int32_t* status) {
hal::init::CheckInit();
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex) {
@@ -43,8 +45,9 @@ HAL_DigitalHandle HAL_InitializePWMPort(HAL_PortHandle portHandle,
auto handle =
digitalChannelHandles->Allocate(channel, HAL_HandleEnum::PWM, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = digitalChannelHandles->Get(handle, HAL_HandleEnum::PWM);
if (port == nullptr) { // would only occur on thread issue.
@@ -89,7 +92,9 @@ void HAL_SetPWMConfig(HAL_DigitalHandle pwmPortHandle, double max,
// calculate the loop time in milliseconds
double loopTime =
HAL_GetPWMLoopTiming(status) / (kSystemClockTicksPerMicrosecond * 1e3);
if (*status != 0) return;
if (*status != 0) {
return;
}
int32_t maxPwm = static_cast<int32_t>((max - kDefaultPwmCenter) / loopTime +
kDefaultPwmStepsDown - 1);
@@ -249,8 +254,12 @@ double HAL_GetPWMSpeed(HAL_DigitalHandle pwmPortHandle, int32_t* status) {
}
double speed = SimPWMData[port->channel].speed;
if (speed > 1) speed = 1;
if (speed < -1) speed = -1;
if (speed > 1) {
speed = 1;
}
if (speed < -1) {
speed = -1;
}
return speed;
}
@@ -266,8 +275,12 @@ double HAL_GetPWMPosition(HAL_DigitalHandle pwmPortHandle, int32_t* status) {
}
double position = SimPWMData[port->channel].position;
if (position > 1) position = 1;
if (position < 0) position = 0;
if (position > 1) {
position = 1;
}
if (position < 0) {
position = 0;
}
return position;
}
@@ -293,7 +306,11 @@ void HAL_SetPWMPeriodScale(HAL_DigitalHandle pwmPortHandle, int32_t squelchMask,
SimPWMData[port->channel].periodScale = squelchMask;
}
int32_t HAL_GetPWMLoopTiming(int32_t* status) { return kExpectedLoopTiming; }
int32_t HAL_GetPWMLoopTiming(int32_t* status) {
return kExpectedLoopTiming;
}
uint64_t HAL_GetPWMCycleStartTime(int32_t* status) { return 0; }
uint64_t HAL_GetPWMCycleStartTime(int32_t* status) {
return 0;
}
} // extern "C"

View File

@@ -15,24 +15,64 @@ void InitializePorts() {}
} // namespace hal
extern "C" {
int32_t HAL_GetNumAccumulators(void) { return kNumAccumulators; }
int32_t HAL_GetNumAnalogTriggers(void) { return kNumAnalogTriggers; }
int32_t HAL_GetNumAnalogInputs(void) { return kNumAnalogInputs; }
int32_t HAL_GetNumAnalogOutputs(void) { return kNumAnalogOutputs; }
int32_t HAL_GetNumCounters(void) { return kNumCounters; }
int32_t HAL_GetNumDigitalHeaders(void) { return kNumDigitalHeaders; }
int32_t HAL_GetNumPWMHeaders(void) { return kNumPWMHeaders; }
int32_t HAL_GetNumDigitalChannels(void) { return kNumDigitalChannels; }
int32_t HAL_GetNumPWMChannels(void) { return kNumPWMChannels; }
int32_t HAL_GetNumDigitalPWMOutputs(void) { return kNumDigitalPWMOutputs; }
int32_t HAL_GetNumEncoders(void) { return kNumEncoders; }
int32_t HAL_GetNumInterrupts(void) { return kNumInterrupts; }
int32_t HAL_GetNumRelayChannels(void) { return kNumRelayChannels; }
int32_t HAL_GetNumRelayHeaders(void) { return kNumRelayHeaders; }
int32_t HAL_GetNumPCMModules(void) { return kNumPCMModules; }
int32_t HAL_GetNumSolenoidChannels(void) { return kNumSolenoidChannels; }
int32_t HAL_GetNumPDPModules(void) { return kNumPDPModules; }
int32_t HAL_GetNumPDPChannels(void) { return kNumPDPChannels; }
int32_t HAL_GetNumDutyCycles(void) { return kNumDutyCycles; }
int32_t HAL_GetNumAddressableLEDs(void) { return kNumAddressableLEDs; }
int32_t HAL_GetNumAccumulators(void) {
return kNumAccumulators;
}
int32_t HAL_GetNumAnalogTriggers(void) {
return kNumAnalogTriggers;
}
int32_t HAL_GetNumAnalogInputs(void) {
return kNumAnalogInputs;
}
int32_t HAL_GetNumAnalogOutputs(void) {
return kNumAnalogOutputs;
}
int32_t HAL_GetNumCounters(void) {
return kNumCounters;
}
int32_t HAL_GetNumDigitalHeaders(void) {
return kNumDigitalHeaders;
}
int32_t HAL_GetNumPWMHeaders(void) {
return kNumPWMHeaders;
}
int32_t HAL_GetNumDigitalChannels(void) {
return kNumDigitalChannels;
}
int32_t HAL_GetNumPWMChannels(void) {
return kNumPWMChannels;
}
int32_t HAL_GetNumDigitalPWMOutputs(void) {
return kNumDigitalPWMOutputs;
}
int32_t HAL_GetNumEncoders(void) {
return kNumEncoders;
}
int32_t HAL_GetNumInterrupts(void) {
return kNumInterrupts;
}
int32_t HAL_GetNumRelayChannels(void) {
return kNumRelayChannels;
}
int32_t HAL_GetNumRelayHeaders(void) {
return kNumRelayHeaders;
}
int32_t HAL_GetNumPCMModules(void) {
return kNumPCMModules;
}
int32_t HAL_GetNumSolenoidChannels(void) {
return kNumSolenoidChannels;
}
int32_t HAL_GetNumPDPModules(void) {
return kNumPDPModules;
}
int32_t HAL_GetNumPDPChannels(void) {
return kNumPDPChannels;
}
int32_t HAL_GetNumDutyCycles(void) {
return kNumDutyCycles;
}
int32_t HAL_GetNumAddressableLEDs(void) {
return kNumAddressableLEDs;
}
} // extern "C"

View File

@@ -16,8 +16,12 @@ void InitializePower() {}
// TODO: Fix the naming in here
extern "C" {
double HAL_GetVinVoltage(int32_t* status) { return SimRoboRioData->vInVoltage; }
double HAL_GetVinCurrent(int32_t* status) { return SimRoboRioData->vInCurrent; }
double HAL_GetVinVoltage(int32_t* status) {
return SimRoboRioData->vInVoltage;
}
double HAL_GetVinCurrent(int32_t* status) {
return SimRoboRioData->vInCurrent;
}
double HAL_GetUserVoltage6V(int32_t* status) {
return SimRoboRioData->userVoltage6V;
}

View File

@@ -36,7 +36,9 @@ extern "C" {
HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd,
int32_t* status) {
hal::init::CheckInit();
if (*status != 0) return HAL_kInvalidHandle;
if (*status != 0) {
return HAL_kInvalidHandle;
}
int16_t channel = getPortHandleChannel(portHandle);
if (channel == InvalidHandleIndex) {
@@ -44,12 +46,15 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd,
return HAL_kInvalidHandle;
}
if (!fwd) channel += kNumRelayHeaders; // add 4 to reverse channels
if (!fwd) {
channel += kNumRelayHeaders; // add 4 to reverse channels
}
auto handle = relayHandles->Allocate(channel, status);
if (*status != 0)
if (*status != 0) {
return HAL_kInvalidHandle; // failed to allocate. Pass error back.
}
auto port = relayHandles->Get(handle);
if (port == nullptr) { // would only occur on thread issue.
@@ -77,11 +82,14 @@ HAL_RelayHandle HAL_InitializeRelayPort(HAL_PortHandle portHandle, HAL_Bool fwd,
void HAL_FreeRelayPort(HAL_RelayHandle relayPortHandle) {
auto port = relayHandles->Get(relayPortHandle);
relayHandles->Free(relayPortHandle);
if (port == nullptr) return;
if (port->fwd)
if (port == nullptr) {
return;
}
if (port->fwd) {
SimRelayData[port->channel].initializedForward = false;
else
} else {
SimRelayData[port->channel].initializedReverse = false;
}
}
HAL_Bool HAL_CheckRelayChannel(int32_t channel) {
@@ -98,10 +106,11 @@ void HAL_SetRelay(HAL_RelayHandle relayPortHandle, HAL_Bool on,
*status = HAL_HANDLE_ERROR;
return;
}
if (port->fwd)
if (port->fwd) {
SimRelayData[port->channel].forward = on;
else
} else {
SimRelayData[port->channel].reverse = on;
}
}
HAL_Bool HAL_GetRelay(HAL_RelayHandle relayPortHandle, int32_t* status) {
@@ -110,9 +119,10 @@ HAL_Bool HAL_GetRelay(HAL_RelayHandle relayPortHandle, int32_t* status) {
*status = HAL_HANDLE_ERROR;
return false;
}
if (port->fwd)
if (port->fwd) {
return SimRelayData[port->channel].forward;
else
} else {
return SimRelayData[port->channel].reverse;
}
}
} // extern "C"

View File

@@ -32,13 +32,17 @@ int32_t HAL_WriteSPI(HAL_SPIPort port, const uint8_t* dataToSend,
int32_t HAL_ReadSPI(HAL_SPIPort port, uint8_t* buffer, int32_t count) {
return SimSPIData[port].Read(buffer, count);
}
void HAL_CloseSPI(HAL_SPIPort port) { SimSPIData[port].initialized = false; }
void HAL_CloseSPI(HAL_SPIPort port) {
SimSPIData[port].initialized = false;
}
void HAL_SetSPISpeed(HAL_SPIPort port, int32_t speed) {}
void HAL_SetSPIOpts(HAL_SPIPort port, HAL_Bool msbFirst,
HAL_Bool sampleOnTrailing, HAL_Bool clkIdleHigh) {}
void HAL_SetSPIChipSelectActiveHigh(HAL_SPIPort port, int32_t* status) {}
void HAL_SetSPIChipSelectActiveLow(HAL_SPIPort port, int32_t* status) {}
int32_t HAL_GetSPIHandle(HAL_SPIPort port) { return 0; }
int32_t HAL_GetSPIHandle(HAL_SPIPort port) {
return 0;
}
void HAL_SetSPIHandle(HAL_SPIPort port, int32_t handle) {}
void HAL_InitSPIAuto(HAL_SPIPort port, int32_t bufferSize, int32_t* status) {}

View File

@@ -26,7 +26,9 @@ HAL_SerialPortHandle HAL_InitializeSerialPortDirect(HAL_SerialPort port,
return HAL_kInvalidHandle;
}
int HAL_GetSerialFD(HAL_SerialPortHandle handle, int32_t* status) { return -1; }
int HAL_GetSerialFD(HAL_SerialPortHandle handle, int32_t* status) {
return -1;
}
void HAL_SetSerialBaudRate(HAL_SerialPortHandle handle, int32_t baud,
int32_t* status) {}

View File

@@ -78,7 +78,9 @@ HAL_SolenoidHandle HAL_InitializeSolenoidPort(HAL_PortHandle portHandle,
}
void HAL_FreeSolenoidPort(HAL_SolenoidHandle solenoidPortHandle) {
auto port = solenoidHandles->Get(solenoidPortHandle);
if (port == nullptr) return;
if (port == nullptr) {
return;
}
solenoidHandles->Free(solenoidPortHandle);
HALSIM_SetPCMSolenoidInitialized(port->module, port->channel, false);
int count = 0;

View File

@@ -41,7 +41,9 @@ void AddressableLEDData::SetData(const HAL_AddressableLEDData* d, int32_t len) {
int32_t AddressableLEDData::GetData(HAL_AddressableLEDData* d) {
std::scoped_lock lock(m_dataMutex);
int32_t len = length;
if (d) std::memcpy(d, m_data, len * sizeof(d[0]));
if (d) {
std::memcpy(d, m_data, len * sizeof(d[0]));
}
return len;
}
@@ -50,8 +52,9 @@ extern "C" {
int32_t HALSIM_FindAddressableLEDForChannel(int32_t channel) {
for (int i = 0; i < kNumAddressableLEDs; ++i) {
if (SimAddressableLEDData[i].initialized &&
SimAddressableLEDData[i].outputPort == channel)
SimAddressableLEDData[i].outputPort == channel) {
return i;
}
}
return -1;
}

View File

@@ -29,8 +29,9 @@ extern "C" {
int32_t HALSIM_FindAnalogTriggerForChannel(int32_t channel) {
for (int i = 0; i < kNumAnalogTriggers; ++i) {
if (SimAnalogTriggerData[i].initialized &&
SimAnalogTriggerData[i].inputPort == channel)
SimAnalogTriggerData[i].inputPort == channel) {
return i;
}
}
return -1;
}

View File

@@ -28,7 +28,9 @@ void CanData::ResetData() {
extern "C" {
void HALSIM_ResetCanData(void) { SimCanData->ResetData(); }
void HALSIM_ResetCanData(void) {
SimCanData->ResetData();
}
#define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \
HAL_SIMCALLBACKREGISTRY_DEFINE_CAPI_NOINDEX(TYPE, HALSIM, Can##CAPINAME, \

View File

@@ -27,7 +27,9 @@ void DIOData::ResetData() {
}
extern "C" {
void HALSIM_ResetDIOData(int32_t index) { SimDIOData[index].ResetData(); }
void HALSIM_ResetDIOData(int32_t index) {
SimDIOData[index].ResetData();
}
HAL_SimDeviceHandle HALSIM_GetDIOSimDevice(int32_t index) {
return SimDIOData[index].simDevice;

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