blob: 8fa603e0fa0eb8b385faae5c3e048026ea724eaa [file] [log] [blame]
Maxwell Henderson80bec322024-01-09 15:48:44 -08001// 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.
4
5#include "hal/LEDs.h"
6
7#include <unistd.h>
8
9#include <fstream>
10
11#include <wpi/fs.h>
12
13#include "hal/Errors.h"
14
15namespace hal::init {
16
17void InitializeLEDs() {
18 int32_t status = 0;
19 HAL_SetRadioLEDState(HAL_RadioLED_kOff, &status);
20}
21} // namespace hal::init
22
23static const fs::path radioLEDGreenFilePath =
24 "/sys/class/leds/nilrt:wifi:primary/brightness";
25static const fs::path radioLEDRedFilePath =
26 "/sys/class/leds/nilrt:wifi:secondary/brightness";
27
28static const char* onStr = "1";
29static const char* offStr = "0";
30
31extern "C" {
32void HAL_SetRadioLEDState(HAL_RadioLEDState state, int32_t* status) {
33 std::error_code ec;
34 fs::file_t greenFile = fs::OpenFileForWrite(radioLEDGreenFilePath, ec,
35 fs::CD_OpenExisting, fs::OF_Text);
36 if (ec) {
37 *status = INCOMPATIBLE_STATE;
38 return;
39 }
40 fs::file_t redFile = fs::OpenFileForWrite(radioLEDRedFilePath, ec,
41 fs::CD_OpenExisting, fs::OF_Text);
42 if (ec) {
43 *status = INCOMPATIBLE_STATE;
44 return;
45 }
46
47 write(greenFile, state & HAL_RadioLED_kGreen ? onStr : offStr, 1);
48 write(redFile, state & HAL_RadioLED_kRed ? onStr : offStr, 1);
49
50 fs::CloseFile(greenFile);
51 fs::CloseFile(redFile);
52}
53
54bool ReadStateFromFile(fs::path path, int32_t* status) {
55 std::error_code ec;
56 fs::file_t file = fs::OpenFileForRead(path, ec, fs::OF_Text);
57 if (ec) {
58 *status = INCOMPATIBLE_STATE;
59 return false;
60 }
61 // We only need to read one byte because the file won't have leading zeros.
62 char buf[1]{};
63 size_t count = read(file, buf, 1);
64 if (count == 0) {
65 *status = INCOMPATIBLE_STATE;
66 return false;
67 }
68 // If the brightness is not zero, the LED is on.
69 return buf[0] != '0';
70}
71
72HAL_RadioLEDState HAL_GetRadioLEDState(int32_t* status) {
73 bool green = ReadStateFromFile(radioLEDGreenFilePath, status);
74 bool red = ReadStateFromFile(radioLEDRedFilePath, status);
75 if (*status == 0) {
76 if (green && red) {
77 return HAL_RadioLED_kOrange;
78 } else if (green) {
79 return HAL_RadioLED_kGreen;
80 } else if (red) {
81 return HAL_RadioLED_kRed;
82 } else {
83 return HAL_RadioLED_kOff;
84 }
85 } else {
86 return HAL_RadioLED_kOff;
87 }
88}
89} // extern "C"