Clean up printing in MCU code and add new options

We now have four different ways of getting debug prints off of boards,
with varying tradeoffs. Split out the printing into dedicated libraries
that are easy to switch between to avoid duplicating even more code, and
also make using the new options easy.

USB is handy for testing the code on a Teensy.
Semihosting is nice in theory, but in practice it's super slow and
messes up the code's timing.
ITM works well, as long as you have a debugger attached.
Serial also works pretty well, but it means having another cable.

Change-Id: I7af5099d421c33f0324aeca92b46732e341848d4
diff --git a/motors/print/uart.cc b/motors/print/uart.cc
new file mode 100644
index 0000000..84b33cd
--- /dev/null
+++ b/motors/print/uart.cc
@@ -0,0 +1,69 @@
+#include "motors/print/uart.h"
+
+#include "motors/core/kinetis.h"
+
+#include <atomic>
+
+namespace frc971 {
+namespace motors {
+namespace {
+
+::std::atomic<teensy::InterruptBufferedUart *> global_stdout{nullptr};
+
+}  // namespace
+
+::std::unique_ptr<PrintingImplementation> CreatePrinting(
+    const PrintingParameters &parameters) {
+  if (parameters.stdout_uart_module == nullptr) {
+    return ::std::unique_ptr<PrintingImplementation>(new NopPrinting());
+  }
+  if (parameters.stdout_uart_module_clock_frequency == 0) {
+    return ::std::unique_ptr<PrintingImplementation>(new NopPrinting());
+  }
+  if (parameters.stdout_uart_status_interrupt < 0) {
+    return ::std::unique_ptr<PrintingImplementation>(new NopPrinting());
+  }
+  return ::std::unique_ptr<PrintingImplementation>(
+      new UartPrinting(parameters));
+}
+
+extern "C" void uart0_status_isr(void) {
+  teensy::InterruptBufferedUart *const tty =
+      global_stdout.load(::std::memory_order_relaxed);
+  DisableInterrupts disable_interrupts;
+  tty->HandleInterrupt(disable_interrupts);
+}
+
+UartPrinting::UartPrinting(const PrintingParameters &parameters)
+    : stdout_uart_{parameters.stdout_uart_module,
+                   parameters.stdout_uart_module_clock_frequency},
+      stdout_status_interrupt_(parameters.stdout_uart_status_interrupt) {
+  stdout_uart_.Initialize(parameters.stdout_uart_baud_rate);
+}
+
+UartPrinting::~UartPrinting() {
+  NVIC_DISABLE_IRQ(stdout_status_interrupt_);
+  global_stdout.store(nullptr, ::std::memory_order_release);
+}
+
+void UartPrinting::Initialize() {
+  global_stdout.store(&stdout_uart_, ::std::memory_order_release);
+  NVIC_ENABLE_IRQ(stdout_status_interrupt_);
+}
+
+int UartPrinting::WriteStdout(gsl::span<const char> buffer) {
+  stdout_uart_.Write(buffer);
+  return buffer.size();
+}
+
+extern "C" int _write(const int /*file*/, char *const ptr, const int len) {
+  teensy::InterruptBufferedUart *const tty =
+      global_stdout.load(::std::memory_order_acquire);
+  if (tty != nullptr) {
+    tty->Write(gsl::make_span(ptr, len));
+  }
+  return len;
+}
+
+}  // namespace motors
+}  // namespace frc971