31#include "fdo2_version.h"
42template <
typename Port>
43concept DeclaresGpioSet =
47template <
typename Port>
49 requires { ExactHook<Port, bool(
CtrlPin,
GpioSignal)
noexcept>::Take(&Port::GpioSet); };
52template <
typename Port>
53concept DeclaresDelayUs =
requires(Port& port) { port.DelayUs(1_u32); };
57template <
typename Port>
58concept HasDelayUs =
requires { ExactHook<Port, void(uint32_t)
noexcept>::Take(&Port::DelayUs); };
61template <
typename Port>
62concept DeclaresNowUs =
requires(Port& port) { port.NowUs(); };
65template <
typename Port>
66concept HasNowUs =
requires { ExactHook<Port, uint32_t()
noexcept>::Take(&Port::NowUs); };
69template <
typename Port>
70concept DeclaresSetBaudRate =
requires(Port& port) { port.SetBaudRate(1_u32); };
73template <
typename Port>
74concept HasSetBaudRate =
75 requires { ExactHook<Port, bool(uint32_t)
noexcept>::Take(&Port::SetBaudRate); };
78template <
typename Port>
79concept DeclaresLog =
requires(Port& port) { port.Log(
LogLevel::Info,
""); };
82template <
typename Port>
84 requires { ExactHook<Port, void(
LogLevel,
const char*)
noexcept>::Take(&Port::Log); };
88template <
typename Port>
89void DelayUs(Port& port, uint32_t us)
noexcept {
90 if constexpr (HasDelayUs<Port>) {
93 static_assert(kAlwaysFalse<Port>,
94 "fdo2: the port must implement `void DelayUs(uint32_t us) noexcept`");
99template <
typename Port>
100void Log(Port& port, [[maybe_unused]]
LogLevel level,
101 [[maybe_unused]]
const char* message)
noexcept {
102 if constexpr (HasLog<Port>) {
103 port.Log(level, message);
110enum class Phase : uint8_t {
131 detail::Phase phase{detail::Phase::Main};
132 std::array<int32_t, kMaxValues> args{};
133 std::size_t arg_count{0};
134 uint64_t deadline_us{0};
135 uint64_t elapsed_us{0};
138 uint32_t new_baud{0};
139 int32_t crc_target{0};
140 int32_t expect_mhpa{0};
142 std::size_t main_arg_count{0};
143 uint8_t attempts_left{0};
144 bool tolerant{
false};
150 bool supported{
true};
151 bool allow_streaming{
false};
152 bool tolerant{
false};
153 int32_t crc_target{0};
154 uint32_t new_baud{0};
192template <UartPort Port>
194 static_assert(!detail::DeclaresGpioSet<Port> || detail::HasGpioSet<Port>,
195 "fdo2: the optional GpioSet hook must be `bool GpioSet(CtrlPin, GpioSignal) "
196 "noexcept`, so that a failed pin write is reported");
197 static_assert(!detail::DeclaresDelayUs<Port> || detail::HasDelayUs<Port>,
198 "fdo2: the DelayUs hook must be `void DelayUs(uint32_t us) noexcept`, so that no "
199 "wait is truncated");
200 static_assert(!detail::DeclaresNowUs<Port> || detail::HasNowUs<Port>,
201 "fdo2: the optional NowUs hook must be `uint32_t NowUs() noexcept`");
202 static_assert(!detail::DeclaresSetBaudRate<Port> || detail::HasSetBaudRate<Port>,
203 "fdo2: the optional SetBaudRate hook must be `bool SetBaudRate(uint32_t baud) "
205 static_assert(!detail::DeclaresLog<Port> || detail::HasLog<Port>,
206 "fdo2: the optional Log hook must be `void Log(LogLevel, const char* message) "
215 explicit FDO2(Port& port,
const Config& config = {})
noexcept
216 : port_(port), config_(config), baud_(config.baud) {}
305 requires detail::HasNowUs<Port>;
314 requires(!detail::HasNowUs<Port>);
563 return device_error_code_;
585 return flash_quiet_us_ > 0U;
597 using Op = detail::Op;
598 using StartOptions = detail::StartOptions;
601 [[nodiscard]]
Error gate(
bool allow_streaming) const noexcept;
603 const StartOptions& options) noexcept;
606 uint32_t steady_s) noexcept;
607 Error transmit() noexcept;
608 void armDeadline() noexcept;
609 [[nodiscard]] static
bool isFlash(
Command command) noexcept;
610 [[nodiscard]]
Error flashGate() const noexcept;
611 [[nodiscard]]
Error steadyGate(uint32_t steady_s) const noexcept;
612 void resetSession() noexcept;
615 void advanceTime(uint32_t dt_us) noexcept;
616 uint32_t clockDelta() noexcept;
617 uint32_t stepDelta() noexcept;
620 Result<
bool> pollCore(uint32_t dt_us) noexcept;
621 Result<
bool> pollPowerUp() noexcept;
622 Result<
bool> pollWaiting() noexcept;
623 Result<
bool> pollSettle() noexcept;
624 Result<
bool> pollDraining() noexcept;
625 Result<
bool> pollStreaming() noexcept;
626 [[nodiscard]] static
Result<
bool> toResult(const detail::Step& step) noexcept;
627 Error fillRx() noexcept;
628 void scanInput(
bool count_discard) noexcept;
629 void noteIdleLine(std::span<const
char> line) noexcept;
630 [[nodiscard]]
ParseOptions parseOptions(
bool relaxed_crc) const noexcept;
633 detail::Step onReplyLine(std::span<const
char> line) noexcept;
634 detail::Step onStreamLine(std::span<const
char> line) noexcept;
635 detail::Step onForeignLine(const
ParsedLine& parsed) noexcept;
636 detail::Step onErro(const
ParsedLine& parsed) noexcept;
637 detail::Step complete(const
ParsedLine& parsed) noexcept;
638 detail::Step completeMain(const
ParsedLine& parsed) noexcept;
639 detail::Step completeBaud() noexcept;
640 void storeUserMemory(const
ParsedLine& parsed) noexcept;
641 detail::Step completeVerify(const
ParsedLine& parsed) noexcept;
642 detail::Step completeInit(const
ParsedLine& parsed) noexcept;
643 detail::Step completeInitVersion(const
ParsedLine& parsed) noexcept;
644 detail::Step sendInit(
Command command, std::span<const int32_t> args,
645 detail::Phase phase) noexcept;
646 detail::Step startVerify() noexcept;
647 Error startGuard() noexcept;
648 detail::Step completeGuard(const
ParsedLine& parsed) noexcept;
649 [[nodiscard]]
Error checkCalibrationReading(const
ParsedLine& parsed) const noexcept;
650 [[nodiscard]]
bool versionMatches(const
Version& version) const noexcept;
651 detail::Step failUnknown(
Error error) noexcept;
653 Result<
void> resyncAt(uint32_t rate) noexcept;
654 detail::Step finishOk() noexcept;
655 detail::Step fail(
Error error,
bool refused) noexcept;
656 detail::Step failInit(
Error error) noexcept;
657 detail::Step retryOrFailInit(
Error error) noexcept;
658 detail::Step scheduleRetry(
Error error) noexcept;
659 detail::Step restartAfterDrain() noexcept;
660 void enterDraining(
bool retry) noexcept;
661 void learnUnsupported() noexcept;
666 [[nodiscard]]
Error checkStatus(const
Status& status) const noexcept;
667 [[nodiscard]]
Error checkOxygen(const
Oxygen& oxygen) const noexcept;
668 [[nodiscard]]
Error plausibleRaw(const
Raw& raw) const noexcept;
671 [[nodiscard]]
Error resultGate(
bool have) const noexcept;
675 void say(
LogLevel level, const
char* message) noexcept;
678 Result<
bool> stepOnce() noexcept;
679 Result<
void> waitIdle() noexcept;
680 Result<
void> await() noexcept;
681 Result<
void> runBlocking(const
Result<
void>& started) noexcept;
682 [[nodiscard]] uint64_t budgetUs() const noexcept;
683 Result<
void> applyBroadcastAfterResync() noexcept;
689 bool streaming_{
false};
690 bool power_set_{
false};
691 bool crc_active_{
false};
692 bool broadcast_seen_{
false};
693 bool retry_pending_{
false};
695 uint64_t drain_deadline_us_{0};
696 uint64_t drain_elapsed_us_{0};
697 uint64_t uptime_us_{0};
698 bool uptime_valid_{
false};
699 uint32_t last_now_{0};
700 std::array<uint8_t, 64> rx_{};
701 std::size_t rx_len_{0};
702 std::size_t rx_pos_{0};
703 LineAssembler assembler_;
704 Identity identity_{};
705 Counters counters_{};
706 int32_t device_error_code_{0};
707 uint8_t flash_used_{0};
708 uint32_t baud_candidate_{0};
709 uint64_t flash_quiet_us_{0};
710 uint64_t stream_silent_us_{0};
715 uint64_t unique_id_{0};
716 std::array<int32_t, kUserMemoryWords> user_memory_{};
717 std::size_t user_memory_count_{0};
718 bool have_oxygen_{
false};
719 bool have_raw_{
false};
720 bool have_version_{
false};
721 bool have_id_{
false};
722 bool have_user_memory_{
false};
723 bool have_last_frame_{
false};
724 bool frame_fresh_{
false};
733#include "../src/fdo2.ipp"
Driver for one FDO2-G2 or FDO2 on a platform port.
Definition fdo2.hpp:193
FDO2(const FDO2 &)=delete
One driver object per module.
Result< bool > ProbeBroadcast(uint32_t window_ms) noexcept
Listen without sending for a window and say whether #MRAW lines arrived.
Result< Oxygen > MeasureOxygen() noexcept
#MOXY, with the status and plausibility checks.
Result< void > AbortOperation() noexcept
Drop the operation in flight. A read is dropped into Draining; a flash write or #BAUD becomes StateUn...
Result< void > Identify() noexcept
#LOGO: waits for the echo (about 1 s).
Result< void > StartMeasureOxygen() noexcept
Send #MOXY; Poll() ends it; GetOxygen() returns it.
Result< void > EnsureInitialized() noexcept
BeginInitialize() and Poll() until it ends; needs DelayUs(). Bounded by the sum of the allowances.
Result< void > DisableBroadcast() noexcept
#BCST 0: the vendor's workaround, sent right after a frame, among frames.
Result< std::span< const int32_t > > GetUserMemory() const noexcept
Result< Raw > GetRaw() noexcept
FDO2(Port &port, const Config &config={}) noexcept
Bind the driver to a port and store the configuration. No I/O, cannot fail.
Definition fdo2.hpp:215
void GetConfig() const &&=delete
Not on a temporary driver.
Result< Raw > MeasureRaw() noexcept
#MRAW, with the same checks.
Result< void > StartSetMeasurementMode(uint8_t mode) noexcept
Send #SETM M (a flash write; the FDO2-G2 only).
State GetState() const noexcept
Definition fdo2.hpp:255
Result< Raw > GetLastFrame() const noexcept
The last decoded measurement frame even when the status policy rejected it, for diagnostics....
FDO2 & operator=(const FDO2 &)=delete
One driver object per module.
void GetIdentity() const &&=delete
Not on a temporary driver: the reference would dangle (KB-CPP20-044).
Result< void > BeginInitialize() noexcept
Start the module without waiting: validate the Config, bring the UART up, power the module through Gp...
Result< void > StartSetCrcEnabled(bool enabled) noexcept
Send #CRCE K (a flash write), then #VERS to verify the mode.
Result< Version > ReadVersion() noexcept
#VERS.
Result< int32_t > MeasureVolumePercentMilli() noexcept
Oxygen in 10^-3 volume percent: #MRAW, then VolumePercentMilli() with the module's back-side pressure...
Result< void > StartMeasureRaw() noexcept
Send #MRAW; GetRaw() returns it.
Result< void > SetCrcEnabled(bool enabled) noexcept
#CRCE, then #VERS; see StartSetCrcEnabled().
Result< void > StartIdentify() noexcept
Send #LOGO: the status LED flashes four times.
Result< void > CalibrateAir(uint32_t steady_s, uint32_t fraction_ppm=kDryAirO2Ppm) noexcept
One-point calibration in dry ambient air: #MRAW for the pressure, then #CAHI with AirO2Mhpa(P,...
Result< void > StartSetBaudRate(uint32_t baud) noexcept
Send #BAUD R, switch the port, then #VERS at the new rate. Needs the port's SetBaudRate().
Result< void > StartCalibrateZero(uint32_t steady_s) noexcept
Send #CALO (a flash write; loses the factory calibration).
void GetCounters() const &&=delete
Not on a temporary driver.
const Identity & GetIdentity() const &noexcept
Definition fdo2.hpp:550
Result< void > StartWriteUserMemory(uint8_t first, std::span< const int32_t > words) noexcept
Send #WRUM first count Y... (a flash write, guarded).
uint8_t FlashWritesUsed() const noexcept
Definition fdo2.hpp:576
bool IsInitialized() const noexcept
Definition fdo2.hpp:249
Result< void > StartCalibrateHigh(int32_t po2_mhpa, uint32_t steady_s) noexcept
Send #CAHI P (a flash write; loses the factory calibration).
bool FlashWritePending() const noexcept
Definition fdo2.hpp:584
Result< void > PowerCycle() noexcept
Switch the module off through CtrlPin::Power, wait power_off_ms, switch it on and start again at 1920...
Result< Raw > ReadRawFrame() noexcept
#MRAW once: the same checks as MeasureRaw() but a failed read is reported, never repeated.
Result< void > StartSetBroadcast(uint32_t interval_ms) noexcept
Send #BCST T (a flash write).
int32_t DeviceErrorCode() const noexcept
Definition fdo2.hpp:562
Result< Version > GetVersion() const noexcept
OperationKind Pending() const noexcept
Definition fdo2.hpp:324
const Counters & GetCounters() const &noexcept
Definition fdo2.hpp:556
Result< void > Deinitialize() noexcept
Drop the operation in flight, leave the broadcast alone, set the power pin INACTIVE (when the port ha...
Result< bool > Poll() noexcept
Advance the state machine and read what arrived, with the port's clock. One Read() of at most 64 byte...
Result< uint64_t > ReadUniqueId() noexcept
#IDNR.
const Config & GetConfig() const &noexcept
Definition fdo2.hpp:566
bool CrcActive() const noexcept
Definition fdo2.hpp:572
Result< void > Resync() noexcept
Find the module again after StateUnknown: #VERS at the candidate baud rates (the rate being set,...
uint32_t StreamSilentMs() const noexcept
Result< void > StartReadVersion() noexcept
Send #VERS; GetVersion() returns it.
Result< uint64_t > GetUniqueId() const noexcept
Result< Oxygen > GetOxygen() const noexcept
Result< void > StartReadUniqueId() noexcept
Send #IDNR; GetUniqueId() returns it.
Result< void > StartReadUserMemory(uint8_t first, uint8_t count) noexcept
Send #RDUM first count.
Compile-time helpers of the FDO2 driver: typed integer literals, exact hook matching,...
The FDO2 line protocol as pure functions: CRC-16, command encoders, the line assembler and the strict...
Public types of the FDO2 driver: errors, Result<T>, the status word, measurements,...
The UART port of the FDO2 driver: the CRTP base, its pin enums, the UartPort concept and the line req...
Command
The thirteen commands of the module (datasheet 4.3).
Definition fdo2_protocol.hpp:50
State
The driver's state machine (docs/non-blocking.md).
Definition fdo2_types.hpp:247
constexpr uint32_t kDryAirO2Ppm
Fraction of oxygen in dry air, parts per million (standard dry air, assumption A-10).
Definition fdo2_types.hpp:724
OperationKind
The operation the driver has in flight.
Definition fdo2_types.hpp:228
LogLevel
Severity passed to the optional Log() hook.
Definition fdo2_types.hpp:185
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition fdo2_types.hpp:39
@ Draining
Discarding input after a failed read, so a late reply is never taken.
@ StateUnknown
A flash write or baud change ended without a confirmed echo.
@ Waiting
An operation is waiting for its reply.
@ Streaming
The module sends #MRAW lines by itself.
@ Uninitialized
Nothing started, or Deinitialize() ran.
@ SetMeasurementMode
#SETM.
@ Info
Lifecycle events: initialised, reset.
The FDO2 driver: everything it declares lives here; internals in detail.
Definition fdo2.hpp:33
GpioSignal
Logical level of a control pin; the port maps it to the physical polarity.
Definition fdo2_uart_interface.hpp:55
@ ACTIVE
The pin function is asserted (module powered).
CtrlPin
Control pins the port may drive through the optional GpioSet() hook.
Definition fdo2_uart_interface.hpp:50
@ Power
Supply switch of the module: ACTIVE powers it. It idles INACTIVE (off).
Everything the driver needs from the application, with the datasheet defaults.
Definition fdo2_types.hpp:516
Counters of what happened on the line; they only grow (docs/non-blocking.md).
Definition fdo2_types.hpp:406
Who the module is: #VERS, #IDNR, the family and what follows from the firmware.
Definition fdo2_types.hpp:396
#MOXY result: oxygen partial pressure, temperature and status.
Definition fdo2_types.hpp:358
How ParseLine() treats the CRC and the spacing (from the Config).
Definition fdo2_protocol.hpp:440
A parsed reply line.
Definition fdo2_protocol.hpp:449
#MRAW result: the Oxygen fields plus the raw values.
Definition fdo2_types.hpp:367
The value of a call, or why there is none.
Definition fdo2_types.hpp:125
The status word S of #MOXY and #MRAW, decoded (datasheet 4.3, #MOXY). Pure functions of the word; the...
Definition fdo2_types.hpp:284
#VERS result (datasheet 4.3, #VERS).
Definition fdo2_types.hpp:377