17#ifndef FDO2_PROTOCOL_HPP
18#define FDO2_PROTOCOL_HPP
122 requires(std::is_same_v<T, uint8_t> || std::is_same_v<T, char>)
124 uint32_t crc = 0xFFFFU;
125 for (
const T item : data) {
127 static_cast<uint32_t
>(std::bit_cast<uint8_t>(item));
128 for (uint32_t bit = 0U; bit < 8U; ++bit) {
129 const bool lsb = (crc & 1U) != 0U;
136 return static_cast<uint16_t
>(crc);
142inline constexpr std::array<char, 10> kDecimalDigits{
'0',
'1',
'2',
'3',
'4',
143 '5',
'6',
'7',
'8',
'9'};
146inline constexpr std::array<char, 26> kCapitalLetters{
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
147 'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
148 'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z'};
151constexpr bool SameChar(
char first,
char second)
noexcept {
152 return std::array<char, 1>{first} == std::array<char, 1>{second};
156template <std::
size_t N>
157constexpr bool OneOf(
char c,
const std::array<char, N>& set)
noexcept {
158 return std::find(set.begin(), set.end(), c) != set.end();
162constexpr bool PutInt(std::span<char> out, std::size_t& pos, int32_t value)
noexcept {
163 std::array<char, 12> digits{};
165 const bool neg = value < 0;
166 uint32_t mag = neg ? (0U -
static_cast<uint32_t
>(value)) : static_cast<uint32_t>(value);
168 digits[n] = kDecimalDigits[mag % 10U];
172 const std::size_t total = n + (neg ? 1U : 0U);
173 if ((pos + total) > out.size()) {
182 out[pos] = digits[n];
189constexpr std::size_t FixedArgCount(
Command command)
noexcept {
214constexpr bool OneArgumentValid(
Command command, int32_t value)
noexcept {
217 return (value == 0) || (value == 1);
223 return (value == 0) || (std::cmp_greater_equal(value,
kBroadcastMinMs) &&
242constexpr bool UserMemoryArgumentsValid(
bool is_write, std::span<const int32_t> args)
noexcept {
243 if (args.size() < 2U) {
246 const int64_t first = args[0];
247 const int64_t count = args[1];
249 (first >= 0) && (first <= 63) && (count >= 1) && (count <= 64) && ((first + count) <= 64);
250 const bool length_ok =
251 is_write ? (
static_cast<int64_t
>(args.size()) == (count + 2)) : (args.size() == 2U);
252 return span_ok && length_ok;
256constexpr bool ArgumentsValid(
Command command, std::span<const int32_t> args)
noexcept {
263 return (args.size() == 1U) && OneArgumentValid(command, args[0]);
266 return UserMemoryArgumentsValid(command ==
Command::Wrum, args);
295 std::span<char> out)
noexcept {
296 if (!detail::IsEnumerator(command) || !detail::ArgumentsValid(command, args)) {
299 const char* header =
HeaderOf(command);
300 std::size_t pos = 0U;
301 if (out.size() < 6U) {
306 for (std::size_t i = 0U; i < 4U; ++i) {
307 out[pos] = header[i];
310 for (
const int32_t value : args) {
316 if (!detail::PutInt(out, pos, value)) {
320 if (pos >= out.size()) {
353 constexpr
void Reset(
bool ignore_lf) noexcept {
357 ignore_lf_ = ignore_lf;
377 if ((
byte == 0x0AU) && ignore_lf_ && (len_ == 0U)) {
380 if ((
byte < 0x20U) || (
byte > 0x7EU) || (len_ >= (
kMaxLineLength - 1U))) {
381 discarded_ +=
static_cast<uint32_t
>(len_) + 1U;
386 buf_[len_] = std::bit_cast<char>(
byte);
392 [[nodiscard]]
constexpr std::span<const char>
Line() const noexcept {
393 return std::span<const char>{buf_}.first(len_);
398 const uint32_t n = discarded_;
407 [[nodiscard]]
constexpr std::size_t
Pending() const noexcept {
424 std::array<char, kMaxLineLength> buf_{};
426 uint32_t discarded_{0};
427 bool discarding_{
false};
429 bool ignore_lf_{
true};
458 std::array<int64_t, kMaxValues>
values{};
465constexpr bool ParseNumber(std::span<const char> token,
bool& negative, uint64_t& mag)
noexcept {
472 if (SameChar(token[0],
'-')) {
476 const std::size_t digits = token.size() - i;
477 if ((digits == 0U) || (digits > 20U)) {
480 if (SameChar(token[i],
'0') && ((digits > 1U) || negative)) {
483 for (; i < token.size(); ++i) {
484 const auto*
const found = std::find(kDecimalDigits.begin(), kDecimalDigits.end(), token[i]);
485 if (found == kDecimalDigits.end()) {
489 static_cast<uint64_t
>(found - kDecimalDigits.begin());
490 if (mag > ((0xFFFF'FFFF'FFFF'FFFFULL - d) / 10U)) {
493 mag = (mag * 10U) + d;
499enum class ValueKind : uint8_t { Int32, UInt32, UInt64 };
503constexpr ValueKind FieldOf(
Command command, std::size_t index)
noexcept {
505 return ValueKind::UInt64;
508 return ValueKind::UInt32;
510 return ValueKind::Int32;
514constexpr bool ConvertValue(ValueKind kind, std::span<const char> token, int64_t& out,
515 uint64_t& big)
noexcept {
518 if (!ParseNumber(token, neg, mag)) {
522 case ValueKind::UInt64:
526 case ValueKind::UInt32:
527 out =
static_cast<int64_t
>(mag);
528 return !neg && (mag <= 0xFFFF'FFFFULL);
529 case ValueKind::Int32:
531 out = (mag <= 2'147'483'648ULL) ? -
static_cast<int64_t
>(mag) : 0;
532 return mag <= 2'147'483'648ULL;
534 out =
static_cast<int64_t
>(mag);
535 return mag <= 2'147'483'647ULL;
543constexpr bool FindCommand(std::span<const char> letters,
Command& out)
noexcept {
544 if (letters.size() < 4U) {
547 for (uint8_t i = 0U; i <= static_cast<uint8_t>(
Command::Setm); ++i) {
548 const auto candidate =
static_cast<Command>(i);
549 const char* header =
HeaderOf(candidate);
550 if (SameChar(letters[0], header[0]) && SameChar(letters[1], header[1]) &&
551 SameChar(letters[2], header[2]) && SameChar(letters[3], header[3])) {
560constexpr bool ParseValues(std::span<const char> rest,
bool strict,
Command command,
bool erro,
561 ParsedLine& out)
noexcept {
562 std::size_t pos = 0U;
563 while (pos < rest.size()) {
564 if (!SameChar(rest[pos],
' ')) {
569 while ((pos < rest.size()) && (SameChar(rest[pos],
' '))) {
572 if (pos >= rest.size()) {
576 std::size_t end = pos;
577 while ((end < rest.size()) && (!SameChar(rest[end],
' '))) {
580 if ((end == pos) || (out.count >=
kMaxValues)) {
583 const std::span<const char> token = rest.subspan(pos, end - pos);
585 const ValueKind kind = erro ? ValueKind::Int32 : FieldOf(command, out.count);
586 if (!ConvertValue(kind, token, value, out.big)) {
589 out.values[out.count] = value;
597constexpr ParseStatus SplitCrc(std::span<const char> line, std::span<const char>& body,
598 bool& suffix, uint32_t& crc)
noexcept {
601 std::size_t colon = line.size();
602 for (std::size_t i = 0U; i < line.size(); ++i) {
603 if (SameChar(line[i],
':')) {
607 if (colon == line.size()) {
611 if (((colon + 2U) >= line.size()) || (!SameChar(line[colon + 1U],
' '))) {
614 const std::size_t digits = line.size() - colon - 2U;
620 if (!ParseNumber(line.subspan(colon + 2U), neg, mag) || neg || (mag > 0xFFFFU)) {
623 body = line.first(colon);
625 crc =
static_cast<uint32_t
>(mag);
630constexpr ParseStatus CheckCrc(std::span<const char> body,
bool suffix, uint32_t crc,
bool is_erro,
631 const ParseOptions& options)
noexcept {
632 if (suffix && options.crc_forbidden) {
635 if (suffix && (
Crc16Modbus(body) !=
static_cast<uint16_t
>(crc))) {
638 if (!suffix && options.crc_required && !(is_erro && options.erro_without_crc)) {
645constexpr bool TakeErrorCode(ParsedLine& line)
noexcept {
646 if ((line.count != 1U) || (line.values[0] >= 0)) {
649 line.error_code =
static_cast<int32_t
>(line.values[0]);
654constexpr bool IsErroHeader(std::span<const char> body)
noexcept {
655 return (body.size() >= 5U) && (SameChar(body[0],
'#')) && (SameChar(body[1],
'E')) &&
656 (SameChar(body[2],
'R')) && (SameChar(body[3],
'R')) && (SameChar(body[4],
'O'));
660constexpr bool HasHeader(std::span<const char> body)
noexcept {
661 if ((body.size() < 5U) || (!SameChar(body[0],
'#'))) {
664 for (std::size_t i = 1U; i < 5U; ++i) {
665 if (!OneOf(body[i], kCapitalLetters)) {
669 return (body.size() == 5U) || (SameChar(body[5],
' '));
689 std::span<const char> body{};
695 const bool is_erro = detail::IsErroHeader(body);
696 const ParseStatus crc_status = detail::CheckCrc(body, suffix, crc, is_erro, options);
698 out.status = crc_status;
701 if (!detail::HasHeader(body)) {
704 out.crc_present = suffix;
706 out.known = is_erro || detail::FindCommand(body.subspan(1U, 4U), out.command);
711 const bool strict = options.strict_spacing || is_erro;
712 if (!detail::ParseValues(body.subspan(5U), strict, out.command, is_erro, out)) {
716 if (is_erro && !detail::TakeErrorCode(out)) {
748 return (args.size() >= 2U) ? (2U +
static_cast<std::size_t
>(args[1])) : 0U;
766 if (!reply.known || reply.erro || (reply.command != command)) {
769 const std::size_t echoed = args.size();
774 if (reply.count < echoed) {
777 for (std::size_t i = 0U; i < echoed; ++i) {
778 if (reply.values[i] !=
static_cast<int64_t
>(args[i])) {
804 return 32U + (12U * words);
Collects the bytes of a reply into lines, one byte at a time (datasheet 4.1: one CR ends a reply).
Definition fdo2_protocol.hpp:344
constexpr uint32_t TakeDiscarded() noexcept
Definition fdo2_protocol.hpp:397
constexpr void Reset(bool ignore_lf) noexcept
Drop the partial line and the discard state.
Definition fdo2_protocol.hpp:353
constexpr std::span< const char > Line() const noexcept
Definition fdo2_protocol.hpp:392
constexpr bool Discarding() const noexcept
Definition fdo2_protocol.hpp:403
constexpr std::size_t Pending() const noexcept
Definition fdo2_protocol.hpp:407
constexpr LineAssembler() noexcept=default
An empty assembler that ignores a leading LF.
constexpr PushResult PushByte(uint8_t byte) noexcept
Feed one byte.
Definition fdo2_protocol.hpp:365
Public types of the FDO2 driver: errors, Result<T>, the status word, measurements,...
constexpr const char * HeaderOf(Command command) noexcept
The four header letters of a command, without the #.
Definition fdo2_protocol.hpp:79
ParseStatus
The outcome class of ParseLine().
Definition fdo2_protocol.hpp:433
constexpr std::size_t kMaxValues
Most values a reply holds: #RDUM R N and 64 words.
Definition fdo2_protocol.hpp:45
constexpr std::size_t kMaxLineLength
Definition fdo2_protocol.hpp:41
PushResult
What LineAssembler::PushByte() did with a byte.
Definition fdo2_protocol.hpp:329
constexpr std::size_t ExpectedCount(Command command, std::span< const int32_t > args) noexcept
How many values the reply to a command holds (datasheet 4.3).
Definition fdo2_protocol.hpp:730
constexpr uint32_t MaxReplyChars(Command command, uint32_t words) noexcept
The longest reply of a command, in characters including the CR and a CRC suffix, for the deadline (de...
Definition fdo2_protocol.hpp:792
constexpr ParsedLine ParseLine(std::span< const char > line, const ParseOptions &options) noexcept
Parse one reply line (without its CR) under the grammar of datasheet 4.
Definition fdo2_protocol.hpp:687
constexpr std::size_t EncodeCommand(Command command, std::span< const int32_t > args, std::span< char > out) noexcept
Encode a command line: #HEAD, each argument as plain decimal with one space before it,...
Definition fdo2_protocol.hpp:294
Command
The thirteen commands of the module (datasheet 4.3).
Definition fdo2_protocol.hpp:50
constexpr uint16_t Crc16Modbus(std::span< const T > data) noexcept
The CRC-16/MODBUS of a byte or character string (polynomial 0xA001 reflected, start 0xFFFF),...
Definition fdo2_protocol.hpp:123
constexpr uint32_t kMaxStale
Complete lines of another command dropped per transaction before the reply is InvalidReply.
Definition fdo2_protocol.hpp:47
constexpr bool VerifyEcho(Command command, std::span< const int32_t > args, const ParsedLine &reply) noexcept
The echo check of datasheet 4.2: the header and the echoed arguments equal what was sent.
Definition fdo2_protocol.hpp:764
constexpr std::size_t kMaxCommandLength
Longest command line the driver sends (#WRUM 0 64 and 64 values), including the CR.
Definition fdo2_protocol.hpp:43
@ Malformed
The line breaks the grammar.
@ BadCrc
A CRC suffix is wrong, or required and missing.
@ Ok
The line follows the grammar (and its CRC matches when present).
@ Pending
The line is not complete.
@ Line
A carriage return completed a line: Line() holds it (without the CR).
@ Bad
The byte, or the length, broke the grammar; the line is discarded to the next CR.
@ Wrum
#WRUM R N Y1 ... YN
constexpr uint32_t kBroadcastMaxMs
Longest broadcast interval, milliseconds.
Definition fdo2_types.hpp:442
constexpr uint32_t kBroadcastMinMs
Shortest and longest broadcast interval, milliseconds (#BCST).
Definition fdo2_types.hpp:440
constexpr bool IsSupportedBaud(uint32_t baud) noexcept
Whether baud is one of the eleven rates.
Definition fdo2_types.hpp:490
constexpr uint32_t kMaxMeasurementMode
Highest #SETM mode.
Definition fdo2_types.hpp:444
The FDO2 driver: everything it declares lives here; internals in detail.
Definition fdo2.hpp:33
How ParseLine() treats the CRC and the spacing (from the Config).
Definition fdo2_protocol.hpp:440
bool strict_spacing
Exactly one space between tokens, none leading or trailing.
Definition fdo2_protocol.hpp:443
bool crc_forbidden
A suffix is Malformed (CrcMode::Off).
Definition fdo2_protocol.hpp:442
bool crc_required
A suffix must be present (except #ERRO with erro_without_crc).
Definition fdo2_protocol.hpp:441
bool erro_without_crc
An #ERRO line without a suffix is accepted while CRC is required.
Definition fdo2_protocol.hpp:444
A parsed reply line.
Definition fdo2_protocol.hpp:449
std::size_t count
Values parsed (for Idnr: 1, in big).
Definition fdo2_protocol.hpp:455
Command command
The header, when known and not erro.
Definition fdo2_protocol.hpp:454
bool known
The header is one of the thirteen (or #ERRO).
Definition fdo2_protocol.hpp:451
bool erro
The line is #ERRO E.
Definition fdo2_protocol.hpp:452
int32_t error_code
E of #ERRO.
Definition fdo2_protocol.hpp:456
bool crc_present
A CRC suffix was present and valid.
Definition fdo2_protocol.hpp:453
std::array< int64_t, kMaxValues > values
The values, signed 32 bit or unsigned 32 bit.
Definition fdo2_protocol.hpp:458
uint64_t big
The #IDNR value.
Definition fdo2_protocol.hpp:457
ParseStatus status
Whether the line is valid.
Definition fdo2_protocol.hpp:450