SFM_FLOW_METER Driver 0.1.0
API reference
Loading...
Searching...
No Matches
sfm_flow_meter_protocols.hpp
Go to the documentation of this file.
1
16#ifndef SFM_FLOW_METER_PROTOCOLS_HPP
17#define SFM_FLOW_METER_PROTOCOLS_HPP
18
19#include <array>
20#include <cstddef>
21#include <cstdint>
22#include <span>
23
29
30namespace sfm::detail {
31
33
35enum class StepKind : uint8_t {
36 Write,
37 Poll,
39 Read,
40 ReadStretch,
42 GeneralCall,
43 Wait,
44 ResetPin,
45 PowerCycle,
46};
47
50enum class Op : uint8_t {
51 None = 0,
52 Init,
53 Start,
54 Stop,
55 SetAveraging,
56 ReadScaling,
57 Sleep,
58 Wake,
59 SoftReset,
60 HardReset,
61 ReadSample,
62 ReadTemperature,
63 Concentration,
64};
65
68struct Step {
69 StepKind kind{StepKind::Wait};
70 uint8_t len{0};
71 uint8_t retries{0};
72 Error on_fail{Error::Bus};
73 bool optional{false};
74 bool level{false};
75 uint32_t us{0};
76 std::array<uint8_t, kMaxWrite> bytes{};
77};
78
80inline constexpr std::size_t kMaxSteps = 10;
83inline constexpr uint8_t kMaxPhases = 3;
84
87struct Plan {
88 std::array<Step, kMaxSteps> steps{};
89 uint8_t count{0};
90 uint8_t rx_len{0};
91};
92
94struct Request {
95 Op op{Op::None};
96 const GasRow* gas{nullptr};
97 uint16_t value{0};
98 uint16_t filter{0};
99 uint16_t eeprom_base{0};
100 bool filter_on{false};
101 bool restart{false};
102 bool conservative{true};
103 bool poll_id{false};
105 bool serial_low{true};
106};
107
109inline constexpr uint8_t kWordBytes = 3;
112inline constexpr uint32_t kConservativeUs = 20000;
114inline constexpr uint32_t kPollIntervalUs = 1000;
115
117constexpr Step Write16(uint16_t cmd, Error fail) noexcept {
118 Step s{};
119 s.kind = StepKind::Write;
120 s.len = 2U;
121 s.on_fail = fail;
122 s.bytes[0] = static_cast<uint8_t>((static_cast<uint32_t>(cmd) >> 8U) & 0xFFU);
123 s.bytes[1] = static_cast<uint8_t>(static_cast<uint32_t>(cmd) & 0xFFU);
124 return s;
125}
126
128constexpr Step Write8(uint8_t cmd, Error fail) noexcept {
129 Step s{};
130 s.kind = StepKind::Write;
131 s.len = 1U;
132 s.on_fail = fail;
133 s.bytes[0] = cmd;
134 return s;
135}
136
139constexpr Step WriteArg(uint16_t cmd, uint16_t arg, uint8_t crc_init) noexcept {
140 Step s = Write16(cmd, Error::Bus);
141 s.len = 5U;
142 const auto high = static_cast<uint8_t>((static_cast<uint32_t>(arg) >> 8U) & 0xFFU);
143 const auto low = static_cast<uint8_t>(static_cast<uint32_t>(arg) & 0xFFU);
144 s.bytes[2] = high;
145 s.bytes[3] = low;
146 s.bytes[4] = reg::Crc8(crc_init, high, low);
147 return s;
148}
149
152constexpr Step WriteEeprom(uint16_t address) noexcept {
153 Step s{};
154 s.kind = StepKind::Write;
155 s.len = 3U;
156 s.bytes[0] = reg::kSf04Eeprom;
157 const uint32_t aligned = (static_cast<uint32_t>(address) << 4U) & 0xFFFFU;
158 s.bytes[1] = static_cast<uint8_t>(aligned >> 8U);
159 s.bytes[2] = static_cast<uint8_t>(aligned & 0xFFU);
160 return s;
161}
162
165constexpr Step ReadWords(uint8_t words, Error fail, bool stretch) noexcept {
166 Step s{};
167 s.kind = stretch ? StepKind::ReadStretch : StepKind::Read;
168 s.len = static_cast<uint8_t>(static_cast<uint32_t>(words) * kWordBytes);
169 s.on_fail = fail;
170 return s;
171}
172
174constexpr Step Delay(uint32_t us) noexcept {
175 Step s{};
176 s.kind = StepKind::Wait;
177 s.us = us;
178 return s;
179}
180
188constexpr Step PollCommand(const PartInfo& p, bool id = false) noexcept {
189 if (id && ((p.family == Family::Sf06) || (p.family == Family::Sf06Gen2) ||
190 (p.family == Family::Sf06Dual))) {
191 return Write16((p.family == Family::Sf06Dual) ? reg::kCmdDeviceIdDual : reg::kCmdProductId,
192 Error::Bus);
193 }
194 switch (p.family) {
195 case Family::Sf05:
196 return Write16(reg::kSf05Serial, Error::Bus);
197 case Family::Sf04:
198 return Write8(reg::kSf04ReadOnly2, Error::Bus);
199 case Family::Sf06:
200 case Family::Sf06Gen2:
201 case Family::Sf06Dual:
202 case Family::Sfx6000:
203 default:
204 break;
205 }
206 return Write16(reg::kCmdStop, Error::Bus);
207}
208
212constexpr Step PollStep(const PartInfo& p, uint32_t bound_us, Error fail,
213 bool id = false) noexcept {
214 Step s = PollCommand(p, id);
215 s.kind = StepKind::Poll;
216 s.on_fail = fail;
217 s.us = kPollIntervalUs;
218 const uint32_t tries = (bound_us / kPollIntervalUs) + 1U;
219 s.retries = static_cast<uint8_t>((tries < 255U) ? tries : 255U);
220 return s;
221}
222
225constexpr void Add(Plan& plan, const Step& step) noexcept {
226 if (plan.count < kMaxSteps) {
227 plan.steps[plan.count] = step;
228 plan.count = static_cast<uint8_t>(plan.count + 1U);
229 if ((step.kind == StepKind::Read) || (step.kind == StepKind::ReadStretch)) {
230 plan.rx_len = static_cast<uint8_t>(plan.rx_len + step.len);
231 }
232 }
233}
234
236constexpr void AddDelay(Plan& plan, uint32_t us) noexcept {
237 if (us != 0U) {
238 Add(plan, Delay(us));
239 }
240}
241
244inline constexpr uint32_t kSamplePeriodUs = 500;
245
250constexpr uint32_t SilenceBoundUs(const PartInfo& p, uint32_t averaging) noexcept {
251 const uint32_t n = (Has(p, feature::kAveraging) && (averaging > 1U)) ? averaging : 1U;
252 const uint32_t period = n * kSamplePeriodUs;
253 return p.timing.first_sample_us + period + (period / 10U) + kPollIntervalUs;
254}
255
257constexpr uint32_t ResetBoundUs(const PartInfo& p, bool conservative) noexcept {
258 uint32_t bound = p.timing.power_up_us;
259 bound = (p.timing.soft_reset_us > bound) ? p.timing.soft_reset_us : bound;
260 bound = (p.timing.wake_us > bound) ? p.timing.wake_us : bound;
261 if (conservative && ((p.family == Family::Sf06) || (p.family == Family::Sf06Gen2))) {
262 bound = (bound > kConservativeUs) ? bound : kConservativeUs;
263 }
264 // The datasheet figures are typical values: one quarter more before the poll
265 // gives up.
266 return bound + (bound / 4U);
267}
268
270constexpr uint32_t SoftResetUs(const PartInfo& p, bool conservative) noexcept {
271 if (conservative && (p.family == Family::Sf06)) {
272 return (p.timing.soft_reset_us > kConservativeUs) ? p.timing.soft_reset_us : kConservativeUs;
273 }
274 return p.timing.soft_reset_us;
275}
276
279constexpr uint16_t ResetAveraging(const PartInfo& p) noexcept {
280 return (p.family == Family::Sf06) ? 0U : 2U;
281}
282
284constexpr uint16_t IdentifierCommand(const PartInfo& p) noexcept {
286}
287
288// --- Plans
289// -----------------------------------------------------------------------------------
290
292constexpr Plan InitIdentifierPlan(const PartInfo& p, const Request& rq) noexcept {
293 Plan plan{};
294 // The poll sends the stop command until it is acknowledged: a sensor that is
295 // asleep or still in reset does not answer its address yet, and one that is
296 // idle takes the stop as a no-op.
297 Add(plan, PollStep(p, ResetBoundUs(p, rq.conservative), Error::NoDevice, rq.poll_id));
298 AddDelay(plan, p.timing.stop_us);
299 Add(plan, Write16(IdentifierCommand(p), Error::NoDevice));
300 AddDelay(plan, p.timing.id_read_us);
301 Add(plan, ReadWords(6U, Error::NoDevice, false));
302 return plan;
303}
304
307constexpr Plan InitSf05Plan(const PartInfo& p, const Request& rq) noexcept {
308 Plan plan{};
309 Add(plan, PollStep(p, p.timing.power_up_us, Error::NoDevice));
311 Add(plan, Write16(reg::kSf05Reset, Error::NoDevice));
312 AddDelay(plan, SoftResetUs(p, rq.conservative));
313 Add(plan, PollStep(p, kPollIntervalUs * 4U, Error::NoDevice));
314 }
315 // The serial number is two words behind two pointers (SFM4200 datasheet 5.2,
316 // ambiguity K-SF05-SERIAL).
317 Add(plan, Write16(reg::kSf05Serial, Error::NoDevice));
318 Add(plan, ReadWords(1U, Error::NoDevice, false));
319 if (rq.serial_low) {
320 Step ptr = Write16(reg::kSf05SerialLow, Error::NoDevice);
321 Step word = ReadWords(1U, Error::NoDevice, false);
322 // The SFM3000 application note lists 0x31AE only (K-SF05-SERIAL): there a
323 // NACK of the second pair leaves the serial number with its high word
324 // instead of failing the start-up.
325 const bool legacy = (p.variant == Variant::SFM3000_200_C);
326 ptr.optional = legacy;
327 word.optional = legacy;
328 Add(plan, ptr);
329 Add(plan, word);
330 }
331 return plan;
332}
333
336constexpr Plan InitSf04Plan(const PartInfo& p) noexcept {
337 Plan plan{};
338 Add(plan, PollStep(p, p.timing.power_up_us, Error::NoDevice));
339 Add(plan, Write8(reg::kSf04ReadOnly2, Error::NoDevice));
340 Add(plan, ReadWords(1U, Error::NoDevice, false));
341 return plan;
342}
343
345constexpr Plan AveragingPlan(const PartInfo& p, uint16_t n) noexcept {
346 Plan plan{};
347 const uint16_t cmd = (p.family == Family::Sf06Dual) ? reg::kCmdAveragingDual : reg::kCmdAveraging;
348 Add(plan, WriteArg(cmd, n, p.crc_init));
349 return plan;
350}
351
354constexpr Plan InitSecondPlan(const PartInfo& p, const Request& rq) noexcept {
355 Plan plan{};
356 if (p.family == Family::Sf04) {
357 Add(plan, WriteEeprom(static_cast<uint16_t>(rq.eeprom_base + reg::kSf04EepromSerial)));
358 Add(plan, ReadWords(2U, Error::NoDevice, false));
359 return plan;
360 }
361 if (Has(p, feature::kAveraging)) {
362 return AveragingPlan(p, (rq.value == kAveragingDefault) ? ResetAveraging(p) : rq.value);
363 }
364 return plan;
365}
366
368constexpr Plan ScalePlan(const PartInfo& p, const Request& rq, uint8_t phase) noexcept {
369 Plan plan{};
370 const uint16_t code = (rq.gas != nullptr) ? rq.gas->code : uint16_t{0};
371 switch (p.family) {
372 case Family::Sf06:
373 case Family::Sf06Gen2:
374 if (phase == 0U) {
375 Add(plan, WriteArg(reg::kCmdReadScale, code, p.crc_init));
376 Add(plan, ReadWords(3U, Error::Bus, false));
377 }
378 break;
379 case Family::Sfx6000:
380 if (phase == 0U) {
381 Add(plan, WriteArg(reg::kCmdReadScale, code, p.crc_init));
382 Add(plan, Write16(reg::kCmdSfxScalePointer, Error::Bus));
383 Add(plan, ReadWords(5U, Error::Bus, false));
384 }
385 break;
386 case Family::Sf05:
387 if (phase == 0U) {
388 Add(plan, Write16(reg::kSf05ScaleFlow, Error::Bus));
389 Add(plan, ReadWords(1U, Error::Bus, false));
390 Add(plan, Write16(reg::kSf05OffsetFlow, Error::Bus));
391 Add(plan, ReadWords(1U, Error::Bus, false));
392 }
393 break;
394 case Family::Sf04:
395 if (phase == 0U) {
396 Add(plan, Write8(reg::kSf04UserRegister, Error::Bus));
397 Add(plan, ReadWords(1U, Error::Bus, false));
398 } else if (phase == 1U) {
399 Add(plan, WriteEeprom(static_cast<uint16_t>(rq.eeprom_base + reg::kSf04EepromScale)));
400 Add(plan, ReadWords(2U, Error::Bus, false));
401 } else {
402 // Phase 2 does not exist for SF04.
403 }
404 break;
405 case Family::Sf06Dual:
406 default:
407 break;
408 }
409 return plan;
410}
411
413constexpr Plan LaunchPlan(const PartInfo& p, const Request& rq) noexcept {
414 Plan plan{};
415 if ((rq.gas == nullptr) || (p.family == Family::Sf04)) {
416 return plan; // SF04 has no continuous mode: each read triggers its own
417 // measurement
418 }
419 if (p.family == Family::Sf05) {
420 Add(plan, Write16(reg::kSf05Flow, Error::Bus));
421 } else if (rq.gas->takes_argument) {
422 Add(plan, WriteArg(rq.gas->code, rq.value, p.crc_init));
423 } else if (rq.filter_on && Has(p, feature::kFilterArg)) {
424 Add(plan, WriteArg(rq.gas->code, rq.filter, p.crc_init));
425 } else {
426 Add(plan, Write16(rq.gas->code, Error::Bus));
427 }
428 AddDelay(plan, p.timing.first_sample_us);
429 return plan;
430}
431
433constexpr Plan SamplePlan(const PartInfo& p, const Request& rq) noexcept {
434 Plan plan{};
435 switch (p.family) {
436 case Family::Sf04:
437 Add(plan, Write8(reg::kSf04TriggerFlow, Error::Bus));
438 Add(plan, ReadWords(1U, Error::Timeout, true));
439 break;
440 case Family::Sf05:
441 Add(plan, ReadWords(1U, Error::NoData, false));
442 if (rq.restart) {
443 Add(plan, Write16(reg::kSf05Flow, Error::Bus));
444 }
445 break;
446 case Family::Sf06:
447 case Family::Sf06Gen2:
448 case Family::Sf06Dual:
449 case Family::Sfx6000:
450 default:
451 Add(plan, ReadWords(3U, Error::NoData, false));
452 break;
453 }
454 return plan;
455}
456
459inline constexpr uint32_t kSf05TemperatureUs = 5000;
460
463constexpr Plan TemperaturePlan(const PartInfo& p) noexcept {
464 Plan plan{};
465 const bool sf05 = (p.family == Family::Sf05);
466 Add(plan, Write16(sf05 ? reg::kSf05Temperature : reg::kCmdSfxTemperature, Error::Bus));
467 if (sf05) {
468 AddDelay(plan, kSf05TemperatureUs);
469 }
470 Add(plan, ReadWords(1U, Error::Bus, false));
471 Add(plan, Write16(sf05 ? reg::kSf05Flow : reg::kCmdResultPointer, Error::Bus));
472 return plan;
473}
474
477constexpr Plan StopPlan(const PartInfo& p) noexcept {
478 Plan plan{};
479 if (p.family == Family::Sf05) {
480 Add(plan, Write16(reg::kSf05Serial, Error::Bus));
481 } else if (p.family != Family::Sf04) {
482 Add(plan, Write16(reg::kCmdStop, Error::Bus));
483 AddDelay(plan, p.timing.stop_us);
484 } else {
485 // SF04: no continuous mode, no traffic.
486 }
487 return plan;
488}
489
492constexpr Plan WakePlan(const PartInfo& p, const Request& rq) noexcept {
493 Plan plan{};
494 Add(plan, PollStep(p, ResetBoundUs(p, rq.conservative), Error::Timeout, rq.poll_id));
495 AddDelay(plan, p.timing.stop_us);
496 return plan;
497}
498
500constexpr Plan SoftResetPlan(const PartInfo& p, const Request& rq) noexcept {
501 Plan plan{};
503 Step gc{};
504 gc.kind = StepKind::GeneralCall;
505 gc.bytes[0] = reg::kGeneralCallReset;
506 Add(plan, gc);
507 } else if (p.family == Family::Sf05) {
508 Add(plan, Write16(reg::kSf05Reset, Error::Bus));
509 } else {
510 Add(plan, Write8(reg::kSf04SoftReset, Error::Bus));
511 }
512 AddDelay(plan, SoftResetUs(p, rq.conservative));
513 Add(plan, PollStep(p, kPollIntervalUs * 4U, Error::Timeout, rq.poll_id));
514 AddDelay(plan, p.timing.stop_us);
515 return plan;
516}
517
519constexpr Plan HardResetPlan(const PartInfo& p, const Request& rq) noexcept {
520 Plan plan{};
521 if (Has(p, feature::kResetPin)) {
522 Step low{};
523 low.kind = StepKind::ResetPin;
524 low.level = true; // asserted
525 Add(plan, low);
526 AddDelay(plan, p.timing.hard_reset_us);
527 Step high{};
528 high.kind = StepKind::ResetPin;
529 Add(plan, high);
530 } else {
531 Step cycle{};
532 cycle.kind = StepKind::PowerCycle;
533 Add(plan, cycle);
534 }
535 AddDelay(plan, p.timing.power_up_us);
536 Add(plan, PollStep(p, p.timing.power_up_us, Error::Timeout, rq.poll_id));
537 AddDelay(plan, p.timing.stop_us);
538 return plan;
539}
540
542constexpr Plan ConcentrationPlan(const PartInfo& p, const Request& rq) noexcept {
543 Plan plan{};
544 Add(plan, WriteArg(reg::kCmdUpdateConcentration, rq.value, p.crc_init));
545 Add(plan, Write16(reg::kCmdResultPointer, Error::Bus));
546 return plan;
547}
548
550constexpr Plan InitFirstPlan(const PartInfo& p, const Request& rq) noexcept {
551 switch (p.family) {
552 case Family::Sf05:
553 return InitSf05Plan(p, rq);
554 case Family::Sf04:
555 return InitSf04Plan(p);
556 case Family::Sf06:
557 case Family::Sf06Gen2:
558 case Family::Sf06Dual:
559 case Family::Sfx6000:
560 default:
561 break;
562 }
563 return InitIdentifierPlan(p, rq);
564}
565
568constexpr Plan WakeSecondPlan(const PartInfo& p, const Request& rq) noexcept {
569 return Has(p, feature::kAveraging) ? AveragingPlan(p, rq.value) : Plan{};
570}
571
573constexpr Plan BuildSingle(const PartInfo& p, const Request& rq) noexcept {
574 switch (rq.op) {
575 case Op::Stop:
576 return StopPlan(p);
577 case Op::SetAveraging:
578 return AveragingPlan(p, rq.value);
579 case Op::Sleep:
580 return Plan{[] {
581 Plan plan{};
582 Add(plan, Write16(reg::kCmdSleep, Error::Bus));
583 return plan;
584 }()};
585 case Op::SoftReset:
586 return SoftResetPlan(p, rq);
587 case Op::HardReset:
588 return HardResetPlan(p, rq);
589 case Op::ReadSample:
590 return SamplePlan(p, rq);
591 case Op::ReadTemperature:
592 return TemperaturePlan(p);
593 case Op::Concentration:
594 return ConcentrationPlan(p, rq);
595 case Op::None:
596 case Op::Init:
597 case Op::Start:
598 case Op::ReadScaling:
599 case Op::Wake:
600 default:
601 break;
602 }
603 return Plan{};
604}
605
608constexpr Plan Build(const PartInfo& p, const Request& rq, uint8_t phase) noexcept {
609 switch (rq.op) {
610 case Op::Init:
611 if (phase == 0U) {
612 return InitFirstPlan(p, rq);
613 }
614 return (phase == 1U) ? InitSecondPlan(p, rq) : Plan{};
615 case Op::Start:
616 if (phase < 2U) {
617 return Has(p, feature::kScaleRead) ? ScalePlan(p, rq, phase) : Plan{};
618 }
619 return (phase == 2U) ? LaunchPlan(p, rq) : Plan{};
620 case Op::ReadScaling:
621 return ScalePlan(p, rq, phase);
622 case Op::Wake:
623 if (phase == 0U) {
624 return WakePlan(p, rq);
625 }
626 return (phase == 1U) ? WakeSecondPlan(p, rq) : Plan{};
627 case Op::None:
628 case Op::Stop:
629 case Op::SetAveraging:
630 case Op::Sleep:
631 case Op::SoftReset:
632 case Op::HardReset:
633 case Op::ReadSample:
634 case Op::ReadTemperature:
635 case Op::Concentration:
636 default:
637 break;
638 }
639 return (phase == 0U) ? BuildSingle(p, rq) : Plan{};
640}
641
642// --- Decoding
643// --------------------------------------------------------------------------------
644
646struct Words {
647 std::array<uint16_t, 6> w{};
648 uint8_t n{0};
649};
650
660constexpr Result<Words> ParseWords(uint8_t crc_init, std::span<const uint8_t> rx) noexcept {
661 if (rx.empty() || ((rx.size() % kWordBytes) != 0U) || (rx.size() > kMaxRead)) {
663 }
664 Words out{};
665 const std::size_t count = rx.size() / kWordBytes;
666 for (std::size_t i = 0U; i < count; ++i) {
667 const uint8_t high = rx[i * kWordBytes];
668 const uint8_t low = rx[(i * kWordBytes) + 1U];
669 if (reg::Crc8(crc_init, high, low) != rx[(i * kWordBytes) + 2U]) {
671 }
672 out.w[i] =
673 static_cast<uint16_t>((static_cast<uint32_t>(high) << 8U) | static_cast<uint32_t>(low));
674 }
675 out.n = static_cast<uint8_t>(count);
676 return Result<Words>::Success(out);
677}
678
680constexpr int32_t AsSigned(uint16_t word) noexcept {
681 return (word >= 0x8000U) ? (static_cast<int32_t>(word) - 65536) : static_cast<int32_t>(word);
682}
683
687inline constexpr int32_t kTemperatureMinMdegC = -60000;
688inline constexpr int32_t kTemperatureMaxMdegC = 150000;
689
692constexpr bool IsStuck(const PartInfo& p, std::span<const uint8_t> rx) noexcept {
693 bool zeros = true;
694 bool ones = true;
695 for (const uint8_t byte : rx) {
696 zeros = zeros && (byte == 0U);
697 ones = ones && (byte == 0xFFU);
698 }
699 const bool zero_is_value = (p.gases.rows[0].scaling.offset == 0);
700 return ones || (zeros && !zero_is_value);
701}
702
704struct Frame {
705 int32_t flow{0};
706 int32_t flow2{0};
707 int32_t temperature{0};
708 uint16_t status{0};
709 bool has_temperature{false};
710 bool has_status{false};
711 bool has_flow2{false};
712};
713
715constexpr Frame DualFrame(const Words& w) noexcept {
716 Frame f{};
717 f.flow = static_cast<int32_t>((static_cast<uint32_t>(w.w[0]) << 8U) |
718 (static_cast<uint32_t>(w.w[1]) >> 8U));
719 f.flow2 = static_cast<int32_t>(((static_cast<uint32_t>(w.w[1]) & 0xFFU) << 16U) |
720 static_cast<uint32_t>(w.w[2]));
721 f.has_flow2 = true;
722 return f;
723}
724
727constexpr Frame StatusFrame(const PartInfo& p, const Words& w) noexcept {
728 Frame f{};
729 f.flow = AsSigned(w.w[0]);
730 f.status = w.w[2];
731 f.has_status = true;
732 f.has_temperature = Has(p, feature::kTemperatureFrame);
733 f.temperature = f.has_temperature ? AsSigned(w.w[1]) : 0;
734 return f;
735}
736
745constexpr Result<Frame> DecodeFrame(const PartInfo& p, std::span<const uint8_t> rx) noexcept {
746 const Result<Words> words = ParseWords(p.crc_init, rx);
747 if (!words) {
748 return Result<Frame>::Failure(words.error);
749 }
750 const Words& w = words.value;
751 if (IsStuck(p, rx) || ((w.n == 3U) && (w.w[0] == w.w[1]) && (w.w[1] == w.w[2]))) {
753 }
754 switch (p.family) {
755 case Family::Sf06Dual:
756 return Result<Frame>::Success(DualFrame(w));
757 case Family::Sf05:
758 // SFM3x00 and SFM4200: 14 bits in a 16-bit word, the two least significant
759 // bits are zero.
760 if ((static_cast<uint32_t>(w.w[0]) & 0x3U) != 0U) {
762 }
763 return Result<Frame>::Success(Frame{.flow = static_cast<int32_t>(w.w[0])});
764 case Family::Sf04:
765 return Result<Frame>::Success(Frame{.flow = AsSigned(w.w[0])});
766 case Family::Sf06:
767 case Family::Sf06Gen2:
768 case Family::Sfx6000:
769 default:
770 break;
771 }
772 return Result<Frame>::Success(StatusFrame(p, w));
773}
774
776struct StatusContext {
777 uint16_t gas_index{0};
778 uint16_t permille{0};
779 uint16_t averages{0};
780 bool mixture{false};
781 bool filter_given{false};
782};
783
785constexpr bool NibbleLegal(Family family, uint32_t nibble) noexcept {
786 switch (family) {
787 case Family::Sf06:
788 return (nibble <= 3U) || ((nibble >= 6U) && (nibble <= 8U));
789 case Family::Sfx6000:
790 return (nibble <= 4U) || (nibble == 10U);
791 case Family::Sf06Gen2:
792 return nibble == 0U;
793 case Family::Sf06Dual:
794 case Family::Sf05:
795 case Family::Sf04:
796 default:
797 break;
798 }
799 return false;
800}
801
811constexpr Error CheckStatus(const PartInfo& p, uint16_t status, const StatusContext& ctx) noexcept {
812 const uint32_t nibble = reg::StatusCommand::Extract(status);
813 if (!NibbleLegal(p.family, nibble)) {
814 return Error::InvalidReply;
815 }
816 if (nibble != ctx.gas_index) {
818 }
819 if (p.family == Family::Sf06Gen2) {
820 const bool fixed = ctx.averages >= 1U;
821 const bool ok = ((reg::StatusFixedN::Extract(status) != 0U) == fixed) &&
822 (reg::StatusAverages::Extract(status) == ctx.averages) &&
823 ((reg::StatusFilterArg::Extract(status) != 0U) == ctx.filter_given);
824 return ok ? Error::Ok : Error::StatusMismatch;
825 }
826 if (p.family != Family::Sf06) {
827 // SFx6000 [P]: the concentration and averaging fields are not documented;
828 // only the nibble is checked.
829 return Error::Ok;
830 }
831 const uint32_t conc = reg::StatusConcentration::Extract(status);
832 const uint32_t expected =
833 ctx.mixture ? static_cast<uint32_t>(ctx.permille) : uint32_t{reg::kStatusPureGas};
834 if (conc != expected) {
836 }
837 const bool fixed = ctx.averages >= 1U;
838 return ((reg::StatusFixedN::Extract(status) != 0U) == fixed) ? Error::Ok : Error::StatusMismatch;
839}
840
842constexpr bool IsSmoothed(const PartInfo& p, uint16_t status) noexcept {
843 const bool has_bit = (p.family == Family::Sf06) || (p.family == Family::Sf06Gen2);
844 return has_bit && (reg::StatusSmoothing::Extract(status) != 0U);
845}
846
848struct IdentityQuery {
849 const PartInfo* expected{nullptr};
850 Family family{Family::Sf06};
851 uint8_t address{0};
852 bool accept_prototype{false};
853};
854
856constexpr uint32_t Join(uint16_t high, uint16_t low) noexcept {
857 return (static_cast<uint32_t>(high) << 16U) | static_cast<uint32_t>(low);
858}
859
870constexpr Result<ProductInfo> DecodeIdentifier(const IdentityQuery& q, uint8_t crc_init,
871 std::span<const uint8_t> rx) noexcept {
872 const Result<Words> words = ParseWords(crc_init, rx);
873 if (!words) {
874 return Result<ProductInfo>::Failure(words.error);
875 }
876 const Words& w = words.value;
877 ProductInfo info{};
878 info.product_id = Join(w.w[0], w.w[1]);
879 info.serial = Join(w.w[4], w.w[5]);
880 info.revision = static_cast<uint8_t>(info.product_id & 0xFFU);
881 const bool serial_stuck =
882 ((w.w[2] == 0U) && (w.w[3] == 0U) && (info.serial == 0U)) ||
883 ((w.w[2] == 0xFFFFU) && (w.w[3] == 0xFFFFU) && (info.serial == 0xFFFFFFFFU));
884 if (serial_stuck) {
886 }
887 const PartInfo* row =
888 (q.expected != nullptr) ? q.expected : FindById(q.family, info.product_id, q.address);
889 if ((row == nullptr) || ((info.product_id & row->id_mask) != row->id_value) ||
890 (row->family != q.family)) {
892 }
893 info.prototype =
894 (row->id_mask != 0xFFFFFFFFU) && ((static_cast<uint32_t>(info.revision) >> 4U) == 8U);
895 if (info.prototype && !q.accept_prototype) {
897 }
898 info.variant = row->variant;
899 info.preliminary = row->preliminary;
900 return Result<ProductInfo>::Success(info);
901}
902
905constexpr Result<ProductInfo> DecodeSerial(const PartInfo& p,
906 std::span<const uint8_t> rx) noexcept {
907 const Result<Words> words = ParseWords(p.crc_init, rx);
908 if (!words) {
909 return Result<ProductInfo>::Failure(words.error);
910 }
911 ProductInfo info{};
912 const uint16_t low = (words.value.n > 1U) ? words.value.w[1] : uint16_t{0};
913 info.serial = Join(words.value.w[0], low);
914 if ((info.serial == 0U) || (info.serial == 0xFFFFFFFFU)) {
916 }
917 info.variant = p.variant;
918 info.preliminary = p.preliminary;
919 return Result<ProductInfo>::Success(info);
920}
921
924constexpr int32_t TableScale(const Scaling& s) noexcept {
925 return static_cast<int32_t>(
926 DivideRounded(static_cast<int64_t>(s.num), static_cast<int64_t>(s.den)));
927}
928
930constexpr bool ScalingMatches(const ScalingInfo& got, const Scaling& table,
931 ScalingCheck check) noexcept {
932 if (got.scale == 0) {
933 return false;
934 }
935 if (check == ScalingCheck::Off) {
936 return true;
937 }
938 const int32_t want = TableScale(table);
939 const int64_t diff = (got.scale > want) ? (static_cast<int64_t>(got.scale) - want)
940 : (static_cast<int64_t>(want) - got.scale);
941 const bool scale_ok =
942 (check == ScalingCheck::Strict) ? (diff == 0) : ((diff * 100) <= static_cast<int64_t>(want));
943 return scale_ok && (got.offset == table.offset) && (got.unit == table.unit);
944}
945
948constexpr Result<ScalingInfo> DecodeScaling(const PartInfo& p,
949 std::span<const uint8_t> rx) noexcept {
950 const Result<Words> words = ParseWords(p.crc_init, rx);
951 if (!words) {
952 return Result<ScalingInfo>::Failure(words.error);
953 }
954 const Words& w = words.value;
955 ScalingInfo info{};
956 info.scale = static_cast<int32_t>(w.w[0]);
957 switch (p.family) {
958 case Family::Sf05:
959 info.offset = static_cast<int32_t>(w.w[1]); // unsigned: SFM3200 and its relatives use 32768
960 break;
961 case Family::Sf04:
962 info.unit = w.w[1];
963 break;
964 case Family::Sf06:
965 case Family::Sf06Gen2:
966 case Family::Sfx6000:
967 case Family::Sf06Dual:
968 default:
969 info.offset = AsSigned(w.w[1]);
970 info.unit = w.w[2];
971 break;
972 }
973 return Result<ScalingInfo>::Success(info);
974}
975
978constexpr uint16_t EepromBase(uint32_t field) noexcept {
979 return static_cast<uint16_t>(field * reg::kSf04FieldStride);
980}
981
984constexpr Result<uint16_t> DecodeField(const PartInfo& p, std::span<const uint8_t> rx,
985 bool user_register) noexcept {
986 const Result<Words> words = ParseWords(p.crc_init, rx);
987 if (!words) {
988 return Result<uint16_t>::Failure(words.error);
989 }
990 const uint32_t reg_value = words.value.w[0];
991 const uint32_t field = user_register ? ((reg_value >> 4U) & 0x7U) : (reg_value & 0x7U);
992 return Result<uint16_t>::Success(EepromBase(field));
993}
994
996
997} // namespace sfm::detail
998
999#endif // SFM_FLOW_METER_PROTOCOLS_HPP
constexpr uint16_t kSf05Reset
Soft reset (SFM3x00).
Definition sfm_flow_meter_registers.hpp:69
constexpr uint16_t kSf05ScaleFlow
Flow scale factor.
Definition sfm_flow_meter_registers.hpp:70
constexpr uint16_t kCmdAveragingDual
SFM3505: configure averaging.
Definition sfm_flow_meter_registers.hpp:53
constexpr uint8_t kSf04ReadOnly2
Read read-only register 2.
Definition sfm_flow_meter_registers.hpp:81
constexpr uint8_t kSf04Eeprom
Read the EEPROM.
Definition sfm_flow_meter_registers.hpp:82
constexpr uint16_t kCmdReadScale
Read scale factor, offset and unit (argument).
Definition sfm_flow_meter_registers.hpp:54
constexpr uint16_t kSf05Flow
Start flow measurement / point at the flow.
Definition sfm_flow_meter_registers.hpp:67
constexpr uint16_t kCmdProductId
Read the product identifier (idle).
Definition sfm_flow_meter_registers.hpp:57
constexpr uint8_t kSf04UserRegister
Read the user register.
Definition sfm_flow_meter_registers.hpp:80
constexpr uint16_t kSf04EepromSerial
EEPROM address of the product serial number.
Definition sfm_flow_meter_registers.hpp:83
constexpr uint16_t kSf05Serial
Definition sfm_flow_meter_registers.hpp:72
constexpr uint8_t Crc8(uint8_t init, uint8_t high, uint8_t low) noexcept
CRC-8 of one 16-bit word as the chip computes it: polynomial 0x31 (x^8.
Definition sfm_flow_meter_registers.hpp:123
constexpr uint8_t kGeneralCallReset
Byte sent to address 0x00 to reset.
Definition sfm_flow_meter_registers.hpp:63
constexpr uint16_t kCmdSfxTemperature
SFx6000: point the read at the temperature.
Definition sfm_flow_meter_registers.hpp:61
constexpr uint16_t kCmdSfxScalePointer
SFx6000: point the read at the gas information.
Definition sfm_flow_meter_registers.hpp:59
constexpr uint16_t kSf04EepromScale
EEPROM address of the scale factor.
Definition sfm_flow_meter_registers.hpp:85
constexpr uint16_t kCmdAveraging
SF06 and SFM3304: configure averaging.
Definition sfm_flow_meter_registers.hpp:52
constexpr uint16_t kStatusPureGas
Status bits 9:0 of a pure gas.
Definition sfm_flow_meter_registers.hpp:96
constexpr uint16_t kCmdSleep
Enter sleep mode.
Definition sfm_flow_meter_registers.hpp:56
constexpr uint16_t kSf05SerialLow
Serial number, least significant word.
Definition sfm_flow_meter_registers.hpp:74
constexpr uint16_t kSf04FieldStride
EEPROM size of one calibration field.
Definition sfm_flow_meter_registers.hpp:87
constexpr uint8_t kSf04SoftReset
Soft reset.
Definition sfm_flow_meter_registers.hpp:79
constexpr uint16_t kCmdDeviceIdDual
SFM3505: read the device identifier.
Definition sfm_flow_meter_registers.hpp:58
constexpr uint16_t kSf05Temperature
Point at the temperature.
Definition sfm_flow_meter_registers.hpp:68
constexpr uint16_t kCmdResultPointer
Point the read at the result buffer.
Definition sfm_flow_meter_registers.hpp:50
constexpr uint16_t kCmdStop
Stop continuous measurement.
Definition sfm_flow_meter_registers.hpp:51
constexpr uint16_t kCmdUpdateConcentration
Update concentration, part 1 (argument).
Definition sfm_flow_meter_registers.hpp:48
constexpr uint8_t kSf04TriggerFlow
Trigger a flow measurement.
Definition sfm_flow_meter_registers.hpp:77
constexpr uint16_t kSf05OffsetFlow
Flow offset.
Definition sfm_flow_meter_registers.hpp:71
ScalingCheck
What ReadScaling() does when the sensor's scale or offset differs from the datasheet.
Definition sfm_flow_meter_types.hpp:302
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition sfm_flow_meter_types.hpp:41
Family
The command-set family of a part. One protocol policy per family; every part is a row of data that na...
Definition sfm_flow_meter_types.hpp:207
constexpr uint16_t kAveragingDefault
Marks Config::averaging as "the family's reset value".
Definition sfm_flow_meter_types.hpp:425
@ Strict
Any difference or a wrong unit is DeviceFault.
@ Off
The sensor's values are used; only scale 0 and the unit are checked.
@ Bus
A write hook returned false.
@ Ok
The call succeeded.
@ Timeout
A bounded wait or poll ended: wake, reset, stretched read.
@ Sf06Dual
SFM3505: two 24-bit flows (air and oxygen) in one frame.
@ SFM3000_200_C
SFM3000-200-C, 5 V, address 0x40, legacy.
constexpr uint32_t kScaleRead
ReadScaling().
Definition sfm_flow_meter_parts.hpp:38
constexpr uint32_t kSoftResetCommand
SoftReset() is a command to the device.
Definition sfm_flow_meter_parts.hpp:48
constexpr uint32_t kGeneralCallReset
SoftReset() is the general call.
Definition sfm_flow_meter_parts.hpp:47
constexpr uint32_t kAveraging
SetAveraging().
Definition sfm_flow_meter_parts.hpp:39
constexpr uint32_t kResetPin
HardReset() pulses /RES (SFM4200).
Definition sfm_flow_meter_parts.hpp:50
constexpr uint32_t kFilterArg
The start command takes a filter argument.
Definition sfm_flow_meter_parts.hpp:52
constexpr uint32_t kTemperatureFrame
The frame carries the temperature.
Definition sfm_flow_meter_parts.hpp:44
constexpr const PartInfo * FindById(Family family, uint32_t id, uint8_t address) noexcept
The table row that a product identifier and address select inside one family.
Definition sfm_flow_meter_parts.hpp:546
constexpr std::size_t kMaxRead
Definition sfm_flow_meter_i2c_interface.hpp:68
constexpr int64_t DivideRounded(int64_t value, int64_t divisor) noexcept
Divide value by divisor rounding to nearest, ties away from zero.
Definition sfm_flow_meter_parts.hpp:628
constexpr bool Has(const PartInfo &part, uint32_t bits) noexcept
Definition sfm_flow_meter_parts.hpp:595
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...
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,...
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition sfm_flow_meter_types.hpp:162
static constexpr Result Success(T v) noexcept
A successful result.
Definition sfm_flow_meter_types.hpp:154