From 06a4cce831ff4cf2db52cbd4e41cb500a9f81d78 Mon Sep 17 00:00:00 2001 From: virskl Date: Tue, 17 Nov 2026 15:37:48 +0100 Subject: [PATCH 1/2] Host code written out twice is one function (OIL 41, FN-13) The loops that send all and read what has arrived, of the control program's serial port on Linux and its TCP port, are ControlStream's. How a run of either simulator starts and ends, with the chain every example has and the exit codes, is SimulatorRun's; reading a whole file, for the page and --expect, SimulatorFile's; and the test whether a connection is gone SimulatorSocket's, for both hosts. The window makes each line from its fields in one place, the front end says a port is taken in one, and DocuPictures has its pattern and the panel's height once. Left as they are, with the reason in OIL.md: the hosts' Begin(), the accept loops and SimulatorAvr's notifies. The library and its sizes do not change. --- AGENTS.md | 10 ++- CMakeLists.txt | 5 +- OIL.md | 11 ++++ control/ControlSerialPort.cpp | 60 +++++++++--------- control/ControlStream.h | 86 ++++++++++++++++++++++++++ control/ControlTcpPort.cpp | 56 ++++++++--------- control/ControlWindow.cpp | 40 +++++++----- control/ControlWindow.h | 5 ++ docu/DocuPictures.cpp | 39 +++++++----- simulator/Avr/mainAvr.cpp | 45 ++++---------- simulator/Host/SimulatorFile.cpp | 20 ++++++ simulator/Host/SimulatorFile.h | 41 ++++++++++++ simulator/Host/SimulatorSerialHost.cpp | 3 +- simulator/Host/SimulatorSocket.cpp | 9 ++- simulator/Host/SimulatorSocket.h | 13 ++++ simulator/Host/SimulatorWebHost.cpp | 14 ++--- simulator/SimulatorFrontEnd.cpp | 15 +++-- simulator/SimulatorRun.cpp | 34 ++++++++++ simulator/SimulatorRun.h | 70 +++++++++++++++++++++ simulator/SimulatorTerminal.cpp | 20 ++---- simulator/SimulatorTerminal.h | 3 - simulator/main.cpp | 41 +++--------- 22 files changed, 448 insertions(+), 192 deletions(-) create mode 100644 control/ControlStream.h create mode 100644 simulator/Host/SimulatorFile.cpp create mode 100644 simulator/Host/SimulatorFile.h create mode 100644 simulator/SimulatorRun.cpp create mode 100644 simulator/SimulatorRun.h diff --git a/AGENTS.md b/AGENTS.md index b815765..7bf8f9e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,6 +147,8 @@ exception goes at the end of a list, with its reason. serial host; it takes what the sketch printed from the mock once per tick, for all of them. - `SimulatorPanel` — the model's LEDs for a wiring and mounting, and whether to draw again. - `SimulatorTerminal` — the panel redrawn in place, or printed once at the end of `--for`. + - `SimulatorRun` — how a run of either simulator starts, from the command line with the chain + every example has, and ends, with its exit code; `main.cpp` and `mainAvr.cpp` share it. - `Web/` — `SimulatorWeb`, the JSON for `index.html` beside it (read at run time) and its commands; `serial LINE` from the page reaches the sketch's `Serial`, and what the sketch prints goes back in the JSON. @@ -158,7 +160,9 @@ exception goes at the end of a list, with its reason. - `SimulatorSerialHost` — `--tcp PORT`: the sketch's `Serial` as a plain TCP port on loopback, one client at a time, for the control program, which has no WebSocket. - `SimulatorSocket` — what both hosts do with a socket: listen on loopback, never wait, send - all. + all, and tell a connection that is gone. + - `SimulatorFile` — a whole file read into a string, the page the web host serves and the + panel `--expect` names. - `Avr/` — `mainAvr.cpp` and `SimulatorAvr`, the executable `SimulatorAvr`: the same simulator for the `.elf` `avr-gcc` makes of an example (`--elf`). simavr runs it on an ATmega328P, its pins 10, 11 and 13 and its SPI output drive the model, its UART is `Serial`. It writes the @@ -174,7 +178,9 @@ exception goes at the end of a list, with its reason. old Windows tool of `AndreasBur/Led-Matrix`. A CMake project of its own as well, for Windows. Classes start with `Control`; everything but the window is the library `Control`, tested without wxWidgets: - - `ControlPort` — one end: `ControlSerialPort` (`termios` / Win32) or `ControlTcpPort`. + - `ControlPort` — one end: `ControlSerialPort` (`termios` / Win32) or `ControlTcpPort`; + `ControlStream` holds the loops that send all and read what has arrived, which the serial port + on Linux and the TCP port share. - `ControlLink` — the lines over a port, waiting for `ready` on a board, and asking for the `picture` the window shows. - `ControlCommand` — the lines `Command` reads, whether one fits its buffer, and the diff --git a/CMakeLists.txt b/CMakeLists.txt index ac60ff3..4980c00 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,7 +53,8 @@ gtest_discover_tests(Max7219Test TEST_PREFIX "model/") # The simulator's hosts once as well, the web host and the serial port on TCP: they know neither the library nor the # sketch, and the WebSocket half is tested on its own, without a network. add_library(SimulatorHosts STATIC simulator/Host/SimulatorSocket.cpp simulator/Host/SimulatorWebHost.cpp - simulator/Host/SimulatorWebSocket.cpp simulator/Host/SimulatorSerialHost.cpp) + simulator/Host/SimulatorWebSocket.cpp simulator/Host/SimulatorSerialHost.cpp + simulator/Host/SimulatorFile.cpp) # src/ for MaxMatrixAttributes.h alone, as for the model. target_include_directories(SimulatorHosts PUBLIC simulator src) foreach(Test SimulatorWebSocketTest SimulatorWebHostTest SimulatorSerialHostTest) @@ -67,7 +68,7 @@ endforeach() # The rest of the simulator but main.cpp once too: it reads the model, never the library, so the transfer path makes no # difference to it, and its tests need no sketch. add_library(Simulator STATIC simulator/SimulatorOptions.cpp simulator/SimulatorPanel.cpp simulator/SimulatorTerminal.cpp - simulator/Web/SimulatorWeb.cpp simulator/SimulatorFrontEnd.cpp) + simulator/Web/SimulatorWeb.cpp simulator/SimulatorFrontEnd.cpp simulator/SimulatorRun.cpp) target_include_directories(Simulator PUBLIC src) target_link_libraries(Simulator PUBLIC SimulatorHosts ArduinoMock) # read at run time, so that a change to the page needs a reload in the browser rather than a rebuild diff --git a/OIL.md b/OIL.md index 325f4cb..60e2efa 100644 --- a/OIL.md +++ b/OIL.md @@ -1160,6 +1160,17 @@ On the Uno every example 20 bytes of flash smaller with bit banging, with the re `MAXMATRIX_DEV_ERROR_DETECT` and without, and the same with SPI, where only chip select is looked up; the same RAM in every variant. +As built for FN-13 in the host code: what was written out twice or more is one function each. The +loops that send all and read what has arrived, of the serial port on Linux and the TCP port, are +`ControlStream`'s; how a run of either simulator starts and ends is `SimulatorRun`'s, with the +chain every example has; reading a whole file is `SimulatorFile`'s, for the page and `--expect`; +`SimulatorSocket` tells a connection that is gone, for both hosts. The control program's window +makes each line from its fields in one place, the front end says a port is taken in one, and +`DocuPictures` has its pattern and the panel's height once. Left as they are: the two +`Begin()` of the hosts, one shared call and a check; the accept loops, whose bodies differ; and +the seven `avr_irq_register_notify()` of `SimulatorAvr`, one call of simavr each, which a function +of two numbers side by side, the port and the bit, would only make swappable. + ### 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/ControlSerialPort.cpp b/control/ControlSerialPort.cpp index 16f5d57..4ddc7fa 100644 --- a/control/ControlSerialPort.cpp +++ b/control/ControlSerialPort.cpp @@ -31,12 +31,12 @@ #include #include "ControlSerialPort.h" +#include "ControlStream.h" #include "Utility/Bit.h" namespace { /* ControlSerialPort Parameter */ -constexpr size_t kChunkLength{256u}; constexpr int kWriteTimeoutMs{1000}; /* the rates of the Arduino IDE's serial monitor that termios names on every @@ -50,6 +50,11 @@ bool IsBaudRate(uint32_t baud_rate) { kBaudRates.end(); } +#ifndef _WIN32 +// Whether the call that failed only would have had to wait. +bool WouldBlock() { return errno == EAGAIN; } +#endif + } // namespace #ifdef _WIN32 @@ -136,7 +141,7 @@ bool ControlSerialPort::Write(std::string const& data) { } bool ControlSerialPort::Read(std::string* data) { - std::array chunk; + std::array chunk; DWORD const size = static_cast(chunk.size()); DWORD length = size; @@ -236,44 +241,41 @@ bool ControlSerialPort::IsOpen() const { return descriptor_ >= 0; } // kWriteTimeoutMs: a line is a few bytes, and a port that // takes none for that long has no board behind it. bool ControlSerialPort::Write(std::string const& data) { - size_t sent{0}; - if (!IsOpen()) { return false; } - while (sent < data.size()) { - ssize_t const written{write(descriptor_, &data[sent], data.size() - sent)}; - pollfd writable{descriptor_, POLLOUT, 0}; - if (written > 0) { - sent += static_cast(written); - } else if ((written < 0) && (errno == EAGAIN) && - (poll(&writable, 1, kWriteTimeoutMs) > 0)) { - continue; - } else { - Close(); - return false; - } + int const descriptor{descriptor_}; + bool const sent{ControlStream::SendAll( + data, + [descriptor](char const* bytes, size_t length) { + return write(descriptor, bytes, length); + }, + WouldBlock, + [descriptor] { + pollfd writable{descriptor, POLLOUT, 0}; + return poll(&writable, 1, kWriteTimeoutMs) > 0; + })}; + if (!sent) { + Close(); } - return true; + return sent; } bool ControlSerialPort::Read(std::string* data) { - std::array chunk{}; - if (!IsOpen()) { return false; } - for (;;) { - ssize_t const length{read(descriptor_, chunk.data(), chunk.size())}; - if (length > 0) { - data->append(chunk.data(), static_cast(length)); - } else if ((length < 0) && (errno == EAGAIN)) { - return true; - } else { - Close(); - return false; - } + int const descriptor{descriptor_}; + bool const open{ControlStream::ReceiveAvailable( + *data, + [descriptor](char* bytes, size_t length) { + return read(descriptor, bytes, length); + }, + WouldBlock)}; + if (!open) { + Close(); } + return open; } void ControlSerialPort::Close() { diff --git a/control/ControlStream.h b/control/ControlStream.h new file mode 100644 index 0000000..373ec76 --- /dev/null +++ b/control/ControlStream.h @@ -0,0 +1,86 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief How a port that never waits sends all and reads what has arrived: the + * serial port on Linux and the TCP port. + */ + +#ifndef MAXMATRIX_CONTROL_CONTROLSTREAM_H_ +#define MAXMATRIX_CONTROL_CONTROLSTREAM_H_ + +#include + +#include +#include + +/* the bytes ControlStream::ReceiveAvailable() reads at a time */ +constexpr size_t kControlStreamChunkLength{256u}; + +/*! + * \brief The loops of a port that never waits, whatever system calls it makes. + * + * The port hands in its calls: one that sends or reads some bytes and returns + * how many, or less than 0 on an error; one that says whether that error is + * only that the call would have had to wait; and to send, one that waits until + * the port takes bytes again. + */ +class ControlStream { + public: + /*! + * \brief Sends all of `data`, waiting while the port takes nothing. + * + * \param[in] data The bytes to send. + * \param[in] send_some Sends up to a length of bytes from a pointer and + * returns how many it took, or less than 0 on an error. + * \param[in] would_block Returns whether that error was only that the port + * took nothing for now. + * \param[in] wait_writable Waits until the port takes bytes again, and + * returns whether it does before it gives up. + * \return True once all was sent, or false if the port is broken. + */ + template + static bool SendAll(std::string const& data, SendSome send_some, + WouldBlock would_block, WaitWritable wait_writable) { + size_t sent{0}; + + while (sent < data.size()) { + auto const written{send_some(&data[sent], data.size() - sent)}; + if (written > 0) { + sent += static_cast(written); + } else if ((written >= 0) || !would_block() || !wait_writable()) { + return false; + } + } + return true; + } + + /*! + * \brief Reads what has arrived, without waiting for more. + * + * \param[in,out] data Every byte that has arrived is appended. + * \param[in] receive_some Reads up to a length of bytes to a pointer and + * returns how many, 0 if the other end is gone, or + * less than 0 on an error. + * \param[in] would_block Returns whether that error was only that nothing has + * arrived. + * \return True while the port is open, or false once the other end is gone or + * the port is broken. + */ + template + static bool ReceiveAvailable(std::string& data, ReceiveSome receive_some, + WouldBlock would_block) { + std::array chunk{}; + + for (;;) { + auto const length{receive_some(chunk.data(), chunk.size())}; + if (length <= 0) { + return (length < 0) && would_block(); + } + data.append(chunk.data(), static_cast(length)); + } + } +}; + +#endif // MAXMATRIX_CONTROL_CONTROLSTREAM_H_ diff --git a/control/ControlTcpPort.cpp b/control/ControlTcpPort.cpp index aa270bc..abb5e43 100644 --- a/control/ControlTcpPort.cpp +++ b/control/ControlTcpPort.cpp @@ -23,9 +23,9 @@ #include #include -#include #include +#include "ControlStream.h" #include "ControlTcpPort.h" #include "Utility/Bit.h" @@ -33,7 +33,6 @@ namespace { /* ControlTcpPort Parameter */ constexpr intptr_t kNone{(-1)}; -constexpr size_t kChunkLength{256u}; constexpr int kWriteTimeoutMs{1000}; #ifdef _WIN32 @@ -122,46 +121,41 @@ bool ControlTcpPort::Open(uint16_t port) { bool ControlTcpPort::IsOpen() const { return socket_ != kNone; } bool ControlTcpPort::Write(std::string const& data) { - size_t sent{0}; - if (!IsOpen()) { return false; } - while (sent < data.size()) { - auto const written{send(ToSocket(socket_), &data[sent], - ToLength(data.size() - sent), kSendFlags)}; - pollfd writable{ToSocket(socket_), POLLOUT, 0}; - if (written > 0) { - sent += static_cast(written); - } else if ((written < 0) && WouldBlock() && - (Poll(&writable, kWriteTimeoutMs) > 0)) { - continue; - } else { - Close(); - return false; - } + Socket const connection{ToSocket(socket_)}; + bool const sent{ControlStream::SendAll( + data, + [connection](char const* bytes, size_t length) { + return send(connection, bytes, ToLength(length), kSendFlags); + }, + WouldBlock, + [connection] { + pollfd writable{connection, POLLOUT, 0}; + return Poll(&writable, kWriteTimeoutMs) > 0; + })}; + if (!sent) { + Close(); } - return true; + return sent; } bool ControlTcpPort::Read(std::string* data) { - std::array chunk{}; - if (!IsOpen()) { return false; } - for (;;) { - auto const length{recv(ToSocket(socket_), chunk.data(), - static_cast(chunk.size()), 0)}; - if (length > 0) { - data->append(chunk.data(), static_cast(length)); - } else if ((length < 0) && WouldBlock()) { - return true; - } else { - Close(); - return false; - } + Socket const connection{ToSocket(socket_)}; + bool const open{ControlStream::ReceiveAvailable( + *data, + [connection](char* bytes, size_t length) { + return recv(connection, bytes, ToLength(length), 0); + }, + WouldBlock)}; + if (!open) { + Close(); } + return open; } void ControlTcpPort::Close() { diff --git a/control/ControlWindow.cpp b/control/ControlWindow.cpp index f1e09be..10f1e1a 100644 --- a/control/ControlWindow.cpp +++ b/control/ControlWindow.cpp @@ -311,8 +311,7 @@ wxWindow* ControlWindow::MakeConnections(wxWindow* parent) { * line too long". */ void ControlWindow::OnSend(wxCommandEvent& /* event */) { - std::string const line = ControlCommand::MakeText( - std::string(text_->GetValue().ToUTF8()), shift_->GetValue()); + std::string const line = GetTextLine(); if (ControlCommand::Fits(line)) { Broadcast(line); @@ -334,18 +333,15 @@ void ControlWindow::OnClear(wxCommandEvent& /* event */) { void ControlWindow::OnShift(wxCommandEvent& /* event */) { ShowState(); } void ControlWindow::OnIntensity(wxCommandEvent& /* event */) { - BroadcastSetting(ControlCommand::MakeIntensity( - static_cast(intensity_->GetValue()))); + BroadcastSetting(GetIntensityLine()); } void ControlWindow::OnSpeed(wxCommandEvent& /* event */) { - BroadcastSetting( - ControlCommand::MakeSpeed(static_cast(speed_->GetValue()))); + BroadcastSetting(GetSpeedLine()); } void ControlWindow::OnSpace(wxSpinEvent& /* event */) { - Broadcast( - ControlCommand::MakeSpace(static_cast(space_->GetValue()))); + Broadcast(GetSpaceLine()); } // Opens the port in the box, or closes the one that is open. @@ -452,6 +448,26 @@ void ControlWindow::BroadcastSetting(std::string const& line) { Broadcast(line); } +// The line for the text in the field, standing or shifting in as Shift says. +std::string ControlWindow::GetTextLine() const { + return ControlCommand::MakeText(std::string(text_->GetValue().ToUTF8()), + shift_->GetValue()); +} + +// The lines for the intensity, speed and space the window shows. +std::string ControlWindow::GetIntensityLine() const { + return ControlCommand::MakeIntensity( + static_cast(intensity_->GetValue())); +} + +std::string ControlWindow::GetSpeedLine() const { + return ControlCommand::MakeSpeed(static_cast(speed_->GetValue())); +} + +std::string ControlWindow::GetSpaceLine() const { + return ControlCommand::MakeSpace(static_cast(space_->GetValue())); +} + /* * Sends `link` the intensity, speed and space the window shows: its * SerialControl has just started with the ones it was built with, or the @@ -459,10 +475,7 @@ void ControlWindow::BroadcastSetting(std::string const& line) { */ void ControlWindow::SendSettings(ControlLink& link, char const* name) { std::array const lines{ - {ControlCommand::MakeIntensity( - static_cast(intensity_->GetValue())), - ControlCommand::MakeSpeed(static_cast(speed_->GetValue())), - ControlCommand::MakeSpace(static_cast(space_->GetValue()))}}; + {GetIntensityLine(), GetSpeedLine(), GetSpaceLine()}}; for (std::string const& line : lines) { Log(wxString(name) + ": > " + ConvertToText(line) + "\n"); @@ -554,8 +567,7 @@ void ControlWindow::ShowState() { * umlaut takes two, and Shift in five more. */ void ControlWindow::ShowBytesLeft() { - std::string const line = ControlCommand::MakeText( - std::string(text_->GetValue().ToUTF8()), shift_->GetValue()); + std::string const line = GetTextLine(); int32_t const left{ControlCommand::GetBytesLeft(line)}; if (left >= 0) { diff --git a/control/ControlWindow.h b/control/ControlWindow.h index 6c8b537..6ff4df2 100644 --- a/control/ControlWindow.h +++ b/control/ControlWindow.h @@ -21,6 +21,7 @@ #include "ControlLink.h" #include "ControlSerialPort.h" #include "ControlTcpPort.h" +#include "MaxMatrixAttributes.h" class wxButton; // NOLINT(readability-identifier-naming): wxWidgets' name class wxCheckBox; // NOLINT(readability-identifier-naming): wxWidgets' name @@ -94,6 +95,10 @@ class ControlWindow : public wxFrame { void Broadcast(std::string const& line); void BroadcastSetting(std::string const& line); void SendSettings(ControlLink& link, char const* name); + MAXMATRIX_NODISCARD std::string GetTextLine() const; + MAXMATRIX_NODISCARD std::string GetIntensityLine() const; + MAXMATRIX_NODISCARD std::string GetSpeedLine() const; + MAXMATRIX_NODISCARD std::string GetSpaceLine() const; void Follow(ControlLink& link, char const* name); ControlLink* GetShownLink(); void ShowState(); diff --git a/docu/DocuPictures.cpp b/docu/DocuPictures.cpp index ccf604b..3ed2b8c 100644 --- a/docu/DocuPictures.cpp +++ b/docu/DocuPictures.cpp @@ -38,6 +38,8 @@ namespace { /* layout, in pixels */ constexpr int32_t kCell{28}; +/* the height of a module, and so of the panel of one row of them */ +constexpr int32_t kPanelHeight{max_matrix::kRowNumberOfModule * kCell}; constexpr int32_t kLed{22}; constexpr int32_t kModuleGap{28}; constexpr int32_t kLeft{60}; @@ -212,6 +214,20 @@ bool FindLedOfDot(uint8_t x, uint8_t y, DocuLed* led) { return FindLed(led); } +/*! + * \brief Returns whether a dot of the pattern IsUpright() sets is lit. + * + * The pattern has no symmetry a wrong wiring could hide behind, as that of + * MaxMatrixModuleTest. + * + * \param[in] x The column. + * \param[in] y The row. + * \return True for a lit dot. + */ +constexpr bool IsPatternDot(uint8_t x, uint8_t y) { + return (((x * x) + (3 * y) + (x * y)) % 3) == 0; +} + /*! * \brief Returns whether a module of a wiring shows the panel upright. * @@ -227,14 +243,13 @@ bool IsUpright(Max7219Wiring const& wiring) { matrix.Clear(); for (uint8_t x{0}; x < kNumberOfColumns; x++) { for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { - bool const lit{(((x * x) + (3 * y) + (x * y)) % 3) == 0}; - matrix.SetDot(max_matrix::Point{max_matrix::X{x}, max_matrix::Y{y}}, lit); + matrix.SetDot(max_matrix::Point{max_matrix::X{x}, max_matrix::Y{y}}, + IsPatternDot(x, y)); } } for (uint8_t x{0}; x < kNumberOfColumns; x++) { for (uint8_t y{0}; y < max_matrix::kRowNumberOfModule; y++) { - if (mock::chain.IsLit(wiring, x, y) != - ((((x * x) + (3 * y) + (x * y)) % 3) == 0)) { + if (mock::chain.IsLit(wiring, x, y) != IsPatternDot(x, y)) { upright = false; } } @@ -351,14 +366,13 @@ void DrawLed(DocuSvg* svg, Dot dot, char const* colour, */ void DrawModule(DocuSvg* svg, uint8_t module) { int32_t const module_width{max_matrix::kColumnNumberOfModule * kCell}; - int32_t const module_height{max_matrix::kRowNumberOfModule * kCell}; int32_t const left{GetCellX(module * max_matrix::kColumnNumberOfModule)}; - int32_t const middle{kTop + (module_height / 2)}; + int32_t const middle{kTop + (kPanelHeight / 2)}; DocuLed led{}; svg->AddRect({left - kFramePadding, kTop - kFramePadding}, {static_cast(module_width + (2 * kFramePadding)), - static_cast(module_height + (2 * kFramePadding))}, + static_cast(kPanelHeight + (2 * kFramePadding))}, {"none", kColourFrame, kFrameRadius}); svg->AddText({left + (module_width / 2), kTop - kModuleNameAbove}, "Module " + std::to_string(module), kNameText); @@ -380,8 +394,7 @@ void DrawModule(DocuSvg* svg, uint8_t module) { * \param[in,out] svg The picture. */ void DrawAxes(DocuSvg* svg) { - int32_t const module_height{max_matrix::kRowNumberOfModule * kCell}; - int32_t const below{kTop + module_height + kAxisBelow}; + int32_t const below{kTop + kPanelHeight + kAxisBelow}; for (uint8_t x{0}; x < kNumberOfColumns; x++) { svg->AddText({GetCellX(x) + (kCell / 2), below}, std::to_string(x), @@ -393,7 +406,7 @@ void DrawAxes(DocuSvg* svg) { std::to_string(y), kRowAxisText); } svg->AddText( - {kLeft - kAxisNameLeft, kTop + (module_height / 2) + kAxisNameShift}, "Y", + {kLeft - kAxisNameLeft, kTop + (kPanelHeight / 2) + kAxisNameShift}, "Y", kNameText); svg->AddText({kLeft - kAxisLeft, below}, "X", kXText); } @@ -539,8 +552,7 @@ void LabelLitDots(uint8_t bit, PerDot* labels) { * \param[in,out] svg The picture. */ void DrawFunctionNames(DocuSvg* svg) { - int32_t const panel_height{max_matrix::kRowNumberOfModule * kCell}; - int32_t const names{kTop + panel_height + kNamesBelow}; + int32_t const names{kTop + kPanelHeight + kNamesBelow}; int32_t const row_module_left{ GetCellX(kExampleRowModule * max_matrix::kColumnNumberOfModule)}; @@ -566,9 +578,8 @@ void DrawFunctionNames(DocuSvg* svg) { * \return The SVG text. */ std::string DrawCoordinates() { - int32_t const panel_height{max_matrix::kRowNumberOfModule * kCell}; DocuSvg svg{GetPictureWidth(), - kCoordinatesAbove + panel_height + kCoordinatesBelow, + kCoordinatesAbove + kPanelHeight + kCoordinatesBelow, kTop - kCoordinatesAbove}; PerDot column_labels; PerDot row_labels; diff --git a/simulator/Avr/mainAvr.cpp b/simulator/Avr/mainAvr.cpp index 424953e..adfa9c3 100644 --- a/simulator/Avr/mainAvr.cpp +++ b/simulator/Avr/mainAvr.cpp @@ -27,27 +27,14 @@ #include #include -#include "Arduino.h" #include "SimulatorAvr.h" #include "SimulatorFrontEnd.h" #include "SimulatorOptions.h" #include "SimulatorPanel.h" -#include "SimulatorTerminal.h" +#include "SimulatorRun.h" namespace { -/* the pins every example puts the chain on */ -constexpr uint8_t kDataInPin{11u}; -constexpr uint8_t kChipSelectPin{10u}; -constexpr uint8_t kClockPin{13u}; -/* the chain every example has, max_matrix::MatrixOf<4> */ -constexpr uint8_t kNumberOfModules{4u}; - -/* exit codes, as in main.cpp */ -constexpr int kExitOk{0}; -constexpr int kExitFailed{1}; -constexpr int kExitUsage{2}; - // mock::tick is a plain function pointer, so what Tick() works on has to be // reachable without an object. // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) @@ -93,34 +80,28 @@ bool RunAvr() { * * \param[in] argc The number of arguments, the program's name included. * \param[in] argv The arguments. - * \return `kExitOk` if the run with `--for` ended with the panel expected and - * no transfer error; `kExitFailed` if the .elf cannot be read, the port - * is taken, the AVR stopped, or the run with `--for` ended with another - * panel or a transfer error; or `kExitUsage` if the command line is - * wrong. + * \return `kSimulatorRunExitOk` if the run with `--for` ended with the panel + * expected and no transfer error; `kSimulatorRunExitFailed` if the .elf + * cannot be read, the port is taken, the AVR stopped, or the run with + * `--for` ended with another panel or a transfer error; or + * `kSimulatorRunExitUsage` if the command line is wrong. */ int main(int argc, char** argv) { - if (!options.Parse(argc, argv) || (options.GetElfFile() == nullptr) || - !panel.SetWiring(options.GetWiringName())) { + if (!SimulatorRun::SetUp(argc, argv, options, panel) || + (options.GetElfFile() == nullptr)) { SimulatorOptions::PrintUsage(*argv); - return kExitUsage; + return kSimulatorRunExitUsage; } - panel.SetUpsideDown(options.IsUpsideDown()); - mock::Reset(kDataInPin, kChipSelectPin, kClockPin, kNumberOfModules); - mock::serial_input = options.GetSerialInput(); if (!avr.Load(options.GetElfFile())) { std::cerr << options.GetElfFile() << " is no .elf for the " << kSimulatorAvrMcu << '\n'; - return kExitFailed; + return kSimulatorRunExitFailed; } if (!front_end.Begin(options)) { - return kExitFailed; + return kSimulatorRunExitFailed; } if (!RunAvr()) { - return kExitFailed; + return kSimulatorRunExitFailed; } - bool const passed{ - SimulatorTerminal::PrintResult(panel, options.GetExpectFile()) && - (mock::errors == 0)}; - return passed ? kExitOk : kExitFailed; + return SimulatorRun::End(options, panel); } diff --git a/simulator/Host/SimulatorFile.cpp b/simulator/Host/SimulatorFile.cpp new file mode 100644 index 0000000..6c6b9ed --- /dev/null +++ b/simulator/Host/SimulatorFile.cpp @@ -0,0 +1,20 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief A whole file read into a string. + */ + +#include "SimulatorFile.h" + +#include +#include + +SimulatorFileText SimulatorFile::Read(char const* path) { + std::ifstream const file{path}; + std::stringstream content; + + content << file.rdbuf(); + return SimulatorFileText{content.str(), static_cast(file)}; +} diff --git a/simulator/Host/SimulatorFile.h b/simulator/Host/SimulatorFile.h new file mode 100644 index 0000000..a0d3472 --- /dev/null +++ b/simulator/Host/SimulatorFile.h @@ -0,0 +1,41 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief A whole file read into a string: the page the web host serves, and the + * panel a run with `--expect` compares with. + */ + +#ifndef MAXMATRIX_SIMULATOR_HOST_SIMULATORFILE_H_ +#define MAXMATRIX_SIMULATOR_HOST_SIMULATORFILE_H_ + +#include + +#include "MaxMatrixAttributes.h" + +/*! \brief A file's text as SimulatorFile::Read() gives it. */ +struct SimulatorFileText { + std::string text; /*!< What was read; all of the file if `complete`. */ + bool complete; /*!< Whether the file was read to its end. */ +}; + +/*! + * \brief A whole file read into a string. + * + * It has no state of its own, so its function is static, as in + * max_matrix::Font. + */ +class SimulatorFile { + public: + /*! + * \brief Reads the whole file at `path`. + * + * \param[in] path The file. + * \return Its text, and whether it was read to its end; of a file that cannot + * be read, what was read even so, for the caller to show. + */ + MAXMATRIX_NODISCARD static SimulatorFileText Read(char const* path); +}; + +#endif // MAXMATRIX_SIMULATOR_HOST_SIMULATORFILE_H_ diff --git a/simulator/Host/SimulatorSerialHost.cpp b/simulator/Host/SimulatorSerialHost.cpp index 325e0cc..0ac4ab1 100644 --- a/simulator/Host/SimulatorSerialHost.cpp +++ b/simulator/Host/SimulatorSerialHost.cpp @@ -9,7 +9,6 @@ #include "SimulatorSerialHost.h" -#include #include #include #include @@ -59,7 +58,7 @@ void SimulatorSerialHost::Task(std::string* received) { if (length > 0) { received->append(chunk.data(), static_cast(length)); } else { - if ((length == 0) || ((errno != EAGAIN) && (errno != EWOULDBLOCK))) { + if (SimulatorSocket::IsGone(length)) { DropClient(); } break; diff --git a/simulator/Host/SimulatorSocket.cpp b/simulator/Host/SimulatorSocket.cpp index 4788f1e..7f5411f 100644 --- a/simulator/Host/SimulatorSocket.cpp +++ b/simulator/Host/SimulatorSocket.cpp @@ -30,6 +30,9 @@ namespace { /* SimulatorSocket Parameter */ constexpr int kBacklog{4}; +// Whether the call that failed only would have had to wait. +bool WouldBlock() { return (errno == EAGAIN) || (errno == EWOULDBLOCK); } + } // namespace int SimulatorSocket::OpenListener(uint16_t port) { @@ -69,6 +72,10 @@ void SimulatorSocket::SetNonBlocking(int socket) { fcntl(socket, F_SETFL, non_blocking_flags); } +bool SimulatorSocket::IsGone(ssize_t received) { + return (received == 0) || ((received < 0) && !WouldBlock()); +} + // setsockopt() takes the timeout in whole seconds and the microseconds beyond. void SimulatorSocket::SetReceiveTimeout(int socket, std::chrono::milliseconds timeout) { @@ -90,7 +97,7 @@ bool SimulatorSocket::SendAll(int socket, std::string const& data) { send(socket, &data[sent], data.size() - sent, MSG_NOSIGNAL)}; if (written > 0) { sent += static_cast(written); - } else if ((written < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) { + } else if ((written < 0) && WouldBlock()) { continue; } else { return false; diff --git a/simulator/Host/SimulatorSocket.h b/simulator/Host/SimulatorSocket.h index 795c9dd..49febdb 100644 --- a/simulator/Host/SimulatorSocket.h +++ b/simulator/Host/SimulatorSocket.h @@ -14,10 +14,13 @@ #define MAXMATRIX_SIMULATOR_HOST_SIMULATORSOCKET_H_ #include +#include #include #include +#include "MaxMatrixAttributes.h" + /* SimulatorSocket Parameter */ constexpr int kSimulatorSocketNone{(-1)}; @@ -50,6 +53,16 @@ class SimulatorSocket { */ static void SetNonBlocking(int socket); + /*! + * \brief Returns whether the other end of a connection is gone, as a recv() + * on it says: closed, or broken. + * + * \param[in] received What recv() returned. + * \return True if it returned 0 or failed for another reason than that + * nothing has arrived yet. + */ + MAXMATRIX_NODISCARD static bool IsGone(ssize_t received); + /*! * \brief Lets recv() on the blocking `socket` give up after a while. * diff --git a/simulator/Host/SimulatorWebHost.cpp b/simulator/Host/SimulatorWebHost.cpp index f0f5ea5..58b7c81 100644 --- a/simulator/Host/SimulatorWebHost.cpp +++ b/simulator/Host/SimulatorWebHost.cpp @@ -12,7 +12,6 @@ #include "SimulatorWebHost.h" -#include #include #include #include @@ -21,11 +20,11 @@ #include #include -#include #include #include #include +#include "SimulatorFile.h" #include "SimulatorSocket.h" #include "SimulatorWebSocket.h" @@ -106,8 +105,7 @@ void SimulatorWebHost::ReadClient(uint8_t slot, uint8_t opcode{0}; std::string payload; - if ((received == 0) || - ((received < 0) && (errno != EAGAIN) && (errno != EWOULDBLOCK))) { + if (SimulatorSocket::IsGone(received)) { DropClient(slot); return; } @@ -156,12 +154,10 @@ bool SimulatorWebHost::AnswerRequest(int socket, std::string const& request) { // Sends the page on the connection `socket`, read from its path every time, so // that the browser always gets the current one. void SimulatorWebHost::SendPage(int socket) { - std::ifstream const file{page_path_}; - std::stringstream body; + SimulatorFileText const page{SimulatorFile::Read(page_path_)}; - body << file.rdbuf(); - if (file) { - SendResponse(socket, "200 OK", "text/html; charset=utf-8", body.str()); + if (page.complete) { + SendResponse(socket, "200 OK", "text/html; charset=utf-8", page.text); } else { SendResponse(socket, "500 Internal Server Error", "text/plain", std::string("cannot read ") + page_path_ + "\n"); diff --git a/simulator/SimulatorFrontEnd.cpp b/simulator/SimulatorFrontEnd.cpp index 9520df4..46b58ff 100644 --- a/simulator/SimulatorFrontEnd.cpp +++ b/simulator/SimulatorFrontEnd.cpp @@ -19,6 +19,15 @@ #include "SimulatorPanel.h" #include "SimulatorTerminal.h" +namespace { + +// Says that `port` is taken, which another simulator does most often. +void ReportTaken(uint16_t port) { + std::cerr << "port " << port << " is taken, maybe by another simulator\n"; +} + +} // namespace + SimulatorFrontEnd::SimulatorFrontEnd() = default; bool SimulatorFrontEnd::Begin(SimulatorOptions const& options) { @@ -27,16 +36,14 @@ bool SimulatorFrontEnd::Begin(SimulatorOptions const& options) { if (web_on_) { if (!web_.Begin(options.GetPort(), SIMULATOR_PAGE)) { - std::cerr << "port " << options.GetPort() - << " is taken, maybe by another simulator\n"; + ReportTaken(options.GetPort()); return false; } std::cout << "http://localhost:" << options.GetPort() << "/\n"; } if (options.GetTcpPort() != 0) { if (!serial_host_.Begin(options.GetTcpPort())) { - std::cerr << "port " << options.GetTcpPort() - << " is taken, maybe by another simulator\n"; + ReportTaken(options.GetTcpPort()); return false; } std::cout << "Serial on localhost:" << options.GetTcpPort() << '\n'; diff --git a/simulator/SimulatorRun.cpp b/simulator/SimulatorRun.cpp new file mode 100644 index 0000000..f799dda --- /dev/null +++ b/simulator/SimulatorRun.cpp @@ -0,0 +1,34 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief How a run of either simulator starts and ends. + */ + +#include "SimulatorRun.h" + +#include "Arduino.h" +#include "SimulatorOptions.h" +#include "SimulatorPanel.h" +#include "SimulatorTerminal.h" + +bool SimulatorRun::SetUp(int argc, char** argv, SimulatorOptions& options, + SimulatorPanel& panel) { + if (!options.Parse(argc, argv) || !panel.SetWiring(options.GetWiringName())) { + return false; + } + panel.SetUpsideDown(options.IsUpsideDown()); + mock::Reset(kSimulatorRunDataInPin, kSimulatorRunChipSelectPin, + kSimulatorRunClockPin, kSimulatorRunNumberOfModules); + mock::serial_input = options.GetSerialInput(); + return true; +} + +int SimulatorRun::End(SimulatorOptions const& options, + SimulatorPanel const& panel) { + bool const as_expected{ + SimulatorTerminal::PrintResult(panel, options.GetExpectFile())}; + bool const passed{as_expected && (mock::errors == 0)}; + return passed ? kSimulatorRunExitOk : kSimulatorRunExitFailed; +} diff --git a/simulator/SimulatorRun.h b/simulator/SimulatorRun.h new file mode 100644 index 0000000..57a061a --- /dev/null +++ b/simulator/SimulatorRun.h @@ -0,0 +1,70 @@ +// Copyright 2026 Andreas Burnickl +// SPDX-License-Identifier: GPL-3.0-or-later + +/*! + * \file + * \brief How a run of either simulator starts and ends: the chain every example + * has, the command line, and the exit code. + */ + +#ifndef MAXMATRIX_SIMULATOR_SIMULATORRUN_H_ +#define MAXMATRIX_SIMULATOR_SIMULATORRUN_H_ + +#include + +#include "MaxMatrixAttributes.h" +#include "SimulatorOptions.h" +#include "SimulatorPanel.h" + +/* the pins every example puts the chain on, and the chain it has, + * max_matrix::MatrixOf<4> */ +constexpr uint8_t kSimulatorRunDataInPin{11u}; +constexpr uint8_t kSimulatorRunChipSelectPin{10u}; +constexpr uint8_t kSimulatorRunClockPin{13u}; +constexpr uint8_t kSimulatorRunNumberOfModules{4u}; + +/* exit codes */ +constexpr int kSimulatorRunExitOk{0}; +constexpr int kSimulatorRunExitFailed{1}; +constexpr int kSimulatorRunExitUsage{2}; + +/*! + * \brief How a run of the simulator on the host and of SimulatorAvr starts and + * ends. + * + * It has no state of its own, so every function is static, as in + * max_matrix::Font. + */ +class SimulatorRun { + public: + /*! + * \brief Sets a run up from its command line. + * + * It reads the options, draws the panel for their wiring and mounting, and + * gives the mock the chain every example has and the serial input. + * + * \param[in] argc The number of arguments, the program's name included. + * \param[in] argv The arguments. + * \param[out] options The options read. + * \param[out] panel The panel, for the wiring and mounting read. + * \return True, or false if the command line is wrong or names no wiring + * there is. + */ + MAXMATRIX_NODISCARD static bool SetUp(int argc, char** argv, + SimulatorOptions& options, + SimulatorPanel& panel); + + /*! + * \brief Ends a run with `--for`: prints the panel and says how it went. + * + * \param[in] options The options of the run, with the expected panel. + * \param[in] panel The panel at the end. + * \return `kSimulatorRunExitOk` if the panel is the one expected, or none is, + * and no frame reached the chain broken; else + * `kSimulatorRunExitFailed`. + */ + MAXMATRIX_NODISCARD static int End(SimulatorOptions const& options, + SimulatorPanel const& panel); +}; + +#endif // MAXMATRIX_SIMULATOR_SIMULATORRUN_H_ diff --git a/simulator/SimulatorTerminal.cpp b/simulator/SimulatorTerminal.cpp index e5e8a12..1b8111b 100644 --- a/simulator/SimulatorTerminal.cpp +++ b/simulator/SimulatorTerminal.cpp @@ -12,12 +12,12 @@ #include -#include #include #include #include #include "Arduino.h" +#include "Host/SimulatorFile.h" #include "SimulatorPanel.h" namespace { @@ -69,28 +69,16 @@ void SimulatorTerminal::Draw(SimulatorPanel const& panel) { bool SimulatorTerminal::PrintResult(SimulatorPanel const& panel, char const* expect_file) { std::string const result = panel.GetText(kResultLit, kResultDark, "\n"); - std::string expected; std::cout << result; if (expect_file == nullptr) { return true; } - if (!ReadFile(expect_file, &expected) || (expected != result)) { - std::cerr << "differs from " << expect_file << ":\n" << expected; + SimulatorFileText const expected{SimulatorFile::Read(expect_file)}; + if (!expected.complete || (expected.text != result)) { + std::cerr << "differs from " << expect_file << ":\n" << expected.text; return false; } return true; } - -// Reads the whole file at `path` into `text`. Returns false if it cannot be -// read; `text` then holds what was read even so, so that the caller can show -// it. -bool SimulatorTerminal::ReadFile(char const* path, std::string* text) { - std::ifstream const file{path}; - std::stringstream content; - - content << file.rdbuf(); - *text = content.str(); - return static_cast(file); -} diff --git a/simulator/SimulatorTerminal.h b/simulator/SimulatorTerminal.h index ca6b0ca..ecbaace 100644 --- a/simulator/SimulatorTerminal.h +++ b/simulator/SimulatorTerminal.h @@ -23,9 +23,6 @@ * max_matrix::Font. */ class SimulatorTerminal { - private: - static bool ReadFile(char const* path, std::string* text); - public: /*! * \brief Returns the line above the panel. diff --git a/simulator/main.cpp b/simulator/main.cpp index 10dadee..791212e 100644 --- a/simulator/main.cpp +++ b/simulator/main.cpp @@ -40,23 +40,7 @@ #include "SimulatorFrontEnd.h" #include "SimulatorOptions.h" #include "SimulatorPanel.h" -#include "SimulatorTerminal.h" - -namespace { - -/* the pins every example puts the chain on */ -constexpr uint8_t kDataInPin{11u}; -constexpr uint8_t kChipSelectPin{10u}; -constexpr uint8_t kClockPin{13u}; -/* the chain every example has, max_matrix::MatrixOf<4> */ -constexpr uint8_t kNumberOfModules{4u}; - -/* exit codes */ -constexpr int kExitOk{0}; -constexpr int kExitFailed{1}; -constexpr int kExitUsage{2}; - -} // namespace +#include "SimulatorRun.h" /* the sketch's, compiled into the same program */ void setup(); // NOLINT(readability-identifier-naming): Arduino's name @@ -79,13 +63,7 @@ SimulatorFrontEnd front_end; * It prints the panel and exits, from within the sketch's loop() or delay(), * which never return on their own. */ -[[noreturn]] void Finish() { - bool const passed{ - SimulatorTerminal::PrintResult(panel, options.GetExpectFile()) && - (mock::errors == 0)}; - - exit(passed ? kExitOk : kExitFailed); -} +[[noreturn]] void Finish() { exit(SimulatorRun::End(options, panel)); } /*! * \brief Follows the sketch. @@ -112,24 +90,21 @@ void Tick() { * * \param[in] argc The number of arguments, the program's name included. * \param[in] argv The arguments. - * \return `kExitFailed` if the port is taken, or `kExitUsage` if the command - * line is wrong. + * \return `kSimulatorRunExitFailed` if the port is taken, or + * `kSimulatorRunExitUsage` if the command line is wrong. * \note It returns only on these errors: a run with `--for` exits from * Finish(), and one without runs until Ctrl+C. */ int main(int argc, char** argv) { /* the sketch is built in; an .elf is for SimulatorAvr */ - if (!options.Parse(argc, argv) || (options.GetElfFile() != nullptr) || - !panel.SetWiring(options.GetWiringName())) { + if (!SimulatorRun::SetUp(argc, argv, options, panel) || + (options.GetElfFile() != nullptr)) { SimulatorOptions::PrintUsage(*argv); - return kExitUsage; + return kSimulatorRunExitUsage; } - panel.SetUpsideDown(options.IsUpsideDown()); - mock::Reset(kDataInPin, kChipSelectPin, kClockPin, kNumberOfModules); - mock::serial_input = options.GetSerialInput(); mock::tick = Tick; if (!front_end.Begin(options)) { - return kExitFailed; + return kSimulatorRunExitFailed; } setup(); From 3356d6ce443621d57e8ba8f4fd0e0cbd86ea0663 Mon Sep 17 00:00:00 2001 From: virskl Date: Tue, 17 Nov 2026 15:37:58 +0100 Subject: [PATCH 2/2] OIL.md: 41 is #125 as well --- OIL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OIL.md b/OIL.md index 60e2efa..778c612 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 | +| 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 | | 42 | A newer avr-gcc as a cross-check | 41 | done | | | 43 | Bit operations in one class, from the template | 41 | done | #109 |