blob: 658b06437174293ee5ce5154c5329e0ec8101f78 [file] [log] [blame]
Brian Silvermand8f403a2014-12-13 19:12:04 -05001#include "frc971/wpilib/loop_output_handler.h"
2
3#include <sys/timerfd.h>
4
5#include <thread>
6#include <functional>
7
8#include "aos/linux_code/init.h"
9#include "aos/common/messages/robot_state.q.h"
10
11namespace frc971 {
12namespace wpilib {
13
Austin Schuhbb227f82015-09-06 15:27:52 -070014LoopOutputHandler::LoopOutputHandler(const ::aos::time::Time &timeout)
15 : watchdog_(this, timeout) {}
Brian Silvermand8f403a2014-12-13 19:12:04 -050016
17void LoopOutputHandler::operator()() {
18 ::aos::SetCurrentThreadName("OutputHandler");
19 ::std::thread watchdog_thread(::std::ref(watchdog_));
20
21 ::aos::SetCurrentThreadRealtimePriority(30);
22 while (run_) {
Brian Silverman699f0cb2015-02-05 19:45:01 -050023 no_joystick_state_.Print();
24 fake_joystick_state_.Print();
Brian Silvermand8f403a2014-12-13 19:12:04 -050025 Read();
Brian Silverman699f0cb2015-02-05 19:45:01 -050026 ::aos::joystick_state.FetchLatest();
27 if (!::aos::joystick_state.get()) {
28 LOG_INTERVAL(no_joystick_state_);
Brian Silvermand8f403a2014-12-13 19:12:04 -050029 continue;
30 }
Brian Silverman699f0cb2015-02-05 19:45:01 -050031 if (::aos::joystick_state->fake) {
32 LOG_INTERVAL(fake_joystick_state_);
Brian Silvermand8f403a2014-12-13 19:12:04 -050033 continue;
34 }
35
36 watchdog_.Reset();
37 Write();
38 }
39
40 Stop();
41
42 watchdog_.Quit();
43 watchdog_thread.join();
44}
45
Austin Schuhbb227f82015-09-06 15:27:52 -070046LoopOutputHandler::Watchdog::Watchdog(LoopOutputHandler *handler,
47 const ::aos::time::Time &timeout)
Brian Silvermand8f403a2014-12-13 19:12:04 -050048 : handler_(handler),
Austin Schuhbb227f82015-09-06 15:27:52 -070049 timeout_(timeout),
Brian Silvermand8f403a2014-12-13 19:12:04 -050050 timerfd_(timerfd_create(::aos::time::Time::kDefaultClock, 0)) {
51 if (timerfd_.get() == -1) {
52 PLOG(FATAL, "timerfd_create(Time::kDefaultClock, 0)");
53 }
54 ::aos::SetCurrentThreadRealtimePriority(35);
55 ::aos::SetCurrentThreadName("OutputWatchdog");
56}
57
58void LoopOutputHandler::Watchdog::operator()() {
59 uint8_t buf[8];
60 while (run_) {
61 PCHECK(read(timerfd_.get(), buf, sizeof(buf)));
62 handler_->Stop();
63 }
64}
65
66void LoopOutputHandler::Watchdog::Reset() {
67 itimerspec value = itimerspec();
Austin Schuhbb227f82015-09-06 15:27:52 -070068 value.it_value = timeout_.ToTimespec();
Brian Silvermand8f403a2014-12-13 19:12:04 -050069 PCHECK(timerfd_settime(timerfd_.get(), 0, &value, nullptr));
70}
71
72} // namespace wpilib
73} // namespace frc971