blob: b18af5b36993aaeaaee5dd922b381034918b59ec [file] [log] [blame]
Brian Silverman41cdd3e2019-01-19 19:48:58 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) 2014-2018 FIRST. All Rights Reserved. */
3/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#include "frc/AnalogOutput.h"
9
10#include <limits>
11#include <utility>
12
13#include <hal/HAL.h>
14#include <hal/Ports.h>
15
16#include "frc/SensorUtil.h"
17#include "frc/WPIErrors.h"
18#include "frc/smartdashboard/SendableBuilder.h"
19
20using namespace frc;
21
22AnalogOutput::AnalogOutput(int channel) {
23 if (!SensorUtil::CheckAnalogOutputChannel(channel)) {
24 wpi_setWPIErrorWithContext(ChannelIndexOutOfRange,
25 "analog output " + wpi::Twine(channel));
26 m_channel = std::numeric_limits<int>::max();
27 m_port = HAL_kInvalidHandle;
28 return;
29 }
30
31 m_channel = channel;
32
33 HAL_PortHandle port = HAL_GetPort(m_channel);
34 int32_t status = 0;
35 m_port = HAL_InitializeAnalogOutputPort(port, &status);
36 if (status != 0) {
37 wpi_setErrorWithContextRange(status, 0, HAL_GetNumAnalogOutputs(), channel,
38 HAL_GetErrorMessage(status));
39 m_channel = std::numeric_limits<int>::max();
40 m_port = HAL_kInvalidHandle;
41 return;
42 }
43
44 HAL_Report(HALUsageReporting::kResourceType_AnalogOutput, m_channel);
45 SetName("AnalogOutput", m_channel);
46}
47
48AnalogOutput::~AnalogOutput() { HAL_FreeAnalogOutputPort(m_port); }
49
50AnalogOutput::AnalogOutput(AnalogOutput&& rhs)
51 : ErrorBase(std::move(rhs)),
52 SendableBase(std::move(rhs)),
53 m_channel(std::move(rhs.m_channel)) {
54 std::swap(m_port, rhs.m_port);
55}
56
57AnalogOutput& AnalogOutput::operator=(AnalogOutput&& rhs) {
58 ErrorBase::operator=(std::move(rhs));
59 SendableBase::operator=(std::move(rhs));
60
61 m_channel = std::move(rhs.m_channel);
62 std::swap(m_port, rhs.m_port);
63
64 return *this;
65}
66
67void AnalogOutput::SetVoltage(double voltage) {
68 int32_t status = 0;
69 HAL_SetAnalogOutput(m_port, voltage, &status);
70
71 wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
72}
73
74double AnalogOutput::GetVoltage() const {
75 int32_t status = 0;
76 double voltage = HAL_GetAnalogOutput(m_port, &status);
77
78 wpi_setErrorWithContext(status, HAL_GetErrorMessage(status));
79
80 return voltage;
81}
82
83int AnalogOutput::GetChannel() { return m_channel; }
84
85void AnalogOutput::InitSendable(SendableBuilder& builder) {
86 builder.SetSmartDashboardType("Analog Output");
87 builder.AddDoubleProperty("Value", [=]() { return GetVoltage(); },
88 [=](double value) { SetVoltage(value); });
89}