SFM_FLOW_METER Driver 0.1.0
API reference
Loading...
Searching...
No Matches
sfm_flow_meter.hpp
Go to the documentation of this file.
1
19#ifndef SFM_FLOW_METER_HPP
20#define SFM_FLOW_METER_HPP
21
22#include <array>
23#include <cstddef>
24#include <cstdint>
25#include <span>
26
33#include "sfm_flow_meter_version.h"
34
35namespace sfm {
36
37namespace detail {
38
39// Optional hooks: a `Declares*` concept only tests the name, the `Has*` concept
40// the exact signature, `noexcept` and the result type; the driver rejects a
41// hook that is declared but does not match (KB-CPP20-007).
42
44template <typename Port>
45concept DeclaresDelayUs = requires(Port& port) { port.DelayUs(uint32_t{0}); };
47template <typename Port>
48concept HasDelayUs = requires { ExactHook<Port, void(uint32_t) noexcept>::Take(&Port::DelayUs); };
49
51template <typename Port>
52concept DeclaresNowUs = requires(Port& port) { port.NowUs(); };
54template <typename Port>
55concept HasNowUs = requires { ExactHook<Port, uint32_t() noexcept>::Take(&Port::NowUs); };
56
58template <typename Port>
59concept DeclaresLog = requires(Port& port) { port.Log(LogLevel::Info, ""); };
61template <typename Port>
62concept HasLog =
63 requires { ExactHook<Port, void(LogLevel, const char*) noexcept>::Take(&Port::Log); };
64
66template <typename Port>
67concept DeclaresReadStretch =
68 requires(Port& port, uint8_t* data) { port.ReadStretch(uint8_t{0}, data, std::size_t{0}); };
71template <typename Port>
72concept HasReadStretch = requires {
73 ExactHook<Port, bool(uint8_t, uint8_t*, std::size_t) noexcept>::Take(&Port::ReadStretch);
74} && requires { requires Port::kClockStretch; };
75
77template <typename Port>
78concept DeclaresGeneralCall = requires(Port& port) { port.WriteGeneralCall(uint8_t{0}); };
80template <typename Port>
81concept HasGeneralCall =
82 requires { ExactHook<Port, bool(uint8_t) noexcept>::Take(&Port::WriteGeneralCall); };
83
85template <typename Port>
86concept DeclaresPowerCycle = requires(Port& port) { port.PowerCycle(); };
88template <typename Port>
89concept HasPowerCycle = requires { ExactHook<Port, bool() noexcept>::Take(&Port::PowerCycle); };
90
92template <typename Port>
93concept DeclaresResetPin = requires(Port& port) { port.SetResetPin(true); };
95template <typename Port>
96concept HasResetPin = requires { ExactHook<Port, bool(bool) noexcept>::Take(&Port::SetResetPin); };
97
101template <typename Port>
102void DelayUs(Port& port, uint32_t us) noexcept {
103 if constexpr (HasDelayUs<Port>) {
104 port.DelayUs(us);
105 } else {
106 static_assert(kAlwaysFalse<Port>, "sfm_flow_meter: the port must implement "
107 "`void DelayUs(uint32_t us) noexcept`");
108 }
109}
110
112template <typename Port>
113uint32_t NowUs(Port& port) noexcept {
114 if constexpr (HasNowUs<Port>) {
115 return port.NowUs();
116 } else {
117 (void)port;
118 return 0U;
119 }
120}
121
124template <typename Port>
125void Log(Port& port, [[maybe_unused]] LogLevel level,
126 [[maybe_unused]] const char* message) noexcept {
127 if constexpr (HasLog<Port>) {
128 port.Log(level, message);
129 } else {
130 (void)port;
131 }
132}
133
136constexpr uint8_t LastPhase(Op op) noexcept {
137 switch (op) {
138 case Op::Init:
139 case Op::ReadScaling:
140 case Op::Wake:
141 return 1U;
142 case Op::Start:
143 return 2U;
144 case Op::None:
145 case Op::Stop:
146 case Op::SetAveraging:
147 case Op::Sleep:
148 case Op::SoftReset:
149 case Op::HardReset:
150 case Op::ReadSample:
151 case Op::ReadTemperature:
152 case Op::Concentration:
153 default:
154 break;
155 }
156 return 0U;
157}
158
161inline constexpr uint32_t kMaxAwaitRounds = 10000U;
162
163} // namespace detail
164
173template <I2cPort Port, uint32_t FamilyMask = kAllFamilies>
175 static_assert((FamilyMask != 0U) && ((FamilyMask & ~kAllFamilies) == 0U),
176 "sfm_flow_meter: bad family mask");
177 static_assert(!detail::DeclaresDelayUs<Port> || detail::HasDelayUs<Port>,
178 "sfm_flow_meter: `DelayUs` must be `void DelayUs(uint32_t) noexcept`");
179 static_assert(!detail::DeclaresNowUs<Port> || detail::HasNowUs<Port>,
180 "sfm_flow_meter: `NowUs` must be `uint32_t NowUs() noexcept`");
181 static_assert(!detail::DeclaresLog<Port> || detail::HasLog<Port>,
182 "sfm_flow_meter: `Log` must be `void Log(LogLevel, const "
183 "char*) noexcept`");
184 static_assert(!detail::DeclaresReadStretch<Port> || detail::HasReadStretch<Port>,
185 "sfm_flow_meter: `ReadStretch` must be `bool "
186 "ReadStretch(uint8_t, uint8_t*, "
187 "size_t) noexcept` "
188 "with `static constexpr bool kClockStretch = true`");
189 static_assert(!detail::DeclaresGeneralCall<Port> || detail::HasGeneralCall<Port>,
190 "sfm_flow_meter: `WriteGeneralCall` must be `bool "
191 "WriteGeneralCall(uint8_t) noexcept`");
192 static_assert(!detail::DeclaresPowerCycle<Port> || detail::HasPowerCycle<Port>,
193 "sfm_flow_meter: `PowerCycle` must be `bool PowerCycle() noexcept`");
194 static_assert(!detail::DeclaresResetPin<Port> || detail::HasResetPin<Port>,
195 "sfm_flow_meter: `SetResetPin` must be `bool SetResetPin(bool) "
196 "noexcept`");
197 static_assert(FamilyMask != kFamilySf04 || detail::HasReadStretch<Port>,
198 "sfm_flow_meter: the SFM4100 family needs the port's "
199 "`ReadStretch()` hook");
200
201public:
208 explicit SfmFlowMeter(Port& port, const Config& config = Config{}) noexcept
209 : port_(port), config_(config),
210 part_((FindPart(config.variant) != nullptr) ? FindPart(config.variant)
211 : FamilyRow(config.family)),
212 address_(((config.address != 0U) || (part_ == nullptr)) ? config.address
213 : part_->addresses.list[0]),
214 auto_(config.variant == Variant::Auto) {}
216 SfmFlowMeter(const SfmFlowMeter&) = delete;
219 ~SfmFlowMeter() = default;
220
223
233
240 Result<void> EnsureInitialized() noexcept;
241
247 Result<void> Deinitialize() noexcept;
248
252
262 Result<Wait> StartMeasurement(Gas gas, uint16_t o2_permille = 0) noexcept;
263
270 Result<Wait> Stop() noexcept;
271
279 Result<Wait> SetAveraging(uint16_t n) noexcept;
280
288 Result<Wait> ReadScaling(Gas gas) noexcept;
289
294 Result<Wait> Sleep() noexcept;
295
301 Result<Wait> WakeUp() noexcept;
302
309 Result<Wait> SoftReset() noexcept;
310
316 Result<Wait> HardReset() noexcept;
317
325 Result<Wait> UpdateConcentration(uint16_t o2_permille) noexcept;
326
333 Result<Wait> Poll(uint32_t elapsed_us) noexcept;
334
340 Result<Wait> Poll() noexcept;
341
348 Result<void> AwaitPending() noexcept;
349
353
361
373
384
388
390 [[nodiscard]] State GetState() const noexcept {
391 return state_;
392 }
394 [[nodiscard]] bool HasPending() const noexcept {
395 return op_ != detail::Op::None;
396 }
398 [[nodiscard]] const ProductInfo& GetProductInfo() const noexcept {
399 return info_;
400 }
403 [[nodiscard]] int32_t GetTemperature() const noexcept {
404 return temperature_mdegc_;
405 }
408 [[nodiscard]] const RawReply& GetLastReply() const noexcept {
409 return last_reply_;
410 }
412 [[nodiscard]] const ScalingInfo& GetScaling() const noexcept {
413 return scaling_;
414 }
416 [[nodiscard]] const Stats& GetStats() const noexcept {
417 return stats_;
418 }
420 [[nodiscard]] const Config& GetConfig() const noexcept {
421 return config_;
422 }
425 [[nodiscard]] const PartInfo* GetPart() const noexcept {
426 return part_;
427 }
429 [[nodiscard]] Capabilities GetCapabilities() const noexcept {
430 return (part_ != nullptr) ? CapabilitiesOf(*part_) : Capabilities{};
431 }
433 [[nodiscard]] uint8_t GetAddress() const noexcept {
434 return address_;
435 }
436
438
439private:
440 Result<Wait> begin(const detail::Request& rq) noexcept;
441 Result<Wait> run() noexcept;
442 Result<Wait> advance() noexcept;
443 Result<Wait> failOp(Error error) noexcept;
444 Error execStep(const detail::Step& step, uint32_t& wait_us) noexcept;
445 Error writeStep(const detail::Step& step) noexcept;
446 Error doWrite(const detail::Step& step) noexcept;
447 Error doPoll(const detail::Step& step, uint32_t& wait_us) noexcept;
448 Error doRead(const detail::Step& step) noexcept;
449 Error finishPhase() noexcept;
450 Error finishInit() noexcept;
451 Error finishScale() noexcept;
452 Error finishTemperature() noexcept;
453 Error adoptIdentity(const ProductInfo& info) noexcept;
454 void loadPhase() noexcept;
455 bool nextPhase() noexcept;
456 void complete() noexcept;
457 [[nodiscard]] detail::Request makeRequest(detail::Op op) const noexcept;
458 Error gate(bool allowed) const noexcept;
459 Error decodeSample(Sample& sample) noexcept;
460 Error captureReply() noexcept;
461 Error fillSample(const detail::Frame& frame, Sample& sample) noexcept;
462 Error checkRange(Sample& sample) const noexcept;
463 Error checkFresh(Sample& sample) noexcept;
464 Result<Sample> sampleFailure(Error error) noexcept;
465 void noteFrame() noexcept;
466 [[nodiscard]] bool silenceExceeded() const noexcept;
467 Error escalateSilence() noexcept;
468 Error resetSupport() const noexcept;
469 [[nodiscard]] uint16_t resolvedAveraging() const noexcept;
470 Error driverConfigOk() const noexcept;
471 [[nodiscard]] std::span<const uint8_t> rx() const noexcept {
472 return {rx_.data(), rx_used_};
473 }
474
475 Port& port_;
476 Config config_;
477 const PartInfo* part_{nullptr};
478 const GasRow* running_{nullptr};
479 detail::Op op_{detail::Op::None};
480 detail::Request req_{};
481 detail::Plan plan_{};
482 std::array<uint8_t, kMaxRead> rx_{};
483 ProductInfo info_{};
484 int32_t temperature_mdegc_{0};
485 ScalingInfo scaling_{};
486 RawReply last_reply_{};
487 Stats stats_{};
489 uint32_t wait_us_{0};
490 uint32_t wait_start_us_{0};
491 uint32_t started_us_{0};
492 uint32_t last_good_us_{0};
493 uint32_t last_frame_us_{0};
494 uint32_t quiet_start_us_{0};
495 uint32_t quiet_us_{0};
496 uint16_t o2_permille_{0};
497 uint16_t averaging_{0};
498 std::size_t rx_used_{0};
499 uint8_t address_{0};
500 uint8_t step_{0};
501 uint8_t polls_{0};
502 uint8_t phase_{0};
503 bool waiting_{false};
504 bool skip_optional_read_{false};
505 bool auto_{false};
506};
507
508} // namespace sfm
509
510// codeql::misra_deviation_next_line(MD-CPP-009)
511#include "../src/sfm_flow_meter.ipp" // IWYU pragma: export
512
513#endif // SFM_FLOW_METER_HPP
The driver.
Definition sfm_flow_meter.hpp:174
const ScalingInfo & GetScaling() const noexcept
Definition sfm_flow_meter.hpp:412
State GetState() const noexcept
Definition sfm_flow_meter.hpp:390
Capabilities GetCapabilities() const noexcept
Definition sfm_flow_meter.hpp:429
Result< Wait > BeginInitialize() noexcept
Start identification: wake the sensor, check the product identifier (or serial number),...
Result< void > EnsureInitialized() noexcept
BeginInitialize() and AwaitPending(): blocking, needs the port's DelayUs().
SfmFlowMeter(const SfmFlowMeter &)=delete
The driver is not copied: it holds a reference to the port.
Result< Wait > StartMeasurement(Gas gas, uint16_t o2_permille=0) noexcept
Start a measurement of a gas or gas mixture; reads and checks the part's scaling first.
Result< Wait > Sleep() noexcept
Enter sleep mode (idle only). Failure leaves StateUnknown.
SfmFlowMeter & operator=(const SfmFlowMeter &)=delete
The driver is not copied.
Result< Wait > SoftReset() noexcept
Reset by the part's soft-reset command (the general call needs allow_general_call_reset)....
bool HasPending() const noexcept
Definition sfm_flow_meter.hpp:394
Result< RawReply > ReadRawReply() noexcept
One raw read of the running measurement: the CRC-checked words, with no decoding, no status check and...
Result< void > Deinitialize() noexcept
Forget the initialisation. No bus traffic: call Stop() first if the sensor measures.
uint8_t GetAddress() const noexcept
Definition sfm_flow_meter.hpp:433
const Config & GetConfig() const noexcept
Definition sfm_flow_meter.hpp:420
Result< void > AwaitPending() noexcept
Wait with DelayUs() until no operation is pending. Needs the port's DelayUs().
const Stats & GetStats() const noexcept
Definition sfm_flow_meter.hpp:416
Result< Wait > ReadScaling(Gas gas) noexcept
Read and check the sensor's scaling of a gas while idle; see GetScaling().
Result< Wait > WakeUp() noexcept
Wake from sleep and write the averaging again.
const RawReply & GetLastReply() const noexcept
Definition sfm_flow_meter.hpp:408
Result< Wait > Stop() noexcept
Stop the measurement. A no-op when idle. Failure leaves StateUnknown.
Result< Sample > ReadSample() noexcept
Read one sample of the running measurement.
const ProductInfo & GetProductInfo() const noexcept
Definition sfm_flow_meter.hpp:398
Result< Wait > SetAveraging(uint16_t n) noexcept
Set the averaging while idle.
Result< Wait > HardReset() noexcept
Reset by the /RES pin (SFM4200) or by cycling the supply; needs the port hook.
SfmFlowMeter(Port &port, const Config &config=Config{}) noexcept
Bind a port and a configuration. No bus traffic.
Definition sfm_flow_meter.hpp:208
Result< Wait > ReadTemperature() noexcept
Read the sensor temperature by a pointer sequence while measuring (parts that offer it); the SF05 fam...
Result< Wait > Poll() noexcept
Poll() using the port's NowUs(); without a clock the whole wait counts as elapsed.
Result< Wait > UpdateConcentration(uint16_t o2_permille) noexcept
Change the oxygen fraction of a running mixture (no read in between).
int32_t GetTemperature() const noexcept
Definition sfm_flow_meter.hpp:403
const PartInfo * GetPart() const noexcept
Definition sfm_flow_meter.hpp:425
Gas
A calibrated gas or gas mixture. Which gases a part offers is in its table row.
Definition sfm_flow_meter_types.hpp:285
constexpr uint32_t kAllFamilies
Every family: the default mask.
Definition sfm_flow_meter_types.hpp:238
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition sfm_flow_meter_types.hpp:41
LogLevel
Severity passed to the optional Log() hook.
Definition sfm_flow_meter_types.hpp:196
constexpr uint32_t kFamilySf04
Family::Sf04.
Definition sfm_flow_meter_types.hpp:235
Variant
A part (one row of the table in sfm_flow_meter_parts.hpp). The names follow the vendor's ordering suf...
Definition sfm_flow_meter_types.hpp:245
State
The driver's shadow of the chip's mode.
Definition sfm_flow_meter_types.hpp:325
@ Info
Lifecycle events: initialised, reset.
@ Uninitialized
EnsureInitialized() has not succeeded.
The SFM flow meter driver: everything it declares lives here; internals in detail.
Definition sfm_flow_meter.hpp:35
constexpr Capabilities CapabilitiesOf(const PartInfo &part) noexcept
Definition sfm_flow_meter_parts.hpp:603
constexpr const PartInfo * FindPart(Variant variant) noexcept
The table row of a variant.
Definition sfm_flow_meter_parts.hpp:529
constexpr const PartInfo * FamilyRow(Family family) noexcept
The first row of a family: what Variant::Auto uses for waits before the part is known.
Definition sfm_flow_meter_parts.hpp:566
Compile-time helpers of the SFM_FLOW_METER driver: typed integer literals, exact hook matching,...
The I2C port of the SFM flow meter driver: the CRTP base, the I2cPort concept and the bus requirement...
The table of supported parts: one row of data per variant, the lookups, Validate() and the unit conve...
The six protocol policies: pure constexpr functions that turn an operation into a Plan of bus steps a...
Command codes, status-word helpers and the CRC-8 of the SFM flow meters.
Public types of the SFM flow meter driver: errors, Result<T>, the families, variants and gases,...
Which calls a part offers, from its table row.
Definition sfm_flow_meter_types.hpp:361
Everything EnsureInitialized() applies.
Definition sfm_flow_meter_types.hpp:437
One row of the part table.
Definition sfm_flow_meter_parts.hpp:112
The product identifier read at initialisation.
Definition sfm_flow_meter_types.hpp:341
The words of one reply, after their CRCs were checked and before anything was decoded.
Definition sfm_flow_meter_types.hpp:408
The value of a call, or why there is none.
Definition sfm_flow_meter_types.hpp:136
One measurement. Flow is in millilitres per minute at the part's reference conditions.
Definition sfm_flow_meter_types.hpp:380
What the sensor reports about the scaling of a gas, and whether it matches the table.
Definition sfm_flow_meter_types.hpp:352
Counters the driver keeps; none of them is cleared by a successful call.
Definition sfm_flow_meter_types.hpp:415
A wait the caller owes the driver: delay us, then call Poll(). 0 means nothing to wait.
Definition sfm_flow_meter_types.hpp:336