Merge "Add support for building code for Debian armhf"
diff --git a/NO_BUILD_AMD64 b/NO_BUILD_AMD64
index 2a4c1cf..391b1cb 100644
--- a/NO_BUILD_AMD64
+++ b/NO_BUILD_AMD64
@@ -3,6 +3,8 @@
-//third_party/allwpilib_2016/...
-//third_party/ntcore_2016/...
-//frc971/wpilib/...
+-//y2012/wpilib/...
+-//y2012:download
-//y2014/wpilib/...
-//y2014:download
-//y2014_bot3/wpilib/...
@@ -11,5 +13,5 @@
-//y2015:download
-//y2015_bot3/wpilib/...
-//y2015_bot3:download
--//y2012/wpilib/...
--//y2012:download
+-//y2016/wpilib/...
+-//y2016:download
diff --git a/NO_BUILD_ROBORIO b/NO_BUILD_ROBORIO
index b8efe8f..f4800e2 100644
--- a/NO_BUILD_ROBORIO
+++ b/NO_BUILD_ROBORIO
@@ -1,5 +1,6 @@
-@slycot_repo//...
--//y2014/control_loops/python/...
--//y2015_bot3/control_loops/python/...
-//frc971/control_loops/python/...
-//y2012/control_loops/python/...
+-//y2014/control_loops/python/...
+-//y2015_bot3/control_loops/python/...
+-//y2016/control_loops/python/...
diff --git a/WORKSPACE b/WORKSPACE
index 821624d..82a20f2 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -17,7 +17,7 @@
)
new_http_archive(
- name = 'arm-frc-linux-gnueabi-repo',
+ name = 'arm_frc_linux_gnueabi_repo',
build_file = 'tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi.BUILD',
sha256 = '9d92b513b627c4aaa93d4d8049b4c6b96a532b64df11b27fde4dead58347a9f6',
url = 'http://frc971.org/Build-Dependencies/arm-frc-linux-gnueabi_4.9.3.tar.gz',
@@ -35,7 +35,7 @@
)
new_git_repository(
- name = 'python-gflags-repo',
+ name = 'python_gflags_repo',
remote = 'https://github.com/gflags/python-gflags.git',
build_file = 'debian/gflags.BUILD',
commit = '41c4571864f0db5823e07715317e7388e94faabc',
@@ -43,11 +43,11 @@
bind(
name = 'python-gflags',
- actual = '@python-gflags-repo//:gflags',
+ actual = '@python_gflags_repo//:gflags',
)
new_http_archive(
- name = 'python-glog-repo',
+ name = 'python_glog_repo',
build_file = 'debian/glog.BUILD',
sha256 = '953fd80122c48023d1148e6d1bda2763fcab59c8a81682bb298238a5935547b0',
url = 'https://pypi.python.org/packages/source/g/glog/glog-0.1.tar.gz',
@@ -56,11 +56,11 @@
bind(
name = 'python-glog',
- actual = '@python-glog-repo//:glog',
+ actual = '@python_glog_repo//:glog',
)
new_http_archive(
- name = 'allwpilib_ni-libraries_repo',
+ name = 'allwpilib_ni_libraries_repo',
build_file = 'debian/ni-libraries.BUILD',
sha256 = '821687afbee2d7531fb3e47d8d58ac10005695e59685be3ac3aa00b3179faf52',
url = 'http://frc971.org/Build-Dependencies/allwpilib_ni-libraries_20749ed.tar.gz',
@@ -69,5 +69,5 @@
bind(
name = 'ni-libraries',
- actual = '@allwpilib_ni-libraries_repo//:ni-libraries',
+ actual = '@allwpilib_ni_libraries_repo//:ni-libraries',
)
diff --git a/aos/common/controls/BUILD b/aos/common/controls/BUILD
index 5bb31fb..9cc6f31 100644
--- a/aos/common/controls/BUILD
+++ b/aos/common/controls/BUILD
@@ -40,6 +40,22 @@
deps = [
'//third_party/eigen',
'//third_party/cddlib',
+ '//aos/common/logging',
+ '//aos/common/logging:matrix_logging',
+ ],
+)
+
+cc_test(
+ name = 'polytope_test',
+ srcs = [
+ 'polytope_test.cc',
+ ],
+ deps = [
+ ':polytope',
+ '//aos/testing:googletest',
+ '//third_party/eigen',
+ '//third_party/googletest:googlemock',
+ '//aos/testing:test_logging',
],
)
diff --git a/aos/common/controls/polytope.h b/aos/common/controls/polytope.h
index 4efa628..ccd257b 100644
--- a/aos/common/controls/polytope.h
+++ b/aos/common/controls/polytope.h
@@ -5,39 +5,67 @@
#include "third_party/cddlib/lib-src/setoper.h"
#include "third_party/cddlib/lib-src/cdd.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/logging/matrix_logging.h"
+
namespace aos {
namespace controls {
-// A n dimension polytope.
+// A number_of_dimensions dimensional polytope.
+// This represents the region consisting of all points X such that H * X <= k.
+// The vertices are calculated at construction time because we always use those
+// and libcdd is annoying about calculating vertices. In particular, for some
+// random-seeming polytopes it refuses to calculate the vertices completely. To
+// avoid issues with that, using the "shifting" constructor is recommended
+// whenever possible.
template <int number_of_dimensions>
class HPolytope {
public:
- // Constructs a polytope given the H and k matricies.
- HPolytope(Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> H,
- Eigen::Matrix<double, Eigen::Dynamic, 1> k)
- : H_(H),
- k_(k) {
- }
+ // Constructs a polytope given the H and k matrices.
+ // Do NOT use this to calculate a polytope derived from another one in a way
+ // another constructor can be used instead.
+ HPolytope(
+ const Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> &H,
+ const Eigen::Matrix<double, Eigen::Dynamic, 1> &k)
+ : H_(H), k_(k), vertices_(CalculateVertices(H, k)) {}
+
+ // Constructs a polytope with H = other.H() * H_multiplier and
+ // k = other.k() + other.H() * k_shifter.
+ // This avoids calculating the vertices for the new H and k directly because
+ // that sometimes confuses libcdd depending on what exactly the new H and k
+ // are.
+ //
+ // This currently has the following restrictions (CHECKed internally) because
+ // we don't have uses for anything else:
+ // If number_of_dimensions is not 1, it must be 2, other.H() *
+ // H_multiplier.inverse() * k_shifter must have its first 2 columns and last
+ // 2 columns as opposites, and the 1st+2nd and 3rd+4th vertices must be
+ // normal to each other.
+ HPolytope(const HPolytope<number_of_dimensions> &other,
+ const Eigen::Matrix<double, number_of_dimensions,
+ number_of_dimensions> &H_multiplier,
+ const Eigen::Matrix<double, number_of_dimensions, 1> &k_shifter)
+ : H_(other.H() * H_multiplier),
+ k_(other.k() + other.H() * k_shifter),
+ vertices_(
+ ShiftVertices(CalculateVertices(H_, other.k()),
+ other.H() * H_multiplier.inverse() * k_shifter)) {}
// This is an initialization function shared across all instantiations of this
// template.
- // This must be called at least once before calling any of the methods. It is
+ // This must be called at least once before creating any instances. It is
// not thread-safe.
static void Init() {
dd_set_global_constants();
}
// Returns a reference to H.
- const Eigen::Matrix<double, Eigen::Dynamic,
- number_of_dimensions> &H() const {
+ const Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> &H() const {
return H_;
}
// Returns a reference to k.
- const Eigen::Matrix<double, Eigen::Dynamic,
- 1> &k() const {
- return k_;
- }
+ const Eigen::Matrix<double, Eigen::Dynamic, 1> &k() const { return k_; }
// Returns the number of dimensions in the polytope.
int ndim() const { return number_of_dimensions; }
@@ -49,11 +77,63 @@
bool IsInside(Eigen::Matrix<double, number_of_dimensions, 1> point) const;
// Returns the list of vertices inside the polytope.
- Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic> Vertices() const;
+ const Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic> &Vertices()
+ const {
+ return vertices_;
+ }
private:
- Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> H_;
- Eigen::Matrix<double, Eigen::Dynamic, 1> k_;
+ static Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic>
+ CalculateVertices(
+ const Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> &H,
+ const Eigen::Matrix<double, Eigen::Dynamic, 1> &k);
+
+ static Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic>
+ ShiftVertices(const Eigen::Matrix<double, number_of_dimensions,
+ Eigen::Dynamic> &vertices,
+ const Eigen::Matrix<double, Eigen::Dynamic, 1> &shift) {
+ static_assert(number_of_dimensions <= 2, "not implemented yet");
+ if (vertices.cols() != number_of_dimensions * 2) {
+ LOG(FATAL,
+ "less vertices not supported yet: %zd vertices vs %d dimensions\n",
+ vertices.cols(), number_of_dimensions);
+ }
+ if (number_of_dimensions == 2) {
+ if ((shift.row(0) + shift.row(1)).norm() > 0.0001) {
+ LOG_MATRIX(FATAL, "bad shift amount", shift.row(0) + shift.row(1));
+ }
+ if ((shift.row(2) + shift.row(3)).norm() > 0.0001) {
+ LOG_MATRIX(FATAL, "bad shift amount", shift.row(2) + shift.row(3));
+ }
+ if (vertices.col(0).dot(vertices.col(1)) > 0.0001) {
+ ::Eigen::Matrix<double, number_of_dimensions, 2> bad;
+ bad.col(0) = vertices.col(0);
+ bad.col(1) = vertices.col(1);
+ LOG_MATRIX(FATAL, "bad vertices", bad);
+ }
+ if (vertices.col(2).dot(vertices.col(3)) > 0.0001) {
+ ::Eigen::Matrix<double, number_of_dimensions, 2> bad;
+ bad.col(0) = vertices.col(2);
+ bad.col(1) = vertices.col(3);
+ LOG_MATRIX(FATAL, "bad vertices", bad);
+ }
+ }
+
+ Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic> r(
+ number_of_dimensions, vertices.cols());
+ Eigen::Matrix<double, number_of_dimensions, 1> real_shift;
+ real_shift(0, 0) = shift(0, 0);
+ if (number_of_dimensions == 2) real_shift(1, 0) = shift(2, 0);
+ for (int i = 0; i < vertices.cols(); ++i) {
+ r.col(i) = vertices.col(i) + real_shift;
+ }
+ return r;
+ }
+
+ const Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> H_;
+ const Eigen::Matrix<double, Eigen::Dynamic, 1> k_;
+
+ const Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic> vertices_;
};
template <int number_of_dimensions>
@@ -70,14 +150,16 @@
template <int number_of_dimensions>
Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic>
- HPolytope<number_of_dimensions>::Vertices() const {
- dd_MatrixPtr matrix = dd_CreateMatrix(num_constraints(), ndim() + 1);
+HPolytope<number_of_dimensions>::CalculateVertices(
+ const Eigen::Matrix<double, Eigen::Dynamic, number_of_dimensions> &H,
+ const Eigen::Matrix<double, Eigen::Dynamic, 1> &k) {
+ dd_MatrixPtr matrix = dd_CreateMatrix(k.rows(), number_of_dimensions + 1);
// Copy the data over. TODO(aschuh): Is there a better way? I hate copying...
- for (int i = 0; i < num_constraints(); ++i) {
- dd_set_d(matrix->matrix[i][0], k_(i, 0));
- for (int j = 0; j < ndim(); ++j) {
- dd_set_d(matrix->matrix[i][j + 1], -H_(i, j));
+ for (int i = 0; i < k.rows(); ++i) {
+ dd_set_d(matrix->matrix[i][0], k(i, 0));
+ for (int j = 0; j < number_of_dimensions; ++j) {
+ dd_set_d(matrix->matrix[i][j + 1], -H(i, j));
}
}
@@ -89,8 +171,9 @@
if (error != dd_NoError || polyhedra == NULL) {
dd_WriteErrorMessages(stderr, error);
dd_FreeMatrix(matrix);
- Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic> ans(0, 0);
- return ans;
+ LOG_MATRIX(ERROR, "bad H", H);
+ LOG_MATRIX(ERROR, "bad k_", k);
+ LOG(FATAL, "dd_DDMatrix2Poly failed\n");
}
dd_MatrixPtr vertex_matrix = dd_CopyGenerators(polyhedra);
@@ -105,6 +188,9 @@
}
}
+ // Rays are unsupported right now. This may change in the future.
+ CHECK_EQ(0, num_rays);
+
Eigen::Matrix<double, number_of_dimensions, Eigen::Dynamic> vertices(
number_of_dimensions, num_vertices);
diff --git a/aos/common/controls/polytope_test.cc b/aos/common/controls/polytope_test.cc
new file mode 100644
index 0000000..b458b74
--- /dev/null
+++ b/aos/common/controls/polytope_test.cc
@@ -0,0 +1,154 @@
+#include "aos/common/controls/polytope.h"
+
+#include <vector>
+
+#include "Eigen/Dense"
+#include "gtest/gtest.h"
+#include "gmock/gmock.h"
+
+#include "aos/testing/test_logging.h"
+
+namespace aos {
+namespace controls {
+
+class HPolytopeTest : public ::testing::Test {
+ protected:
+ HPolytope<2> Polytope1() {
+ return HPolytope<2>{
+ (Eigen::Matrix<double, 4, 2>() << 1, 0, -1, 0, 0, 1, 0, -1).finished(),
+ (Eigen::Matrix<double, 4, 1>() << 12.0, 12.0, 12.0, 12.0).finished()};
+ }
+ HPolytope<2> Polytope2() {
+ return HPolytope<2>{
+ (Eigen::Matrix<double, 4, 2>() << 1, 1, -1, -1, 0, 1, 0, -1).finished(),
+ (Eigen::Matrix<double, 4, 1>() << 12.0, 12.0, 12.0, 12.0).finished()};
+ }
+ HPolytope<1> Polytope3() {
+ return HPolytope<1>{(Eigen::Matrix<double, 2, 1>() << 1, -0.5).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 5.0, 2.0).finished()};
+ }
+ HPolytope<2> Polytope4() {
+ return HPolytope<2>{
+ (Eigen::Matrix<double, 4, 2>() << 1, 1, -1, -1, 1, -1, -1, 1)
+ .finished(),
+ (Eigen::Matrix<double, 4, 1>() << 2, -1, 2, -1).finished()};
+ }
+ HPolytope<2> Polytope5() {
+ return HPolytope<2>{
+ (Eigen::Matrix<double, 4, 2>() << 1, 1, -1, -1, 1, -1, -1, 1)
+ .finished(),
+ (Eigen::Matrix<double, 4, 1>() << 1.5, -0.5, 1.5, -0.5).finished()};
+ }
+
+ void SetUp() override {
+ ::aos::testing::EnableTestLogging();
+ ::aos::testing::ForcePrintLogsDuringTests();
+ HPolytope<0>::Init();
+ }
+
+ template <typename T>
+ ::std::vector<::std::vector<double>> MatrixToVectors(const T &matrix) {
+ ::std::vector<::std::vector<double>> r;
+ for (int i = 0; i < matrix.cols(); ++i) {
+ ::std::vector<double> col;
+ for (int j = 0; j < matrix.rows(); ++j) {
+ col.emplace_back(matrix(j, i));
+ }
+ r.emplace_back(col);
+ }
+ return r;
+ }
+
+ template <typename T>
+ ::std::vector<::testing::Matcher<::std::vector<double>>> MatrixToMatchers(
+ const T &matrix) {
+ ::std::vector<::testing::Matcher<::std::vector<double>>> r;
+ for (int i = 0; i < matrix.cols(); ++i) {
+ ::std::vector<::testing::Matcher<double>> col;
+ for (int j = 0; j < matrix.rows(); ++j) {
+ col.emplace_back(::testing::DoubleNear(matrix(j, i), 0.000001));
+ }
+ r.emplace_back(::testing::ElementsAreArray(col));
+ }
+ return r;
+ }
+
+ template <int number_of_dimensions>
+ void CheckShiftedVertices(
+ const HPolytope<number_of_dimensions> &base,
+ const Eigen::Matrix<double, number_of_dimensions, number_of_dimensions> &
+ H_multiplier,
+ const Eigen::Matrix<double, number_of_dimensions, 1> &k_shifter) {
+ LOG_MATRIX(DEBUG, "base vertices", base.Vertices());
+ const auto shifted = HPolytope<number_of_dimensions>(
+ base.H() * H_multiplier, base.k() + base.H() * k_shifter);
+ LOG_MATRIX(DEBUG, "shifted vertices", shifted.Vertices());
+ LOG_MATRIX(DEBUG, "shifted - base", shifted.Vertices() - base.Vertices());
+ EXPECT_THAT(MatrixToVectors(HPolytope<number_of_dimensions>(
+ base, H_multiplier, k_shifter).Vertices()),
+ ::testing::UnorderedElementsAreArray(
+ MatrixToMatchers(shifted.Vertices())));
+ }
+};
+
+// Tests that the vertices for various polytopes calculated from H and k are
+// correct.
+TEST_F(HPolytopeTest, CalculatedVertices) {
+ EXPECT_THAT(MatrixToVectors(Polytope1().Vertices()),
+ ::testing::UnorderedElementsAreArray(
+ MatrixToVectors((Eigen::Matrix<double, 2, 4>() << -12, -12,
+ 12, 12, -12, 12, 12, -12).finished())));
+ EXPECT_THAT(MatrixToVectors(Polytope2().Vertices()),
+ ::testing::UnorderedElementsAreArray(
+ MatrixToVectors((Eigen::Matrix<double, 2, 4>() << 24, 0, -24,
+ 0, -12, 12, 12, -12).finished())));
+ EXPECT_THAT(MatrixToVectors(Polytope3().Vertices()),
+ ::testing::UnorderedElementsAreArray(MatrixToVectors(
+ (Eigen::Matrix<double, 1, 2>() << 5, -4).finished())));
+ EXPECT_THAT(MatrixToVectors(Polytope4().Vertices()),
+ ::testing::UnorderedElementsAreArray(
+ MatrixToVectors((Eigen::Matrix<double, 2, 4>() << 1, 1.5, 1.5,
+ 2, 0, -0.5, 0.5, 0).finished())));
+ EXPECT_THAT(MatrixToVectors(Polytope5().Vertices()),
+ ::testing::UnorderedElementsAreArray(
+ MatrixToVectors((Eigen::Matrix<double, 2, 4>() << 0.5, 1, 1.5,
+ 1, 0, 0.5, 0, -0.5).finished())));
+}
+
+TEST_F(HPolytopeTest, ShiftedVertices) {
+ CheckShiftedVertices(
+ Polytope1(), (Eigen::Matrix<double, 2, 2>() << 1, 1, 1, -1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+ CheckShiftedVertices(
+ Polytope1(), (Eigen::Matrix<double, 2, 2>() << 1, -1, 1, 1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+ CheckShiftedVertices(
+ Polytope1(), (Eigen::Matrix<double, 2, 2>() << 1, 1, 1.5, -1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+ CheckShiftedVertices(
+ Polytope1(),
+ (Eigen::Matrix<double, 2, 2>() << 1, 1.5, -1.5, -1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+ CheckShiftedVertices(
+ Polytope1(),
+ (Eigen::Matrix<double, 2, 2>() << 1, -1.5, -1.5, -1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+ CheckShiftedVertices(
+ Polytope1(),
+ (Eigen::Matrix<double, 2, 2>() << 2, -1.5, -1.5, -1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+ CheckShiftedVertices(
+ Polytope1(),
+ (Eigen::Matrix<double, 2, 2>() << 2, -1.5, -1.25, -1).finished(),
+ (Eigen::Matrix<double, 2, 1>() << 9.71, 2.54).finished());
+
+ CheckShiftedVertices(Polytope3(),
+ (Eigen::Matrix<double, 1, 1>() << 1).finished(),
+ (Eigen::Matrix<double, 1, 1>() << 9.71).finished());
+ CheckShiftedVertices(Polytope3(),
+ (Eigen::Matrix<double, 1, 1>() << -2.54).finished(),
+ (Eigen::Matrix<double, 1, 1>() << 16.78).finished());
+}
+
+} // namespace controls
+} // namespace aos
diff --git a/aos/common/logging/matrix_logging.h b/aos/common/logging/matrix_logging.h
index e763ed5..a915643 100644
--- a/aos/common/logging/matrix_logging.h
+++ b/aos/common/logging/matrix_logging.h
@@ -15,23 +15,30 @@
// Logs the contents of a matrix and a constant string.
// matrix must be an instance of an Eigen matrix (or something similar).
-#define LOG_MATRIX(level, message, matrix) \
- do { \
- static const ::std::string kAosLoggingMessage( \
- LOG_SOURCENAME ": " STRINGIFY(__LINE__) ": " message); \
- ::aos::logging::DoLogMatrixTemplated(level, kAosLoggingMessage, matrix); \
- /* so that GCC knows that it won't return */ \
- if (level == FATAL) { \
- ::aos::Die("DoLogStruct(FATAL) fell through!!!!!\n"); \
- } \
+#define LOG_MATRIX(level, message, matrix) \
+ do { \
+ static const ::std::string kAosLoggingMessage( \
+ LOG_SOURCENAME ": " STRINGIFY(__LINE__) ": " message); \
+ ::aos::logging::DoLogMatrixTemplated(level, kAosLoggingMessage, \
+ (matrix).eval()); \
+ /* so that GCC knows that it won't return */ \
+ if (level == FATAL) { \
+ ::aos::Die("DoLogStruct(FATAL) fell through!!!!!\n"); \
+ } \
} while (false)
template <class T>
void DoLogMatrixTemplated(log_level level, const ::std::string &message,
const T &matrix) {
- static_assert(!T::IsRowMajor, "we only handle column-major storage");
- internal::DoLogMatrix(level, message, TypeID<typename T::Scalar>::id,
- matrix.rows(), matrix.cols(), matrix.data(), 1);
+ if (T::IsRowMajor) {
+ typename T::Scalar data[matrix.rows() * matrix.cols()];
+ ::Eigen::Map<T>(data, matrix.rows(), matrix.cols()) = matrix;
+ internal::DoLogMatrix(level, message, TypeID<typename T::Scalar>::id,
+ matrix.rows(), matrix.cols(), data, 1);
+ } else {
+ internal::DoLogMatrix(level, message, TypeID<typename T::Scalar>::id,
+ matrix.rows(), matrix.cols(), matrix.data(), 1);
+ }
}
} // namespace logging
diff --git a/debian/BUILD b/debian/BUILD
index d3aef1d..82c85bc 100644
--- a/debian/BUILD
+++ b/debian/BUILD
@@ -5,7 +5,7 @@
[ cc_library(
name = libname,
deps = cpu_select({
- "roborio": ['@arm-frc-linux-gnueabi-repo//:' + libname],
+ "roborio": ['@arm_frc_linux_gnueabi_repo//:' + libname],
"amd64": ['@usr_repo//:' + libname],
"armhf": ['@linaro_linux_gcc_4.9_repo//:' + libname],
}),
diff --git a/frc971/control_loops/coerce_goal.cc b/frc971/control_loops/coerce_goal.cc
index 6482cc7..0868c2c 100644
--- a/frc971/control_loops/coerce_goal.cc
+++ b/frc971/control_loops/coerce_goal.cc
@@ -7,11 +7,10 @@
namespace frc971 {
namespace control_loops {
-Eigen::Matrix<double, 2, 1> DoCoerceGoal(const aos::controls::HPolytope<2> ®ion,
- const Eigen::Matrix<double, 1, 2> &K,
- double w,
- const Eigen::Matrix<double, 2, 1> &R,
- bool *is_inside) {
+Eigen::Matrix<double, 2, 1> DoCoerceGoal(
+ const aos::controls::HPolytope<2> ®ion,
+ const Eigen::Matrix<double, 1, 2> &K, double w,
+ const Eigen::Matrix<double, 2, 1> &R, bool *is_inside) {
if (region.IsInside(R)) {
if (is_inside) *is_inside = true;
return R;
@@ -43,6 +42,7 @@
} else {
Eigen::Matrix<double, 2, Eigen::Dynamic> region_vertices =
region.Vertices();
+ CHECK_GT(region_vertices.outerSize(), 0);
double min_distance = INFINITY;
int closest_i = 0;
for (int i = 0; i < region_vertices.outerSize(); i++) {
diff --git a/frc971/control_loops/drivetrain/BUILD b/frc971/control_loops/drivetrain/BUILD
new file mode 100644
index 0000000..369de78
--- /dev/null
+++ b/frc971/control_loops/drivetrain/BUILD
@@ -0,0 +1,121 @@
+package(default_visibility = ['//visibility:public'])
+
+load('/aos/build/queues', 'queue_library')
+
+cc_binary(
+ name = 'replay_drivetrain',
+ srcs = [
+ 'replay_drivetrain.cc',
+ ],
+ deps = [
+ ':drivetrain_queue',
+ '//aos/common/controls:replay_control_loop',
+ '//aos/linux_code:init',
+ '//frc971/queues:gyro',
+ ],
+)
+
+queue_library(
+ name = 'drivetrain_queue',
+ srcs = [
+ 'drivetrain.q',
+ ],
+ deps = [
+ '//aos/common/controls:control_loop_queues',
+ ],
+)
+
+cc_library(
+ name = 'drivetrain_config',
+ hdrs = [
+ 'drivetrain_config.h',
+ ],
+ deps = [
+ '//frc971/control_loops:state_feedback_loop',
+ '//frc971:shifter_hall_effect',
+ ],
+)
+
+cc_library(
+ name = 'ssdrivetrain',
+ srcs = [
+ 'ssdrivetrain.cc',
+ ],
+ hdrs = [
+ 'ssdrivetrain.h',
+ ],
+ deps = [
+ ':drivetrain_queue',
+ ':drivetrain_config',
+ '//aos/common/controls:polytope',
+ '//aos/common:math',
+ '//aos/common/messages:robot_state',
+ '//frc971/control_loops:state_feedback_loop',
+ '//frc971/control_loops:coerce_goal',
+ '//frc971:shifter_hall_effect',
+ '//aos/common/util:log_interval',
+ '//aos/common/logging:queue_logging',
+ '//aos/common/logging:matrix_logging',
+ ],
+)
+
+cc_library(
+ name = 'polydrivetrain',
+ srcs = [
+ 'polydrivetrain.cc',
+ ],
+ hdrs = [
+ 'polydrivetrain.h',
+ ],
+ deps = [
+ ':drivetrain_queue',
+ ':drivetrain_config',
+ '//aos/common/controls:polytope',
+ '//aos/common:math',
+ '//aos/common/messages:robot_state',
+ '//frc971/control_loops:state_feedback_loop',
+ '//frc971/control_loops:coerce_goal',
+ '//aos/common/util:log_interval',
+ '//aos/common/logging:queue_logging',
+ '//aos/common/logging:matrix_logging',
+ ],
+)
+
+cc_library(
+ name = 'drivetrain_lib',
+ srcs = [
+ 'drivetrain.cc',
+ ],
+ hdrs = [
+ 'drivetrain.h',
+ ],
+ deps = [
+ ':drivetrain_queue',
+ ':polydrivetrain',
+ ':ssdrivetrain',
+ '//aos/common/controls:control_loop',
+ '//frc971/queues:gyro',
+ '//aos/common/util:log_interval',
+ '//aos/common/logging:queue_logging',
+ '//aos/common/logging:matrix_logging',
+ ],
+)
+
+cc_test(
+ name = 'drivetrain_lib_test',
+ srcs = [
+ 'drivetrain_lib_test.cc',
+ ],
+ deps = [
+ '//aos/testing:googletest',
+ ':drivetrain_queue',
+ ':drivetrain_lib',
+ ':drivetrain_config',
+ '//aos/common/controls:control_loop_test',
+ '//frc971/control_loops:state_feedback_loop',
+ '//frc971/queues:gyro',
+ '//aos/common:queues',
+ '//y2014:constants',
+ '//y2014/control_loops/drivetrain:polydrivetrain_plants',
+ ],
+)
diff --git a/y2014/control_loops/drivetrain/drivetrain.cc b/frc971/control_loops/drivetrain/drivetrain.cc
similarity index 73%
rename from y2014/control_loops/drivetrain/drivetrain.cc
rename to frc971/control_loops/drivetrain/drivetrain.cc
index 5717f36..ca395cb 100644
--- a/y2014/control_loops/drivetrain/drivetrain.cc
+++ b/frc971/control_loops/drivetrain/drivetrain.cc
@@ -1,4 +1,4 @@
-#include "y2014/control_loops/drivetrain/drivetrain.h"
+#include "frc971/control_loops/drivetrain/drivetrain.h"
#include <stdio.h>
#include <sched.h>
@@ -10,39 +10,34 @@
#include "aos/common/logging/queue_logging.h"
#include "aos/common/logging/matrix_logging.h"
-#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
-#include "y2014/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
-#include "y2014/control_loops/drivetrain/kalman_drivetrain_motor_plant.h"
-#include "y2014/control_loops/drivetrain/polydrivetrain.h"
-#include "y2014/control_loops/drivetrain/ssdrivetrain.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/polydrivetrain.h"
+#include "frc971/control_loops/drivetrain/ssdrivetrain.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
#include "frc971/queues/gyro.q.h"
#include "frc971/shifter_hall_effect.h"
-// A consistent way to mark code that goes away without shifters. It's still
-// here because we will have shifters again in the future.
-#define HAVE_SHIFTERS 1
-
using frc971::sensors::gyro_reading;
-namespace y2014 {
+namespace frc971 {
namespace control_loops {
namespace drivetrain {
DrivetrainLoop::DrivetrainLoop(
- ::y2014::control_loops::DrivetrainQueue *my_drivetrain)
- : aos::controls::ControlLoop<::y2014::control_loops::DrivetrainQueue>(
+ const DrivetrainConfig &dt_config,
+ ::frc971::control_loops::DrivetrainQueue *my_drivetrain)
+ : aos::controls::ControlLoop<::frc971::control_loops::DrivetrainQueue>(
my_drivetrain),
- kf_(::y2014::control_loops::drivetrain::MakeKFDrivetrainLoop()),
- dt_openloop_(&kf_) {
+ dt_config_(dt_config),
+ kf_(dt_config_.make_kf_drivetrain_loop()) {
::aos::controls::HPolytope<0>::Init();
}
void DrivetrainLoop::RunIteration(
- const ::y2014::control_loops::DrivetrainQueue::Goal *goal,
- const ::y2014::control_loops::DrivetrainQueue::Position *position,
- ::y2014::control_loops::DrivetrainQueue::Output *output,
- ::y2014::control_loops::DrivetrainQueue::Status *status) {
+ const ::frc971::control_loops::DrivetrainQueue::Goal *goal,
+ const ::frc971::control_loops::DrivetrainQueue::Position *position,
+ ::frc971::control_loops::DrivetrainQueue::Output *output,
+ ::frc971::control_loops::DrivetrainQueue::Status *status) {
bool bad_pos = false;
if (position == nullptr) {
LOG_INTERVAL(no_position_);
@@ -56,8 +51,9 @@
Eigen::Matrix<double, 3, 1> Y;
Y << position->left_encoder, position->right_encoder, last_gyro_rate_;
kf_.Correct(Y);
- integrated_kf_heading_ +=
- kDt * (kf_.X_hat(3, 0) - kf_.X_hat(1, 0)) / (kRobotRadius * 2.0);
+ integrated_kf_heading_ += dt_config_.dt *
+ (kf_.X_hat(3, 0) - kf_.X_hat(1, 0)) /
+ (dt_config_.robot_radius * 2.0);
}
bool control_loop_driving = false;
@@ -65,9 +61,7 @@
double wheel = goal->steering;
double throttle = goal->throttle;
bool quickturn = goal->quickturn;
-#if HAVE_SHIFTERS
bool highgear = goal->highgear;
-#endif
control_loop_driving = goal->control_loop_driving;
double left_goal = goal->left_goal;
@@ -75,11 +69,7 @@
dt_closedloop_.SetGoal(left_goal, goal->left_velocity_goal, right_goal,
goal->right_velocity_goal);
-#if HAVE_SHIFTERS
dt_openloop_.SetGoal(wheel, throttle, quickturn, highgear);
-#else
- dt_openloop_.SetGoal(wheel, throttle, quickturn, false);
-#endif
}
if (!bad_pos) {
@@ -123,7 +113,6 @@
status->uncapped_right_voltage = dt_closedloop_.loop().U_uncapped(1, 0);
}
-
double left_voltage = 0.0;
double right_voltage = 0.0;
if (output) {
@@ -154,4 +143,4 @@
} // namespace drivetrain
} // namespace control_loops
-} // namespace y2014
+} // namespace frc971
diff --git a/frc971/control_loops/drivetrain/drivetrain.h b/frc971/control_loops/drivetrain/drivetrain.h
new file mode 100644
index 0000000..22a6c32
--- /dev/null
+++ b/frc971/control_loops/drivetrain/drivetrain.h
@@ -0,0 +1,58 @@
+#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_H_
+#define FRC971_CONTROL_LOOPS_DRIVETRAIN_H_
+
+#include "Eigen/Dense"
+
+#include "aos/common/controls/polytope.h"
+#include "aos/common/controls/control_loop.h"
+#include "aos/common/controls/polytope.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/polydrivetrain.h"
+#include "frc971/control_loops/drivetrain/ssdrivetrain.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+#include "aos/common/util/log_interval.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace drivetrain {
+
+class DrivetrainLoop : public aos::controls::ControlLoop<
+ ::frc971::control_loops::DrivetrainQueue> {
+ public:
+ // Constructs a control loop which can take a Drivetrain or defaults to the
+ // drivetrain at frc971::control_loops::drivetrain
+ explicit DrivetrainLoop(const DrivetrainConfig &dt_config,
+ ::frc971::control_loops::DrivetrainQueue *my_drivetrain =
+ &::frc971::control_loops::drivetrain_queue);
+
+ protected:
+ // Executes one cycle of the control loop.
+ virtual void RunIteration(
+ const ::frc971::control_loops::DrivetrainQueue::Goal *goal,
+ const ::frc971::control_loops::DrivetrainQueue::Position *position,
+ ::frc971::control_loops::DrivetrainQueue::Output *output,
+ ::frc971::control_loops::DrivetrainQueue::Status *status);
+
+ typedef ::aos::util::SimpleLogInterval SimpleLogInterval;
+ SimpleLogInterval no_position_ = SimpleLogInterval(
+ ::aos::time::Time::InSeconds(0.25), WARNING, "no position");
+ double last_gyro_heading_ = 0.0;
+ double last_gyro_rate_ = 0.0;
+
+ const DrivetrainConfig dt_config_;
+
+ PolyDrivetrain dt_openloop_{dt_config_};
+ DrivetrainMotorsSS dt_closedloop_{dt_config_};
+ StateFeedbackLoop<7, 2, 3> kf_;
+
+ double last_left_voltage_ = 0;
+ double last_right_voltage_ = 0;
+
+ double integrated_kf_heading_ = 0;
+};
+
+} // namespace drivetrain
+} // namespace control_loops
+} // namespace frc971
+
+#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_H_
diff --git a/y2014/control_loops/drivetrain/drivetrain.q b/frc971/control_loops/drivetrain/drivetrain.q
similarity index 99%
rename from y2014/control_loops/drivetrain/drivetrain.q
rename to frc971/control_loops/drivetrain/drivetrain.q
index 96bd817..b4a71ec 100644
--- a/y2014/control_loops/drivetrain/drivetrain.q
+++ b/frc971/control_loops/drivetrain/drivetrain.q
@@ -1,4 +1,4 @@
-package y2014.control_loops;
+package frc971.control_loops;
import "aos/common/controls/control_loops.q";
diff --git a/frc971/control_loops/drivetrain/drivetrain_config.h b/frc971/control_loops/drivetrain/drivetrain_config.h
new file mode 100644
index 0000000..07fbe93
--- /dev/null
+++ b/frc971/control_loops/drivetrain/drivetrain_config.h
@@ -0,0 +1,54 @@
+#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_CONSTANTS_H_
+#define FRC971_CONTROL_LOOPS_DRIVETRAIN_CONSTANTS_H_
+
+#include <functional>
+
+#include "frc971/shifter_hall_effect.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace drivetrain {
+
+enum class ShifterType : int32_t {
+ HALL_EFFECT_SHIFTER = 0, // Detect when inbetween gears.
+ SIMPLE_SHIFTER = 1, // Switch gears without speedmatch logic.
+};
+
+struct DrivetrainConfig {
+ // Shifting method we are using.
+ ShifterType shifter_type;
+
+ // Polydrivetrain functions returning various controller loops with plants.
+ ::std::function<StateFeedbackLoop<4, 2, 2>()> make_drivetrain_loop;
+ ::std::function<StateFeedbackLoop<2, 2, 2>()> make_v_drivetrain_loop;
+ ::std::function<StateFeedbackLoop<7, 2, 3>()> make_kf_drivetrain_loop;
+
+ double dt; // Control loop time step.
+ double stall_torque; // Stall torque in N m.
+ double stall_current; // Stall current in amps.
+ double free_speed_rpm; // Free speed in rpm.
+ double free_current; // Free current in amps.
+ double j; // CIM moment of inertia in kg m^2.
+ double mass; // Mass of the robot.
+ double robot_radius; // Robot radius, in meters.
+ double wheel_radius; // Wheel radius, in meters.
+ double r; // Motor resistance.
+ double v; // Motor velocity constant.
+ double t; // Torque constant.
+
+ double turn_width; // Robot turn width, in meters.
+ // Gear ratios, from encoder shaft to transmission output.
+ double high_gear_ratio;
+ double low_gear_ratio;
+
+ // Hall effect constants. Unused if not applicable to shifter type.
+ constants::ShifterHallEffect left_drive;
+ constants::ShifterHallEffect right_drive;
+};
+
+} // namespace drivetrain
+} // namespace control_loops
+} // namespace frc971
+
+#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_CONSTANTS_H_
diff --git a/y2014/control_loops/drivetrain/drivetrain_lib_test.cc b/frc971/control_loops/drivetrain/drivetrain_lib_test.cc
similarity index 65%
rename from y2014/control_loops/drivetrain/drivetrain_lib_test.cc
rename to frc971/control_loops/drivetrain/drivetrain_lib_test.cc
index adfc519..9d7e223 100644
--- a/y2014/control_loops/drivetrain/drivetrain_lib_test.cc
+++ b/frc971/control_loops/drivetrain/drivetrain_lib_test.cc
@@ -7,21 +7,53 @@
#include "aos/common/controls/polytope.h"
#include "aos/common/controls/control_loop_test.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
-#include "y2014/control_loops/drivetrain/drivetrain.h"
+#include "y2014/constants.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
#include "frc971/control_loops/state_feedback_loop.h"
#include "frc971/control_loops/coerce_goal.h"
#include "y2014/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
+#include "y2014/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
+#include "y2014/control_loops/drivetrain/kalman_drivetrain_motor_plant.h"
#include "frc971/queues/gyro.q.h"
-
-namespace y2014 {
+namespace frc971 {
namespace control_loops {
namespace drivetrain {
namespace testing {
using ::y2014::control_loops::drivetrain::MakeDrivetrainPlant;
+// TODO(Comran): Make one that doesn't depend on the actual values for a
+// specific robot.
+const DrivetrainConfig kDrivetrainConfig {
+ ::frc971::control_loops::drivetrain::ShifterType::HALL_EFFECT_SHIFTER,
+
+ ::y2014::control_loops::drivetrain::MakeDrivetrainLoop,
+ ::y2014::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+ ::y2014::control_loops::drivetrain::MakeKFDrivetrainLoop,
+
+ ::y2014::control_loops::drivetrain::kDt,
+ ::y2014::control_loops::drivetrain::kStallTorque,
+ ::y2014::control_loops::drivetrain::kStallCurrent,
+ ::y2014::control_loops::drivetrain::kFreeSpeedRPM,
+ ::y2014::control_loops::drivetrain::kFreeCurrent,
+ ::y2014::control_loops::drivetrain::kJ,
+ ::y2014::control_loops::drivetrain::kMass,
+ ::y2014::control_loops::drivetrain::kRobotRadius,
+ ::y2014::control_loops::drivetrain::kWheelRadius,
+ ::y2014::control_loops::drivetrain::kR,
+ ::y2014::control_loops::drivetrain::kV,
+ ::y2014::control_loops::drivetrain::kT,
+
+ ::y2014::constants::GetValuesForTeam(971).turn_width,
+ ::y2014::constants::GetValuesForTeam(971).high_gear_ratio,
+ ::y2014::constants::GetValuesForTeam(971).low_gear_ratio,
+ ::y2014::constants::GetValuesForTeam(971).left_drive,
+ ::y2014::constants::GetValuesForTeam(971).right_drive
+};
+
class Environment : public ::testing::Environment {
public:
virtual ~Environment() {}
@@ -51,11 +83,11 @@
DrivetrainSimulation()
: drivetrain_plant_(
new StateFeedbackPlant<4, 2, 2>(MakeDrivetrainPlant())),
- my_drivetrain_queue_(".y2014.control_loops.drivetrain",
- 0x8a8dde77, ".y2014.control_loops.drivetrain.goal",
- ".y2014.control_loops.drivetrain.position",
- ".y2014.control_loops.drivetrain.output",
- ".y2014.control_loops.drivetrain.status") {
+ my_drivetrain_queue_(".frc971.control_loops.drivetrain",
+ 0x8a8dde77, ".frc971.control_loops.drivetrain.goal",
+ ".frc971.control_loops.drivetrain.position",
+ ".frc971.control_loops.drivetrain.output",
+ ".frc971.control_loops.drivetrain.status") {
Reinitialize();
}
@@ -78,7 +110,7 @@
const double left_encoder = GetLeftPosition();
const double right_encoder = GetRightPosition();
- ::aos::ScopedMessagePtr<::y2014::control_loops::DrivetrainQueue::Position>
+ ::aos::ScopedMessagePtr<::frc971::control_loops::DrivetrainQueue::Position>
position = my_drivetrain_queue_.position.MakeMessage();
position->left_encoder = left_encoder;
position->right_encoder = right_encoder;
@@ -97,7 +129,7 @@
::std::unique_ptr<StateFeedbackPlant<4, 2, 2>> drivetrain_plant_;
private:
- ::y2014::control_loops::DrivetrainQueue my_drivetrain_queue_;
+ ::frc971::control_loops::DrivetrainQueue my_drivetrain_queue_;
double last_left_position_;
double last_right_position_;
};
@@ -107,19 +139,19 @@
// Create a new instance of the test queue so that it invalidates the queue
// that it points to. Otherwise, we will have a pointer to shared memory that
// is no longer valid.
- ::y2014::control_loops::DrivetrainQueue my_drivetrain_queue_;
+ ::frc971::control_loops::DrivetrainQueue my_drivetrain_queue_;
// Create a loop and simulation plant.
DrivetrainLoop drivetrain_motor_;
DrivetrainSimulation drivetrain_motor_plant_;
- DrivetrainTest() : my_drivetrain_queue_(".y2014.control_loops.drivetrain",
+ DrivetrainTest() : my_drivetrain_queue_(".frc971.control_loops.drivetrain",
0x8a8dde77,
- ".y2014.control_loops.drivetrain.goal",
- ".y2014.control_loops.drivetrain.position",
- ".y2014.control_loops.drivetrain.output",
- ".y2014.control_loops.drivetrain.status"),
- drivetrain_motor_(&my_drivetrain_queue_),
+ ".frc971.control_loops.drivetrain.goal",
+ ".frc971.control_loops.drivetrain.position",
+ ".frc971.control_loops.drivetrain.output",
+ ".frc971.control_loops.drivetrain.status"),
+ drivetrain_motor_(kDrivetrainConfig, &my_drivetrain_queue_),
drivetrain_motor_plant_() {
::frc971::sensors::gyro_reading.Clear();
}
@@ -192,6 +224,48 @@
}
}
+// Tests that the robot successfully drives straight forward.
+// This used to not work due to a U-capping bug.
+TEST_F(DrivetrainTest, DriveStraightForward) {
+ my_drivetrain_queue_.goal.MakeWithBuilder()
+ .control_loop_driving(true)
+ .left_goal(4.0)
+ .right_goal(4.0)
+ .Send();
+ for (int i = 0; i < 500; ++i) {
+ drivetrain_motor_plant_.SendPositionMessage();
+ drivetrain_motor_.Iterate();
+ drivetrain_motor_plant_.Simulate();
+ SimulateTimestep(true);
+ ASSERT_TRUE(my_drivetrain_queue_.output.FetchLatest());
+ EXPECT_FLOAT_EQ(my_drivetrain_queue_.output->left_voltage,
+ my_drivetrain_queue_.output->right_voltage);
+ EXPECT_GT(my_drivetrain_queue_.output->left_voltage, -3);
+ EXPECT_GT(my_drivetrain_queue_.output->right_voltage, -3);
+ }
+ VerifyNearGoal();
+}
+
+// Tests that the robot successfully drives close to straight.
+// This used to fail in simulation due to libcdd issues with U-capping.
+TEST_F(DrivetrainTest, DriveAlmostStraightForward) {
+ my_drivetrain_queue_.goal.MakeWithBuilder()
+ .control_loop_driving(true)
+ .left_goal(4.0)
+ .right_goal(3.9)
+ .Send();
+ for (int i = 0; i < 500; ++i) {
+ drivetrain_motor_plant_.SendPositionMessage();
+ drivetrain_motor_.Iterate();
+ drivetrain_motor_plant_.Simulate();
+ SimulateTimestep(true);
+ ASSERT_TRUE(my_drivetrain_queue_.output.FetchLatest());
+ EXPECT_GT(my_drivetrain_queue_.output->left_voltage, -3);
+ EXPECT_GT(my_drivetrain_queue_.output->right_voltage, -3);
+ }
+ VerifyNearGoal();
+}
+
::aos::controls::HPolytope<2> MakeBox(double x1_min, double x1_max,
double x2_min, double x2_max) {
Eigen::Matrix<double, 4, 2> box_H;
@@ -297,4 +371,4 @@
} // namespace testing
} // namespace drivetrain
} // namespace control_loops
-} // namespace y2014
+} // namespace frc971
diff --git a/y2014/control_loops/drivetrain/polydrivetrain.cc b/frc971/control_loops/drivetrain/polydrivetrain.cc
similarity index 71%
rename from y2014/control_loops/drivetrain/polydrivetrain.cc
rename to frc971/control_loops/drivetrain/polydrivetrain.cc
index 014a1ae..dd9354e 100644
--- a/y2014/control_loops/drivetrain/polydrivetrain.cc
+++ b/frc971/control_loops/drivetrain/polydrivetrain.cc
@@ -1,4 +1,4 @@
-#include "y2014/control_loops/drivetrain/polydrivetrain.h"
+#include "frc971/control_loops/drivetrain/polydrivetrain.h"
#include "aos/common/logging/logging.h"
#include "aos/common/controls/polytope.h"
@@ -9,22 +9,19 @@
#include "aos/common/messages/robot_state.q.h"
#include "frc971/control_loops/state_feedback_loop.h"
#include "frc971/control_loops/coerce_goal.h"
-#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
-#include "y2014/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
-#define HAVE_SHIFTERS 1
-
-namespace y2014 {
+namespace frc971 {
namespace control_loops {
namespace drivetrain {
-using ::y2014::control_loops::GearLogging;
-using ::y2014::control_loops::CIMLogging;
+using ::frc971::control_loops::GearLogging;
+using ::frc971::control_loops::CIMLogging;
using ::frc971::control_loops::CoerceGoal;
-PolyDrivetrain::PolyDrivetrain(StateFeedbackLoop<7, 2, 3> *kf)
- : kf_(kf),
+PolyDrivetrain::PolyDrivetrain(const DrivetrainConfig &dt_config)
+ : kf_(dt_config.make_kf_drivetrain_loop()),
U_Poly_((Eigen::Matrix<double, 4, 2>() << /*[[*/ 1, 0 /*]*/,
/*[*/ -1, 0 /*]*/,
/*[*/ 0, 1 /*]*/,
@@ -33,17 +30,17 @@
/*[*/ 12 /*]*/,
/*[*/ 12 /*]*/,
/*[*/ 12 /*]]*/).finished()),
- loop_(new StateFeedbackLoop<2, 2, 2>(
- constants::GetValues().make_v_drivetrain_loop())),
+ loop_(new StateFeedbackLoop<2, 2, 2>(dt_config.make_v_drivetrain_loop())),
ttrust_(1.1),
wheel_(0.0),
throttle_(0.0),
quickturn_(false),
stale_count_(0),
- position_time_delta_(kDt),
+ position_time_delta_(dt_config.dt),
left_gear_(LOW),
right_gear_(LOW),
- counter_(0) {
+ counter_(0),
+ dt_config_(dt_config) {
last_position_.Zero();
position_.Zero();
}
@@ -55,19 +52,22 @@
(hall_effect.clear_high + hall_effect.clear_low) / 2.0;
if (shifter_position > avg_hall_effect) {
- return velocity / constants::GetValues().high_gear_ratio / kWheelRadius;
+ return velocity / dt_config_.high_gear_ratio / dt_config_.wheel_radius;
} else {
- return velocity / constants::GetValues().low_gear_ratio / kWheelRadius;
+ return velocity / dt_config_.low_gear_ratio / dt_config_.wheel_radius;
}
}
-PolyDrivetrain::Gear PolyDrivetrain::UpdateSingleGear(
- Gear requested_gear, Gear current_gear) {
+PolyDrivetrain::Gear PolyDrivetrain::UpdateSingleGear(Gear requested_gear,
+ Gear current_gear) {
const Gear shift_up =
- constants::GetValues().clutch_transmission ? HIGH : SHIFTING_UP;
+ (dt_config_.shifter_type == ShifterType::HALL_EFFECT_SHIFTER)
+ ? SHIFTING_UP
+ : HIGH;
const Gear shift_down =
- constants::GetValues().clutch_transmission ? LOW : SHIFTING_DOWN;
-
+ (dt_config_.shifter_type == ShifterType::HALL_EFFECT_SHIFTER)
+ ? SHIFTING_DOWN
+ : LOW;
if (current_gear != requested_gear) {
if (IsInGear(current_gear)) {
if (requested_gear == HIGH) {
@@ -101,6 +101,16 @@
// Apply a sin function that's scaled to make it feel better.
const double angular_range = M_PI_2 * kWheelNonLinearity;
+ if (dt_config_.shifter_type == ShifterType::SIMPLE_SHIFTER) {
+ // Force the right controller for simple shifters since we assume that
+ // gear switching is instantaneous.
+ if (highgear) {
+ loop_->set_controller_index(3);
+ } else {
+ loop_->set_controller_index(0);
+ }
+ }
+
wheel_ = sin(angular_range * wheel) / sin(angular_range);
wheel_ = sin(angular_range * wheel_) / sin(angular_range);
quickturn_ = quickturn;
@@ -118,24 +128,25 @@
}
void PolyDrivetrain::SetPosition(
- const ::y2014::control_loops::DrivetrainQueue::Position *position) {
+ const ::frc971::control_loops::DrivetrainQueue::Position *position) {
if (position == NULL) {
++stale_count_;
} else {
last_position_ = position_;
position_ = *position;
- position_time_delta_ = (stale_count_ + 1) * kDt;
+ position_time_delta_ = (stale_count_ + 1) * dt_config_.dt;
stale_count_ = 0;
}
- if (position) {
- const auto &values = constants::GetValues();
+ if (dt_config_.shifter_type == ShifterType::HALL_EFFECT_SHIFTER && position) {
GearLogging gear_logging;
// Switch to the correct controller.
const double left_middle_shifter_position =
- (values.left_drive.clear_high + values.left_drive.clear_low) / 2.0;
+ (dt_config_.left_drive.clear_high + dt_config_.left_drive.clear_low) /
+ 2.0;
const double right_middle_shifter_position =
- (values.right_drive.clear_high + values.right_drive.clear_low) / 2.0;
+ (dt_config_.right_drive.clear_high + dt_config_.right_drive.clear_low) /
+ 2.0;
if (position->left_shifter_position < left_middle_shifter_position ||
left_gear_ == LOW) {
@@ -162,19 +173,19 @@
}
}
- if (position->left_shifter_position > values.left_drive.clear_high &&
+ if (position->left_shifter_position > dt_config_.left_drive.clear_high &&
left_gear_ == SHIFTING_UP) {
left_gear_ = HIGH;
}
- if (position->left_shifter_position < values.left_drive.clear_low &&
+ if (position->left_shifter_position < dt_config_.left_drive.clear_low &&
left_gear_ == SHIFTING_DOWN) {
left_gear_ = LOW;
}
- if (position->right_shifter_position > values.right_drive.clear_high &&
+ if (position->right_shifter_position > dt_config_.right_drive.clear_high &&
right_gear_ == SHIFTING_UP) {
right_gear_ = HIGH;
}
- if (position->right_shifter_position < values.right_drive.clear_low &&
+ if (position->right_shifter_position < dt_config_.right_drive.clear_low &&
right_gear_ == SHIFTING_DOWN) {
right_gear_ = LOW;
}
@@ -233,48 +244,12 @@
}
void PolyDrivetrain::Update() {
- loop_->mutable_X_hat()(0, 0) = kf_->X_hat()(1, 0);
- loop_->mutable_X_hat()(1, 0) = kf_->X_hat()(3, 0);
+ loop_->mutable_X_hat()(0, 0) = kf_.X_hat()(1, 0);
+ loop_->mutable_X_hat()(1, 0) = kf_.X_hat()(3, 0);
- const auto &values = constants::GetValues();
// TODO(austin): Observer for the current velocity instead of difference
// calculations.
++counter_;
- const double current_left_velocity =
- (position_.left_encoder - last_position_.left_encoder) /
- position_time_delta_;
- const double current_right_velocity =
- (position_.right_encoder - last_position_.right_encoder) /
- position_time_delta_;
- const double left_motor_speed =
- MotorSpeed(values.left_drive, position_.left_shifter_position,
- current_left_velocity);
- const double right_motor_speed =
- MotorSpeed(values.right_drive, position_.right_shifter_position,
- current_right_velocity);
-
- {
- CIMLogging logging;
-
- // Reset the CIM model to the current conditions to be ready for when we
- // shift.
- if (IsInGear(left_gear_)) {
- logging.left_in_gear = true;
- } else {
- logging.left_in_gear = false;
- }
- logging.left_motor_speed = left_motor_speed;
- logging.left_velocity = current_left_velocity;
- if (IsInGear(right_gear_)) {
- logging.right_in_gear = true;
- } else {
- logging.right_in_gear = false;
- }
- logging.right_motor_speed = right_motor_speed;
- logging.right_velocity = current_right_velocity;
-
- LOG_STRUCT(DEBUG, "currently", logging);
- }
if (IsInGear(left_gear_) && IsInGear(right_gear_)) {
// FF * X = U (steady state)
@@ -328,6 +303,42 @@
loop_->mutable_U()[i] = ::aos::Clip(U_ideal[i], -12, 12);
}
} else {
+ const double current_left_velocity =
+ (position_.left_encoder - last_position_.left_encoder) /
+ position_time_delta_;
+ const double current_right_velocity =
+ (position_.right_encoder - last_position_.right_encoder) /
+ position_time_delta_;
+ const double left_motor_speed =
+ MotorSpeed(dt_config_.left_drive, position_.left_shifter_position,
+ current_left_velocity);
+ const double right_motor_speed =
+ MotorSpeed(dt_config_.right_drive, position_.right_shifter_position,
+ current_right_velocity);
+
+ {
+ CIMLogging logging;
+
+ // Reset the CIM model to the current conditions to be ready for when we
+ // shift.
+ if (IsInGear(left_gear_)) {
+ logging.left_in_gear = true;
+ } else {
+ logging.left_in_gear = false;
+ }
+ logging.left_motor_speed = left_motor_speed;
+ logging.left_velocity = current_left_velocity;
+ if (IsInGear(right_gear_)) {
+ logging.right_in_gear = true;
+ } else {
+ logging.right_in_gear = false;
+ }
+ logging.right_motor_speed = right_motor_speed;
+ logging.right_velocity = current_right_velocity;
+
+ LOG_STRUCT(DEBUG, "currently", logging);
+ }
+
// Any motor is not in gear. Speed match.
::Eigen::Matrix<double, 1, 1> R_left;
::Eigen::Matrix<double, 1, 1> R_right;
@@ -338,16 +349,17 @@
(static_cast<double>((counter_ % 20) / 10) - 0.5) * 5.0;
loop_->mutable_U(0, 0) = ::aos::Clip(
- (R_left / Kv)(0, 0) + (IsInGear(left_gear_) ? 0 : wiggle), -12.0, 12.0);
- loop_->mutable_U(1, 0) =
- ::aos::Clip((R_right / Kv)(0, 0) + (IsInGear(right_gear_) ? 0 : wiggle),
- -12.0, 12.0);
+ (R_left / dt_config_.v)(0, 0) + (IsInGear(left_gear_) ? 0 : wiggle),
+ -12.0, 12.0);
+ loop_->mutable_U(1, 0) = ::aos::Clip(
+ (R_right / dt_config_.v)(0, 0) + (IsInGear(right_gear_) ? 0 : wiggle),
+ -12.0, 12.0);
loop_->mutable_U() *= 12.0 / ::aos::robot_state->voltage_battery;
}
}
void PolyDrivetrain::SendMotors(
- ::y2014::control_loops::DrivetrainQueue::Output *output) {
+ ::frc971::control_loops::DrivetrainQueue::Output *output) {
if (output != NULL) {
output->left_voltage = loop_->U(0, 0);
output->right_voltage = loop_->U(1, 0);
@@ -356,15 +368,6 @@
}
}
-constexpr double PolyDrivetrain::kStallTorque;
-constexpr double PolyDrivetrain::kStallCurrent;
-constexpr double PolyDrivetrain::kFreeSpeed;
-constexpr double PolyDrivetrain::kFreeCurrent;
-constexpr double PolyDrivetrain::kWheelRadius;
-constexpr double PolyDrivetrain::kR;
-constexpr double PolyDrivetrain::Kv;
-constexpr double PolyDrivetrain::Kt;
-
} // namespace drivetrain
} // namespace control_loops
-} // namespace y2014
+} // namespace frc971
diff --git a/frc971/control_loops/drivetrain/polydrivetrain.h b/frc971/control_loops/drivetrain/polydrivetrain.h
new file mode 100644
index 0000000..1ba7eee
--- /dev/null
+++ b/frc971/control_loops/drivetrain/polydrivetrain.h
@@ -0,0 +1,75 @@
+#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
+#define FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
+
+#include "aos/common/controls/polytope.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace drivetrain {
+
+class PolyDrivetrain {
+ public:
+ enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN };
+
+ PolyDrivetrain(const DrivetrainConfig &dt_config);
+
+ int controller_index() const { return loop_->controller_index(); }
+
+ bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
+
+ // Computes the speed of the motor given the hall effect position and the
+ // speed of the robot.
+ double MotorSpeed(const constants::ShifterHallEffect &hall_effect,
+ double shifter_position, double velocity);
+
+ // Computes the states of the shifters for the left and right drivetrain sides
+ // given a requested state.
+ void UpdateGears(Gear requested_gear);
+
+ // Computes the next state of a shifter given the current state and the
+ // requested state.
+ Gear UpdateSingleGear(Gear requested_gear, Gear current_gear);
+
+ void SetGoal(double wheel, double throttle, bool quickturn, bool highgear);
+
+ void SetPosition(
+ const ::frc971::control_loops::DrivetrainQueue::Position *position);
+
+ double FilterVelocity(double throttle);
+
+ double MaxVelocity();
+
+ void Update();
+
+ void SendMotors(::frc971::control_loops::DrivetrainQueue::Output *output);
+
+ private:
+ StateFeedbackLoop<7, 2, 3> kf_;
+
+ const ::aos::controls::HPolytope<2> U_Poly_;
+
+ ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
+
+ const double ttrust_;
+ double wheel_;
+ double throttle_;
+ bool quickturn_;
+ int stale_count_;
+ double position_time_delta_;
+ Gear left_gear_;
+ Gear right_gear_;
+ ::frc971::control_loops::DrivetrainQueue::Position last_position_;
+ ::frc971::control_loops::DrivetrainQueue::Position position_;
+ int counter_;
+ DrivetrainConfig dt_config_;
+};
+
+} // namespace drivetrain
+} // namespace control_loops
+} // namespace frc971
+
+#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
diff --git a/y2014/control_loops/drivetrain/replay_drivetrain.cc b/frc971/control_loops/drivetrain/replay_drivetrain.cc
similarity index 64%
rename from y2014/control_loops/drivetrain/replay_drivetrain.cc
rename to frc971/control_loops/drivetrain/replay_drivetrain.cc
index b0ac33f..c535607 100644
--- a/y2014/control_loops/drivetrain/replay_drivetrain.cc
+++ b/frc971/control_loops/drivetrain/replay_drivetrain.cc
@@ -1,7 +1,7 @@
#include "aos/common/controls/replay_control_loop.h"
#include "aos/linux_code/init.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#include "frc971/queues/gyro.q.h"
// Reads one or more log files and sends out all the queue messages (in the
@@ -17,8 +17,8 @@
{
::aos::controls::ControlLoopReplayer<
- ::y2014::control_loops::DrivetrainQueue>
- replayer(&::y2014::control_loops::drivetrain_queue, "drivetrain");
+ ::frc971::control_loops::DrivetrainQueue>
+ replayer(&::frc971::control_loops::drivetrain_queue, "drivetrain");
replayer.AddDirectQueueSender("wpilib_interface.Gyro", "sending",
::frc971::sensors::gyro_reading);
@@ -27,10 +27,10 @@
}
}
::frc971::sensors::gyro_reading.Clear();
- ::y2014::control_loops::drivetrain_queue.goal.Clear();
- ::y2014::control_loops::drivetrain_queue.status.Clear();
- ::y2014::control_loops::drivetrain_queue.position.Clear();
- ::y2014::control_loops::drivetrain_queue.output.Clear();
+ ::frc971::control_loops::drivetrain_queue.goal.Clear();
+ ::frc971::control_loops::drivetrain_queue.status.Clear();
+ ::frc971::control_loops::drivetrain_queue.position.Clear();
+ ::frc971::control_loops::drivetrain_queue.output.Clear();
::aos::Cleanup();
}
diff --git a/frc971/control_loops/drivetrain/ssdrivetrain.cc b/frc971/control_loops/drivetrain/ssdrivetrain.cc
new file mode 100644
index 0000000..9fdfe1c
--- /dev/null
+++ b/frc971/control_loops/drivetrain/ssdrivetrain.cc
@@ -0,0 +1,185 @@
+#include "frc971/control_loops/drivetrain/ssdrivetrain.h"
+
+#include "aos/common/controls/polytope.h"
+#include "aos/common/commonmath.h"
+#include "aos/common/logging/matrix_logging.h"
+
+#include "frc971/control_loops/state_feedback_loop.h"
+#include "frc971/control_loops/coerce_goal.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+namespace frc971 {
+namespace control_loops {
+namespace drivetrain {
+
+using ::frc971::control_loops::DoCoerceGoal;
+
+DrivetrainMotorsSS::LimitedDrivetrainLoop::LimitedDrivetrainLoop(
+ StateFeedbackLoop<4, 2, 2> &&loop)
+ : StateFeedbackLoop<4, 2, 2>(::std::move(loop)),
+ U_poly_((Eigen::Matrix<double, 4, 2>() << 1, 0, -1, 0, 0, 1, 0, -1)
+ .finished(),
+ (Eigen::Matrix<double, 4, 1>() << 12.0, 12.0, 12.0, 12.0)
+ .finished()) {
+ ::aos::controls::HPolytope<0>::Init();
+ T_ << 1, 1, 1, -1;
+ T_inverse_ = T_.inverse();
+}
+
+// This intentionally runs the U-capping code even when it's unnecessary to help
+// make it more deterministic. Only running it when one or both sides want
+// out-of-range voltages could lead to things like running out of CPU under
+// certain situations, which would be bad.
+void DrivetrainMotorsSS::LimitedDrivetrainLoop::CapU() {
+ output_was_capped_ = ::std::abs(U(0, 0)) > 12.0 || ::std::abs(U(1, 0)) > 12.0;
+
+ const Eigen::Matrix<double, 4, 1> error = R() - X_hat();
+
+ LOG_MATRIX(DEBUG, "U at start", U());
+ LOG_MATRIX(DEBUG, "R at start", R());
+ LOG_MATRIX(DEBUG, "Xhat at start", X_hat());
+
+ Eigen::Matrix<double, 2, 2> position_K;
+ position_K << K(0, 0), K(0, 2), K(1, 0), K(1, 2);
+ Eigen::Matrix<double, 2, 2> velocity_K;
+ velocity_K << K(0, 1), K(0, 3), K(1, 1), K(1, 3);
+
+ Eigen::Matrix<double, 2, 1> position_error;
+ position_error << error(0, 0), error(2, 0);
+ // drive_error = [total_distance_error, left_error - right_error]
+ const auto drive_error = T_inverse_ * position_error;
+ Eigen::Matrix<double, 2, 1> velocity_error;
+ velocity_error << error(1, 0), error(3, 0);
+ LOG_MATRIX(DEBUG, "error", error);
+
+ const ::aos::controls::HPolytope<2> pos_poly(U_poly_, position_K * T_,
+ -velocity_K * velocity_error);
+
+ Eigen::Matrix<double, 2, 1> adjusted_pos_error;
+ {
+ const auto &P = drive_error;
+
+ Eigen::Matrix<double, 1, 2> L45;
+ L45 << ::aos::sign(P(1, 0)), -::aos::sign(P(0, 0));
+ const double w45 = 0;
+
+ Eigen::Matrix<double, 1, 2> LH;
+ if (::std::abs(P(0, 0)) > ::std::abs(P(1, 0))) {
+ LH << 0, 1;
+ } else {
+ LH << 1, 0;
+ }
+ const double wh = LH.dot(P);
+
+ Eigen::Matrix<double, 2, 2> standard;
+ standard << L45, LH;
+ Eigen::Matrix<double, 2, 1> W;
+ W << w45, wh;
+ const Eigen::Matrix<double, 2, 1> intersection = standard.inverse() * W;
+
+ bool is_inside_h, is_inside_45;
+ const auto adjusted_pos_error_h =
+ DoCoerceGoal(pos_poly, LH, wh, drive_error, &is_inside_h);
+ const auto adjusted_pos_error_45 =
+ DoCoerceGoal(pos_poly, L45, w45, intersection, &is_inside_45);
+ if (pos_poly.IsInside(intersection)) {
+ adjusted_pos_error = adjusted_pos_error_h;
+ } else {
+ if (is_inside_h) {
+ if (adjusted_pos_error_h.norm() > adjusted_pos_error_45.norm() ||
+ adjusted_pos_error_45.norm() > intersection.norm()) {
+ adjusted_pos_error = adjusted_pos_error_h;
+ } else {
+ adjusted_pos_error = adjusted_pos_error_45;
+ }
+ } else {
+ adjusted_pos_error = adjusted_pos_error_45;
+ }
+ }
+ }
+
+ mutable_U() =
+ velocity_K * velocity_error + position_K * T_ * adjusted_pos_error;
+ LOG_MATRIX(DEBUG, "U is now", U());
+
+ if (!output_was_capped_) {
+ if ((U() - U_uncapped()).norm() > 0.0001) {
+ LOG(FATAL, "U unnecessarily capped\n");
+ }
+ }
+}
+
+DrivetrainMotorsSS::DrivetrainMotorsSS(const DrivetrainConfig &dt_config)
+ : loop_(
+ new LimitedDrivetrainLoop(dt_config.make_drivetrain_loop())),
+ filtered_offset_(0.0),
+ gyro_(0.0),
+ left_goal_(0.0),
+ right_goal_(0.0),
+ raw_left_(0.0),
+ raw_right_(0.0),
+ dt_config_(dt_config) {
+ // High gear on both.
+ loop_->set_controller_index(3);
+}
+
+void DrivetrainMotorsSS::SetGoal(double left, double left_velocity,
+ double right, double right_velocity) {
+ left_goal_ = left;
+ right_goal_ = right;
+ loop_->mutable_R() << left, left_velocity, right, right_velocity;
+}
+void DrivetrainMotorsSS::SetRawPosition(double left, double right) {
+ raw_right_ = right;
+ raw_left_ = left;
+ Eigen::Matrix<double, 2, 1> Y;
+ Y << left + filtered_offset_, right - filtered_offset_;
+ loop_->Correct(Y);
+}
+void DrivetrainMotorsSS::SetPosition(double left, double right, double gyro) {
+ // Decay the offset quickly because this gyro is great.
+ const double offset =
+ (right - left - gyro * dt_config_.turn_width) / 2.0;
+ filtered_offset_ = 0.25 * offset + 0.75 * filtered_offset_;
+ gyro_ = gyro;
+ SetRawPosition(left, right);
+}
+
+void DrivetrainMotorsSS::SetExternalMotors(double left_voltage,
+ double right_voltage) {
+ loop_->mutable_U() << left_voltage, right_voltage;
+}
+
+void DrivetrainMotorsSS::Update(bool stop_motors, bool enable_control_loop) {
+ if (enable_control_loop) {
+ loop_->Update(stop_motors);
+ } else {
+ if (stop_motors) {
+ loop_->mutable_U().setZero();
+ loop_->mutable_U_uncapped().setZero();
+ }
+ loop_->UpdateObserver(loop_->U());
+ }
+ ::Eigen::Matrix<double, 4, 1> E = loop_->R() - loop_->X_hat();
+ LOG_MATRIX(DEBUG, "E", E);
+}
+
+double DrivetrainMotorsSS::GetEstimatedRobotSpeed() const {
+ // lets just call the average of left and right velocities close enough
+ return (loop_->X_hat(1, 0) + loop_->X_hat(3, 0)) / 2;
+}
+
+void DrivetrainMotorsSS::SendMotors(
+ ::frc971::control_loops::DrivetrainQueue::Output *output) const {
+ if (output) {
+ output->left_voltage = loop_->U(0, 0);
+ output->right_voltage = loop_->U(1, 0);
+ output->left_high = true;
+ output->right_high = true;
+ }
+}
+
+} // namespace drivetrain
+} // namespace control_loops
+} // namespace frc971
diff --git a/y2014/control_loops/drivetrain/ssdrivetrain.h b/frc971/control_loops/drivetrain/ssdrivetrain.h
similarity index 65%
rename from y2014/control_loops/drivetrain/ssdrivetrain.h
rename to frc971/control_loops/drivetrain/ssdrivetrain.h
index 1964ac5..193dbb2 100644
--- a/y2014/control_loops/drivetrain/ssdrivetrain.h
+++ b/frc971/control_loops/drivetrain/ssdrivetrain.h
@@ -1,5 +1,5 @@
-#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
-#define Y2014_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
+#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
+#define FRC971_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
#include "aos/common/controls/polytope.h"
#include "aos/common/commonmath.h"
@@ -7,10 +7,10 @@
#include "frc971/control_loops/state_feedback_loop.h"
#include "frc971/control_loops/coerce_goal.h"
-#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
-namespace y2014 {
+namespace frc971 {
namespace control_loops {
namespace drivetrain {
@@ -27,12 +27,18 @@
private:
void CapU() override;
- const ::aos::controls::HPolytope<2> U_Poly_;
- Eigen::Matrix<double, 2, 2> T, T_inverse;
- bool output_was_capped_ = false;;
+ // Reprsents +/- full power on each motor in U-space, aka the square from
+ // (-12, -12) to (12, 12).
+ const ::aos::controls::HPolytope<2> U_poly_;
+
+ // multiplying by T converts [left_error, right_error] to
+ // [left_right_error_difference, total_distance_error].
+ Eigen::Matrix<double, 2, 2> T_, T_inverse_;
+
+ bool output_was_capped_ = false;
};
- DrivetrainMotorsSS();
+ DrivetrainMotorsSS(const DrivetrainConfig &dt_config);
void SetGoal(double left, double left_velocity, double right,
double right_velocity);
@@ -63,7 +69,7 @@
}
void SendMotors(
- ::y2014::control_loops::DrivetrainQueue::Output *output) const;
+ ::frc971::control_loops::DrivetrainQueue::Output *output) const;
const LimitedDrivetrainLoop &loop() const { return *loop_; }
@@ -76,10 +82,12 @@
double right_goal_;
double raw_left_;
double raw_right_;
+
+ const DrivetrainConfig dt_config_;
};
} // namespace drivetrain
} // namespace control_loops
-} // namespace y2014
+} // namespace frc971
-#endif // Y2014_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
+#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_SSDRIVETRAIN_H_
diff --git a/frc971/control_loops/python/BUILD b/frc971/control_loops/python/BUILD
index fa94d01..d172983 100644
--- a/frc971/control_loops/python/BUILD
+++ b/frc971/control_loops/python/BUILD
@@ -16,3 +16,13 @@
'//third_party/cddlib:_cddlib.so',
],
)
+
+py_test(
+ name = 'polytope_test',
+ srcs = [
+ 'polytope_test.py',
+ ],
+ deps = [
+ ':controls',
+ ],
+)
diff --git a/frc971/control_loops/python/polytope_test.py b/frc971/control_loops/python/polytope_test.py
index 9a35ebe..51bf6fd 100755
--- a/frc971/control_loops/python/polytope_test.py
+++ b/frc971/control_loops/python/polytope_test.py
@@ -2,9 +2,10 @@
import numpy
from numpy.testing import *
-import polytope
import unittest
+import frc971.control_loops.python.polytope as polytope
+
__author__ = 'Austin Schuh (austin.linux@gmail.com)'
def MakePoint(*args):
diff --git a/tools/cpp/BUILD b/tools/cpp/BUILD
index 272a896..44eaa41 100644
--- a/tools/cpp/BUILD
+++ b/tools/cpp/BUILD
@@ -38,7 +38,7 @@
srcs = [
':cc-compiler-k8',
':cc-compiler-roborio',
- '@arm-frc-linux-gnueabi-repo//:compiler_components',
+ '@arm_frc_linux_gnueabi_repo//:compiler_components',
':roborio-compiler-files',
':flags_compiler_inputs',
'@linaro_linux_gcc_4.9_repo//:compiler_components',
@@ -79,7 +79,7 @@
srcs = [
'//tools/cpp/arm-frc-linux-gnueabi:tool-wrappers',
'//tools/cpp/arm-frc-linux-gnueabi:as',
- '@arm-frc-linux-gnueabi-repo//:compiler_pieces',
+ '@arm_frc_linux_gnueabi_repo//:compiler_pieces',
':flags_compiler_inputs',
],
)
@@ -90,7 +90,7 @@
'//tools/cpp/arm-frc-linux-gnueabi:ld',
'//tools/cpp/arm-frc-linux-gnueabi:ar',
'//tools/cpp/arm-frc-linux-gnueabi:gcc',
- '@arm-frc-linux-gnueabi-repo//:compiler_pieces',
+ '@arm_frc_linux_gnueabi_repo//:compiler_pieces',
],
)
filegroup(
diff --git a/tools/cpp/CROSSTOOL b/tools/cpp/CROSSTOOL
index 0a07ba3..f483e2b 100644
--- a/tools/cpp/CROSSTOOL
+++ b/tools/cpp/CROSSTOOL
@@ -312,41 +312,41 @@
tool_path { name: "objdump" path: "arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objdump" }
tool_path { name: "strip" path: "arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-strip" }
- compiler_flag: "--sysroot=external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi"
+ compiler_flag: "--sysroot=external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi"
compiler_flag: "-nostdinc"
compiler_flag: "-isystem"
- compiler_flag: "external/arm-frc-linux-gnueabi-repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include",
+ compiler_flag: "external/arm_frc_linux_gnueabi_repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include",
compiler_flag: "-isystem"
- compiler_flag: "external/arm-frc-linux-gnueabi-repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include-fixed"
+ compiler_flag: "external/arm_frc_linux_gnueabi_repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include-fixed"
compiler_flag: "-isystem"
- compiler_flag: "external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi/usr/include"
+ compiler_flag: "external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi/usr/include"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi/include/c++/4.9.3"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi/include/c++/4.9.3"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi/include/c++/4.9.3/arm-frc-linux-gnueabi"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi/include/c++/4.9.3/arm-frc-linux-gnueabi"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi/include/c++/4.9.3/backward"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi/include/c++/4.9.3/backward"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include-fixed"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include-fixed"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi/include"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi/include"
cxx_flag: "-isystem"
- cxx_flag: "external/arm-frc-linux-gnueabi-repo/usr/arm-frc-linux-gnueabi/usr/include"
+ cxx_flag: "external/arm_frc_linux_gnueabi_repo/usr/arm-frc-linux-gnueabi/usr/include"
# TODO(bazel-team): In theory, the path here ought to exactly match the path
# used by gcc. That works because bazel currently doesn't track files at
# absolute locations and has no remote execution, yet. However, this will need
# to be fixed, maybe with auto-detection?
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/arm-frc-linux-gnueabi/include)%/c++/4.9.3"
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/arm-frc-linux-gnueabi/include)%/c++/4.9.3/arm-frc-linux-gnueabi"
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/arm-frc-linux-gnueabi/include)%/c++/4.9.3/backward"
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include)%"
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include-fixed)%"
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/arm-frc-linux-gnueabi/include)%"
- cxx_builtin_include_directory: "%package(@arm-frc-linux-gnueabi-repo//usr/arm-frc-linux-gnueabi/usr/include)%"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/arm-frc-linux-gnueabi/include)%/c++/4.9.3"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/arm-frc-linux-gnueabi/include)%/c++/4.9.3/arm-frc-linux-gnueabi"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/arm-frc-linux-gnueabi/include)%/c++/4.9.3/backward"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include)%"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/lib/x86_64-linux-gnu/gcc/arm-frc-linux-gnueabi/4.9.3/include-fixed)%"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/arm-frc-linux-gnueabi/include)%"
+ cxx_builtin_include_directory: "%package(@arm_frc_linux_gnueabi_repo//usr/arm-frc-linux-gnueabi/usr/include)%"
linker_flag: "-lstdc++"
#linker_flag: "-B/usr/bin/"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/BUILD b/tools/cpp/arm-frc-linux-gnueabi/BUILD
index 64342a9..17a10c2 100644
--- a/tools/cpp/arm-frc-linux-gnueabi/BUILD
+++ b/tools/cpp/arm-frc-linux-gnueabi/BUILD
@@ -3,7 +3,7 @@
filegroup(
name = 'gcc',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:gcc',
+ '@arm_frc_linux_gnueabi_repo//:gcc',
'arm-frc-linux-gnueabi-gcc',
],
)
@@ -11,7 +11,7 @@
filegroup(
name = 'ar',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:ar',
+ '@arm_frc_linux_gnueabi_repo//:ar',
'arm-frc-linux-gnueabi-ar',
],
)
@@ -19,7 +19,7 @@
filegroup(
name = 'as',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:as',
+ '@arm_frc_linux_gnueabi_repo//:as',
'arm-frc-linux-gnueabi-as',
],
)
@@ -27,7 +27,7 @@
filegroup(
name = 'ld',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:ld',
+ '@arm_frc_linux_gnueabi_repo//:ld',
'arm-frc-linux-gnueabi-ld',
],
)
@@ -35,7 +35,7 @@
filegroup(
name = 'nm',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:nm',
+ '@arm_frc_linux_gnueabi_repo//:nm',
'arm-frc-linux-gnueabi-nm',
],
)
@@ -43,7 +43,7 @@
filegroup(
name = 'objcopy',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:objcopy',
+ '@arm_frc_linux_gnueabi_repo//:objcopy',
'arm-frc-linux-gnueabi-objcopy',
],
)
@@ -51,7 +51,7 @@
filegroup(
name = 'objdump',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:objdump',
+ '@arm_frc_linux_gnueabi_repo//:objdump',
'arm-frc-linux-gnueabi-objdump',
],
)
@@ -59,7 +59,7 @@
filegroup(
name = 'strip',
srcs = [
- '@arm-frc-linux-gnueabi-repo//:strip',
+ '@arm_frc_linux_gnueabi_repo//:strip',
'arm-frc-linux-gnueabi-strip',
],
)
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ar b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ar
index 040a122..d70337f 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ar
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ar
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-ar \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-ar" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-ar" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-as b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-as
index 84b49da..5f1a2fc 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-as
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-as
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-as \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-as" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-as" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-cpp b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-cpp
index c04ad23..3262658 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-cpp
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-cpp
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-cpp \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-cpp" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-cpp" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-dwp b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-dwp
index 04bfaa3..dbd074b 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-dwp
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-dwp
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-dwp \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-dwp" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-dwp" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcc b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcc
index 0e306f1..aab008a 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcc
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcc
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-gcc" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-gcc" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcov b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcov
index d220b95..a3c71c3 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcov
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-gcov
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-gcov \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-gcov" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-gcov" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ld b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ld
index db762f3..d5dce71 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ld
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-ld
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-ld \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-ld" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-ld" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-nm b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-nm
index 6348eda..4163be0 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-nm
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-nm
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-nm \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-nm" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-nm" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objcopy b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objcopy
index b126fc7..a77d3a9 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objcopy
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objcopy
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-objcopy \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-objcopy" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-objcopy" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objdump b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objdump
index dacf923..0de0532 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objdump
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-objdump
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-objdump \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-objdump" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-objdump" \
"$@"
diff --git a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-strip b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-strip
index 8469103..15cc2f9 100755
--- a/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-strip
+++ b/tools/cpp/arm-frc-linux-gnueabi/arm-frc-linux-gnueabi-strip
@@ -1,5 +1,5 @@
#!/bin/bash --norc
exec -a arm-frc-linux-gnueabi-strip \
- "${BAZEL_OUTPUT_ROOT}external/arm-frc-linux-gnueabi-repo/usr/bin/arm-frc-linux-gnueabi-strip" \
+ "${BAZEL_OUTPUT_ROOT}external/arm_frc_linux_gnueabi_repo/usr/bin/arm-frc-linux-gnueabi-strip" \
"$@"
diff --git a/y2014/BUILD b/y2014/BUILD
index 6561047..2938aa6 100644
--- a/y2014/BUILD
+++ b/y2014/BUILD
@@ -33,7 +33,7 @@
'//aos/common:time',
'//aos/common/util:log_interval',
'//aos/common/actions:action_lib',
- '//y2014/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
'//frc971/queues:gyro',
'//frc971/autonomous:auto_queue',
'//y2014/control_loops/claw:claw_queue',
diff --git a/y2014/actors/BUILD b/y2014/actors/BUILD
index 6fea9eb..ef94367 100644
--- a/y2014/actors/BUILD
+++ b/y2014/actors/BUILD
@@ -35,7 +35,7 @@
'//aos/common/logging',
'//y2014/control_loops/shooter:shooter_queue',
'//y2014/control_loops/claw:claw_queue',
- '//y2014/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
'//y2014:constants',
],
)
@@ -81,7 +81,7 @@
'//aos/common/logging:queue_logging',
'//third_party/eigen',
'//aos/common/util:trapezoid_profile',
- '//y2014/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
'//frc971/control_loops:state_feedback_loop',
],
)
diff --git a/y2014/actors/drivetrain_actor.cc b/y2014/actors/drivetrain_actor.cc
index 9f94ff4..4cb69ca 100644
--- a/y2014/actors/drivetrain_actor.cc
+++ b/y2014/actors/drivetrain_actor.cc
@@ -13,7 +13,7 @@
#include "y2014/actors/drivetrain_actor.h"
#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
namespace y2014 {
namespace actors {
@@ -50,9 +50,9 @@
while (true) {
::aos::time::PhasedLoopXMS(5, 2500);
- control_loops::drivetrain_queue.status.FetchLatest();
- if (control_loops::drivetrain_queue.status.get()) {
- const auto& status = *control_loops::drivetrain_queue.status;
+ ::frc971::control_loops::drivetrain_queue.status.FetchLatest();
+ if (::frc971::control_loops::drivetrain_queue.status.get()) {
+ const auto& status = *::frc971::control_loops::drivetrain_queue.status;
if (::std::abs(status.uncapped_left_voltage -
status.uncapped_right_voltage) > 24) {
LOG(DEBUG, "spinning in place\n");
@@ -119,7 +119,7 @@
LOG(DEBUG, "Driving left to %f, right to %f\n",
left_goal_state(0, 0) + params.left_initial_position,
right_goal_state(0, 0) + params.right_initial_position);
- control_loops::drivetrain_queue.goal.MakeWithBuilder()
+ ::frc971::control_loops::drivetrain_queue.goal.MakeWithBuilder()
.control_loop_driving(true)
.highgear(true)
.left_goal(left_goal_state(0, 0) + params.left_initial_position)
@@ -129,11 +129,11 @@
.Send();
}
if (ShouldCancel()) return true;
- control_loops::drivetrain_queue.status.FetchLatest();
- while (!control_loops::drivetrain_queue.status.get()) {
+ ::frc971::control_loops::drivetrain_queue.status.FetchLatest();
+ while (!::frc971::control_loops::drivetrain_queue.status.get()) {
LOG(WARNING,
"No previous drivetrain status packet, trying to fetch again\n");
- control_loops::drivetrain_queue.status.FetchNextBlocking();
+ ::frc971::control_loops::drivetrain_queue.status.FetchNextBlocking();
if (ShouldCancel()) return true;
}
while (true) {
@@ -141,13 +141,13 @@
const double kPositionThreshold = 0.05;
const double left_error = ::std::abs(
- control_loops::drivetrain_queue.status->filtered_left_position -
+ ::frc971::control_loops::drivetrain_queue.status->filtered_left_position -
(left_goal_state(0, 0) + params.left_initial_position));
const double right_error = ::std::abs(
- control_loops::drivetrain_queue.status->filtered_right_position -
+ ::frc971::control_loops::drivetrain_queue.status->filtered_right_position -
(right_goal_state(0, 0) + params.right_initial_position));
const double velocity_error =
- ::std::abs(control_loops::drivetrain_queue.status->robot_speed);
+ ::std::abs(::frc971::control_loops::drivetrain_queue.status->robot_speed);
if (left_error < kPositionThreshold && right_error < kPositionThreshold &&
velocity_error < 0.2) {
break;
@@ -155,7 +155,7 @@
LOG(DEBUG, "Drivetrain error is %f, %f, %f\n", left_error, right_error,
velocity_error);
}
- control_loops::drivetrain_queue.status.FetchNextBlocking();
+ ::frc971::control_loops::drivetrain_queue.status.FetchNextBlocking();
}
LOG(INFO, "Done moving\n");
return true;
diff --git a/y2014/actors/shoot_actor.cc b/y2014/actors/shoot_actor.cc
index a70d692..743a4c3 100644
--- a/y2014/actors/shoot_actor.cc
+++ b/y2014/actors/shoot_actor.cc
@@ -7,7 +7,7 @@
#include "y2014/control_loops/shooter/shooter.q.h"
#include "y2014/control_loops/claw/claw.q.h"
#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
namespace y2014 {
namespace actors {
diff --git a/y2014/autonomous/BUILD b/y2014/autonomous/BUILD
index 4a4c842..984b110 100644
--- a/y2014/autonomous/BUILD
+++ b/y2014/autonomous/BUILD
@@ -11,7 +11,7 @@
deps = [
'//frc971/autonomous:auto_queue',
'//aos/common/controls:control_loop',
- '//y2014/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
'//y2014/control_loops/shooter:shooter_queue',
'//y2014/control_loops/claw:claw_queue',
'//y2014:constants',
diff --git a/y2014/autonomous/auto.cc b/y2014/autonomous/auto.cc
index 899d071..e954637 100644
--- a/y2014/autonomous/auto.cc
+++ b/y2014/autonomous/auto.cc
@@ -11,7 +11,7 @@
#include "frc971/autonomous/auto.q.h"
#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#include "y2014/control_loops/shooter/shooter.q.h"
#include "y2014/control_loops/claw/claw.q.h"
#include "y2014/actors/shoot_actor.h"
@@ -41,7 +41,7 @@
void StopDrivetrain() {
LOG(INFO, "Stopping the drivetrain\n");
- control_loops::drivetrain_queue.goal.MakeWithBuilder()
+ frc971::control_loops::drivetrain_queue.goal.MakeWithBuilder()
.control_loop_driving(true)
.highgear(true)
.left_goal(left_initial_position)
@@ -54,7 +54,7 @@
void ResetDrivetrain() {
LOG(INFO, "resetting the drivetrain\n");
- control_loops::drivetrain_queue.goal.MakeWithBuilder()
+ ::frc971::control_loops::drivetrain_queue.goal.MakeWithBuilder()
.control_loop_driving(false)
.highgear(true)
.steering(0.0)
@@ -86,7 +86,7 @@
theta * constants::GetValues().turn_width / 2.0);
double right_goal = (right_initial_position + distance +
theta * constants::GetValues().turn_width / 2.0);
- control_loops::drivetrain_queue.goal.MakeWithBuilder()
+ ::frc971::control_loops::drivetrain_queue.goal.MakeWithBuilder()
.control_loop_driving(true)
.highgear(true)
.left_goal(left_goal)
@@ -159,13 +159,13 @@
void WaitUntilNear(double distance) {
while (true) {
if (ShouldExitAuto()) return;
- control_loops::drivetrain_queue.status.FetchAnother();
+ ::frc971::control_loops::drivetrain_queue.status.FetchAnother();
double left_error = ::std::abs(
left_initial_position -
- control_loops::drivetrain_queue.status->filtered_left_position);
+ ::frc971::control_loops::drivetrain_queue.status->filtered_left_position);
double right_error = ::std::abs(
right_initial_position -
- control_loops::drivetrain_queue.status->filtered_right_position);
+ ::frc971::control_loops::drivetrain_queue.status->filtered_right_position);
const double kPositionThreshold = 0.05 + distance;
if (right_error < kPositionThreshold && left_error < kPositionThreshold) {
LOG(INFO, "At the goal\n");
@@ -211,11 +211,11 @@
}
void InitializeEncoders() {
- control_loops::drivetrain_queue.status.FetchAnother();
+ ::frc971::control_loops::drivetrain_queue.status.FetchAnother();
left_initial_position =
- control_loops::drivetrain_queue.status->filtered_left_position;
+ ::frc971::control_loops::drivetrain_queue.status->filtered_left_position;
right_initial_position =
- control_loops::drivetrain_queue.status->filtered_right_position;
+ ::frc971::control_loops::drivetrain_queue.status->filtered_right_position;
}
void WaitUntilClawDone() {
diff --git a/y2014/control_loops/drivetrain/BUILD b/y2014/control_loops/drivetrain/BUILD
index 54d6581..9d7edb6 100644
--- a/y2014/control_loops/drivetrain/BUILD
+++ b/y2014/control_loops/drivetrain/BUILD
@@ -2,29 +2,6 @@
load('/aos/build/queues', 'queue_library')
-cc_binary(
- name = 'replay_drivetrain',
- srcs = [
- 'replay_drivetrain.cc',
- ],
- deps = [
- ':drivetrain_queue',
- '//aos/common/controls:replay_control_loop',
- '//aos/linux_code:init',
- '//frc971/queues:gyro',
- ],
-)
-
-queue_library(
- name = 'drivetrain_queue',
- srcs = [
- 'drivetrain.q',
- ],
- deps = [
- '//aos/common/controls:control_loop_queues',
- ],
-)
-
genrule(
name = 'genrule_drivetrain',
visibility = ['//visibility:private'],
@@ -73,83 +50,17 @@
)
cc_library(
- name = 'ssdrivetrain',
+ name = 'drivetrain_base',
srcs = [
- 'ssdrivetrain.cc',
+ 'drivetrain_base.cc',
],
hdrs = [
- 'ssdrivetrain.h',
+ 'drivetrain_base.h',
],
deps = [
- ':drivetrain_queue',
+ ':polydrivetrain_plants',
'//y2014:constants',
- '//aos/common/controls:polytope',
- '//aos/common:math',
- '//aos/common/messages:robot_state',
- '//frc971/control_loops:state_feedback_loop',
- '//frc971/control_loops:coerce_goal',
- '//aos/common/util:log_interval',
- '//aos/common/logging:queue_logging',
- '//aos/common/logging:matrix_logging',
- ],
-)
-
-cc_library(
- name = 'polydrivetrain',
- srcs = [
- 'polydrivetrain.cc',
- ],
- hdrs = [
- 'polydrivetrain.h',
- ],
- deps = [
- ':drivetrain_queue',
- '//y2014:constants',
- '//aos/common/controls:polytope',
- '//aos/common:math',
- '//aos/common/messages:robot_state',
- '//frc971/control_loops:state_feedback_loop',
- '//frc971/control_loops:coerce_goal',
- '//aos/common/util:log_interval',
- '//aos/common/logging:queue_logging',
- '//aos/common/logging:matrix_logging',
- ],
-)
-
-cc_library(
- name = 'drivetrain_lib',
- srcs = [
- 'drivetrain.cc',
- ],
- hdrs = [
- 'drivetrain.h',
- ],
- deps = [
- ':drivetrain_queue',
- ':polydrivetrain',
- ':ssdrivetrain',
- '//aos/common/controls:control_loop',
- '//y2014:constants',
- '//frc971/queues:gyro',
- '//aos/common/util:log_interval',
- '//aos/common/logging:queue_logging',
- '//aos/common/logging:matrix_logging',
- ],
-)
-
-cc_test(
- name = 'drivetrain_lib_test',
- srcs = [
- 'drivetrain_lib_test.cc',
- ],
- deps = [
- '//aos/testing:googletest',
- ':drivetrain_queue',
- ':drivetrain_lib',
- '//aos/common/controls:control_loop_test',
- '//frc971/control_loops:state_feedback_loop',
- '//frc971/queues:gyro',
- '//aos/common:queues',
+ '//frc971/control_loops/drivetrain:drivetrain_config',
],
)
@@ -159,8 +70,8 @@
'drivetrain_main.cc',
],
deps = [
+ ':drivetrain_base',
'//aos/linux_code:init',
- ':drivetrain_lib',
- ':drivetrain_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_lib',
],
)
diff --git a/y2014/control_loops/drivetrain/drivetrain.h b/y2014/control_loops/drivetrain/drivetrain.h
deleted file mode 100644
index 489b4ca..0000000
--- a/y2014/control_loops/drivetrain/drivetrain.h
+++ /dev/null
@@ -1,55 +0,0 @@
-#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_H_
-#define Y2014_CONTROL_LOOPS_DRIVETRAIN_H_
-
-#include "Eigen/Dense"
-
-#include "aos/common/controls/polytope.h"
-#include "aos/common/controls/control_loop.h"
-#include "aos/common/controls/polytope.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
-#include "y2014/control_loops/drivetrain/polydrivetrain.h"
-#include "y2014/control_loops/drivetrain/ssdrivetrain.h"
-#include "aos/common/util/log_interval.h"
-
-namespace y2014 {
-namespace control_loops {
-namespace drivetrain {
-
-class DrivetrainLoop : public aos::controls::ControlLoop<
- ::y2014::control_loops::DrivetrainQueue> {
- public:
- // Constructs a control loop which can take a Drivetrain or defaults to the
- // drivetrain at y2014::control_loops::drivetrain
- explicit DrivetrainLoop(
- ::y2014::control_loops::DrivetrainQueue *my_drivetrain =
- &::y2014::control_loops::drivetrain_queue);
-
- protected:
- // Executes one cycle of the control loop.
- virtual void RunIteration(
- const ::y2014::control_loops::DrivetrainQueue::Goal *goal,
- const ::y2014::control_loops::DrivetrainQueue::Position *position,
- ::y2014::control_loops::DrivetrainQueue::Output *output,
- ::y2014::control_loops::DrivetrainQueue::Status *status);
-
- typedef ::aos::util::SimpleLogInterval SimpleLogInterval;
- SimpleLogInterval no_position_ = SimpleLogInterval(
- ::aos::time::Time::InSeconds(0.25), WARNING, "no position");
- double last_gyro_heading_ = 0.0;
- double last_gyro_rate_ = 0.0;
-
- StateFeedbackLoop<7, 2, 3> kf_;
- PolyDrivetrain dt_openloop_;
- DrivetrainMotorsSS dt_closedloop_;
-
- double last_left_voltage_ = 0;
- double last_right_voltage_ = 0;
-
- double integrated_kf_heading_ = 0;
-};
-
-} // namespace drivetrain
-} // namespace control_loops
-} // namespace y2014
-
-#endif // Y2014_CONTROL_LOOPS_DRIVETRAIN_H_
diff --git a/y2014/control_loops/drivetrain/drivetrain_base.cc b/y2014/control_loops/drivetrain/drivetrain_base.cc
new file mode 100644
index 0000000..b4ef447
--- /dev/null
+++ b/y2014/control_loops/drivetrain/drivetrain_base.cc
@@ -0,0 +1,36 @@
+#include "y2014/control_loops/drivetrain/drivetrain_base.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+#include "y2014/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
+#include "y2014/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
+#include "y2014/control_loops/drivetrain/kalman_drivetrain_motor_plant.h"
+#include "y2014/constants.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainConfig;
+
+namespace y2014 {
+namespace control_loops {
+
+const DrivetrainConfig &GetDrivetrainConfig() {
+ static DrivetrainConfig kDrivetrainConfig{
+ ::frc971::control_loops::drivetrain::ShifterType::HALL_EFFECT_SHIFTER,
+
+ ::y2014::control_loops::drivetrain::MakeDrivetrainLoop,
+ ::y2014::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+ ::y2014::control_loops::drivetrain::MakeKFDrivetrainLoop,
+
+ drivetrain::kDt, drivetrain::kStallTorque, drivetrain::kStallCurrent,
+ drivetrain::kFreeSpeedRPM, drivetrain::kFreeCurrent, drivetrain::kJ,
+ drivetrain::kMass, drivetrain::kRobotRadius, drivetrain::kWheelRadius,
+ drivetrain::kR, drivetrain::kV, drivetrain::kT,
+
+ constants::GetValues().turn_width, constants::GetValues().high_gear_ratio,
+ constants::GetValues().low_gear_ratio,
+ constants::GetValues().left_drive, constants::GetValues().right_drive};
+
+ return kDrivetrainConfig;
+};
+
+} // namespace control_loops
+} // namespace y2014
diff --git a/y2014/control_loops/drivetrain/drivetrain_base.h b/y2014/control_loops/drivetrain/drivetrain_base.h
new file mode 100644
index 0000000..3a9d70e
--- /dev/null
+++ b/y2014/control_loops/drivetrain/drivetrain_base.h
@@ -0,0 +1,16 @@
+#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
+#define Y2014_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
+
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainConfig;
+
+namespace y2014 {
+namespace control_loops {
+
+const DrivetrainConfig &GetDrivetrainConfig();
+
+} // namespace control_loops
+} // namespace y2014
+
+#endif // Y2014_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
diff --git a/y2014/control_loops/drivetrain/drivetrain_main.cc b/y2014/control_loops/drivetrain/drivetrain_main.cc
index cc71c69..52dafcc 100644
--- a/y2014/control_loops/drivetrain/drivetrain_main.cc
+++ b/y2014/control_loops/drivetrain/drivetrain_main.cc
@@ -1,10 +1,14 @@
-#include "y2014/control_loops/drivetrain/drivetrain.h"
-
#include "aos/linux_code/init.h"
+#include "y2014/control_loops/drivetrain/drivetrain_base.h"
+#include "frc971/control_loops/drivetrain/drivetrain.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainLoop;
+
int main() {
::aos::Init();
- ::y2014::control_loops::drivetrain::DrivetrainLoop drivetrain;
+ DrivetrainLoop drivetrain =
+ DrivetrainLoop(::y2014::control_loops::GetDrivetrainConfig());
drivetrain.Run();
::aos::Cleanup();
return 0;
diff --git a/y2014/control_loops/drivetrain/polydrivetrain.h b/y2014/control_loops/drivetrain/polydrivetrain.h
deleted file mode 100644
index 5cd7fff..0000000
--- a/y2014/control_loops/drivetrain/polydrivetrain.h
+++ /dev/null
@@ -1,90 +0,0 @@
-#ifndef Y2014_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
-#define Y2014_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
-
-#include "aos/common/controls/polytope.h"
-
-#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
-#include "frc971/control_loops/state_feedback_loop.h"
-#include "y2014/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
-
-namespace y2014 {
-namespace control_loops {
-namespace drivetrain {
-
-class PolyDrivetrain {
- public:
- enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN };
- // Stall Torque in N m
- static constexpr double kStallTorque = drivetrain::kStallTorque;
- // Stall Current in Amps
- static constexpr double kStallCurrent = drivetrain::kStallCurrent;
- // Free Speed in RPM. Used number from last year.
- static constexpr double kFreeSpeed = drivetrain::kFreeSpeedRPM;
- // Free Current in Amps
- static constexpr double kFreeCurrent = drivetrain::kFreeCurrent;
- static constexpr double kWheelRadius = drivetrain::kWheelRadius;
- // Resistance of the motor, divided by the number of motors per side.
- static constexpr double kR = drivetrain::kR;
- // Motor velocity constant
- static constexpr double Kv = drivetrain::kV;
-
- // Torque constant
- static constexpr double Kt = drivetrain::kT;
-
- PolyDrivetrain(StateFeedbackLoop<7, 2, 3> *kf);
-
- int controller_index() const { return loop_->controller_index(); }
-
- static bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
-
- // Computes the speed of the motor given the hall effect position and the
- // speed of the robot.
- static double MotorSpeed(const constants::ShifterHallEffect &hall_effect,
- double shifter_position, double velocity);
-
- // Computes the states of the shifters for the left and right drivetrain sides
- // given a requested state.
- void UpdateGears(Gear requested_gear);
-
- // Computes the next state of a shifter given the current state and the
- // requested state.
- static Gear UpdateSingleGear(Gear requested_gear, Gear current_gear);
-
- void SetGoal(double wheel, double throttle, bool quickturn, bool highgear);
-
- void SetPosition(
- const ::y2014::control_loops::DrivetrainQueue::Position *position);
-
- double FilterVelocity(double throttle);
-
- double MaxVelocity();
-
- void Update();
-
- void SendMotors(::y2014::control_loops::DrivetrainQueue::Output *output);
-
- private:
- StateFeedbackLoop<7, 2, 3> *kf_;
- const ::aos::controls::HPolytope<2> U_Poly_;
-
- ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
-
- const double ttrust_;
- double wheel_;
- double throttle_;
- bool quickturn_;
- int stale_count_;
- double position_time_delta_;
- Gear left_gear_;
- Gear right_gear_;
- ::y2014::control_loops::DrivetrainQueue::Position last_position_;
- ::y2014::control_loops::DrivetrainQueue::Position position_;
- int counter_;
-};
-
-} // namespace drivetrain
-} // namespace control_loops
-} // namespace y2014
-
-#endif // Y2014_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
diff --git a/y2014/control_loops/drivetrain/ssdrivetrain.cc b/y2014/control_loops/drivetrain/ssdrivetrain.cc
deleted file mode 100644
index 45ab4eb..0000000
--- a/y2014/control_loops/drivetrain/ssdrivetrain.cc
+++ /dev/null
@@ -1,187 +0,0 @@
-#include "y2014/control_loops/drivetrain/ssdrivetrain.h"
-
-#include "aos/common/controls/polytope.h"
-#include "aos/common/commonmath.h"
-#include "aos/common/logging/matrix_logging.h"
-
-#include "frc971/control_loops/state_feedback_loop.h"
-#include "frc971/control_loops/coerce_goal.h"
-#include "y2014/constants.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
-
-namespace y2014 {
-namespace control_loops {
-namespace drivetrain {
-
-using ::frc971::control_loops::DoCoerceGoal;
-
-DrivetrainMotorsSS::LimitedDrivetrainLoop::LimitedDrivetrainLoop(
- StateFeedbackLoop<4, 2, 2> &&loop)
- : StateFeedbackLoop<4, 2, 2>(::std::move(loop)),
- U_Poly_((Eigen::Matrix<double, 4, 2>() << 1, 0, -1, 0, 0, 1, 0, -1)
- .finished(),
- (Eigen::Matrix<double, 4, 1>() << 12.0, 12.0, 12.0, 12.0)
- .finished()) {
- ::aos::controls::HPolytope<0>::Init();
- T << 1, -1, 1, 1;
- T_inverse = T.inverse();
-}
-
-void DrivetrainMotorsSS::LimitedDrivetrainLoop::CapU() {
- const Eigen::Matrix<double, 4, 1> error = R() - X_hat();
-
- if (::std::abs(U(0, 0)) > 12.0 || ::std::abs(U(1, 0)) > 12.0) {
- mutable_U() =
- U() * 12.0 / ::std::max(::std::abs(U(0, 0)), ::std::abs(U(1, 0)));
- LOG_MATRIX(DEBUG, "U is now", U());
- // TODO(Austin): Figure out why the polytope stuff wasn't working and
- // remove this hack.
- output_was_capped_ = true;
- return;
-
- LOG_MATRIX(DEBUG, "U at start", U());
- LOG_MATRIX(DEBUG, "R at start", R());
- LOG_MATRIX(DEBUG, "Xhat at start", X_hat());
-
- Eigen::Matrix<double, 2, 2> position_K;
- position_K << K(0, 0), K(0, 2), K(1, 0), K(1, 2);
- Eigen::Matrix<double, 2, 2> velocity_K;
- velocity_K << K(0, 1), K(0, 3), K(1, 1), K(1, 3);
-
- Eigen::Matrix<double, 2, 1> position_error;
- position_error << error(0, 0), error(2, 0);
- const auto drive_error = T_inverse * position_error;
- Eigen::Matrix<double, 2, 1> velocity_error;
- velocity_error << error(1, 0), error(3, 0);
- LOG_MATRIX(DEBUG, "error", error);
-
- const auto &poly = U_Poly_;
- const Eigen::Matrix<double, 4, 2> pos_poly_H = poly.H() * position_K * T;
- const Eigen::Matrix<double, 4, 1> pos_poly_k =
- poly.k() - poly.H() * velocity_K * velocity_error;
- const ::aos::controls::HPolytope<2> pos_poly(pos_poly_H, pos_poly_k);
-
- Eigen::Matrix<double, 2, 1> adjusted_pos_error;
- {
- const auto &P = drive_error;
-
- Eigen::Matrix<double, 1, 2> L45;
- L45 << ::aos::sign(P(1, 0)), -::aos::sign(P(0, 0));
- const double w45 = 0;
-
- Eigen::Matrix<double, 1, 2> LH;
- if (::std::abs(P(0, 0)) > ::std::abs(P(1, 0))) {
- LH << 0, 1;
- } else {
- LH << 1, 0;
- }
- const double wh = LH.dot(P);
-
- Eigen::Matrix<double, 2, 2> standard;
- standard << L45, LH;
- Eigen::Matrix<double, 2, 1> W;
- W << w45, wh;
- const Eigen::Matrix<double, 2, 1> intersection = standard.inverse() * W;
-
- bool is_inside_h;
- const auto adjusted_pos_error_h =
- DoCoerceGoal(pos_poly, LH, wh, drive_error, &is_inside_h);
- const auto adjusted_pos_error_45 =
- DoCoerceGoal(pos_poly, L45, w45, intersection, nullptr);
- if (pos_poly.IsInside(intersection)) {
- adjusted_pos_error = adjusted_pos_error_h;
- } else {
- if (is_inside_h) {
- if (adjusted_pos_error_h.norm() > adjusted_pos_error_45.norm() ||
- adjusted_pos_error_45.norm() > intersection.norm()) {
- adjusted_pos_error = adjusted_pos_error_h;
- } else {
- adjusted_pos_error = adjusted_pos_error_45;
- }
- } else {
- adjusted_pos_error = adjusted_pos_error_45;
- }
- }
- }
-
- LOG_MATRIX(DEBUG, "adjusted_pos_error", adjusted_pos_error);
- mutable_U() =
- velocity_K * velocity_error + position_K * T * adjusted_pos_error;
- LOG_MATRIX(DEBUG, "U is now", U());
- } else {
- output_was_capped_ = false;
- }
-}
-
-DrivetrainMotorsSS::DrivetrainMotorsSS()
- : loop_(new LimitedDrivetrainLoop(
- constants::GetValues().make_drivetrain_loop())),
- filtered_offset_(0.0),
- gyro_(0.0),
- left_goal_(0.0),
- right_goal_(0.0),
- raw_left_(0.0),
- raw_right_(0.0) {
- // High gear on both.
- loop_->set_controller_index(3);
-}
-
-void DrivetrainMotorsSS::SetGoal(double left, double left_velocity,
- double right, double right_velocity) {
- left_goal_ = left;
- right_goal_ = right;
- loop_->mutable_R() << left, left_velocity, right, right_velocity;
-}
-void DrivetrainMotorsSS::SetRawPosition(double left, double right) {
- raw_right_ = right;
- raw_left_ = left;
- Eigen::Matrix<double, 2, 1> Y;
- Y << left + filtered_offset_, right - filtered_offset_;
- loop_->Correct(Y);
-}
-void DrivetrainMotorsSS::SetPosition(double left, double right, double gyro) {
- // Decay the offset quickly because this gyro is great.
- const double offset =
- (right - left - gyro * constants::GetValues().turn_width) / 2.0;
- filtered_offset_ = 0.25 * offset + 0.75 * filtered_offset_;
- gyro_ = gyro;
- SetRawPosition(left, right);
-}
-
-void DrivetrainMotorsSS::SetExternalMotors(double left_voltage,
- double right_voltage) {
- loop_->mutable_U() << left_voltage, right_voltage;
-}
-
-void DrivetrainMotorsSS::Update(bool stop_motors, bool enable_control_loop) {
- if (enable_control_loop) {
- loop_->Update(stop_motors);
- } else {
- if (stop_motors) {
- loop_->mutable_U().setZero();
- loop_->mutable_U_uncapped().setZero();
- }
- loop_->UpdateObserver(loop_->U());
- }
- ::Eigen::Matrix<double, 4, 1> E = loop_->R() - loop_->X_hat();
- LOG_MATRIX(DEBUG, "E", E);
-}
-
-double DrivetrainMotorsSS::GetEstimatedRobotSpeed() const {
- // lets just call the average of left and right velocities close enough
- return (loop_->X_hat(1, 0) + loop_->X_hat(3, 0)) / 2;
-}
-
-void DrivetrainMotorsSS::SendMotors(
- ::y2014::control_loops::DrivetrainQueue::Output *output) const {
- if (output) {
- output->left_voltage = loop_->U(0, 0);
- output->right_voltage = loop_->U(1, 0);
- output->left_high = true;
- output->right_high = true;
- }
-}
-
-} // namespace drivetrain
-} // namespace control_loops
-} // namespace y2014
diff --git a/y2014/joystick_reader.cc b/y2014/joystick_reader.cc
index 87dc3f1..137856f 100644
--- a/y2014/joystick_reader.cc
+++ b/y2014/joystick_reader.cc
@@ -11,7 +11,7 @@
#include "aos/common/time.h"
#include "aos/common/actions/actions.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#include "y2014/constants.h"
#include "frc971/queues/gyro.q.h"
#include "frc971/autonomous/auto.q.h"
@@ -19,7 +19,7 @@
#include "y2014/control_loops/shooter/shooter.q.h"
#include "y2014/actors/shoot_actor.h"
-using ::y2014::control_loops::drivetrain_queue;
+using ::frc971::control_loops::drivetrain_queue;
using ::frc971::sensors::gyro_reading;
using ::aos::input::driver_station::ButtonLocation;
@@ -427,11 +427,11 @@
velocity_compensation_ = 0.0;
}
- control_loops::drivetrain_queue.status.FetchLatest();
+ ::frc971::control_loops::drivetrain_queue.status.FetchLatest();
double goal_angle = goal_angle_;
- if (control_loops::drivetrain_queue.status.get()) {
+ if (::frc971::control_loops::drivetrain_queue.status.get()) {
goal_angle += SpeedToAngleOffset(
- control_loops::drivetrain_queue.status->robot_speed);
+ ::frc971::control_loops::drivetrain_queue.status->robot_speed);
} else {
LOG_INTERVAL(no_drivetrain_status_);
}
diff --git a/y2014/wpilib/BUILD b/y2014/wpilib/BUILD
index 38853ca..120ff49 100644
--- a/y2014/wpilib/BUILD
+++ b/y2014/wpilib/BUILD
@@ -12,7 +12,7 @@
'//aos/externals:wpilib',
'//y2014:constants',
'//y2014/queues:auto_mode',
- '//y2014/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
'//y2014/control_loops/shooter:shooter_queue',
'//y2014/control_loops/claw:claw_queue',
'//aos/common/controls:control_loop',
diff --git a/y2014/wpilib/wpilib_interface.cc b/y2014/wpilib/wpilib_interface.cc
index 13b2e7b..6442a2a 100644
--- a/y2014/wpilib/wpilib_interface.cc
+++ b/y2014/wpilib/wpilib_interface.cc
@@ -32,7 +32,7 @@
#include "frc971/shifter_hall_effect.h"
-#include "y2014/control_loops/drivetrain/drivetrain.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#include "y2014/control_loops/claw/claw.q.h"
#include "y2014/control_loops/shooter/shooter.q.h"
#include "y2014/constants.h"
@@ -54,7 +54,7 @@
#define M_PI 3.14159265358979323846
#endif
-using ::y2014::control_loops::drivetrain_queue;
+using ::frc971::control_loops::drivetrain_queue;
using ::y2014::control_loops::claw_queue;
using ::y2014::control_loops::shooter_queue;
@@ -470,7 +470,7 @@
SolenoidWriter(const ::std::unique_ptr<::frc971::wpilib::BufferedPcm> &pcm)
: pcm_(pcm),
shooter_(".y2014.control_loops.shooter_queue.output"),
- drivetrain_(".y2014.control_loops.drivetrain_queue.output") {}
+ drivetrain_(".frc971.control_loops.drivetrain_queue.output") {}
void set_pressure_switch(::std::unique_ptr<DigitalInput> pressure_switch) {
pressure_switch_ = ::std::move(pressure_switch);
@@ -566,7 +566,7 @@
::std::unique_ptr<Relay> compressor_relay_;
::aos::Queue<::y2014::control_loops::ShooterQueue::Output> shooter_;
- ::aos::Queue<::y2014::control_loops::DrivetrainQueue::Output> drivetrain_;
+ ::aos::Queue<::frc971::control_loops::DrivetrainQueue::Output> drivetrain_;
::std::atomic<bool> run_{true};
};
@@ -583,11 +583,11 @@
private:
virtual void Read() override {
- ::y2014::control_loops::drivetrain_queue.output.FetchAnother();
+ ::frc971::control_loops::drivetrain_queue.output.FetchAnother();
}
virtual void Write() override {
- auto &queue = ::y2014::control_loops::drivetrain_queue.output;
+ auto &queue = ::frc971::control_loops::drivetrain_queue.output;
LOG_STRUCT(DEBUG, "will output", *queue);
left_drivetrain_talon_->Set(-queue->left_voltage / 12.0);
right_drivetrain_talon_->Set(queue->right_voltage / 12.0);
diff --git a/y2016/BUILD b/y2016/BUILD
new file mode 100644
index 0000000..19f30e0
--- /dev/null
+++ b/y2016/BUILD
@@ -0,0 +1,55 @@
+load('/aos/downloader/downloader', 'aos_downloader')
+
+cc_library(
+ name = 'constants',
+ visibility = ['//visibility:public'],
+ srcs = [
+ 'constants.cc',
+ ],
+ hdrs = [
+ 'constants.h',
+ ],
+ deps = [
+ '//aos/common/logging',
+ '//aos/common:once',
+ '//aos/common/network:team_number',
+ '//aos/common:mutex',
+ '//frc971/control_loops:state_feedback_loop',
+ '//frc971:shifter_hall_effect',
+ '//y2016/control_loops/drivetrain:polydrivetrain_plants',
+ ],
+)
+
+cc_binary(
+ name = 'joystick_reader',
+ srcs = [
+ 'joystick_reader.cc',
+ ],
+ deps = [
+ ':constants',
+ '//aos/input:joystick_input',
+ '//aos/linux_code:init',
+ '//aos/common/logging',
+ '//aos/common:time',
+ '//aos/common/util:log_interval',
+ '//aos/common/actions:action_lib',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/queues:gyro',
+ '//frc971/autonomous:auto_queue',
+ ],
+)
+
+aos_downloader(
+ name = 'download',
+ start_srcs = [
+ ':joystick_reader',
+ '//aos:prime_start_binaries',
+ '//y2016/control_loops/drivetrain:drivetrain',
+ '//y2016/autonomous:auto',
+ '//y2016/actors:binaries',
+ '//y2016/wpilib:wpilib_interface',
+ ],
+ srcs = [
+ '//aos:prime_binaries',
+ ],
+)
diff --git a/y2016/actors/BUILD b/y2016/actors/BUILD
new file mode 100644
index 0000000..e3de5fb
--- /dev/null
+++ b/y2016/actors/BUILD
@@ -0,0 +1,96 @@
+package(default_visibility = ['//visibility:public'])
+
+load('/aos/build/queues', 'queue_library')
+
+filegroup(
+ name = 'binaries',
+ srcs = [
+ ':drivetrain_action',
+ ':superstructure_action',
+ ],
+)
+
+queue_library(
+ name = 'drivetrain_action_queue',
+ srcs = [
+ 'drivetrain_action.q',
+ ],
+ deps = [
+ '//aos/common/actions:action_queue',
+ ],
+)
+
+cc_library(
+ name = 'drivetrain_action_lib',
+ srcs = [
+ 'drivetrain_actor.cc',
+ ],
+ hdrs = [
+ 'drivetrain_actor.h',
+ ],
+ deps = [
+ ':drivetrain_action_queue',
+ '//aos/common:time',
+ '//aos/common:math',
+ '//aos/common/util:phased_loop',
+ '//aos/common/logging',
+ '//aos/common/actions:action_lib',
+ '//aos/common/logging:queue_logging',
+ '//aos/common/util:trapezoid_profile',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/control_loops:state_feedback_loop',
+ '//third_party/eigen',
+ '//y2016:constants',
+ ],
+)
+
+cc_binary(
+ name = 'drivetrain_action',
+ srcs = [
+ 'drivetrain_actor_main.cc',
+ ],
+ deps = [
+ ':drivetrain_action_lib',
+ ':drivetrain_action_queue',
+ '//aos/linux_code:init',
+ ],
+)
+
+queue_library(
+ name = 'superstructure_action_queue',
+ srcs = [
+ 'superstructure_action.q',
+ ],
+ deps = [
+ '//aos/common/actions:action_queue',
+ ],
+)
+
+cc_library(
+ name = 'superstructure_action_lib',
+ srcs = [
+ 'superstructure_actor.cc',
+ ],
+ hdrs = [
+ 'superstructure_actor.h',
+ ],
+ deps = [
+ ':superstructure_action_queue',
+ '//aos/common/util:phased_loop',
+ '//aos/common/logging',
+ '//aos/common/actions:action_lib',
+ '//y2016/control_loops/superstructure:superstructure_queue',
+ ],
+)
+
+cc_binary(
+ name = 'superstructure_action',
+ srcs = [
+ 'superstructure_actor_main.cc',
+ ],
+ deps = [
+ ':superstructure_action_lib',
+ ':superstructure_action_queue',
+ '//aos/linux_code:init',
+ ],
+)
diff --git a/y2016/actors/drivetrain_action.q b/y2016/actors/drivetrain_action.q
new file mode 100644
index 0000000..9bbebb2
--- /dev/null
+++ b/y2016/actors/drivetrain_action.q
@@ -0,0 +1,29 @@
+package y2016.actors;
+
+import "aos/common/actions/actions.q";
+
+// Parameters to send with start.
+struct DrivetrainActionParams {
+ double left_initial_position;
+ double right_initial_position;
+ double y_offset;
+ double theta_offset;
+ double maximum_velocity;
+ double maximum_acceleration;
+ double maximum_turn_velocity;
+ double maximum_turn_acceleration;
+};
+
+queue_group DrivetrainActionQueueGroup {
+ implements aos.common.actions.ActionQueueGroup;
+
+ message Goal {
+ uint32_t run;
+ DrivetrainActionParams params;
+ };
+
+ queue Goal goal;
+ queue aos.common.actions.Status status;
+};
+
+queue_group DrivetrainActionQueueGroup drivetrain_action;
diff --git a/y2016/actors/drivetrain_actor.cc b/y2016/actors/drivetrain_actor.cc
new file mode 100644
index 0000000..2276108
--- /dev/null
+++ b/y2016/actors/drivetrain_actor.cc
@@ -0,0 +1,181 @@
+#include "y2016/actors/drivetrain_actor.h"
+
+#include <functional>
+#include <numeric>
+
+#include <Eigen/Dense>
+
+#include "aos/common/util/phased_loop.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/util/trapezoid_profile.h"
+#include "aos/common/commonmath.h"
+#include "aos/common/time.h"
+
+#include "y2016/actors/drivetrain_actor.h"
+#include "y2016/constants.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+
+namespace y2016 {
+namespace actors {
+
+DrivetrainActor::DrivetrainActor(actors::DrivetrainActionQueueGroup *s)
+ : aos::common::actions::ActorBase<actors::DrivetrainActionQueueGroup>(s),
+ loop_(constants::GetValues().make_drivetrain_loop()) {
+ loop_.set_controller_index(3);
+}
+
+bool DrivetrainActor::RunAction(const actors::DrivetrainActionParams ¶ms) {
+ static const auto K = loop_.K();
+
+ const double yoffset = params.y_offset;
+ const double turn_offset =
+ params.theta_offset * constants::GetValues().turn_width / 2.0;
+ LOG(INFO, "Going to move %f and turn %f\n", yoffset, turn_offset);
+
+ // Measured conversion to get the distance right.
+ ::aos::util::TrapezoidProfile profile(::aos::time::Time::InMS(5));
+ ::aos::util::TrapezoidProfile turn_profile(::aos::time::Time::InMS(5));
+ const double goal_velocity = 0.0;
+ const double epsilon = 0.01;
+ ::Eigen::Matrix<double, 2, 1> left_goal_state, right_goal_state;
+
+ profile.set_maximum_acceleration(params.maximum_acceleration);
+ profile.set_maximum_velocity(params.maximum_velocity);
+ turn_profile.set_maximum_acceleration(params.maximum_turn_acceleration *
+ constants::GetValues().turn_width /
+ 2.0);
+ turn_profile.set_maximum_velocity(params.maximum_turn_velocity *
+ constants::GetValues().turn_width / 2.0);
+
+ while (true) {
+ ::aos::time::PhasedLoopXMS(5, 2500);
+
+ ::frc971::control_loops::drivetrain_queue.status.FetchLatest();
+ if (::frc971::control_loops::drivetrain_queue.status.get()) {
+ const auto &status = *::frc971::control_loops::drivetrain_queue.status;
+ if (::std::abs(status.uncapped_left_voltage -
+ status.uncapped_right_voltage) > 24) {
+ LOG(DEBUG, "spinning in place\n");
+ // They're more than 24V apart, so stop moving forwards and let it deal
+ // with spinning first.
+ profile.SetGoal(
+ (status.filtered_left_position + status.filtered_right_position -
+ params.left_initial_position - params.right_initial_position) /
+ 2.0);
+ } else {
+ static const double divisor = K(0, 0) + K(0, 2);
+ double dx_left, dx_right;
+
+ if (status.uncapped_left_voltage > 12.0) {
+ dx_left = (status.uncapped_left_voltage - 12.0) / divisor;
+ } else if (status.uncapped_left_voltage < -12.0) {
+ dx_left = (status.uncapped_left_voltage + 12.0) / divisor;
+ } else {
+ dx_left = 0;
+ }
+
+ if (status.uncapped_right_voltage > 12.0) {
+ dx_right = (status.uncapped_right_voltage - 12.0) / divisor;
+ } else if (status.uncapped_right_voltage < -12.0) {
+ dx_right = (status.uncapped_right_voltage + 12.0) / divisor;
+ } else {
+ dx_right = 0;
+ }
+
+ double dx;
+
+ if (dx_left == 0 && dx_right == 0) {
+ dx = 0;
+ } else if (dx_left != 0 && dx_right != 0 &&
+ ::aos::sign(dx_left) != ::aos::sign(dx_right)) {
+ // Both saturating in opposite directions. Don't do anything.
+ LOG(DEBUG, "Saturating opposite ways, not adjusting\n");
+ dx = 0;
+ } else if (::std::abs(dx_left) > ::std::abs(dx_right)) {
+ dx = dx_left;
+ } else {
+ dx = dx_right;
+ }
+
+ if (dx != 0) {
+ LOG(DEBUG, "adjusting goal by %f\n", dx);
+ profile.MoveGoal(-dx);
+ }
+ }
+ } else {
+ // If we ever get here, that's bad and we should just give up
+ LOG(ERROR, "no drivetrain status!\n");
+ return false;
+ }
+
+ const auto drive_profile_goal_state =
+ profile.Update(yoffset, goal_velocity);
+ const auto turn_profile_goal_state = turn_profile.Update(turn_offset, 0.0);
+ left_goal_state = drive_profile_goal_state - turn_profile_goal_state;
+ right_goal_state = drive_profile_goal_state + turn_profile_goal_state;
+
+ if (::std::abs(drive_profile_goal_state(0, 0) - yoffset) < epsilon &&
+ ::std::abs(turn_profile_goal_state(0, 0) - turn_offset) < epsilon) {
+ break;
+ }
+
+ if (ShouldCancel()) return true;
+
+ LOG(DEBUG, "Driving left to %f, right to %f\n",
+ left_goal_state(0, 0) + params.left_initial_position,
+ right_goal_state(0, 0) + params.right_initial_position);
+ ::frc971::control_loops::drivetrain_queue.goal.MakeWithBuilder()
+ .control_loop_driving(true)
+ .highgear(true)
+ .left_goal(left_goal_state(0, 0) + params.left_initial_position)
+ .right_goal(right_goal_state(0, 0) + params.right_initial_position)
+ .left_velocity_goal(left_goal_state(1, 0))
+ .right_velocity_goal(right_goal_state(1, 0))
+ .Send();
+ }
+ if (ShouldCancel()) return true;
+ ::frc971::control_loops::drivetrain_queue.status.FetchLatest();
+
+ while (!::frc971::control_loops::drivetrain_queue.status.get()) {
+ LOG(WARNING,
+ "No previous drivetrain status packet, trying to fetch again\n");
+ ::frc971::control_loops::drivetrain_queue.status.FetchNextBlocking();
+ if (ShouldCancel()) return true;
+ }
+
+ while (true) {
+ if (ShouldCancel()) return true;
+ const double kPositionThreshold = 0.05;
+
+ const double left_error =
+ ::std::abs(::frc971::control_loops::drivetrain_queue.status
+ ->filtered_left_position -
+ (left_goal_state(0, 0) + params.left_initial_position));
+ const double right_error =
+ ::std::abs(::frc971::control_loops::drivetrain_queue.status
+ ->filtered_right_position -
+ (right_goal_state(0, 0) + params.right_initial_position));
+ const double velocity_error = ::std::abs(
+ ::frc971::control_loops::drivetrain_queue.status->robot_speed);
+ if (left_error < kPositionThreshold && right_error < kPositionThreshold &&
+ velocity_error < 0.2) {
+ break;
+ } else {
+ LOG(DEBUG, "Drivetrain error is %f, %f, %f\n", left_error, right_error,
+ velocity_error);
+ }
+ ::frc971::control_loops::drivetrain_queue.status.FetchNextBlocking();
+ }
+
+ LOG(INFO, "Done moving\n");
+ return true;
+}
+
+::std::unique_ptr<DrivetrainAction> MakeDrivetrainAction(
+ const ::y2016::actors::DrivetrainActionParams ¶ms) {
+ return ::std::unique_ptr<DrivetrainAction>(
+ new DrivetrainAction(&::y2016::actors::drivetrain_action, params));
+}
+
+} // namespace actors
+} // namespace y2016
diff --git a/y2016/actors/drivetrain_actor.h b/y2016/actors/drivetrain_actor.h
new file mode 100644
index 0000000..0ab3bf2
--- /dev/null
+++ b/y2016/actors/drivetrain_actor.h
@@ -0,0 +1,36 @@
+#ifndef Y2016_ACTORS_DRIVETRAIN_ACTOR_H_
+#define Y2016_ACTORS_DRIVETRAIN_ACTOR_H_
+
+#include <memory>
+
+#include "aos/common/actions/actor.h"
+#include "aos/common/actions/actions.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+#include "y2016/actors/drivetrain_action.q.h"
+
+namespace y2016 {
+namespace actors {
+
+class DrivetrainActor
+ : public ::aos::common::actions::ActorBase<DrivetrainActionQueueGroup> {
+ public:
+ explicit DrivetrainActor(DrivetrainActionQueueGroup *s);
+
+ bool RunAction(const actors::DrivetrainActionParams ¶ms) override;
+
+ private:
+ StateFeedbackLoop<4, 2, 2> loop_;
+};
+
+typedef ::aos::common::actions::TypedAction<DrivetrainActionQueueGroup>
+ DrivetrainAction;
+
+// Makes a new DrivetrainActor action.
+::std::unique_ptr<DrivetrainAction> MakeDrivetrainAction(
+ const ::y2016::actors::DrivetrainActionParams ¶ms);
+
+} // namespace actors
+} // namespace y2016
+
+#endif
diff --git a/y2016/actors/drivetrain_actor_main.cc b/y2016/actors/drivetrain_actor_main.cc
new file mode 100644
index 0000000..0fe9e71
--- /dev/null
+++ b/y2016/actors/drivetrain_actor_main.cc
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+#include "aos/linux_code/init.h"
+#include "y2016/actors/drivetrain_action.q.h"
+#include "y2016/actors/drivetrain_actor.h"
+
+using ::aos::time::Time;
+
+int main(int /*argc*/, char* /*argv*/ []) {
+ ::aos::Init(-1);
+
+ ::y2016::actors::DrivetrainActor drivetrain(
+ &::y2016::actors::drivetrain_action);
+ drivetrain.Run();
+
+ ::aos::Cleanup();
+ return 0;
+}
diff --git a/y2016/actors/superstructure_action.q b/y2016/actors/superstructure_action.q
new file mode 100644
index 0000000..72bd310
--- /dev/null
+++ b/y2016/actors/superstructure_action.q
@@ -0,0 +1,22 @@
+package y2016.actors;
+
+import "aos/common/actions/actions.q";
+
+// Parameters to send with start.
+struct SuperstructureActionParams {
+ double value;
+};
+
+queue_group SuperstructureActionQueueGroup {
+ implements aos.common.actions.ActionQueueGroup;
+
+ message Goal {
+ uint32_t run;
+ SuperstructureActionParams params;
+ };
+
+ queue Goal goal;
+ queue aos.common.actions.Status status;
+};
+
+queue_group SuperstructureActionQueueGroup superstructure_action;
diff --git a/y2016/actors/superstructure_actor.cc b/y2016/actors/superstructure_actor.cc
new file mode 100644
index 0000000..b8ad33a
--- /dev/null
+++ b/y2016/actors/superstructure_actor.cc
@@ -0,0 +1,37 @@
+#include "y2016/actors/superstructure_actor.h"
+
+#include "aos/common/util/phased_loop.h"
+#include "aos/common/logging/logging.h"
+#include "y2016/actors/superstructure_actor.h"
+#include "y2016/control_loops/superstructure/superstructure.q.h"
+
+namespace y2016 {
+namespace actors {
+
+SuperstructureActor::SuperstructureActor(
+ actors::SuperstructureActionQueueGroup* s)
+ : aos::common::actions::ActorBase<actors::SuperstructureActionQueueGroup>(
+ s) {}
+
+bool SuperstructureActor::RunAction(
+ const actors::SuperstructureActionParams& params) {
+ LOG(INFO, "Starting superstructure action with value %f", params.value);
+
+ while (true) {
+ control_loops::superstructure_queue.status.FetchLatest();
+ ::aos::time::PhasedLoop phased_loop(::aos::time::Time::InMS(5),
+ ::aos::time::Time::InMS(5) / 2);
+ break;
+ }
+
+ return true;
+}
+
+::std::unique_ptr<SuperstructureAction> MakeSuperstructureAction(
+ const ::y2016::actors::SuperstructureActionParams& params) {
+ return ::std::unique_ptr<SuperstructureAction>(new SuperstructureAction(
+ &::y2016::actors::superstructure_action, params));
+}
+
+} // namespace actors
+} // namespace y2016
diff --git a/y2016/actors/superstructure_actor.h b/y2016/actors/superstructure_actor.h
new file mode 100644
index 0000000..b882585
--- /dev/null
+++ b/y2016/actors/superstructure_actor.h
@@ -0,0 +1,31 @@
+#ifndef Y2016_ACTORS_SUPERSTRUCTURE_ACTOR_H_
+#define Y2016_ACTORS_SUPERSTRUCTURE_ACTOR_H_
+
+#include <memory>
+
+#include "aos/common/actions/actor.h"
+#include "aos/common/actions/actions.h"
+#include "y2016/actors/superstructure_action.q.h"
+
+namespace y2016 {
+namespace actors {
+
+class SuperstructureActor
+ : public ::aos::common::actions::ActorBase<SuperstructureActionQueueGroup> {
+ public:
+ explicit SuperstructureActor(SuperstructureActionQueueGroup* s);
+
+ bool RunAction(const actors::SuperstructureActionParams& params) override;
+};
+
+using SuperstructureAction =
+ ::aos::common::actions::TypedAction<SuperstructureActionQueueGroup>;
+
+// Makes a new SuperstructureActor action.
+::std::unique_ptr<SuperstructureAction> MakeSuperstructureAction(
+ const ::y2016::actors::SuperstructureActionParams& params);
+
+} // namespace actors
+} // namespace y2016
+
+#endif // Y2016_ACTORS_SUPERSTRUCTURE_ACTOR_H_
diff --git a/y2016/actors/superstructure_actor_main.cc b/y2016/actors/superstructure_actor_main.cc
new file mode 100644
index 0000000..a6da2a2
--- /dev/null
+++ b/y2016/actors/superstructure_actor_main.cc
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+#include "aos/linux_code/init.h"
+#include "y2016/actors/superstructure_action.q.h"
+#include "y2016/actors/superstructure_actor.h"
+
+using ::aos::time::Time;
+
+int main(int /*argc*/, char* /*argv*/ []) {
+ ::aos::Init(-1);
+
+ ::y2016::actors::SuperstructureActor superstructure(
+ &::y2016::actors::superstructure_action);
+ superstructure.Run();
+
+ ::aos::Cleanup();
+ return 0;
+}
diff --git a/y2016/autonomous/BUILD b/y2016/autonomous/BUILD
new file mode 100644
index 0000000..3cda768
--- /dev/null
+++ b/y2016/autonomous/BUILD
@@ -0,0 +1,37 @@
+package(default_visibility = ['//visibility:public'])
+
+cc_library(
+ name = 'auto_lib',
+ srcs = [
+ 'auto.cc',
+ ],
+ hdrs = [
+ 'auto.h',
+ ],
+ deps = [
+ '//aos/common/actions:action_lib',
+ '//aos/common/controls:control_loop',
+ '//aos/common/logging',
+ '//aos/common/logging:queue_logging',
+ '//aos/common:time',
+ '//aos/common/util:phased_loop',
+ '//aos/common/util:trapezoid_profile',
+ '//frc971/autonomous:auto_queue',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
+ '//y2016:constants',
+ '//y2016/queues:profile_params',
+ '//y2016/actors:drivetrain_action_lib',
+ ],
+)
+
+cc_binary(
+ name = 'auto',
+ srcs = [
+ 'auto_main.cc',
+ ],
+ deps = [
+ ':auto_lib',
+ '//aos/linux_code:init',
+ '//frc971/autonomous:auto_queue',
+ ],
+)
diff --git a/y2016/autonomous/auto.cc b/y2016/autonomous/auto.cc
new file mode 100644
index 0000000..ad211cf
--- /dev/null
+++ b/y2016/autonomous/auto.cc
@@ -0,0 +1,110 @@
+#include "y2016/autonomous/auto.h"
+
+#include <stdio.h>
+
+#include <memory>
+
+#include "aos/common/actions/actions.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/logging/queue_logging.h"
+#include "aos/common/time.h"
+#include "aos/common/util/phased_loop.h"
+#include "aos/common/util/trapezoid_profile.h"
+
+#include "frc971/autonomous/auto.q.h"
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "y2016/actors/drivetrain_actor.h"
+#include "y2016/constants.h"
+#include "y2016/queues/profile_params.q.h"
+
+using ::aos::time::Time;
+
+namespace y2016 {
+namespace autonomous {
+
+namespace time = ::aos::time;
+
+static double left_initial_position, right_initial_position;
+
+bool ShouldExitAuto() {
+ ::frc971::autonomous::autonomous.FetchLatest();
+ bool ans = !::frc971::autonomous::autonomous->run_auto;
+ if (ans) {
+ LOG(INFO, "Time to exit auto mode\n");
+ }
+ return ans;
+}
+
+void ResetDrivetrain() {
+ LOG(INFO, "resetting the drivetrain\n");
+ ::frc971::control_loops::drivetrain_queue.goal.MakeWithBuilder()
+ .control_loop_driving(false)
+ .highgear(true)
+ .steering(0.0)
+ .throttle(0.0)
+ .left_goal(left_initial_position)
+ .left_velocity_goal(0)
+ .right_goal(right_initial_position)
+ .right_velocity_goal(0)
+ .Send();
+}
+
+void WaitUntilDoneOrCanceled(
+ ::std::unique_ptr<aos::common::actions::Action> action) {
+ if (!action) {
+ LOG(ERROR, "No action, not waiting\n");
+ return;
+ }
+ while (true) {
+ // Poll the running bit and auto done bits.
+ ::aos::time::PhasedLoopXMS(10, 5000);
+ if (!action->Running() || ShouldExitAuto()) {
+ return;
+ }
+ }
+}
+
+const ProfileParams kFastDrive = {3.0, 2.5};
+const ProfileParams kSlowDrive = {2.5, 2.5};
+const ProfileParams kFastTurn = {3.0, 10.0};
+
+::std::unique_ptr<::y2016::actors::DrivetrainAction> SetDriveGoal(
+ double distance, const ProfileParams drive_params, double theta = 0,
+ const ProfileParams &turn_params = kFastTurn) {
+ LOG(INFO, "Driving to %f\n", distance);
+
+ ::y2016::actors::DrivetrainActionParams params;
+ params.left_initial_position = left_initial_position;
+ params.right_initial_position = right_initial_position;
+ params.y_offset = distance;
+ params.theta_offset = theta;
+ params.maximum_turn_acceleration = turn_params.acceleration;
+ params.maximum_turn_velocity = turn_params.velocity;
+ params.maximum_velocity = drive_params.velocity;
+ params.maximum_acceleration = drive_params.acceleration;
+ auto drivetrain_action = actors::MakeDrivetrainAction(params);
+ drivetrain_action->Start();
+ left_initial_position +=
+ distance - theta * constants::GetValues().turn_width / 2.0;
+ right_initial_position +=
+ distance + theta * constants::GetValues().turn_width / 2.0;
+ return ::std::move(drivetrain_action);
+}
+
+void InitializeEncoders() {
+ ::frc971::control_loops::drivetrain_queue.status.FetchAnother();
+ left_initial_position =
+ ::frc971::control_loops::drivetrain_queue.status->filtered_left_position;
+ right_initial_position =
+ ::frc971::control_loops::drivetrain_queue.status->filtered_right_position;
+}
+
+void HandleAuto() {
+ LOG(INFO, "Handling auto mode\n");
+
+ ResetDrivetrain();
+ InitializeEncoders();
+}
+
+} // namespace autonomous
+} // namespace y2016
diff --git a/y2016/autonomous/auto.h b/y2016/autonomous/auto.h
new file mode 100644
index 0000000..e5ab422
--- /dev/null
+++ b/y2016/autonomous/auto.h
@@ -0,0 +1,12 @@
+#ifndef Y2016_AUTONOMOUS_AUTO_H_
+#define Y2016_AUTONOMOUS_AUTO_H_
+
+namespace y2016 {
+namespace autonomous {
+
+void HandleAuto();
+
+} // namespace autonomous
+} // namespace y2016
+
+#endif // Y2016_AUTONOMOUS_AUTO_H_
diff --git a/y2016/autonomous/auto_main.cc b/y2016/autonomous/auto_main.cc
new file mode 100644
index 0000000..adf1bca
--- /dev/null
+++ b/y2016/autonomous/auto_main.cc
@@ -0,0 +1,46 @@
+#include <stdio.h>
+
+#include "aos/common/time.h"
+#include "aos/linux_code/init.h"
+#include "aos/common/logging/logging.h"
+#include "frc971/autonomous/auto.q.h"
+#include "y2016/autonomous/auto.h"
+
+using ::aos::time::Time;
+
+int main(int /*argc*/, char * /*argv*/ []) {
+ ::aos::Init(-1);
+
+ LOG(INFO, "Auto main started\n");
+ ::frc971::autonomous::autonomous.FetchLatest();
+
+ while (!::frc971::autonomous::autonomous.get()) {
+ ::frc971::autonomous::autonomous.FetchNextBlocking();
+ LOG(INFO, "Got another auto packet\n");
+ }
+
+ while (true) {
+ while (!::frc971::autonomous::autonomous->run_auto) {
+ ::frc971::autonomous::autonomous.FetchNextBlocking();
+ LOG(INFO, "Got another auto packet\n");
+ }
+
+ LOG(INFO, "Starting auto mode\n");
+ ::aos::time::Time start_time = ::aos::time::Time::Now();
+ ::y2016::autonomous::HandleAuto();
+
+ ::aos::time::Time elapsed_time = ::aos::time::Time::Now() - start_time;
+ LOG(INFO, "Auto mode exited in %f, waiting for it to finish.\n",
+ elapsed_time.ToSeconds());
+
+ while (::frc971::autonomous::autonomous->run_auto) {
+ ::frc971::autonomous::autonomous.FetchNextBlocking();
+ LOG(INFO, "Got another auto packet\n");
+ }
+
+ LOG(INFO, "Waiting for auto to start back up.\n");
+ }
+
+ ::aos::Cleanup();
+ return 0;
+}
diff --git a/y2016/constants.cc b/y2016/constants.cc
new file mode 100644
index 0000000..52285f7
--- /dev/null
+++ b/y2016/constants.cc
@@ -0,0 +1,130 @@
+#include "y2016/constants.h"
+
+#include <math.h>
+#include <stdint.h>
+#include <inttypes.h>
+
+#include <map>
+
+#if __has_feature(address_sanitizer)
+#include "sanitizer/lsan_interface.h"
+#endif
+
+#include "aos/common/logging/logging.h"
+#include "aos/common/once.h"
+#include "aos/common/network/team_number.h"
+#include "aos/common/mutex.h"
+
+#include "y2016/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
+#include "y2016/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+namespace y2016 {
+namespace constants {
+namespace {
+
+const uint16_t kCompTeamNumber = 971;
+const uint16_t kPracticeTeamNumber = 9971;
+
+// TODO(constants): Update these to what we're using this year.
+const double kCompDrivetrainEncoderRatio =
+ (18.0 / 50.0) /*output reduction*/ * (56.0 / 30.0) /*encoder gears*/;
+const double kCompLowGearRatio = 18.0 / 60.0 * 18.0 / 50.0;
+const double kCompHighGearRatio = 28.0 / 50.0 * 18.0 / 50.0;
+
+const double kPracticeDrivetrainEncoderRatio = kCompDrivetrainEncoderRatio;
+const double kPracticeLowGearRatio = kCompLowGearRatio;
+const double kPracticeHighGearRatio = kCompHighGearRatio;
+
+const ShifterHallEffect kCompLeftDriveShifter{2.61, 2.33, 4.25, 3.28, 0.2, 0.7};
+const ShifterHallEffect kCompRightDriveShifter{2.94, 4.31, 4.32,
+ 3.25, 0.2, 0.7};
+
+const ShifterHallEffect kPracticeLeftDriveShifter{2.80, 3.05, 4.15,
+ 3.2, 0.2, 0.7};
+const ShifterHallEffect kPracticeRightDriveShifter{2.90, 3.75, 3.80,
+ 2.98, 0.2, 0.7};
+
+const double kRobotWidth = 25.0 / 100.0 * 2.54;
+
+const Values *DoGetValuesForTeam(uint16_t team) {
+ switch (team) {
+ case 1: // for tests
+ return new Values{
+ kCompDrivetrainEncoderRatio,
+ kCompLowGearRatio,
+ kCompHighGearRatio,
+ kCompLeftDriveShifter,
+ kCompRightDriveShifter,
+ 0.5,
+ ::y2016::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+ ::y2016::control_loops::drivetrain::MakeDrivetrainLoop,
+ 5.0, // drivetrain max speed
+ };
+ break;
+ case kCompTeamNumber:
+ return new Values{
+ kCompDrivetrainEncoderRatio,
+ kCompLowGearRatio,
+ kCompHighGearRatio,
+ kCompLeftDriveShifter,
+ kCompRightDriveShifter,
+ kRobotWidth,
+ ::y2016::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+ ::y2016::control_loops::drivetrain::MakeDrivetrainLoop,
+ 5.0, // drivetrain max speed
+ };
+ break;
+ case kPracticeTeamNumber:
+ return new Values{
+ kPracticeDrivetrainEncoderRatio,
+ kPracticeLowGearRatio,
+ kPracticeHighGearRatio,
+ kPracticeLeftDriveShifter,
+ kPracticeRightDriveShifter,
+ kRobotWidth,
+ ::y2016::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+ ::y2016::control_loops::drivetrain::MakeDrivetrainLoop,
+ 5.0, // drivetrain max speed
+ };
+ break;
+ default:
+ LOG(FATAL, "unknown team #%" PRIu16 "\n", team);
+ }
+}
+
+const Values *DoGetValues() {
+ uint16_t team = ::aos::network::GetTeamNumber();
+ LOG(INFO, "creating a Constants for team %" PRIu16 "\n", team);
+ return DoGetValuesForTeam(team);
+}
+
+} // namespace
+
+const Values &GetValues() {
+ static ::aos::Once<const Values> once(DoGetValues);
+ return *once.Get();
+}
+
+const Values &GetValuesForTeam(uint16_t team_number) {
+ static ::aos::Mutex mutex;
+ ::aos::MutexLocker locker(&mutex);
+
+ // IMPORTANT: This declaration has to stay after the mutex is locked to avoid
+ // race conditions.
+ static ::std::map<uint16_t, const Values *> values;
+
+ if (values.count(team_number) == 0) {
+ values[team_number] = DoGetValuesForTeam(team_number);
+#if __has_feature(address_sanitizer)
+ __lsan_ignore_object(values[team_number]);
+#endif
+ }
+ return *values[team_number];
+}
+
+} // namespace constants
+} // namespace y2016
diff --git a/y2016/constants.h b/y2016/constants.h
new file mode 100644
index 0000000..5f55938
--- /dev/null
+++ b/y2016/constants.h
@@ -0,0 +1,51 @@
+#ifndef Y2016_CONSTANTS_H_
+#define Y2016_CONSTANTS_H_
+
+#include <stdint.h>
+
+#include "frc971/shifter_hall_effect.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+namespace y2016 {
+namespace constants {
+
+using ::frc971::constants::ShifterHallEffect;
+
+// Has all of the numbers that change for both robots and makes it easy to
+// retrieve the values for the current one.
+
+// Everything is in SI units (volts, radians, meters, seconds, etc).
+// Some of these values are related to the conversion between raw values
+// (encoder counts, voltage, etc) to scaled units (radians, meters, etc).
+
+// This structure contains current values for all of the things that change.
+struct Values {
+ // The ratio from the encoder shaft to the drivetrain wheels.
+ double drivetrain_encoder_ratio;
+
+ // The gear ratios from motor shafts to the drivetrain wheels for high and low
+ // gear.
+ double low_gear_ratio;
+ double high_gear_ratio;
+ ShifterHallEffect left_drive, right_drive;
+
+ double turn_width;
+
+ ::std::function<StateFeedbackLoop<2, 2, 2>()> make_v_drivetrain_loop;
+ ::std::function<StateFeedbackLoop<4, 2, 2>()> make_drivetrain_loop;
+
+ double drivetrain_max_speed;
+};
+
+// Creates (once) a Values instance for ::aos::network::GetTeamNumber() and
+// returns a reference to it.
+const Values &GetValues();
+
+// Creates Values instances for each team number it is called with and returns
+// them.
+const Values &GetValuesForTeam(uint16_t team_number);
+
+} // namespace constants
+} // namespace y2016
+
+#endif // Y2016_CONSTANTS_H_
diff --git a/y2016/control_loops/drivetrain/BUILD b/y2016/control_loops/drivetrain/BUILD
new file mode 100644
index 0000000..1150426
--- /dev/null
+++ b/y2016/control_loops/drivetrain/BUILD
@@ -0,0 +1,77 @@
+package(default_visibility = ['//visibility:public'])
+
+load('/aos/build/queues', 'queue_library')
+
+genrule(
+ name = 'genrule_drivetrain',
+ visibility = ['//visibility:private'],
+ cmd = '$(location //y2016/control_loops/python:drivetrain) $(OUTS)',
+ tools = [
+ '//y2016/control_loops/python:drivetrain',
+ ],
+ outs = [
+ 'drivetrain_dog_motor_plant.h',
+ 'drivetrain_dog_motor_plant.cc',
+ 'kalman_drivetrain_motor_plant.h',
+ 'kalman_drivetrain_motor_plant.cc',
+ ],
+)
+
+genrule(
+ name = 'genrule_polydrivetrain',
+ visibility = ['//visibility:private'],
+ cmd = '$(location //y2016/control_loops/python:polydrivetrain) $(OUTS)',
+ tools = [
+ '//y2016/control_loops/python:polydrivetrain',
+ ],
+ outs = [
+ 'polydrivetrain_dog_motor_plant.h',
+ 'polydrivetrain_dog_motor_plant.cc',
+ 'polydrivetrain_cim_plant.h',
+ 'polydrivetrain_cim_plant.cc',
+ ],
+)
+
+cc_library(
+ name = 'polydrivetrain_plants',
+ srcs = [
+ 'polydrivetrain_dog_motor_plant.cc',
+ 'drivetrain_dog_motor_plant.cc',
+ 'kalman_drivetrain_motor_plant.cc',
+ ],
+ hdrs = [
+ 'polydrivetrain_dog_motor_plant.h',
+ 'drivetrain_dog_motor_plant.h',
+ 'kalman_drivetrain_motor_plant.h',
+ ],
+ deps = [
+ '//frc971/control_loops:state_feedback_loop',
+ ],
+)
+
+cc_library(
+ name = 'drivetrain_base',
+ srcs = [
+ 'drivetrain_base.cc',
+ ],
+ hdrs = [
+ 'drivetrain_base.h',
+ ],
+ deps = [
+ ':polydrivetrain_plants',
+ '//frc971/control_loops/drivetrain:drivetrain_config',
+ '//y2016:constants',
+ ],
+)
+
+cc_binary(
+ name = 'drivetrain',
+ srcs = [
+ 'drivetrain_main.cc',
+ ],
+ deps = [
+ ':drivetrain_base',
+ '//aos/linux_code:init',
+ '//frc971/control_loops/drivetrain:drivetrain_lib',
+ ],
+)
diff --git a/y2016/control_loops/drivetrain/drivetrain_base.cc b/y2016/control_loops/drivetrain/drivetrain_base.cc
new file mode 100644
index 0000000..2e5138c
--- /dev/null
+++ b/y2016/control_loops/drivetrain/drivetrain_base.cc
@@ -0,0 +1,46 @@
+#include "y2016/control_loops/drivetrain/drivetrain_base.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+#include "y2016/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
+#include "y2016/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
+#include "y2016/control_loops/drivetrain/kalman_drivetrain_motor_plant.h"
+#include "y2016/constants.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainConfig;
+
+namespace y2016 {
+namespace control_loops {
+
+const DrivetrainConfig &GetDrivetrainConfig() {
+ static DrivetrainConfig kDrivetrainConfig{
+ ::frc971::control_loops::drivetrain::ShifterType::HALL_EFFECT_SHIFTER,
+
+ ::y2016::control_loops::drivetrain::MakeDrivetrainLoop,
+ ::y2016::control_loops::drivetrain::MakeVelocityDrivetrainLoop,
+ ::y2016::control_loops::drivetrain::MakeKFDrivetrainLoop,
+
+ drivetrain::kDt,
+ drivetrain::kStallTorque,
+ drivetrain::kStallCurrent,
+ drivetrain::kFreeSpeedRPM,
+ drivetrain::kFreeCurrent,
+ drivetrain::kJ,
+ drivetrain::kMass,
+ drivetrain::kRobotRadius,
+ drivetrain::kWheelRadius,
+ drivetrain::kR,
+ drivetrain::kV,
+ drivetrain::kT,
+
+ constants::GetValues().turn_width,
+ constants::GetValues().high_gear_ratio,
+ constants::GetValues().low_gear_ratio,
+ constants::GetValues().left_drive,
+ constants::GetValues().right_drive};
+
+ return kDrivetrainConfig;
+};
+
+} // namespace control_loops
+} // namespace y2016
diff --git a/y2016/control_loops/drivetrain/drivetrain_base.h b/y2016/control_loops/drivetrain/drivetrain_base.h
new file mode 100644
index 0000000..816ed21
--- /dev/null
+++ b/y2016/control_loops/drivetrain/drivetrain_base.h
@@ -0,0 +1,16 @@
+#ifndef Y2016_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
+#define Y2016_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
+
+#include "frc971/control_loops/drivetrain/drivetrain_config.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainConfig;
+
+namespace y2016 {
+namespace control_loops {
+
+const DrivetrainConfig &GetDrivetrainConfig();
+
+} // namespace control_loops
+} // namespace y2016
+
+#endif // Y2016_CONTROL_LOOPS_DRIVETRAIN_DRIVETRAIN_BASE_H_
diff --git a/y2016/control_loops/drivetrain/drivetrain_main.cc b/y2016/control_loops/drivetrain/drivetrain_main.cc
new file mode 100644
index 0000000..9c678bf
--- /dev/null
+++ b/y2016/control_loops/drivetrain/drivetrain_main.cc
@@ -0,0 +1,15 @@
+#include "aos/linux_code/init.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain.h"
+#include "y2016/control_loops/drivetrain/drivetrain_base.h"
+
+using ::frc971::control_loops::drivetrain::DrivetrainLoop;
+
+int main() {
+ ::aos::Init();
+ DrivetrainLoop drivetrain =
+ DrivetrainLoop(::y2016::control_loops::GetDrivetrainConfig());
+ drivetrain.Run();
+ ::aos::Cleanup();
+ return 0;
+}
diff --git a/y2016/control_loops/python/BUILD b/y2016/control_loops/python/BUILD
new file mode 100644
index 0000000..bd5c4bd
--- /dev/null
+++ b/y2016/control_loops/python/BUILD
@@ -0,0 +1,90 @@
+package(default_visibility = ['//y2016:__subpackages__'])
+
+py_binary(
+ name = 'drivetrain',
+ srcs = [
+ 'drivetrain.py',
+ ],
+ deps = [
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ],
+)
+
+py_binary(
+ name = 'polydrivetrain',
+ srcs = [
+ 'polydrivetrain.py',
+ 'drivetrain.py',
+ ],
+ deps = [
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ],
+)
+
+py_library(
+ name = 'polydrivetrain_lib',
+ srcs = [
+ 'polydrivetrain.py',
+ 'drivetrain.py',
+ ],
+ deps = [
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ],
+)
+
+py_binary(
+ name = 'shooter',
+ srcs = [
+ 'shooter.py',
+ ],
+ deps = [
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'intake',
+ srcs = [
+ 'intake.py',
+ ],
+ deps = [
+ ':polydrivetrain_lib',
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'shoulder',
+ srcs = [
+ 'shoulder.py',
+ ],
+ deps = [
+ ':polydrivetrain_lib',
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
+
+py_binary(
+ name = 'wrist',
+ srcs = [
+ 'wrist.py',
+ ],
+ deps = [
+ ':polydrivetrain_lib',
+ '//external:python-gflags',
+ '//external:python-glog',
+ '//frc971/control_loops/python:controls',
+ ]
+)
diff --git a/y2016/control_loops/python/drivetrain.py b/y2016/control_loops/python/drivetrain.py
new file mode 100755
index 0000000..f94b456
--- /dev/null
+++ b/y2016/control_loops/python/drivetrain.py
@@ -0,0 +1,354 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+import numpy
+import sys
+import argparse
+from matplotlib import pylab
+
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+
+#TODO(constants): All of the constants need to be updated for 2016.
+
+class CIM(control_loop.ControlLoop):
+ def __init__(self):
+ super(CIM, self).__init__("CIM")
+ # Stall Torque in N m
+ self.stall_torque = 2.42
+ # Stall Current in Amps
+ self.stall_current = 133
+ # Free Speed in RPM
+ self.free_speed = 4650.0
+ # Free Current in Amps
+ self.free_current = 2.7
+ # Moment of inertia of the CIM in kg m^2
+ self.J = 0.0001
+ # Resistance of the motor, divided by 2 to account for the 2 motors
+ self.resistance = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.resistance * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Control loop time step
+ self.dt = 0.005
+
+ # State feedback matrices
+ self.A_continuous = numpy.matrix(
+ [[-self.Kt / self.Kv / (self.J * self.resistance)]])
+ self.B_continuous = numpy.matrix(
+ [[self.Kt / (self.J * self.resistance)]])
+ self.C = numpy.matrix([[1]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
+ self.B_continuous, self.dt)
+
+ self.PlaceControllerPoles([0.01])
+ self.PlaceObserverPoles([0.01])
+
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+
+class Drivetrain(control_loop.ControlLoop):
+ def __init__(self, name="Drivetrain", left_low=True, right_low=True):
+ super(Drivetrain, self).__init__(name)
+ # Number of motors per side
+ self.num_motors = 2
+ # Stall Torque in N m
+ self.stall_torque = 2.42 * self.num_motors * 0.60
+ # Stall Current in Amps
+ self.stall_current = 133.0 * self.num_motors
+ # Free Speed in RPM. Used number from last year.
+ self.free_speed = 5500.0
+ # Free Current in Amps
+ self.free_current = 4.7 * self.num_motors
+ # Moment of inertia of the drivetrain in kg m^2
+ self.J = 2.8
+ # Mass of the robot, in kg.
+ self.m = 68
+ # Radius of the robot, in meters (from last year).
+ self.rb = 0.647998644 / 2.0
+ # Radius of the wheels, in meters.
+ self.r = .04445
+ # Resistance of the motor, divided by the number of motors.
+ self.resistance = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.resistance * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Gear ratios
+ self.G_low = 18.0 / 60.0 * 18.0 / 50.0
+ self.G_high = 28.0 / 50.0 * 18.0 / 50.0
+ if left_low:
+ self.Gl = self.G_low
+ else:
+ self.Gl = self.G_high
+ if right_low:
+ self.Gr = self.G_low
+ else:
+ self.Gr = self.G_high
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # These describe the way that a given side of a robot will be influenced
+ # by the other side. Units of 1 / kg.
+ self.msp = 1.0 / self.m + self.rb * self.rb / self.J
+ self.msn = 1.0 / self.m - self.rb * self.rb / self.J
+ # The calculations which we will need for A and B.
+ self.tcl = -self.Kt / self.Kv / (self.Gl * self.Gl * self.resistance * self.r * self.r)
+ self.tcr = -self.Kt / self.Kv / (self.Gr * self.Gr * self.resistance * self.r * self.r)
+ self.mpl = self.Kt / (self.Gl * self.resistance * self.r)
+ self.mpr = self.Kt / (self.Gr * self.resistance * self.r)
+
+ # State feedback matrices
+ # X will be of the format
+ # [[positionl], [velocityl], [positionr], velocityr]]
+ self.A_continuous = numpy.matrix(
+ [[0, 1, 0, 0],
+ [0, self.msp * self.tcl, 0, self.msn * self.tcr],
+ [0, 0, 0, 1],
+ [0, self.msn * self.tcl, 0, self.msp * self.tcr]])
+ self.B_continuous = numpy.matrix(
+ [[0, 0],
+ [self.msp * self.mpl, self.msn * self.mpr],
+ [0, 0],
+ [self.msn * self.mpl, self.msp * self.mpr]])
+ self.C = numpy.matrix([[1, 0, 0, 0],
+ [0, 0, 1, 0]])
+ self.D = numpy.matrix([[0, 0],
+ [0, 0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.12
+ q_vel = 1.0
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0, 0.0, 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0)), 0.0, 0.0],
+ [0.0, 0.0, (1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, 0.0, 0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0)), 0.0],
+ [0.0, (1.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ glog.debug('DT K %s', name)
+ glog.debug(str(self.K))
+ glog.debug(str(numpy.linalg.eig(self.A - self.B * self.K)[0]))
+
+ self.hlp = 0.3
+ self.llp = 0.4
+ self.PlaceObserverPoles([self.hlp, self.hlp, self.llp, self.llp])
+
+ self.U_max = numpy.matrix([[12.0], [12.0]])
+ self.U_min = numpy.matrix([[-12.0], [-12.0]])
+ self.InitializeState()
+
+
+class KFDrivetrain(Drivetrain):
+ def __init__(self, name="KFDrivetrain", left_low=True, right_low=True):
+ super(KFDrivetrain, self).__init__(name, left_low, right_low)
+
+ self.unaugmented_A_continuous = self.A_continuous
+ self.unaugmented_B_continuous = self.B_continuous
+
+ # The states are
+ # The practical voltage applied to the wheels is
+ # V_left = U_left + left_voltage_error
+ #
+ # [left position, left velocity, right position, right velocity,
+ # left voltage error, right voltage error, angular_error]
+ self.A_continuous = numpy.matrix(numpy.zeros((7, 7)))
+ self.B_continuous = numpy.matrix(numpy.zeros((7, 2)))
+ self.A_continuous[0:4,0:4] = self.unaugmented_A_continuous
+ self.A_continuous[0:4,4:6] = self.unaugmented_B_continuous
+ self.B_continuous[0:4,0:2] = self.unaugmented_B_continuous
+ self.A_continuous[0,6] = 1
+ self.A_continuous[2,6] = -1
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ self.C = numpy.matrix([[1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0],
+ [0, -0.5 / self.rb, 0, 0.5 / self.rb, 0, 0, 0]])
+
+ self.D = numpy.matrix([[0, 0],
+ [0, 0],
+ [0, 0]])
+
+ q_pos = 0.05
+ q_vel = 1.00
+ q_voltage = 10.0
+ q_encoder_uncertainty = 2.00
+
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, (q_pos ** 2.0), 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, (q_vel ** 2.0), 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, (q_voltage ** 2.0), 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, (q_voltage ** 2.0), 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, (q_encoder_uncertainty ** 2.0)]])
+
+ r_pos = 0.0001
+ r_gyro = 0.000001
+ self.R = numpy.matrix([[(r_pos ** 2.0), 0.0, 0.0],
+ [0.0, (r_pos ** 2.0), 0.0],
+ [0.0, 0.0, (r_gyro ** 2.0)]])
+
+ # Solving for kf gains.
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+
+ self.L = self.A * self.KalmanGain
+
+ # We need a nothing controller for the autogen code to be happy.
+ self.K = numpy.matrix(numpy.zeros((self.B.shape[1], self.A.shape[0])))
+
+
+def main(argv):
+ argv = FLAGS(argv)
+ glog.init()
+
+ # Simulate the response of the system to a step input.
+ drivetrain = Drivetrain()
+ simulated_left = []
+ simulated_right = []
+ for _ in xrange(100):
+ drivetrain.Update(numpy.matrix([[12.0], [12.0]]))
+ simulated_left.append(drivetrain.X[0, 0])
+ simulated_right.append(drivetrain.X[2, 0])
+
+ if FLAGS.plot:
+ pylab.plot(range(100), simulated_left)
+ pylab.plot(range(100), simulated_right)
+ pylab.show()
+
+ # Simulate forwards motion.
+ drivetrain = Drivetrain()
+ close_loop_left = []
+ close_loop_right = []
+ R = numpy.matrix([[1.0], [0.0], [1.0], [0.0]])
+ for _ in xrange(100):
+ U = numpy.clip(drivetrain.K * (R - drivetrain.X_hat),
+ drivetrain.U_min, drivetrain.U_max)
+ drivetrain.UpdateObserver(U)
+ drivetrain.Update(U)
+ close_loop_left.append(drivetrain.X[0, 0])
+ close_loop_right.append(drivetrain.X[2, 0])
+
+ if FLAGS.plot:
+ pylab.plot(range(100), close_loop_left)
+ pylab.plot(range(100), close_loop_right)
+ pylab.show()
+
+ # Try turning in place
+ drivetrain = Drivetrain()
+ close_loop_left = []
+ close_loop_right = []
+ R = numpy.matrix([[-1.0], [0.0], [1.0], [0.0]])
+ for _ in xrange(100):
+ U = numpy.clip(drivetrain.K * (R - drivetrain.X_hat),
+ drivetrain.U_min, drivetrain.U_max)
+ drivetrain.UpdateObserver(U)
+ drivetrain.Update(U)
+ close_loop_left.append(drivetrain.X[0, 0])
+ close_loop_right.append(drivetrain.X[2, 0])
+
+ if FLAGS.plot:
+ pylab.plot(range(100), close_loop_left)
+ pylab.plot(range(100), close_loop_right)
+ pylab.show()
+
+ # Try turning just one side.
+ drivetrain = Drivetrain()
+ close_loop_left = []
+ close_loop_right = []
+ R = numpy.matrix([[0.0], [0.0], [1.0], [0.0]])
+ for _ in xrange(100):
+ U = numpy.clip(drivetrain.K * (R - drivetrain.X_hat),
+ drivetrain.U_min, drivetrain.U_max)
+ drivetrain.UpdateObserver(U)
+ drivetrain.Update(U)
+ close_loop_left.append(drivetrain.X[0, 0])
+ close_loop_right.append(drivetrain.X[2, 0])
+
+ if FLAGS.plot:
+ pylab.plot(range(100), close_loop_left)
+ pylab.plot(range(100), close_loop_right)
+ pylab.show()
+
+ # Write the generated constants out to a file.
+ drivetrain_low_low = Drivetrain(
+ name="DrivetrainLowLow", left_low=True, right_low=True)
+ drivetrain_low_high = Drivetrain(
+ name="DrivetrainLowHigh", left_low=True, right_low=False)
+ drivetrain_high_low = Drivetrain(
+ name="DrivetrainHighLow", left_low=False, right_low=True)
+ drivetrain_high_high = Drivetrain(
+ name="DrivetrainHighHigh", left_low=False, right_low=False)
+
+ kf_drivetrain_low_low = KFDrivetrain(
+ name="KFDrivetrainLowLow", left_low=True, right_low=True)
+ kf_drivetrain_low_high = KFDrivetrain(
+ name="KFDrivetrainLowHigh", left_low=True, right_low=False)
+ kf_drivetrain_high_low = KFDrivetrain(
+ name="KFDrivetrainHighLow", left_low=False, right_low=True)
+ kf_drivetrain_high_high = KFDrivetrain(
+ name="KFDrivetrainHighHigh", left_low=False, right_low=False)
+
+ if len(argv) != 5:
+ print "Expected .h file name and .cc file name"
+ else:
+ namespaces = ['y2016', 'control_loops', 'drivetrain']
+ dog_loop_writer = control_loop.ControlLoopWriter(
+ "Drivetrain", [drivetrain_low_low, drivetrain_low_high,
+ drivetrain_high_low, drivetrain_high_high],
+ namespaces = namespaces)
+ dog_loop_writer.AddConstant(control_loop.Constant("kDt", "%f",
+ drivetrain_low_low.dt))
+ dog_loop_writer.AddConstant(control_loop.Constant("kStallTorque", "%f",
+ drivetrain_low_low.stall_torque))
+ dog_loop_writer.AddConstant(control_loop.Constant("kStallCurrent", "%f",
+ drivetrain_low_low.stall_current))
+ dog_loop_writer.AddConstant(control_loop.Constant("kFreeSpeedRPM", "%f",
+ drivetrain_low_low.free_speed))
+ dog_loop_writer.AddConstant(control_loop.Constant("kFreeCurrent", "%f",
+ drivetrain_low_low.free_current))
+ dog_loop_writer.AddConstant(control_loop.Constant("kJ", "%f",
+ drivetrain_low_low.J))
+ dog_loop_writer.AddConstant(control_loop.Constant("kMass", "%f",
+ drivetrain_low_low.m))
+ dog_loop_writer.AddConstant(control_loop.Constant("kRobotRadius", "%f",
+ drivetrain_low_low.rb))
+ dog_loop_writer.AddConstant(control_loop.Constant("kWheelRadius", "%f",
+ drivetrain_low_low.r))
+ dog_loop_writer.AddConstant(control_loop.Constant("kR", "%f",
+ drivetrain_low_low.resistance))
+ dog_loop_writer.AddConstant(control_loop.Constant("kV", "%f",
+ drivetrain_low_low.Kv))
+ dog_loop_writer.AddConstant(control_loop.Constant("kT", "%f",
+ drivetrain_low_low.Kt))
+
+ dog_loop_writer.Write(argv[1], argv[2])
+
+ kf_loop_writer = control_loop.ControlLoopWriter(
+ "KFDrivetrain", [kf_drivetrain_low_low, kf_drivetrain_low_high,
+ kf_drivetrain_high_low, kf_drivetrain_high_high],
+ namespaces = namespaces)
+ kf_loop_writer.Write(argv[3], argv[4])
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/y2016/control_loops/python/intake.py b/y2016/control_loops/python/intake.py
new file mode 100755
index 0000000..ae57730
--- /dev/null
+++ b/y2016/control_loops/python/intake.py
@@ -0,0 +1,282 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+from frc971.control_loops.python import polytope
+from y2016.control_loops.python import polydrivetrain
+import numpy
+import sys
+import matplotlib
+from matplotlib import pylab
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+try:
+ gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+except gflags.DuplicateFlagError:
+ pass
+
+class Intake(control_loop.ControlLoop):
+ def __init__(self, name="Intake"):
+ super(Intake, self).__init__(name)
+ # TODO(constants): Update all of these & retune poles.
+ # Stall Torque in N m
+ self.stall_torque = 0.71
+ # Stall Current in Amps
+ self.stall_current = 134
+ # Free Speed in RPM
+ self.free_speed = 18730
+ # Free Current in Amps
+ self.free_current = 0.7
+
+ # Resistance of the motor
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Gear ratio
+ self.G = (56.0 / 12.0) * (54.0 / 14.0) * (64.0 / 18.0) * (48.0 / 16.0)
+
+ self.J = 0.9
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # State is [position, velocity]
+ # Input is [Voltage]
+
+ C1 = self.G * self.G * self.Kt / (self.R * self.J * self.Kv)
+ C2 = self.Kt * self.G / (self.J * self.R)
+
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -C1]])
+
+ # Start with the unmodified input
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [C2]])
+
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ controllability = controls.ctrb(self.A, self.B)
+
+ print "Free speed is", self.free_speed * numpy.pi * 2.0 / 60.0 / self.G
+
+ q_pos = 0.20
+ q_vel = 5.5
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ print 'K', self.K
+ print 'Poles are', numpy.linalg.eig(self.A - self.B * self.K)[0]
+
+ self.rpl = 0.30
+ self.ipl = 0.10
+ self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
+ self.rpl - 1j * self.ipl])
+
+ print 'L is', self.L
+
+ q_pos = 0.05
+ q_vel = 2.65
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
+ [0.0, (q_vel ** 2.0)]])
+
+ r_volts = 0.025
+ self.R = numpy.matrix([[(r_volts ** 2.0)]])
+
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+
+ print 'Kal', self.KalmanGain
+ self.L = self.A * self.KalmanGain
+ print 'KalL is', self.L
+
+ # The box formed by U_min and U_max must encompass all possible values,
+ # or else Austin's code gets angry.
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+class IntegralIntake(Intake):
+ def __init__(self, name="IntegralIntake"):
+ super(IntegralIntake, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.08
+ q_vel = 4.00
+ q_voltage = 3.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.05
+ self.R = numpy.matrix([[(r_pos ** 2.0)]])
+
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+ self.L = self.A * self.KalmanGain
+
+ self.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+
+ self.InitializeState()
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, intake, goal, iterations=200, controller_intake=None,
+ observer_intake=None):
+ """Runs the intake plant with an initial condition and goal.
+
+ Test for whether the goal has been reached and whether the separation
+ goes outside of the initial and goal values by more than
+ max_separation_error.
+
+ Prints out something for a failure of either condition and returns
+ False if tests fail.
+ Args:
+ intake: intake object to use.
+ goal: goal state.
+ iterations: Number of timesteps to run the model for.
+ controller_intake: Intake object to get K from, or None if we should
+ use intake.
+ observer_intake: Intake object to use for the observer, or None if we should
+ use the actual state.
+ """
+
+ if controller_intake is None:
+ controller_intake = intake
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + intake.dt
+ else:
+ initial_t = 0
+
+ for i in xrange(iterations):
+ X_hat = intake.X
+
+ if observer_intake is not None:
+ X_hat = observer_intake.X_hat
+ self.x_hat.append(observer_intake.X_hat[0, 0])
+
+ U = controller_intake.K * (goal - X_hat)
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(intake.X[0, 0])
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(intake.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / intake.dt)
+
+ if observer_intake is not None:
+ observer_intake.Y = intake.Y
+ observer_intake.CorrectObserver(U)
+ self.offset.append(observer_intake.X_hat[2, 0])
+
+ intake.Update(U + 2.0)
+
+ if observer_intake is not None:
+ observer_intake.PredictObserver(U)
+
+ self.t.append(initial_t + i * intake.dt)
+ self.u.append(U[0, 0])
+
+ glog.debug('Time: %f', self.t[-1])
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.x, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ argv = FLAGS(argv)
+
+ scenario_plotter = ScenarioPlotter()
+
+ intake = Intake()
+ intake_controller = IntegralIntake()
+ observer_intake = IntegralIntake()
+
+ # Test moving the intake with constant separation.
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
+ scenario_plotter.run_test(intake, goal=R, controller_intake=intake_controller,
+ observer_intake=observer_intake, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ # Write the generated constants out to a file.
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name for the intake and integral intake.')
+ else:
+ namespaces = ['y2016', 'control_loops', 'superstructure']
+ intake = Intake("Intake")
+ loop_writer = control_loop.ControlLoopWriter('Intake', [intake],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_intake = IntegralIntake("IntegralIntake")
+ integral_loop_writer = control_loop.ControlLoopWriter("IntegralIntake", [integral_intake],
+ namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/y2016/control_loops/python/polydrivetrain.py b/y2016/control_loops/python/polydrivetrain.py
new file mode 100755
index 0000000..eb0890e
--- /dev/null
+++ b/y2016/control_loops/python/polydrivetrain.py
@@ -0,0 +1,512 @@
+#!/usr/bin/python
+
+import numpy
+import sys
+from frc971.control_loops.python import polytope
+from y2016.control_loops.python import drivetrain
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+from matplotlib import pylab
+
+import gflags
+import glog
+
+__author__ = 'Austin Schuh (austin.linux@gmail.com)'
+
+FLAGS = gflags.FLAGS
+
+try:
+ gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+except gflags.DuplicateFlagError:
+ pass
+
+def CoerceGoal(region, K, w, R):
+ """Intersects a line with a region, and finds the closest point to R.
+
+ Finds a point that is closest to R inside the region, and on the line
+ defined by K X = w. If it is not possible to find a point on the line,
+ finds a point that is inside the region and closest to the line. This
+ function assumes that
+
+ Args:
+ region: HPolytope, the valid goal region.
+ K: numpy.matrix (2 x 1), the matrix for the equation [K1, K2] [x1; x2] = w
+ w: float, the offset in the equation above.
+ R: numpy.matrix (2 x 1), the point to be closest to.
+
+ Returns:
+ numpy.matrix (2 x 1), the point.
+ """
+ return DoCoerceGoal(region, K, w, R)[0]
+
+def DoCoerceGoal(region, K, w, R):
+ if region.IsInside(R):
+ return (R, True)
+
+ perpendicular_vector = K.T / numpy.linalg.norm(K)
+ parallel_vector = numpy.matrix([[perpendicular_vector[1, 0]],
+ [-perpendicular_vector[0, 0]]])
+
+ # We want to impose the constraint K * X = w on the polytope H * X <= k.
+ # We do this by breaking X up into parallel and perpendicular components to
+ # the half plane. This gives us the following equation.
+ #
+ # parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) = X
+ #
+ # Then, substitute this into the polytope.
+ #
+ # H * (parallel * (parallel.T \dot X) + perpendicular * (perpendicular \dot X)) <= k
+ #
+ # Substitute K * X = w
+ #
+ # H * parallel * (parallel.T \dot X) + H * perpendicular * w <= k
+ #
+ # Move all the knowns to the right side.
+ #
+ # H * parallel * ([parallel1 parallel2] * X) <= k - H * perpendicular * w
+ #
+ # Let t = parallel.T \dot X, the component parallel to the surface.
+ #
+ # H * parallel * t <= k - H * perpendicular * w
+ #
+ # This is a polytope which we can solve, and use to figure out the range of X
+ # that we care about!
+
+ t_poly = polytope.HPolytope(
+ region.H * parallel_vector,
+ region.k - region.H * perpendicular_vector * w)
+
+ vertices = t_poly.Vertices()
+
+ if vertices.shape[0]:
+ # The region exists!
+ # Find the closest vertex
+ min_distance = numpy.infty
+ closest_point = None
+ for vertex in vertices:
+ point = parallel_vector * vertex + perpendicular_vector * w
+ length = numpy.linalg.norm(R - point)
+ if length < min_distance:
+ min_distance = length
+ closest_point = point
+
+ return (closest_point, True)
+ else:
+ # Find the vertex of the space that is closest to the line.
+ region_vertices = region.Vertices()
+ min_distance = numpy.infty
+ closest_point = None
+ for vertex in region_vertices:
+ point = vertex.T
+ length = numpy.abs((perpendicular_vector.T * point)[0, 0])
+ if length < min_distance:
+ min_distance = length
+ closest_point = point
+
+ return (closest_point, False)
+
+
+class VelocityDrivetrainModel(control_loop.ControlLoop):
+ def __init__(self, left_low=True, right_low=True, name="VelocityDrivetrainModel"):
+ super(VelocityDrivetrainModel, self).__init__(name)
+ self._drivetrain = drivetrain.Drivetrain(left_low=left_low,
+ right_low=right_low)
+ self.dt = 0.005
+ self.A_continuous = numpy.matrix(
+ [[self._drivetrain.A_continuous[1, 1], self._drivetrain.A_continuous[1, 3]],
+ [self._drivetrain.A_continuous[3, 1], self._drivetrain.A_continuous[3, 3]]])
+
+ self.B_continuous = numpy.matrix(
+ [[self._drivetrain.B_continuous[1, 0], self._drivetrain.B_continuous[1, 1]],
+ [self._drivetrain.B_continuous[3, 0], self._drivetrain.B_continuous[3, 1]]])
+ self.C = numpy.matrix(numpy.eye(2))
+ self.D = numpy.matrix(numpy.zeros((2, 2)))
+
+ self.A, self.B = self.ContinuousToDiscrete(self.A_continuous,
+ self.B_continuous, self.dt)
+
+ # FF * X = U (steady state)
+ self.FF = self.B.I * (numpy.eye(2) - self.A)
+
+ self.PlaceControllerPoles([0.7, 0.7])
+ self.PlaceObserverPoles([0.02, 0.02])
+
+ self.G_high = self._drivetrain.G_high
+ self.G_low = self._drivetrain.G_low
+ self.R = self._drivetrain.R
+ self.r = self._drivetrain.r
+ self.Kv = self._drivetrain.Kv
+ self.Kt = self._drivetrain.Kt
+
+ self.U_max = self._drivetrain.U_max
+ self.U_min = self._drivetrain.U_min
+
+
+class VelocityDrivetrain(object):
+ HIGH = 'high'
+ LOW = 'low'
+ SHIFTING_UP = 'up'
+ SHIFTING_DOWN = 'down'
+
+ def __init__(self):
+ self.drivetrain_low_low = VelocityDrivetrainModel(
+ left_low=True, right_low=True, name='VelocityDrivetrainLowLow')
+ self.drivetrain_low_high = VelocityDrivetrainModel(left_low=True, right_low=False, name='VelocityDrivetrainLowHigh')
+ self.drivetrain_high_low = VelocityDrivetrainModel(left_low=False, right_low=True, name = 'VelocityDrivetrainHighLow')
+ self.drivetrain_high_high = VelocityDrivetrainModel(left_low=False, right_low=False, name = 'VelocityDrivetrainHighHigh')
+
+ # X is [lvel, rvel]
+ self.X = numpy.matrix(
+ [[0.0],
+ [0.0]])
+
+ self.U_poly = polytope.HPolytope(
+ numpy.matrix([[1, 0],
+ [-1, 0],
+ [0, 1],
+ [0, -1]]),
+ numpy.matrix([[12],
+ [12],
+ [12],
+ [12]]))
+
+ self.U_max = numpy.matrix(
+ [[12.0],
+ [12.0]])
+ self.U_min = numpy.matrix(
+ [[-12.0000000000],
+ [-12.0000000000]])
+
+ self.dt = 0.005
+
+ self.R = numpy.matrix(
+ [[0.0],
+ [0.0]])
+
+ # ttrust is the comprimise between having full throttle negative inertia,
+ # and having no throttle negative inertia. A value of 0 is full throttle
+ # inertia. A value of 1 is no throttle negative inertia.
+ self.ttrust = 1.0
+
+ self.left_gear = VelocityDrivetrain.LOW
+ self.right_gear = VelocityDrivetrain.LOW
+ self.left_shifter_position = 0.0
+ self.right_shifter_position = 0.0
+ self.left_cim = drivetrain.CIM()
+ self.right_cim = drivetrain.CIM()
+
+ def IsInGear(self, gear):
+ return gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.LOW
+
+ def MotorRPM(self, shifter_position, velocity):
+ if shifter_position > 0.5:
+ return (velocity / self.CurrentDrivetrain().G_high /
+ self.CurrentDrivetrain().r)
+ else:
+ return (velocity / self.CurrentDrivetrain().G_low /
+ self.CurrentDrivetrain().r)
+
+ def CurrentDrivetrain(self):
+ if self.left_shifter_position > 0.5:
+ if self.right_shifter_position > 0.5:
+ return self.drivetrain_high_high
+ else:
+ return self.drivetrain_high_low
+ else:
+ if self.right_shifter_position > 0.5:
+ return self.drivetrain_low_high
+ else:
+ return self.drivetrain_low_low
+
+ def SimShifter(self, gear, shifter_position):
+ if gear is VelocityDrivetrain.HIGH or gear is VelocityDrivetrain.SHIFTING_UP:
+ shifter_position = min(shifter_position + 0.5, 1.0)
+ else:
+ shifter_position = max(shifter_position - 0.5, 0.0)
+
+ if shifter_position == 1.0:
+ gear = VelocityDrivetrain.HIGH
+ elif shifter_position == 0.0:
+ gear = VelocityDrivetrain.LOW
+
+ return gear, shifter_position
+
+ def ComputeGear(self, wheel_velocity, should_print=False, current_gear=False, gear_name=None):
+ high_omega = (wheel_velocity / self.CurrentDrivetrain().G_high /
+ self.CurrentDrivetrain().r)
+ low_omega = (wheel_velocity / self.CurrentDrivetrain().G_low /
+ self.CurrentDrivetrain().r)
+ #print gear_name, "Motor Energy Difference.", 0.5 * 0.000140032647 * (low_omega * low_omega - high_omega * high_omega), "joules"
+ high_torque = ((12.0 - high_omega / self.CurrentDrivetrain().Kv) *
+ self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
+ low_torque = ((12.0 - low_omega / self.CurrentDrivetrain().Kv) *
+ self.CurrentDrivetrain().Kt / self.CurrentDrivetrain().R)
+ high_power = high_torque * high_omega
+ low_power = low_torque * low_omega
+ #if should_print:
+ # print gear_name, "High omega", high_omega, "Low omega", low_omega
+ # print gear_name, "High torque", high_torque, "Low torque", low_torque
+ # print gear_name, "High power", high_power, "Low power", low_power
+
+ # Shift algorithm improvements.
+ # TODO(aschuh):
+ # It takes time to shift. Shifting down for 1 cycle doesn't make sense
+ # because you will end up slower than without shifting. Figure out how
+ # to include that info.
+ # If the driver is still in high gear, but isn't asking for the extra power
+ # from low gear, don't shift until he asks for it.
+ goal_gear_is_high = high_power > low_power
+ #goal_gear_is_high = True
+
+ if not self.IsInGear(current_gear):
+ glog.debug('%s Not in gear.', gear_name)
+ return current_gear
+ else:
+ is_high = current_gear is VelocityDrivetrain.HIGH
+ if is_high != goal_gear_is_high:
+ if goal_gear_is_high:
+ glog.debug('%s Shifting up.', gear_name)
+ return VelocityDrivetrain.SHIFTING_UP
+ else:
+ glog.debug('%s Shifting down.', gear_name)
+ return VelocityDrivetrain.SHIFTING_DOWN
+ else:
+ return current_gear
+
+ def FilterVelocity(self, throttle):
+ # Invert the plant to figure out how the velocity filter would have to work
+ # out in order to filter out the forwards negative inertia.
+ # This math assumes that the left and right power and velocity are equal.
+
+ # The throttle filter should filter such that the motor in the highest gear
+ # should be controlling the time constant.
+ # Do this by finding the index of FF that has the lowest value, and computing
+ # the sums using that index.
+ FF_sum = self.CurrentDrivetrain().FF.sum(axis=1)
+ min_FF_sum_index = numpy.argmin(FF_sum)
+ min_FF_sum = FF_sum[min_FF_sum_index, 0]
+ min_K_sum = self.CurrentDrivetrain().K[min_FF_sum_index, :].sum()
+ # Compute the FF sum for high gear.
+ high_min_FF_sum = self.drivetrain_high_high.FF[0, :].sum()
+
+ # U = self.K[0, :].sum() * (R - x_avg) + self.FF[0, :].sum() * R
+ # throttle * 12.0 = (self.K[0, :].sum() + self.FF[0, :].sum()) * R
+ # - self.K[0, :].sum() * x_avg
+
+ # R = (throttle * 12.0 + self.K[0, :].sum() * x_avg) /
+ # (self.K[0, :].sum() + self.FF[0, :].sum())
+
+ # U = (K + FF) * R - K * X
+ # (K + FF) ^-1 * (U + K * X) = R
+
+ # Scale throttle by min_FF_sum / high_min_FF_sum. This will make low gear
+ # have the same velocity goal as high gear, and so that the robot will hold
+ # the same speed for the same throttle for all gears.
+ adjusted_ff_voltage = numpy.clip(throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0)
+ return ((adjusted_ff_voltage + self.ttrust * min_K_sum * (self.X[0, 0] + self.X[1, 0]) / 2.0)
+ / (self.ttrust * min_K_sum + min_FF_sum))
+
+ def Update(self, throttle, steering):
+ # Shift into the gear which sends the most power to the floor.
+ # This is the same as sending the most torque down to the floor at the
+ # wheel.
+
+ self.left_gear = self.right_gear = True
+ if True:
+ self.left_gear = self.ComputeGear(self.X[0, 0], should_print=True,
+ current_gear=self.left_gear,
+ gear_name="left")
+ self.right_gear = self.ComputeGear(self.X[1, 0], should_print=True,
+ current_gear=self.right_gear,
+ gear_name="right")
+ if self.IsInGear(self.left_gear):
+ self.left_cim.X[0, 0] = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
+
+ if self.IsInGear(self.right_gear):
+ self.right_cim.X[0, 0] = self.MotorRPM(self.right_shifter_position, self.X[0, 0])
+
+ if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
+ # Filter the throttle to provide a nicer response.
+ fvel = self.FilterVelocity(throttle)
+
+ # Constant radius means that angualar_velocity / linear_velocity = constant.
+ # Compute the left and right velocities.
+ steering_velocity = numpy.abs(fvel) * steering
+ left_velocity = fvel - steering_velocity
+ right_velocity = fvel + steering_velocity
+
+ # Write this constraint in the form of K * R = w
+ # angular velocity / linear velocity = constant
+ # (left - right) / (left + right) = constant
+ # left - right = constant * left + constant * right
+
+ # (fvel - steering * numpy.abs(fvel) - fvel - steering * numpy.abs(fvel)) /
+ # (fvel - steering * numpy.abs(fvel) + fvel + steering * numpy.abs(fvel)) =
+ # constant
+ # (- 2 * steering * numpy.abs(fvel)) / (2 * fvel) = constant
+ # (-steering * sign(fvel)) = constant
+ # (-steering * sign(fvel)) * (left + right) = left - right
+ # (steering * sign(fvel) + 1) * left + (steering * sign(fvel) - 1) * right = 0
+
+ equality_k = numpy.matrix(
+ [[1 + steering * numpy.sign(fvel), -(1 - steering * numpy.sign(fvel))]])
+ equality_w = 0.0
+
+ self.R[0, 0] = left_velocity
+ self.R[1, 0] = right_velocity
+
+ # Construct a constraint on R by manipulating the constraint on U
+ # Start out with H * U <= k
+ # U = FF * R + K * (R - X)
+ # H * (FF * R + K * R - K * X) <= k
+ # H * (FF + K) * R <= k + H * K * X
+ R_poly = polytope.HPolytope(
+ self.U_poly.H * (self.CurrentDrivetrain().K + self.CurrentDrivetrain().FF),
+ self.U_poly.k + self.U_poly.H * self.CurrentDrivetrain().K * self.X)
+
+ # Limit R back inside the box.
+ self.boxed_R = CoerceGoal(R_poly, equality_k, equality_w, self.R)
+
+ FF_volts = self.CurrentDrivetrain().FF * self.boxed_R
+ self.U_ideal = self.CurrentDrivetrain().K * (self.boxed_R - self.X) + FF_volts
+ else:
+ glog.debug('Not all in gear')
+ if not self.IsInGear(self.left_gear) and not self.IsInGear(self.right_gear):
+ # TODO(austin): Use battery volts here.
+ R_left = self.MotorRPM(self.left_shifter_position, self.X[0, 0])
+ self.U_ideal[0, 0] = numpy.clip(
+ self.left_cim.K * (R_left - self.left_cim.X) + R_left / self.left_cim.Kv,
+ self.left_cim.U_min, self.left_cim.U_max)
+ self.left_cim.Update(self.U_ideal[0, 0])
+
+ R_right = self.MotorRPM(self.right_shifter_position, self.X[1, 0])
+ self.U_ideal[1, 0] = numpy.clip(
+ self.right_cim.K * (R_right - self.right_cim.X) + R_right / self.right_cim.Kv,
+ self.right_cim.U_min, self.right_cim.U_max)
+ self.right_cim.Update(self.U_ideal[1, 0])
+ else:
+ assert False
+
+ self.U = numpy.clip(self.U_ideal, self.U_min, self.U_max)
+
+ # TODO(austin): Model the robot as not accelerating when you shift...
+ # This hack only works when you shift at the same time.
+ if self.IsInGear(self.left_gear) and self.IsInGear(self.right_gear):
+ self.X = self.CurrentDrivetrain().A * self.X + self.CurrentDrivetrain().B * self.U
+
+ self.left_gear, self.left_shifter_position = self.SimShifter(
+ self.left_gear, self.left_shifter_position)
+ self.right_gear, self.right_shifter_position = self.SimShifter(
+ self.right_gear, self.right_shifter_position)
+
+ glog.debug('U is %s %s', str(self.U[0, 0]), str(self.U[1, 0]))
+ glog.debug('Left shifter %s %d Right shifter %s %d',
+ self.left_gear, self.left_shifter_position,
+ self.right_gear, self.right_shifter_position)
+
+
+def main(argv):
+ argv = FLAGS(argv)
+
+ vdrivetrain = VelocityDrivetrain()
+
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name')
+ else:
+ namespaces = ['y2016', 'control_loops', 'drivetrain']
+ dog_loop_writer = control_loop.ControlLoopWriter(
+ "VelocityDrivetrain", [vdrivetrain.drivetrain_low_low,
+ vdrivetrain.drivetrain_low_high,
+ vdrivetrain.drivetrain_high_low,
+ vdrivetrain.drivetrain_high_high],
+ namespaces=namespaces)
+
+ dog_loop_writer.Write(argv[1], argv[2])
+
+ cim_writer = control_loop.ControlLoopWriter(
+ "CIM", [drivetrain.CIM()])
+
+ cim_writer.Write(argv[3], argv[4])
+ return
+
+ vl_plot = []
+ vr_plot = []
+ ul_plot = []
+ ur_plot = []
+ radius_plot = []
+ t_plot = []
+ left_gear_plot = []
+ right_gear_plot = []
+ vdrivetrain.left_shifter_position = 0.0
+ vdrivetrain.right_shifter_position = 0.0
+ vdrivetrain.left_gear = VelocityDrivetrain.LOW
+ vdrivetrain.right_gear = VelocityDrivetrain.LOW
+
+ glog.debug('K is %s', str(vdrivetrain.CurrentDrivetrain().K))
+
+ if vdrivetrain.left_gear is VelocityDrivetrain.HIGH:
+ glog.debug('Left is high')
+ else:
+ glog.debug('Left is low')
+ if vdrivetrain.right_gear is VelocityDrivetrain.HIGH:
+ glog.debug('Right is high')
+ else:
+ glog.debug('Right is low')
+
+ for t in numpy.arange(0, 1.7, vdrivetrain.dt):
+ if t < 0.5:
+ vdrivetrain.Update(throttle=0.00, steering=1.0)
+ elif t < 1.2:
+ vdrivetrain.Update(throttle=0.5, steering=1.0)
+ else:
+ vdrivetrain.Update(throttle=0.00, steering=1.0)
+ t_plot.append(t)
+ vl_plot.append(vdrivetrain.X[0, 0])
+ vr_plot.append(vdrivetrain.X[1, 0])
+ ul_plot.append(vdrivetrain.U[0, 0])
+ ur_plot.append(vdrivetrain.U[1, 0])
+ left_gear_plot.append((vdrivetrain.left_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
+ right_gear_plot.append((vdrivetrain.right_gear is VelocityDrivetrain.HIGH) * 2.0 - 10.0)
+
+ fwd_velocity = (vdrivetrain.X[1, 0] + vdrivetrain.X[0, 0]) / 2
+ turn_velocity = (vdrivetrain.X[1, 0] - vdrivetrain.X[0, 0])
+ if abs(fwd_velocity) < 0.0000001:
+ radius_plot.append(turn_velocity)
+ else:
+ radius_plot.append(turn_velocity / fwd_velocity)
+
+ cim_velocity_plot = []
+ cim_voltage_plot = []
+ cim_time = []
+ cim = drivetrain.CIM()
+ R = numpy.matrix([[300]])
+ for t in numpy.arange(0, 0.5, cim.dt):
+ U = numpy.clip(cim.K * (R - cim.X) + R / cim.Kv, cim.U_min, cim.U_max)
+ cim.Update(U)
+ cim_velocity_plot.append(cim.X[0, 0])
+ cim_voltage_plot.append(U[0, 0] * 10)
+ cim_time.append(t)
+ pylab.plot(cim_time, cim_velocity_plot, label='cim spinup')
+ pylab.plot(cim_time, cim_voltage_plot, label='cim voltage')
+ pylab.legend()
+ pylab.show()
+
+ # TODO(austin):
+ # Shifting compensation.
+
+ # Tighten the turn.
+ # Closed loop drive.
+
+ pylab.plot(t_plot, vl_plot, label='left velocity')
+ pylab.plot(t_plot, vr_plot, label='right velocity')
+ pylab.plot(t_plot, ul_plot, label='left voltage')
+ pylab.plot(t_plot, ur_plot, label='right voltage')
+ pylab.plot(t_plot, radius_plot, label='radius')
+ pylab.plot(t_plot, left_gear_plot, label='left gear high')
+ pylab.plot(t_plot, right_gear_plot, label='right gear high')
+ pylab.legend()
+ pylab.show()
+ return 0
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/y2016/control_loops/python/polydrivetrain_test.py b/y2016/control_loops/python/polydrivetrain_test.py
new file mode 100755
index 0000000..434cdca
--- /dev/null
+++ b/y2016/control_loops/python/polydrivetrain_test.py
@@ -0,0 +1,82 @@
+#!/usr/bin/python
+
+import polydrivetrain
+import numpy
+from numpy.testing import *
+import polytope
+import unittest
+
+__author__ = 'Austin Schuh (austin.linux@gmail.com)'
+
+
+class TestVelocityDrivetrain(unittest.TestCase):
+ def MakeBox(self, x1_min, x1_max, x2_min, x2_max):
+ H = numpy.matrix([[1, 0],
+ [-1, 0],
+ [0, 1],
+ [0, -1]])
+ K = numpy.matrix([[x1_max],
+ [-x1_min],
+ [x2_max],
+ [-x2_min]])
+ return polytope.HPolytope(H, K)
+
+ def test_coerce_inside(self):
+ """Tests coercion when the point is inside the box."""
+ box = self.MakeBox(1, 2, 1, 2)
+
+ # x1 = x2
+ K = numpy.matrix([[1, -1]])
+ w = 0
+
+ assert_array_equal(polydrivetrain.CoerceGoal(box, K, w,
+ numpy.matrix([[1.5], [1.5]])),
+ numpy.matrix([[1.5], [1.5]]))
+
+ def test_coerce_outside_intersect(self):
+ """Tests coercion when the line intersects the box."""
+ box = self.MakeBox(1, 2, 1, 2)
+
+ # x1 = x2
+ K = numpy.matrix([[1, -1]])
+ w = 0
+
+ assert_array_equal(polydrivetrain.CoerceGoal(box, K, w, numpy.matrix([[5], [5]])),
+ numpy.matrix([[2.0], [2.0]]))
+
+ def test_coerce_outside_no_intersect(self):
+ """Tests coercion when the line does not intersect the box."""
+ box = self.MakeBox(3, 4, 1, 2)
+
+ # x1 = x2
+ K = numpy.matrix([[1, -1]])
+ w = 0
+
+ assert_array_equal(polydrivetrain.CoerceGoal(box, K, w, numpy.matrix([[5], [5]])),
+ numpy.matrix([[3.0], [2.0]]))
+
+ def test_coerce_middle_of_edge(self):
+ """Tests coercion when the line intersects the middle of an edge."""
+ box = self.MakeBox(0, 4, 1, 2)
+
+ # x1 = x2
+ K = numpy.matrix([[-1, 1]])
+ w = 0
+
+ assert_array_equal(polydrivetrain.CoerceGoal(box, K, w, numpy.matrix([[5], [5]])),
+ numpy.matrix([[2.0], [2.0]]))
+
+ def test_coerce_perpendicular_line(self):
+ """Tests coercion when the line does not intersect and is in quadrant 2."""
+ box = self.MakeBox(1, 2, 1, 2)
+
+ # x1 = -x2
+ K = numpy.matrix([[1, 1]])
+ w = 0
+
+ assert_array_equal(polydrivetrain.CoerceGoal(box, K, w, numpy.matrix([[5], [5]])),
+ numpy.matrix([[1.0], [1.0]]))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/y2016/control_loops/python/shooter.py b/y2016/control_loops/python/shooter.py
new file mode 100755
index 0000000..c81d597
--- /dev/null
+++ b/y2016/control_loops/python/shooter.py
@@ -0,0 +1,73 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+import numpy
+import sys
+from matplotlib import pylab
+
+class Shooter(control_loop.ControlLoop):
+ def __init__(self):
+ super(Shooter, self).__init__("Shooter")
+ # Stall Torque in N m
+ self.stall_torque = 0.71
+ # Stall Current in Amps
+ self.stall_current = 134
+ # Free Speed in RPM
+ self.free_speed = 18730.0
+ # Free Current in Amps
+ self.free_current = 0.7
+ # Moment of inertia of the shooter wheel in kg m^2
+ self.J = 0.00032
+ # Resistance of the motor, divided by 2 to account for the 2 motors
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Gear ratio
+ self.G = 12.0 / 18.0
+ # Control loop time step
+ self.dt = 0.005
+
+ # State feedback matrices
+ # [position, angular velocity]
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -self.Kt / self.Kv / (self.J * self.G * self.G * self.R)]])
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [self.Kt / (self.J * self.G * self.R)]])
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ self.PlaceControllerPoles([.6, .981])
+
+ self.rpl = .45
+ self.ipl = 0.07
+ self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
+ self.rpl - 1j * self.ipl])
+
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+
+def main(argv):
+ if len(argv) != 3:
+ print "Expected .h file name and .cc file name"
+ else:
+ namespaces = ['y2016', 'control_loops', 'shooter']
+ shooter = Shooter()
+ loop_writer = control_loop.ControlLoopWriter("Shooter", [shooter],
+ namespaces=namespaces)
+ if argv[1][-3:] == '.cc':
+ loop_writer.Write(argv[2], argv[1])
+ else:
+ loop_writer.Write(argv[1], argv[2])
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/y2016/control_loops/python/shoulder.py b/y2016/control_loops/python/shoulder.py
new file mode 100755
index 0000000..554228e
--- /dev/null
+++ b/y2016/control_loops/python/shoulder.py
@@ -0,0 +1,273 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+from frc971.control_loops.python import polytope
+from y2016.control_loops.python import polydrivetrain
+import numpy
+import sys
+import matplotlib
+from matplotlib import pylab
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+try:
+ gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+except gflags.DuplicateFlagError:
+ pass
+
+class Shoulder(control_loop.ControlLoop):
+ def __init__(self, name="Shoulder", mass=None):
+ super(Shoulder, self).__init__(name)
+ # TODO(constants): Update all of these & retune poles.
+ # Stall Torque in N m
+ self.stall_torque = 0.71
+ # Stall Current in Amps
+ self.stall_current = 134
+ # Free Speed in RPM
+ self.free_speed = 18730
+ # Free Current in Amps
+ self.free_current = 0.7
+
+ # Resistance of the motor
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Gear ratio
+ self.G = (56.0 / 12.0) * (64.0 / 14.0) * (72.0 / 18.0) * (58.0 / 16.0)
+
+ self.J = 3.0
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # State is [position, velocity]
+ # Input is [Voltage]
+
+ C1 = self.G * self.G * self.Kt / (self.R * self.J * self.Kv)
+ C2 = self.Kt * self.G / (self.J * self.R)
+
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -C1]])
+
+ # Start with the unmodified input
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [C2]])
+
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ controllability = controls.ctrb(self.A, self.B)
+
+ q_pos = 0.14
+ q_vel = 4.5
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ print 'K', self.K
+ print 'Poles are', numpy.linalg.eig(self.A - self.B * self.K)[0]
+
+ q_pos = 0.05
+ q_vel = 2.65
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
+ [0.0, (q_vel ** 2.0)]])
+
+ r_volts = 0.025
+ self.R = numpy.matrix([[(r_volts ** 2.0)]])
+
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+
+ print 'Kal', self.KalmanGain
+ self.L = self.A * self.KalmanGain
+ print 'KalL is', self.L
+
+ # The box formed by U_min and U_max must encompass all possible values,
+ # or else Austin's code gets angry.
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+class IntegralShoulder(Shoulder):
+ def __init__(self, name="IntegralShoulder"):
+ super(IntegralShoulder, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.08
+ q_vel = 4.00
+ q_voltage = 6.0
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.05
+ self.R = numpy.matrix([[(r_pos ** 2.0)]])
+
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+ self.L = self.A * self.KalmanGain
+
+ self.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+
+ self.InitializeState()
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, shoulder, goal, iterations=200, controller_shoulder=None,
+ observer_shoulder=None):
+ """Runs the shoulder plant with an initial condition and goal.
+
+ Test for whether the goal has been reached and whether the separation
+ goes outside of the initial and goal values by more than
+ max_separation_error.
+
+ Prints out something for a failure of either condition and returns
+ False if tests fail.
+ Args:
+ shoulder: shoulder object to use.
+ goal: goal state.
+ iterations: Number of timesteps to run the model for.
+ controller_shoulder: Shoulder object to get K from, or None if we should
+ use shoulder.
+ observer_shoulder: Shoulder object to use for the observer, or None if we should
+ use the actual state.
+ """
+
+ if controller_shoulder is None:
+ controller_shoulder = shoulder
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + shoulder.dt
+ else:
+ initial_t = 0
+
+ for i in xrange(iterations):
+ X_hat = shoulder.X
+
+ if observer_shoulder is not None:
+ X_hat = observer_shoulder.X_hat
+ self.x_hat.append(observer_shoulder.X_hat[0, 0])
+
+ U = controller_shoulder.K * (goal - X_hat)
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(shoulder.X[0, 0])
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(shoulder.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / shoulder.dt)
+
+ if observer_shoulder is not None:
+ observer_shoulder.Y = shoulder.Y
+ observer_shoulder.CorrectObserver(U)
+ self.offset.append(observer_shoulder.X_hat[2, 0])
+
+ shoulder.Update(U + 2.0)
+
+ if observer_shoulder is not None:
+ observer_shoulder.PredictObserver(U)
+
+ self.t.append(initial_t + i * shoulder.dt)
+ self.u.append(U[0, 0])
+
+ glog.debug('Time: %f', self.t[-1])
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.x, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ argv = FLAGS(argv)
+
+ scenario_plotter = ScenarioPlotter()
+
+ shoulder = Shoulder()
+ shoulder_controller = IntegralShoulder()
+ observer_shoulder = IntegralShoulder()
+
+ # Test moving the shoulder with constant separation.
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[numpy.pi / 2.0], [0.0], [0.0]])
+ scenario_plotter.run_test(shoulder, goal=R, controller_shoulder=shoulder_controller,
+ observer_shoulder=observer_shoulder, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ # Write the generated constants out to a file.
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name for the shoulder and integral shoulder.')
+ else:
+ namespaces = ['y2016', 'control_loops', 'superstructure']
+ shoulder = Shoulder("Shoulder")
+ loop_writer = control_loop.ControlLoopWriter('Shoulder', [shoulder],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_shoulder = IntegralShoulder("IntegralShoulder")
+ integral_loop_writer = control_loop.ControlLoopWriter("IntegralShoulder", [integral_shoulder],
+ namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/y2016/control_loops/python/wrist.py b/y2016/control_loops/python/wrist.py
new file mode 100755
index 0000000..79a115e
--- /dev/null
+++ b/y2016/control_loops/python/wrist.py
@@ -0,0 +1,273 @@
+#!/usr/bin/python
+
+from frc971.control_loops.python import control_loop
+from frc971.control_loops.python import controls
+from frc971.control_loops.python import polytope
+from y2016.control_loops.python import polydrivetrain
+import numpy
+import sys
+import matplotlib
+from matplotlib import pylab
+import gflags
+import glog
+
+FLAGS = gflags.FLAGS
+
+try:
+ gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
+except gflags.DuplicateFlagError:
+ pass
+
+class Wrist(control_loop.ControlLoop):
+ def __init__(self, name="Wrist"):
+ super(Wrist, self).__init__(name)
+ # TODO(constants): Update all of these & retune poles.
+ # Stall Torque in N m
+ self.stall_torque = 0.71
+ # Stall Current in Amps
+ self.stall_current = 134
+ # Free Speed in RPM
+ self.free_speed = 18730
+ # Free Current in Amps
+ self.free_current = 0.7
+
+ # Resistance of the motor
+ self.R = 12.0 / self.stall_current
+ # Motor velocity constant
+ self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
+ (12.0 - self.R * self.free_current))
+ # Torque constant
+ self.Kt = self.stall_torque / self.stall_current
+ # Gear ratio
+ self.G = (56.0 / 12.0) * (54.0 / 14.0) * (64.0 / 18.0) * (48.0 / 16.0)
+
+ self.J = 0.15
+
+ # Control loop time step
+ self.dt = 0.005
+
+ # State is [position, velocity]
+ # Input is [Voltage]
+
+ C1 = self.G * self.G * self.Kt / (self.R * self.J * self.Kv)
+ C2 = self.Kt * self.G / (self.J * self.R)
+
+ self.A_continuous = numpy.matrix(
+ [[0, 1],
+ [0, -C1]])
+
+ # Start with the unmodified input
+ self.B_continuous = numpy.matrix(
+ [[0],
+ [C2]])
+
+ self.C = numpy.matrix([[1, 0]])
+ self.D = numpy.matrix([[0]])
+
+ self.A, self.B = self.ContinuousToDiscrete(
+ self.A_continuous, self.B_continuous, self.dt)
+
+ controllability = controls.ctrb(self.A, self.B)
+
+ q_pos = 0.20
+ q_vel = 8.0
+ self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
+ [0.0, (1.0 / (q_vel ** 2.0))]])
+
+ self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
+ self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
+
+ print 'K', self.K
+ print 'Poles are', numpy.linalg.eig(self.A - self.B * self.K)[0]
+
+ q_pos = 0.05
+ q_vel = 2.65
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
+ [0.0, (q_vel ** 2.0)]])
+
+ r_volts = 0.025
+ self.R = numpy.matrix([[(r_volts ** 2.0)]])
+
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+
+ print 'Kal', self.KalmanGain
+ self.L = self.A * self.KalmanGain
+ print 'KalL is', self.L
+
+ # The box formed by U_min and U_max must encompass all possible values,
+ # or else Austin's code gets angry.
+ self.U_max = numpy.matrix([[12.0]])
+ self.U_min = numpy.matrix([[-12.0]])
+
+ self.InitializeState()
+
+class IntegralWrist(Wrist):
+ def __init__(self, name="IntegralWrist"):
+ super(IntegralWrist, self).__init__(name=name)
+
+ self.A_continuous_unaugmented = self.A_continuous
+ self.B_continuous_unaugmented = self.B_continuous
+
+ self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
+ self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
+ self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
+
+ self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
+ self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
+
+ self.C_unaugmented = self.C
+ self.C = numpy.matrix(numpy.zeros((1, 3)))
+ self.C[0:1, 0:2] = self.C_unaugmented
+
+ self.A, self.B = self.ContinuousToDiscrete(self.A_continuous, self.B_continuous, self.dt)
+
+ q_pos = 0.08
+ q_vel = 4.00
+ q_voltage = 1.5
+ self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
+ [0.0, (q_vel ** 2.0), 0.0],
+ [0.0, 0.0, (q_voltage ** 2.0)]])
+
+ r_pos = 0.05
+ self.R = numpy.matrix([[(r_pos ** 2.0)]])
+
+ self.KalmanGain, self.Q_steady = controls.kalman(
+ A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
+ self.L = self.A * self.KalmanGain
+
+ self.K_unaugmented = self.K
+ self.K = numpy.matrix(numpy.zeros((1, 3)))
+ self.K[0, 0:2] = self.K_unaugmented
+ self.K[0, 2] = 1
+
+ self.InitializeState()
+
+class ScenarioPlotter(object):
+ def __init__(self):
+ # Various lists for graphing things.
+ self.t = []
+ self.x = []
+ self.v = []
+ self.a = []
+ self.x_hat = []
+ self.u = []
+ self.offset = []
+
+ def run_test(self, wrist, goal, iterations=200, controller_wrist=None,
+ observer_wrist=None):
+ """Runs the wrist plant with an initial condition and goal.
+
+ Test for whether the goal has been reached and whether the separation
+ goes outside of the initial and goal values by more than
+ max_separation_error.
+
+ Prints out something for a failure of either condition and returns
+ False if tests fail.
+ Args:
+ wrist: wrist object to use.
+ goal: goal state.
+ iterations: Number of timesteps to run the model for.
+ controller_wrist: Wrist object to get K from, or None if we should
+ use wrist.
+ observer_wrist: Wrist object to use for the observer, or None if we should
+ use the actual state.
+ """
+
+ if controller_wrist is None:
+ controller_wrist = wrist
+
+ vbat = 12.0
+
+ if self.t:
+ initial_t = self.t[-1] + wrist.dt
+ else:
+ initial_t = 0
+
+ for i in xrange(iterations):
+ X_hat = wrist.X
+
+ if observer_wrist is not None:
+ X_hat = observer_wrist.X_hat
+ self.x_hat.append(observer_wrist.X_hat[0, 0])
+
+ U = controller_wrist.K * (goal - X_hat)
+ U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
+ self.x.append(wrist.X[0, 0])
+
+ if self.v:
+ last_v = self.v[-1]
+ else:
+ last_v = 0
+
+ self.v.append(wrist.X[1, 0])
+ self.a.append((self.v[-1] - last_v) / wrist.dt)
+
+ if observer_wrist is not None:
+ observer_wrist.Y = wrist.Y
+ observer_wrist.CorrectObserver(U)
+ self.offset.append(observer_wrist.X_hat[2, 0])
+
+ wrist.Update(U + 2.0)
+
+ if observer_wrist is not None:
+ observer_wrist.PredictObserver(U)
+
+ self.t.append(initial_t + i * wrist.dt)
+ self.u.append(U[0, 0])
+
+ glog.debug('Time: %f', self.t[-1])
+
+ def Plot(self):
+ pylab.subplot(3, 1, 1)
+ pylab.plot(self.t, self.x, label='x')
+ pylab.plot(self.t, self.x_hat, label='x_hat')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 2)
+ pylab.plot(self.t, self.u, label='u')
+ pylab.plot(self.t, self.offset, label='voltage_offset')
+ pylab.legend()
+
+ pylab.subplot(3, 1, 3)
+ pylab.plot(self.t, self.a, label='a')
+ pylab.legend()
+
+ pylab.show()
+
+
+def main(argv):
+ argv = FLAGS(argv)
+
+ scenario_plotter = ScenarioPlotter()
+
+ wrist = Wrist()
+ wrist_controller = IntegralWrist()
+ observer_wrist = IntegralWrist()
+
+ # Test moving the wrist with constant separation.
+ initial_X = numpy.matrix([[0.0], [0.0]])
+ R = numpy.matrix([[1.0], [0.0], [0.0]])
+ scenario_plotter.run_test(wrist, goal=R, controller_wrist=wrist_controller,
+ observer_wrist=observer_wrist, iterations=200)
+
+ if FLAGS.plot:
+ scenario_plotter.Plot()
+
+ # Write the generated constants out to a file.
+ if len(argv) != 5:
+ glog.fatal('Expected .h file name and .cc file name for the wrist and integral wrist.')
+ else:
+ namespaces = ['y2016', 'control_loops', 'superstructure']
+ wrist = Wrist("Wrist")
+ loop_writer = control_loop.ControlLoopWriter('Wrist', [wrist],
+ namespaces=namespaces)
+ loop_writer.Write(argv[1], argv[2])
+
+ integral_wrist = IntegralWrist("IntegralWrist")
+ integral_loop_writer = control_loop.ControlLoopWriter("IntegralWrist", [integral_wrist],
+ namespaces=namespaces)
+ integral_loop_writer.Write(argv[3], argv[4])
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/y2016/control_loops/shooter/BUILD b/y2016/control_loops/shooter/BUILD
new file mode 100644
index 0000000..cb3c0bc
--- /dev/null
+++ b/y2016/control_loops/shooter/BUILD
@@ -0,0 +1,83 @@
+package(default_visibility = ['//visibility:public'])
+
+load('/aos/build/queues', 'queue_library')
+
+queue_library(
+ name = 'shooter_queue',
+ srcs = [
+ 'shooter.q',
+ ],
+ deps = [
+ '//aos/common/controls:control_loop_queues',
+ '//frc971/control_loops:queues',
+ ],
+)
+
+genrule(
+ name = 'genrule_shooter',
+ visibility = ['//visibility:private'],
+ cmd = '$(location //y2016/control_loops/python:shooter) $(OUTS)',
+ tools = [
+ '//y2016/control_loops/python:shooter',
+ ],
+ outs = [
+ 'shooter_plant.h',
+ 'shooter_plant.cc',
+ ],
+)
+
+cc_library(
+ name = 'shooter_plants',
+ srcs = [
+ 'shooter_plant.cc',
+ ],
+ hdrs = [
+ 'shooter_plant.h',
+ ],
+ deps = [
+ '//frc971/control_loops:state_feedback_loop',
+ ],
+)
+
+cc_library(
+ name = 'shooter_lib',
+ srcs = [
+ 'shooter.cc',
+ ],
+ hdrs = [
+ 'shooter.h',
+ ],
+ deps = [
+ ':shooter_queue',
+ ':shooter_plants',
+ '//aos/common/controls:control_loop',
+ ],
+)
+
+cc_test(
+ name = 'shooter_lib_test',
+ srcs = [
+ 'shooter_lib_test.cc',
+ ],
+ deps = [
+ ':shooter_queue',
+ ':shooter_lib',
+ '//aos/testing:googletest',
+ '//aos/common:queues',
+ '//aos/common/controls:control_loop_test',
+ '//frc971/control_loops:state_feedback_loop',
+ '//frc971/control_loops:team_number_test_environment',
+ ],
+)
+
+cc_binary(
+ name = 'shooter',
+ srcs = [
+ 'shooter_main.cc',
+ ],
+ deps = [
+ '//aos/linux_code:init',
+ ':shooter_lib',
+ ':shooter_queue',
+ ],
+)
diff --git a/y2016/control_loops/shooter/shooter.cc b/y2016/control_loops/shooter/shooter.cc
new file mode 100644
index 0000000..9a46906
--- /dev/null
+++ b/y2016/control_loops/shooter/shooter.cc
@@ -0,0 +1,137 @@
+#include "y2016/control_loops/shooter/shooter.h"
+
+#include "aos/common/controls/control_loops.q.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/logging/queue_logging.h"
+
+#include "y2016/control_loops/shooter/shooter_plant.h"
+
+
+namespace y2016 {
+namespace control_loops {
+
+ShooterSide::ShooterSide()
+ : loop_(new StateFeedbackLoop<2, 1, 1>(
+ ::y2016::control_loops::shooter::MakeShooterLoop())) {
+ memset(history_, 0, sizeof(history_));
+}
+
+void ShooterSide::SetGoal(double angular_velocity_goal_uncapped) {
+ angular_velocity_goal_ = std::min(angular_velocity_goal_uncapped,
+ kMaxSpeed);
+}
+
+void ShooterSide::EstimatePositionTimestep() {
+ // NULL position, so look at the loop.
+ SetPosition(loop_->X_hat(0, 0));
+}
+
+void ShooterSide::SetPosition(double current_position) {
+ current_position_ = current_position;
+
+ // Track the current position if the velocity goal is small.
+ if (angular_velocity_goal_ <= 1.0) position_goal_ = current_position_;
+
+ // Update position in the model.
+ Eigen::Matrix<double, 1, 1> Y;
+ Y << current_position_;
+ loop_->Correct(Y);
+
+ // Prevents integral windup by limiting the position error such that the
+ // error can't produce much more than full power.
+ const double max_reference =
+ (loop_->U_max(0, 0) -
+ kAngularVelocityWeightScalar *
+ (angular_velocity_goal_ - loop_->X_hat(1, 0)) * loop_->K(0, 1)) /
+ loop_->K(0, 0) +
+ loop_->X_hat(0, 0);
+ const double min_reference =
+ (loop_->U_min(0, 0) -
+ kAngularVelocityWeightScalar *
+ (angular_velocity_goal_ - loop_->X_hat(1, 0)) * loop_->K(0, 1)) /
+ loop_->K(0, 0) +
+ loop_->X_hat(0, 0);
+ position_goal_ =
+ ::std::max(::std::min(position_goal_, max_reference), min_reference);
+
+ loop_->mutable_R() << position_goal_, angular_velocity_goal_;
+ position_goal_ +=
+ angular_velocity_goal_ * ::aos::controls::kLoopFrequency.ToSeconds();
+
+ // Add the position to the history.
+ history_[history_position_] = current_position_;
+ history_position_ = (history_position_ + 1) % kHistoryLength;
+}
+
+const ShooterStatus ShooterSide::GetStatus() {
+ // Calculate average over dt * kHistoryLength.
+ int old_history_position =
+ ((history_position_ == 0) ? kHistoryLength : history_position_) - 1;
+ double avg_angular_velocity =
+ (history_[old_history_position] - history_[history_position_]) /
+ ::aos::controls::kLoopFrequency.ToSeconds() /
+ static_cast<double>(kHistoryLength - 1);
+
+ // Ready if average angular velocity is close to the goal.
+ bool ready = (std::abs(angular_velocity_goal_ - avg_angular_velocity) <
+ kTolerance &&
+ angular_velocity_goal_ != 0.0);
+
+ return {avg_angular_velocity, ready};
+}
+
+double ShooterSide::GetOutput() {
+ if (angular_velocity_goal_ < 1.0) {
+ // Kill power at low angular velocities.
+ return 0.0;
+ }
+
+ return loop_->U(0, 0);
+}
+
+void ShooterSide::UpdateLoop(bool output_is_null) {
+ loop_->Update(output_is_null);
+}
+
+Shooter::Shooter(control_loops::ShooterQueue *my_shooter)
+ : aos::controls::ControlLoop<control_loops::ShooterQueue>(my_shooter) {}
+
+void Shooter::RunIteration(
+ const control_loops::ShooterQueue::Goal *goal,
+ const control_loops::ShooterQueue::Position *position,
+ control_loops::ShooterQueue::Output *output,
+ control_loops::ShooterQueue::Status *status) {
+ if (goal) {
+ // Update position/goal for our two shooter sides.
+ left_.SetGoal(goal->angular_velocity_left);
+ right_.SetGoal(goal->angular_velocity_right);
+
+ if (position == nullptr) {
+ left_.EstimatePositionTimestep();
+ right_.EstimatePositionTimestep();
+ } else {
+ left_.SetPosition(position->theta_left);
+ right_.SetPosition(position->theta_right);
+ }
+ }
+
+ ShooterStatus status_left = left_.GetStatus();
+ ShooterStatus status_right = right_.GetStatus();
+ status->avg_angular_velocity_left = status_left.avg_angular_velocity;
+ status->avg_angular_velocity_right = status_right.avg_angular_velocity;
+
+ status->ready_left = status_left.ready;
+ status->ready_right = status_right.ready;
+ status->ready_both = (status_left.ready && status_right.ready);
+
+ left_.UpdateLoop(output == nullptr);
+ right_.UpdateLoop(output == nullptr);
+
+ if (output) {
+ output->voltage_left = left_.GetOutput();
+ output->voltage_right = right_.GetOutput();
+ }
+}
+
+} // namespace control_loops
+} // namespace y2016
diff --git a/y2016/control_loops/shooter/shooter.h b/y2016/control_loops/shooter/shooter.h
new file mode 100644
index 0000000..6a3fa4d
--- /dev/null
+++ b/y2016/control_loops/shooter/shooter.h
@@ -0,0 +1,74 @@
+#ifndef Y2016_CONTROL_LOOPS_SHOOTER_SHOOTER_H_
+#define Y2016_CONTROL_LOOPS_SHOOTER_SHOOTER_H_
+
+#include <memory>
+
+#include "aos/common/controls/control_loop.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+#include "y2016/control_loops/shooter/shooter_plant.h"
+#include "y2016/control_loops/shooter/shooter.q.h"
+
+namespace y2016 {
+namespace control_loops {
+
+namespace {
+// TODO(constants): Update.
+const double kTolerance = 10.0;
+const double kMaxSpeed = 10000.0 * (2.0 * M_PI) / 60.0 * 15.0 / 34.0;
+const double kAngularVelocityWeightScalar = 0.35;
+} // namespace
+
+struct ShooterStatus {
+ double avg_angular_velocity;
+ bool ready;
+};
+
+class ShooterSide {
+ public:
+ ShooterSide();
+
+ void SetGoal(double angular_velocity_goal);
+ void EstimatePositionTimestep();
+ void SetPosition(double current_position);
+ const ShooterStatus GetStatus();
+ double GetOutput();
+ void UpdateLoop(bool output_is_null);
+
+ private:
+ ::std::unique_ptr<StateFeedbackLoop<2, 1, 1>> loop_;
+
+ double current_position_ = 0.0;
+ double position_goal_ = 0.0;
+ double angular_velocity_goal_ = 0.0;
+
+ // History array for calculating a filtered angular velocity.
+ static const int kHistoryLength = 5;
+ double history_[kHistoryLength];
+ ptrdiff_t history_position_;
+
+ DISALLOW_COPY_AND_ASSIGN(ShooterSide);
+};
+
+class Shooter
+ : public ::aos::controls::ControlLoop<control_loops::ShooterQueue> {
+ public:
+ explicit Shooter(control_loops::ShooterQueue *shooter_queue =
+ &control_loops::shooter_queue);
+
+ protected:
+ void RunIteration(const control_loops::ShooterQueue::Goal *goal,
+ const control_loops::ShooterQueue::Position *position,
+ control_loops::ShooterQueue::Output *output,
+ control_loops::ShooterQueue::Status *status) override;
+
+ private:
+ ShooterSide left_, right_;
+
+ DISALLOW_COPY_AND_ASSIGN(Shooter);
+};
+
+} // namespace control_loops
+} // namespace y2016
+
+#endif // Y2016_CONTROL_LOOPS_SHOOTER_SHOOTER_H_
diff --git a/y2016/control_loops/shooter/shooter.q b/y2016/control_loops/shooter/shooter.q
new file mode 100644
index 0000000..49575fb
--- /dev/null
+++ b/y2016/control_loops/shooter/shooter.q
@@ -0,0 +1,46 @@
+package y2016.control_loops;
+
+import "aos/common/controls/control_loops.q";
+import "frc971/control_loops/control_loops.q";
+
+queue_group ShooterQueue {
+ implements aos.control_loops.ControlLoop;
+
+ // All angles are in radians, and angular velocities are in rad/sec. For all
+ // angular velocities, positive is shooting the ball out of the robot.
+
+ message Goal {
+ // Angular velocity goals in rad/sec.
+ double angular_velocity_left;
+ double angular_velocity_right;
+ };
+
+ message Position {
+ // Wheel angle in rad/sec.
+ double theta_left;
+ double theta_right;
+ };
+
+ message Status {
+ bool ready_left;
+ bool ready_right;
+ // Is the shooter ready to shoot?
+ bool ready_both;
+
+ // Average angular velocities over dt * kHistoryLength.
+ double avg_angular_velocity_left;
+ double avg_angular_velocity_right;
+ };
+
+ message Output {
+ double voltage_left;
+ double voltage_right;
+ };
+
+ queue Goal goal;
+ queue Position position;
+ queue Output output;
+ queue Status status;
+};
+
+queue_group ShooterQueue shooter_queue;
diff --git a/y2016/control_loops/shooter/shooter_lib_test.cc b/y2016/control_loops/shooter/shooter_lib_test.cc
new file mode 100644
index 0000000..9ec0334
--- /dev/null
+++ b/y2016/control_loops/shooter/shooter_lib_test.cc
@@ -0,0 +1,263 @@
+#include "y2016/control_loops/shooter/shooter.h"
+
+#include <unistd.h>
+
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "aos/common/queue.h"
+#include "aos/common/controls/control_loop_test.h"
+#include "frc971/control_loops/team_number_test_environment.h"
+#include "y2016/control_loops/shooter/shooter.q.h"
+#include "y2016/control_loops/shooter/shooter.h"
+
+using ::aos::time::Time;
+using ::frc971::control_loops::testing::kTeamNumber;
+
+namespace y2016 {
+namespace control_loops {
+namespace testing {
+
+// Class which simulates the shooter and sends out queue messages with the
+// position.
+class ShooterSimulation {
+ public:
+ // Constructs a shooter simulation.
+ ShooterSimulation()
+ : shooter_plant_left_(new StateFeedbackPlant<2, 1, 1>(
+ ::y2016::control_loops::shooter::MakeShooterPlant())),
+ shooter_plant_right_(new StateFeedbackPlant<2, 1, 1>(
+ ::y2016::control_loops::shooter::MakeShooterPlant())),
+ shooter_queue_(".y2016.control_loops.shooter", 0x78d8e372,
+ ".y2016.control_loops.shooter.goal",
+ ".y2016.control_loops.shooter.position",
+ ".y2016.control_loops.shooter.output",
+ ".y2016.control_loops.shooter.status") {}
+
+ // Sends a queue message with the position of the shooter.
+ void SendPositionMessage() {
+ ::aos::ScopedMessagePtr<control_loops::ShooterQueue::Position> position =
+ shooter_queue_.position.MakeMessage();
+
+ position->theta_left = shooter_plant_left_->Y(0, 0);
+ position->theta_right = shooter_plant_right_->Y(0, 0);
+ position.Send();
+ }
+
+ // Simulates shooter for a single timestep.
+ void Simulate() {
+ EXPECT_TRUE(shooter_queue_.output.FetchLatest());
+
+ shooter_plant_left_->mutable_U(0, 0) = shooter_queue_.output->voltage_left;
+ shooter_plant_right_->mutable_U(0, 0) =
+ shooter_queue_.output->voltage_right;
+
+ shooter_plant_left_->Update();
+ shooter_plant_right_->Update();
+ }
+
+ ::std::unique_ptr<StateFeedbackPlant<2, 1, 1>> shooter_plant_left_,
+ shooter_plant_right_;
+
+ private:
+ ShooterQueue shooter_queue_;
+};
+
+class ShooterTest : public ::aos::testing::ControlLoopTest {
+ protected:
+ ShooterTest()
+ : shooter_queue_(".y2016.control_loops.shooter", 0x78d8e372,
+ ".y2016.control_loops.shooter.goal",
+ ".y2016.control_loops.shooter.position",
+ ".y2016.control_loops.shooter.output",
+ ".y2016.control_loops.shooter.status"),
+ shooter_(&shooter_queue_),
+ shooter_plant_() {
+ set_team_id(kTeamNumber);
+ }
+
+ void VerifyNearGoal() {
+ shooter_queue_.goal.FetchLatest();
+ shooter_queue_.status.FetchLatest();
+
+ EXPECT_TRUE(shooter_queue_.goal.get() != nullptr);
+ EXPECT_TRUE(shooter_queue_.status.get() != nullptr);
+
+ EXPECT_NEAR(shooter_queue_.goal->angular_velocity_left,
+ shooter_queue_.status->avg_angular_velocity_left, 10.0);
+ EXPECT_NEAR(shooter_queue_.goal->angular_velocity_right,
+ shooter_queue_.status->avg_angular_velocity_right, 10.0);
+ }
+
+ // Runs one iteration of the whole simulation.
+ void RunIteration(bool enabled = true) {
+ SendMessages(enabled);
+
+ shooter_plant_.SendPositionMessage();
+ shooter_.Iterate();
+ shooter_plant_.Simulate();
+
+ TickTime();
+ }
+
+ // Runs iterations until the specified amount of simulated time has elapsed.
+ void RunForTime(const Time &run_for, bool enabled = true) {
+ const auto start_time = Time::Now();
+ while (Time::Now() < start_time + run_for) {
+ RunIteration(enabled);
+ }
+ }
+
+ // Create a new instance of the test queue so that it invalidates the queue
+ // that it points to. Otherwise, we will have a pointer to shared memory that
+ // is no longer valid.
+ ShooterQueue shooter_queue_;
+
+ // Create a control loop and simulation.
+ Shooter shooter_;
+ ShooterSimulation shooter_plant_;
+};
+
+// Tests that the shooter does nothing when the goal is zero.
+TEST_F(ShooterTest, DoesNothing) {
+ ASSERT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(0.0)
+ .angular_velocity_right(0.0)
+ .Send());
+ RunIteration();
+
+ VerifyNearGoal();
+
+ EXPECT_TRUE(shooter_queue_.output.FetchLatest());
+ EXPECT_EQ(shooter_queue_.output->voltage_left, 0.0);
+ EXPECT_EQ(shooter_queue_.output->voltage_right, 0.0);
+}
+
+// Tests that the shooter spins up to speed and that it then spins down
+// without applying any power.
+TEST_F(ShooterTest, SpinUpAndDown) {
+ // Spin up.
+ EXPECT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(450.0)
+ .angular_velocity_right(450.0)
+ .Send());
+ RunForTime(Time::InSeconds(10));
+ VerifyNearGoal();
+ EXPECT_TRUE(shooter_queue_.status->ready_both);
+ EXPECT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(0.0)
+ .angular_velocity_right(0.0)
+ .Send());
+
+ // Make sure we don't apply voltage on spin-down.
+ RunIteration();
+ EXPECT_TRUE(shooter_queue_.output.FetchLatest());
+ EXPECT_EQ(0.0, shooter_queue_.output->voltage_left);
+ EXPECT_EQ(0.0, shooter_queue_.output->voltage_right);
+
+ // Continue to stop.
+ RunForTime(Time::InSeconds(5));
+ EXPECT_TRUE(shooter_queue_.output.FetchLatest());
+ EXPECT_EQ(0.0, shooter_queue_.output->voltage_left);
+ EXPECT_EQ(0.0, shooter_queue_.output->voltage_right);
+}
+
+// Tests that the shooter doesn't say it is ready if one side isn't up to speed.
+// According to our tuning, we may overshoot the goal on one shooter and
+// mistakenly say that we are ready. This test should look at both extremes.
+TEST_F(ShooterTest, SideLagTest) {
+ // Spin up.
+ EXPECT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(20.0)
+ .angular_velocity_right(450.0)
+ .Send());
+ RunForTime(Time::InSeconds(0.1));
+
+ shooter_queue_.goal.FetchLatest();
+ shooter_queue_.status.FetchLatest();
+
+ EXPECT_TRUE(shooter_queue_.goal.get() != nullptr);
+ EXPECT_TRUE(shooter_queue_.status.get() != nullptr);
+
+ // Left should be up to speed, right shouldn't.
+ EXPECT_TRUE(shooter_queue_.status->ready_left);
+ EXPECT_FALSE(shooter_queue_.status->ready_right);
+ EXPECT_FALSE(shooter_queue_.status->ready_both);
+
+ RunForTime(Time::InSeconds(5));
+
+ shooter_queue_.goal.FetchLatest();
+ shooter_queue_.status.FetchLatest();
+
+ EXPECT_TRUE(shooter_queue_.goal.get() != nullptr);
+ EXPECT_TRUE(shooter_queue_.status.get() != nullptr);
+
+ // Both should be up to speed.
+ EXPECT_TRUE(shooter_queue_.status->ready_left);
+ EXPECT_TRUE(shooter_queue_.status->ready_right);
+ EXPECT_TRUE(shooter_queue_.status->ready_both);
+}
+
+// Test to make sure that it does not exceed the encoder's rated speed.
+TEST_F(ShooterTest, RateLimitTest) {
+ ASSERT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(1000.0)
+ .angular_velocity_right(1000.0)
+ .Send());
+
+ RunForTime(Time::InSeconds(10));
+ EXPECT_TRUE(shooter_queue_.status.FetchLatest());
+ EXPECT_TRUE(shooter_queue_.status->ready_both);
+
+ shooter_queue_.goal.FetchLatest();
+ shooter_queue_.status.FetchLatest();
+
+ EXPECT_TRUE(shooter_queue_.goal.get() != nullptr);
+ EXPECT_TRUE(shooter_queue_.status.get() != nullptr);
+
+ EXPECT_GT(::y2016::control_loops::kMaxSpeed,
+ shooter_queue_.status->avg_angular_velocity_left);
+
+ EXPECT_GT(::y2016::control_loops::kMaxSpeed,
+ shooter_queue_.status->avg_angular_velocity_right);
+}
+
+// Tests that the shooter can spin up nicely while missing position packets.
+TEST_F(ShooterTest, MissingPositionMessages) {
+ ASSERT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(200.0)
+ .angular_velocity_right(200.0)
+ .Send());
+ for (int i = 0; i < 100; ++i) {
+ if (i % 7) {
+ shooter_plant_.SendPositionMessage();
+ }
+
+ RunIteration();
+ }
+
+ VerifyNearGoal();
+}
+
+// Tests that the shooter can spin up nicely while disabled for a while.
+// TODO(comran): Update this test, since it's the same as
+// MissingPositionMessages.
+TEST_F(ShooterTest, Disabled) {
+ ASSERT_TRUE(shooter_queue_.goal.MakeWithBuilder()
+ .angular_velocity_left(200.0)
+ .angular_velocity_right(200.0)
+ .Send());
+ for (int i = 0; i < 100; ++i) {
+ if (i % 7) {
+ shooter_plant_.SendPositionMessage();
+ }
+
+ RunIteration();
+ }
+
+ VerifyNearGoal();
+}
+
+} // namespace testing
+} // namespace control_loops
+} // namespace y2016
diff --git a/y2016/control_loops/shooter/shooter_main.cc b/y2016/control_loops/shooter/shooter_main.cc
new file mode 100644
index 0000000..911ab29
--- /dev/null
+++ b/y2016/control_loops/shooter/shooter_main.cc
@@ -0,0 +1,11 @@
+#include "y2016/control_loops/shooter/shooter.h"
+
+#include "aos/linux_code/init.h"
+
+int main() {
+ ::aos::Init();
+ ::y2016::control_loops::Shooter shooter;
+ shooter.Run();
+ ::aos::Cleanup();
+ return 0;
+}
diff --git a/y2016/control_loops/superstructure/BUILD b/y2016/control_loops/superstructure/BUILD
new file mode 100644
index 0000000..183c3c0
--- /dev/null
+++ b/y2016/control_loops/superstructure/BUILD
@@ -0,0 +1,123 @@
+package(default_visibility = ['//visibility:public'])
+
+load('/aos/build/queues', 'queue_library')
+
+queue_library(
+ name = 'superstructure_queue',
+ srcs = [
+ 'superstructure.q',
+ ],
+ deps = [
+ '//aos/common/controls:control_loop_queues',
+ '//frc971/control_loops:queues',
+ ],
+)
+
+genrule(
+ name = 'genrule_intake',
+ visibility = ['//visibility:private'],
+ cmd = '$(location //y2016/control_loops/python:intake) $(OUTS)',
+ tools = [
+ '//y2016/control_loops/python:intake',
+ ],
+ outs = [
+ 'intake_plant.h',
+ 'intake_plant.cc',
+ 'integral_intake_plant.h',
+ 'integral_intake_plant.cc',
+ ],
+)
+
+genrule(
+ name = 'genrule_shoulder',
+ visibility = ['//visibility:private'],
+ cmd = '$(location //y2016/control_loops/python:shoulder) $(OUTS)',
+ tools = [
+ '//y2016/control_loops/python:shoulder',
+ ],
+ outs = [
+ 'shoulder_plant.h',
+ 'shoulder_plant.cc',
+ 'integral_shoulder_plant.h',
+ 'integral_shoulder_plant.cc',
+ ],
+)
+
+genrule(
+ name = 'genrule_wrist',
+ visibility = ['//visibility:private'],
+ cmd = '$(location //y2016/control_loops/python:wrist) $(OUTS)',
+ tools = [
+ '//y2016/control_loops/python:wrist',
+ ],
+ outs = [
+ 'wrist_plant.h',
+ 'wrist_plant.cc',
+ 'integral_wrist_plant.h',
+ 'integral_wrist_plant.cc',
+ ],
+)
+
+cc_library(
+ name = 'superstructure_plants',
+ srcs = [
+ 'intake_plant.cc',
+ 'shoulder_plant.cc',
+ 'wrist_plant.cc',
+ 'integral_intake_plant.cc',
+ 'integral_shoulder_plant.cc',
+ 'integral_wrist_plant.cc',
+ ],
+ hdrs = [
+ 'intake_plant.h',
+ 'shoulder_plant.h',
+ 'wrist_plant.h',
+ 'integral_intake_plant.h',
+ 'integral_shoulder_plant.h',
+ 'integral_wrist_plant.h',
+ ],
+ deps = [
+ '//frc971/control_loops:state_feedback_loop',
+ ],
+)
+
+cc_library(
+ name = 'superstructure_lib',
+ srcs = [
+ 'superstructure.cc',
+ ],
+ hdrs = [
+ 'superstructure.h',
+ ],
+ deps = [
+ ':superstructure_queue',
+ '//aos/common/controls:control_loop',
+ '//frc971/control_loops:state_feedback_loop',
+ ],
+)
+
+cc_test(
+ name = 'superstructure_lib_test',
+ srcs = [
+ 'superstructure_lib_test.cc',
+ ],
+ deps = [
+ ':superstructure_queue',
+ ':superstructure_lib',
+ '//aos/testing:googletest',
+ '//aos/common:queues',
+ '//aos/common/controls:control_loop_test',
+ ],
+)
+
+cc_binary(
+ name = 'superstructure',
+ srcs = [
+ 'superstructure_main.cc',
+ ],
+ deps = [
+ '//aos/linux_code:init',
+ ':superstructure_lib',
+ ':superstructure_queue',
+ ],
+)
diff --git a/y2016/control_loops/superstructure/superstructure.cc b/y2016/control_loops/superstructure/superstructure.cc
new file mode 100644
index 0000000..db31ffc
--- /dev/null
+++ b/y2016/control_loops/superstructure/superstructure.cc
@@ -0,0 +1,26 @@
+#include "y2016/control_loops/superstructure/superstructure.h"
+
+#include "aos/common/controls/control_loops.q.h"
+#include "aos/common/logging/logging.h"
+
+namespace y2016 {
+namespace control_loops {
+
+Superstructure::Superstructure(
+ control_loops::SuperstructureQueue *my_superstructure)
+ : aos::controls::ControlLoop<control_loops::SuperstructureQueue>(
+ my_superstructure) {}
+
+void Superstructure::RunIteration(
+ const control_loops::SuperstructureQueue::Goal *goal,
+ const control_loops::SuperstructureQueue::Position *position,
+ ::aos::control_loops::Output *output,
+ control_loops::SuperstructureQueue::Status *status) {
+ (void)goal;
+ (void)position;
+ (void)output;
+ (void)status;
+}
+
+} // namespace control_loops
+} // namespace y2016
diff --git a/y2016/control_loops/superstructure/superstructure.h b/y2016/control_loops/superstructure/superstructure.h
new file mode 100644
index 0000000..f53629c
--- /dev/null
+++ b/y2016/control_loops/superstructure/superstructure.h
@@ -0,0 +1,35 @@
+#ifndef Y2016_CONTROL_LOOPS_SUPERSTRUCTURE_SUPERSTRUCTURE_H_
+#define Y2016_CONTROL_LOOPS_SUPERSTRUCTURE_SUPERSTRUCTURE_H_
+
+#include <memory>
+
+#include "aos/common/controls/control_loop.h"
+#include "frc971/control_loops/state_feedback_loop.h"
+
+#include "y2016/control_loops/superstructure/superstructure.q.h"
+
+namespace y2016 {
+namespace control_loops {
+
+class Superstructure
+ : public ::aos::controls::ControlLoop<control_loops::SuperstructureQueue> {
+ public:
+ explicit Superstructure(
+ control_loops::SuperstructureQueue *my_superstructure =
+ &control_loops::superstructure_queue);
+
+ protected:
+ virtual void RunIteration(
+ const control_loops::SuperstructureQueue::Goal *goal,
+ const control_loops::SuperstructureQueue::Position *position,
+ ::aos::control_loops::Output *output,
+ control_loops::SuperstructureQueue::Status *status) override;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(Superstructure);
+};
+
+} // namespace control_loops
+} // namespace y2016
+
+#endif // Y2016_CONTROL_LOOPS_SUPERSTRUCTURE_SUPERSTRUCTURE_H_
diff --git a/y2016/control_loops/superstructure/superstructure.q b/y2016/control_loops/superstructure/superstructure.q
new file mode 100644
index 0000000..f7a93f8
--- /dev/null
+++ b/y2016/control_loops/superstructure/superstructure.q
@@ -0,0 +1,27 @@
+package y2016.control_loops;
+
+import "aos/common/controls/control_loops.q";
+import "frc971/control_loops/control_loops.q";
+
+queue_group SuperstructureQueue {
+ implements aos.control_loops.ControlLoop;
+
+ message Goal {
+ double value;
+ };
+
+ message Status {
+ double value;
+ };
+
+ message Position {
+ double value;
+ };
+
+ queue Goal goal;
+ queue Position position;
+ queue aos.control_loops.Output output;
+ queue Status status;
+};
+
+queue_group SuperstructureQueue superstructure_queue;
diff --git a/y2016/control_loops/superstructure/superstructure_lib_test.cc b/y2016/control_loops/superstructure/superstructure_lib_test.cc
new file mode 100644
index 0000000..3a843cd
--- /dev/null
+++ b/y2016/control_loops/superstructure/superstructure_lib_test.cc
@@ -0,0 +1,86 @@
+#include "y2016/control_loops/superstructure/superstructure.h"
+
+#include <unistd.h>
+
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "aos/common/queue.h"
+#include "aos/common/controls/control_loop_test.h"
+#include "y2016/control_loops/superstructure/superstructure.q.h"
+
+using ::aos::time::Time;
+
+namespace y2016 {
+namespace control_loops {
+namespace testing {
+
+// Class which simulates the superstructure and sends out queue messages with
+// the position.
+class SuperstructureSimulation {
+ public:
+ SuperstructureSimulation()
+ : superstructure_queue_(".y2016.control_loops.superstructure", 0x0,
+ ".y2016.control_loops.superstructure.goal",
+ ".y2016.control_loops.superstructure.status",
+ ".y2016.control_loops.superstructure.output",
+ ".y2016.control_loops.superstructure.status") {
+ }
+
+ // Simulates superstructure for a single timestep.
+ void Simulate() { EXPECT_TRUE(superstructure_queue_.output.FetchLatest()); }
+
+ private:
+ SuperstructureQueue superstructure_queue_;
+};
+
+class SuperstructureTest : public ::aos::testing::ControlLoopTest {
+ protected:
+ SuperstructureTest()
+ : superstructure_queue_(".y2016.control_loops.superstructure", 0x0,
+ ".y2016.control_loops.superstructure.goal",
+ ".y2016.control_loops.superstructure.status",
+ ".y2016.control_loops.superstructure.output",
+ ".y2016.control_loops.superstructure.status"),
+ superstructure_(&superstructure_queue_),
+ superstructure_plant_() {}
+
+ void VerifyNearGoal() {
+ // TODO(phil): Implement a check here.
+ }
+
+ // Runs one iteration of the whole simulation and checks that separation
+ // remains reasonable.
+ void RunIteration(bool enabled = true) {
+ SendMessages(enabled);
+ TickTime();
+ }
+
+ // Runs iterations until the specified amount of simulated time has elapsed.
+ void RunForTime(const Time &run_for, bool enabled = true) {
+ const auto start_time = Time::Now();
+ while (Time::Now() < start_time + run_for) {
+ RunIteration(enabled);
+ }
+ }
+
+ // Create a new instance of the test queue so that it invalidates the queue
+ // that it points to. Otherwise, we will have a pointed to
+ // shared memory that is no longer valid.
+ SuperstructureQueue superstructure_queue_;
+
+ // Create a control loop and simulation.
+ Superstructure superstructure_;
+ SuperstructureSimulation superstructure_plant_;
+};
+
+// Tests that the superstructure does nothing when the goal is zero.
+TEST_F(SuperstructureTest, DoesNothing) {
+ // TODO(phil): Send a goal of some sort.
+ RunIteration();
+ VerifyNearGoal();
+}
+
+} // namespace testing
+} // namespace control_loops
+} // namespace frc971
diff --git a/y2016/control_loops/superstructure/superstructure_main.cc b/y2016/control_loops/superstructure/superstructure_main.cc
new file mode 100644
index 0000000..d825eeb
--- /dev/null
+++ b/y2016/control_loops/superstructure/superstructure_main.cc
@@ -0,0 +1,11 @@
+#include "y2016/control_loops/superstructure/superstructure.h"
+
+#include "aos/linux_code/init.h"
+
+int main() {
+ ::aos::Init();
+ ::y2016::control_loops::Superstructure superstructure;
+ superstructure.Run();
+ ::aos::Cleanup();
+ return 0;
+}
diff --git a/y2016/joystick_reader.cc b/y2016/joystick_reader.cc
new file mode 100644
index 0000000..c50b092
--- /dev/null
+++ b/y2016/joystick_reader.cc
@@ -0,0 +1,127 @@
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <math.h>
+
+#include "aos/linux_code/init.h"
+#include "aos/input/joystick_input.h"
+#include "aos/common/input/driver_station_data.h"
+#include "aos/common/logging/logging.h"
+#include "aos/common/util/log_interval.h"
+#include "aos/common/time.h"
+#include "aos/common/actions/actions.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "y2016/constants.h"
+#include "frc971/queues/gyro.q.h"
+#include "frc971/autonomous/auto.q.h"
+
+using ::frc971::control_loops::drivetrain_queue;
+
+using ::aos::input::driver_station::ButtonLocation;
+using ::aos::input::driver_station::JoystickAxis;
+using ::aos::input::driver_station::ControlBit;
+
+namespace y2016 {
+namespace input {
+namespace joysticks {
+
+const JoystickAxis kSteeringWheel(1, 1), kDriveThrottle(2, 2);
+const ButtonLocation kShiftHigh(2, 1), kShiftLow(2, 3);
+const ButtonLocation kQuickTurn(1, 5);
+
+class Reader : public ::aos::input::JoystickInput {
+ public:
+ Reader()
+ : is_high_gear_(false),
+ was_running_(false) {}
+
+ void RunIteration(const ::aos::input::driver_station::Data &data) override {
+ bool last_auto_running = auto_running_;
+ auto_running_ = data.GetControlBit(ControlBit::kAutonomous) &&
+ data.GetControlBit(ControlBit::kEnabled);
+ if (auto_running_ != last_auto_running) {
+ if (auto_running_) {
+ StartAuto();
+ } else {
+ StopAuto();
+ }
+ }
+
+ if (!data.GetControlBit(ControlBit::kAutonomous)) {
+ HandleDrivetrain(data);
+ HandleTeleop(data);
+ }
+ }
+
+ void HandleDrivetrain(const ::aos::input::driver_station::Data &data) {
+ bool is_control_loop_driving = false;
+ double left_goal = 0.0;
+ double right_goal = 0.0;
+ const double wheel = -data.GetAxis(kSteeringWheel);
+ const double throttle = -data.GetAxis(kDriveThrottle);
+
+ if (!drivetrain_queue.goal.MakeWithBuilder()
+ .steering(wheel)
+ .throttle(throttle)
+ .highgear(is_high_gear_)
+ .quickturn(data.IsPressed(kQuickTurn))
+ .control_loop_driving(is_control_loop_driving)
+ .left_goal(left_goal)
+ .right_goal(right_goal)
+ .left_velocity_goal(0)
+ .right_velocity_goal(0)
+ .Send()) {
+ LOG(WARNING, "sending stick values failed\n");
+ }
+
+ if (data.PosEdge(kShiftHigh)) {
+ is_high_gear_ = false;
+ }
+
+ if (data.PosEdge(kShiftLow)) {
+ is_high_gear_ = true;
+ }
+ }
+
+ void HandleTeleop(const ::aos::input::driver_station::Data &data) {
+ if (!data.GetControlBit(ControlBit::kEnabled)) {
+ action_queue_.CancelAllActions();
+ LOG(DEBUG, "Canceling\n");
+ }
+
+ was_running_ = action_queue_.Running();
+ }
+
+ private:
+ void StartAuto() {
+ LOG(INFO, "Starting auto mode\n");
+ ::frc971::autonomous::autonomous.MakeWithBuilder().run_auto(true).Send();
+ }
+
+ void StopAuto() {
+ LOG(INFO, "Stopping auto mode\n");
+ ::frc971::autonomous::autonomous.MakeWithBuilder().run_auto(false).Send();
+ }
+
+ bool is_high_gear_;
+ bool was_running_;
+ bool auto_running_ = false;
+
+ ::aos::common::actions::ActionQueue action_queue_;
+
+ ::aos::util::SimpleLogInterval no_drivetrain_status_ =
+ ::aos::util::SimpleLogInterval(::aos::time::Time::InSeconds(0.2), WARNING,
+ "no drivetrain status");
+};
+
+} // namespace joysticks
+} // namespace input
+} // namespace y2016
+
+int main() {
+ ::aos::Init(-1);
+ ::y2016::input::joysticks::Reader reader;
+ reader.Run();
+ ::aos::Cleanup();
+}
diff --git a/y2016/queues/BUILD b/y2016/queues/BUILD
new file mode 100644
index 0000000..3b282fd
--- /dev/null
+++ b/y2016/queues/BUILD
@@ -0,0 +1,10 @@
+package(default_visibility = ['//visibility:public'])
+
+load('/aos/build/queues', 'queue_library')
+
+queue_library(
+ name = 'profile_params',
+ srcs = [
+ 'profile_params.q',
+ ],
+)
diff --git a/y2016/queues/profile_params.q b/y2016/queues/profile_params.q
new file mode 100644
index 0000000..56b2ab3
--- /dev/null
+++ b/y2016/queues/profile_params.q
@@ -0,0 +1,6 @@
+package y2016;
+
+struct ProfileParams {
+ double velocity;
+ double acceleration;
+};
diff --git a/y2016/wpilib/BUILD b/y2016/wpilib/BUILD
new file mode 100644
index 0000000..9521d74
--- /dev/null
+++ b/y2016/wpilib/BUILD
@@ -0,0 +1,35 @@
+package(default_visibility = ['//visibility:public'])
+
+cc_binary(
+ name = 'wpilib_interface',
+ srcs = [
+ 'wpilib_interface.cc',
+ ],
+ deps = [
+ '//aos/common:stl_mutex',
+ '//aos/common/logging',
+ '//aos/common/controls:control_loop',
+ '//aos/common/util:log_interval',
+ '//aos/common:time',
+ '//aos/common/logging:queue_logging',
+ '//aos/common/messages:robot_state',
+ '//aos/common/util:phased_loop',
+ '//aos/common/util:wrapping_counter',
+ '//aos/linux_code:init',
+ '//aos/externals:wpilib',
+ '//frc971/control_loops/drivetrain:drivetrain_queue',
+ '//frc971/wpilib:joystick_sender',
+ '//frc971/wpilib:loop_output_handler',
+ '//frc971/wpilib:buffered_pcm',
+ '//frc971/wpilib:gyro_sender',
+ '//frc971/wpilib:dma_edge_counting',
+ '//frc971/wpilib:interrupt_edge_counting',
+ '//frc971/wpilib:wpilib_robot_base',
+ '//frc971/wpilib:encoder_and_potentiometer',
+ '//frc971/control_loops:queues',
+ '//frc971/wpilib:logging_queue',
+ '//frc971/wpilib:wpilib_interface',
+ '//frc971/wpilib:pdp_fetcher',
+ '//y2016:constants',
+ ],
+)
diff --git a/y2016/wpilib/wpilib_interface.cc b/y2016/wpilib/wpilib_interface.cc
new file mode 100644
index 0000000..7bcf0bc
--- /dev/null
+++ b/y2016/wpilib/wpilib_interface.cc
@@ -0,0 +1,431 @@
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <inttypes.h>
+
+#include <thread>
+#include <mutex>
+#include <functional>
+
+#include "Encoder.h"
+#include "Talon.h"
+#include "DriverStation.h"
+#include "AnalogInput.h"
+#include "Compressor.h"
+#include "Relay.h"
+#include "frc971/wpilib/wpilib_robot_base.h"
+#include "dma.h"
+#ifndef WPILIB2015
+#include "DigitalGlitchFilter.h"
+#endif
+#undef ERROR
+
+#include "aos/common/logging/logging.h"
+#include "aos/common/logging/queue_logging.h"
+#include "aos/common/time.h"
+#include "aos/common/util/log_interval.h"
+#include "aos/common/util/phased_loop.h"
+#include "aos/common/util/wrapping_counter.h"
+#include "aos/common/stl_mutex.h"
+#include "aos/linux_code/init.h"
+#include "aos/common/messages/robot_state.q.h"
+
+#include "frc971/shifter_hall_effect.h"
+
+#include "frc971/control_loops/drivetrain/drivetrain.q.h"
+#include "y2016/constants.h"
+
+#include "frc971/wpilib/joystick_sender.h"
+#include "frc971/wpilib/loop_output_handler.h"
+#include "frc971/wpilib/buffered_solenoid.h"
+#include "frc971/wpilib/buffered_pcm.h"
+#include "frc971/wpilib/gyro_sender.h"
+#include "frc971/wpilib/dma_edge_counting.h"
+#include "frc971/wpilib/interrupt_edge_counting.h"
+#include "frc971/wpilib/encoder_and_potentiometer.h"
+#include "frc971/wpilib/logging.q.h"
+#include "frc971/wpilib/wpilib_interface.h"
+#include "frc971/wpilib/pdp_fetcher.h"
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+using ::frc971::control_loops::drivetrain_queue;
+
+namespace y2016 {
+namespace wpilib {
+
+// TODO(Brian): Fix the interpretation of the result of GetRaw here and in the
+// DMA stuff and then removing the * 2.0 in *_translate.
+// The low bit is direction.
+
+// TODO(brian): Replace this with ::std::make_unique once all our toolchains
+// have support.
+template <class T, class... U>
+std::unique_ptr<T> make_unique(U &&... u) {
+ return std::unique_ptr<T>(new T(std::forward<U>(u)...));
+}
+
+double drivetrain_translate(int32_t in) {
+ return -static_cast<double>(in) / (256.0 /*cpr*/ * 4.0 /*4x*/) *
+ constants::GetValues().drivetrain_encoder_ratio *
+ (3.5 /*wheel diameter*/ * 2.54 / 100.0 * M_PI) * 2.0 / 2.0;
+}
+
+double drivetrain_velocity_translate(double in) {
+ return (1.0 / in) / 256.0 /*cpr*/ *
+ constants::GetValues().drivetrain_encoder_ratio *
+ (3.5 /*wheel diameter*/ * 2.54 / 100.0 * M_PI) * 2.0 / 2.0;
+}
+
+float hall_translate(const constants::ShifterHallEffect &k, float in_low,
+ float in_high) {
+ const float low_ratio =
+ 0.5 * (in_low - static_cast<float>(k.low_gear_low)) /
+ static_cast<float>(k.low_gear_middle - k.low_gear_low);
+ const float high_ratio =
+ 0.5 +
+ 0.5 * (in_high - static_cast<float>(k.high_gear_middle)) /
+ static_cast<float>(k.high_gear_high - k.high_gear_middle);
+
+ // Return low when we are below 1/2, and high when we are above 1/2.
+ if (low_ratio + high_ratio < 1.0) {
+ return low_ratio;
+ } else {
+ return high_ratio;
+ }
+}
+
+// TODO(constants): Update.
+static const double kMaximumEncoderPulsesPerSecond =
+ 5600.0 /* free speed RPM */ * 14.0 / 48.0 /* bottom gear reduction */ *
+ 18.0 / 32.0 /* big belt reduction */ * 18.0 /
+ 66.0 /* top gear reduction */ * 48.0 / 18.0 /* encoder gears */ /
+ 60.0 /* seconds / minute */ * 256.0 /* CPR */;
+
+class SensorReader {
+ public:
+ SensorReader() {
+ // Set it to filter out anything shorter than 1/4 of the minimum pulse width
+ // we should ever see.
+ encoder_filter_.SetPeriodNanoSeconds(
+ static_cast<int>(1 / 4.0 / kMaximumEncoderPulsesPerSecond * 1e9 + 0.5));
+ hall_filter_.SetPeriodNanoSeconds(100000);
+ }
+
+ void set_drivetrain_left_encoder(::std::unique_ptr<Encoder> encoder) {
+ drivetrain_left_encoder_ = ::std::move(encoder);
+ drivetrain_left_encoder_->SetMaxPeriod(0.005);
+ }
+
+ void set_drivetrain_right_encoder(::std::unique_ptr<Encoder> encoder) {
+ drivetrain_right_encoder_ = ::std::move(encoder);
+ drivetrain_right_encoder_->SetMaxPeriod(0.005);
+ }
+
+ void set_high_left_drive_hall(::std::unique_ptr<AnalogInput> analog) {
+ high_left_drive_hall_ = ::std::move(analog);
+ }
+
+ void set_low_right_drive_hall(::std::unique_ptr<AnalogInput> analog) {
+ low_right_drive_hall_ = ::std::move(analog);
+ }
+
+ void set_high_right_drive_hall(::std::unique_ptr<AnalogInput> analog) {
+ high_right_drive_hall_ = ::std::move(analog);
+ }
+
+ void set_low_left_drive_hall(::std::unique_ptr<AnalogInput> analog) {
+ low_left_drive_hall_ = ::std::move(analog);
+ }
+
+ // All of the DMA-related set_* calls must be made before this, and it doesn't
+ // hurt to do all of them.
+
+ // TODO(comran): Add 2016 things down below for dma synchronization.
+ void set_dma(::std::unique_ptr<DMA> dma) {
+ dma_synchronizer_.reset(
+ new ::frc971::wpilib::DMASynchronizer(::std::move(dma)));
+ }
+
+ void operator()() {
+ ::aos::SetCurrentThreadName("SensorReader");
+
+ my_pid_ = getpid();
+ ds_ =
+#ifdef WPILIB2015
+ DriverStation::GetInstance();
+#else
+ &DriverStation::GetInstance();
+#endif
+
+ dma_synchronizer_->Start();
+
+ ::aos::time::PhasedLoop phased_loop(::aos::time::Time::InMS(5),
+ ::aos::time::Time::InMS(4));
+
+ ::aos::SetCurrentThreadRealtimePriority(40);
+ while (run_) {
+ {
+ const int iterations = phased_loop.SleepUntilNext();
+ if (iterations != 1) {
+ LOG(WARNING, "SensorReader skipped %d iterations\n", iterations - 1);
+ }
+ }
+ RunIteration();
+ }
+ }
+
+ void RunIteration() {
+ ::frc971::wpilib::SendRobotState(my_pid_, ds_);
+
+ const auto &values = constants::GetValues();
+
+ {
+ auto drivetrain_message = drivetrain_queue.position.MakeMessage();
+ drivetrain_message->right_encoder =
+ drivetrain_translate(drivetrain_right_encoder_->GetRaw());
+ drivetrain_message->left_encoder =
+ -drivetrain_translate(drivetrain_left_encoder_->GetRaw());
+ drivetrain_message->left_speed =
+ drivetrain_velocity_translate(drivetrain_left_encoder_->GetPeriod());
+ drivetrain_message->right_speed =
+ drivetrain_velocity_translate(drivetrain_right_encoder_->GetPeriod());
+
+ drivetrain_message->low_left_hall = low_left_drive_hall_->GetVoltage();
+ drivetrain_message->high_left_hall = high_left_drive_hall_->GetVoltage();
+ drivetrain_message->left_shifter_position =
+ hall_translate(values.left_drive, drivetrain_message->low_left_hall,
+ drivetrain_message->high_left_hall);
+
+ drivetrain_message->low_right_hall = low_right_drive_hall_->GetVoltage();
+ drivetrain_message->high_right_hall =
+ high_right_drive_hall_->GetVoltage();
+ drivetrain_message->right_shifter_position =
+ hall_translate(values.right_drive, drivetrain_message->low_right_hall,
+ drivetrain_message->high_right_hall);
+
+ drivetrain_message.Send();
+ }
+
+ dma_synchronizer_->RunIteration();
+ }
+
+ void Quit() { run_ = false; }
+
+ private:
+ int32_t my_pid_;
+ DriverStation *ds_;
+
+ ::std::unique_ptr<::frc971::wpilib::DMASynchronizer> dma_synchronizer_;
+
+ ::std::unique_ptr<Encoder> drivetrain_left_encoder_;
+ ::std::unique_ptr<Encoder> drivetrain_right_encoder_;
+ ::std::unique_ptr<AnalogInput> low_left_drive_hall_;
+ ::std::unique_ptr<AnalogInput> high_left_drive_hall_;
+ ::std::unique_ptr<AnalogInput> low_right_drive_hall_;
+ ::std::unique_ptr<AnalogInput> high_right_drive_hall_;
+
+ ::std::atomic<bool> run_{true};
+ DigitalGlitchFilter encoder_filter_, hall_filter_;
+};
+
+class SolenoidWriter {
+ public:
+ SolenoidWriter(const ::std::unique_ptr<::frc971::wpilib::BufferedPcm> &pcm)
+ : pcm_(pcm),
+ drivetrain_(".frc971.control_loops.drivetrain_queue.output") {}
+
+ void set_pressure_switch(::std::unique_ptr<DigitalInput> pressure_switch) {
+ pressure_switch_ = ::std::move(pressure_switch);
+ }
+
+ void set_compressor_relay(::std::unique_ptr<Relay> compressor_relay) {
+ compressor_relay_ = ::std::move(compressor_relay);
+ }
+
+ void set_drivetrain_left(
+ ::std::unique_ptr<::frc971::wpilib::BufferedSolenoid> s) {
+ drivetrain_left_ = ::std::move(s);
+ }
+
+ void set_drivetrain_right(
+ ::std::unique_ptr<::frc971::wpilib::BufferedSolenoid> s) {
+ drivetrain_right_ = ::std::move(s);
+ }
+
+ void operator()() {
+ ::aos::SetCurrentThreadName("Solenoids");
+ ::aos::SetCurrentThreadRealtimePriority(27);
+
+ ::aos::time::PhasedLoop phased_loop(::aos::time::Time::InMS(20),
+ ::aos::time::Time::InMS(1));
+
+ while (run_) {
+ {
+ const int iterations = phased_loop.SleepUntilNext();
+ if (iterations != 1) {
+ LOG(DEBUG, "Solenoids skipped %d iterations\n", iterations - 1);
+ }
+ }
+
+ {
+ drivetrain_.FetchLatest();
+ if (drivetrain_.get()) {
+ LOG_STRUCT(DEBUG, "solenoids", *drivetrain_);
+ drivetrain_left_->Set(!drivetrain_->left_high);
+ drivetrain_right_->Set(!drivetrain_->right_high);
+ }
+ }
+
+ {
+ ::frc971::wpilib::PneumaticsToLog to_log;
+ {
+ const bool compressor_on = !pressure_switch_->Get();
+ to_log.compressor_on = compressor_on;
+ if (compressor_on) {
+ compressor_relay_->Set(Relay::kForward);
+ } else {
+ compressor_relay_->Set(Relay::kOff);
+ }
+ }
+
+ pcm_->Flush();
+ to_log.read_solenoids = pcm_->GetAll();
+ LOG_STRUCT(DEBUG, "pneumatics info", to_log);
+ }
+ }
+ }
+
+ void Quit() { run_ = false; }
+
+ private:
+ const ::std::unique_ptr<::frc971::wpilib::BufferedPcm> &pcm_;
+
+ ::std::unique_ptr<::frc971::wpilib::BufferedSolenoid> drivetrain_left_;
+ ::std::unique_ptr<::frc971::wpilib::BufferedSolenoid> drivetrain_right_;
+
+ ::std::unique_ptr<DigitalInput> pressure_switch_;
+ ::std::unique_ptr<Relay> compressor_relay_;
+
+ ::aos::Queue<::frc971::control_loops::DrivetrainQueue::Output> drivetrain_;
+
+ ::std::atomic<bool> run_{true};
+};
+
+class DrivetrainWriter : public ::frc971::wpilib::LoopOutputHandler {
+ public:
+ void set_left_drivetrain_talon(::std::unique_ptr<Talon> t) {
+ left_drivetrain_talon_ = ::std::move(t);
+ }
+
+ void set_right_drivetrain_talon(::std::unique_ptr<Talon> t) {
+ right_drivetrain_talon_ = ::std::move(t);
+ }
+
+ private:
+ virtual void Read() override {
+ ::frc971::control_loops::drivetrain_queue.output.FetchAnother();
+ }
+
+ virtual void Write() override {
+ auto &queue = ::frc971::control_loops::drivetrain_queue.output;
+ LOG_STRUCT(DEBUG, "will output", *queue);
+ left_drivetrain_talon_->Set(-queue->left_voltage / 12.0);
+ right_drivetrain_talon_->Set(queue->right_voltage / 12.0);
+ }
+
+ virtual void Stop() override {
+ LOG(WARNING, "drivetrain output too old\n");
+ left_drivetrain_talon_->Disable();
+ right_drivetrain_talon_->Disable();
+ }
+
+ ::std::unique_ptr<Talon> left_drivetrain_talon_;
+ ::std::unique_ptr<Talon> right_drivetrain_talon_;
+};
+
+class WPILibRobot : public ::frc971::wpilib::WPILibRobotBase {
+ public:
+ ::std::unique_ptr<Encoder> make_encoder(int index) {
+ return make_unique<Encoder>(10 + index * 2, 11 + index * 2, false,
+ Encoder::k4X);
+ }
+
+ void Run() override {
+ ::aos::InitNRT();
+ ::aos::SetCurrentThreadName("StartCompetition");
+
+ ::frc971::wpilib::JoystickSender joystick_sender;
+ ::std::thread joystick_thread(::std::ref(joystick_sender));
+
+ ::frc971::wpilib::PDPFetcher pdp_fetcher;
+ ::std::thread pdp_fetcher_thread(::std::ref(pdp_fetcher));
+ SensorReader reader;
+
+ // TODO(constants): Update these input numbers.
+ reader.set_drivetrain_left_encoder(make_encoder(0));
+ reader.set_drivetrain_right_encoder(make_encoder(1));
+ reader.set_high_left_drive_hall(make_unique<AnalogInput>(1));
+ reader.set_low_left_drive_hall(make_unique<AnalogInput>(0));
+ reader.set_high_right_drive_hall(make_unique<AnalogInput>(2));
+ reader.set_low_right_drive_hall(make_unique<AnalogInput>(3));
+
+ reader.set_dma(make_unique<DMA>());
+ ::std::thread reader_thread(::std::ref(reader));
+
+ ::frc971::wpilib::GyroSender gyro_sender;
+ ::std::thread gyro_thread(::std::ref(gyro_sender));
+
+ DrivetrainWriter drivetrain_writer;
+ drivetrain_writer.set_left_drivetrain_talon(
+ ::std::unique_ptr<Talon>(new Talon(5)));
+ drivetrain_writer.set_right_drivetrain_talon(
+ ::std::unique_ptr<Talon>(new Talon(2)));
+ ::std::thread drivetrain_writer_thread(::std::ref(drivetrain_writer));
+
+ ::std::unique_ptr<::frc971::wpilib::BufferedPcm> pcm(
+ new ::frc971::wpilib::BufferedPcm());
+ SolenoidWriter solenoid_writer(pcm);
+ solenoid_writer.set_drivetrain_left(pcm->MakeSolenoid(6));
+ solenoid_writer.set_drivetrain_right(pcm->MakeSolenoid(7));
+
+ solenoid_writer.set_pressure_switch(make_unique<DigitalInput>(25));
+ solenoid_writer.set_compressor_relay(make_unique<Relay>(0));
+ ::std::thread solenoid_thread(::std::ref(solenoid_writer));
+
+ // Wait forever. Not much else to do...
+ while (true) {
+ const int r = select(0, nullptr, nullptr, nullptr, nullptr);
+ if (r != 0) {
+ PLOG(WARNING, "infinite select failed");
+ } else {
+ PLOG(WARNING, "infinite select succeeded??\n");
+ }
+ }
+
+ LOG(ERROR, "Exiting WPILibRobot\n");
+
+ joystick_sender.Quit();
+ joystick_thread.join();
+ pdp_fetcher.Quit();
+ pdp_fetcher_thread.join();
+ reader.Quit();
+ reader_thread.join();
+ gyro_sender.Quit();
+ gyro_thread.join();
+
+ drivetrain_writer.Quit();
+ drivetrain_writer_thread.join();
+ solenoid_writer.Quit();
+ solenoid_thread.join();
+
+ ::aos::Cleanup();
+ }
+};
+
+} // namespace wpilib
+} // namespace y2016
+
+AOS_ROBOT_CLASS(::y2016::wpilib::WPILibRobot);