blob: 0b6d05efaeac874386da2bd57d9df7f6fd24910f [file] [log] [blame]
Austin Schuh812d0d12021-11-04 20:16:48 -07001// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
Brian Silverman8fce7482020-01-05 13:18:21 -08004
5#include "hal/HAL.h"
6
7#include <signal.h> // linux for kill
8#include <sys/prctl.h>
9#include <unistd.h>
10
11#include <atomic>
Austin Schuh812d0d12021-11-04 20:16:48 -070012#include <cstdio>
Brian Silverman8fce7482020-01-05 13:18:21 -080013#include <cstdlib>
14#include <fstream>
15#include <thread>
16
17#include <FRC_NetworkCommunication/FRCComm.h>
18#include <FRC_NetworkCommunication/LoadOut.h>
19#include <FRC_NetworkCommunication/UsageReporting.h>
Austin Schuh812d0d12021-11-04 20:16:48 -070020#include <fmt/format.h>
Brian Silverman8fce7482020-01-05 13:18:21 -080021#include <wpi/mutex.h>
Brian Silverman8fce7482020-01-05 13:18:21 -080022#include <wpi/timestamp.h>
23
24#include "HALInitializer.h"
Austin Schuh1e69f942020-11-14 15:06:14 -080025#include "HALInternal.h"
Brian Silverman8fce7482020-01-05 13:18:21 -080026#include "hal/ChipObject.h"
27#include "hal/DriverStation.h"
28#include "hal/Errors.h"
29#include "hal/Notifier.h"
30#include "hal/handles/HandlesInternal.h"
Austin Schuh1e69f942020-11-14 15:06:14 -080031#include "visa/visa.h"
Brian Silverman8fce7482020-01-05 13:18:21 -080032
33using namespace hal;
34
35static std::unique_ptr<tGlobal> global;
36static std::unique_ptr<tSysWatchdog> watchdog;
37
38using namespace hal;
39
40namespace hal {
41namespace init {
42void InitializeHAL() {
Austin Schuh812d0d12021-11-04 20:16:48 -070043 InitializeCTREPCM();
44 InitializeREVPH();
Brian Silverman8fce7482020-01-05 13:18:21 -080045 InitializeAddressableLED();
46 InitializeAccelerometer();
47 InitializeAnalogAccumulator();
Austin Schuh1e69f942020-11-14 15:06:14 -080048 InitializeAnalogGyro();
Brian Silverman8fce7482020-01-05 13:18:21 -080049 InitializeAnalogInput();
50 InitializeAnalogInternal();
51 InitializeAnalogOutput();
52 InitializeAnalogTrigger();
53 InitializeCAN();
54 InitializeCANAPI();
Brian Silverman8fce7482020-01-05 13:18:21 -080055 InitializeConstants();
56 InitializeCounter();
57 InitializeDigitalInternal();
58 InitializeDIO();
59 InitializeDMA();
60 InitializeDutyCycle();
61 InitializeEncoder();
62 InitializeFPGAEncoder();
63 InitializeFRCDriverStation();
64 InitializeI2C();
Austin Schuh1e69f942020-11-14 15:06:14 -080065 InitializeInterrupts();
Brian Silverman8fce7482020-01-05 13:18:21 -080066 InitializeMain();
67 InitializeNotifier();
Austin Schuh812d0d12021-11-04 20:16:48 -070068 InitializeCTREPDP();
69 InitializeREVPDH();
Brian Silverman8fce7482020-01-05 13:18:21 -080070 InitializePorts();
71 InitializePower();
72 InitializePWM();
73 InitializeRelay();
Austin Schuh1e69f942020-11-14 15:06:14 -080074 InitializeSerialPort();
Brian Silverman8fce7482020-01-05 13:18:21 -080075 InitializeSPI();
76 InitializeThreads();
77}
78} // namespace init
Austin Schuh1e69f942020-11-14 15:06:14 -080079
80void ReleaseFPGAInterrupt(int32_t interruptNumber) {
81 if (!global) {
82 return;
83 }
84 int32_t status = 0;
85 global->writeInterruptForceNumber(static_cast<unsigned char>(interruptNumber),
86 &status);
87 global->strobeInterruptForceOnce(&status);
88}
Brian Silverman8fce7482020-01-05 13:18:21 -080089} // namespace hal
90
91extern "C" {
92
93HAL_PortHandle HAL_GetPort(int32_t channel) {
94 // Dont allow a number that wouldn't fit in a uint8_t
Austin Schuh812d0d12021-11-04 20:16:48 -070095 if (channel < 0 || channel >= 255) {
96 return HAL_kInvalidHandle;
97 }
Brian Silverman8fce7482020-01-05 13:18:21 -080098 return createPortHandle(channel, 1);
99}
100
101HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) {
102 // Dont allow a number that wouldn't fit in a uint8_t
Austin Schuh812d0d12021-11-04 20:16:48 -0700103 if (channel < 0 || channel >= 255) {
104 return HAL_kInvalidHandle;
105 }
106 if (module < 0 || module >= 255) {
107 return HAL_kInvalidHandle;
108 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800109 return createPortHandle(channel, module);
110}
111
112const char* HAL_GetErrorMessage(int32_t code) {
113 switch (code) {
114 case 0:
115 return "";
Brian Silverman8fce7482020-01-05 13:18:21 -0800116 case NiFpga_Status_FifoTimeout:
117 return NiFpga_Status_FifoTimeout_MESSAGE;
118 case NiFpga_Status_TransferAborted:
119 return NiFpga_Status_TransferAborted_MESSAGE;
120 case NiFpga_Status_MemoryFull:
121 return NiFpga_Status_MemoryFull_MESSAGE;
122 case NiFpga_Status_SoftwareFault:
123 return NiFpga_Status_SoftwareFault_MESSAGE;
124 case NiFpga_Status_InvalidParameter:
125 return NiFpga_Status_InvalidParameter_MESSAGE;
126 case NiFpga_Status_ResourceNotFound:
127 return NiFpga_Status_ResourceNotFound_MESSAGE;
128 case NiFpga_Status_ResourceNotInitialized:
129 return NiFpga_Status_ResourceNotInitialized_MESSAGE;
130 case NiFpga_Status_HardwareFault:
131 return NiFpga_Status_HardwareFault_MESSAGE;
132 case NiFpga_Status_IrqTimeout:
133 return NiFpga_Status_IrqTimeout_MESSAGE;
134 case SAMPLE_RATE_TOO_HIGH:
135 return SAMPLE_RATE_TOO_HIGH_MESSAGE;
136 case VOLTAGE_OUT_OF_RANGE:
137 return VOLTAGE_OUT_OF_RANGE_MESSAGE;
138 case LOOP_TIMING_ERROR:
139 return LOOP_TIMING_ERROR_MESSAGE;
140 case SPI_WRITE_NO_MOSI:
141 return SPI_WRITE_NO_MOSI_MESSAGE;
142 case SPI_READ_NO_MISO:
143 return SPI_READ_NO_MISO_MESSAGE;
144 case SPI_READ_NO_DATA:
145 return SPI_READ_NO_DATA_MESSAGE;
146 case INCOMPATIBLE_STATE:
147 return INCOMPATIBLE_STATE_MESSAGE;
148 case NO_AVAILABLE_RESOURCES:
149 return NO_AVAILABLE_RESOURCES_MESSAGE;
150 case RESOURCE_IS_ALLOCATED:
151 return RESOURCE_IS_ALLOCATED_MESSAGE;
152 case RESOURCE_OUT_OF_RANGE:
153 return RESOURCE_OUT_OF_RANGE_MESSAGE;
154 case HAL_INVALID_ACCUMULATOR_CHANNEL:
155 return HAL_INVALID_ACCUMULATOR_CHANNEL_MESSAGE;
156 case HAL_HANDLE_ERROR:
157 return HAL_HANDLE_ERROR_MESSAGE;
158 case NULL_PARAMETER:
159 return NULL_PARAMETER_MESSAGE;
160 case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
161 return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
162 case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
163 return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
164 case PARAMETER_OUT_OF_RANGE:
165 return PARAMETER_OUT_OF_RANGE_MESSAGE;
166 case HAL_COUNTER_NOT_SUPPORTED:
167 return HAL_COUNTER_NOT_SUPPORTED_MESSAGE;
168 case HAL_ERR_CANSessionMux_InvalidBuffer:
169 return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
170 case HAL_ERR_CANSessionMux_MessageNotFound:
171 return ERR_CANSessionMux_MessageNotFound_MESSAGE;
172 case HAL_WARN_CANSessionMux_NoToken:
173 return WARN_CANSessionMux_NoToken_MESSAGE;
174 case HAL_ERR_CANSessionMux_NotAllowed:
175 return ERR_CANSessionMux_NotAllowed_MESSAGE;
176 case HAL_ERR_CANSessionMux_NotInitialized:
177 return ERR_CANSessionMux_NotInitialized_MESSAGE;
Austin Schuh1e69f942020-11-14 15:06:14 -0800178 case VI_ERROR_SYSTEM_ERROR:
179 return VI_ERROR_SYSTEM_ERROR_MESSAGE;
180 case VI_ERROR_INV_OBJECT:
181 return VI_ERROR_INV_OBJECT_MESSAGE;
182 case VI_ERROR_RSRC_LOCKED:
183 return VI_ERROR_RSRC_LOCKED_MESSAGE;
184 case VI_ERROR_RSRC_NFOUND:
185 return VI_ERROR_RSRC_NFOUND_MESSAGE;
186 case VI_ERROR_INV_RSRC_NAME:
187 return VI_ERROR_INV_RSRC_NAME_MESSAGE;
188 case VI_ERROR_QUEUE_OVERFLOW:
189 return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
190 case VI_ERROR_IO:
191 return VI_ERROR_IO_MESSAGE;
192 case VI_ERROR_ASRL_PARITY:
193 return VI_ERROR_ASRL_PARITY_MESSAGE;
194 case VI_ERROR_ASRL_FRAMING:
195 return VI_ERROR_ASRL_FRAMING_MESSAGE;
196 case VI_ERROR_ASRL_OVERRUN:
197 return VI_ERROR_ASRL_OVERRUN_MESSAGE;
198 case VI_ERROR_RSRC_BUSY:
199 return VI_ERROR_RSRC_BUSY_MESSAGE;
200 case VI_ERROR_INV_PARAMETER:
201 return VI_ERROR_INV_PARAMETER_MESSAGE;
Brian Silverman8fce7482020-01-05 13:18:21 -0800202 case HAL_PWM_SCALE_ERROR:
203 return HAL_PWM_SCALE_ERROR_MESSAGE;
204 case HAL_SERIAL_PORT_NOT_FOUND:
205 return HAL_SERIAL_PORT_NOT_FOUND_MESSAGE;
206 case HAL_THREAD_PRIORITY_ERROR:
207 return HAL_THREAD_PRIORITY_ERROR_MESSAGE;
208 case HAL_THREAD_PRIORITY_RANGE_ERROR:
209 return HAL_THREAD_PRIORITY_RANGE_ERROR_MESSAGE;
210 case HAL_SERIAL_PORT_OPEN_ERROR:
211 return HAL_SERIAL_PORT_OPEN_ERROR_MESSAGE;
212 case HAL_SERIAL_PORT_ERROR:
213 return HAL_SERIAL_PORT_ERROR_MESSAGE;
214 case HAL_CAN_TIMEOUT:
215 return HAL_CAN_TIMEOUT_MESSAGE;
216 case ERR_FRCSystem_NetCommNotResponding:
217 return ERR_FRCSystem_NetCommNotResponding_MESSAGE;
218 case ERR_FRCSystem_NoDSConnection:
219 return ERR_FRCSystem_NoDSConnection_MESSAGE;
220 case HAL_CAN_BUFFER_OVERRUN:
221 return HAL_CAN_BUFFER_OVERRUN_MESSAGE;
222 case HAL_LED_CHANNEL_ERROR:
223 return HAL_LED_CHANNEL_ERROR_MESSAGE;
Austin Schuh812d0d12021-11-04 20:16:48 -0700224 case HAL_INVALID_DMA_STATE:
225 return HAL_INVALID_DMA_STATE_MESSAGE;
226 case HAL_INVALID_DMA_ADDITION:
227 return HAL_INVALID_DMA_ADDITION_MESSAGE;
228 case HAL_USE_LAST_ERROR:
229 return HAL_USE_LAST_ERROR_MESSAGE;
230 case HAL_CONSOLE_OUT_ENABLED_ERROR:
231 return HAL_CONSOLE_OUT_ENABLED_ERROR_MESSAGE;
Brian Silverman8fce7482020-01-05 13:18:21 -0800232 default:
233 return "Unknown error status";
234 }
235}
236
Austin Schuh812d0d12021-11-04 20:16:48 -0700237HAL_RuntimeType HAL_GetRuntimeType(void) {
238 nLoadOut::tTargetClass targetClass = nLoadOut::getTargetClass();
239 if (targetClass == nLoadOut::kTargetClass_RoboRIO2) {
240 return HAL_Runtime_RoboRIO2;
241 }
242 return HAL_Runtime_RoboRIO;
243}
Brian Silverman8fce7482020-01-05 13:18:21 -0800244
245int32_t HAL_GetFPGAVersion(int32_t* status) {
246 if (!global) {
247 *status = NiFpga_Status_ResourceNotInitialized;
248 return 0;
249 }
250 return global->readVersion(status);
251}
252
253int64_t HAL_GetFPGARevision(int32_t* status) {
254 if (!global) {
255 *status = NiFpga_Status_ResourceNotInitialized;
256 return 0;
257 }
258 return global->readRevision(status);
259}
260
261uint64_t HAL_GetFPGATime(int32_t* status) {
262 if (!global) {
263 *status = NiFpga_Status_ResourceNotInitialized;
264 return 0;
265 }
266 *status = 0;
267 uint64_t upper1 = global->readLocalTimeUpper(status);
268 uint32_t lower = global->readLocalTime(status);
269 uint64_t upper2 = global->readLocalTimeUpper(status);
Austin Schuh812d0d12021-11-04 20:16:48 -0700270 if (*status != 0) {
271 return 0;
272 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800273 if (upper1 != upper2) {
274 // Rolled over between the lower call, reread lower
275 lower = global->readLocalTime(status);
Austin Schuh812d0d12021-11-04 20:16:48 -0700276 if (*status != 0) {
277 return 0;
278 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800279 }
280 return (upper2 << 32) + lower;
281}
282
Austin Schuh812d0d12021-11-04 20:16:48 -0700283uint64_t HAL_ExpandFPGATime(uint32_t unexpandedLower, int32_t* status) {
Brian Silverman8fce7482020-01-05 13:18:21 -0800284 // Capture the current FPGA time. This will give us the upper half of the
285 // clock.
Austin Schuh812d0d12021-11-04 20:16:48 -0700286 uint64_t fpgaTime = HAL_GetFPGATime(status);
287 if (*status != 0) {
288 return 0;
289 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800290
291 // Now, we need to detect the case where the lower bits rolled over after we
292 // sampled. In that case, the upper bits will be 1 bigger than they should
293 // be.
294
295 // Break it into lower and upper portions.
Austin Schuh812d0d12021-11-04 20:16:48 -0700296 uint32_t lower = fpgaTime & 0xffffffffull;
297 uint64_t upper = (fpgaTime >> 32) & 0xffffffff;
Brian Silverman8fce7482020-01-05 13:18:21 -0800298
299 // The time was sampled *before* the current time, so roll it back.
Austin Schuh812d0d12021-11-04 20:16:48 -0700300 if (lower < unexpandedLower) {
Brian Silverman8fce7482020-01-05 13:18:21 -0800301 --upper;
302 }
303
Austin Schuh812d0d12021-11-04 20:16:48 -0700304 return (upper << 32) + static_cast<uint64_t>(unexpandedLower);
Brian Silverman8fce7482020-01-05 13:18:21 -0800305}
306
307HAL_Bool HAL_GetFPGAButton(int32_t* status) {
308 if (!global) {
309 *status = NiFpga_Status_ResourceNotInitialized;
310 return false;
311 }
312 return global->readUserButton(status);
313}
314
315HAL_Bool HAL_GetSystemActive(int32_t* status) {
316 if (!watchdog) {
317 *status = NiFpga_Status_ResourceNotInitialized;
318 return false;
319 }
320 return watchdog->readStatus_SystemActive(status);
321}
322
323HAL_Bool HAL_GetBrownedOut(int32_t* status) {
324 if (!watchdog) {
325 *status = NiFpga_Status_ResourceNotInitialized;
326 return false;
327 }
328 return !(watchdog->readStatus_PowerAlive(status));
329}
330
331static bool killExistingProgram(int timeout, int mode) {
332 // Kill any previous robot programs
333 std::fstream fs;
334 // By making this both in/out, it won't give us an error if it doesnt exist
335 fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
Austin Schuh812d0d12021-11-04 20:16:48 -0700336 if (fs.bad()) {
337 return false;
338 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800339
340 pid_t pid = 0;
341 if (!fs.eof() && !fs.fail()) {
342 fs >> pid;
343 // see if the pid is around, but we don't want to mess with init id=1, or
344 // ourselves
345 if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid()) {
Austin Schuh812d0d12021-11-04 20:16:48 -0700346 std::puts("Killing previously running FRC program...");
Brian Silverman8fce7482020-01-05 13:18:21 -0800347 kill(pid, SIGTERM); // try to kill it
348 std::this_thread::sleep_for(std::chrono::milliseconds(timeout));
349 if (kill(pid, 0) == 0) {
Austin Schuh1e69f942020-11-14 15:06:14 -0800350 // still not successful
Austin Schuh812d0d12021-11-04 20:16:48 -0700351 fmt::print(
352 "FRC pid {} did not die within {} ms. Force killing with kill -9\n",
353 pid, timeout);
Brian Silverman8fce7482020-01-05 13:18:21 -0800354 // Force kill -9
355 auto forceKill = kill(pid, SIGKILL);
356 if (forceKill != 0) {
357 auto errorMsg = std::strerror(forceKill);
Austin Schuh812d0d12021-11-04 20:16:48 -0700358 fmt::print("Kill -9 error: {}\n", errorMsg);
Brian Silverman8fce7482020-01-05 13:18:21 -0800359 }
360 // Give a bit of time for the kill to take place
361 std::this_thread::sleep_for(std::chrono::milliseconds(250));
362 }
363 }
364 }
365 fs.close();
366 // we will re-open it write only to truncate the file
367 fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
368 fs.seekp(0);
369 pid = getpid();
370 fs << pid << std::endl;
371 fs.close();
372 return true;
373}
374
375HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) {
376 static std::atomic_bool initialized{false};
377 static wpi::mutex initializeMutex;
378 // Initial check, as if it's true initialization has finished
Austin Schuh812d0d12021-11-04 20:16:48 -0700379 if (initialized) {
380 return true;
381 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800382
383 std::scoped_lock lock(initializeMutex);
384 // Second check in case another thread was waiting
Austin Schuh812d0d12021-11-04 20:16:48 -0700385 if (initialized) {
386 return true;
387 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800388
389 hal::init::InitializeHAL();
390
391 hal::init::HAL_IsInitialized.store(true);
392
393 setlinebuf(stdin);
394 setlinebuf(stdout);
Brian Silverman8fce7482020-01-05 13:18:21 -0800395
396 prctl(PR_SET_PDEATHSIG, SIGTERM);
397
398 // Return false if program failed to kill an existing program
399 if (!killExistingProgram(timeout, mode)) {
400 return false;
401 }
402
403 FRC_NetworkCommunication_Reserve(nullptr);
404
405 std::atexit([]() {
406 // Unregister our new data condition variable.
407 setNewDataSem(nullptr);
408 });
409
Brian Silverman8fce7482020-01-05 13:18:21 -0800410 nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
Austin Schuh1e69f942020-11-14 15:06:14 -0800411 nLoadOut::getTargetClass();
Brian Silverman8fce7482020-01-05 13:18:21 -0800412
413 int32_t status = 0;
414 global.reset(tGlobal::create(&status));
415 watchdog.reset(tSysWatchdog::create(&status));
416
Austin Schuh812d0d12021-11-04 20:16:48 -0700417 if (status != 0) {
418 return false;
419 }
Brian Silverman8fce7482020-01-05 13:18:21 -0800420
421 HAL_InitializeDriverStation();
422
423 // Set WPI_Now to use FPGA timestamp
424 wpi::SetNowImpl([]() -> uint64_t {
425 int32_t status = 0;
426 uint64_t rv = HAL_GetFPGATime(&status);
427 if (status != 0) {
Austin Schuh812d0d12021-11-04 20:16:48 -0700428 fmt::print(stderr,
429 "Call to HAL_GetFPGATime failed in wpi::Now() with status {}. "
430 "Initialization might have failed. Time will not be correct\n",
431 status);
432 std::fflush(stderr);
Brian Silverman8fce7482020-01-05 13:18:21 -0800433 return 0u;
434 }
435 return rv;
436 });
437
438 initialized = true;
439 return true;
440}
441
Austin Schuh1e69f942020-11-14 15:06:14 -0800442void HAL_Shutdown(void) {}
443
Austin Schuh812d0d12021-11-04 20:16:48 -0700444void HAL_SimPeriodicBefore(void) {}
445
446void HAL_SimPeriodicAfter(void) {}
447
Brian Silverman8fce7482020-01-05 13:18:21 -0800448int64_t HAL_Report(int32_t resource, int32_t instanceNumber, int32_t context,
449 const char* feature) {
450 if (feature == nullptr) {
451 feature = "";
452 }
453
454 return FRC_NetworkCommunication_nUsageReporting_report(
455 resource, instanceNumber, context, feature);
456}
457
Brian Silverman8fce7482020-01-05 13:18:21 -0800458} // extern "C"