Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
13 changes: 12 additions & 1 deletion OIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down Expand Up @@ -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,
Expand Down
60 changes: 31 additions & 29 deletions control/ControlSerialPort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@
#include <vector>

#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
Expand All @@ -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
Expand Down Expand Up @@ -136,7 +141,7 @@ bool ControlSerialPort::Write(std::string const& data) {
}

bool ControlSerialPort::Read(std::string* data) {
std::array<char, kChunkLength> chunk;
std::array<char, kControlStreamChunkLength> chunk;
DWORD const size = static_cast<DWORD>(chunk.size());
DWORD length = size;

Expand Down Expand Up @@ -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<size_t>(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<char, kChunkLength> 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<size_t>(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() {
Expand Down
86 changes: 86 additions & 0 deletions control/ControlStream.h
Original file line number Diff line number Diff line change
@@ -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 <stddef.h>

#include <array>
#include <string>

/* 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 <typename SendSome, typename WouldBlock, typename WaitWritable>
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<size_t>(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 <typename ReceiveSome, typename WouldBlock>
static bool ReceiveAvailable(std::string& data, ReceiveSome receive_some,
WouldBlock would_block) {
std::array<char, kControlStreamChunkLength> 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<size_t>(length));
}
}
};

#endif // MAXMATRIX_CONTROL_CONTROLSTREAM_H_
56 changes: 25 additions & 31 deletions control/ControlTcpPort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,16 @@
#include <stddef.h>
#include <stdint.h>

#include <array>
#include <string>

#include "ControlStream.h"
#include "ControlTcpPort.h"
#include "Utility/Bit.h"

namespace {

/* ControlTcpPort Parameter */
constexpr intptr_t kNone{(-1)};
constexpr size_t kChunkLength{256u};
constexpr int kWriteTimeoutMs{1000};

#ifdef _WIN32
Expand Down Expand Up @@ -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<size_t>(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<char, kChunkLength> chunk{};

if (!IsOpen()) {
return false;
}
for (;;) {
auto const length{recv(ToSocket(socket_), chunk.data(),
static_cast<int>(chunk.size()), 0)};
if (length > 0) {
data->append(chunk.data(), static_cast<size_t>(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() {
Expand Down
Loading