BASIS 2 Driver 0.1.0
API reference
Loading...
Searching...
No Matches
alicat_basis2_ascii.hpp
Go to the documentation of this file.
1
11#ifndef ALICAT_BASIS2_ASCII_HPP
12#define ALICAT_BASIS2_ASCII_HPP
13
14#include <algorithm>
15#include <array>
16#include <cstddef>
17#include <cstdint>
18#include <span>
19
23
26
34inline constexpr char kCr = '\r';
35
37enum class ArgKind : uint8_t {
38 None = 0,
39 Int = 1,
40 Milli = 2,
41 Letter = 3,
42 Star = 4,
43 Ramp = 5,
44 IntPair = 6,
45};
46
50 const char* token;
52 bool space;
54 uint16_t min_firmware;
55 uint16_t reply_max;
56 bool slow;
57 bool guarded;
58 int64_t lo;
59 int64_t hi;
60 const char* letters;
61};
62
64inline constexpr std::size_t kCommandRows = 46;
65
68inline constexpr int64_t kMilliCap = 999'999'999'999LL;
70inline constexpr int64_t kMeasureMaxMs = 163'837;
71
74inline constexpr std::array<CommandSpec, kCommandRows> kCommands{
75 {{.id = Command::Poll,
76 .token = "",
77 .arg = ArgKind::None,
78 .space = false,
79 .controller_only = false,
80 .min_firmware = 0,
81 .reply_max = 96,
82 .slow = false,
83 .guarded = false,
84 .lo = 0,
85 .hi = 0,
86 .letters = ""},
87 {.id = Command::ReadData,
88 .token = "DV",
89 .arg = ArgKind::Int,
90 .space = true,
91 .controller_only = false,
92 .min_firmware = 0,
93 .reply_max = 96,
94 .slow = false,
95 .guarded = false,
96 .lo = 1,
97 .hi = 255,
98 .letters = ""},
100 .token = "S",
101 .arg = ArgKind::Milli,
102 .space = true,
103 .controller_only = true,
104 .min_firmware = 0,
105 .reply_max = 96,
106 .slow = false,
107 .guarded = false,
108 .lo = 0,
109 .hi = kMilliCap,
110 .letters = ""},
112 .token = "LSS",
113 .arg = ArgKind::None,
114 .space = false,
115 .controller_only = true,
116 .min_firmware = 0,
117 .reply_max = 64,
118 .slow = false,
119 .guarded = false,
120 .lo = 0,
121 .hi = 0,
122 .letters = ""},
124 .token = "LSS",
125 .arg = ArgKind::Letter,
126 .space = true,
127 .controller_only = true,
128 .min_firmware = 0,
129 .reply_max = 64,
130 .slow = true,
131 .guarded = false,
132 .lo = 0,
133 .hi = 0,
134 .letters = "ASU"},
135 {.id = Command::ReadRamp,
136 .token = "SR",
137 .arg = ArgKind::None,
138 .space = false,
139 .controller_only = true,
140 .min_firmware = 0,
141 .reply_max = 64,
142 .slow = false,
143 .guarded = false,
144 .lo = 0,
145 .hi = 0,
146 .letters = ""},
147 {.id = Command::SetRamp,
148 .token = "SR",
149 .arg = ArgKind::Ramp,
150 .space = true,
151 .controller_only = true,
152 .min_firmware = 0,
153 .reply_max = 64,
154 .slow = true,
155 .guarded = false,
156 .lo = 1,
157 .hi = kMilliCap,
158 .letters = ""},
160 .token = "SR",
161 .arg = ArgKind::Int,
162 .space = true,
163 .controller_only = true,
164 .min_firmware = 0,
165 .reply_max = 64,
166 .slow = true,
167 .guarded = false,
168 .lo = 0,
169 .hi = 0,
170 .letters = ""},
172 .token = "WD",
173 .arg = ArgKind::None,
174 .space = false,
175 .controller_only = true,
176 .min_firmware = 0,
177 .reply_max = 64,
178 .slow = false,
179 .guarded = false,
180 .lo = 0,
181 .hi = 0,
182 .letters = ""},
184 .token = "WD",
185 .arg = ArgKind::Int,
186 .space = true,
187 .controller_only = true,
188 .min_firmware = 0,
189 .reply_max = 64,
190 .slow = true,
191 .guarded = false,
192 .lo = 0,
193 .hi = 5000,
194 .letters = ""},
195 {.id = Command::HoldValve,
196 .token = "HPUR",
197 .arg = ArgKind::Milli,
198 .space = true,
199 .controller_only = true,
200 .min_firmware = 0,
201 .reply_max = 96,
202 .slow = false,
203 .guarded = false,
204 .lo = 0,
205 .hi = 100000,
206 .letters = ""},
208 .token = "C",
209 .arg = ArgKind::None,
210 .space = false,
211 .controller_only = true,
212 .min_firmware = 0,
213 .reply_max = 96,
214 .slow = false,
215 .guarded = false,
216 .lo = 0,
217 .hi = 0,
218 .letters = ""},
219 {.id = Command::ReadGains,
220 .token = "LCG",
221 .arg = ArgKind::None,
222 .space = false,
223 .controller_only = true,
224 .min_firmware = 0,
225 .reply_max = 64,
226 .slow = false,
227 .guarded = false,
228 .lo = 0,
229 .hi = 0,
230 .letters = ""},
231 {.id = Command::SetGains,
232 .token = "LCG",
233 .arg = ArgKind::IntPair,
234 .space = true,
235 .controller_only = true,
236 .min_firmware = 0,
237 .reply_max = 64,
238 .slow = true,
239 .guarded = false,
240 .lo = 0,
241 .hi = 65535,
242 .letters = ""},
244 .token = "RT",
245 .arg = ArgKind::None,
246 .space = false,
247 .controller_only = false,
248 .min_firmware = 0,
249 .reply_max = 64,
250 .slow = false,
251 .guarded = false,
252 .lo = 0,
253 .hi = 0,
254 .letters = ""},
256 .token = "RT",
257 .arg = ArgKind::Milli,
258 .space = true,
259 .controller_only = false,
260 .min_firmware = 0,
261 .reply_max = 64,
262 .slow = true,
263 .guarded = false,
264 .lo = 0,
265 .hi = 30000,
266 .letters = ""},
268 .token = "DCA",
269 .arg = ArgKind::None,
270 .space = false,
271 .controller_only = false,
272 .min_firmware = 0,
273 .reply_max = 64,
274 .slow = false,
275 .guarded = false,
276 .lo = 0,
277 .hi = 0,
278 .letters = ""},
280 .token = "DCA",
281 .arg = ArgKind::Int,
282 .space = true,
283 .controller_only = false,
284 .min_firmware = 0,
285 .reply_max = 64,
286 .slow = false,
287 .guarded = false,
288 .lo = 0,
289 .hi = 2500,
290 .letters = ""},
292 .token = "MT",
293 .arg = ArgKind::None,
294 .space = false,
295 .controller_only = true,
296 .min_firmware = 0,
297 .reply_max = 64,
298 .slow = false,
299 .guarded = false,
300 .lo = 0,
301 .hi = 0,
302 .letters = ""},
303 {.id = Command::SetTrigger,
304 .token = "MT",
305 .arg = ArgKind::Int,
306 .space = true,
307 .controller_only = true,
308 .min_firmware = 0,
309 .reply_max = 64,
310 .slow = false,
311 .guarded = false,
312 .lo = 0,
313 .hi = 7,
314 .letters = ""},
316 .token = "DVAS",
317 .arg = ArgKind::Int,
318 .space = true,
319 .controller_only = false,
320 .min_firmware = 0,
321 .reply_max = 64,
322 .slow = false,
323 .guarded = false,
324 .lo = 1,
325 .hi = kMeasureMaxMs,
326 .letters = ""},
328 .token = "DVAA",
329 .arg = ArgKind::None,
330 .space = false,
331 .controller_only = false,
332 .min_firmware = 0,
333 .reply_max = 64,
334 .slow = false,
335 .guarded = false,
336 .lo = 0,
337 .hi = 0,
338 .letters = ""},
339 {.id = Command::ReadRanges,
340 .token = "DVAR",
341 .arg = ArgKind::None,
342 .space = false,
343 .controller_only = false,
344 .min_firmware = 0,
345 .reply_max = 96,
346 .slow = false,
347 .guarded = false,
348 .lo = 0,
349 .hi = 0,
350 .letters = ""},
351 {.id = Command::Tare,
352 .token = "V",
353 .arg = ArgKind::Int,
354 .space = true,
355 .controller_only = false,
356 .min_firmware = 0,
357 .reply_max = 64,
358 .slow = false,
359 .guarded = false,
360 .lo = 1,
361 .hi = 32767,
362 .letters = ""},
364 .token = "ZCA",
365 .arg = ArgKind::None,
366 .space = false,
367 .controller_only = true,
368 .min_firmware = 0,
369 .reply_max = 64,
370 .slow = false,
371 .guarded = false,
372 .lo = 0,
373 .hi = 0,
374 .letters = ""},
376 .token = "ZCA",
377 .arg = ArgKind::Int,
378 .space = true,
379 .controller_only = true,
380 .min_firmware = 0,
381 .reply_max = 64,
382 .slow = false,
383 .guarded = false,
384 .lo = 0,
385 .hi = 1,
386 .letters = ""},
387 {.id = Command::ReadGas,
388 .token = "GS",
389 .arg = ArgKind::None,
390 .space = false,
391 .controller_only = false,
392 .min_firmware = 0,
393 .reply_max = 64,
394 .slow = false,
395 .guarded = false,
396 .lo = 0,
397 .hi = 0,
398 .letters = ""},
400 .token = "GS",
401 .arg = ArgKind::Star,
402 .space = true,
403 .controller_only = false,
404 .min_firmware = reg::kFw305,
405 .reply_max = 256,
406 .slow = false,
407 .guarded = false,
408 .lo = 0,
409 .hi = 0,
410 .letters = ""},
411 {.id = Command::SetGas,
412 .token = "GS",
413 .arg = ArgKind::Int,
414 .space = true,
415 .controller_only = false,
416 .min_firmware = 0,
417 .reply_max = 64,
418 .slow = false,
419 .guarded = false,
420 .lo = 0,
421 .hi = 255,
422 .letters = ""},
423 {.id = Command::ResetTotal,
424 .token = "T",
425 .arg = ArgKind::None,
426 .space = false,
427 .controller_only = false,
428 .min_firmware = 0,
429 .reply_max = 96,
430 .slow = false,
431 .guarded = false,
432 .lo = 0,
433 .hi = 0,
434 .letters = ""},
435 {.id = Command::SetBatch,
436 .token = "TB",
437 .arg = ArgKind::Milli,
438 .space = true,
439 .controller_only = true,
440 .min_firmware = 0,
441 .reply_max = 64,
442 .slow = false,
443 .guarded = false,
444 .lo = 1,
445 .hi = kMilliCap,
446 .letters = ""},
448 .token = "TB",
449 .arg = ArgKind::Int,
450 .space = true,
451 .controller_only = true,
452 .min_firmware = 0,
453 .reply_max = 64,
454 .slow = false,
455 .guarded = false,
456 .lo = 0,
457 .hi = 0,
458 .letters = ""},
460 .token = "TC",
461 .arg = ArgKind::None,
462 .space = false,
463 .controller_only = false,
464 .min_firmware = 0,
465 .reply_max = 64,
466 .slow = false,
467 .guarded = false,
468 .lo = 0,
469 .hi = 0,
470 .letters = ""},
472 .token = "TC",
473 .arg = ArgKind::Int,
474 .space = true,
475 .controller_only = false,
476 .min_firmware = 0,
477 .reply_max = 64,
478 .slow = true,
479 .guarded = false,
480 .lo = 0,
481 .hi = 3,
482 .letters = ""},
484 .token = "FPF",
485 .arg = ArgKind::Int,
486 .space = true,
487 .controller_only = false,
488 .min_firmware = 0,
489 .reply_max = 64,
490 .slow = false,
491 .guarded = false,
492 .lo = 0,
493 .hi = 2,
494 .letters = ""},
496 .token = "@=",
497 .arg = ArgKind::Letter,
498 .space = false,
499 .controller_only = false,
500 .min_firmware = 0,
501 .reply_max = 96,
502 .slow = true,
503 .guarded = true,
504 .lo = 0,
505 .hi = 0,
506 .letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
508 .token = "SN",
509 .arg = ArgKind::None,
510 .space = false,
511 .controller_only = false,
512 .min_firmware = 0,
513 .reply_max = 64,
514 .slow = false,
515 .guarded = false,
516 .lo = 0,
517 .hi = 0,
518 .letters = ""},
520 .token = "VE",
521 .arg = ArgKind::None,
522 .space = false,
523 .controller_only = false,
524 .min_firmware = 0,
525 .reply_max = 64,
526 .slow = false,
527 .guarded = false,
528 .lo = 0,
529 .hi = 0,
530 .letters = ""},
532 .token = "MA",
533 .arg = ArgKind::None,
534 .space = false,
535 .controller_only = false,
536 .min_firmware = 0,
537 .reply_max = 64,
538 .slow = false,
539 .guarded = false,
540 .lo = 0,
541 .hi = 0,
542 .letters = ""},
544 .token = "MA",
545 .arg = ArgKind::Int,
546 .space = true,
547 .controller_only = false,
548 .min_firmware = 0,
549 .reply_max = 64,
550 .slow = true,
551 .guarded = true,
552 .lo = 1,
553 .hi = 247,
554 .letters = ""},
555 {.id = Command::ReadBaud,
556 .token = "NCB",
557 .arg = ArgKind::None,
558 .space = false,
559 .controller_only = false,
560 .min_firmware = 0,
561 .reply_max = 64,
562 .slow = false,
563 .guarded = false,
564 .lo = 0,
565 .hi = 0,
566 .letters = ""},
567 {.id = Command::ChangeBaud,
568 .token = "NCB",
569 .arg = ArgKind::Int,
570 .space = true,
571 .controller_only = false,
572 .min_firmware = 0,
573 .reply_max = 64,
574 .slow = true,
575 .guarded = true,
576 .lo = 4800,
577 .hi = 115200,
578 .letters = ""},
580 .token = "P",
581 .arg = ArgKind::None,
582 .space = false,
583 .controller_only = false,
584 .min_firmware = 0,
585 .reply_max = 64,
586 .slow = false,
587 .guarded = false,
588 .lo = 0,
589 .hi = 0,
590 .letters = ""},
592 .token = "P",
593 .arg = ArgKind::Int,
594 .space = true,
595 .controller_only = false,
596 .min_firmware = 0,
597 .reply_max = 64,
598 .slow = true,
599 .guarded = true,
600 .lo = 1,
601 .hi = 1,
602 .letters = ""},
604 .token = "P2",
605 .arg = ArgKind::None,
606 .space = false,
607 .controller_only = false,
608 .min_firmware = 0,
609 .reply_max = 64,
610 .slow = true,
611 .guarded = true,
612 .lo = 0,
613 .hi = 0,
614 .letters = ""},
616 .token = "FACTORY RESTORE",
617 .arg = ArgKind::None,
618 .space = false,
619 .controller_only = false,
620 .min_firmware = 0,
621 .reply_max = 64,
622 .slow = true,
623 .guarded = true,
624 .lo = 0,
625 .hi = 0,
626 .letters = ""}}};
627
633[[nodiscard]] constexpr const CommandSpec& Spec(Command c) noexcept {
634 const auto i = static_cast<std::size_t>(c);
635 return kCommands[(i < kCommandRows) ? i : 0U];
636}
637
639struct Args {
640 int64_t a{0};
641 int64_t b{0};
642 char c{'\0'};
643 uint8_t dec{3};
644 bool trim{true};
645};
646
647namespace detail {
648
650struct Writer {
651 std::array<uint8_t, kMaxRequest>& buf;
652 std::size_t pos{0};
653 bool ok{true};
655 void Put(char ch) noexcept {
656 if (pos < buf.size()) {
657 buf[pos] = ::alicat_basis2::detail::ByteOf(ch);
658 ++pos;
659 } else {
660 ok = false;
661 }
662 }
664 void PutText(const char* s) noexcept {
665 for (std::size_t i = 0U; !::alicat_basis2::detail::SameChar(s[i], '\0'); ++i) {
666 Put(s[i]);
667 }
668 }
669};
670
672[[nodiscard]] constexpr int64_t Pow10(uint32_t n) noexcept {
673 int64_t r = 1;
674 for (uint32_t i = 0U; i < n; ++i) {
675 r *= 10;
676 }
677 return r;
678}
679
681inline void PutUnsigned(Writer& w, uint64_t v) noexcept {
682 std::array<char, 20> tmp{};
683 std::size_t n = 0U;
684 do {
685 tmp[n] = ::alicat_basis2::detail::DigitChar(v);
686 v /= 10U;
687 ++n;
688 } while ((v != 0U) && (n < tmp.size()));
689 while (n > 0U) {
690 --n;
691 w.Put(tmp[n]);
692 }
693}
694
696[[nodiscard]] constexpr int64_t Rescale(int64_t milli, uint32_t dec) noexcept {
697 if (dec >= 3U) {
698 return milli * Pow10(dec - 3U);
699 }
700 const int64_t div = Pow10(3U - dec);
701 const int64_t half = div / 2;
702 return (milli >= 0) ? ((milli + half) / div) : -((-milli + half) / div);
703}
704
707[[nodiscard]] constexpr int64_t WireMilli(int64_t milli, uint32_t dec) noexcept {
708 return (dec >= 3U) ? milli : (Rescale(milli, dec) * Pow10(3U - dec));
709}
710
712inline void PutMilli(Writer& w, int64_t milli, uint32_t dec, bool trim) noexcept {
713 const int64_t v = Rescale(milli, dec);
714 const bool neg = v < 0;
715 const auto mag = static_cast<uint64_t>(neg ? -v : v);
716 const auto scale = static_cast<uint64_t>(Pow10(dec));
717 if (neg && (mag != 0U)) {
718 w.Put('-');
719 }
720 PutUnsigned(w, mag / scale);
721 uint64_t frac = mag % scale;
722 uint32_t digits = dec;
723 if (trim) {
724 while ((digits > 0U) && ((frac % 10U) == 0U)) {
725 frac /= 10U;
726 --digits;
727 }
728 }
729 if (digits > 0U) {
730 w.Put('.');
731 for (uint32_t i = digits; i > 0U; --i) {
732 w.Put(::alicat_basis2::detail::DigitChar(frac / static_cast<uint64_t>(Pow10(i - 1U))));
733 }
734 }
735}
736
738[[nodiscard]] constexpr bool IsRead(Command c) noexcept {
739 constexpr std::array<Command, 21> kReads{Command::Poll,
760 return std::ranges::any_of(kReads, [c](Command r) { return r == c; });
761}
762
764[[nodiscard]] constexpr bool BaudValid(int64_t b) noexcept {
765 return (b == 4800) || (b == 9600) || (b == 19200) || (b == 38400) || (b == 57600) ||
766 (b == 115200);
767}
768
770[[nodiscard]] constexpr bool InSet(char ch, const char* set) noexcept {
771 for (std::size_t i = 0U; !::alicat_basis2::detail::SameChar(set[i], '\0'); ++i) {
772 if (::alicat_basis2::detail::SameChar(set[i], ch)) {
773 return true;
774 }
775 }
776 return false;
777}
778
780[[nodiscard]] constexpr bool ArgsValid(const CommandSpec& s, const Args& a) noexcept {
781 const bool in_range = (a.a >= s.lo) && (a.a <= s.hi);
782 switch (s.arg) {
783 case ArgKind::None:
784 case ArgKind::Star:
785 return true;
786 case ArgKind::Int:
787 return in_range && ((s.id != Command::ChangeBaud) || BaudValid(a.a));
788 case ArgKind::Milli:
789 return in_range && (a.dec <= 6U);
790 case ArgKind::Letter:
791 return (!::alicat_basis2::detail::SameChar(a.c, '\0')) && InSet(a.c, s.letters);
792 case ArgKind::Ramp:
793 return in_range && (a.dec <= 6U) && (a.b >= 3) && (a.b <= 5);
794 case ArgKind::IntPair:
795 return in_range && (a.b >= s.lo) && (a.b <= s.hi);
796 default:
797 break;
798 }
799 return false;
800}
801
803inline void PutArgs(Writer& w, const CommandSpec& s, const Args& a) noexcept {
804 switch (s.arg) {
805 case ArgKind::Int:
806 PutUnsigned(w, static_cast<uint64_t>(a.a));
807 break;
808 case ArgKind::Milli:
809 PutMilli(w, a.a, a.dec, a.trim);
810 break;
811 case ArgKind::Letter:
812 w.Put(a.c);
813 break;
814 case ArgKind::Star:
815 w.Put('*');
816 break;
817 case ArgKind::Ramp:
818 PutMilli(w, a.a, a.dec, a.trim);
819 w.Put(' ');
820 PutUnsigned(w, static_cast<uint64_t>(a.b));
821 break;
822 case ArgKind::IntPair:
823 PutUnsigned(w, static_cast<uint64_t>(a.a));
824 w.Put(' ');
825 PutUnsigned(w, static_cast<uint64_t>(a.b));
826 break;
827 case ArgKind::None:
828 break;
829 default:
830 break;
831 }
832}
833
834} // namespace detail
835
849[[nodiscard]] inline Result<Request> Make(Command command, char id, const Args& args,
850 bool allow_guarded) noexcept {
851 if (static_cast<std::size_t>(command) >= kCommandRows) {
853 }
854 const CommandSpec& s = Spec(command);
855 if (!::alicat_basis2::detail::IsUpper(id) || (s.guarded && !allow_guarded) ||
856 !detail::ArgsValid(s, args)) {
858 }
859 ::alicat_basis2::detail::RequestData d{};
860 detail::Writer w{.buf = d.bytes};
861 w.Put(id);
862 w.PutText(s.token);
863 if (s.arg != ArgKind::None) {
864 if (s.space) {
865 w.Put(' ');
866 }
867 detail::PutArgs(w, s, args);
868 }
869 w.Put(kCr);
870 if (!w.ok) {
872 }
873 d.length = static_cast<uint8_t>(w.pos);
874 d.command = command;
875 d.id = id;
876 d.alt_id = (command == Command::ChangeUnitId) ? args.c : '\0';
877 d.slow = s.slow;
878 d.guarded = s.guarded;
879 d.idempotent = detail::IsRead(command);
880 d.reply_chars = s.reply_max;
881 return Result<Request>::Success(::alicat_basis2::detail::RequestBuilder::Build(d));
882}
883
884// ---------------------------------------------------------------------------------------------------------------
885// Independent wire validator (hand-written, not generated from the table): accepts exactly the
886// grammar of M pp.10-17
887// ---------------------------------------------------------------------------------------------------------------
888
889namespace detail::legal {
890
892using View = std::span<const char>;
893
895[[nodiscard]] constexpr bool Eq(View v, const char* s) noexcept {
896 std::size_t i = 0U;
897 while ((!::alicat_basis2::detail::SameChar(s[i], '\0')) && (i < v.size()) &&
898 (::alicat_basis2::detail::SameChar(v[i], s[i]))) {
899 ++i;
900 }
901 return (::alicat_basis2::detail::SameChar(s[i], '\0')) && (i == v.size());
902}
903
905[[nodiscard]] constexpr bool After(View v, const char* p, View& rest) noexcept {
906 std::size_t i = 0U;
907 while ((!::alicat_basis2::detail::SameChar(p[i], '\0')) && (i < v.size()) &&
908 (::alicat_basis2::detail::SameChar(v[i], p[i]))) {
909 ++i;
910 }
911 if (!::alicat_basis2::detail::SameChar(p[i], '\0')) {
912 return false;
913 }
914 rest = v.subspan(i);
915 return true;
916}
917
919[[nodiscard]] constexpr bool IntIn(View v, int64_t lo, int64_t hi) noexcept {
920 if (v.empty() || (v.size() > 12U) ||
921 ((::alicat_basis2::detail::SameChar(v[0], '0')) && (v.size() > 1U))) {
922 return false;
923 }
924 int64_t n = 0;
925 for (const char ch : v) {
926 const int32_t digit = ::alicat_basis2::detail::DigitValue(ch);
927 if (digit < 0) {
928 return false;
929 }
930 n = (n * 10) + digit;
931 }
932 return (n >= lo) && (n <= hi);
933}
934
938[[nodiscard]] constexpr bool DecIn(View v, int64_t lo_milli, int64_t hi_milli) noexcept {
939 std::size_t dot = v.size();
940 for (std::size_t i = 0U; i < v.size(); ++i) {
941 if (::alicat_basis2::detail::SameChar(v[i], '.')) {
942 dot = i;
943 break;
944 }
945 }
946 const View ip = v.first(dot);
947 if (!IntIn(ip, 0, 999'999'999'999LL)) {
948 return false;
949 }
950 int64_t milli = 0;
951 for (const char ch : ip) {
952 milli = (milli * 10) + ::alicat_basis2::detail::DigitValue(ch);
953 }
954 milli *= 1000;
955 if (dot < v.size()) {
956 const View fr = v.subspan(dot + 1U);
957 if (fr.empty() || (fr.size() > 6U)) {
958 return false;
959 }
960 int64_t scale = 100;
961 for (const char ch : fr) {
962 const int32_t digit = ::alicat_basis2::detail::DigitValue(ch);
963 if (digit < 0) {
964 return false;
965 }
966 milli += (scale >= 1) ? (digit * scale) : 0;
967 scale /= 10;
968 }
969 // Rounding of the sub-thousandth digits to the nearest thousandth may add one.
970 if ((fr.size() > 3U) && (::alicat_basis2::detail::DigitValue(fr[3]) >= 5)) {
971 milli += 1;
972 }
973 }
974 return (milli >= lo_milli) && (milli <= hi_milli);
975}
976
978[[nodiscard]] constexpr bool NoArg(View r) noexcept {
979 constexpr std::array<const char*, 22> kWords{
980 "", "C", "T", "SN", "VE", "MA", "NCB", "P", "P2", "LSS", "SR",
981 "WD", "LCG", "RT", "DCA", "MT", "DVAA", "DVAR", "ZCA", "GS", "TC", "FACTORY RESTORE"};
982 return std::ranges::any_of(kWords, [r](const char* w) { return Eq(r, w); });
983}
984
986struct IntForm {
987 const char* prefix;
988 int64_t lo;
989 int64_t hi;
990};
991
993[[nodiscard]] constexpr bool OneInt(View r) noexcept {
994 constexpr std::array<IntForm, 14> kForms{{{.prefix = "DV ", .lo = 1, .hi = 255},
995 {.prefix = "DVAS ", .lo = 1, .hi = 163'837},
996 {.prefix = "WD ", .lo = 0, .hi = 5000},
997 {.prefix = "DCA ", .lo = 0, .hi = 2500},
998 {.prefix = "MT ", .lo = 0, .hi = 7},
999 {.prefix = "V ", .lo = 1, .hi = 32767},
1000 {.prefix = "ZCA ", .lo = 0, .hi = 1},
1001 {.prefix = "GS ", .lo = 0, .hi = 255},
1002 {.prefix = "TC ", .lo = 0, .hi = 3},
1003 {.prefix = "FPF ", .lo = 0, .hi = 2},
1004 {.prefix = "MA ", .lo = 1, .hi = 247},
1005 {.prefix = "P ", .lo = 1, .hi = 1},
1006 {.prefix = "SR ", .lo = 0, .hi = 0},
1007 {.prefix = "TB ", .lo = 0, .hi = 0}}};
1008 View rest{};
1009 for (const IntForm& f : kForms) {
1010 if (After(r, f.prefix, rest) && IntIn(rest, f.lo, f.hi)) {
1011 return true;
1012 }
1013 }
1014 return false;
1015}
1016
1018[[nodiscard]] constexpr bool DecimalArg(View r) noexcept {
1019 View rest{};
1020 if (After(r, "S ", rest)) {
1021 return DecIn(rest, 0, 999'999'999'999LL);
1022 }
1023 if (After(r, "HPUR ", rest)) {
1024 return DecIn(rest, 0, 100'000);
1025 }
1026 if (After(r, "RT ", rest)) {
1027 return DecIn(rest, 0, 30'000);
1028 }
1029 return After(r, "TB ", rest) && DecIn(rest, 1, 999'999'999'999LL);
1030}
1031
1033[[nodiscard]] constexpr bool BaudArg(View r) noexcept {
1034 View rest{};
1035 if (!After(r, "NCB ", rest)) {
1036 return false;
1037 }
1038 return Eq(rest, "4800") || Eq(rest, "9600") || Eq(rest, "19200") || Eq(rest, "38400") ||
1039 Eq(rest, "57600") || Eq(rest, "115200");
1040}
1041
1043[[nodiscard]] constexpr bool OtherArg(View r) noexcept {
1044 View rest{};
1045 if (DecimalArg(r) || BaudArg(r) || Eq(r, "GS *")) {
1046 return true;
1047 }
1048 if (After(r, "LSS ", rest)) {
1049 return (rest.size() == 1U) && ((::alicat_basis2::detail::SameChar(rest[0], 'A')) ||
1050 (::alicat_basis2::detail::SameChar(rest[0], 'S')) ||
1051 (::alicat_basis2::detail::SameChar(rest[0], 'U')));
1052 }
1053 return After(r, "@=", rest) && (rest.size() == 1U) && ::alicat_basis2::detail::IsUpper(rest[0]);
1054}
1055
1057[[nodiscard]] constexpr bool AllowedChar(char ch) noexcept {
1058 const bool alnum = ::alicat_basis2::detail::IsUpper(ch) || ::alicat_basis2::detail::IsDigit(ch);
1059 return alnum || (::alicat_basis2::detail::SameChar(ch, ' ')) ||
1060 (::alicat_basis2::detail::SameChar(ch, '+')) ||
1061 (::alicat_basis2::detail::SameChar(ch, '-')) ||
1062 (::alicat_basis2::detail::SameChar(ch, '.')) ||
1063 (::alicat_basis2::detail::SameChar(ch, '*')) ||
1064 (::alicat_basis2::detail::SameChar(ch, '@')) ||
1065 (::alicat_basis2::detail::SameChar(ch, '='));
1066}
1067
1069[[nodiscard]] constexpr bool TwoArgs(View r) noexcept {
1070 View rest{};
1071 std::size_t sp = 0U;
1072 if (After(r, "SR ", rest)) {
1073 while ((sp < rest.size()) && (!::alicat_basis2::detail::SameChar(rest[sp], ' '))) {
1074 ++sp;
1075 }
1076 return (sp < rest.size()) && DecIn(rest.first(sp), 1, 999'999'999'999LL) &&
1077 IntIn(rest.subspan(sp + 1U), 3, 5);
1078 }
1079 if (After(r, "LCG ", rest)) {
1080 while ((sp < rest.size()) && (!::alicat_basis2::detail::SameChar(rest[sp], ' '))) {
1081 ++sp;
1082 }
1083 return (sp < rest.size()) && IntIn(rest.first(sp), 0, 65535) &&
1084 IntIn(rest.subspan(sp + 1U), 0, 65535);
1085 }
1086 return false;
1087}
1088
1089} // namespace detail::legal
1090
1102[[nodiscard]] inline bool IsLegalRequest(std::span<const uint8_t> bytes) noexcept {
1103 if ((bytes.size() < 2U) || (bytes.size() > kMaxRequest) ||
1104 (bytes.back() != ::alicat_basis2::detail::ByteOf(kCr))) {
1105 return false;
1106 }
1107 std::array<char, kMaxRequest> text{};
1108 const std::size_t n = bytes.size() - 1U;
1109 for (std::size_t i = 0U; i < n; ++i) {
1110 const char ch = ::alicat_basis2::detail::CharOf(bytes[i]);
1111 if (!detail::legal::AllowedChar(ch)) {
1112 return false;
1113 }
1114 text[i] = ch;
1115 }
1116 if (!::alicat_basis2::detail::IsUpper(text[0])) {
1117 return false;
1118 }
1119 const detail::legal::View rest{text.data() + 1, n - 1U};
1120 return detail::legal::NoArg(rest) || detail::legal::OneInt(rest) ||
1121 detail::legal::OtherArg(rest) || detail::legal::TwoArgs(rest);
1122}
1123
1124// ---------------------------------------------------------------------------------------------------------------
1125// Reply parsing
1126// ---------------------------------------------------------------------------------------------------------------
1127
1129inline constexpr std::size_t kMaxTokens = 26;
1131inline constexpr std::size_t kMaxToken = 32;
1132
1134struct Token {
1135 uint8_t offset{0};
1136 uint8_t length{0};
1137};
1138
1140struct Tokens {
1141 std::array<Token, kMaxTokens> items{};
1142 uint8_t count{0};
1143};
1144
1152[[nodiscard]] inline Error Tokenize(std::span<const char> line, Tokens& out) noexcept {
1153 out = Tokens{};
1154 std::size_t i = 0U;
1155 while (i < line.size()) {
1156 const uint8_t ch = ::alicat_basis2::detail::ByteOf(line[i]);
1157 if (::alicat_basis2::detail::SameChar(line[i], ' ')) {
1158 ++i;
1159 } else if ((ch > 0x20U) && (ch < 0x7FU)) {
1160 const std::size_t start = i;
1161 while ((i < line.size()) && (!::alicat_basis2::detail::SameChar(line[i], ' '))) {
1162 const uint8_t c2 = ::alicat_basis2::detail::ByteOf(line[i]);
1163 if ((c2 <= 0x20U) || (c2 >= 0x7FU)) {
1164 return Error::BadReply;
1165 }
1166 ++i;
1167 }
1168 if (((i - start) > kMaxToken) || (out.count >= kMaxTokens)) {
1169 return Error::BadReply;
1170 }
1171 out.items[out.count] =
1172 Token{.offset = static_cast<uint8_t>(start), .length = static_cast<uint8_t>(i - start)};
1173 ++out.count;
1174 } else {
1175 return Error::BadReply;
1176 }
1177 }
1178 return (out.count > 0U) ? Error::Ok : Error::BadReply;
1179}
1180
1187[[nodiscard]] inline std::span<const char> View(std::span<const char> line,
1188 const Token& t) noexcept {
1189 return line.subspan(t.offset, t.length);
1190}
1191
1192namespace detail {
1195inline std::size_t ScanDigits(std::span<const char> tok, std::size_t& i, int64_t& m,
1196 std::size_t cap) noexcept {
1197 std::size_t n = 0U;
1198 while ((i < tok.size()) && (n < cap) && ::alicat_basis2::detail::IsDigit(tok[i])) {
1199 m = (m * 10) + ::alicat_basis2::detail::DigitValue(tok[i]);
1200 ++n;
1201 ++i;
1202 }
1203 return n;
1204}
1205} // namespace detail
1206
1214[[nodiscard]] inline bool ParseDecimal(std::span<const char> tok, Decimal& out) noexcept {
1215 std::size_t i = 0U;
1216 bool neg = false;
1217 if (!tok.empty() && ((::alicat_basis2::detail::SameChar(tok[0], '+')) ||
1218 (::alicat_basis2::detail::SameChar(tok[0], '-')))) {
1219 neg = ::alicat_basis2::detail::SameChar(tok[0], '-');
1220 i = 1U;
1221 }
1222 int64_t m = 0;
1223 // At most 12 integer digits and 6 decimals are read, so the mantissa stays below 10^18 whatever
1224 // the input; a digit left over after the cap makes the token end early and the final check fails.
1225 if (detail::ScanDigits(tok, i, m, 12U) == 0U) {
1226 return false;
1227 }
1228 uint8_t dec = 0U;
1229 if ((i < tok.size()) && (::alicat_basis2::detail::SameChar(tok[i], '.'))) {
1230 ++i;
1231 dec = static_cast<uint8_t>(detail::ScanDigits(tok, i, m, 6U));
1232 if (dec == 0U) {
1233 return false;
1234 }
1235 }
1236 if (i != tok.size()) {
1237 return false;
1238 }
1239 out = Decimal{.mantissa = neg ? -m : m, .decimals = dec};
1240 return true;
1241}
1242
1245[[nodiscard]] constexpr char Upper(char c) noexcept {
1246 const int32_t place = ::alicat_basis2::detail::PlaceOf(::alicat_basis2::detail::kLowerChars, c);
1247 return (place < 0) ? c : ::alicat_basis2::detail::kUpperChars[static_cast<std::size_t>(place)];
1248}
1249
1256[[nodiscard]] inline bool EqualsNoCase(std::span<const char> tok, const char* word) noexcept {
1257 std::size_t i = 0U;
1258 while ((!::alicat_basis2::detail::SameChar(word[i], '\0')) && (i < tok.size()) &&
1259 (::alicat_basis2::detail::SameChar(Upper(tok[i]), Upper(word[i])))) {
1260 ++i;
1261 }
1262 return (::alicat_basis2::detail::SameChar(word[i], '\0')) && (i == tok.size());
1263}
1264
1272[[nodiscard]] inline bool StartsWithId(std::span<const char> line, const Tokens& toks,
1273 char id) noexcept {
1274 return (toks.count > 0U) && (toks.items[0].length == 1U) &&
1275 (::alicat_basis2::detail::SameChar(Upper(line[toks.items[0].offset]), id));
1276}
1277
1289
1290namespace detail {
1291
1293inline void CopyToken(std::span<const char> tok, char* dst, std::size_t cap) noexcept {
1294 std::size_t n = (tok.size() < (cap - 1U)) ? tok.size() : (cap - 1U);
1295 for (std::size_t i = 0U; i < n; ++i) {
1296 dst[i] = tok[i];
1297 }
1298 dst[n] = '\0';
1299}
1300
1302[[nodiscard]] inline bool ParseGasName(std::span<const char> tok, Frame& f) noexcept {
1303 if (tok.empty() || (tok.size() > 8U)) {
1304 return false;
1305 }
1306 for (const char ch : tok) {
1307 if (!::alicat_basis2::detail::IsAlnum(ch)) {
1308 return false;
1309 }
1310 }
1311 CopyToken(tok, f.gas_name.data(), f.gas_name.size());
1312 f.gas_known = false;
1313 for (uint8_t n = 0U; n < 9U; ++n) {
1314 if (EqualsNoCase(tok, GasName(n))) {
1315 f.gas = GasId{n};
1316 f.gas_known = true;
1317 }
1318 }
1319 return true;
1320}
1321
1323[[nodiscard]] inline bool SetFlag(std::span<const char> name, StatusFlags& s) noexcept {
1324 bool* target = nullptr;
1325 if (EqualsNoCase(name, "TOV")) {
1326 target = &s.temperature_over;
1327 } else if (EqualsNoCase(name, "MOV")) {
1328 target = &s.mass_flow_over;
1329 } else if (EqualsNoCase(name, "OVR")) {
1330 target = &s.totalizer_over;
1331 } else if (EqualsNoCase(name, "HLD")) {
1332 target = &s.valve_hold;
1333 } else if (EqualsNoCase(name, "VTM")) {
1334 target = &s.valve_thermal;
1335 } else {
1336 if (s.unknown_count < 255U) {
1337 ++s.unknown_count;
1338 }
1339 return true;
1340 }
1341 if (*target) {
1342 return false;
1343 }
1344 *target = true;
1345 return true;
1346}
1347
1349[[nodiscard]] inline bool ParseFlagToken(std::span<const char> tok, StatusFlags& s) noexcept {
1350 if (tok.empty()) {
1351 return false;
1352 }
1353 if (!::alicat_basis2::detail::SameChar(tok[0], '[')) {
1354 return SetFlag(tok, s);
1355 }
1356 std::size_t i = 0U;
1357 while (i < tok.size()) {
1358 if (!::alicat_basis2::detail::SameChar(tok[i], '[')) {
1359 return false;
1360 }
1361 std::size_t j = i + 1U;
1362 while ((j < tok.size()) && (!::alicat_basis2::detail::SameChar(tok[j], ']'))) {
1363 ++j;
1364 }
1365 if ((j >= tok.size()) || (j == (i + 1U)) || !SetFlag(tok.subspan(i + 1U, j - i - 1U), s)) {
1366 return false;
1367 }
1368 i = j + 1U;
1369 }
1370 return true;
1371}
1372
1374[[nodiscard]] inline bool Carries(const Frame& f, DataItem item) noexcept {
1375 return (static_cast<uint32_t>(f.present) & static_cast<uint32_t>(item)) != 0U;
1376}
1377
1379[[nodiscard]] inline Error CheckMeasured(const Frame& f, const FrameRules& r) noexcept {
1380 if (Carries(f, DataItem::Temperature)) {
1381 const int64_t t_milli = f.temperature.ToMilli();
1382 if ((t_milli < (static_cast<int64_t>(r.temperature_min_c) * 1000)) ||
1383 (t_milli > (static_cast<int64_t>(r.temperature_max_c) * 1000))) {
1384 return Error::OutOfRange;
1385 }
1386 }
1387 if (r.full_scale_known && Carries(f, DataItem::Flow)) {
1388 const int64_t limit = (r.full_scale_milli * r.flow_margin_permille) / 1000;
1389 const int64_t flow = f.flow.ToMilli();
1390 if ((flow > limit) || (flow < -limit)) {
1391 return Error::OutOfRange;
1392 }
1393 }
1394 if (r.full_scale_known && Carries(f, DataItem::Setpoint)) {
1395 const int64_t sp = f.setpoint.ToMilli();
1396 if ((sp < 0) || (sp > ((r.full_scale_milli * 1025) / 1000))) {
1397 return Error::OutOfRange;
1398 }
1399 }
1400 return Error::Ok;
1401}
1402
1404[[nodiscard]] inline Error CheckFrame(const Frame& f, const FrameRules& r) noexcept {
1405 if (const Error e = CheckMeasured(f, r); e != Error::Ok) {
1406 return e;
1407 }
1408 if (Carries(f, DataItem::ValveDrive) &&
1409 ((f.valve_drive.ToMilli() < -500) || (f.valve_drive.ToMilli() > 100'500))) {
1410 return Error::OutOfRange;
1411 }
1412 if (Carries(f, DataItem::TotalVolume) && (f.total.mantissa < 0)) {
1413 return Error::OutOfRange;
1414 }
1415 if (Carries(f, DataItem::BatchRemaining) && (f.batch_remaining.mantissa < 0)) {
1416 return Error::OutOfRange;
1417 }
1418 return Error::Ok;
1419}
1420
1422[[nodiscard]] inline bool ParseNumbers(std::span<const char> line, const Tokens& t,
1423 std::size_t first, std::size_t n, Decimal* out) noexcept {
1424 for (std::size_t k = 0U; k < n; ++k) {
1425 if (!ParseDecimal(View(line, t.items[first + k]), out[k])) {
1426 return false;
1427 }
1428 }
1429 return true;
1430}
1431
1433[[nodiscard]] inline bool ParseFlags(std::span<const char> line, const Tokens& t, std::size_t first,
1434 UnknownFlagPolicy policy, StatusFlags& s) noexcept {
1435 for (std::size_t k = first; k < t.count; ++k) {
1436 if (!ParseFlagToken(View(line, t.items[k]), s)) {
1437 return false;
1438 }
1439 }
1440 return (policy == UnknownFlagPolicy::Report) || (s.unknown_count == 0U);
1441}
1442
1443} // namespace detail
1444
1445namespace detail {
1447[[nodiscard]] inline std::size_t LeadingNumbers(std::span<const char> line, const Tokens& t,
1448 std::array<Decimal, 5>& v) noexcept {
1449 std::size_t numbers = 0U;
1450 while ((numbers < 5U) && ((numbers + 1U) < t.count) &&
1451 ParseDecimal(View(line, t.items[numbers + 1U]), v[numbers])) {
1452 ++numbers;
1453 }
1454 return numbers;
1455}
1456} // namespace detail
1457
1467[[nodiscard]] inline Error DecodeFrame(std::span<const char> line, const FrameRules& rules,
1468 Frame& out, FrameLayout& layout_seen) noexcept {
1469 Tokens t{};
1470 if (Tokenize(line, t) != Error::Ok) {
1471 return Error::BadReply;
1472 }
1473 if (!StartsWithId(line, t, rules.unit_id)) {
1475 }
1476 std::array<Decimal, 5> v{};
1477 const std::size_t numbers = detail::LeadingNumbers(line, t, v);
1478 if (((numbers != 3U) && (numbers != 5U)) || ((numbers + 1U) >= t.count)) {
1479 return Error::BadReply;
1480 }
1481 const FrameLayout seen = (numbers == 3U) ? FrameLayout::Meter : FrameLayout::Controller;
1482 if ((rules.layout != FrameLayout::Auto) && (rules.layout != seen)) {
1483 return Error::BadReply;
1484 }
1485 Frame f{};
1486 f.unit_id = rules.unit_id;
1487 if (!detail::ParseGasName(View(line, t.items[numbers + 1U]), f) ||
1488 !detail::ParseFlags(line, t, numbers + 2U, rules.flags, f.status)) {
1489 return Error::BadReply;
1490 }
1491 f.temperature = v[0];
1492 f.flow = v[1];
1493 f.total = v[2];
1496 if (numbers == 5U) {
1497 f.setpoint = v[3];
1498 f.valve_drive = v[4];
1499 f.present = f.present | DataItem::Setpoint | DataItem::ValveDrive;
1500 }
1501 if (const Error e = detail::CheckFrame(f, rules); e != Error::Ok) {
1502 return e;
1503 }
1504 out = f;
1505 layout_seen = seen;
1506 return Error::Ok;
1507}
1508
1509namespace detail {
1510
1512[[nodiscard]] inline Decimal* DataField(Frame& f, uint32_t bit) noexcept {
1513 switch (bit) {
1514 case 1U:
1515 return &f.flow;
1516 case 2U:
1517 return &f.setpoint;
1518 case 4U:
1519 return &f.temperature;
1520 case 8U:
1521 return &f.valve_drive;
1522 case 32U:
1523 return &f.total;
1524 case 64U:
1525 return &f.batch_remaining;
1526 default:
1527 break;
1528 }
1529 return nullptr;
1530}
1531
1532} // namespace detail
1533
1534namespace detail {
1536[[nodiscard]] inline bool ParseStatusTail(std::span<const char> line, const Tokens& t,
1537 std::size_t k, const FrameRules& rules,
1538 Frame& f) noexcept {
1539 Decimal bits{};
1540 if (((k + 1U) == t.count) && ParseDecimal(View(line, t.items[k]), bits) &&
1541 (bits.decimals == 0U) && (bits.mantissa >= 0) && (bits.mantissa < 256)) {
1542 f.status = StatusFromBits(static_cast<uint32_t>(bits.mantissa));
1543 return true;
1544 }
1545 return ParseFlags(line, t, k, rules.flags, f.status);
1546}
1547} // namespace detail
1548
1561[[nodiscard]] inline Error DecodeData(std::span<const char> line, uint8_t mask,
1562 const FrameRules& rules, Frame& out) noexcept {
1563 Tokens t{};
1564 if (Tokenize(line, t) != Error::Ok) {
1565 return Error::BadReply;
1566 }
1567 if (!StartsWithId(line, t, rules.unit_id)) {
1569 }
1570 Frame f{};
1571 f.unit_id = rules.unit_id;
1572 f.present = mask;
1573 std::size_t k = 1U;
1574 for (uint32_t bit = 1U; bit <= 64U; bit <<= 1U) {
1575 if ((static_cast<uint32_t>(mask) & bit) == 0U) {
1576 continue;
1577 }
1578 if (k >= t.count) {
1579 return Error::BadReply;
1580 }
1581 Decimal* field = detail::DataField(f, bit);
1582 const bool ok = (field != nullptr) ? ParseDecimal(View(line, t.items[k]), *field)
1583 : detail::ParseGasName(View(line, t.items[k]), f);
1584 if (!ok) {
1585 return Error::BadReply;
1586 }
1587 ++k;
1588 }
1589 if ((static_cast<uint32_t>(mask) & static_cast<uint32_t>(DataItem::Status)) != 0U) {
1590 if (!detail::ParseStatusTail(line, t, k, rules, f)) {
1591 return Error::BadReply;
1592 }
1593 } else if (k != t.count) {
1594 return Error::BadReply;
1595 } else {
1596 // Every number is accounted for.
1597 }
1598 if (const Error e = detail::CheckFrame(f, rules); e != Error::Ok) {
1599 return e;
1600 }
1601 out = f;
1602 return Error::Ok;
1603}
1604
1606struct Values {
1607 std::array<Decimal, 5> v{};
1608 uint8_t count{0};
1609};
1610
1619[[nodiscard]] inline Error DecodeValues(std::span<const char> line, char id, uint8_t count,
1620 Values& out) noexcept {
1621 Tokens t{};
1622 if (Tokenize(line, t) != Error::Ok) {
1623 return Error::BadReply;
1624 }
1625 if (!StartsWithId(line, t, id)) {
1627 }
1628 if ((count < 1U) || (count > 5U) || (t.count != (count + 1U))) {
1629 return Error::BadReply;
1630 }
1631 Values vals{};
1632 if (!detail::ParseNumbers(line, t, 1U, count, vals.v.data())) {
1633 return Error::BadReply;
1634 }
1635 vals.count = count;
1636 out = vals;
1637 return Error::Ok;
1638}
1639
1648[[nodiscard]] inline Error DecodeLetter(std::span<const char> line, char id, const char* allowed,
1649 char& out) noexcept {
1650 Tokens t{};
1651 if (Tokenize(line, t) != Error::Ok) {
1652 return Error::BadReply;
1653 }
1654 if (!StartsWithId(line, t, id)) {
1656 }
1657 if ((t.count != 2U) || (t.items[1].length != 1U) ||
1658 !detail::InSet(Upper(line[t.items[1].offset]), allowed)) {
1659 return Error::BadReply;
1660 }
1661 out = Upper(line[t.items[1].offset]);
1662 return Error::Ok;
1663}
1664
1673[[nodiscard]] inline Error DecodeText(std::span<const char> line, char id, Text& out) noexcept {
1674 Tokens t{};
1675 if (Tokenize(line, t) != Error::Ok) {
1676 return Error::BadReply;
1677 }
1678 if (!StartsWithId(line, t, id)) {
1680 }
1681 if (t.count < 2U) {
1682 return Error::BadReply;
1683 }
1684 const std::size_t start = t.items[1].offset;
1685 Text x{};
1686 std::size_t n = line.size() - start;
1687 n = (n < kTextMax) ? n : kTextMax;
1688 while ((n > 0U) && (::alicat_basis2::detail::SameChar(line[start + n - 1U], ' '))) {
1689 --n;
1690 }
1691 detail::CopyToken(line.subspan(start, n), x.chars.data(), x.chars.size());
1692 x.length = static_cast<uint8_t>(n);
1693 out = x;
1694 return Error::Ok;
1695}
1696
1704[[nodiscard]] inline Error DecodeGas(std::span<const char> line, char id, Frame& out) noexcept {
1705 Tokens t{};
1706 if (Tokenize(line, t) != Error::Ok) {
1707 return Error::BadReply;
1708 }
1709 if (!StartsWithId(line, t, id)) {
1711 }
1712 Decimal n{};
1713 Frame f{};
1714 if ((t.count != 3U) || !ParseDecimal(View(line, t.items[1]), n) || (n.decimals != 0U) ||
1715 (n.mantissa < 0) || (n.mantissa > 255) || !detail::ParseGasName(View(line, t.items[2]), f)) {
1716 return Error::BadReply;
1717 }
1718 f.gas = GasId{static_cast<uint8_t>(n.mantissa)};
1719 f.gas_known = true;
1720 f.unit_id = id;
1721 f.present = static_cast<uint8_t>(DataItem::Gas);
1722 out = f;
1723 return Error::Ok;
1724}
1725
1733[[nodiscard]] inline Error DecodeFullScale(std::span<const char> line, char id,
1734 FullScale& out) noexcept {
1735 Tokens t{};
1736 if (Tokenize(line, t) != Error::Ok) {
1737 return Error::BadReply;
1738 }
1739 if (!StartsWithId(line, t, id)) {
1741 }
1742 FullScale fs{};
1743 if ((t.count != 3U) || !ParseDecimal(View(line, t.items[1]), fs.value)) {
1744 return Error::BadReply;
1745 }
1746 detail::CopyToken(View(line, t.items[2]), fs.unit.chars.data(), fs.unit.chars.size());
1747 fs.unit.length = t.items[2].length;
1748 out = fs;
1749 return Error::Ok;
1750}
1751
1758[[nodiscard]] inline FlowUnit FlowUnitFromLabel(std::span<const char> label) noexcept {
1759 for (uint16_t i = 0U; i < 20U; ++i) {
1760 if (EqualsNoCase(label, reg::kFlowUnitLabels[i])) {
1761 return static_cast<FlowUnit>(i);
1762 }
1763 }
1764 return FlowUnit::Other;
1765}
1766
1774[[nodiscard]] inline Error DecodeGasList(std::span<const char> line, char id,
1775 GasList& out) noexcept {
1776 Tokens t{};
1777 if (Tokenize(line, t) != Error::Ok) {
1778 return Error::BadReply;
1779 }
1780 if (!StartsWithId(line, t, id)) {
1782 }
1783 GasList g{};
1784 bool parsed = (t.count > 1U) && (((t.count - 1U) % 2U) == 0U) && (((t.count - 1U) / 2U) <= 12U);
1785 for (std::size_t k = 1U; parsed && ((k + 1U) < t.count); k += 2U) {
1786 Decimal n{};
1787 Frame f{};
1788 parsed = ParseDecimal(View(line, t.items[k]), n) && (n.decimals == 0U) && (n.mantissa >= 0) &&
1789 (n.mantissa <= 255) && detail::ParseGasName(View(line, t.items[k + 1U]), f);
1790 if (parsed) {
1791 g.numbers[g.count] = static_cast<uint8_t>(n.mantissa);
1792 ++g.count;
1793 }
1794 }
1795 if (!parsed) {
1796 g = GasList{};
1797 g.raw = true;
1798 const std::size_t n = (line.size() < kTextMax) ? line.size() : kTextMax;
1799 detail::CopyToken(line.first(n), g.text.chars.data(), g.text.chars.size());
1800 g.text.length = static_cast<uint8_t>(n);
1801 }
1802 out = g;
1803 return Error::Ok;
1804}
1805
1815[[nodiscard]] inline Error DecodeWindow(std::span<const char> line, char id, uint8_t count,
1816 uint32_t& time_ms, Values& out) noexcept {
1817 Values all{};
1818 if (const Error e = DecodeValues(line, id, static_cast<uint8_t>(count + 1U), all);
1819 e != Error::Ok) {
1820 return e;
1821 }
1822 const Decimal& tm = all.v[0];
1823 if ((tm.decimals != 0U) || (tm.mantissa < 0) || (tm.mantissa > 0x7FFF'FFFFLL)) {
1824 return Error::BadReply;
1825 }
1826 time_ms = static_cast<uint32_t>(tm.mantissa);
1827 out = Values{};
1828 for (uint8_t i = 0U; i < count; ++i) {
1829 out.v[i] = all.v[i + 1U];
1830 }
1831 out.count = count;
1832 return Error::Ok;
1833}
1834
1841[[nodiscard]] inline bool IsErrorToken(std::span<const char> line, char id) noexcept {
1842 Tokens t{};
1843 if (Tokenize(line, t) != Error::Ok) {
1844 return false;
1845 }
1846 const bool alone = (t.count == 1U) && (t.items[0].length == 1U) &&
1847 (::alicat_basis2::detail::SameChar(line[t.items[0].offset], '?'));
1848 const bool after_id = (t.count == 2U) && StartsWithId(line, t, id) && (t.items[1].length == 1U) &&
1849 (::alicat_basis2::detail::SameChar(line[t.items[1].offset], '?'));
1850 return alone || after_id;
1851}
1852
1855} // namespace alicat_basis2::ascii
1856
1857#endif // ALICAT_BASIS2_ASCII_HPP
ALICAT_BASIS2 Modbus register map, magic values, firmware gates and unit tables (M pp....
Request and Reply: the only things the driver puts on and takes off the wire, and the timing formulas...
Public types of the ALICAT_BASIS2 driver: errors, Result<T>, configuration, enumerations and the valu...
bool EqualsNoCase(std::span< const char > tok, const char *word) noexcept
Case-insensitive equality of a token and a word.
Definition alicat_basis2_ascii.hpp:1256
FlowUnit FlowUnitFromLabel(std::span< const char > label) noexcept
The flow unit of an instrument's label (case-insensitive), Other when it is not one of the twenty.
Definition alicat_basis2_ascii.hpp:1758
Result< Request > Make(Command command, char id, const Args &args, bool allow_guarded) noexcept
Build a request: validate every argument, write the wire bytes.
Definition alicat_basis2_ascii.hpp:849
Error DecodeGasList(std::span< const char > line, char id, GasList &out) noexcept
Decode a gas list ID n name n name ... (C28, A5); sets raw when it does not parse.
Definition alicat_basis2_ascii.hpp:1774
bool IsLegalRequest(std::span< const uint8_t > bytes) noexcept
Whether bytes is exactly one request of the grammar of M pp.10 to 17: unit ID A to Z,...
Definition alicat_basis2_ascii.hpp:1102
constexpr const CommandSpec & Spec(Command c) noexcept
The row of a command.
Definition alicat_basis2_ascii.hpp:633
Error DecodeFullScale(std::span< const char > line, char id, FullScale &out) noexcept
Decode a full-scale reply ID value units (C35).
Definition alicat_basis2_ascii.hpp:1733
std::span< const char > View(std::span< const char > line, const Token &t) noexcept
The characters of a token.
Definition alicat_basis2_ascii.hpp:1187
ArgKind
What a command's argument looks like.
Definition alicat_basis2_ascii.hpp:37
Error DecodeText(std::span< const char > line, char id, Text &out) noexcept
Decode ID text...: the rest of the line after the ID, truncated to kTextMax characters.
Definition alicat_basis2_ascii.hpp:1673
constexpr char Upper(char c) noexcept
Upper-case a letter.
Definition alicat_basis2_ascii.hpp:1245
constexpr std::size_t kCommandRows
Number of rows of the command table.
Definition alicat_basis2_ascii.hpp:64
Error DecodeGas(std::span< const char > line, char id, Frame &out) noexcept
Decode a gas reply ID number name (C27, C29).
Definition alicat_basis2_ascii.hpp:1704
Error DecodeValues(std::span< const char > line, char id, uint8_t count, Values &out) noexcept
Decode ID followed by exactly count numbers.
Definition alicat_basis2_ascii.hpp:1619
constexpr std::array< CommandSpec, kCommandRows > kCommands
The command table, indexed by Command (data; one row per command of the coverage map).
Definition alicat_basis2_ascii.hpp:74
Error DecodeData(std::span< const char > line, uint8_t mask, const FrameRules &rules, Frame &out) noexcept
Decode a DV n reply: ID, then the selected fields in table order (M p.11).
Definition alicat_basis2_ascii.hpp:1561
Error DecodeLetter(std::span< const char > line, char id, const char *allowed, char &out) noexcept
Decode ID x where x is one character out of allowed (case-insensitive).
Definition alicat_basis2_ascii.hpp:1648
Error Tokenize(std::span< const char > line, Tokens &out) noexcept
Split a line on runs of spaces.
Definition alicat_basis2_ascii.hpp:1152
constexpr char kCr
Carriage return, the terminator of every request and reply (M p.10).
Definition alicat_basis2_ascii.hpp:34
bool IsErrorToken(std::span< const char > line, char id) noexcept
Whether a reply line is the error token: ? alone, or ? after the unit ID.
Definition alicat_basis2_ascii.hpp:1841
constexpr std::size_t kMaxTokens
Tokens in a line, at most.
Definition alicat_basis2_ascii.hpp:1129
constexpr std::size_t kMaxToken
Longest token, in characters.
Definition alicat_basis2_ascii.hpp:1131
constexpr int64_t kMeasureMaxMs
Longest measurement duration in ms the driver sends (derived: 65535 samples of 2.5 ms,...
Definition alicat_basis2_ascii.hpp:70
bool StartsWithId(std::span< const char > line, const Tokens &toks, char id) noexcept
Whether the first token is exactly one letter equal (any case) to the unit ID.
Definition alicat_basis2_ascii.hpp:1272
Error DecodeFrame(std::span< const char > line, const FrameRules &rules, Frame &out, FrameLayout &layout_seen) noexcept
Decode a data frame (C01): ID, three or five numbers, the gas, zero or more flags (M p....
Definition alicat_basis2_ascii.hpp:1467
constexpr int64_t kMilliCap
Definition alicat_basis2_ascii.hpp:68
Error DecodeWindow(std::span< const char > line, char id, uint8_t count, uint32_t &time_ms, Values &out) noexcept
Decode ID time ... replies of DVAA (two values after the time) and DVAR (four).
Definition alicat_basis2_ascii.hpp:1815
bool ParseDecimal(std::span< const char > tok, Decimal &out) noexcept
Parse ‘[+-]? digit{1,12} ( ’.' digit{1,6} )?: no exponent, no hex, nonan`, no leading or trailing poi...
Definition alicat_basis2_ascii.hpp:1214
@ Milli
One decimal number, given in thousandths, in lo to hi.
@ Int
One integer in lo to hi.
@ Letter
One character out of letters.
@ IntPair
Two integers, each in lo to hi.
@ Ramp
A decimal rate then a time unit 3 to 5.
constexpr std::array< const char *, 20 > kFlowUnitLabels
Flow unit labels in the order of register 49 (M p.26, p.31).
Definition alicat_basis2_registers.hpp:391
constexpr uint16_t kFw305
3.0.5: gas table and GS *.
Definition alicat_basis2_registers.hpp:88
constexpr std::size_t kMaxRequest
Longest request the driver builds, in bytes.
Definition alicat_basis2_request.hpp:83
Command
The 46 ASCII commands of M pp.10 to 17 (rows C01 to C46 of the coverage map), plus the Modbus kind.
Definition alicat_basis2_request.hpp:32
@ ReadAverages
C22 aDVAA.
@ SwitchToProtocol1
C44 aP 1 (guarded).
@ SetRamp
C07 aSR r t.
@ ReadFullScale
C35 aFPF v.
@ SetSetpointSource
C05 aLSS x.
@ ReadReferenceTemperature
C15 aRT.
@ DisableBatch
C32 aTB 0.
@ ReadSetpointSource
C04 aLSS.
@ StartMeasurement
C21 aDVAS t.
@ SetTotalizerLimit
C34 aTC m.
@ ChangeBaud
C42 aNCB b (guarded).
@ FactoryRestore
C46 aFACTORY RESTORE (guarded).
@ ReadTotalizerLimit
C33 aTC.
@ SetModbusAddress
C40 aMA n (guarded).
@ HoldValve
C11 aHPUR p.
@ SetReferenceTemperature
C16 aRT t.
@ SetAveraging
C18 aDCA t.
@ SetAutotare
C26 aZCA 1 or aZCA 0.
@ ChangeUnitId
C36 a@=b (guarded).
@ SetGains
C14 aLCG p i.
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition alicat_basis2_types.hpp:37
constexpr const char * GasName(uint8_t number) noexcept
The name of a gas of the nine of M p.15.
Definition alicat_basis2_types.hpp:438
constexpr std::size_t kTextMax
Maximum characters kept of a text reply.
Definition alicat_basis2_types.hpp:615
UnknownFlagPolicy
What happens with a flag token the manual does not list.
Definition alicat_basis2_types.hpp:242
FrameLayout
Which data frame layout is accepted (assumption A2: a meter's frame is not shown in the manual).
Definition alicat_basis2_types.hpp:235
DataItem
Items of DV (a bit mask, M p.11).
Definition alicat_basis2_types.hpp:495
FlowUnit
Flow units (Modbus register 49, M p.26; M p.31).
Definition alicat_basis2_types.hpp:540
constexpr StatusFlags StatusFromBits(uint32_t bits) noexcept
Decode status bits (Modbus register 2101 or an integer DV status): +1 MOV, +2 TOV,...
Definition alicat_basis2_types.hpp:587
@ InvalidArgument
An argument or a Config field is out of range; nothing was sent.
@ OutOfRange
A decoded value is outside what the instrument can physically report.
@ DeviceIdMismatch
The reply carried another unit ID or Modbus address than the one addressed.
@ BadReply
The line does not match the command's reply grammar.
@ Ok
The call succeeded.
@ Report
Count it in StatusFlags::unknown_count and return the frame.
@ Auto
Learn from the first valid frame, reject a later frame of the other layout.
@ Meter
Three numbers, then the gas, then the flags.
@ Controller
Five numbers, then the gas, then the flags.
@ Other
A label not in the table of M p.31; the raw text is kept.
The ASCII grammar: table, encoder, validator, decoders.
Definition alicat_basis2_ascii.hpp:25
An exact decimal number as the instrument printed it: +0021513.0 is {215130, 1}.
Definition alicat_basis2_types.hpp:375
uint8_t decimals
Digits after the point.
Definition alicat_basis2_types.hpp:377
int64_t mantissa
The number without its decimal point.
Definition alicat_basis2_types.hpp:376
One data frame (A) or a DV selection; present says which fields were read.
Definition alicat_basis2_types.hpp:599
GasId gas
Valid when gas_known.
Definition alicat_basis2_types.hpp:608
char unit_id
The unit ID of the reply, upper case.
Definition alicat_basis2_types.hpp:601
One reading of FPF: a value and its unit text.
Definition alicat_basis2_types.hpp:666
A gas number. Not a closed enumeration: the V3.0.5 gas table allows numbers up to 255 (A5).
Definition alicat_basis2_types.hpp:414
Result of ReadGasList(): the parsed pairs, or the raw text when the grammar did not match (A5).
Definition alicat_basis2_types.hpp:685
bool raw
The text did not parse; text holds it.
Definition alicat_basis2_types.hpp:688
Result of ReadRamp(): rate and time unit as the instrument reported them.
Definition alicat_basis2_types.hpp:624
The value of a call, or why there is none.
Definition alicat_basis2_types.hpp:151
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition alicat_basis2_types.hpp:177
static constexpr Result Success(T v) noexcept
A successful result.
Definition alicat_basis2_types.hpp:169
A short text value (serial number, firmware, unit label), NUL terminated.
Definition alicat_basis2_types.hpp:618
The arguments of a request before encoding.
Definition alicat_basis2_ascii.hpp:639
bool trim
Drop trailing zeros of the fraction.
Definition alicat_basis2_ascii.hpp:644
int64_t b
Second number (Ramp time unit, IntPair second value).
Definition alicat_basis2_ascii.hpp:641
int64_t a
First number: an integer, or thousandths for a decimal argument.
Definition alicat_basis2_ascii.hpp:640
uint8_t dec
Digits printed after the point of a decimal argument (0 to 6).
Definition alicat_basis2_ascii.hpp:643
char c
Character argument.
Definition alicat_basis2_ascii.hpp:642
One row of the command table (rows C01 to C46).
Definition alicat_basis2_ascii.hpp:48
int64_t hi
Highest argument value.
Definition alicat_basis2_ascii.hpp:59
const char * letters
Allowed characters of a Letter argument.
Definition alicat_basis2_ascii.hpp:60
int64_t lo
Lowest argument value.
Definition alicat_basis2_ascii.hpp:58
const char * token
The text after the unit ID.
Definition alicat_basis2_ascii.hpp:50
uint16_t min_firmware
Firmware gate for the ASCII command, 0 for none.
Definition alicat_basis2_ascii.hpp:54
bool slow
May write non-volatile memory (longer reply wait).
Definition alicat_basis2_ascii.hpp:56
bool guarded
Needs a guard token.
Definition alicat_basis2_ascii.hpp:57
ArgKind arg
The argument form.
Definition alicat_basis2_ascii.hpp:51
bool controller_only
The manual says controllers only.
Definition alicat_basis2_ascii.hpp:53
uint16_t reply_max
Most characters of the reply line.
Definition alicat_basis2_ascii.hpp:55
Command id
The command.
Definition alicat_basis2_ascii.hpp:49
bool space
A space between the token and the argument.
Definition alicat_basis2_ascii.hpp:52
The rules a decoded frame is checked against.
Definition alicat_basis2_ascii.hpp:1279
UnknownFlagPolicy flags
Unknown flag policy.
Definition alicat_basis2_ascii.hpp:1282
char unit_id
Addressed ID.
Definition alicat_basis2_ascii.hpp:1280
int64_t full_scale_milli
Full scale flow in thousandths.
Definition alicat_basis2_ascii.hpp:1284
uint16_t flow_margin_permille
Flow plausibility.
Definition alicat_basis2_ascii.hpp:1285
int16_t temperature_min_c
Temperature plausibility.
Definition alicat_basis2_ascii.hpp:1286
FrameLayout layout
Layout accepted (learned or configured).
Definition alicat_basis2_ascii.hpp:1281
int16_t temperature_max_c
Temperature plausibility.
Definition alicat_basis2_ascii.hpp:1287
bool full_scale_known
full_scale_milli is valid.
Definition alicat_basis2_ascii.hpp:1283
One token: where it starts and how long it is.
Definition alicat_basis2_ascii.hpp:1134
uint8_t offset
Index of the first character.
Definition alicat_basis2_ascii.hpp:1135
uint8_t length
Number of characters.
Definition alicat_basis2_ascii.hpp:1136
The tokens of a line.
Definition alicat_basis2_ascii.hpp:1140
uint8_t count
Their number.
Definition alicat_basis2_ascii.hpp:1142
std::array< Token, kMaxTokens > items
The tokens.
Definition alicat_basis2_ascii.hpp:1141
The numbers of a short reply: ID v1 [v2 ...].
Definition alicat_basis2_ascii.hpp:1606
std::array< Decimal, 5 > v
The numbers.
Definition alicat_basis2_ascii.hpp:1607
uint8_t count
How many.
Definition alicat_basis2_ascii.hpp:1608