diff --git a/AGENTS.md b/AGENTS.md index fb87d02..64c3b83 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -474,6 +474,16 @@ be lost, and the `Status` a part below the facade passes on. A setter's `Status` to tell, and the examples do. Where the library drops a marked result on purpose, it hands it to `Discard()` with the reason beside it. +The host code marks alike what it computes or finds, as `ControlCommand::MakeText()` or +`SimulatorWebSocket::EncodeFrame()`, and leaves unmarked what only says whether an action +worked, as `Send()` or `Begin()`. It drops no result without `Discard()` and its reason, marked +or not, a system call's as well (`close()`, `setsockopt()`, `avr_ioctl()`), and handles one +whose failure matters instead: a socket that still blocks is closed, not polled. A result is a +value that tells the caller something, success, a count, a place or whether something changed; +a reference to the object itself, as `std::string::append()` and `std::ostream::flush()` return, +or a handle to what was just added, as `wxSizer::Add()` returns, is none, as the call returns +it only so that calls can be chained. + The texts lie in a table in `PROGMEM`, not behind a `switch`: avr-gcc turns a `switch` that returns a constant per case into a table in `.rodata`, which the Uno copies into RAM, as it does with every constant not marked `PROGMEM`. diff --git a/OIL.md b/OIL.md index 6b2a71f..6ecdc39 100644 --- a/OIL.md +++ b/OIL.md @@ -50,7 +50,7 @@ Status: `open`, `in progress`, `done`, `dropped` (with the reason in the item). | 38 | Results that must not be ignored | 36 | done | #94 | | 39 | MC/DC coverage | 34 | done | #95, #96 | | 40 | Braced initialization checked | 34 | done | #93 | -| 41 | The template's rules that review checks | 36 | in progress | #99, #100, #101, #102, #104, #105, #106, #107, #113, #115, #116, #117, #118, #121, #122, #124, #125, #126 | +| 41 | The template's rules that review checks | 36 | in progress | #99, #100, #101, #102, #104, #105, #106, #107, #113, #115, #116, #117, #118, #121, #122, #124, #125, #126, #127 | | 42 | A newer avr-gcc as a cross-check | 41 | done | | | 43 | Bit operations in one class, from the template | 41 | done | #109 | @@ -1180,6 +1180,16 @@ calls, as what a port has read, the index into the command line and the labels a `DocuPictures` draws on are references. `SimulatorRun::SetUp()` keeps its two references, as it sets up the objects the tick reaches through a plain function pointer. +As built for FN-10 in the host code: no result is dropped without `Discard()` and its reason, +a system call's included. Where a failure matters it is handled instead: a socket that still +blocks after `SetNonBlocking()`, or that would wait without end for a request, is closed rather +than polled; `avr_init()` that fails fails the load; a matrix of `DocuPictures` that does not +start fails the run; and the control program logs a window without a timer. What only says +whether something changed, as wxWidgets' `Enable()`, goes to `Discard()` as well, and so does +`close()`, through `SimulatorSocket::Close()` in the simulator. What the host code computes or +finds is `MAXMATRIX_NODISCARD` now, some thirty functions. A reference to the object itself or a +handle to what was just added is no result, AGENTS.md says why. + ### 42 A newer avr-gcc as a cross-check `max_matrix::Byte` (41) made the examples 30 to 50 bytes of flash larger on the Uno at first, diff --git a/control/ControlCommand.h b/control/ControlCommand.h index e5f19bf..95c065a 100644 --- a/control/ControlCommand.h +++ b/control/ControlCommand.h @@ -58,7 +58,8 @@ class ControlCommand { * \param[in] shift True to shift it in, false to show it at once. * \return The line. */ - static std::string MakeText(std::string const& text, bool shift); + MAXMATRIX_NODISCARD static std::string MakeText(std::string const& text, + bool shift); /*! * \brief Makes the line that sets the brightness. @@ -66,7 +67,7 @@ class ControlCommand { * \param[in] intensity The brightness, 0 to 15. * \return The line. */ - static std::string MakeIntensity(uint8_t intensity); + MAXMATRIX_NODISCARD static std::string MakeIntensity(uint8_t intensity); /*! * \brief Makes the line that sets how fast a text shifts. @@ -74,7 +75,7 @@ class ControlCommand { * \param[in] milliseconds The time per column. * \return The line. */ - static std::string MakeSpeed(uint16_t milliseconds); + MAXMATRIX_NODISCARD static std::string MakeSpeed(uint16_t milliseconds); /*! * \brief Makes the line that sets the empty columns between the chars of a @@ -83,7 +84,7 @@ class ControlCommand { * \param[in] columns The columns. * \return The line. */ - static std::string MakeSpace(uint8_t columns); + MAXMATRIX_NODISCARD static std::string MakeSpace(uint8_t columns); /*! * \brief Makes the line that lights a dot or turns it off. @@ -93,21 +94,22 @@ class ControlCommand { * \param[in] lit True to light it, false to turn it off. * \return The line. */ - static std::string MakeDot(uint8_t column, uint8_t row, bool lit); + MAXMATRIX_NODISCARD static std::string MakeDot(uint8_t column, uint8_t row, + bool lit); /*! * \brief Makes the line that turns every LED off. * * \return The line. */ - static std::string MakeClear(); + MAXMATRIX_NODISCARD static std::string MakeClear(); /*! * \brief Makes the line that asks what the matrix shows. * * \return The line. */ - static std::string MakePicture(); + MAXMATRIX_NODISCARD static std::string MakePicture(); /*! * \brief Decodes the answer to `picture` into the columns of the panel. @@ -128,7 +130,7 @@ class ControlCommand { * \return True if it fits into the board's line buffer and holds no line * break. */ - static bool Fits(std::string const& line); + MAXMATRIX_NODISCARD static bool Fits(std::string const& line); /*! * \brief Returns how many bytes `line` may still grow by before SerialControl @@ -138,7 +140,7 @@ class ControlCommand { * \return The bytes left in the board's line buffer, negative by as many * bytes as the line is too long. */ - static int32_t GetBytesLeft(std::string const& line); + MAXMATRIX_NODISCARD static int32_t GetBytesLeft(std::string const& line); }; #endif // MAXMATRIX_CONTROL_CONTROLCOMMAND_H_ diff --git a/control/ControlDotPanel.cpp b/control/ControlDotPanel.cpp index c1ad0c2..b253821 100644 --- a/control/ControlDotPanel.cpp +++ b/control/ControlDotPanel.cpp @@ -26,6 +26,7 @@ #include #include "ControlCommand.h" +#include "MaxMatrixAttributes.h" #include "MaxMatrixConfig.h" #include "Utility/Bit.h" @@ -57,9 +58,9 @@ ControlDotPanel::ControlDotPanel( wxCoord const height{(max_matrix::kRowNumberOfModule * kCell) + (2 * kMargin)}; - // the background is painted whole by OnPaint(), which the buffered DC needs - // to know - SetBackgroundStyle(wxBG_STYLE_PAINT); + // The background is painted whole by OnPaint(), which the buffered DC needs + // to know; the style fails only for a transparent background a system lacks. + max_matrix::Discard(SetBackgroundStyle(wxBG_STYLE_PAINT)); SetMinSize(FromDIP(wxSize(width, height))); Bind(wxEVT_PAINT, &ControlDotPanel::OnPaint, this); Bind(wxEVT_LEFT_DOWN, &ControlDotPanel::OnLeftDown, this); diff --git a/control/ControlLink.h b/control/ControlLink.h index b45a797..327dbc1 100644 --- a/control/ControlLink.h +++ b/control/ControlLink.h @@ -75,7 +75,7 @@ class ControlLink { bool picture_timed_{false}; uint32_t picture_asked_at_{0}; - bool Take(std::string const& line); + MAXMATRIX_NODISCARD bool Take(std::string const& line); public: /*! diff --git a/control/ControlSerialPort.cpp b/control/ControlSerialPort.cpp index 250d04b..cdbdc2c 100644 --- a/control/ControlSerialPort.cpp +++ b/control/ControlSerialPort.cpp @@ -32,6 +32,7 @@ #include "ControlSerialPort.h" #include "ControlStream.h" +#include "MaxMatrixAttributes.h" #include "Utility/Bit.h" namespace { @@ -157,7 +158,11 @@ bool ControlSerialPort::Read(std::string& data) { } void ControlSerialPort::Close() { - if (handle_ != INVALID_HANDLE_VALUE) CloseHandle(handle_); + if (handle_ != INVALID_HANDLE_VALUE) { + // The handle is gone even when it reports an error, and there is nothing + // to try again. + max_matrix::Discard(CloseHandle(handle_)); + } handle_ = INVALID_HANDLE_VALUE; } @@ -176,8 +181,6 @@ ControlSerialPort::~ControlSerialPort() { Close(); } * it. */ bool ControlSerialPort::Open(std::string const& name, uint32_t baud_rate) { - termios settings{}; - Close(); if (!IsBaudRate(baud_rate)) { return false; @@ -185,20 +188,38 @@ bool ControlSerialPort::Open(std::string const& name, uint32_t baud_rate) { /* read and write, not as the terminal that controls this process, and * without waiting for the modem lines */ constexpr int kOpenFlags{O_RDWR | O_NOCTTY | O_NONBLOCK}; - /* the modem lines ignored, and receiving on */ - constexpr tcflag_t kLocalReceive{CLOCAL | CREAD}; - /* two stop bits and the hardware handshake, both off for SerialControl */ - constexpr tcflag_t kTwoStopsHandshake{CSTOPB | CRTSCTS}; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg): POSIX's open() descriptor_ = open(name.c_str(), kOpenFlags); if (descriptor_ < 0) { return false; } + bool const opened{Configure(baud_rate)}; + if (opened) { + // What lay in the buffers from before goes, if it can; left there, it + // starts the first line read, which the link passes on as a line of its + // own. + max_matrix::Discard(tcflush(descriptor_, TCIOFLUSH)); + } else { + Close(); + } + return opened; +} + +// Takes the open port for itself and sets it up as Open() says. Returns false +// if it is taken or does not take the baud rate. FN-11: not const, as it +// changes the port this object stands for, through its descriptor. +// NOLINTNEXTLINE(readability-make-member-function-const) +bool ControlSerialPort::Configure(uint32_t baud_rate) { + /* the modem lines ignored, and receiving on */ + constexpr tcflag_t kLocalReceive{CLOCAL | CREAD}; + /* two stop bits and the hardware handshake, both off for SerialControl */ + constexpr tcflag_t kTwoStopsHandshake{CSTOPB | CRTSCTS}; + termios settings{}; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg): POSIX's ioctl() - bool opened{(ioctl(descriptor_, TIOCEXCL) == 0) && - (tcgetattr(descriptor_, &settings) == 0)}; + bool const taken{(ioctl(descriptor_, TIOCEXCL) == 0) && + (tcgetattr(descriptor_, &settings) == 0)}; cfmakeraw(&settings); max_matrix::Bit::SetBits(settings.c_cflag, kLocalReceive); max_matrix::Bit::ClearBits(settings.c_cflag, kTwoStopsHandshake); @@ -206,14 +227,8 @@ bool ControlSerialPort::Open(std::string const& name, uint32_t baud_rate) { settings.c_cc[VTIME] = 0; // glibc's cfsetspeed() takes a rate as its number as well as its B constant, // so no table maps one to the other. - opened = opened && (cfsetspeed(&settings, baud_rate) == 0) && - (tcsetattr(descriptor_, TCSANOW, &settings) == 0); - if (opened) { - tcflush(descriptor_, TCIOFLUSH); - } else { - Close(); - } - return opened; + return taken && (cfsetspeed(&settings, baud_rate) == 0) && + (tcsetattr(descriptor_, TCSANOW, &settings) == 0); } std::vector ControlSerialPort::List() { @@ -280,7 +295,9 @@ bool ControlSerialPort::Read(std::string& data) { void ControlSerialPort::Close() { if (descriptor_ >= 0) { - close(descriptor_); + // close() frees the descriptor even when it reports an error, and there is + // nothing to try again. + max_matrix::Discard(close(descriptor_)); } descriptor_ = -1; } diff --git a/control/ControlSerialPort.h b/control/ControlSerialPort.h index e54f79f..7a87550 100644 --- a/control/ControlSerialPort.h +++ b/control/ControlSerialPort.h @@ -35,6 +35,8 @@ class ControlSerialPort final : public ControlPort { void* handle_; #else int descriptor_{-1}; + + MAXMATRIX_NODISCARD bool Configure(uint32_t baud_rate); #endif public: @@ -70,7 +72,7 @@ class ControlSerialPort final : public ControlPort { * * \return The names, sorted. */ - static std::vector List(); + MAXMATRIX_NODISCARD static std::vector List(); MAXMATRIX_NODISCARD bool IsOpen() const override; bool Write(std::string const& data) override; diff --git a/control/ControlTcpPort.cpp b/control/ControlTcpPort.cpp index a9c5f99..8d052eb 100644 --- a/control/ControlTcpPort.cpp +++ b/control/ControlTcpPort.cpp @@ -27,6 +27,7 @@ #include "ControlStream.h" #include "ControlTcpPort.h" +#include "MaxMatrixAttributes.h" #include "Utility/Bit.h" namespace { @@ -42,7 +43,9 @@ using Length = int; constexpr int kSendFlags{0}; bool WouldBlock() { return WSAGetLastError() == WSAEWOULDBLOCK; } -void CloseSocket(Socket socket) { closesocket(socket); } +// The socket is gone even when closing reports an error, and there is nothing +// to try again. +void CloseSocket(Socket socket) { max_matrix::Discard(closesocket(socket)); } int Poll(pollfd* descriptor, int timeout) { return WSAPoll(descriptor, 1, timeout); } @@ -58,7 +61,8 @@ using Length = size_t; constexpr int kSendFlags{MSG_NOSIGNAL}; bool WouldBlock() { return (errno == EAGAIN) || (errno == EWOULDBLOCK); } -void CloseSocket(Socket socket) { close(socket); } +// As on Windows. +void CloseSocket(Socket socket) { max_matrix::Discard(close(socket)); } int Poll(pollfd* descriptor, int timeout) { return poll(descriptor, 1, timeout); } @@ -99,7 +103,8 @@ bool ControlTcpPort::Open(uint16_t port) { socket_ = static_cast(socket(AF_INET, SOCK_STREAM, 0)); if (socket_ == kNone) { #ifdef _WIN32 - WSACleanup(); + // It fails only without the WSAStartup() above. + max_matrix::Discard(WSACleanup()); #endif return false; } @@ -165,6 +170,7 @@ void ControlTcpPort::Close() { CloseSocket(ToSocket(socket_)); socket_ = kNone; #ifdef _WIN32 - WSACleanup(); + // It fails only without the WSAStartup() of Open(). + max_matrix::Discard(WSACleanup()); #endif } diff --git a/control/ControlWindow.cpp b/control/ControlWindow.cpp index b9cbae2..a8216a7 100644 --- a/control/ControlWindow.cpp +++ b/control/ControlWindow.cpp @@ -39,6 +39,7 @@ #include "ControlCommand.h" #include "ControlDotPanel.h" #include "ControlLink.h" +#include "MaxMatrixAttributes.h" #include "MaxMatrixConfig.h" namespace { @@ -118,7 +119,9 @@ ControlWindow::ControlWindow() SetMinClientSize(content->GetBestSize()); Bind(wxEVT_TIMER, &ControlWindow::OnTimer, this); - timer_.Start(kPollMs); + if (!timer_.Start(kPollMs)) { + Log("No timer: the window follows neither the board nor the simulator.\n"); + } ShowState(); } @@ -130,8 +133,9 @@ void ControlWindow::MakeMenu() { file->Append(wxID_EXIT); help->Append(wxID_ABOUT); - bar->Append(file, "&File"); - bar->Append(help, "&Help"); + // A bar fails only past the menus it can take, far more than two. + max_matrix::Discard(bar->Append(file, "&File")); + max_matrix::Discard(bar->Append(help, "&Help")); SetMenuBar(bar); Bind(wxEVT_MENU, &ControlWindow::OnExit, this, wxID_EXIT); Bind(wxEVT_MENU, &ControlWindow::OnAbout, this, wxID_ABOUT); @@ -385,7 +389,8 @@ void ControlWindow::OnListPorts(wxCommandEvent& /* event */) { serial_port_name_->Clear(); for (std::string const& port : ControlSerialPort::List()) { - serial_port_name_->Append(wxString::FromUTF8(port)); + // the place of the new entry, which the list keeps in order + max_matrix::Discard(serial_port_name_->Append(wxString::FromUTF8(port))); } if (!typed.empty()) { serial_port_name_->SetValue(typed); @@ -427,13 +432,18 @@ void ControlWindow::OnAbout(wxCommandEvent& /* event */) { wxAboutBox(about, this); } -void ControlWindow::OnExit(wxCommandEvent& /* event */) { Close(true); } +// Forced, the window closes whatever its handlers say. +void ControlWindow::OnExit(wxCommandEvent& /* event */) { + max_matrix::Discard(Close(true)); +} // Sends `line` to every end that takes commands, and logs it once. void ControlWindow::Broadcast(std::string const& line) { Log("> " + ConvertToText(line) + "\n"); - board_link_.Send(line); - simulator_link_.Send(line); + // A link that is not ready takes nothing, and one whose port broke shows it + // at the next Follow(). + max_matrix::Discard(board_link_.Send(line)); + max_matrix::Discard(simulator_link_.Send(line)); ShowState(); } @@ -478,7 +488,8 @@ void ControlWindow::SendSettings(ControlLink& link, char const* name) { for (std::string const& line : lines) { Log(wxString(name) + ": > " + ConvertToText(line) + "\n"); - link.Send(line); + // as in Broadcast() + max_matrix::Discard(link.Send(line)); } } @@ -531,30 +542,37 @@ ControlLink* ControlWindow::GetShownLink() { void ControlWindow::ShowState() { bool const any_ready{board_link_.IsReady() || simulator_link_.IsReady()}; + /* + * Enable() and SetForegroundColour() say whether they changed anything, here + * and in ShowBytesLeft(), which the window does not need: it shows the state + * whatever it was before. + */ board_button_->SetLabel(serial_port_.IsOpen() ? "Close" : "Open"); - serial_port_name_->Enable(!serial_port_.IsOpen()); + max_matrix::Discard(serial_port_name_->Enable(!serial_port_.IsOpen())); if (board_link_.IsReady()) { board_status_->SetLabel("ready"); - board_status_->SetForegroundColour(CONTROL_WINDOW_READY); + max_matrix::Discard( + board_status_->SetForegroundColour(CONTROL_WINDOW_READY)); } else if (serial_port_.IsOpen()) { board_status_->SetLabel("waiting for ready"); - board_status_->SetForegroundColour(CONTROL_WINDOW_WAITING); + max_matrix::Discard( + board_status_->SetForegroundColour(CONTROL_WINDOW_WAITING)); } else { board_status_->SetLabel("closed"); - board_status_->SetForegroundColour( - wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT)); + max_matrix::Discard(board_status_->SetForegroundColour( + wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT))); } simulator_button_->SetLabel(tcp_port_.IsOpen() ? "Disconnect" : "Connect"); - tcp_port_number_->Enable(!tcp_port_.IsOpen()); + max_matrix::Discard(tcp_port_number_->Enable(!tcp_port_.IsOpen())); simulator_status_->SetLabel(simulator_link_.IsReady() ? "ready" : "not connected"); - simulator_status_->SetForegroundColour( + max_matrix::Discard(simulator_status_->SetForegroundColour( simulator_link_.IsReady() ? CONTROL_WINDOW_READY - : wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT)); - controls_->Enable(any_ready); + : wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT))); + max_matrix::Discard(controls_->Enable(any_ready)); ShowBytesLeft(); - speed_->Enable(any_ready && shift_->GetValue()); + max_matrix::Discard(speed_->Enable(any_ready && shift_->GetValue())); dots_->Refresh(); } @@ -574,10 +592,11 @@ void ControlWindow::ShowBytesLeft() { bytes_left_->SetLabel( wxString::Format("%" PRId32 " bytes too long", -left)); } - bytes_left_->SetForegroundColour( + // whether they changed anything, as in ShowState() + max_matrix::Discard(bytes_left_->SetForegroundColour( (left >= 0) ? wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT) - : CONTROL_WINDOW_TOO_LONG); - send_->Enable(ControlCommand::Fits(line)); + : CONTROL_WINDOW_TOO_LONG)); + max_matrix::Discard(send_->Enable(ControlCommand::Fits(line))); } void ControlWindow::Log(wxString const& text) { log_->AppendText(text); } diff --git a/control/ControlWindow.h b/control/ControlWindow.h index 6ff4df2..d8a5685 100644 --- a/control/ControlWindow.h +++ b/control/ControlWindow.h @@ -77,9 +77,9 @@ class ControlWindow : public wxFrame { wxTextCtrl* log_{}; void MakeMenu(); - wxWindow* MakeMatrix(wxWindow* parent); - wxWindow* MakeText(wxWindow* parent); - wxWindow* MakeConnections(wxWindow* parent); + MAXMATRIX_NODISCARD wxWindow* MakeMatrix(wxWindow* parent); + MAXMATRIX_NODISCARD wxWindow* MakeText(wxWindow* parent); + MAXMATRIX_NODISCARD wxWindow* MakeConnections(wxWindow* parent); void OnSend(wxCommandEvent& event); void OnClear(wxCommandEvent& event); void OnShift(wxCommandEvent& event); @@ -100,11 +100,11 @@ class ControlWindow : public wxFrame { MAXMATRIX_NODISCARD std::string GetSpeedLine() const; MAXMATRIX_NODISCARD std::string GetSpaceLine() const; void Follow(ControlLink& link, char const* name); - ControlLink* GetShownLink(); + MAXMATRIX_NODISCARD ControlLink* GetShownLink(); void ShowState(); void ShowBytesLeft(); void Log(wxString const& text); - static wxString ConvertToText(std::string const& line); + MAXMATRIX_NODISCARD static wxString ConvertToText(std::string const& line); public: /*! \brief Makes the window, with nothing connected. */ diff --git a/control/main.cpp b/control/main.cpp index 8711505..cfa2768 100644 --- a/control/main.cpp +++ b/control/main.cpp @@ -16,6 +16,7 @@ #include #include "ControlWindow.h" +#include "MaxMatrixAttributes.h" /*! * \brief The control program: one window. @@ -31,7 +32,8 @@ class ControlApp : public wxApp { // NOLINT(misc-use-internal-linkage): the * starting. */ bool OnInit() override { - (new ControlWindow())->Show(); + // Show() says whether the window was hidden before, as a new one is. + max_matrix::Discard((new ControlWindow())->Show()); return true; } }; diff --git a/docu/DocuPictures.cpp b/docu/DocuPictures.cpp index 32a66da..608bcc4 100644 --- a/docu/DocuPictures.cpp +++ b/docu/DocuPictures.cpp @@ -732,6 +732,9 @@ int main(int argc, char** argv) { // NOLINT(misc-const-correctness): main() bool const write{arguments[1] == "--write"}; mock::Reset(kDataInPin, kChipSelectPin, kClockPin, kNumberOfModules); - matrix.Init(); + if (!matrix.Init().IsOk()) { + std::cerr << "the matrix does not start on the pins of the examples\n"; + return 1; + } return (WriteOrCheck(DrawPictures(), arguments[2], write) == 0) ? 0 : 1; } diff --git a/docu/DocuSvg.h b/docu/DocuSvg.h index cb9838a..6bd2445 100644 --- a/docu/DocuSvg.h +++ b/docu/DocuSvg.h @@ -18,6 +18,8 @@ #include #include +#include "MaxMatrixAttributes.h" + /*! \brief A point of a picture, in pixels from its left and top. */ struct DocuPoint { int32_t x; /*!< From the left. */ @@ -75,7 +77,7 @@ class DocuSvg { * * \return The SVG text. */ - std::string GetDocument() const; + MAXMATRIX_NODISCARD std::string GetDocument() const; /*! * \brief Adds a rectangle, with an outline 2 pixels wide where it has one. diff --git a/simulator/Avr/SimulatorAvr.cpp b/simulator/Avr/SimulatorAvr.cpp index 941759a..f18ef0c 100644 --- a/simulator/Avr/SimulatorAvr.cpp +++ b/simulator/Avr/SimulatorAvr.cpp @@ -89,10 +89,9 @@ bool SimulatorAvr::Load(char const* elf_file) { return false; } avr_ = avr_make_mcu_by_name(kSimulatorAvrMcu); - if (avr_ == nullptr) { + if ((avr_ == nullptr) || (avr_init(avr_) != 0)) { return false; } - avr_init(avr_); avr_->frequency = kSimulatorAvrFrequency; avr_load_firmware(avr_, &firmware_); ConnectPins(); @@ -121,10 +120,12 @@ void SimulatorAvr::ConnectPins() { // itself, between the panel and the command line. void SimulatorAvr::ConnectUart() { uint32_t flags{0}; - avr_ioctl(avr_, AVR_IOCTL_UART_GET_FLAGS(kUart), &flags); + // Without the flags, simavr also prints the sketch's Serial on the console, + // between the panel and the command line; the run is right all the same. + max_matrix::Discard(avr_ioctl(avr_, AVR_IOCTL_UART_GET_FLAGS(kUart), &flags)); max_matrix::Bit::ClearBits( flags, static_cast(AVR_UART_FLAG_STDIO)); - avr_ioctl(avr_, AVR_IOCTL_UART_SET_FLAGS(kUart), &flags); + max_matrix::Discard(avr_ioctl(avr_, AVR_IOCTL_UART_SET_FLAGS(kUart), &flags)); avr_irq_register_notify( avr_io_getirq(avr_, AVR_IOCTL_UART_GETIRQ(kUart), UART_IRQ_OUTPUT), OnSerialByte, this); diff --git a/simulator/Host/SimulatorSerialHost.cpp b/simulator/Host/SimulatorSerialHost.cpp index 6411e1e..2ecc8fc 100644 --- a/simulator/Host/SimulatorSerialHost.cpp +++ b/simulator/Host/SimulatorSerialHost.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include @@ -32,10 +31,10 @@ SimulatorSerialHost::SimulatorSerialHost() SimulatorSerialHost::~SimulatorSerialHost() { if (client_ != kSimulatorSocketNone) { - close(client_); + SimulatorSocket::Close(client_); } if (listener_ != kSimulatorSocketNone) { - close(listener_); + SimulatorSocket::Close(listener_); } } @@ -85,17 +84,17 @@ void SimulatorSerialHost::AcceptClient() { int accepted{0}; while ((accepted = accept(listener_, nullptr, nullptr)) >= 0) { - if (client_ == kSimulatorSocketNone) { - SimulatorSocket::SetNonBlocking(accepted); + if ((client_ == kSimulatorSocketNone) && + SimulatorSocket::SetNonBlocking(accepted)) { client_ = accepted; } else { - close(accepted); + SimulatorSocket::Close(accepted); } } } // Closes the client's connection, so that the next one may connect. void SimulatorSerialHost::DropClient() { - close(client_); + SimulatorSocket::Close(client_); client_ = kSimulatorSocketNone; } diff --git a/simulator/Host/SimulatorSocket.cpp b/simulator/Host/SimulatorSocket.cpp index 7f5411f..207f822 100644 --- a/simulator/Host/SimulatorSocket.cpp +++ b/simulator/Host/SimulatorSocket.cpp @@ -23,6 +23,7 @@ #include #include +#include "MaxMatrixAttributes.h" #include "Utility/Bit.h" namespace { @@ -44,8 +45,11 @@ int SimulatorSocket::OpenListener(uint16_t port) { return kSimulatorSocketNone; } - // so that a restart does not wait out the last connection's TIME_WAIT - setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); + // So that a restart does not wait out the last connection's TIME_WAIT; + // without it the port is taken a minute longer, which bind() below then + // reports. + max_matrix::Discard( + setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); @@ -54,22 +58,31 @@ int SimulatorSocket::OpenListener(uint16_t port) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) if ((bind(listening, reinterpret_cast(&address), sizeof(address)) != 0) || - (listen(listening, kBacklog) != 0)) { - close(listening); + (listen(listening, kBacklog) != 0) || !SetNonBlocking(listening)) { + Close(listening); return kSimulatorSocketNone; } - SetNonBlocking(listening); return listening; } -void SimulatorSocket::SetNonBlocking(int socket) { +bool SimulatorSocket::SetNonBlocking(int socket) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg): POSIX's fcntl() int const flags{fcntl(socket, F_GETFL, 0)}; + if (flags < 0) { + return false; + } // H-8: fcntl() takes its flags as an int, or'ed here as the bits they are. int const non_blocking_flags{ static_cast(max_matrix::Bit::Combine( static_cast(flags), static_cast(O_NONBLOCK)))}; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg): POSIX's fcntl() - fcntl(socket, F_SETFL, non_blocking_flags); + return fcntl(socket, F_SETFL, non_blocking_flags) == 0; +} + +void SimulatorSocket::Close(int socket) { + // close() frees the descriptor even when it reports an error, and there is + // nothing to try again. + max_matrix::Discard(close(socket)); } bool SimulatorSocket::IsGone(ssize_t received) { @@ -77,7 +90,7 @@ bool SimulatorSocket::IsGone(ssize_t received) { } // setsockopt() takes the timeout in whole seconds and the microseconds beyond. -void SimulatorSocket::SetReceiveTimeout(int socket, +bool SimulatorSocket::SetReceiveTimeout(int socket, std::chrono::milliseconds timeout) { auto const seconds{std::chrono::duration_cast(timeout)}; auto const beyond{ @@ -86,7 +99,7 @@ void SimulatorSocket::SetReceiveTimeout(int socket, wait.tv_sec = static_cast(seconds.count()); wait.tv_usec = static_cast(beyond.count()); - setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait)); + return setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait)) == 0; } bool SimulatorSocket::SendAll(int socket, std::string const& data) { diff --git a/simulator/Host/SimulatorSocket.h b/simulator/Host/SimulatorSocket.h index 49febdb..c8f15dc 100644 --- a/simulator/Host/SimulatorSocket.h +++ b/simulator/Host/SimulatorSocket.h @@ -41,17 +41,27 @@ class SimulatorSocket { * nobody is waiting. * * \param[in] port The port to listen on. - * \return The socket, or `kSimulatorSocketNone` if the port is taken. + * \return The socket, or `kSimulatorSocketNone` if the port is taken or the + * socket would block. */ - static int OpenListener(uint16_t port); + MAXMATRIX_NODISCARD static int OpenListener(uint16_t port); /*! * \brief Lets `socket` return at once: sets O_NONBLOCK, so that polling it * from the tick never stops the sketch. * * \param[in] socket The socket. + * \return True, or false if it still blocks, which the caller must not poll + * then. */ - static void SetNonBlocking(int socket); + MAXMATRIX_NODISCARD static bool SetNonBlocking(int socket); + + /*! + * \brief Closes `socket`. + * + * \param[in] socket The socket. + */ + static void Close(int socket); /*! * \brief Returns whether the other end of a connection is gone, as a recv() @@ -72,8 +82,11 @@ class SimulatorSocket { * \param[in] socket The socket. * \param[in] timeout The longest wait; a duration rather than a number, so * that it cannot take the socket's place (FN-16). + * \return True, or false if recv() would wait without end, which the caller + * must not call then. */ - static void SetReceiveTimeout(int socket, std::chrono::milliseconds timeout); + MAXMATRIX_NODISCARD static bool SetReceiveTimeout( + int socket, std::chrono::milliseconds timeout); /*! * \brief Sends all of `data` on the connection `socket`. diff --git a/simulator/Host/SimulatorWebHost.cpp b/simulator/Host/SimulatorWebHost.cpp index b23d285..152ed9a 100644 --- a/simulator/Host/SimulatorWebHost.cpp +++ b/simulator/Host/SimulatorWebHost.cpp @@ -16,7 +16,6 @@ #include #include #include -#include #include #include @@ -24,6 +23,7 @@ #include #include +#include "MaxMatrixAttributes.h" #include "SimulatorFile.h" #include "SimulatorSocket.h" #include "SimulatorWebSocket.h" @@ -88,11 +88,11 @@ void SimulatorWebHost::AcceptClients() { uint8_t const slot{FindFreeSlot()}; if ((slot < kSimulatorWebHostMaxClients) && - AnswerRequest(accepted, request)) { - SimulatorSocket::SetNonBlocking(accepted); + AnswerRequest(accepted, request) && + SimulatorSocket::SetNonBlocking(accepted)) { clients_[slot] = accepted; } else { - close(accepted); + SimulatorSocket::Close(accepted); } } } @@ -185,7 +185,7 @@ uint8_t SimulatorWebHost::FindFreeSlot() const { // Closes the WebSocket in `slot`, frees the slot and forgets what the client // sent that was not yet a whole frame. void SimulatorWebHost::DropClient(uint8_t slot) { - close(clients_[slot]); + SimulatorSocket::Close(clients_[slot]); clients_[slot] = kSimulatorSocketNone; pending_[slot].clear(); } @@ -207,8 +207,11 @@ std::string SimulatorWebHost::ReadRequest(int socket) { std::string request; std::array chunk{}; - SimulatorSocket::SetReceiveTimeout(socket, kRequestTimeout); - + // Without the timeout a silent client would stop the sketch, so its request + // is not read; it gets no answer, and its connection is closed. + if (!SimulatorSocket::SetReceiveTimeout(socket, kRequestTimeout)) { + return request; + } while (request.find("\r\n\r\n") == std::string::npos) { ssize_t const received{recv(socket, chunk.data(), chunk.size(), 0)}; if (received <= 0) { @@ -247,5 +250,7 @@ void SimulatorWebHost::SendResponse(int socket, char const* status, << "\r\nContent-Length: " << body.size() << "\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n" << body; - SimulatorSocket::SendAll(socket, response.str()); + // The connection is closed after the answer either way, and a browser that + // has gone needs none. + max_matrix::Discard(SimulatorSocket::SendAll(socket, response.str())); } diff --git a/simulator/Host/SimulatorWebHost.h b/simulator/Host/SimulatorWebHost.h index a2acde6..f6924c1 100644 --- a/simulator/Host/SimulatorWebHost.h +++ b/simulator/Host/SimulatorWebHost.h @@ -40,12 +40,13 @@ class SimulatorWebHost { char const* page_path_{nullptr}; void AcceptClients(); - std::vector ReadClient(uint8_t slot); - bool AnswerRequest(int socket, std::string const& request); + MAXMATRIX_NODISCARD std::vector ReadClient(uint8_t slot); + MAXMATRIX_NODISCARD bool AnswerRequest(int socket, + std::string const& request); void SendPage(int socket); MAXMATRIX_NODISCARD uint8_t FindFreeSlot() const; void DropClient(uint8_t slot); - static std::string ReadRequest(int socket); + MAXMATRIX_NODISCARD static std::string ReadRequest(int socket); MAXMATRIX_NODISCARD static SimulatorFoundText GetPath( std::string const& request); static void SendResponse(int socket, char const* status, diff --git a/simulator/Host/SimulatorWebSocket.h b/simulator/Host/SimulatorWebSocket.h index 3a776df..e0fa18e 100644 --- a/simulator/Host/SimulatorWebSocket.h +++ b/simulator/Host/SimulatorWebSocket.h @@ -59,10 +59,12 @@ class SimulatorWebSocket { MAXMATRIX_NODISCARD static SimulatorFoundText GetKey( std::string const& request); - static std::string PadSha1Message(std::string const& message); - static Sha1State ProcessSha1Block(std::string const& padded, size_t offset, - Sha1State state); - static uint32_t MixSha1(uint8_t round, uint32_t b, uint32_t c, uint32_t d); + MAXMATRIX_NODISCARD static std::string PadSha1Message( + std::string const& message); + MAXMATRIX_NODISCARD static Sha1State ProcessSha1Block( + std::string const& padded, size_t offset, Sha1State state); + MAXMATRIX_NODISCARD static uint32_t MixSha1(uint8_t round, uint32_t b, + uint32_t c, uint32_t d); public: /*! @@ -87,7 +89,8 @@ class SimulatorWebSocket { * \note The 64 bit length is never written, as a panel update is a few * hundred bytes: a payload of 64 KiB or more does not fit. */ - static std::string EncodeFrame(std::string const& payload); + MAXMATRIX_NODISCARD static std::string EncodeFrame( + std::string const& payload); /*! * \brief Takes the first frame out of what has arrived. @@ -110,7 +113,8 @@ class SimulatorWebSocket { * \param[in] key The value of `Sec-WebSocket-Key`. * \return The value of `Sec-WebSocket-Accept`. */ - static std::string ConvertKeyToAcceptKey(std::string const& key); + MAXMATRIX_NODISCARD static std::string ConvertKeyToAcceptKey( + std::string const& key); /*! * \brief Calculates the SHA-1 of a message. @@ -118,7 +122,8 @@ class SimulatorWebSocket { * \param[in] message The bytes to hash. * \return The hash. */ - static SimulatorSha1Digest CalculateSha1(std::string const& message); + MAXMATRIX_NODISCARD static SimulatorSha1Digest CalculateSha1( + std::string const& message); /*! * \brief Converts bytes to base64. @@ -128,7 +133,8 @@ class SimulatorWebSocket { * \param[in] bytes The bytes to convert. * \return The base64 text. */ - static std::string ConvertToBase64(std::string const& bytes); + MAXMATRIX_NODISCARD static std::string ConvertToBase64( + std::string const& bytes); }; #endif // MAXMATRIX_SIMULATOR_HOST_SIMULATORWEBSOCKET_H_ diff --git a/simulator/SimulatorPanel.h b/simulator/SimulatorPanel.h index 110610e..654badc 100644 --- a/simulator/SimulatorPanel.h +++ b/simulator/SimulatorPanel.h @@ -42,7 +42,8 @@ class SimulatorPanel { uint32_t last_draw_{0}; bool draw_requested_{true}; - static Max7219Wiring const* FindWiring(std::string const& name); + MAXMATRIX_NODISCARD static Max7219Wiring const* FindWiring( + std::string const& name); public: /*! \brief Makes a panel of the default wiring, mounted upright, that has @@ -59,12 +60,12 @@ class SimulatorPanel { /*! \brief Returns the modules of the model's chain, as mock::Reset() made it. */ - static uint8_t GetNumberOfModules() { + MAXMATRIX_NODISCARD static uint8_t GetNumberOfModules() { return static_cast(mock::chain.chips.size()); } /*! \brief Returns the columns of the model's chain, eight per module. */ - static uint8_t GetNumberOfColumns() { + MAXMATRIX_NODISCARD static uint8_t GetNumberOfColumns() { return static_cast(GetNumberOfModules() * max_matrix::kColumnNumberOfModule); } @@ -78,8 +79,8 @@ class SimulatorPanel { * \param[in] end_of_row What follows every row. * \return The panel. */ - std::string GetText(char const* lit, char const* dark, - char const* end_of_row) const; + MAXMATRIX_NODISCARD std::string GetText(char const* lit, char const* dark, + char const* end_of_row) const; /*! * \brief Returns the brightness of a module. diff --git a/simulator/SimulatorTerminal.h b/simulator/SimulatorTerminal.h index ecbaace..609374c 100644 --- a/simulator/SimulatorTerminal.h +++ b/simulator/SimulatorTerminal.h @@ -14,6 +14,7 @@ #include +#include "MaxMatrixAttributes.h" #include "SimulatorPanel.h" /*! @@ -34,7 +35,8 @@ class SimulatorTerminal { * \param[in] panel The panel to describe. * \return The line, without a line break. */ - static std::string GetStatusLine(SimulatorPanel const& panel); + MAXMATRIX_NODISCARD static std::string GetStatusLine( + SimulatorPanel const& panel); /*! * \brief Clears the terminal. diff --git a/simulator/Web/SimulatorWeb.cpp b/simulator/Web/SimulatorWeb.cpp index 8353b5e..6110396 100644 --- a/simulator/Web/SimulatorWeb.cpp +++ b/simulator/Web/SimulatorWeb.cpp @@ -22,6 +22,7 @@ #include #include "Arduino.h" +#include "MaxMatrixAttributes.h" #include "MaxMatrixConfig.h" #include "SimulatorPanel.h" @@ -126,7 +127,9 @@ void SimulatorWeb::Command(SimulatorPanel& panel, std::string const& message) { std::string const serial_command = kCommandSerial; if (message.compare(0, wiring_command.size(), wiring_command) == 0) { - panel.SetWiring(message.substr(wiring_command.size())); + // An unknown wiring keeps the panel as it is, and the page shows what it + // draws, so it says nothing more. + max_matrix::Discard(panel.SetWiring(message.substr(wiring_command.size()))); } else if (message.compare(0, serial_command.size(), serial_command) == 0) { mock::serial_input += message.substr(serial_command.size()) + "\n"; } else if (message == kCommandUpsideDown) { diff --git a/simulator/Web/SimulatorWeb.h b/simulator/Web/SimulatorWeb.h index d4963b1..16e7525 100644 --- a/simulator/Web/SimulatorWeb.h +++ b/simulator/Web/SimulatorWeb.h @@ -48,7 +48,8 @@ class SimulatorWeb { static void Command(SimulatorPanel& panel, std::string const& message); MAXMATRIX_NODISCARD std::string GetMessage(SimulatorPanel const& panel) const; MAXMATRIX_NODISCARD std::string GetLog() const; - static std::string GetIntensities(SimulatorPanel const& panel); + MAXMATRIX_NODISCARD static std::string GetIntensities( + SimulatorPanel const& panel); public: /*! \brief Makes a web view that has logged no frame yet. */ @@ -91,7 +92,8 @@ class SimulatorWeb { * \param[in] text The bytes, as the sketch printed them. * \return The text for between the quotes of a JSON string. */ - static std::string ConvertToJsonString(std::string const& text); + MAXMATRIX_NODISCARD static std::string ConvertToJsonString( + std::string const& text); }; #endif // MAXMATRIX_SIMULATOR_WEB_SIMULATORWEB_H_